plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
lcnbeapp/beapp-master
pop_importegimat.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_importegimat.m
6,094
utf_8
dba75d9338bed4f93159796aecef4717
% pop_importegimat() - import EGI Matlab segmented file % % Usage: % >> EEG = pop_importegimat(filename, srate, latpoint0); % % Inputs: % filename - Matlab file name % srate - sampling rate % latpoint0 - latency in sample ms of stimulus presentation. % When data files are exported using Netstation, the user specify % a time range (-100 ms to 500 ms for instance). In this % case, the latency of the stimulus is 100 (ms). Default is 0 (ms) % % Output: % EEG - EEGLAB dataset structure % % Authors: Arnaud Delorme, CERCO/UCSD, Jan 2010 % Copyright (C) Arnaud Delorme, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG com] = pop_importegimat(filename, srate, latpoint0, dataField); EEG = []; com = ''; if nargin < 3, latpoint0 = 0; end; if nargin < 4, dataField = 'Session'; end; if nargin < 1 % ask user [filename, filepath] = uigetfile('*.mat', 'Choose a Matlab file from Netstation -- pop_importegimat()'); if filename == 0 return; end; filename = fullfile(filepath, filename); tmpdata = load('-mat', filename); fieldValues = fieldnames(tmpdata); sessionPos = strmatch('Session', fieldValues); posFieldData = 1; if ~isempty(sessionPos), posFieldData = sessionPos; end; if ~isfield(tmpdata, 'samplingRate'), srate = 250; else srate = tmpdata.samplingRate; end; % epoch data files only promptstr = { { 'style' 'text' 'string' 'Sampling rate (Hz)' } ... { 'style' 'edit' 'string' int2str(srate) } ... { 'style' 'text' 'string' 'Sample latency for stimulus (ms)' } ... { 'style' 'edit' 'string' '0' } ... { 'style' 'text' 'string' 'Field containing data' } ... { 'style' 'popupmenu' 'string' fieldValues 'value' posFieldData } ... }; geometry = { [1 1] [1 1] [1 1] }; result = inputgui( 'geometry', geometry, 'uilist', promptstr, ... 'helpcom', 'pophelp(''pop_importegimat'')', ... 'title', 'Import a Matlab file from Netstation -- pop_importegimat()'); if length(result) == 0 return; end; srate = str2num(result{1}); latpoint0 = str2num(result{2}); dataField = fieldValues{result{3}}; if isempty(latpoint0), latpoint0 = 0; end; end; EEG = eeg_emptyset; fprintf('Reading EGI Matlab file %s\n', filename); tmpdata = load('-mat', filename); if isfield(tmpdata, 'samplingRate') % continuous file srate = tmpdata.samplingRate; end; fieldValues = fieldnames(tmpdata); if all(cellfun(@(x)isempty(findstr(x, 'Segment')), fieldValues)) EEG.srate = srate; indData = strmatch(dataField, fieldValues); EEG.data = tmpdata.(fieldValues{indData(1)}); EEG = eeg_checkset(EEG); EEG = readegilocs(EEG); com = sprintf('EEG = pop_importegimat(''%s'');', filename); else % get data types % -------------- allfields = fieldnames(tmpdata); for index = 1:length(allfields) allfields{index} = allfields{index}(1:findstr(allfields{index}, 'Segment')-2); end; datatypes = unique_bc(allfields); datatypes(cellfun(@isempty, datatypes)) = []; % read all data % ------------- counttrial = 1; EEG.srate = srate; latency = (latpoint0/1000)*EEG.srate+1; for index = 1:length(datatypes) tindex = 1; for tindex = 1:length(allfields) if isfield(tmpdata, sprintf('%s_Segment%d', datatypes{index}, tindex)) datatrial = getfield(tmpdata, sprintf('%s_Segment%d', datatypes{index}, tindex)); if counttrial == 1 EEG.pnts = size(datatrial,2); EEG.data = repmat(single(0), [size(datatrial,1), size(datatrial,2), 1000]); end; EEG.data(:,:,counttrial) = datatrial; EEG.event(counttrial).type = datatypes{index}; EEG.event(counttrial).latency = latency; EEG.event(counttrial).epoch = counttrial; counttrial = counttrial+1; latency = latency + EEG.pnts; end; end; end; fprintf('%d trials read\n', counttrial-1); EEG.data(:,:,counttrial:end) = []; EEG.setname = filename(1:end-4); EEG.nbchan = size(EEG.data,1); EEG.trials = counttrial-1; if latpoint0 ~= 1 EEG.xmin = -latpoint0/1000; end; EEG = eeg_checkset(EEG); % channel location % ---------------- if all(EEG.data(end,1:10) == 0) disp('Deleting empty data reference channel (reference channel location is retained)'); EEG.data(end,:) = []; EEG.nbchan = size(EEG.data,1); EEG = eeg_checkset(EEG); end; EEG = readegilocs(EEG); com = sprintf('EEG = pop_importegimat(''%s'', %3.2f, %3.2f, %d);', filename, srate, latpoint0, dataField); end;
github
lcnbeapp/beapp-master
pop_rejepoch.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_rejepoch.m
2,957
utf_8
a252e31365db94282bc48a802d83b48b
% pop_rejepoch() - Reject pre-labeled trials in a EEG dataset. % Ask for confirmation and accept the rejection % % Usage: % >> OUTEEG = pop_rejepoch( INEEG, trialrej, confirm) % % Inputs: % INEEG - Input dataset % trialrej - Array of 0s and 1s (depicting rejected trials) (size is % number of trials) % confirm - Display rejections and ask for confirmation. (0=no. 1=yes; % default is 1). % Outputs: % OUTEEG - output dataset % % Example: % >> data2 = pop_rejepoch( EEG, [1 1 1 0 0 0] ); % % reject the 3 first trials of a six-trial dataset % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab(), eegplot() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad function [EEG, com] = pop_rejepoch( EEG, tmprej, confirm); com = ''; if nargin < 1 help pop_rejepoch; return; end; if nargin < 2 tmprej = find(EEG.reject.rejglobal); end; if nargin < 3 confirm = 1; end; if islogical(tmprej), tmprej = tmprej+0; end; uniquerej = double(sort(unique(tmprej))); if length(tmprej) > 0 && length(uniquerej) <= 2 && ... ismember(uniquerej(1), [0 1]) && ismember(uniquerej(end), [0 1]) && any(~tmprej) format0_1 = 1; fprintf('%d/%d trials rejected\n', sum(tmprej), EEG.trials); else format0_1 = 0; fprintf('%d/%d trials rejected\n', length(tmprej), EEG.trials); end; if confirm ~= 0 ButtonName=questdlg2('Are you sure, you want to reject the labeled trials ?', ... 'Reject pre-labelled epochs -- pop_rejepoch()', 'NO', 'YES', 'YES'); switch ButtonName, case 'NO', disp('Operation cancelled'); return; case 'YES', disp('Compute new dataset'); end % switch end; % create a new set if set_out is non nul % -------------------------------------- if format0_1 tmprej = find(tmprej > 0); end; EEG = pop_select( EEG, 'notrial', tmprej); %com = sprintf( '%s = pop_rejepoch( %s, find(%s.reject.rejglobal), 0);', inputname(1), ... % inputname(1), inputname(1)); com = sprintf( '%s = pop_rejepoch( %s, %s);', inputname(1), inputname(1), vararg2str({ tmprej 0 })); return;
github
lcnbeapp/beapp-master
pop_loadeeg.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_loadeeg.m
5,829
utf_8
1009f8be42d7b9ae13a7b487334378c9
% pop_loadeeg() - load a Neuroscan .EEG file (via a pop-up window if no % arguments). Calls loadeeg(). % % Usage: % >> EEG = pop_loadeeg; % pop-up data entry window % >> EEG = pop_loadeeg( filename, filepath, range_chan, range_trials, ... % range_typeeeg, range_response, format); % no pop-up window % % Graphic interface: % "Data precision in bits..." - [edit box] data binary format length % in bits. Command line equivalent: 'format' % "Trial range subset" - [edit box] integer array. % Command line equivalent: 'range_trials' % "Type range subset" - [edit box] integer array. % Command line equivalent: 'range_typeeeg' % "Electrode subset" - [edit box] integer array. % Command line equivalent: 'range_chan' % "Response range subset" - [edit box] integer array. % Command line equivalent: 'range_response' % % Inputs: % filename - ['string'] file name % filepath - ['string'] file path % range_chan - [integer array] Import only selected electrodes % Ex: 3,4:10; {Default: [] -> import all} % range_trials - [integer array] Import only selected trials % { Default: [] -> import all} % range_typeeeg - [integer array] Import only trials of selected type % {Default: [] -> import all} % range_response - [integer array] Import only trials with selected % response values {Default: [] -> import all} % format - ['short'|'int32'] data binary format (Neuroscan 4.3 % saves data as 'int32'; earlier versions save data as % 'short'. Default is 'short'. % Outputs: % EEG - eeglab() data structure % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: loadeeg(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % uses calls to eeg_emptyset and loadeeg % popup loadeeg file % ------------------ function [EEG, command] = pop_loadeeg(filename, filepath, range_chan, range_sweeps, range_typeeeg, range_response, datformat); EEG = []; command = ''; if nargin < 1 % ask user [filename, filepath] = uigetfile('*.eeg;*.EEG', 'Choose an EEG file -- pop_loadeeg()'); if filename == 0 return; end; % popup window parameters % ----------------------- promptstr = { 'Data precision in bits (16 / 32 bit or Auto for NS v4.3):', ... 'Trial range subset:', ... 'Type range subset:', ... 'Electrodes subset:', ... 'Response range subset:'}; inistr = { 'Auto' '' '' '' '' }; pop_title = sprintf('Load an EEG dataset'); result = inputdlg2( promptstr, pop_title, 1, inistr, 'pop_loadeeg'); if size( result,1 ) == 0 return; end; % decode parameters % ----------------- precision = lower(strtrim(result{1})); if strcmpi(precision, '16') datformat = 'short'; elseif strcmpi(precision, '32') datformat = 'int32'; elseif (strcmpi(precision, '0') || strcmpi(precision, 'auto')) datformat = 'auto' end; range_sweeps = eval( [ '[' result{2} ']' ] ); range_typeeeg = eval( [ '[' result{3} ']' ] ); range_chan = eval( [ '[' result{4} ']' ] ); range_response = eval( [ '[' result{5} ']' ] ); else if exist('filepath') ~= 1 filepath = ''; end; end; if exist('datformat') ~= 1, datformat = 'auto'; end; if exist('range_chan') ~= 1 | isempty(range_chan) , range_chan = 'all'; end; if exist('range_sweeps') ~= 1 | isempty(range_sweeps) , range_sweeps = 'all'; end; if exist('range_typeeeg') ~= 1 | isempty(range_typeeeg) , range_typeeeg = 'all'; end; if exist('range_response') ~= 1 | isempty(range_response), range_response = 'all'; end; % load datas % ---------- EEG = eeg_emptyset; if ~isempty(filepath) if filepath(end) ~= '/' & filepath(end) ~= '\' & filepath(end) ~= ':' error('The file path last character must be a delimiter'); end; fullFileName = sprintf('%s%s', filepath, filename); else fullFileName = filename; end; [EEG.data, accept, eegtype, rt, eegresp, namechan, EEG.pnts, EEG.trials, EEG.srate, EEG.xmin, EEG.xmax] = ... loadeeg( fullFileName, range_chan, range_sweeps, range_typeeeg, 'all', 'all', range_response, datformat); EEG.comments = [ 'Original file: ' fullFileName ]; EEG.setname = 'Neuroscan EEG data'; EEG.nbchan = size(EEG.data,1); for index = 1:size(namechan,1) EEG.chanlocs(index).labels = deblank(char(namechan(index,:))); end; EEG = eeg_checkset(EEG); if any(rt) EEG = pop_importepoch( EEG, [rt(:)*1000 eegtype(:) accept(:) eegresp(:)], { 'RT' 'type' 'accept' 'response'}, {'RT'}, 1E-3, 0, 1); else EEG = pop_importepoch( EEG, [eegtype(:) accept(:) eegresp(:)], { 'type' 'accept' 'response'}, { }, 1E-3, 0, 1); end; command = sprintf('EEG = pop_loadeeg(''%s'', ''%s'', %s);', filename, filepath, ... vararg2str({range_chan range_sweeps range_typeeeg range_response datformat })); return;
github
lcnbeapp/beapp-master
pop_importdata.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_importdata.m
18,140
utf_8
55023f12445bd132394251c54b2b62e5
% pop_importdata() - import data from a Matlab variable or disk file by calling % importdata(). % Usage: % >> EEGOUT = pop_importdata(); % pop-up a data entry window % >> EEGOUT = pop_importdata( 'key', val,...); % no pop-up window % % Graphic interface (refer to a previous version of the GUI): % "Data file/array" - [Edit box] Data file or Matlab variable name to import % to EEGLAB. Command line equivalent: 'data' % "Data file/array" - [list box] select data format from listbox. If you % browse for a data file, the graphical interface might be % able to detect the file format from the file extension and % his list box accordingly. Note that you have to click on % the option to make it active. Command line equivalent is % 'dataformat' % "Dataset name" - [Edit box] Name for the new dataset. % In the last column of the graphic interface, the "EEG.setname" % text indicates which field of the EEG structure this parameter % is corresponding to (in this case 'setname'). % Command line equivalent: 'setname'. % "Data sampling rate" - [Edit box] In Hz. Command line equivalent: 'srate' % "Time points per epoch" - [Edit box] Number of data frames (points) per epoch. % Changing this value will change the number of data epochs. % Command line equivalent: 'pnts'. % "Start time" - [Edit box] This edit box is only present for % data epoch and specify the epochs start time in ms. Epoch upper % time limit is automatically calculated. % Command line equivalent: 'xmin' % "Number of channels" - [Edit box] Number of data channels. Command line % equivalent: 'nbchan'. This edit box cannot be edited. % "Ref. channel indices or mode" - [edit box] current reference. This edit box % cannot be edited. To change data reference, use menu % Tools > Re-reference calling function pop_reref(). The reference % can be a string, 'common' indicating an unknow common reference, % 'averef' indicating average reference, or an array of integer % containing the indices of the reference channels. % "Subject code" - [Edit box] subject code. For example, 'S01'. The command % line equivalent is 'subject'. % "Task Condition" - [Edit box] task condition. For example, 'Targets'. The % command line equivalent is 'condition'. % "Session number" - [Edit box] session number (from the same subject). All datasets % from the same subject and session will be assumed to use the % same ICA decomposition. The command line equivalent is 'session'. % "Subject group" - [Edit box] subject group. For example 'Patients' or 'Control'. % Command line equivalent is 'group'. % "About this dataset" - [Edit box] Comments about the dataset. Command line % equivalent is 'comments'. % "Channel locations file or array" - [Edit box] For channel data formats, see % >> readlocs help Command line equivalent: 'chanlocs' % "ICA weights array or text/binary file" - [edit box] Import ICA weights from other % decompositions (e.g., same data, different conditions). % To use the ICA weights from another loaded dataset (n), enter % ALLEEG(n).icaweights. Command line equivalent: 'icaweights' % "ICA sphere array or text/binary file" - [edit box] Import ICA sphere matrix. % In EEGLAB, ICA decompositions require a sphere matrix % and an unmixing weight matrix (see above). To use the sphere % matrix from another loaded dataset (n), enter ALLEEG(n).icasphere % Command line equivalent: 'icasphere'. % "From other dataset" - [push button] Press this button and enter the index % of another dataset. This will update the channel location or the % ICA edit box. % % Optional inputs: % 'setname' - Name of the EEG dataset % 'data' - ['varname'|'filename'] Import data from a Matlab variable or file % into an EEG data structure % 'dataformat' - ['array|matlab|ascii|float32le|float32be'] Input data format. % 'array' is a Matlab array in the global workspace. % 'matlab' is a Matlab file (which must contain a single variable). % 'ascii' is an ascii file. 'float32le' and 'float32be' are 32-bit % float data files with little-endian and big-endian byte order. % Data must be organised as (channels, timepoints) i.e. % channels = rows, timepoints = columns; else, as 3-D (channels, % timepoints, epochs). For convenience, the data file is transposed % if the number of rows is larger than the number of columns as the % program assumes that there is more channel than data points. % 'subject' - [string] subject code. For example, 'S01'. % {default: none -> each dataset from a different subject} % 'condition' - [string] task condition. For example, 'Targets' % {default: none -> all datasets from one condition} % 'group' - [string] subject group. For example 'Patients' or 'Control'. % {default: none -> all subjects in one group} % 'session' - [integer] session number (from the same subject). All datasets % from the same subject and session will be assumed to use the % same ICA decomposition {default: none -> each dataset from % a different session} % 'chanlocs' - ['varname'|'filename'] Import a channel location file. % For file formats, see >> help readlocs % 'nbchan' - [int] Number of data channels. % 'xmin' - [real] Data epoch start time (in seconds). % {default: 0} % 'pnts' - [int] Number of data points per data epoch. The number of trial % is automatically calculated. % {default: length of the data -> continuous data assumed} % 'srate' - [real] Data sampling rate in Hz {default: 1Hz} % 'ref' - [string or integer] reference channel indices. 'averef' indicates % average reference. Note that this does not perform referencing % but only sets the initial reference when the data is imported. % 'icaweight' - [matrix] ICA weight matrix. % 'icasphere' - [matrix] ICA sphere matrix. By default, the sphere matrix % is initialized to the identity matrix if it is left empty. % 'comments' - [string] Comments on the dataset, accessible through the EEGLAB % main menu using (Edit > About This Dataset). Use this to attach % background information about the experiment or data to the dataset. % Outputs: % EEGOUT - modified EEG dataset structure % % Note: This function calls pop_editset() to modify parameter values. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: pop_editset(), pop_select(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-16-02 text interface editing -sm & ad % 03-16-02 remove EEG.xmax et EEG.xmin (for continuous) -ad & sm % 04-02-02 debugging command line calls -ad & lf function [EEGOUT, com] = pop_importdata( varargin); com = ''; EEGOUT = eeg_emptyset; if nargin < 1 % if several arguments, assign values % popup window parameters % ----------------------- geometry = { [1.4 0.7 .8 0.5] [2 3.02] [1] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] ... [1] [1.4 0.7 .8 0.5] [1] [1.4 0.7 .8 0.5] [1.4 0.7 .8 0.5] }; editcomments = [ 'tmp = pop_comments(get(gcbf, ''userdata''), ''Edit comments of current dataset'');' ... 'if ~isempty(tmp), set(gcf, ''userdata'', tmp); end; clear tmp;' ]; commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ... 'if filename(1) ~=0,' ... ' set(findobj(''parent'', gcbf, ''tag'', tagtest), ''string'', [ filepath filename ]);' ... 'end;' ... 'clear filename filepath tagtest;' ]; commandsetfiletype = [ 'filename = get( findobj(''parent'', gcbf, ''tag'', ''globfile''), ''string'');' ... 'tmpext = findstr(filename,''.'');' ... 'if ~isempty(tmpext),' ... ' tmpext = lower(filename(tmpext(end)+1:end));' ... ' switch tmpext, ' ... ' case ''mat'', set(findobj(gcbf,''tag'', ''loclist''), ''value'',5);' ... ' case ''fdt'', set(findobj(gcbf,''tag'', ''loclist''), ''value'',3);' ... ' case ''txt'', set(findobj(gcbf,''tag'', ''loclist''), ''value'',2);' ... ' end;' ... 'end; clear tmpext filename;' ]; commandselica = [ 'res = inputdlg2({ ''Enter dataset number'' }, ''Select ICA weights and sphere from other dataset'', 1, { ''1'' });' ... 'if ~isempty(res),' ... ' set(findobj( ''parent'', gcbf, ''tag'', ''weightfile''), ''string'', sprintf(''ALLEEG(%s).icaweights'', res{1}));' ... ' set(findobj( ''parent'', gcbf, ''tag'', ''sphfile'') , ''string'', sprintf(''ALLEEG(%s).icasphere'' , res{1}));' ... 'end;' ]; commandselchan = [ 'res = inputdlg2({ ''Enter dataset number'' }, ''Select channel information from other dataset'', 1, { ''1'' });' ... 'if ~isempty(res),' ... ' set(findobj( ''parent'', gcbf, ''tag'', ''chanfile''), ' ... ' ''string'', sprintf(''{ ALLEEG(%s).chanlocs ALLEEG(%s).chaninfo ALLEEG(%s).urchanlocs }'', res{1}, res{1}, res{1}));' ... 'end;' ]; if isstr(EEGOUT.ref) curref = EEGOUT.ref; else if length(EEGOUT.ref) > 1 curref = [ int2str(abs(EEGOUT.ref)) ]; else curref = [ int2str(abs(EEGOUT.ref)) ]; end; end; uilist = { ... { 'Style', 'text', 'string', 'Data file/array (click on the selected option)', 'horizontalalignment', 'right', 'fontweight', 'bold' }, ... { 'Style', 'popupmenu', 'string', 'Matlab variable|ASCII text file|float32 le file|float32 be file|Matlab .mat file', ... 'fontweight', 'bold', 'tag','loclist' } ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'globfile' }, ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', ... [ 'tagtest = ''globfile'';' commandload commandsetfiletype ] }, ... ... { 'Style', 'text', 'string', 'Dataset name', 'horizontalalignment', 'right', ... 'fontweight', 'bold' }, { 'Style', 'edit', 'string', '' }, { } ... ... { 'Style', 'text', 'string', 'Data sampling rate (Hz)', 'horizontalalignment', 'right', 'fontweight', ... 'bold' }, { 'Style', 'edit', 'string', num2str(EEGOUT.srate) }, ... { 'Style', 'text', 'string', 'Subject code', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', '' }, ... { 'Style', 'text', 'string', 'Time points per epoch (0->continuous)', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', num2str(EEGOUT.pnts) }, ... { 'Style', 'text', 'string', 'Task condition', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', '' }, ... { 'Style', 'text', 'string', 'Start time (sec) (only for data epochs)', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', num2str(EEGOUT.xmin) }, ... { 'Style', 'text', 'string', 'Session number', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', '' }, ... { 'Style', 'text', 'string', 'Number of channels (0->set from data)', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', '0' }, ... { 'Style', 'text', 'string', 'Subject group', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', '' }, ... { 'Style', 'text', 'string', 'Ref. channel indices or mode (see help)', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', curref }, ... { 'Style', 'text', 'string', 'About this dataset', 'horizontalalignment', 'right', ... }, { 'Style', 'pushbutton', 'string', 'Enter comments' 'callback' editcomments }, ... { } ... { 'Style', 'text', 'string', 'Channel location file or info', 'horizontalalignment', 'right', 'fontweight', ... 'bold' }, {'Style', 'pushbutton', 'string', 'From other dataset', 'callback', commandselchan }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'chanfile' }, ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''chanfile'';' commandload ] }, ... ... { 'Style', 'text', 'string', ... ' (note: autodetect file format using file extension; use menu "Edit > Channel locations" for more importing options)', ... 'horizontalalignment', 'right' }, ... ... { 'Style', 'text', 'string', 'ICA weights array or text/binary file (if any):', 'horizontalalignment', 'right' }, ... { 'Style', 'pushbutton' 'string' 'from other dataset' 'callback' commandselica }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'weightfile' }, ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''weightfile'';' commandload ] }, ... ... { 'Style', 'text', 'string', 'ICA sphere array or text/binary file (if any):', 'horizontalalignment', 'right' }, ... { 'Style', 'pushbutton' 'string' 'from other dataset' 'callback' commandselica }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'sphfile' } ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''sphfile'';' commandload ] } }; [ results newcomments ] = inputgui( geometry, uilist, 'pophelp(''pop_importdata'');', 'Import dataset info -- pop_importdata()'); if length(results) == 0, return; end; args = {}; % specific to importdata (not identical to pop_editset % ---------------------------------------------------- switch results{1} case 1, args = { args{:}, 'dataformat', 'array' }; case 2, args = { args{:}, 'dataformat', 'ascii' }; case 3, args = { args{:}, 'dataformat', 'float32le' }; case 4, args = { args{:}, 'dataformat', 'float32be' }; case 5, args = { args{:}, 'dataformat', 'matlab' }; end; i = 3; if ~isempty( results{i+7} ) , args = { args{:}, 'nbchan', str2num(results{i+7}) }; end; if ~isempty( results{2} ) , args = { args{:}, 'data', results{2} }; end; if ~isempty( results{i } ) , args = { args{:}, 'setname', results{i } }; end; if ~isempty( results{i+1} ) , args = { args{:}, 'srate', str2num(results{i+1}) }; end; if ~isempty( results{i+2} ) , args = { args{:}, 'subject', results{i+2} }; end; if ~isempty( results{i+3} ) , args = { args{:}, 'pnts', str2num(results{i+3}) }; end; if ~isempty( results{i+4} ) , args = { args{:}, 'condition', results{i+4} }; end; if ~isempty( results{i+5} ) , args = { args{:}, 'xmin', str2num(results{i+5}) }; end; if ~isempty( results{i+6} ) , args = { args{:}, 'session', str2num(results{i+6}) }; end; if ~isempty( results{i+8} ) , args = { args{:}, 'group', results{i+8} }; end; if ~isempty( results{i+9} ) , args = { args{:}, 'ref', str2num(results{i+9}) }; end; if ~isempty( newcomments ) , args = { args{:}, 'comments', newcomments }; end; if abs(str2num(results{i+5})) > 10, fprintf('WARNING: are you sure the epoch start time (%3.2f) is in seconds\n'); end; if ~isempty( results{i+10} ) , args = { args{:}, 'chanlocs' , results{i+10} }; end; if ~isempty( results{i+11} ), args = { args{:}, 'icaweights', results{i+11} }; end; if ~isempty( results{i+12} ) , args = { args{:}, 'icasphere', results{i+12} }; end; % generate the output command % --------------------------- EEGOUT = pop_editset(EEGOUT, args{:}); com = sprintf( 'EEG = pop_importdata(%s);', vararg2str(args) ); %com = ''; %for i=1:2:length(args) % if ~isempty( args{i+1} ) % if isstr( args{i+1} ) com = sprintf('%s, ''%s'', ''%s''', com, args{i}, char(args{i+1}) ); % else com = sprintf('%s, ''%s'', [%s]', com, args{i}, num2str(args{i+1}) ); % end; % else % com = sprintf('%s, ''%s'', []', com, args{i} ); % end; %end; %com = [ 'EEG = pop_importdata(' com(2:end) ');']; else % no interactive inputs EEGOUT = pop_editset(EEGOUT, varargin{:}); end; return;
github
lcnbeapp/beapp-master
pop_newtimef.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_newtimef.m
17,862
utf_8
5299a688b12982118ec8c0a8b74b7567
% pop_newtimef() - Returns estimates and plots of event-related (log) spectral % perturbation (ERSP) and inter-trial coherence (ITC) phenomena % timelocked to a set of single-channel input epochs % % Usage: % >> pop_newtimef(EEG, typeplot); % pop_up window % >> pop_newtimef(EEG, typeplot, lastcom); % pop_up window % >> pop_newtimef(EEG, typeplot, channel); % do not pop-up window % >> pop_newtimef(EEG, typeproc, num, tlimits,cycles, % 'key1',value1,'key2',value2, ... ); % % Graphical interface: % "Channel/component number" - [edit box] this is the index of the data % channel or the index of the component for which to plot the % time-frequency decomposition. % "Sub-epoch time limits" - [edit box] sub epochs may be extracted (note that % this function aims at plotting data epochs not continuous data). % You may select the new epoch limits in this edit box. % "Use n time points" - [muliple choice list] this is the number of time % points to use for the time-frequency decomposition. The more % time points, the longer the time-frequency decomposition % takes to compute. % "Frequency limits" - [edit box] these are the lower and upper % frequency limit of the time-frequency decomposition. Instead % of limits, you may also enter a sequence of frequencies. For % example to compute the time-frequency decomposition at all % frequency between 5 and 50 hertz with 1 Hz increment, enter "1:50" % "Use limits, padding n" - [muliple choice list] "using limits" means % to use the upper and lower limits in "Frequency limits" with % a specific padding ratio (padratio argument of newtimef). % The last option "use actual frequencies" forces newtimef to % ignore the padratio argument and use the vector of frequencies % given as input in the "Frequency limits" edit box. % "Log spaced" - [checkbox] you may check this box to compute log-spaced % frequencies. Note that this is only relevant if you specify % frequency limits (in case you specify actual frequencies, % this parameter is ignored). % "Use divisive baseline" - [muliple choice list] there are two types of % baseline correction, additive (the baseline is subtracted) % or divisive (the data is divided by the baseline values). % The choice is yours. There is also the option to perform % baseline correction in single trials. See the 'trialbase' "full" % option in the newtimef.m documentation for more information. % "No baseline" - [checkbox] check this box to compute the raw time-frequency % decomposition with no baseline removal. % "Wavelet cycles" - [edit box] specify the number of cycle at the lowest % and highest frequency. Instead of specifying the number of cycle % at the highest frequency, you may also specify a wavelet % "factor" (see newtimef help message). In addition, it is % possible to specify actual wavelet cycles for each frequency % by entering a sequence of numbers. % "Use FFT" - [checkbox] check this checkbox to use FFT instead of % wavelet decomposition. % "ERSP color limits" - [edit box] set the upper and lower limit for the % ERSP image. % "see log power" - [checkbox] the log power values (in dB) are plotted. % Uncheck this box to plot the absolute power values. % "ITC color limits" - [edit box] set the upper and lower limit for the % ITC image. % "plot ITC phase" - [checkbox] check this box plot plot (overlayed on % the ITC amplitude) the polarity of the ITC complex value. % "Bootstrap significance level" - [edit box] use this edit box to enter % the p-value threshold for masking both the ERSP and the ITC % image for significance (masked values appear as light green) % "FDR correct" - [checkbox] this correct the p-value for multiple comparisons % (accross all time and frequencies) using the False Discovery % Rate method. See the fdr.m function for more details. % "Optional newtimef arguments" - [edit box] addition argument for the % newtimef function may be entered here in the 'key', value % format. % "Plot Event Related Spectral Power" - [checkbox] plot the ERSP image % showing event related spectral stimulus induced changes % "Plot Inter Trial Coherence" - [checkbox] plot the ITC image. % "Plot Curve at each frequency" - [checkbox] instead of plotting images, % it is also possible to display curves at each frequency. % This functionality is beta and might not work in all cases. % % Inputs: % INEEG - input EEG dataset % typeproc - type of processing: 1 process the raw channel data % 0 process the ICA component data % num - component or channel number % tlimits - [mintime maxtime] (ms) sub-epoch time limits to plot % cycles - > 0 --> Number of cycles in each analysis wavelet % = 0 --> Use FFTs (with constant window length % at all frequencies) % % Optional inputs: % See the newtimef() function. % % Outputs: Same as newtimef(); no outputs are returned when a % window pops-up to ask for additional arguments % % Saving the ERSP and ITC output values: % Simply look up the history using the eegh function (type eegh). % Then copy and paste the pop_newtimef() command and add output args. % See the newtimef() function for a list of outputs. For instance, % >> [ersp itc powbase times frequencies] = pop_newtimef( EEG, ....); % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: newtimef(), eeglab() % Copyright (C) 2002 University of California San Diego % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-08-02 add eeglab option & optimize variable sizes -ad % 03-10-02 change newtimef call -ad % 03-18-02 added title -ad & sm % 04-04-02 added outputs -ad & sm function varargout = pop_newtimef(EEG, typeproc, num, tlimits, cycles, varargin ); varargout{1} = ''; % display help if not enough arguments % ------------------------------------ if nargin < 2 help pop_newtimef; return; end; lastcom = []; if nargin < 3 popup = 1; else popup = isstr(num) | isempty(num); if isstr(num) lastcom = num; end; end; % pop up window % ------------- if popup [txt vars] = gethelpvar('newtimef.m'); g = [1 0.3 0.6 0.4]; geometry = { g g g g g g g g [0.975 1.27] [1] [1.2 1 1.2]}; uilist = { ... { 'Style', 'text', 'string', fastif(typeproc, 'Channel number', 'Component number'), 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,3,[],'1') 'tag' 'chan'} {} {} ... ... { 'Style', 'text', 'string', 'Sub epoch time limits [min max] (msec)', 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,4,[],[ int2str(EEG.xmin*1000) ' ' int2str(EEG.xmax*1000) ]) 'tag' 'tlimits' } ... { 'Style', 'popupmenu', 'string', 'Use 50 time points|Use 100 time points|Use 150 time points|Use 200 time points|Use 300 time points|Use 400 time points' 'tag' 'ntimesout' 'value' 4} { } ... ... { 'Style', 'text', 'string', 'Frequency limits [min max] (Hz) or sequence', 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', '' 'tag' 'freqs' } ... { 'Style', 'popupmenu', 'string', 'Use limits, padding 1|Use limits, padding 2|Use limits, padding 4|Use actual freqs.' 'tag' 'nfreqs' } ... { 'Style', 'checkbox', 'string' 'Log spaced' 'value' 0 'tag' 'freqscale' } ... ... { 'Style', 'text', 'string', 'Baseline limits [min max] (msec) (0->pre-stim.)', 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', '0' 'tag' 'baseline' } ... { 'Style', 'popupmenu', 'string', 'Use divisive baseline (DIV)|Use standard deviation (STD)|Use single trial DIV baseline|Use single trial STD baseline' 'tag' 'basenorm' } ... { 'Style', 'checkbox', 'string' 'No baseline' 'tag' 'nobase' } ... ... { 'Style', 'text', 'string', 'Wavelet cycles [min max/fact] or sequence', 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,5,[],'3 0.5') 'tag' 'cycle' } ... { 'Style', 'checkbox', 'string' 'Use FFT' 'value' 0 'tag' 'fft' } ... { } ... ... { 'Style', 'text', 'string', 'ERSP color limits [max] (min=-max)', 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', '' 'tag' 'erspmax'} ... { 'Style', 'checkbox', 'string' 'see log power (set)' 'tag' 'scale' 'value' 1} {} ... ... { 'Style', 'text', 'string', 'ITC color limits [max]', 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', '' 'tag' 'itcmax'} ... { 'Style', 'checkbox', 'string' 'plot ITC phase (set)' 'tag' 'plotphase' } {} ... ... { 'Style', 'text', 'string', 'Bootstrap significance level (Ex: 0.01 -> 1%)', 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,'alpha') 'tag' 'alpha'} ... { 'Style', 'checkbox', 'string' 'FDR correct (set)' 'tag' 'fdr' } {} ... ... { 'Style', 'text', 'string', 'Optional newtimef() arguments (see Help)', 'fontweight', 'bold', ... 'tooltipstring', 'See newtimef() help via the Help button on the right...' } ... { 'Style', 'edit', 'string', '' 'tag' 'options' } ... {} ... { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotersp','present',0), 'string', ... 'Plot Event Related Spectral Power', 'tooltipstring', ... 'Plot log spectral perturbation image in the upper panel' 'tag' 'plotersp' } ... { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotitc','present',0), 'string', ... 'Plot Inter Trial Coherence', 'tooltipstring', ... 'Plot the inter-trial coherence image in the lower panel' 'tag' 'plotitc' } ... { 'Style', 'checkbox', 'value', 0, 'string', ... 'Plot curve at each frequency' 'tag' 'plotcurve' } ... }; % { 'Style', 'edit', 'string', '''padratio'', 4, ''plotphase'', ''off''' } ... %{ 'Style', 'text', 'string', '[set] -> Plot ITC phase sign', 'fontweight', 'bold', ... % 'tooltipstring', ['Plot the sign (+/-) of inter-trial coherence phase' 10 ... % 'as red (+) or blue (-)'] } ... % { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotphase','present',1) } { } ... [ tmp1 tmp2 strhalt result ] = inputgui( geometry, uilist, 'pophelp(''pop_newtimef'');', ... fastif(typeproc, 'Plot channel time frequency -- pop_newtimef()', ... 'Plot component time frequency -- pop_newtimef()')); if length( tmp1 ) == 0 return; end; if result.fft, result.cycle = '0'; end; if result.nobase, result.baseline = 'NaN'; end; num = eval( [ '[' result.chan ']' ] ); tlimits = eval( [ '[' result.tlimits ']' ] ); cycles = eval( [ '[' result.cycle ']' ] ); freqs = eval( [ '[' result.freqs ']' ] ); %result.ncycles == 2 is ignored % add topoplot % ------------ options = []; if isfield(EEG.chanlocs, 'theta') && ~isempty(EEG.chanlocs(num).theta) if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end; if typeproc == 1 if isempty(EEG.chanlocs), caption = [ 'Channel ' int2str(num) ]; else caption = EEG.chanlocs(num).labels; end; options = [options ', ''topovec'', ' int2str(num) ... ', ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo, ''caption'', ''' caption '''' ]; else options = [options ', ''topovec'', EEG.icawinv(:,' int2str(num) ... '), ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo, ''caption'', [''IC ' num2str(num) ''']' ]; end; end; if ~isempty( result.baseline ), options = [ options ', ''baseline'',[' result.baseline ']' ]; end; if ~isempty( result.alpha ), options = [ options ', ''alpha'',' result.alpha ]; end; if ~isempty( result.options ), options = [ options ',' result.options ]; end; if ~isempty( result.freqs ), options = [ options ', ''freqs'', [' result.freqs ']' ]; end; if ~isempty( result.erspmax ), options = [ options ', ''erspmax'', [' result.erspmax ']' ]; end; if ~isempty( result.itcmax ), options = [ options ', ''itcmax'',' result.itcmax ]; end; if ~result.plotersp, options = [ options ', ''plotersp'', ''off''' ]; end; if ~result.plotitc, options = [ options ', ''plotitc'' , ''off''' ]; end; if result.plotcurve, options = [ options ', ''plottype'', ''curve''' ]; end; if result.fdr, options = [ options ', ''mcorrect'', ''fdr''' ]; end; if result.freqscale, options = [ options ', ''freqscale'', ''log''' ]; end; if ~result.plotphase, options = [ options ', ''plotphase'', ''off''' ]; end; if ~result.scale, options = [ options ', ''scale'', ''abs''' ]; end; if result.ntimesout == 1, options = [ options ', ''ntimesout'', 50' ]; end; if result.ntimesout == 2, options = [ options ', ''ntimesout'', 100' ]; end; if result.ntimesout == 3, options = [ options ', ''ntimesout'', 150' ]; end; if result.ntimesout == 5, options = [ options ', ''ntimesout'', 300' ]; end; if result.ntimesout == 6, options = [ options ', ''ntimesout'', 400' ]; end; if result.nfreqs == 1, options = [ options ', ''padratio'', 1' ]; end; if result.nfreqs == 2, options = [ options ', ''padratio'', 2' ]; end; if result.nfreqs == 3, options = [ options ', ''padratio'', 4' ]; end; if result.nfreqs == 4, options = [ options ', ''nfreqs'', ' int2str(length(freqs)) ]; end; if result.basenorm == 2, options = [ options ', ''basenorm'', ''on''' ]; end; if result.basenorm == 4, options = [ options ', ''basenorm'', ''on''' ]; end; if result.basenorm >= 3, options = [ options ', ''trialbase'', ''full''' ]; end; % add title % --------- if isempty( findstr( '''title''', result.options)) if ~isempty(EEG.chanlocs) & typeproc chanlabel = EEG.chanlocs(num).labels; else chanlabel = int2str(num); end; end; % compute default winsize % ----------------------- if EEG.xmin < 0 && isempty(findstr( '''winsize''', result.options)) && isempty( result.freqs ) fprintf('Computing window size in pop_newtimef based on half of the length of the baseline period'); options = [ options ', ''winsize'', ' int2str(-EEG.xmin*EEG.srate) ]; end; figure; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; else options = [ ',' vararg2str(varargin) ]; end; % compute epoch limits % -------------------- if isempty(tlimits) tlimits = [EEG.xmin, EEG.xmax]*1000; end; pointrange1 = round(max((tlimits(1)/1000-EEG.xmin)*EEG.srate, 1)); pointrange2 = round(min((tlimits(2)/1000-EEG.xmin)*EEG.srate, EEG.pnts)); pointrange = [pointrange1:pointrange2]; % call function sample either on raw data or ICA data % --------------------------------------------------- if typeproc == 1 tmpsig = EEG.data(num,pointrange,:); else if ~isempty( EEG.icasphere ) if ~isempty(EEG.icaact) tmpsig = EEG.icaact(num,pointrange,:); else tmpsig = (EEG.icaweights(num,:)*EEG.icasphere)*reshape(EEG.data(:,pointrange,:), EEG.nbchan, EEG.trials*length(pointrange)); end; else error('You must run ICA first'); end; end; tmpsig = reshape( tmpsig, length(num), size(tmpsig,2)*size(tmpsig,3)); % outputs % ------- outstr = ''; if ~popup for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end; if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end; end; % plot the datas and generate output command % -------------------------------------------- if length( options ) < 2 options = ''; end; if nargin < 4 varargout{1} = sprintf('figure; pop_newtimef( %s, %d, %d, [%s], [%s] %s);', inputname(1), typeproc, num, ... int2str(tlimits), num2str(cycles), options); end; com = sprintf('%s newtimef( tmpsig(:, :), length(pointrange), [tlimits(1) tlimits(2)], EEG.srate, cycles %s);', outstr, options); eval(com) return; % get contextual help % ------------------- function txt = context(var, allvars, alltext); loc = strmatch( var, allvars); if ~isempty(loc) txt= alltext{loc(1)}; else disp([ 'warning: variable ''' var ''' not found']); txt = ''; end;
github
lcnbeapp/beapp-master
pop_comperp.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_comperp.m
24,065
utf_8
0e8f83142764654afb0ecb8f592a7953
% pop_comperp() - Compute the grand average ERP waveforms of multiple datasets % currently loaded into EEGLAB, with optional ERP difference-wave % plotting and t-tests. Creates a plotting figure. % Usage: % >> pop_comperp( ALLEEG, flag ); % pop-up window, interactive mode % >> [erp1 erp2 erpsub time sig] = pop_comperp( ALLEEG, flag, ... % datadd, datsub, 'key', 'val', ...); % Inputs: % ALLEEG - Array of loaded EEGLAB EEG structure datasets % flag - [0|1] 0 -> Use ICA components; 1 -> use data channels {default: 1} % datadd - [integer array] List of ALLEEG dataset indices to average to make % an ERP grand average and optionally to compare with 'datsub' datasets. % % Optional inputs: % datsub - [integer array] List of ALLEEG dataset indices to average and then % subtract from the 'datadd' result to make an ERP grand mean difference. % Together, 'datadd' and 'datsub' may be used to plot and compare grand mean % responses across subjects or conditions. Both arrays must contain the same % number of dataset indices and entries must be matched pairwise (Ex: % 'datadd' indexes condition A datasets from subjects 1:n, and 'datsub', % condition B datasets from the same subjects 1:n). {default: []} % 'alpha' - [0 < float < 1] Apply two-tailed t-tests for p < alpha. If 'datsub' is % not empty, perform t-tests at each latency. If 'datasub' is empty, % perform two-tailed t-tests against a 0 mean dataset with same variance. % Significant time regions are highlighted in the plotted data. % 'chans' - [integer array] Vector of chans. or comps. to use {default: all} % 'geom' - ['scalp'|'array'] Plot erps in a scalp array (plottopo()) % or as a rectangular array (plotdata()). Note: Only channels % (see 'chans' above) can be plotted in a 'scalp' array. % 'tlim' - [min max] Time window (ms) to plot data {default: whole time range} % 'title' - [string] Plot title {default: none} % 'ylim' - [min max] y-axis limits {default: auto from data limits} % 'mode' - ['ave'|'rms'] Plotting mode. Plot either grand average or RMS % (root mean square) time course(s) {default: 'ave' -> grand average}. % 'std' - ['on'|'off'|'none'] 'on' -> plot std. devs.; 'none' -> do not % interact with other options {default:'none'} % % Vizualisation options: % 'addavg' - ['on'|'off'] Plot grand average (or RMS) of 'datadd' datasets % {default: 'on' if 'datsub' empty, otherwise 'off'} % 'subavg' - ['on'|'off'] Plot grand average (or RMS) of 'datsub' datasets % {default:'off'} % 'diffavg' - ['on'|'off'] Plot grand average (or RMS) difference % 'addall' - ['on'|'off'] Plot the ERPs for all 'dataadd' datasets only {default:'off'} % 'suball' - ['on'|'off'] Plot the ERPs for all 'datasub datasets only {default:'off'} % 'diffall' - ['on'|'off'] Plot all the 'datadd'-'datsub' ERP differences {default:'off'} % 'addstd' - ['on'|'off'] Plot std. dev. for 'datadd' datasets only % {default: 'on' if 'datsub' empty, otherwise 'off'} % 'substd' - ['on'|'off'] Plot std. dev. of 'datsub' datasets only {default:'off'} % 'diffstd' - ['on'|'off'] Plot std. dev. of 'datadd'-'datsub' differences {default:'on'} % 'diffonly' - ['on'|'off'|'none'] 'on' -> plot difference only; 'none' -> do not affect % other options {default:'none'} % 'allerps' - ['on'|'off'|'none'] 'on' -> show ERPs for all conditions; % 'none' -> do not affect other options {default:'none'} % 'tplotopt' - [cell array] Pass 'key', val' plotting options to plottopo() % % Output: % erp1 - Grand average (or rms) of the 'datadd' datasets % erp2 - Grand average (or rms) of the 'datsub' datasets % erpsub - Grand average (or rms) 'datadd' minus 'datsub' difference % times - Vector of epoch time indices % sig - T-test significance values (chans,times). % % Author: Arnaud Delorme, CNL / Salk Institute, 15 March 2003 % % Note: t-test functions were adapted for matrix preprocessing from C functions % by Press et al. See the description in the pttest() code below % for more information. % % See also: eeglab(), plottopo() % Copyright (C) 15 March 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [erp1, erp2, erpsub, times, pvalues] = pop_comperp( ALLEEG, flag, datadd, datsub, varargin); erp1 = ''; if nargin < 1 help pop_comperp; return; end; if isempty(ALLEEG) error('pop_comperp: cannot process empty sets of data'); end; if nargin < 2 flag = 1; end; allcolors = { 'b' 'r' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' ... 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm'}; erp1 = ''; if nargin < 3 gtmp = [1.1 0.8 .21 .21 .21 0.1]; gtmp2 = [1.48 1.03 1]; uigeom = { [2.6 0.95] gtmp gtmp gtmp [1] gtmp2 gtmp2 [1.48 0.25 1.75] gtmp2 gtmp2 }; commulcomp= ['if get(gcbo, ''value''),' ... ' set(findobj(gcbf, ''tag'', ''multcomp''), ''enable'', ''on'');' ... 'else,' ... ' set(findobj(gcbf, ''tag'', ''multcomp''), ''enable'', ''off'');' ... 'end;']; uilist = { { } ... { 'style' 'text' 'string' 'avg. std. all ERPs' } ... { 'style' 'text' 'string' 'Datasets to average (ex: 1 3 4):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'checkbox' 'string' '' 'value' 1 } ... { 'style' 'checkbox' 'string' '' } ... { 'style' 'checkbox' 'string' '' } { } ... { 'style' 'text' 'string' 'Datasets to average and subtract (ex: 5 6 7):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'checkbox' 'string' '' 'value' 1 } ... { 'style' 'checkbox' 'string' '' } ... { 'style' 'checkbox' 'string' '' } { } ... { 'style' 'text' 'string' 'Plot difference' } { } ... { 'style' 'checkbox' 'string' '' 'value' 1 } ... { 'style' 'checkbox' 'string' '' } ... { 'style' 'checkbox' 'string' '' } { } ... { } ... { 'style' 'text' 'string' fastif(flag, 'Channels subset ([]=all):', ... 'Components subset ([]=all):') } ... { 'style' 'edit' 'string' '' } { } ... { 'style' 'text' 'string' 'Highlight significant regions (.01 -> p=.01)' } ... { 'style' 'edit' 'string' '' } { } ... { 'style' 'text' 'string' 'Use RMS instead of average (check):' } { 'style' 'checkbox' 'string' '' } { } ... { 'style' 'text' 'string' 'Low pass (Hz) (for display only)' } ... { 'style' 'edit' 'string' '' } { } ... { 'style' 'text' 'string' 'Plottopo options (''key'', ''val''):' } ... { 'style' 'edit' 'string' '''ydir'', -1' } ... { 'style' 'pushbutton' 'string' 'Help' 'callback', 'pophelp(''plottopo'')' } ... }; % remove geometry textbox for ICA components result = inputgui( uigeom, uilist, 'pophelp(''pop_comperp'')', 'ERP grand average/RMS - pop_comperp()'); if length(result) == 0, return; end; %decode parameters list options = {}; datadd = eval( [ '[' result{1} ']' ]); if result{2}, options = { options{:} 'addavg' 'on' }; else, options = { options{:} 'addavg' 'off' }; end; if result{3}, options = { options{:} 'addstd' 'on' }; else, options = { options{:} 'addstd' 'off' }; end; if result{4}, options = { options{:} 'addall' 'on' }; end; datsub = eval( [ '[' result{5} ']' ]); if result{6}, options = { options{:} 'subavg' 'on' }; end; if result{7}, options = { options{:} 'substd' 'on' }; end; if result{8}, options = { options{:} 'suball' 'on' }; end; if result{9}, options = { options{:} 'diffavg' 'on' }; else, options = { options{:} 'diffavg' 'off' }; end; if result{10}, options = { options{:} 'diffstd' 'on' }; else, options = { options{:} 'diffstd' 'off' }; end; if result{11}, options = { options{:} 'diffall' 'on' }; end; if result{12}, options = { options{:} 'chans' eval( [ '[' result{12} ']' ]) }; end; if ~isempty(result{13}), options = { options{:} 'alpha' str2num(result{13}) }; end; if result{14}, options = { options{:} 'mode' 'rms' }; end; if ~isempty(result{15}), options = { options{:} 'lowpass' str2num(result{15}) }; end; if ~isempty(result{16}), options = { options{:} 'tplotopt' eval([ '{ ' result{16} ' }' ]) }; end; else options = varargin; end; if nargin == 3 datsub = []; % default end % decode inputs % ------------- if isempty(datadd), error('First edit box (datasets to add) can not be empty'); end; g = finputcheck( options, ... { 'chans' 'integer' [] [1:ALLEEG(datadd(1)).nbchan]; 'title' 'string' [] ''; 'alpha' 'float' [] []; 'geom' 'string' {'scalp';'array'} fastif(flag, 'scalp', 'array'); 'addstd' 'string' {'on';'off'} fastif(isempty(datsub), 'on', 'off'); 'substd' 'string' {'on';'off'} 'off'; 'diffstd' 'string' {'on';'off'} 'on'; 'addavg' 'string' {'on';'off'} fastif(isempty(datsub), 'on', 'off'); 'subavg' 'string' {'on';'off'} 'off'; 'diffavg' 'string' {'on';'off'} 'on'; 'addall' 'string' {'on';'off'} 'off'; 'suball' 'string' {'on';'off'} 'off'; 'diffall' 'string' {'on';'off'} 'off'; 'std' 'string' {'on';'off';'none'} 'none'; 'diffonly' 'string' {'on';'off';'none'} 'none'; 'allerps' 'string' {'on';'off';'none'} 'none'; 'lowpass' 'float' [0 Inf] []; 'tlim' 'float' [] []; 'ylim' 'float' [] []; 'tplotopt' 'cell' [] {}; 'mode' 'string' {'ave';'rms'} 'ave'; 'multcmp' 'integer' [0 Inf] [] }); if isstr(g), error(g); end; if length(datadd) == 1 disp('Cannot perform statistics using only 1 dataset'); g.alpha = []; end; h = figure; axcopy try, icadefs; set(h, 'color', BACKCOLOR); axis off; catch, end; % backward compatibility of param % ------------------------------- if ~strcmpi(g.diffonly, 'none') if strcmpi(g.diffonly, 'off'), g.addavg = 'on'; g.subavg = 'on'; end; end; if ~strcmpi(g.allerps, 'none') if isempty(datsub) g.addall = g.allerps; else g.diffall = g.allerps; end; end; if ~strcmpi(g.std, 'none') if isempty(datsub) g.addstd = g.std; else g.diffstd = g.std; end; end; % check consistency % ----------------- if length(datsub) > 0 & length(datadd) ~= length(datsub) error('The number of component to subtract must be the same as the number of components to add'); end; % if only 2 dataset entered, toggle average to single trial % --------------------------------------------------------- if length(datadd) == 1 &strcmpi(g.addavg, 'on') g.addavg = 'off'; g.addall = 'on'; end; if length(datsub) == 1 &strcmpi(g.subavg, 'on') g.subavg = 'off'; g.suball = 'on'; end; if length(datsub) == 1 & length(datadd) == 1 &strcmpi(g.diffavg, 'on') g.diffavg = 'off'; g.diffall = 'on'; end; regions = {}; pnts = ALLEEG(datadd(1)).pnts; srate = ALLEEG(datadd(1)).srate; xmin = ALLEEG(datadd(1)).xmin; xmax = ALLEEG(datadd(1)).xmax; nbchan = ALLEEG(datadd(1)).nbchan; chanlocs = ALLEEG(datadd(1)).chanlocs; unionIndices = union_bc(datadd, datsub); for index = unionIndices(:)' if ALLEEG(index).pnts ~= pnts, error(['Dataset ' int2str(index) ' does not have the same number of points as others']); end; if ALLEEG(index).xmin ~= xmin, error(['Dataset ' int2str(index) ' does not have the same xmin as others']); end; if ALLEEG(index).xmax ~= xmax, error(['Dataset ' int2str(index) ' does not have the same xmax as others']); end; if ALLEEG(index).nbchan ~= nbchan, error(['Dataset ' int2str(index) ' does not have the same number of channels as others']); end; end; if ~isempty(g.alpha) & length(datadd) == 1 error([ 'T-tests require more than one ''' datadd ''' dataset' ]); end % compute ERPs for add % -------------------- for index = 1:length(datadd) TMPEEG = eeg_checkset(ALLEEG(datadd(index)),'loaddata'); if flag == 1, erp1ind(:,:,index) = mean(TMPEEG.data,3); else erp1ind(:,:,index) = mean(eeg_getdatact(TMPEEG, 'component', [1:size(TMPEEG.icaweights,1)]),3); end; addnames{index} = [ '#' int2str(datadd(index)) ' ' TMPEEG.setname ' (n=' int2str(TMPEEG.trials) ')' ]; clear TMPEEG; end; % optional: subtract % ------------------ colors = {}; % color aspect for curves allcolors = { 'b' 'r' 'g' 'c' 'm' 'y' [0 0.5 0] [0.5 0 0] [0 0 0.5] [0.5 0.5 0] [0 0.5 0.5] [0.5 0 0.5] [0.5 0.5 0.5] }; allcolors = { allcolors{:} allcolors{:} allcolors{:} allcolors{:} allcolors{:} allcolors{:} }; allcolors = { allcolors{:} allcolors{:} allcolors{:} allcolors{:} allcolors{:} allcolors{:} }; if length(datsub) > 0 % dataset to subtract % compute ERPs for sub % -------------------- for index = 1:length(datsub) TMPEEG = eeg_checkset(ALLEEG(datsub(index)),'loaddata'); if flag == 1, erp2ind(:,:,index) = mean(TMPEEG.data,3); else erp2ind(:,:,index) = mean(eeg_getdatact(TMPEEG, 'component', [1:size(TMPEEG.icaweights,1)]),3); end; subnames{index} = [ '#' int2str(datsub(index)) ' ' TMPEEG.setname '(n=' int2str(TMPEEG.trials) ')' ]; clear TMPEEG end; l1 = size(erp1ind,3); l2 = size(erp2ind,3); allcolors1 = allcolors(3:l1+2); allcolors2 = allcolors(l1+3:l1+l2+3); allcolors3 = allcolors(l1+l2+3:end); [erps1, erpstd1, colors1, colstd1, legend1] = preparedata( erp1ind , g.addavg , g.addstd , g.addall , g.mode, 'Add ' , addnames, 'b', allcolors1 ); [erps2, erpstd2, colors2, colstd2, legend2] = preparedata( erp2ind , g.subavg , g.substd , g.suball , g.mode, 'Sub ' , subnames, 'r', allcolors2 ); [erps3, erpstd3, colors3, colstd3, legend3] = preparedata( erp1ind-erp2ind, g.diffavg, g.diffstd, g.diffall, g.mode, 'Diff ', ... { addnames subnames }, 'k', allcolors3 ); % handle special case of std % -------------------------- erptoplot = [ erps1 erps2 erps3 erpstd1 erpstd2 erpstd3 ]; colors = { colors1{:} colors2{:} colors3{:} colstd1{:} colstd2{:} colstd3{:}}; legend = { legend1{:} legend2{:} legend3{:} }; % highlight significant regions % ----------------------------- if ~isempty(g.alpha) pvalues = pttest(erp1ind(g.chans,:,:), erp2ind(g.chans,:,:), 3); regions = p2regions(pvalues, g.alpha, [xmin xmax]*1000); else pvalues= []; end; else [erptoplot, erpstd, colors, colstd, legend] = preparedata( erp1ind, g.addavg, g.addstd, g.addall, g.mode, '', addnames, 'k', allcolors); erptoplot = [ erptoplot erpstd ]; colors = { colors{:} colstd{:} }; % highlight significant regions % ----------------------------- if ~isempty(g.alpha) pvalues = ttest(erp1ind, 0, 3); regions = p2regions(pvalues, g.alpha, [xmin xmax]*1000); else pvalues= []; end; end; % lowpass data % ------------ if ~isempty(g.lowpass) if exist('filtfilt') == 2 erptoplot = eegfilt(erptoplot, srate, 0, g.lowpass); else erptoplot = eegfiltfft(erptoplot, srate, 0, g.lowpass); end; end; if strcmpi(g.geom, 'array') | flag == 0, chanlocs = []; end; if ~isfield(chanlocs, 'theta'), chanlocs = []; end; % select time range % ----------------- if ~isempty(g.tlim) pointrange = round(eeg_lat2point(g.tlim/1000, [1 1], srate, [xmin xmax])); g.tlim = eeg_point2lat(pointrange, [1 1], srate, [xmin xmax]); erptoplot = reshape(erptoplot, size(erptoplot,1), pnts, size(erptoplot,2)/pnts); erptoplot = erptoplot(:,[pointrange(1):pointrange(2)],:); pnts = size(erptoplot,2); erptoplot = reshape(erptoplot, size(erptoplot,1), pnts*size(erptoplot,3)); xmin = g.tlim(1); xmax = g.tlim(2); end; % plot data % --------- set(0, 'CurrentFigure', h); plottopo( erptoplot, 'chanlocs', chanlocs, 'frames', pnts, ... 'limits', [xmin xmax 0 0]*1000, 'title', g.title, 'colors', colors, ... 'chans', g.chans, 'legend', legend, 'regions', regions, 'ylim', g.ylim, g.tplotopt{:}); % outputs % ------- times = linspace(xmin, xmax, pnts); erp1 = mean(erp1ind,3); if length(datsub) > 0 % dataset to subtract erp2 = mean(erp2ind,3); erpsub = erp1-erp2; else erp2 = []; erpsub = []; end; if nargin < 3 & nargout == 1 erp1 = sprintf('pop_comperp( %s, %d, %s);', inputname(1), ... flag, vararg2str({ datadd datsub options{:} }) ); end; return; % convert significance values to alpha % ------------------------------------ function regions = p2regions( pvalues, alpha, limits); for index = 1:size(pvalues,1) signif = diff([1 pvalues(index,:) 1] < alpha); pos = find([signif] > 0); pos = pos/length(pvalues)*(limits(2) - limits(1))+limits(1); neg = find([signif(2:end)] < 0); neg = neg/length(pvalues)*(limits(2) - limits(1))+limits(1); if length(pos) ~= length(neg), signif, pos, neg, error('Region error'); end; regions{index} = [neg;pos]; end; % process data % ------------ function [erptoplot, erpstd, colors, colstd, legend] = preparedata( erpind, plotavg, plotstd, plotall, mode, tag, dataset, coloravg, allcolors); colors = {}; legend = {}; erptoplot = []; erpstd = []; colstd = {}; % plot individual differences % --------------------------- if strcmpi(plotall, 'on') erptoplot = [ erptoplot erpind(:,:) ]; for index=1:size(erpind,3) if iscell(dataset) if strcmpi(tag, 'Diff ') legend = { legend{:} [ dataset{1}{index} ' - ' dataset{2}{index} ] }; else legend = { legend{:} dataset{index} }; end; else legend = { legend{:} [ 'Dataset ' int2str(dataset(index)) ] }; end; colors = { colors{:} allcolors{index} }; end; end; % plot average % ------------ if strcmpi( plotavg, 'on') if strcmpi(mode, 'ave') granderp = mean(erpind,3); legend = { legend{:} [ tag 'Average' ] }; else granderp = sqrt(mean(erpind.^2,3)); legend = { legend{:} [ tag 'RMS' ] }; end; colors = { colors{:} {coloravg;'linewidth';2 }}; erptoplot = [ erptoplot granderp]; end; % plot standard deviation % ----------------------- if strcmpi(plotstd, 'on') if strcmpi(plotavg, 'on') std1 = std(erpind, [], 3); erptoplot = [ erptoplot granderp+std1 ]; erpstd = granderp-std1; legend = { legend{:} [ tag 'Standard dev.' ] }; colors = { colors{:} { coloravg;'linestyle';':' } }; colstd = { { coloravg 'linestyle' ':' } }; else disp('Warning: cannot show standard deviation without showing average'); end; end; % ------------------------------------------------------------------ function [p, t, df] = pttest(d1, d2, dim) %PTTEST Student's paired t-test. % PTTEST(X1, X2) gives the probability that Student's t % calculated on paired data X1 and X2 is higher than % observed, i.e. the "significance" level. This is used % to test whether two paired samples have significantly % different means. % [P, T] = PTTEST(X1, X2) gives this probability P and the % value of Student's t in T. The smaller P is, the more % significant the difference between the means. % E.g. if P = 0.05 or 0.01, it is very likely that the % two sets are sampled from distributions with different % means. % % This works for PAIRED SAMPLES, i.e. when elements of X1 % and X2 correspond one-on-one somehow. % E.g. residuals of two models on the same data. % Ref: Press et al. 1992. Numerical recipes in C. 14.2, Cambridge. if size(d1,dim) ~= size(d2, dim) error('PTTEST: paired samples must have the same number of elements !') end if size(d1,dim) == 1 close; error('Cannot compute paired t-test for a single ERP difference') end; a1 = mean(d1, dim); a2 = mean(d2, dim); v1 = std(d1, [], dim).^2; v2 = std(d2, [], dim).^2; n1 = size(d1,dim); df = n1 - 1; disp(['Computing t-values, df:' int2str(df) ]); d1 = d1-repmat(a1, [ones(1,dim-1) size(d1,3)]); d2 = d2-repmat(a2, [ones(1,dim-1) size(d2,3)]); %cab = (x1 - a1)' * (x2 - a2) / (n1 - 1); cab = sum(d1.*d2,3)/(n1-1); % use abs to avoid numerical errors for very similar data % for which v1+v2-2cab may be close to 0. t = (a1 - a2) ./ sqrt(abs(v1 + v2 - 2 * cab) / n1) ; p = betainc( df ./ (df + t.*t), df/2, 0.5) ; % ------------------------------------------------------------------ function [p, t] = ttest(d1, d2, dim) %TTEST Student's t-test for equal variances. % TTEST(X1, X2) gives the probability that Student's t % calculated on data X1 and X2, sampled from distributions % with the same variance, is higher than observed, i.e. % the "significance" level. This is used to test whether % two sample have significantly different means. % [P, T] = TTEST(X1, X2) gives this probability P and the % value of Student's t in T. The smaller P is, the more % significant the difference between the means. % E.g. if P = 0.05 or 0.01, it is very likely that the % two sets are sampled from distributions with different % means. % % This works if the samples are drawn from distributions with % the SAME VARIANCE. Otherwise, use UTTEST. % %See also: UTTEST, PTTEST. if size(d1,dim) == 1 close; error('Cannot compute t-test for a single ERP') end; a1 = mean(d1, dim); v1 = std(d1, [], dim).^2; n1 = size(d1,dim); if length(d2) == 1 & d2 == 0 a2 = 0; n2 = n1; df = n1 + n2 - 2; pvar = (2*(n1 - 1) * v1) / df ; else a2 = mean(d2, dim); v2 = std(d2, [], dim).^2; n2 = size(d2,dim); df = n1 + n2 - 2; pvar = ((n1 - 1) * v1 + (n2 - 1) * v2) / df ; end; disp(['Computing t-values, df:' int2str(df) ]); t = (a1 - a2) ./ sqrt( pvar * (1/n1 + 1/n2)) ; p = betainc( df ./ (df + t.*t), df/2, 0.5) ;
github
lcnbeapp/beapp-master
pop_jointprob.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_jointprob.m
11,856
utf_8
2e52771f3ef70d7a913563e5c3d2a0d9
% pop_jointprob() - reject artifacts in an EEG dataset using joint % probability of the recorded electrode or component % activities observed at each time point. e.g., Observing % large absoluate values at most electrodes or components % is improbable and may well mark the presence of artifact. % Usage: % >> pop_jointprob( INEEG, typerej) % pop-up interative window mode % >> [OUTEEG, locthresh, globthresh, nrej] = ... % = pop_jointprob( INEEG, typerej, elec_comp, ... % locthresh, globthresh, superpose, reject, vistype); % % Graphic interface: % "Electrode|Component" - [edit box] electrodes or components indices to take % into consideration for rejection. Same as the 'elec_comp' % parameter in the command line call (see below). % "Single-channel limit|Single-component limit" - [edit box] activity % probability limit(s) (in std. dev.) Sets the 'locthresh' % command line parameter. If more than one, defined individual % electrode|channel limits. If fewer values than the number % of electrodes|components specified above, the last input % value is used for all remaining electrodes|components. % "All-channel limit|All-component limit" - [edit box] activity probability % limit(s) (in std. dev.) for all channels (grouped). % Sets the 'globthresh' command line parameter. % "visualization type" - [popup menu] can be either 'REJECTRIALS'|'EEGPLOT'. % This correspond to the command line input option 'vistype' % "Display with previous rejection(s)" - [checkbox] This checkbox set the % command line input option 'superpose'. % "Reject marked trial(s)" - [checkbox] This checkbox set the command % line input option 'reject'. % Inputs: % INEEG - input dataset % typerej - [1|0] data to reject on (0 = component activations; % 1 = electrode data). {Default: 1 = electrode data}. % elec_comp - [n1 n2 ...] electrode|component number(s) to take into % consideration for rejection % locthresh - activity probability limit(s) (in std. dev.) See "Single- % channel limit(s)" above. % globthresh - global limit(s) (all activities grouped) (in std. dev.) % superpose - [0|1] 0 = Do not superpose rejection marks on previously % marks stored in the dataset: 1 = Show both current and % previous marks using different colors. {Default: 0}. % reject - 0 = do not reject marked trials (but store the marks: % 1 = reject marked trials {Default: 1}. % vistype - Visualization type. [0] calls rejstatepoch() and [1] calls % eegplot() default is [0].When added to the command line % call it will not display the plots if the option 'plotflag' % is not set. % topcommand - [] Deprecated argument , keep to ensure backward compatibility % plotflag - [1,0] [1]Turns plots 'on' from command line, [0] off. % (Note for developers: When called from command line % it will make 'calldisp = plotflag') {Default: 0} % % Outputs: % OUTEEG - output dataset with updated joint probability array % locthresh - electrodes probability of activity thresholds in terms % of standard-dev. % globthresh - global threshold (where all electrode activity are % regrouped). % nrej - number of rejected sweeps % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: jointprob(), rejstatepoch(), eegplot(), eeglab(), pop_rejepoch() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-07-02 added srate argument to eegplot call -ad % 03-08-02 add eeglab options -ad function [EEG, locthresh, globthresh, nrej, com] = pop_jointprob( EEG, icacomp, elecrange, ... locthresh, globthresh, superpose, reject, vistype, topcommand,plotflag); nrej = []; com = ''; if nargin < 1 help pop_jointprob; return; end; if nargin < 2 icacomp = 1; end; if icacomp == 0 if isempty( EEG.icasphere ) ButtonName=questdlg( 'Do you want to run ICA now ?', ... 'Confirmation', 'NO', 'YES', 'YES'); switch ButtonName, case 'NO', disp('Operation cancelled'); return; case 'YES', [ EEG com ] = pop_runica(EEG); end % switch end; end; if exist('reject') ~= 1 reject = 1; end; if nargin < 3 % which set to save % ----------------- promptstr = { [ fastif(icacomp, 'Electrode', 'Component') ' (indices; Ex: 2 6:8 10):' ], ... [ fastif(icacomp, 'Single-channel', 'Single-component') ' limit(s) (std. dev(s).: Ex: 2 2 2.5):'], ... [ fastif(icacomp, 'All-channel', 'All-component') ' limit(s) (std. dev(s).: Ex: 2 2.1 2):'], ... 'Visualization type',... 'Display previous rejection marks', ... 'Reject marked trial(s)'}; inistr = { fastif(icacomp, ['1:' int2str(EEG.nbchan)], ['1:' int2str(size(EEG.icaweights,1))])... fastif(icacomp, '3', '5'), ... fastif(icacomp, '3', '5'), ... '',... '1', ... '0'}; vismodelist= {'REJECTTRIALS','EEGPLOT'}; g1 = [1 0.1 0.75]; g2 = [1 0.26 0.9]; g3 = [1 0.22 0.85]; geometry = {g1 g1 g1 g2 [1] g3 g3}; uilist = {... { 'Style', 'text', 'string', promptstr{1}} {} { 'Style','edit' , 'string' ,inistr{1} 'tag' 'cpnum'}... { 'Style', 'text', 'string', promptstr{2}} {} { 'Style','edit' , 'string' ,inistr{2} 'tag' 'singlelimit'}... { 'Style', 'text', 'string', promptstr{3}} {} { 'Style','edit' , 'string' ,inistr{3} 'tag' 'alllimit'}... { 'Style', 'text', 'string', promptstr{4}} {} { 'Style','popupmenu' , 'string' , vismodelist 'tag' 'specmethod' }... {}... { 'Style', 'text', 'string', promptstr{5}} {} { 'Style','checkbox' ,'string' , ' ' 'value' str2double(inistr{5}) 'tag','rejmarks' }... { 'Style', 'text', 'string', promptstr{6}} {} { 'Style','checkbox' ,'string' ,' ' 'value' str2double(inistr{6}) 'tag' 'rejtrials'} ... }; figname = fastif( ~icacomp, 'Reject. improbable comp. -- pop_jointprob()', 'Reject improbable data -- pop_jointprob()'); result = inputgui( geometry,uilist,'pophelp(''pop_jointprob'');', figname); size_result = size( result ); if size_result(1) == 0, locthresh = []; globthresh = []; return; end; elecrange = result{1}; locthresh = result{2}; globthresh = result{3}; switch result{4}, case 1, vistype=0; otherwise, vistype=1; end; superpose = result{5}; reject = result{6}; end; if ~exist('vistype' ,'var'), vistype = 0; end; if ~exist('reject' ,'var'), reject = 0; end; if ~exist('superpose','var'), superpose = 1; end; if isstr(elecrange) % convert arguments if they are in text format calldisp = 1; elecrange = eval( [ '[' elecrange ']' ] ); locthresh = eval( [ '[' locthresh ']' ] ); globthresh = eval( [ '[' globthresh ']' ] ); else calldisp = 0; end; if exist('plotflag','var') && ismember(plotflag,[1,0]) calldisp = plotflag; else plotflag = 0; end if isempty(elecrange) error('No electrode selectionned'); end; % compute the joint probability % ----------------------------- if icacomp == 1 fprintf('Computing joint probability for channels...\n'); tmpdata = eeg_getdatact(EEG); if isempty(EEG.stats.jpE) [ EEG.stats.jpE rejE ] = jointprob( tmpdata, locthresh, EEG.stats.jpE, 1); end; [ tmp rejEtmp ] = jointprob( tmpdata(elecrange,:,:), locthresh, EEG.stats.jpE(elecrange,:), 1); rejE = zeros(EEG.nbchan, size(rejEtmp,2)); rejE(elecrange,:) = rejEtmp; fprintf('Computing all-channel probability...\n'); tmpdata2 = permute(tmpdata, [3 1 2]); tmpdata2 = reshape(tmpdata2, size(tmpdata2,1), size(tmpdata2,2)*size(tmpdata2,3)); [ EEG.stats.jp rej ] = jointprob( tmpdata2, globthresh, EEG.stats.jp, 1); clear tmpdata2; else tmpdata = eeg_getica(EEG); fprintf('Computing joint probability for components...\n'); if isempty(EEG.stats.icajpE) [ EEG.stats.icajpE rejE ] = jointprob( tmpdata, locthresh, EEG.stats.icajpE, 1); end; [ tmp rejEtmp ] = jointprob( tmpdata(elecrange,:), locthresh, EEG.stats.icajpE(elecrange,:), 1); rejE = zeros(size(tmpdata,1), size(rejEtmp,2)); rejE(elecrange,:) = rejEtmp; fprintf('Computing global joint probability...\n'); tmpdata2 = permute(tmpdata, [3 1 2]); tmpdata2 = reshape(tmpdata2, size(tmpdata2,1), size(tmpdata2,2)*size(tmpdata2,3)); [ EEG.stats.icajp rej] = jointprob( tmpdata2, globthresh, EEG.stats.icajp, 1); clear tmpdata2; end; rej = rej' | max(rejE, [], 1); fprintf('%d/%d trials marked for rejection\n', sum(rej), EEG.trials); if calldisp if vistype == 1 % EEGPLOT ------------------------- if icacomp == 1 macrorej = 'EEG.reject.rejjp'; macrorejE = 'EEG.reject.rejjpE'; else macrorej = 'EEG.reject.icarejjp'; macrorejE = 'EEG.reject.icarejjpE'; end; colrej = EEG.reject.rejjpcol; eeg_rejmacro; % script macro for generating command and old rejection arrays if icacomp == 1 eegplot( tmpdata(elecrange,:,:), 'srate', ... EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}); else eegplot( tmpdata(elecrange,:,:), 'srate', ... EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}); end; else % REJECTRIALS ------------------------- if icacomp == 1 [ rej, rejE, n, locthresh, globthresh] = ... rejstatepoch( tmpdata(elecrange,:,:), EEG.stats.jpE(elecrange,:), 'global', 'on', 'rejglob', EEG.stats.jp, ... 'threshold', locthresh, 'thresholdg', globthresh, 'normalize', 'off' ); else [ rej, rejE, n, locthresh, globthresh] = ... rejstatepoch( tmpdata(elecrange,:,:), EEG.stats.icajpE(elecrange,:), 'global', 'on', 'rejglob', EEG.stats.icajp, ... 'threshold', locthresh, 'thresholdg', globthresh, 'normalize', 'off' ); end; nrej = n; end; else % compute rejection locally rejtmp = max(rejE(elecrange,:),[],1); rej = rejtmp | rej; nrej = sum(rej); fprintf('%d trials marked for rejection\n', nrej); end; if ~isempty(rej) if icacomp == 1 EEG.reject.rejjp = rej; EEG.reject.rejjpE = rejE; else EEG.reject.icarejjp = rej; EEG.reject.icarejjpE = rejE; end; if reject EEG = pop_rejepoch(EEG, rej, 0); end; end; nrej = sum(rej); com = [ com sprintf('%s = pop_jointprob(%s,%s);', inputname(1), ... inputname(1), vararg2str({icacomp,elecrange,locthresh,globthresh,superpose,reject, vistype, [],plotflag})) ]; if nargin < 3 & nargout == 2 locthresh = com; end; return;
github
lcnbeapp/beapp-master
eeg_lat2point.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/eeg_lat2point.m
4,019
utf_8
fc612a716877495d005080fab259effb
% eeg_lat2point() - convert latencies in time units relative to the % time locking event of an eeglab() data epoch to % latencies in data points (assuming concatenated epochs). % Usage: % >> [newlat] = eeg_lat2point( lat_array, epoch_array,... % srate, timelimits, timeunit); % >> [newlat] = eeg_lat2point( lat_array, epoch_array,... % srate, timelimits, '','outrange',1); % Inputs: % lat_array - latency array in 'timeunit' units (see below) % epoch_array - epoch number for each latency % srate - data sampling rate in Hz % timelimits - [min max] epoch timelimits in 'timeunit' units (see below) % timeunit - time unit relative to seconds. Default is 1 = seconds. % % Optional inputs: % outrange - [1/0] Replace the points out of the range with the value of % the maximun point in the valid range or raise an error. % Default [1] : Replace point. % % Outputs: % newlat - converted latency values in points assuming concatenated % data epochs (see eeglab() event structure) % flag - 1 if any point out of range was replaced. % % Author: Arnaud Delorme, CNL / Salk Institute, 2 Mai 2002 % % See also: eeg_point2lat(), eeglab() % Copyright (C) 2 Mai 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [newlat,flag] = eeg_lat2point( lat_array, epoch_array, srate, timewin, timeunit, varargin); % ------------------------------------------------------------------------- try options = varargin; if ~isempty( varargin ), for i = 1:2:numel(options) g.(options{i}) = options{i+1}; end else g= []; end; catch error('std_checkdatasession() error: calling convention {''key'', value, ... } error'); end; try, g.outrange; catch, g.outrange = 1; end; % flag = 0; % ------------------------------------------------------------------------- if nargin <4 help eeg_lat2point; return; end; if nargin <5 | isempty(timeunit) timeunit = 1; end; if length(lat_array) ~= length(epoch_array) if length(epoch_array)~= 1 disp('eeg_lat2point: latency and epochs must have the same length'); return; else epoch_array = ones(1,length(lat_array))*epoch_array; end; end; if length(timewin) ~= 2 disp('eeg_lat2point: timelimits must have length 2'); return; end; if iscell(epoch_array) epoch_array = [ epoch_array{:} ]; end; if iscell(lat_array) lat_array = [ lat_array{:} ]; end timewin = timewin*timeunit; pnts = (timewin(2)-timewin(1))*srate+1; newlat = (lat_array*timeunit-timewin(1))*srate+1 + (epoch_array-1)*pnts; % Detecting points out of range (RMC) % Note: This is neccesary since the double precision multiplication could lead to the % shifting in one sample out of the valid range if and(~isempty(newlat),~isempty(epoch_array)) && max(newlat(:)) > max((epoch_array)*pnts) if g.outrange == 1 IndxOut = find(newlat(:) > max((epoch_array)*pnts)); newlat(IndxOut) = max((epoch_array)*pnts); flag = 1; warning('eeg_lat2point(): Points out of range detected. Points replaced with maximum value'); elseif g.outrange == 0 error('Error in eeg_lat2point(): Points out of range detected'); end end
github
lcnbeapp/beapp-master
eeg_addnewevents.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/eeg_addnewevents.m
7,648
utf_8
ffc9194217c3e26d7b32be5361c7163b
% eeg_addnewevents() Add new events to EEG structure. Both EEG.event and % EEG.urevent are updated. % % Usage: % >> EEG = eeg_addnewevents(EEG, latencies, types, fieldNames, fieldValues); % % Inputs: % EEG - input dataset % latencies - cell containing numerical arrays for latencies of new % events, each array corresponds to a different event type. % type - cell array containing name of event types. % % Optional Inputs % fieldNames - cell array containing names of fields to be added to event structure. % fieldValues - A cell containing arrays for field values corresponding to fieldNames. % Number of values for each field should be equal to the total number of % latencies (new events) added to dataset. % Outputs: % EEG - EEG dataset with updated event and urevent fields % % Example: % EEG = eeg_addnewevents(EEG, {[100 200] [300 400 500]}, {'type1' 'type2'}, {'field1' 'field2'}, {[1 2 3 4 5] [6 7 8 9]}); % % Author: Nima Bigdely Shamlo, SCCN/INC/UCSD, 2008 function EEG = eeg_addnewevents(EEG, eventLatencyArrays, types, fieldNames, fieldValues); if ~isfield(EEG, 'event') EEG.event = []; EEG.urevent = []; EEG.event(1).type = 'dummy'; EEG.event(1).latency = 1; EEG.event(1).duration = 0; EEG.event(1).urevent = 1; EEG.urevent(1).type = 'dummy'; EEG.urevent(1).latency = 1; EEG.urevent(1).duration = 0; end; % add duration field if it does not exist if length(EEG.event)>0 && ~isfield(EEG.event(1),'duration') EEG.event(1).duration = 0; EEG.urevent(1).duration = 0; end; if nargin<4 fieldNames = []; fieldValues = []; end; newEventLatency = []; for i=1:length(eventLatencyArrays) newEventLatency = [newEventLatency eventLatencyArrays{i}]; end; newEventType = []; for i=1:length(eventLatencyArrays{1}) newEventType{i} = types{1}; end; for j=2:length(eventLatencyArrays) startIndex = length(newEventType); for i=1:length(eventLatencyArrays{j}) newEventType{startIndex+i} = types{j}; end; end; % mix new and old events, sort them by latency and put them back in EEG originalEventLatency = []; originalEventType = []; originalFieldNames = []; for i=1:length(EEG.event) originalEventLatency(i) = EEG.event(i).latency; originalEventType{i} = EEG.event(i).type; originalEventFields(i) = EEG.event(i); end; % make sure that originalEventFields has all the new field names if ~isempty(EEG.event) originalFieldNames = fields(originalEventFields); for f= 1:length(fieldNames) if ~isfield(originalEventFields, fieldNames{f}) originalEventFields(length(originalEventFields)).(fieldNames{f}) = NaN; end; end; end; % make sure that newEventFields has all the original field names for i=1:length(originalFieldNames) newEventFields(length(newEventLatency)).(originalFieldNames{i}) = NaN; end; for i=1:length(newEventLatency) newEventFields(i).latency = newEventLatency(i); newEventFields(i).type = newEventType{i}; newEventFields(i).duration = 0; for f= 1:length(fieldNames) newEventFields(i).(fieldNames{f}) = fieldValues{f}(i); end; end; if ~isempty(EEG.event) %newEventFields = struct('latency', num2cell(newEventLatency), 'type', newEventType); combinedFields = [originalEventFields newEventFields]; combinedLatencies = [originalEventLatency newEventLatency]; combinedType = [originalEventType newEventType]; else combinedFields = newEventFields; combinedLatencies = newEventLatency; combinedType = newEventType; end [sortedEventLatency order] = sort(combinedLatencies,'ascend'); sortedEventType = combinedType(order); combinedFields = combinedFields(order); % put events in eeg %EEG.urevent = []; %EEG.event = []; EEG = rmfield(EEG,'event'); for i=1:length(sortedEventLatency) % EEG.urevent(i).latency = sortedEventLatency(i); % EEG.urevent(i).type = sortedEventType{i}; % combinedFields(order(i)).urevent = i; EEG.event(i) = combinedFields(i); % EEG.event(i).urevent = i; end; %% adding new urevents originalUreventNumber = 1:length(EEG.urevent); originalUreventLatency = zeros(1, length(EEG.urevent)); originalUreventFields= cell(1, length(EEG.urevent)); for i=1:length(EEG.urevent) originalUreventLatency(i) = EEG.urevent(i).latency; originalUreventFields{i} = EEG.urevent(i); end; newUreventLatency = []; newUreventType = []; for i=1:length(EEG.event) if ~isfield(EEG.event,'urevent') || length(EEG.event(i).urevent) == 0 || isnan(EEG.event(i).urevent) % newUreventLatency = [newUreventLatency newEventUrEventLatency(EEG, combinedFields, i)]; % use eeg_urlatency to calculate the original latency based on % EEG.event duartions newUreventLatency = [newUreventLatency eeg_urlatency(EEG.event, EEG.event(i).latency)]; else newUreventLatency = [newUreventLatency EEG.urevent(EEG.event(i).urevent).latency]; end; newUreventFields{i} = EEG.event(i); newUreventEventNumber(i) = i; end; combinedEventNumber = newUreventEventNumber;%[NaN(1,length(EEG.urevent)) newUreventEventNumber]; combinedUrEventLatencies = newUreventLatency;%[originalUreventLatency newUreventLatency]; [sortedUrEventLatency order] = sort(combinedUrEventLatencies,'ascend'); % make urvent stucture ready EEG.urevent = []; EEG.urevent= newUreventFields{order(1)}; for i=1:length(order) %if ~isnan(newUreventEventNumber(i)) EEG.urevent(i) = newUreventFields{order(i)}; EEG.urevent(i).latency = combinedUrEventLatencies(order(i)); EEG.event(newUreventEventNumber(i)).urevent = i; %end; end; if isfield(EEG.urevent,'urevent') EEG.urevent = rmfield(EEG.urevent,'urevent'); % remove urevent field end; % turn empty event durations into 0 for i=1:length(EEG.event) if isempty(EEG.event(i).duration) EEG.event(i).duration = 0; end; end; for i=1:length(EEG.urevent) if isempty(EEG.urevent(i).duration) EEG.urevent(i).duration = 0; end; end; % % function latency = newEventUrEventLatency(EEG, combinedFields, i) % % %% looks for an event with urvent before the new event % urlatencyBefore = []; % currentEventNumber = i; % % while isempty(urlatencyBefore) && currentEventNumber > 1 % currentEventNumber = currentEventNumber - 1; % if ~(~isfield(combinedFields(currentEventNumber),'urevent') || isempty(combinedFields(currentEventNumber).urevent) || isnan(combinedFields(currentEventNumber).urevent)) % urlatencyBefore = EEG.urevent(combinedFields(currentEventNumber).urevent).latency; % end; % end % % %% if no event with urevent is found before, look for an event with urvent after the new event % if isempty(urlatencyBefore) % urlatencyAfter = []; % currentEventNumber = i; % % while isempty(urlatencyAfter) && currentEventNumber < length(combinedFields) % currentEventNumber = currentEventNumber + 1; % if ~(~isfield(combinedFields(currentEventNumber),'urevent') || isempty(combinedFields(currentEventNumber).urevent) || isnan(combinedFields(currentEventNumber).urevent)) % urlatencyAfter = EEG.urevent(combinedFields(currentEventNumber).urevent).latency; % end; % end % end; % %% % if ~isempty(urlatencyBefore) % latency = urlatencyBefore + combinedFields(i).latency - combinedFields(currentEventNumber).latency; % elseif ~isempty(urlatencyAfter) % latency = urlatencyAfter + combinedFields(currentEventNumber).latency - combinedFields(i).latency; % else % latency = []; % end;
github
lcnbeapp/beapp-master
fmins.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/octavefunc/optim/fmins.m
3,181
utf_8
775abc7aa3b9020a0c2080db64070155
% Copyright (C) 2003 Andy Adler % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % -*- texinfo -*- % @deftypefn {Function File} {[@var{x}] =} fmins(@var{f},@var{X0},@var{options},@var{grad},@var{P1},@var{P2}, ...) % % Find the minimum of a funtion of several variables. % By default the method used is the Nelder&Mead Simplex algorithm % % Example usage: % fmins(inline('(x(1)-5).^2+(x(2)-8).^4'),[0;0]) % % @strong{Inputs} % @table @var % @item f % A string containing the name of the function to minimize % @item X0 % A vector of initial parameters fo the function @var{f}. % @item options % Vector with control parameters (not all parameters are used) % @verbatim % options(1) - Show progress (if 1, default is 0, no progress) % options(2) - Relative size of simplex (default 1e-3) % options(6) - Optimization algorithm % if options(6)==0 - Nelder & Mead simplex (default) % if options(6)==1 - Multidirectional search Method % if options(6)==2 - Alternating Directions search % options(5) % if options(6)==0 && options(5)==0 - regular simplex % if options(6)==0 && options(5)==1 - right-angled simplex % Comment: the default is set to "right-angled simplex". % this works better for me on a broad range of problems, % although the default in nmsmax is "regular simplex" % options(10) - Maximum number of function evaluations % @end verbatim % @item grad % Unused (For compatibility with Matlab) % @item P1,P2, ... % Optional parameters for function @var{f} % % @end table % @end deftypefn function ret=fmins(funfun, X0, options, grad, varargin) if ismatlab if license('test','optim_toolbox') p = fileparts(which('fmins')); error( [ 'Octave functions should not run on Matlab' 10 'remove path to ' p ]); end; end; stopit = [1e-3, inf, inf, 1, 0, -1]; minfun = 'nmsmax'; if nargin < 3; options=[]; end if length(options)>=1; stopit(5)= options(1); end if length(options)>=2; stopit(1)= options(2); end if length(options)>=5; if options(6)==0; minfun= 'nmsmax'; if options(5)==0; stopit(4)= 0; elseif options(5)==1; stopit(4)= 1; else error('options(5): no associated simple strategy'); end elseif options(6)==1; minfun= 'mdsmax'; elseif options(6)==2; minfun= 'adsmax'; else error('options(6) does not correspond to known algorithm'); end end if length(options)>=10; stopit(2)= options(10); end ret = feval(minfun, funfun, X0, stopit, [], varargin{:});
github
lcnbeapp/beapp-master
fminsearch.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/octavefunc/optim/fminsearch.m
2,386
utf_8
24a86640354f4abf5e4d1e15a97b9a27
% Copyright (C) 2006 Sylvain Pelissier <[email protected]> % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % -*- texinfo -*- % @deftypefn {Function File} {[@var{x}] =} fminsearch(@var{f},@var{X0},@var{options},@var{grad},@var{P1},@var{P2}, ...) % % Find the minimum of a funtion of several variables. % By default the method used is the Nelder&Mead Simplex algorithm % @seealso{fmin,fmins,nmsmax} % @end deftypefn function varargout = fminsearch(funfun, X0, varargin) if ismatlab p1 = fileparts(which('fminsearch')); rmpath(p1); p2 = fileparts(which('fminsearch')); if ~isequal(p1, p2) disp( [ 'Some Octave functions should not run on Matlab' 10 'removing path to Octave fminsearch and using Matlab fminsearch' ]); switch nargout case 1, varargout{1} = fminsearch(funfun, X0, varargin{:}); case 2, [varargout{1} varargout{2}] = fminsearch(funfun, X0, varargin{:}); case 3, [varargout{1} varargout{2} varargout{3}] = fminsearch(funfun, X0, varargin{:}); case 4, [varargout{1} varargout{2} varargout{3} varargout{4}]= fminsearch(funfun, X0, varargin{:}); end; else disp( [ 'Octave functions should not run on Matlab' 10 'remove path ' p1 ]); end; return; end; if (nargin == 0); usage('[x fval] = fminsearch(funfun, X0, options, grad, varargin)'); end if length(varargin) > 0, options = varargin{1}; varargin(1) = []; end; if length(varargin) > 0, grad = varargin{1}; varargin(1) = []; end; if (nargin < 3); options=[]; end if (nargin < 4); grad=[]; end if (nargin < 5); varargin={}; end varargout{1} = fmins(funfun, X0, options, grad, varargin{:}); varargout{2} = feval(funfun, x, varargin{:});
github
lcnbeapp/beapp-master
pwelch.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/octavefunc/signal/pwelch.m
37,809
utf_8
360a005a779e4d7ad6b92dc49ec8c04c
% Copyright (C) 2006 Peter V. Lanspeary % % This program is free software; you can redistribute it and/or % modify it under the terms of the GNU General Public License % as published by the Free Software Foundation; either version 2, % or (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % % USAGE: % [spectra,freq] = pwelch(x,window,overlap,Nfft,Fs, % range,plot_type,detrend,sloppy) % Estimate power spectral density of data "x" by the Welch (1967) % periodogram/FFT method. All arguments except "x" are optional. % The data is divided into segments. If "window" is a vector, each % segment has the same length as "window" and is multiplied by "window" % before (optional) zero-padding and calculation of its periodogram. If % "window" is a scalar, each segment has a length of "window" and a % Hamming window is used. % The spectral density is the mean of the periodograms, scaled so that % area under the spectrum is the same as the mean square of the % data. This equivalence is supposed to be exact, but in practice there % is a mismatch of up to 0.5% when comparing area under a periodogram % with the mean square of the data. % % [spectra,freq] = pwelch(x,y,window,overlap,Nfft,Fs, % range,plot_type,detrend,sloppy,results) % Two-channel spectrum analyser. Estimate power spectral density, cross- % spectral density, transfer function and/or coherence functions of time- % series input data "x" and output data "y" by the Welch (1967) % periodogram/FFT method. % pwelch treats the second argument as "y" if there is a control-string % argument "cross", "trans", "coher" or "ypower"; "power" does not force % the 2nd argument to be treated as "y". All other arguments are % optional. All spectra are returned in matrix "spectra". % % [spectra,Pxx_ci,freq] = pwelch(x,window,overlap,Nfft,Fs,conf, % range,plot_type,detrend,sloppy) % [spectra,Pxx_ci,freq] = pwelch(x,y,window,overlap,Nfft,Fs,conf, % range,plot_type,detrend,sloppy,results) % Estimates confidence intervals for the spectral density. % See Hint (7) below for compatibility options. Confidence level "conf" % is the 6th or 7th numeric argument. If "results" control-string % arguments are used, one of them must be "power" when the "conf" % argument is present; pwelch can estimate confidence intervals only for % the power spectrum of the "x" data. It does not know how to estimate % confidence intervals of the cross-power spectrum, transfer function or % coherence; if you can suggest a good method, please send a bug report. % % ARGUMENTS % All but the first argument are optional and may be empty, except that % the "results" argument may require the second argument to be "y". % % x % [non-empty vector] system-input time-series data % y % [non-empty vector] system-output time-series data % % window % [real vector] of window-function values between 0 and 1; the % % data segment has the same length as the window. % % Default window shape is Hamming. % % [integer scalar] length of each data segment. The default % % value is window=sqrt(length(x)) rounded up to the % % nearest integer power of 2; see 'sloppy' argument. % % overlap % [real scalar] segment overlap expressed as a multiple of % % window or segment length. 0 <= overlap < 1, % % The default is overlap=0.5 . % % Nfft % [integer scalar] Length of FFT. The default is the length % % of the "window" vector or has the same value as the % % scalar "window" argument. If Nfft is larger than the % % segment length, "seg_len", the data segment is padded % % with "Nfft-seg_len" zeros. The default is no padding. % % Nfft values smaller than the length of the data % % segment (or window) are ignored silently. % % Fs % [real scalar] sampling frequency (Hertz); default=1.0 % % conf % [real scalar] confidence level between 0 and 1. Confidence % % intervals of the spectral density are estimated from % % scatter in the periodograms and are returned as Pxx_ci. % % Pxx_ci(:,1) is the lower bound of the confidence % % interval and Pxx_ci(:,2) is the upper bound. If there % % are three return values, or conf is an empty matrix, % % confidence intervals are calculated for conf=0.95 . % % If conf is zero or is not given, confidence intervals % % are not calculated. Confidence intervals can be % % obtained only for the power spectral density of x; % % nothing else. % % CONTROL-STRING ARGUMENTS -- each of these arguments is a character string. % Control-string arguments must be after the other arguments but can be in % any order. % % range % 'half', 'onesided' : frequency range of the spectrum is % % zero up to but not including Fs/2. Power from % % negative frequencies is added to the positive side of % % the spectrum, but not at zero or Nyquist (Fs/2) % % frequencies. This keeps power equal in time and % % spectral domains. See reference [2]. % % 'whole', 'twosided' : frequency range of the spectrum is % % -Fs/2 to Fs/2, with negative frequencies % % stored in "wrap around" order after the positive % % frequencies; e.g. frequencies for a 10-point 'twosided' % % spectrum are 0 0.1 0.2 0.3 0.4 0.5 -0.4 -0.3 -0.2 -0.1 % % 'shift', 'centerdc' : same as 'whole' but with the first half % % of the spectrum swapped with second half to put the % % zero-frequency value in the middle. (See "help % % fftshift". % % If data (x and y) are real, the default range is 'half', % % otherwise default range is 'whole'. % % plot_type % 'plot', 'semilogx', 'semilogy', 'loglog', 'squared' or 'db': % % specifies the type of plot. The default is 'plot', which % % means linear-linear axes. 'squared' is the same as 'plot'. % % 'dB' plots "10*log10(psd)". This argument is ignored and a % % spectrum is not plotted if the caller requires a returned % % value. % % detrend % 'no-strip', 'none' -- do NOT remove mean value from the data % % 'short', 'mean' -- remove the mean value of each segment from % % each segment of the data. % % 'linear', -- remove linear trend from each segment of % % the data. % % 'long-mean' -- remove the mean value from the data before % % splitting it into segments. This is the default. % % sloppy % 'sloppy': FFT length is rounded up to the nearest integer % % power of 2 by zero padding. FFT length is adjusted % % after addition of padding by explicit Nfft argument. % % The default is to use exactly the FFT and window/ % % segment lengths specified in argument list. % % results % specifies what results to return (in the order specified % % and as many as desired). % % 'power' calculate power spectral density of "x" % % 'cross' calculate cross spectral density of "x" and "y" % % 'trans' calculate transfer function of a system with % % input "x" and output "y" % % 'coher' calculate coherence function of "x" and "y" % % 'ypower' calculate power spectral density of "y" % % The default is 'power', with argument "y" omitted. % % RETURNED VALUES: % If return values are not required by the caller, the results are % plotted and nothing is returned. % % spectra % [real-or-complex matrix] columns of the matrix contain results % % in the same order as specified by "results" arguments. % % Each column contains one of the result vectors. % % Pxx_ci % [real matrix] estimate of confidence interval for power % % spectral density of x. First column is the lower % % bound. Second column is the upper bound. % % freq % [real column vector] frequency values % % HINTS % 1) EMPTY ARGS: % if you don't want to use an optional argument you can leave it empty % by writing its value as []. % 2) FOR BEGINNERS: % The profusion of arguments may make pwelch difficult to use, and an % unskilled user can easily produce a meaningless result or can easily % mis-interpret the result. With real data "x" and sampling frequency % "Fs", the easiest and best way for a beginner to use pwelch is % probably "pwelch(x,[],[],[],Fs)". Use the "window" argument to % control the length of the spectrum vector. For real data and integer % scalar M, "pwelch(x,2*M,[],[],Fs)" gives an M+1 point spectrum. % Run "demo pwelch" (octave only). % 3) WINDOWING FUNCTIONS: % Without a window function, sharp spectral peaks can have strong % sidelobes because the FFT of a data in a segment is in effect convolved % with a rectangular window. A window function which tapers off % (gradually) at the ends produces much weaker sidelobes in the FFT. % Hann (hanning), hamming, bartlett, blackman, flattopwin etc are % available as separate Matlab/sigproc or Octave functions. The sidelobes % of the Hann window have a roll-off rate of 60dB/decade of frequency. % The first sidelobe of the Hamming window is suppressed and is about 12dB % lower than the first Hann sidelobe, but the roll-off rate is only % 20dB/decade. You can inspect the FFT of a Hann window by plotting % "abs(fft(postpad(hanning(256),4096,0)))". % The default window is Hamming. % 4) ZERO PADDING: % Zero-padding reduces the frequency step in the % spectrum, and produces an artificially smoothed spectrum. For example, % "Nfft=2*length(window)" gives twice as many frequency values, but % adjacent PSD (power spectral density) values are not independent; % adjacent PSD values are independent if "Nfft=length(window)", which is % the default value of Nfft. % 5) REMOVING MEAN FROM SIGNAL: % If the mean is not removed from the signal there is a large spectral % peak at zero frequency and the sidelobes of this peak are likely to % swamp the rest of the spectrum. For this reason, the default behaviour % is to remove the mean. However, the matlab pwelch does not do this. % 6) WARNING ON CONFIDENCE INTERVALS % Confidence intervals are obtained by measuring the sample variance of % the periodograms and assuming that the periodograms have a Gaussian % probability distribution. This assumption is not accurate. If, for % example, the data (x) is Gaussian, the periodogram has a Rayleigh % distribution. However, the confidence intervals may still be useful. % % 7) COMPATIBILITY WITH Matlab R11, R12, etc % When used without the second data (y) argument, arguments are compatible % with the pwelch of Matlab R12, R13, R14, 2006a and 2006b except that % 1) overlap is expressed as a multiple of window length --- % effect of overlap scales with window length % 2) default values of length(window), Nfft and Fs are more sensible, and % 3) Goertzel algorithm is not available so Nfft cannot be an array of % frequencies as in Matlab 2006b. % Pwelch has four persistent Matlab-compatibility levels. Calling pwelch % with an empty first argument sets the order of arguments and defaults % specified above in the USAGE and ARGUMENTS section of this documentation. % prev_compat=pwelch([]); % [Pxx,f]=pwelch(x,window,overlap,Nfft,Fs,conf,...); % Calling pwelch with a single string argument (as described below) gives % compatibility with Matlab R11 or R12, or the R14 spectrum.welch % defaults. The returned value is the PREVIOUS compatibility string. % % Matlab R11: For compatibility with the Matlab R11 pwelch: % prev_compat=pwelch('R11-'); % [Pxx,f]=pwelch(x,Nfft,Fs,window,overlap,conf,range,units); % % units of overlap are "number of samples" % % defaults: Nfft=min(length(x),256), Fs=2*pi, length(window)=Nfft, % % window=Hanning, do not detrend, % % N.B. "Sloppy" is not available. % % Matlab R12: For compatibility with Matlab R12 to 2006a pwelch: % prev_compat=pwelch('R12+'); % [Pxx,f]=pwelch(x,window,overlap,nfft,Fs,...); % % units of overlap are "number of samples" % % defaults: length(window)==length(x)/8, window=Hamming, % % Nfft=max(256,NextPow2), Fs=2*pi, do not detrend % % NextPow2 is the next power of 2 greater than or equal to the % % window length. "Sloppy", "conf" are not available. Default % % window length gives very poor amplitude resolution. % % To adopt defaults of the Matlab R14 "spectrum.welch" spectrum object % associated "psd" method. % prev_compat=pwelch('psd'); % [Pxx,f] = pwelch(x,window,overlap,Nfft,Fs,conf,...); % % overlap is expressed as a percentage of window length, % % defaults: length(window)==64, Nfft=max(256,NextPow2), Fs=2*pi % % do not detrend % % NextPow2 is the next power of 2 greater than or equal to the % % window length. "Sloppy" is not available. % % Default window length gives coarse frequency resolution. % % % REFERENCES % [1] Peter D. Welch (June 1967): % "The use of fast Fourier transform for the estimation of power spectra: % a method based on time averaging over short, modified periodograms." % IEEE Transactions on Audio Electroacoustics, Vol AU-15(6), pp 70-73 % % [2] William H. Press and Saul A. Teukolsky and William T. Vetterling and % Brian P. Flannery", % "Numerical recipes in C, The art of scientific computing", 2nd edition, % Cambridge University Press, 2002 --- Section 13.7. % [3] Paul Kienzle (1999-2001): "pwelch", http://octave.sourceforge.net/ function [varargout] = pwelch(x,varargin) checkfunctionmatlab('pwelch', 'signal_toolbox') % % COMPATIBILITY LEVEL % Argument positions and defaults depend on compatibility level selected % by calling pwelch without arguments or with a single string argument. % native: compatib=1; prev_compat=pwelch(); prev_compat=pwelch([]); % matlab R11: compatib=2; prev_compat=pwelch('R11-'); % matlab R12: compatib=3; prev_compat=pwelch('R12+'); % spectrum.welch defaults: compatib=4; prev_compat=pwelch('psd'); % In each case, the returned value is the PREVIOUS compatibility string. % compat_str = {[]; 'R11-'; 'R12+'; 'psd'}; persistent compatib; if ( isempty(compatib) || compatib<=0 || compatib>4 ) % legal values are 1, 2, 3, 4 compatib = 1; end if ( nargin <= 0 ) error( 'pwelch: Need at least 1 arg. Use "help pwelch".' ); elseif ( nargin==1 && (ischar(x) || isempty(x)) ) varargout{1} = compat_str{compatib}; if ( isempty(x) ) % native compatib = 1; elseif ( strcmp(x,'R11-') ) compatib = 2; elseif ( strcmp(x,'R12+') ) compatib = 3; elseif ( strcmp(x,'psd') ) compatib = 4; else error( 'pwelch: compatibility arg must be empty, R11-, R12+ or psd' ); end % return % % Check fixed argument elseif ( isempty(x) || ~isvector(x) ) error( 'pwelch: arg 1 (x) must be vector.' ); else % force x to be COLUMN vector if ( size(x,1)==1 ) x=x(:); end % % Look through all args to check if cross PSD, transfer function or % coherence is required. If yes, the second arg is data vector "y". arg2_is_y = 0; x_len = length(x); nvarargin = length(varargin); for iarg=1:nvarargin arg = varargin{iarg}; if ( ~isempty(arg) && ischar(arg) && ... ( strcmp(arg,'cross') || strcmp(arg,'trans') || ... strcmp(arg,'coher') || strcmp(arg,'ypower') )) % OK. Need "y". Grab it from 2nd arg. arg = varargin{1}; if ( nargin<2 || isempty(arg) || ~isvector(arg) || length(arg)~=x_len ) error( 'pwelch: arg 2 (y) must be vector, same length as x.' ); end % force COLUMN vector y = varargin{1}(:); arg2_is_y = 1; break; end end % % COMPATIBILITY % To select default argument values, "compatib" is used as an array index. % Index values are 1=native, 2=R11, 3=R12, 4=spectrum.welch % % argument positions: % arg_posn = varargin index of window, overlap, Nfft, Fs and conf % args respectively, a value of zero ==>> arg does not exist arg_posn = [1 2 3 4 5; % native 3 4 1 2 5; % Matlab R11- pwelch 1 2 3 4 0; % Matlab R12+ pwelch 1 2 3 4 5]; % spectrum.welch defaults arg_posn = arg_posn(compatib,:) + arg2_is_y; % % SPECIFY SOME DEFAULT VALUES for (not all) optional arguments % Use compatib as array index. % Fs = sampling frequency Fs = [ 1.0 2*pi 2*pi 2*pi ]; Fs = Fs(compatib); % plot_type: 1='plot'|'squared'; 5='db'|'dB' plot_type = [ 1 5 5 5 ]; plot_type = plot_type(compatib); % rm_mean: 3='long-mean'; 0='no-strip'|'none' rm_mean = [ 3 0 0 0 ]; rm_mean = rm_mean(compatib); % use max_overlap=x_len-1 because seg_len is not available yet % units of overlap are different for each version: % fraction, samples, or percent max_overlap = [ 0.95 x_len-1 x_len-1 95]; max_overlap = max_overlap(compatib); % default confidence interval % if there are more than 2 return values and if there is a "conf" arg conf = 0.95 * (nargout>2) * (arg_posn(5)>0); % is_win = 0; % =0 means valid window arg is not provided yet Nfft = []; % default depends on segment length overlap = []; % WARNING: units can be #samples, fraction or percentage range = ~isreal(x) || ( arg2_is_y && ~isreal(y) ); is_sloppy = 0; n_results = 0; do_power = 0; do_cross = 0; do_trans = 0; do_coher = 0; do_ypower = 0; % % DECODE AND CHECK OPTIONAL ARGUMENTS end_numeric_args = 0; for iarg = 1+arg2_is_y:nvarargin arg = varargin{iarg}; if ( ischar(arg) ) % first string arg ==> no more numeric args % non-string args cannot follow a string arg end_numeric_args = 1; % % decode control-string arguments if ( strcmp(arg,'sloppy') ) is_sloppy = ~is_win || is_win==1; elseif ( strcmp(arg,'plot') || strcmp(arg,'squared') ) plot_type = 1; elseif ( strcmp(arg,'semilogx') ) plot_type = 2; elseif ( strcmp(arg,'semilogy') ) plot_type = 3; elseif ( strcmp(arg,'loglog') ) plot_type = 4; elseif ( strcmp(arg,'db') || strcmp(arg,'dB') ) plot_type = 5; elseif ( strcmp(arg,'half') || strcmp(arg,'onesided') ) range = 0; elseif ( strcmp(arg,'whole') || strcmp(arg,'twosided') ) range = 1; elseif ( strcmp(arg,'shift') || strcmp(arg,'centerdc') ) range = 2; elseif ( strcmp(arg,'long-mean') ) rm_mean = 3; elseif ( strcmp(arg,'linear') ) rm_mean = 2; elseif ( strcmp(arg,'short') || strcmp(arg,'mean') ) rm_mean = 1; elseif ( strcmp(arg,'no-strip') || strcmp(arg,'none') ) rm_mean = 0; elseif ( strcmp(arg, 'power' ) ) if ( ~do_power ) n_results = n_results+1; do_power = n_results; end elseif ( strcmp(arg, 'cross' ) ) if ( ~do_cross ) n_results = n_results+1; do_cross = n_results; end elseif ( strcmp(arg, 'trans' ) ) if ( ~do_trans ) n_results = n_results+1; do_trans = n_results; end elseif ( strcmp(arg, 'coher' ) ) if ( ~do_coher ) n_results = n_results+1; do_coher = n_results; end elseif ( strcmp(arg, 'ypower' ) ) if ( ~do_ypower ) n_results = n_results+1; do_ypower = n_results; end else error( 'pwelch: string arg %d illegal value: %s', iarg+1, arg ); end % end of processing string args % elseif ( end_numeric_args ) if ( ~isempty(arg) ) % found non-string arg after a string arg ... oops error( 'pwelch: control arg must be string' ); end % % first 4 optional arguments are numeric -- in fixed order % % deal with "Fs" and "conf" first because empty arg is a special default % -- "Fs" arg -- sampling frequency elseif ( iarg == arg_posn(4) ) if ( isempty(arg) ) Fs = 1; elseif ( ~isscalar(arg) || ~isreal(arg) || arg<0 ) error( 'pwelch: arg %d (Fs) must be real scalar >0', iarg+1 ); else Fs = arg; end % % -- "conf" arg -- confidence level % guard against the "it cannot happen" iarg==0 elseif ( arg_posn(5) && iarg == arg_posn(5) ) if ( isempty(arg) ) conf = 0.95; elseif ( ~isscalar(arg) || ~isreal(arg) || arg < 0.0 || arg >= 1.0 ) error( 'pwelch: arg %d (conf) must be real scalar, >=0, <1',iarg+1 ); else conf = arg; end % % skip all empty args from this point onward elseif ( isempty(arg) ) 1; % % -- "window" arg -- window function elseif ( iarg == arg_posn(1) ) if ( isscalar(arg) ) is_win = 1; elseif ( isvector(arg) ) is_win = length(arg); if ( size(arg,2)>1 ) % vector must be COLUMN vector arg = arg(:); end else is_win = 0; end if ( ~is_win ) error( 'pwelch: arg %d (window) must be scalar or vector', iarg+1 ); elseif ( is_win==1 && ( ~isreal(arg) || fix(arg)~=arg || arg<=3 ) ) error( 'pwelch: arg %d (window) must be integer >3', iarg+1 ); elseif ( is_win>1 && ( ~isreal(arg) || any(arg<0) ) ) error( 'pwelch: arg %d (window) vector must be real and >=0',iarg+1); end window = arg; is_sloppy = 0; % % -- "overlap" arg -- segment overlap elseif ( iarg == arg_posn(2) ) if (~isscalar(arg) || ~isreal(arg) || arg<0 || arg>max_overlap ) error( 'pwelch: arg %d (overlap) must be real from 0 to %f', ... iarg+1, max_overlap ); end overlap = arg; % % -- "Nfft" arg -- FFT length elseif ( iarg == arg_posn(3) ) if ( ~isscalar(arg) || ~isreal(arg) || fix(arg)~=arg || arg<0 ) error( 'pwelch: arg %d (Nfft) must be integer >=0', iarg+1 ); end Nfft = arg; % else error( 'pwelch: arg %d must be string', iarg+1 ); end end if ( conf>0 && (n_results && ~do_power ) ) error('pwelch: can give confidence interval for x power spectrum only' ); end % % end DECODE AND CHECK OPTIONAL ARGUMENTS. % % SETUP REMAINING PARAMETERS % default action is to calculate power spectrum only if ( ~n_results ) n_results = 1; do_power = 1; end need_Pxx = do_power || do_trans || do_coher; need_Pxy = do_cross || do_trans || do_coher; need_Pyy = do_coher || do_ypower; log_two = log(2); nearly_one = 0.99999999999; % % compatibility-options % provides exact compatibility with Matlab R11 or R12 % % Matlab R11 compatibility if ( compatib==2 ) if ( isempty(Nfft) ) Nfft = min( 256, x_len ); end if ( is_win > 1 ) seg_len = min( length(window), Nfft ); window = window(1:seg_len); else if ( is_win ) % window arg is scalar seg_len = window; else seg_len = Nfft; end % make Hann window (don't depend on sigproc) xx = seg_len - 1; window = 0.5 - 0.5 * cos( (2*pi/xx)*[0:xx].' ); end % % Matlab R12 compatibility elseif ( compatib==3 ) if ( is_win > 1 ) % window arg provides window function seg_len = length(window); else % window arg does not provide window function; use Hamming if ( is_win ) % window arg is scalar seg_len = window; else % window arg not available; use R12 default, 8 windows % ignore overlap arg; use overlap=50% -- only choice that makes sense % this is the magic formula for 8 segments with 50% overlap seg_len = fix( (x_len-3)*2/9 ); end % make Hamming window (don't depend on sigproc) xx = seg_len - 1; window = 0.54 - 0.46 * cos( (2*pi/xx)*[0:xx].' ); end if ( isempty(Nfft) ) Nfft = max( 256, 2^ceil(log(seg_len)*nearly_one/log_two) ); end % % Matlab R14 psd(spectrum.welch) defaults elseif ( compatib==4 ) if ( is_win > 1 ) % window arg provides window function seg_len = length(window); else % window arg does not provide window function; use Hamming if ( is_win ) % window arg is scalar seg_len = window; else % window arg not available; use default seg_len = 64 seg_len = 64; end % make Hamming window (don't depend on sigproc) xx = seg_len - 1; window = 0.54 - 0.46 * cos( (2*pi/xx)*[0:xx].' ); end % Now we know segment length, % so we can set default overlap as number of samples if ( ~isempty(overlap) ) overlap = fix(seg_len * overlap / 100 ); end if ( isempty(Nfft) ) Nfft = max( 256, 2^ceil(log(seg_len)*nearly_one/log_two) ); end % % default compatibility level else %if ( compatib==1 ) % calculate/adjust segment length, window function if ( is_win > 1 ) % window arg provides window function seg_len = length(window); else % window arg does not provide window function; use Hamming if ( is_win ) % window arg is scalar seg_len = window; else % window arg not available; use default length: % = sqrt(length(x)) rounded up to nearest integer power of 2 if ( isempty(overlap) ) overlap=0.5; end seg_len = 2 ^ ceil( log(sqrt(x_len/(1-overlap)))*nearly_one/log_two ); end % make Hamming window (don't depend on sigproc) xx = seg_len - 1; window = 0.54 - 0.46 * cos( (2*pi/xx)*[0:xx].' ); end % Now we know segment length, % so we can set default overlap as number of samples if ( ~isempty(overlap) ) overlap = fix(seg_len * overlap); end % % calculate FFT length if ( isempty(Nfft) ) Nfft = seg_len; end if ( is_sloppy ) Nfft = 2 ^ ceil( log(Nfft) * nearly_one / log_two ); end end % end of compatibility options % % minimum FFT length is seg_len Nfft = max( Nfft, seg_len ); % Mean square of window is required for normalising PSD amplitude. win_meansq = (window.' * window) / seg_len; % % Set default or check overlap. if ( isempty(overlap) ) overlap = fix(seg_len /2); elseif ( overlap >= seg_len ) error( 'pwelch: arg (overlap=%d) too big. Must be <length(window)=%d',... overlap, seg_len ); end % % Pad data with zeros if shorter than segment. This should not happen. if ( x_len < seg_len ) x = [x; zeros(seg_len-x_len,1)]; if ( arg2_is_y ) y = [y; zeros(seg_len-x_len,1)]; end x_len = seg_len; end % end SETUP REMAINING PARAMETERS % % % MAIN CALCULATIONS % Remove mean from the data if ( rm_mean == 3 ) n_ffts = max( 0, fix( (x_len-seg_len)/(seg_len-overlap) ) ) + 1; x_len = min( x_len, (seg_len-overlap)*(n_ffts-1)+seg_len ); if ( need_Pxx || need_Pxy ) x = x - sum( x(1:x_len) ) / x_len; end if ( arg2_is_y || need_Pxy) y = y - sum( y(1:x_len) ) / x_len; end end % % Calculate and accumulate periodograms % xx and yy are padded data segments % Pxx, Pyy, Pyy are periodogram sums, Vxx is for confidence interval xx = zeros(Nfft,1); yy = xx; Pxx = xx; Pxy = xx; Pyy = xx; if ( conf>0 ) Vxx = xx; else Vxx = []; end n_ffts = 0; for start_seg = [1:seg_len-overlap:x_len-seg_len+1] end_seg = start_seg+seg_len-1; % Don't truncate/remove the zero padding in xx and yy if ( need_Pxx || need_Pxy ) if ( rm_mean==1 ) % remove mean from segment xx(1:seg_len) = window .* ( ... x(start_seg:end_seg) - sum(x(start_seg:end_seg)) / seg_len); elseif ( rm_mean == 2 ) % remove linear trend from segment xx(1:seg_len) = window .* detrend( x(start_seg:end_seg) ); else % rm_mean==0 or 3 xx(1:seg_len) = window .* x(start_seg:end_seg); end fft_x = fft(xx); end if ( need_Pxy || need_Pyy ) if ( rm_mean==1 ) % remove mean from segment yy(1:seg_len) = window .* ( ... y(start_seg:end_seg) - sum(y(start_seg:end_seg)) / seg_len); elseif ( rm_mean == 2 ) % remove linear trend from segment yy(1:seg_len) = window .* detrend( y(start_seg:end_seg) ); else % rm_mean==0 or 3 yy(1:seg_len) = window .* y(start_seg:end_seg); end fft_y = fft(yy); end if ( need_Pxx ) % force Pxx to be real; pgram = periodogram pgram = real(fft_x .* conj(fft_x)); Pxx = Pxx + pgram; % sum of squared periodograms is required for confidence interval if ( conf>0 ) Vxx = Vxx + pgram .^2; end end if ( need_Pxy ) % Pxy (cross power spectrum) is complex. Do not force to be real. Pxy = Pxy + fft_y .* conj(fft_x); end if ( need_Pyy ) % force Pyy to be real Pyy = Pyy + real(fft_y .* conj(fft_y)); end n_ffts = n_ffts +1; end % % Calculate confidence interval % -- incorrectly assumes that the periodogram has Gaussian probability % distribution (actually, it has a single-sided (e.g. exponential) % distribution. % Sample variance of periodograms is (Vxx-Pxx.^2/n_ffts)/(n_ffts-1). % This method of calculating variance is more susceptible to round-off % error, but is quicker, and for double-precision arithmetic and the % inherently noisy periodogram (variance==mean^2), it should be OK. if ( conf>0 && need_Pxx ) if ( n_ffts<2 ) Vxx = zeros(Nfft,1); else % Should use student distribution here (for unknown variance), but tinv % is not a core Matlab function (is in statistics toolbox. Grrr) Vxx = (erfinv(conf)*sqrt(2*n_ffts/(n_ffts-1))) * sqrt(Vxx-Pxx.^2/n_ffts); end end % % Convert two-sided spectra to one-sided spectra (if range == 0). % For one-sided spectra, contributions from negative frequencies are added % to the positive side of the spectrum -- but not at zero or Nyquist % (half sampling) frequencies. This keeps power equal in time and spectral % domains, as required by Parseval theorem. % if ( range == 0 ) if ( ~ rem(Nfft,2) ) % one-sided, Nfft is even psd_len = Nfft/2+1; if ( need_Pxx ) Pxx = Pxx(1:psd_len) + [0; Pxx(Nfft:-1:psd_len+1); 0]; if ( conf>0 ) Vxx = Vxx(1:psd_len) + [0; Vxx(Nfft:-1:psd_len+1); 0]; end end if ( need_Pxy ) Pxy = Pxy(1:psd_len) + conj([0; Pxy(Nfft:-1:psd_len+1); 0]); end if ( need_Pyy ) Pyy = Pyy(1:psd_len) + [0; Pyy(Nfft:-1:psd_len+1); 0]; end else % one-sided, Nfft is odd psd_len = (Nfft+1)/2; if ( need_Pxx ) Pxx = Pxx(1:psd_len) + [0; Pxx(Nfft:-1:psd_len+1)]; if ( conf>0 ) Vxx = Vxx(1:psd_len) + [0; Vxx(Nfft:-1:psd_len+1)]; end end if ( need_Pxy ) Pxy = Pxy(1:psd_len) + conj([0; Pxy(Nfft:-1:psd_len+1)]); end if ( need_Pyy ) Pyy = Pyy(1:psd_len) + [0; Pyy(Nfft:-1:psd_len+1)]; end end else % two-sided (and shifted) psd_len = Nfft; end % end MAIN CALCULATIONS % % SCALING AND OUTPUT % Put all results in matrix, one row per spectrum % Pxx, Pxy, Pyy are sums of periodograms, so "n_ffts" % in the scale factor converts them into averages spectra = zeros(psd_len,n_results); spect_type = zeros(n_results,1); scale = n_ffts * seg_len * Fs * win_meansq; if ( do_power ) spectra(:,do_power) = Pxx / scale; spect_type(do_power) = 1; if ( conf>0 ) Vxx = [Pxx-Vxx Pxx+Vxx]/scale; end end if ( do_cross ) spectra(:,do_cross) = Pxy / scale; spect_type(do_cross) = 2; end if ( do_trans ) spectra(:,do_trans) = Pxy ./ Pxx; spect_type(do_trans) = 3; end if ( do_coher ) % force coherence to be real spectra(:,do_coher) = real(Pxy .* conj(Pxy)) ./ Pxx ./ Pyy; spect_type(do_coher) = 4; end if ( do_ypower ) spectra(:,do_ypower) = Pyy / scale; spect_type(do_ypower) = 5; end freq = [0:psd_len-1].' * ( Fs / Nfft ); % % range='shift': Shift zero-frequency to the middle if ( range == 2 ) len2 = fix((Nfft+1)/2); spectra = [ spectra(len2+1:Nfft,:); spectra(1:len2,:)]; freq = [ freq(len2+1:Nfft)-Fs; freq(1:len2)]; if ( conf>0 ) Vxx = [ Vxx(len2+1:Nfft,:); Vxx(1:len2,:)]; end end % % RETURN RESULTS or PLOT if ( nargout>=2 && conf>0 ) varargout{2} = Vxx; end if ( nargout>=(2+(conf>0)) ) % frequency is 2nd or 3rd return value, % depends on if 2nd is confidence interval varargout{2+(conf>0)} = freq; end if ( nargout>=1 ) varargout{1} = spectra; else % % Plot the spectra if there are no return variables. plot_title=['power spectrum x '; 'cross spectrum '; 'transfer function'; 'coherence '; 'power spectrum y ' ]; for ii = 1: n_results if ( conf>0 && spect_type(ii)==1 ) Vxxxx = Vxx; else Vxxxx = []; end if ( n_results > 1 ) figure(); end if ( plot_type == 1 ) plot(freq,[abs(spectra(:,ii)) Vxxxx]); elseif ( plot_type == 2 ) semilogx(freq,[abs(spectra(:,ii)) Vxxxx]); elseif ( plot_type == 3 ) semilogy(freq,[abs(spectra(:,ii)) Vxxxx]); elseif ( plot_type == 4 ) loglog(freq,[abs(spectra(:,ii)) Vxxxx]); elseif ( plot_type == 5 ) % db ylabel( 'amplitude (dB)' ); plot(freq,[10*log10(abs(spectra(:,ii))) 10*log10(abs(Vxxxx))]); end title( char(plot_title(spect_type(ii),:)) ); ylabel( 'amplitude' ); % Plot phase of cross spectrum and transfer function if ( spect_type(ii)==2 || spect_type(ii)==3 ) figure(); if ( plot_type==2 || plot_type==4 ) semilogx(freq,180/pi*angle(spectra(:,ii))); else plot(freq,180/pi*angle(spectra(:,ii))); end title( char(plot_title(spect_type(ii),:)) ); ylabel( 'phase' ); end end %for end end end %!demo %! fflush(stdout); %! rand('seed',2038014164); %! a = [ 1.0 -1.6216505 1.1102795 -0.4621741 0.2075552 -0.018756746 ]; %! white = rand(1,16384); %! signal = detrend(filter(0.70181,a,white)); %! % frequency shift by modulating with exp(j.omega.t) %! skewed = signal.*exp(2*pi*i*2/25*[1:16384]); %! Fs = 25; % sampling frequency %! hold off %! pwelch([]); %! pwelch(signal); %! disp('Default settings: Fs=1Hz, overlap=0.5, no padding' ) %! input('Onesided power spectral density (real data). Press ENTER', 's' ); %! hold on %! pwelch(skewed); %! disp('Frequency-shifted complex data. Twosided wrap-around spectrum.' ); %! input('Area is same as one-sided spectrum. Press ENTER', 's' ); %! pwelch(signal,'shift','semilogy'); %! input('Twosided, centred zero-frequency, lin-log plot. Press ENTER', 's' ); %! hold off %! figure(); %! pwelch(skewed,[],[],[],Fs,'shift','semilogy'); %! input('Actual Fs=25 Hz. Note change of scales. Press ENTER', 's' ); %! pwelch(skewed,[],[],[],Fs,0.95,'shift','semilogy'); %! input('Spectral density with 95% confidence interval. Press ENTER', 's' ); %! pwelch('R12+'); %! pwelch(signal,'squared'); %! input('Spectral density with Matlab R12 defaults. Press ENTER', 's' ); %! figure(); %! pwelch([]); %! pwelch(signal,3640,[],4096,2*pi,[],'no-strip'); %! input('Same spectrum with 95% confidence interval. Press ENTER', 's' ); %! figure(); %! pwelch(signal,[],[],[],2*pi,0.95,'no-strip'); %! input('95% confidence interval with native defaults. Press ENTER', 's' ); %! pwelch(signal,64,[],[],2*pi,'no-strip'); %! input('Only 32 frequency values in this spectrum. Press ENTER', 's' ); %! hold on %! pwelch(signal,64,[],256,2*pi,'no-strip'); %! input('4:1 zero padding gives artificial smoothing. Press ENTER', 's' ); %! figure(); %! pwelch('psd'); %! pwelch(signal,'squared'); %! input('Just like Matlab spectrum.welch(...) defaults. Press ENTER', 's' ); %! hold off %! pwelch({}); %! pwelch(white,signal,'trans','coher','short') %! input('Transfer and coherence functions. Press ENTER', 's' ); %! disp('Use "close all" to remove plotting windows.' );
github
lcnbeapp/beapp-master
filtfilt.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/octavefunc/signal/filtfilt.m
4,430
iso_8859_1
011f993ef23add46147387112d313898
% Copyright (C) 1999 Paul Kienzle % Copyright (C) 2007 Francesco Potortì % Copyright (C) 2008 Luca Citi % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % usage: y = filtfilt(b, a, x) % % Forward and reverse filter the signal. This corrects for phase % distortion introduced by a one-pass filter, though it does square the % magnitude response in the process. That's the theory at least. In % practice the phase correction is not perfect, and magnitude response % is distorted, particularly in the stop band. %% % Example % [b, a]=butter(3, 0.1); % 10 Hz low-pass filter % t = 0:0.01:1.0; % 1 second sample % x=sin(2*pi*t*2.3)+0.25*randn(size(t)); % 2.3 Hz sinusoid+noise % y = filtfilt(b,a,x); z = filter(b,a,x); % apply filter % plot(t,x,';data;',t,y,';filtfilt;',t,z,';filter;') % Changelog: % 2000 02 [email protected] % - pad with zeros to load up the state vector on filter reverse. % - add example % 2007 12 [email protected] % - use filtic to compute initial and final states % - work for multiple columns as well % 2008 12 [email protected] % - fixed instability issues with IIR filters and noisy inputs % - initial states computed according to Likhterov & Kopeika, 2003 % - use of a 'reflection method' to reduce end effects % - added some basic tests % TODO: (pkienzle) My version seems to have similar quality to matlab, % but both are pretty bad. They do remove gross lag errors, though. function y = filtfilt(b, a, x) checkfunctionmatlab('filtfilt', 'signal_toolbox') if (nargin ~= 3) usage('y=filtfilt(b,a,x)'); end rotflag = 0; if size(x,1) == 1 rotflag == 1; x = x'; % make it a column vector end; lx = size(x,1); a = a(:).'; b = b(:).'; lb = length(b); la = length(a); n = max(lb, la); lrefl = 3 * (n - 1); if la < n, a(n) = 0; end if lb < n, b(n) = 0; end % Compute a the initial state taking inspiration from % Likhterov & Kopeika, 2003. 'Hardware-efficient technique for % minimizing startup transients in Direct Form II digital filters' kdc = sum(b) / sum(a); if (abs(kdc) < inf) % neither NaN nor +/- Inf si = fliplr(cumsum(fliplr(b - kdc * a))); else si = zeros(size(a)); % fall back to zero initialization end si(1) = []; for (c = 1:size(x,2)) % filter all columns, one by one v = [2*x(1,c)-x((lrefl+1):-1:2,c); x(:,c); 2*x(end,c)-x((end-1):-1:end-lrefl,c)]; % a column vector % Do forward and reverse filtering v = filter(b,a,v,si*v(1)); % forward filter v = flipud(filter(b,a,flipud(v),si*v(end))); % reverse filter y(:,c) = v((lrefl+1):(lx+lrefl)); end if (rotflag) % x was a row vector y = y'; % rotate it back end %!error filtfilt (); %!error filtfilt (1, 2, 3, 4); %!test %! randn('state',0); %! r = randn(1,200); %! [b,a] = butter(10, [.2, .25]); %! yfb = filtfilt(b, a, r); %! assert (size(r), size(yfb)); %! assert (mean(abs(yfb)) < 1e3); %! assert (mean(abs(yfb)) < mean(abs(r))); %! ybf = fliplr(filtfilt(b, a, fliplr(r))); %! assert (mean(abs(ybf)) < 1e3); %! assert (mean(abs(ybf)) < mean(abs(r))); %!test %! randn('state',0); %! r = randn(1,1000); %! s = 10 * sin(pi * 4e-2 * (1:length(r))); %! [b,a] = cheby1(2, .5, [4e-4 8e-2]); %! y = filtfilt(b, a, r+s); %! assert (size(r), size(y)); %! assert (mean(abs(y)) < 1e3); %! assert (corrcoef(s(250:750), y(250:750)) > .95) %! [b,a] = butter(2, [4e-4 8e-2]); %! yb = filtfilt(b, a, r+s); %! assert (mean(abs(yb)) < 1e3); %! assert (corrcoef(y, yb) > .99) %!test %! randn('state',0); %! r = randn(1,1000); %! s = 10 * sin(pi * 4e-2 * (1:length(r))); %! [b,a] = butter(2, [4e-4 8e-2]); %! y = filtfilt(b, a, [r.' s.']); %! yr = filtfilt(b, a, r); %! ys = filtfilt(b, a, s); %! assert (y, [yr.' ys.']); %! y2 = filtfilt(b.', a.', [r.' s.']); %! assert (y, y2);
github
lcnbeapp/beapp-master
firls.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/octavefunc/signal/firls.m
4,078
utf_8
2ce6c9bc19a003aceeafdb9fae59f52e
% Copyright (C) 2006 Quentin Spencer % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % b = firls(N, F, A); % b = firls(N, F, A, W); % % FIR filter design using least squares method. Returns a length N+1 % linear phase filter such that the integral of the weighted mean % squared error in the specified bands is minimized. % % F specifies the frequencies of the band edges, normalized so that % half the sample frequency is equal to 1. Each band is specified by % two frequencies, to the vector must have an even length. % % A specifies the amplitude of the desired response at each band edge. % % W is an optional weighting function that contains one value for each % band that weights the mean squared error in that band. A must be the % same length as F, and W must be half the length of F. % The least squares optimization algorithm for computing FIR filter % coefficients is derived in detail in: % % I. Selesnick, 'Linear-Phase FIR Filter Design by Least Squares,' % http://cnx.org/content/m10577 function coef = firls(N, frequencies, pass, weight, str); checkfunctionmatlab('firls', 'signal_toolbox') if nargin<3 | nargin>6 usage(''); end if nargin==3 weight = ones(1, length(pass)/2); str = []; end if nargin==4 if ischar(weight) str = weight; weight = ones(size(pass)); else str = []; end end if length(frequencies) ~= length(pass) error('F and A must have equal lengths.'); end if 2 * length(weight) ~= length(pass) error('W must contain one weight per band.'); end if ischar(str) error('This feature is implemented yet'); else M = N/2; w = kron(weight(:), [-1; 1]); omega = frequencies * pi; i1 = 1:2:length(omega); i2 = 2:2:length(omega); % Generate the matrix Q % As illustrated in the above-cited reference, the matrix can be % expressed as the sum of a Hankel and Toeplitz matrix. A factor of % 1/2 has been dropped and the final filter coefficients multiplied % by 2 to compensate. warning off MATLAB:colon:nonIntegerIndex cos_ints = [omega; sin((1:N)' * omega)]; q = [1, 1./(1:N)]' .* (cos_ints * w); Q = toeplitz(q(1:M+1)) + hankel(q(1:M+1), q(M+1:end)); % The vector b is derived from solving the integral: % % _ w % / 2 % b = / W(w) D(w) cos(kw) dw % k / w % - 1 % % Since we assume that W(w) is constant over each band (if not, the % computation of Q above would be considerably more complex), but % D(w) is allowed to be a linear function, in general the function % W(w) D(w) is linear. The computations below are derived from the % fact that: % _ % / a ax + b % / (ax + b) cos(nx) dx = --- cos (nx) + ------ sin(nx) % / 2 n % - n % cos_ints2 = [omega(i1).^2 - omega(i2).^2; ... cos((1:M)' * omega(i2)) - cos((1:M)' * omega(i1))] ./ ... ([2, 1:M]' * (omega(i2) - omega(i1))); d = [-weight .* pass(i1); weight .* pass(i2)]; d = d(:); b = [1, 1./(1:M)]' .* ((kron(cos_ints2, [1, 1]) + cos_ints(1:M+1,:)) * d); % Having computed the components Q and b of the matrix equation, % solve for the filter coefficients. a = Q \ b; coef = [ a(end:-1:2); 2 * a(1); a(2:end) ]; warning on MATLAB:colon:nonIntegerIndex end
github
lcnbeapp/beapp-master
supergui.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/guifunc/supergui.m
21,074
utf_8
05da62a5889eab777551326464481bdf
% supergui() - a comprehensive gui automatic builder. This function help % to create GUI very fast without bothering about the % positions of the elements. After creating a geometry, % elements just place themselves into the predefined % locations. It is especially usefull for figure where you % intend to put text button and descriptions. % % Usage: % >> [handles, height, allhandles ] = ... % supergui( 'key1', 'val1', 'key2', 'val2', ... ); % % Inputs: % 'fig' - figure handler, if not given, create a new figure. % 'geom' - cell array of cell array of integer vector. Each cell % array defines the coordinate of a given input in the following % manner: { nb_row nb_col [x_topcorner y_topcorner] % [x_bottomcorner y_bottomcorner] }; % 'geomhoriz' - integer vector or cell array of numerical vectors describing the % geometry of the elements in the figure. % - if integer vector, vector length is the number of rows and vector % values are the number of 'uilist' elements in each row. % For example, [2 3 2] means that the % figures will have 3 rows, with 2 elements in the first % and last row and 3 elements in the second row. % - if cell array, each vector describes the relative widths % of items in each row. For example, { [2 8] [1 2 3] } which means % that figures will have 2 rows, the first one with 2 % elements of relative width 2 and 8 (20% and 80%). The % second row will have 3 elements of relative size 1, 2 % and 3 (1/6 2/6 and 3/6). % 'geomvert' - describting geometry for the rows. For instance % [1 2 1] means that the second row will be twice the height % of the other ones. If [], all the lines have the same height. % 'uilist' - list of uicontrol lists describing elements properties % { { ui1 }, { ui2 }... }, { 'uiX' } being GUI matlab % uicontrol arguments such as { 'style', 'radiobutton', % 'String', 'hello' }. See Matlab function uicontrol() for details. % 'borders' - [left right top bottom] GUI internal borders in normalized % units (0 to 1). Default values are % 'title' - optional figure title % 'userdata' - optional userdata input for the figure % 'inseth' - horizontal space between elements. Default is 2% % of window size. % 'insetv' - vertical space between elements. Default is 2% % of window height. % 'spacing' - [horiz vert] spacing in normalized units. Default % 'spacingtype' - ['absolute'|'proportional'] abolute means that the % spacing values are fixed. Proportional means that they % depend on the number of element in a line. % 'minwidth' - [integer] minimal width in pixels. Default is none. % 'screenpos' - [x y] position of the right top corner of the graphic % interface. 'center' may also be used to center the GUI on % the screen. % 'adjustbuttonwidth' - ['on'|'off'] adjust button width in the GUI. % Default is 'off'. % % Hint: % use 'print -mfile filemane' to save a matlab file of the figure. % % Output: % handles - all the handles of the elements (in the same order as the % uilist input). % height - adviced height for the figure (so the text look nice). % allhandles - all the handles in object format % % Example: % figure; % supergui( 'geomhoriz', { 1 1 }, 'uilist', { ... % { 'style', 'radiobutton', 'string', 'radio' }, ... % { 'style', 'pushbutton' , 'string', 'push' } } ); % % Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 2001- % % See also: eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [handlers, outheight, allhandlers] = supergui( varargin); % handlers cell format % allhandlers linear format handlers = {}; outheight = 0; if nargin < 2 help supergui; return; end; % get version and % set additional parameters % ------------------------- v = version; indDot = find(v == '.'); versnum = str2num(v(1:indDot(2)-1)); if versnum >= 7.14 addParamFont = { 'fontsize' 12 }; else addParamFont = { }; end; warning off MATLAB:hg:uicontrol:ParameterValuesMustBeValid % decoding input and backward compatibility % ----------------------------------------- if isstr(varargin{1}) options = varargin; else options = { 'fig' varargin{1} 'geomhoriz' varargin{2} ... 'geomvert' varargin{3} 'uilist' varargin(4:end) }; end g = finputcheck(options, { 'geomhoriz' 'cell' [] {}; 'fig' '' [] 0; 'geom' 'cell' [] {}; 'uilist' 'cell' [] {}; 'title' 'string' [] ''; 'userdata' '' [] []; 'adjustbuttonwidth' 'string' { 'on' 'off' } 'off'; 'geomvert' 'real' [] []; 'screenpos' { 'real' 'string' } [] []; 'horizontalalignment' 'string' { 'left','right','center' } 'left'; 'minwidth' 'real' [] 10; 'borders' 'real' [] [0.05 0.04 0.07 0.06]; 'spacing' 'real' [] [0.02 0.01]; 'inseth' 'real' [] 0.02; % x border absolute (5% of width) 'insetv' 'real' [] 0.02 }, 'supergui'); if isstr(g), error(g); end if ~isempty(g.geomhoriz) maxcount = sum(cellfun('length', g.geomhoriz)); if maxcount ~= length(g.uilist) warning('Wrong size for ''geomhoriz'' input'); end; if ~isempty(g.geomvert) if length(g.geomvert) ~= length(g.geomhoriz) warning('Wrong size for ''geomvert'' input'); end; end; g.insetv = g.insetv/length(g.geomhoriz); end; if ~isempty(g.geom) if length(g.geom) ~= length(g.uilist) warning('Wrong size for ''geom'' input'); end; maxcount = length(g.geom); end; % create new figure % ----------------- if g.fig == 0 g.fig = figure('visible','off'); end % converting the geometry formats % ------------------------------- if ~isempty(g.geomhoriz) & ~iscell( g.geomhoriz ) oldgeom = g.geomhoriz; g.geomhoriz = {}; for row = 1:length(oldgeom) g.geomhoriz = { g.geomhoriz{:} ones(1, oldgeom(row)) }; end; end if isempty(g.geomvert) g.geomvert = ones(1, length(g.geomhoriz)); end % converting to the new format % ---------------------------- if isempty(g.geom) count = 1; incy = 0; sumvert = sum(g.geomvert); maxhoriz = 1; for row = 1:length(g.geomhoriz) incx = 0; maxhoriz = max(maxhoriz, length(g.geomhoriz{row})); ratio = length(g.geomhoriz{row})/sum(g.geomhoriz{row}); for column = 1:length(g.geomhoriz{row}) g.geom{count} = { length(g.geomhoriz{row}) sumvert [incx incy] [g.geomhoriz{row}(column)*ratio g.geomvert(row)] }; incx = incx+g.geomhoriz{row}(column)*ratio; count = count+1; end; incy = incy+g.geomvert(row); end; g.borders(1:2) = g.borders(1:2)/maxhoriz*5; g.borders(3:4) = g.borders(3:4)/sumvert*10; g.spacing(1) = g.spacing(1)/maxhoriz*5; g.spacing(2) = g.spacing(2)/sumvert*10; end; % disp new geometry % ----------------- if 0 fprintf('{ ...\n'); for index = 1:length(g.geom) fprintf('{ %g %g [%g %g] [%g %g] } ...\n', g.geom{index}{1}, g.geom{index}{2}, ... g.geom{index}{3}(1), g.geom{index}{3}(2), g.geom{index}{4}(1), g.geom{index}{3}(2)); end; fprintf('};\n'); end; % get axis coordinates % -------------------- try set(g.fig, 'menubar', 'none', 'numbertitle', 'off'); catch end pos = [0 0 1 1]; % plot relative to current axes q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]; % allow to use normalized position [0 100] for x and y axis('off'); % creating guis % ------------- row = 1; % count the elements column = 1; % count the elements factmultx = 0; factmulty = 0; %zeros(length(g.geomhoriz)); for counter = 1:maxcount % init clear rowhandle; gm = g.geom{counter}; [posx posy width height] = getcoord(gm{1}, gm{2}, gm{3}, gm{4}, g.borders, g.spacing); try currentelem = g.uilist{ counter }; catch fprintf('Warning: not all boxes were filled\n'); return; end; if ~isempty(currentelem) % decode metadata % --------------- if strcmpi(currentelem{1}, 'link2lines'), currentelem(1) = []; hf1 = 3.6/2-0.3; hf2 = 0.7/2-0.3; allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ... [posx-width/2 posy+hf1*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', ''); allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ... [posx-width/2 posy+hf2*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', ''); allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ... [posx posy+hf2*height 0.005 (hf1-hf2+0.1)*height].*s+q, 'style', 'pushbutton', 'string', ''); allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ... [posx posy+(hf1+hf2)/2*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', ''); allhandlers{counter} = 0; else if strcmpi(currentelem{1}, 'width'), curwidth = currentelem{2}; currentelem(1:2) = []; else curwidth = 0; end; if strcmpi(currentelem{1}, 'align'), align = currentelem{2}; currentelem(1:2) = []; else align = 'right'; end; if strcmpi(currentelem{1}, 'stickto'), stickto = currentelem{2}; currentelem(1:2) = []; else stickto = 'none'; end; if strcmpi(currentelem{1}, 'vertshift'), currentelem(1) = []; addvert = -height/2; else addvert = 0; end; if strcmpi(currentelem{1}, 'vertexpand'), heightfactor = currentelem{2}; addvert = -(heightfactor-1)*height; currentelem(1:2) = []; else heightfactor = 1; end; % position adjustment depending on GUI type if isstr(currentelem{2}) && strcmpi(currentelem{2}, 'popupmenu') posy = posy-height/10; end; if isstr(currentelem{2}) && strcmpi(currentelem{2}, 'text') posy = posy+height/5; end; if strcmpi(currentelem{1}, 'function'), % property grid argument panel = uipanel('Title','','FontSize',12,'BackgroundColor','white','Position',[posx posy+addvert width height*heightfactor].*s+q); allhandlers{counter} = arg_guipanel(panel, currentelem{:}); else allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ... [posx posy+addvert width height*heightfactor].*s+q, currentelem{:}, addParamFont{:}); % this simply compute a factor so that all uicontrol will be visible % ------------------------------------------------------------------ style = get( allhandlers{counter}, 'style'); set( allhandlers{counter}, 'units', 'pixels'); curpos = get(allhandlers{counter}, 'position'); curext = get(allhandlers{counter}, 'extent'); if curwidth ~= 0 curwidth = curwidth/((factmultx-1)/1.85+1); if strcmpi(align, 'right') curpos(1) = curpos(1)+curpos(3)-curwidth; elseif strcmpi(align, 'center') curpos(1) = curpos(1)+curpos(3)/2-curwidth/2; end; set(allhandlers{counter}, 'position', [ curpos(1) curpos(2) curwidth curpos(4) ]); if strcmpi(stickto, 'on') set( allhandlers{counter-1}, 'units', 'pixels'); curpos2 = get(allhandlers{counter-1}, 'position'); set(allhandlers{counter-1}, 'position', [ curpos(1)-curpos2(3)-10 curpos2(2) curpos2(3) curpos2(4) ]); set( allhandlers{counter-1}, 'units', 'normalized'); end; curext(3) = curwidth; end; set( allhandlers{counter}, 'units', 'normalized'); end; if ~strcmp(style, 'edit') && (~strcmp(style, 'pushbutton') || strcmpi(g.adjustbuttonwidth, 'on')) %tmp = curext(3)/curpos(3); %if tmp > 3*factmultx && factmultx > 0, adsfasd; end; factmultx = max(factmultx, curext(3)/curpos(3)); if strcmp(style, 'pushbutton'), factmultx = factmultx*1.1; end; end; if ~strcmp(style, 'listbox') factmulty = max(factmulty, curext(4)/curpos(4)); end; % Uniformize button text aspect (first letter must be upercase) % ----------------------------- if strcmp(style, 'pushbutton') tmptext = get(allhandlers{counter}, 'string'); if length(tmptext) > 1 if upper(tmptext(1)) ~= tmptext(1) || lower(tmptext(2)) ~= tmptext(2) && ~strcmpi(tmptext, 'STATS') tmptext = lower(tmptext); try, tmptext(1) = upper(tmptext(1)); catch, end; end; end; set(allhandlers{counter}, 'string', tmptext); end; end; else allhandlers{counter} = 0; end; end; % adjustments % ----------- factmultx = factmultx*1.02;% because some text was still hidden %factmultx = factmultx*1.2; if factmultx < 0.1 factmultx = 0.1; end; % for MAC (magnify figures that have edit fields) % ------- warning off; try, comp = computer; if length(comp) > 2 && strcmpi(comp(1:3), 'MAC') factmulty = factmulty*1.5; elseif ~isunix % windows factmulty = factmulty*1.08; end; catch, end; factmulty = factmulty*0.9; % global shinking warning on; % scale and replace the figure in the screen % ----------------------------------------- pos = get(g.fig, 'position'); if factmulty > 1 pos(2) = max(0,pos(2)+pos(4)-pos(4)*factmulty); end; pos(1) = pos(1)+pos(3)*(1-factmultx)/2; pos(3) = max(pos(3)*factmultx, g.minwidth); pos(4) = pos(4)*factmulty; set(g.fig, 'position', pos); % vertical alignment to bottom for text (isnumeric by ishanlde was changed here) % --------------------------------------- for index = 1:length(allhandlers) if allhandlers{index} ~= 0 && ishandle(allhandlers{index}) if strcmp(get(allhandlers{index}, 'style'), 'text') set(allhandlers{index}, 'unit', 'pixel'); curpos = get(allhandlers{index}, 'position'); curext = get(allhandlers{index}, 'extent'); set(allhandlers{index}, 'position', [curpos(1) curpos(2)-4 curpos(3) curext(4)]); set(allhandlers{index}, 'unit', 'normalized'); end; end; end; % setting defaults colors %------------------------ try, icadefs; catch, GUIBACKCOLOR = [.8 .8 .8]; GUIPOPBUTTONCOLOR = [.8 .8 .8]; GUITEXTCOLOR = [0 0 0]; end; numobjects = cellfun(@ishandle, allhandlers); % (isnumeric by ishanlde was changed here) allhandlersnum = [ allhandlers{numobjects} ]; hh = findobj(allhandlersnum, 'parent', g.fig, 'style', 'text'); %set(hh, 'BackgroundColor', get(g.fig, 'color'), 'horizontalalignment', 'left'); set(hh, 'Backgroundcolor', GUIBACKCOLOR); set(hh, 'foregroundcolor', GUITEXTCOLOR); try set(g.fig, 'color',GUIBACKCOLOR ); catch end set(hh, 'horizontalalignment', g.horizontalalignment); hh = findobj(allhandlersnum, 'style', 'edit'); set(hh, 'BackgroundColor', [1 1 1]); %, 'horizontalalignment', 'right'); hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'pushbutton'); comp = computer; if length(comp) < 3 || ~strcmpi(comp(1:3), 'MAC') % this puts the wrong background on macs set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR); set(hh, 'foregroundcolor', GUITEXTCOLOR); end; hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'popupmenu'); set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR); set(hh, 'foregroundcolor', GUITEXTCOLOR); hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'checkbox'); set(hh, 'backgroundcolor', GUIBACKCOLOR); set(hh, 'foregroundcolor', GUITEXTCOLOR); hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'listbox'); set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR); set(hh, 'foregroundcolor', GUITEXTCOLOR); hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'radio'); set(hh, 'foregroundcolor', GUITEXTCOLOR); set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR); set(g.fig, 'visible', 'on'); % screen position % --------------- if ~isempty(g.screenpos) pos = get(g.fig, 'position'); if isnumeric(g.screenpos) set(g.fig, 'position', [ g.screenpos pos(3) pos(4)]); else screenSize = get(0, 'screensize'); pos(1) = (screenSize(3)-pos(3))/2; pos(2) = (screenSize(4)-pos(4))/2+pos(4); set(g.fig, 'position', pos); end; end; % set userdata and title % ---------------------- if ~isempty(g.userdata), set(g.fig, 'userdata', g.userdata); end; if ~isempty(g.title ), set(g.fig, 'name', g.title ); end; return; function [posx posy width height] = getcoord(geom1, geom2, coord1, sz, borders, spacing); coord2 = coord1+sz; borders(1:2) = borders(1:2)-spacing(1); borders(3:4) = borders(3:4)-spacing(2); % absolute positions posx = coord1(1)/geom1; posy = coord1(2)/geom2; posx2 = coord2(1)/geom1; posy2 = coord2(2)/geom2; width = posx2-posx; height = posy2-posy; % add spacing posx = posx+spacing(1)/2; width = max(posx2-posx-spacing(1), 0.001); height = max(posy2-posy-spacing(2), 0.001); posy = max(0, 1-posy2)+spacing(2)/2; % add border posx = posx*(1-borders(1)-borders(2))+borders(1); posy = posy*(1-borders(3)-borders(4))+borders(4); width = width*( 1-borders(1)-borders(2)); height = height*(1-borders(3)-borders(4)); function [posx posy width height] = getcoordold(geom1, geom2, coord1, sz); coord2 = coord1+sz; horiz_space = 0.05/geom1; vert_space = 0.05/geom2; horiz_border = min(0.1, 1/geom1)-horiz_space; vert_border = min(0.2, 1.5/geom2)-vert_space; % absolute positions posx = coord1(1)/geom1; posy = coord1(2)/geom2; posx2 = coord2(1)/geom1; posy2 = coord2(2)/geom2; width = posx2-posx; height = posy2-posy; % add spacing posx = posx+horiz_space/2; width = max(posx2-posx-horiz_space, 0.001); height = max(posy2-posy- vert_space, 0.001); posy = max(0, 1-posy2)+vert_space/2; % add border posx = posx*(1-horiz_border)+horiz_border/2; posy = posy*(1- vert_border)+vert_border/2; width = width*(1-horiz_border); height = height*(1-vert_border); % posx = coord1(1)/geom1+horiz_border*1/geom1/2; % posy = 1-(coord1(2)/geom2+vert_border*1/geom2/2)-1/geom2; % % posx2 = coord2(1)/geom1+horiz_border*1/geom1/2; % posy2 = 1-(coord2(2)/geom2+vert_border*1/geom2/2)-1/geom2; % % width = posx2-posx; % height = posy-posy2; %h = axes('unit', 'normalized', 'position', [ posx posy width height ]); %h = axes('unit', 'normalized', 'position', [ coordx/geom1 1-coordy/geom2-1/geom2 1/geom1 1/geom2 ]);
github
lcnbeapp/beapp-master
warndlg2.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/guifunc/warndlg2.m
1,031
utf_8
4d58c147c6515911a93ba2375203951d
% warndlg2() - same as warndlg for eeglab() % % Author: Arnaud Delorme, CNL / Salk Institute, 12 August 2002 % % See also: inputdlg2(), questdlg2() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function warndlg2(Prompt, Title); if nargin <2 Title = 'Warning'; end; questdlg2(Prompt, Title, 'OK', 'OK');
github
lcnbeapp/beapp-master
pophelp.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/guifunc/pophelp.m
4,248
utf_8
bde4cd43c45ca121c2aa18c04083fe00
% pophelp() - Same as matlab HTHELP but does not crash under windows. % % Usage: >> pophelp( function ); % >> pophelp( function, nonmatlab ); % % Inputs: % function - string for a Matlab function name % (with or without the '.m' extension). % nonmatlab - [0|1], 1 the file is not a Matlab file % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function pophelp( funct, nonmatlab ); if nargin <1 help pophelp; return; end; if nargin <2 nonmatlab = 0; end; if exist('help2html') if length(funct) > 3 && strcmpi(funct(end-3:end), '.txt') web(funct); else pathHelpHTML = fileparts(which('help2html')); if ~isempty(findstr('NFT', pathHelpHTML)), rmpath(pathHelpHTML); end; text1 = help2html(funct); if length(funct) > 4 & strcmpi(funct(1:4), 'pop_') try, text2 = help2html(funct(5:end)); text1 = [text1 '<br><pre>___________________________________________________________________' 10 ... ' ' 10 ... ' The ''pop'' function above calls the eponymous Matlab function below' 10 ... ' and could use some of its optional parameters' 10 ... '___________________________________________________________________</pre><br><br>' text2 ]; catch, end; end; web([ 'text://' text1 ]); end; else if isempty(funct), return; end; doc1 = readfunc(funct, nonmatlab); if length(funct) > 4 & strcmpi(funct(1:4), 'pop_') try, doc2 = readfunc(funct(5:end), nonmatlab); doc1 = { doc1{:} ' _________________________________________________________________ ' ... ' ' ... ' The ''pop'' function above calls the eponymous Matlab function below, ' ... ' which may contain more information for some parameters. '... ' ' ... ' _________________________________________________________________ ' ... ' ' ... doc2{:} }; catch, end; end; textgui(doc1);1000 h = findobj('parent', gcf, 'style', 'slider'); try, icadefs; catch, GUIBUTTONCOLOR = [0.8 0.8 0.8]; GUITEXTCOLOR = 'k'; end; set(h, 'backgroundcolor', GUIBUTTONCOLOR); h = findobj('parent', gcf, 'style', 'pushbutton'); set(h, 'backgroundcolor', GUIBUTTONCOLOR); h = findobj('parent', gca); set(h, 'color', GUITEXTCOLOR); set(gcf, 'color', BACKCOLOR); end; return; function [doc] = readfunc(funct, nonmatlab) doc = {}; if iseeglabdeployed if isempty(find(funct == '.')), funct = [ funct '.m' ]; end; funct = fullfile(eeglabexefolder, 'help', funct); end; if nonmatlab fid = fopen( funct, 'r'); else if findstr( funct, '.m') fid = fopen( funct, 'r'); else fid = fopen( [funct '.m'], 'r'); end; end; if fid == -1 error('File not found'); end; sub = 1; try, if ~isunix, sub = 0; end; catch, end; if nonmatlab str = fgets( fid ); while ~feof(fid) str = deblank(str(1:end-sub)); doc = { doc{:} str(1:end) }; str = fgets( fid ); end; else str = fgets( fid ); while (str(1) == '%') str = deblank(str(1:end-sub)); doc = { doc{:} str(2:end) }; str = fgets( fid ); end; end; fclose(fid);
github
lcnbeapp/beapp-master
errordlg2.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/guifunc/errordlg2.m
1,467
utf_8
710e811cd40d8f506b5264089f50c95c
% errordlg2() - Makes a popup dialog box with the specified message and (optional) % title. % % Usage: % errordlg2(Prompt, Title); % % Example: % errordlg2('Explanation of error','title of error'); % % Input: % Prompt - A text string explaning why the user is seeing this error message. % Title _ A text string that appears in the title bar of the error message. % % Author: Arnaud Delorme, CNL / Salk Institute, 12 August 2002 % % See also: inputdlg2(), questdlg2() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function errordlg2(Prompt, Title); if exist('beep') == 5 beep; else disp(char(7)); end; if nargin <2 Title = 'Error'; end; if ~ismatlab, error(Prompt); end; questdlg2(Prompt, Title, 'OK', 'OK');
github
lcnbeapp/beapp-master
questdlg2.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/guifunc/questdlg2.m
3,133
utf_8
d94e219e87da50c5af28fe1007906abc
% questdlg2() - questdlg function clone with coloring and help for % eeglab(). % % Usage: same as questdlg() % % Warning: % Case of button text and result might be changed by the function % % Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 11 August 2002 % % See also: inputdlg2(), errordlg2(), supergui(), inputgui() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [result] = questdlg2(Prompt,Title,varargin); result = ''; if nargin < 2 help questdlg2; return; end; if isempty(varargin) varargin = { 'Yes' 'No' 'Cancel' 'Yes' }; end; result = varargin{end}; if Prompt(end) == 10, Prompt(end) = []; end; if Prompt(end) == 10, Prompt(end) = []; end; if Prompt(end) == 10, Prompt(end) = []; end; if Prompt(end) == 10, Prompt(end) = []; end; fig = figure('visible', 'off'); set(gcf, 'name', Title); listui = {}; geometry = {}; if ~isempty(find(Prompt == 10)) indlines = find(Prompt == 10); if indlines(1) ~= 1, indlines = [ 0 indlines ]; end; if indlines(end) ~= length(Prompt), indlines = [ indlines length(Prompt)+1 ]; end; for index = 1:length(indlines)-1 geometry{index} = [1]; listui{index} = { 'Style', 'text', 'string' Prompt(indlines(index)+1:indlines(index+1)-1) }; end; else for index = 1:size(Prompt,1) geometry{index} = [1]; listui{index} = { 'Style', 'text', 'string' Prompt(index,:) }; end; end; listui{end+1} = {}; geometry = { geometry{:} 1 ones(1,length(varargin)-1) }; for index = 1:length(varargin)-1 % ignoring default val listui = {listui{:} { 'width',80,'align','center','Style', 'pushbutton', 'string', varargin{index}, 'callback', ['set(gcbf, ''userdata'', ''' varargin{index} ''');'] } }; if strcmp(varargin{index}, varargin{end}) listui{end}{end+1} = 'fontweight'; listui{end}{end+1} = 'bold'; end; end; %cr = length(find(Prompt == char(10)))+1; %if cr == 1 % cr = size(Prompt,1); %end; %cr = cr^(7/); %if cr >= 8, cr = cr-1; end; %if cr >= 4, cr = cr-1; end; %[tmp tmp2 allobj] = supergui( 'fig', fig, 'geomhoriz', geometry, 'geomvert', [cr 1 1], 'uilist', listui, ... [tmp tmp2 allobj] = supergui( 'fig', fig, 'geomhoriz', geometry, 'uilist', listui, ... 'borders', [0.02 0.015 0.08 0.06], 'spacing', [0 0], 'horizontalalignment', 'left', 'adjustbuttonwidth', 'on' ); waitfor( fig, 'userdata'); try, result = get(fig, 'userdata'); close(fig); drawnow; end;
github
lcnbeapp/beapp-master
listdlg2.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/guifunc/listdlg2.m
3,771
utf_8
a0820fcb823bcb9968afa377c5582498
% listdlg2() - listdlg function clone with coloring and help for % eeglab(). % % Usage: same as listdlg() % % Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 16 August 2002 % % See also: inputdlg2(), errordlg2(), supergui(), inputgui() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [vals, okornot, strval] = listdlg2(varargin); if nargin < 2 help listdlg2; return; end; for index = 1:length(varargin) if iscell(varargin{index}), varargin{index} = { varargin{index} }; end; if isstr(varargin{index}), varargin{index} = lower(varargin{index}); end; end; g = struct(varargin{:}); try, g.promptstring; catch, g.promptstring = ''; end; try, g.liststring; catch, error('''liststring'' must be defined'); end; try, g.selectionmode; catch, g.selectionmode = 'multiple'; end; try, g.listsize; catch, g.listsize = []; end; try, g.initialvalue; catch, g.initialvalue = []; end; try, g.name; catch, g.name = ''; end; fig = figure('visible', 'off'); set(gcf, 'name', g.name); if isstr(g.liststring) allstr = g.liststring; else allstr = ''; for index = 1:length(g.liststring) allstr = [ allstr '|' g.liststring{index} ]; end; allstr = allstr(2:end); end; geometry = {[1] [1 1]}; geomvert = [min(length(g.liststring), 10) 1]; if ~strcmpi(g.selectionmode, 'multiple') | ... (iscell(g.liststring) & length(g.liststring) == 1) | ... (isstr (g.liststring) & size (g.liststring,1) == 1 & isempty(find(g.liststring == '|'))) if isempty(g.initialvalue), g.initialvalue = 1; end; minval = 1; maxval = 1; else minval = 0; maxval = 2; end; listui = {{ 'Style', 'listbox', 'tag', 'listboxvals', 'string', allstr, 'max', maxval, 'min', minval } ... { 'Style', 'pushbutton', 'string', 'Cancel', 'callback', ['set(gcbf, ''userdata'', ''cancel'');'] } ... { 'Style', 'pushbutton', 'string', 'Ok' , 'callback', ['set(gcbf, ''userdata'', ''ok'');'] } }; if ~isempty(g.promptstring) geometry = {[1] geometry{:}}; geomvert = [1 geomvert]; listui = { { 'Style', 'text', 'string', g.promptstring } listui{:}}; end; [tmp tmp2 allobj] = supergui( fig, geometry, geomvert, listui{:} ); % assign value to listbox % must be done after creating it % ------------------------------ lstbox = findobj(fig, 'tag', 'listboxvals'); set(lstbox, 'value', g.initialvalue); if ~isempty(g.listsize) pos = get(gcf, 'position'); set(gcf, 'position', [ pos(1:2) g.listsize]); end; h = findobj( 'parent', fig, 'tag', 'listboxvals'); okornot = 0; strval = ''; vals = []; figure(fig); drawnow; waitfor( fig, 'userdata'); try, vals = get(h, 'value'); strval = ''; if iscell(g.liststring) for index = vals strval = [ strval ' ' g.liststring{index} ]; end; else for index = vals strval = [ strval ' ' g.liststring(index,:) ]; end; end; strval = strval(2:end); if strcmp(get(fig, 'userdata'), 'cancel') okornot = 0; else okornot = 1; end; close(fig); drawnow; end;
github
lcnbeapp/beapp-master
finputcheck.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/guifunc/finputcheck.m
9,133
utf_8
fe838fecdd60e76a4006a13c7c1b20e4
% finputcheck() - check Matlab function {'key','value'} input argument pairs % % Usage: >> result = finputcheck( varargin, fieldlist ); % >> [result varargin] = finputcheck( varargin, fieldlist, ... % callingfunc, mode, verbose ); % Input: % varargin - Cell array 'varargin' argument from a function call using 'key', % 'value' argument pairs. See Matlab function 'varargin'. % May also be a structure such as struct(varargin{:}) % fieldlist - A 4-column cell array, one row per 'key'. The first % column contains the key string, the second its type(s), % the third the accepted value range, and the fourth the % default value. Allowed types are 'boolean', 'integer', % 'real', 'string', 'cell' or 'struct'. For example, % {'key1' 'string' { 'string1' 'string2' } 'defaultval_key1'} % {'key2' {'real' 'integer'} { minint maxint } 'defaultval_key2'} % callingfunc - Calling function name for error messages. {default: none}. % mode - ['ignore'|'error'] ignore keywords that are either not specified % in the fieldlist cell array or generate an error. % {default: 'error'}. % verbose - ['verbose', 'quiet'] print information. Default: 'verbose'. % % Outputs: % result - If no error, structure with 'key' as fields and 'value' as % content. If error this output contain the string error. % varargin - residual varagin containing unrecognized input arguments. % Requires mode 'ignore' above. % % Note: In case of error, a string is returned containing the error message % instead of a structure. % % Example (insert the following at the beginning of your function): % result = finputcheck(varargin, ... % { 'title' 'string' [] ''; ... % 'percent' 'real' [0 1] 1 ; ... % 'elecamp' 'integer' [1:10] [] }); % if isstr(result) % error(result); % end % % Note: % The 'title' argument should be a string. {no default value} % The 'percent' argument should be a real number between 0 and 1. {default: 1} % The 'elecamp' argument should be an integer between 1 and 10 (inclusive). % % Now 'g.title' will contain the title arg (if any, else the default ''), etc. % % Author: Arnaud Delorme, CNL / Salk Institute, 10 July 2002 % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 10 July 2002, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [g, varargnew] = finputcheck( vararg, fieldlist, callfunc, mode, verbose ) if nargin < 2 help finputcheck; return; end; if nargin < 3 callfunc = ''; else callfunc = [callfunc ' ' ]; end; if nargin < 4 mode = 'do not ignore'; end; if nargin < 5 verbose = 'verbose'; end; NAME = 1; TYPE = 2; VALS = 3; DEF = 4; SIZE = 5; varargnew = {}; % create structure % ---------------- if ~isempty(vararg) if isstruct(vararg) g = vararg; else for index=1:length(vararg) if iscell(vararg{index}) vararg{index} = {vararg{index}}; end; end; try g = struct(vararg{:}); catch vararg = removedup(vararg, verbose); try g = struct(vararg{:}); catch g = [ callfunc 'error: bad ''key'', ''val'' sequence' ]; return; end; end; end; else g = []; end; for index = 1:size(fieldlist,NAME) % check if present % ---------------- if ~isfield(g, fieldlist{index, NAME}) g = setfield( g, fieldlist{index, NAME}, fieldlist{index, DEF}); end; tmpval = getfield( g, {1}, fieldlist{index, NAME}); % check type % ---------- if ~iscell( fieldlist{index, TYPE} ) res = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}, ... fieldlist{index, VALS}, tmpval, callfunc ); if isstr(res), g = res; return; end; else testres = 0; tmplist = fieldlist; for it = 1:length( fieldlist{index, TYPE} ) if ~iscell(fieldlist{index, VALS}) res{it} = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}{it}, ... fieldlist{index, VALS}, tmpval, callfunc ); else res{it} = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}{it}, ... fieldlist{index, VALS}{it}, tmpval, callfunc ); end; if ~isstr(res{it}), testres = 1; end; end; if testres == 0, g = res{1}; for tmpi = 2:length(res) g = [ g 10 'or ' res{tmpi} ]; end; return; end; end; end; % check if fields are defined % --------------------------- allfields = fieldnames(g); for index=1:length(allfields) if isempty(strmatch(allfields{index}, fieldlist(:, 1)', 'exact')) if ~strcmpi(mode, 'ignore') g = [ callfunc 'error: undefined argument ''' allfields{index} '''']; return; end; varargnew{end+1} = allfields{index}; varargnew{end+1} = getfield(g, {1}, allfields{index}); end; end; function g = fieldtest( fieldname, fieldtype, fieldval, tmpval, callfunc ); NAME = 1; TYPE = 2; VALS = 3; DEF = 4; SIZE = 5; g = []; switch fieldtype case { 'integer' 'real' 'boolean' 'float' }, if ~isnumeric(tmpval) && ~islogical(tmpval) g = [ callfunc 'error: argument ''' fieldname ''' must be numeric' ]; return; end; if strcmpi(fieldtype, 'boolean') if tmpval ~=0 && tmpval ~= 1 g = [ callfunc 'error: argument ''' fieldname ''' must be 0 or 1' ]; return; end; else if strcmpi(fieldtype, 'integer') if ~isempty(fieldval) if (any(isnan(tmpval(:))) && ~any(isnan(fieldval))) ... && (~ismember(tmpval, fieldval)) g = [ callfunc 'error: wrong value for argument ''' fieldname '''' ]; return; end; end; else % real or float if ~isempty(fieldval) && ~isempty(tmpval) if any(tmpval < fieldval(1)) || any(tmpval > fieldval(2)) g = [ callfunc 'error: value out of range for argument ''' fieldname '''' ]; return; end; end; end; end; case 'string' if ~isstr(tmpval) g = [ callfunc 'error: argument ''' fieldname ''' must be a string' ]; return; end; if ~isempty(fieldval) if isempty(strmatch(lower(tmpval), lower(fieldval), 'exact')) g = [ callfunc 'error: wrong value for argument ''' fieldname '''' ]; return; end; end; case 'cell' if ~iscell(tmpval) g = [ callfunc 'error: argument ''' fieldname ''' must be a cell array' ]; return; end; case 'struct' if ~isstruct(tmpval) g = [ callfunc 'error: argument ''' fieldname ''' must be a structure' ]; return; end; case 'function_handle' if ~isa(tmpval, 'function_handle') g = [ callfunc 'error: argument ''' fieldname ''' must be a function handle' ]; return; end; case ''; otherwise, error([ 'finputcheck error: unrecognized type ''' fieldname '''' ]); end; % remove duplicates in the list of parameters % ------------------------------------------- function cella = removedup(cella, verbose) % make sure if all the values passed to unique() are strings, if not, exist %try [tmp indices] = unique_bc(cella(1:2:end)); if length(tmp) ~= length(cella)/2 myfprintf(verbose,'Note: duplicate ''key'', ''val'' parameter(s), keeping the last one(s)\n'); end; cella = cella(sort(union(indices*2-1, indices*2))); %catch % some elements of cella were not string % error('some ''key'' values are not string.'); %end; function myfprintf(verbose, varargin) if strcmpi(verbose, 'verbose') fprintf(varargin{:}); end;
github
lcnbeapp/beapp-master
inputdlg2.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/guifunc/inputdlg2.m
2,497
utf_8
f37d94d5821140270d3242f0d5d06659
% inputdlg2() - inputdlg function clone with coloring and help for % eeglab(). % % Usage: % >> Answer = inputdlg2(Prompt,Title,LineNo,DefAns,funcname); % % Inputs: % Same as inputdlg. Using the optional additionnal funcname parameter % the function will create a help button. The help message will be % displayed using the pophelp() function. % % Output: % Same as inputdlg % % Note: The advantage of this function is that the color of the window % can be changed and that it displays an help button. Edit % supergui to change window options. Also the parameter LineNo % can only be one. % % Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 11 August 2002 % % See also: supergui(), inputgui() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [result] = inputdlg2(Prompt,Title,LineNo,DefAns,funcname); if nargin < 4 help inputdlg2; return; end; if nargin < 5 funcname = ''; end; if length(Prompt) ~= length(DefAns) error('inputdlg2: prompt and default answer cell array must have the smae size'); end; geometry = {}; listgui = {}; % determine if vertical or horizontal % ----------------------------------- geomvert = []; for index = 1:length(Prompt) geomvert = [geomvert size(Prompt{index},1) 1]; % default is vertical geometry end; if all(geomvert == 1) & length(Prompt) > 1 geomvert = []; % horizontal end; for index = 1:length(Prompt) if ~isempty(geomvert) % vertical geometry = { geometry{:} [ 1] [1 ]}; else geometry = { geometry{:} [ 1 0.6 ]}; end; listgui = { listgui{:} { 'Style', 'text', 'string', Prompt{index}} ... { 'Style', 'edit', 'string', DefAns{index} } }; end; result = inputgui(geometry, listgui, ['pophelp(''' funcname ''');'], Title, [], 'normal', geomvert);
github
lcnbeapp/beapp-master
inputgui.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/guifunc/inputgui.m
13,049
utf_8
4d1fcb532034d20d2ab20e9c28f5da11
% inputgui() - A comprehensive gui automatic builder. This function helps % to create GUI very quickly without bothering about the % positions of the elements. After creating a geometry, % elements just place themselves in the predefined % locations. It is especially useful for figures in which % you intend to put text buttons and descriptions. % % Usage: % >> [ outparam ] = inputgui( 'key1', 'val1', 'key2', 'val2', ... ); % >> [ outparam userdat strhalt outstruct] = ... % inputgui( 'key1', 'val1', 'key2', 'val2', ... ); % % Inputs: % 'geom' - cell array of cell array of integer vector. Each cell % array defines the coordinate of a given input in the % following manner: { nb_row nb_col [x_topcorner y_topcorner] % [x_bottomcorner y_bottomcorner] }; % 'geometry' - cell array describing horizontal geometry. This corresponds % to the supergui function input 'geomhoriz' % 'geomvert' - vertical geometry argument, this argument is passed on to % the supergui function % 'uilist' - list of uicontrol lists describing elements properties % { { ui1 }, { ui2 }... }, { 'uiX' } being GUI matlab % uicontrol arguments such as { 'style', 'radiobutton', % 'String', 'hello' }. See Matlab function uicontrol() for details. % 'helpcom' - optional help command % 'helpbut' - text for help button % 'title' - optional figure title % 'userdata' - optional userdata input for the figure % 'mode' - ['normal'|'noclose'|'plot' fignumber]. Either wait for % user to press OK or CANCEL ('normal'), return without % closing window input ('noclose'), only draw the gui ('plot') % or process an existing window which number is given as % input (fignumber). Default is 'normal'. % 'eval' - [string] command to evaluate at the end of the creation % of the GUI but before waiting for user input. % 'screenpos' - see supergui.m help message. % 'skipline' - ['on'|'off'] skip a row before the "OK" and "Cancel" % button. Default is 'on'. % % Output: % outparam - list of outputs. The function scans all lines and % add up an output for each interactive uicontrol, i.e % edit box, radio button, checkbox and listbox. % userdat - 'userdata' value of the figure. % strhalt - the function returns when the 'userdata' field of the % button with the tag 'ok' is modified. This returns the % new value of this field. % outstruct - returns outputs as a structure (only tagged ui controls % are considered). The field name of the structure is % the tag of the ui and contain the ui value or string. % instruct - resturn inputs provided in the same format as 'outstruct' % This allow to compare in/outputs more easy. % % Note: the function also adds three buttons at the bottom of each % interactive windows: 'CANCEL', 'HELP' (if callback command % is provided) and 'OK'. % % Example: % res = inputgui('geometry', { 1 1 }, 'uilist', ... % { { 'style' 'text' 'string' 'Enter a value' } ... % { 'style' 'edit' 'string' '' } }); % % res = inputgui('geom', { {2 1 [0 0] [1 1]} {2 1 [1 0] [1 1]} }, 'uilist', ... % { { 'style' 'text' 'string' 'Enter a value' } ... % { 'style' 'edit' 'string' '' } }); % % Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 1 Feb 2002 % % See also: supergui(), eeglab() % Copyright (C) Arnaud Delorme, CNL/Salk Institute, 27 Jan 2002, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [result, userdat, strhalt, resstruct, instruct] = inputgui( varargin); if nargin < 2 help inputgui; return; end; % decoding input and backward compatibility % ----------------------------------------- if isstr(varargin{1}) options = varargin; else options = { 'geometry' 'uilist' 'helpcom' 'title' 'userdata' 'mode' 'geomvert' }; options = { options{1:length(varargin)}; varargin{:} }; options = options(:)'; end; % checking inputs % --------------- g = finputcheck(options, { 'geom' 'cell' [] {}; ... 'geometry' {'cell','integer'} [] []; ... 'uilist' 'cell' [] {}; ... 'helpcom' { 'string','cell' } { [] [] } ''; ... 'title' 'string' [] ''; ... 'eval' 'string' [] ''; ... 'helpbut' 'string' [] 'Help'; ... 'skipline' 'string' { 'on' 'off' } 'on'; ... 'addbuttons' 'string' { 'on' 'off' } 'on'; ... 'userdata' '' [] []; ... 'getresult' 'real' [] []; ... 'minwidth' 'real' [] 200; ... 'screenpos' '' [] []; ... 'mode' '' [] 'normal'; ... 'geomvert' 'real' [] [] ... }, 'inputgui'); if isstr(g), error(g); end; if isempty(g.getresult) if isstr(g.mode) fig = figure('visible', 'off'); set(fig, 'name', g.title); set(fig, 'userdata', g.userdata); if ~iscell( g.geometry ) oldgeom = g.geometry; g.geometry = {}; for row = 1:length(oldgeom) g.geometry = { g.geometry{:} ones(1, oldgeom(row)) }; end; end % skip a line if strcmpi(g.skipline, 'on'), g.geometry = { g.geometry{:} [1] }; if ~isempty(g.geom) for ind = 1:length(g.geom) g.geom{ind}{2} = g.geom{ind}{2}+1; % add one row end; g.geom = { g.geom{:} {1 g.geom{1}{2} [0 g.geom{1}{2}-2] [1 1] } }; end; g.uilist = { g.uilist{:}, {} }; end; % add buttons if strcmpi(g.addbuttons, 'on'), g.geometry = { g.geometry{:} [1 1 1 1] }; if ~isempty(g.geom) for ind = 1:length(g.geom) g.geom{ind}{2} = g.geom{ind}{2}+1; % add one row end; g.geom = { g.geom{:} ... {4 g.geom{1}{2} [0 g.geom{1}{2}-1] [1 1] }, ... {4 g.geom{1}{2} [1 g.geom{1}{2}-1] [1 1] }, ... {4 g.geom{1}{2} [2 g.geom{1}{2}-1] [1 1] }, ... {4 g.geom{1}{2} [3 g.geom{1}{2}-1] [1 1] } }; end; if ~isempty(g.helpcom) if ~iscell(g.helpcom) g.uilist = { g.uilist{:}, { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', g.helpbut, 'tag', 'help', 'callback', g.helpcom } {} }; else g.uilist = { g.uilist{:}, { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', 'Help gui', 'callback', g.helpcom{1} } }; g.uilist = { g.uilist{:}, { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', 'More help', 'callback', g.helpcom{2} } }; end; else g.uilist = { g.uilist{:}, {} {} }; end; g.uilist = { g.uilist{:}, { 'width' 80 'align' 'right' 'Style', 'pushbutton', 'string', 'Cancel', 'tag' 'cancel' 'callback', 'close gcbf' } }; g.uilist = { g.uilist{:}, { 'width' 80 'align' 'right' 'stickto' 'on' 'Style', 'pushbutton', 'tag', 'ok', 'string', 'OK', 'callback', 'set(gcbo, ''userdata'', ''retuninginputui'');' } }; end; % add the three buttons (CANCEL HELP OK) at the bottom of the GUI % --------------------------------------------------------------- if ~isempty(g.geom) [tmp tmp2 allobj] = supergui( 'fig', fig, 'minwidth', g.minwidth, 'geom', g.geom, 'uilist', g.uilist, 'screenpos', g.screenpos ); elseif isempty(g.geomvert) [tmp tmp2 allobj] = supergui( 'fig', fig, 'minwidth', g.minwidth, 'geomhoriz', g.geometry, 'uilist', g.uilist, 'screenpos', g.screenpos ); else if strcmpi(g.skipline, 'on'), g.geomvert = [g.geomvert(:)' 1]; end; if strcmpi(g.addbuttons, 'on'),g.geomvert = [g.geomvert(:)' 1]; end; [tmp tmp2 allobj] = supergui( 'fig', fig, 'minwidth', g.minwidth, 'geomhoriz', g.geometry, 'uilist', g.uilist, 'screenpos', g.screenpos, 'geomvert', g.geomvert(:)' ); end; else fig = g.mode; set(findobj('parent', fig, 'tag', 'ok'), 'userdata', []); allobj = findobj('parent',fig); allobj = allobj(end:-1:1); end; % evaluate command before waiting? % -------------------------------- if ~isempty(g.eval), eval(g.eval); end; instruct = outstruct(allobj); % Getting default values in the GUI. % create figure and wait for return % --------------------------------- if isstr(g.mode) & (strcmpi(g.mode, 'plot') | strcmpi(g.mode, 'return') ) if strcmpi(g.mode, 'plot') return; % only plot and returns end; else waitfor( findobj('parent', fig, 'tag', 'ok'), 'userdata'); end; else fig = g.getresult; allobj = findobj('parent',fig); allobj = allobj(end:-1:1); end; result = {}; userdat = []; strhalt = ''; resstruct = []; if ~(ishandle(fig)), return; end % Check if figure still exist % output parameters % ----------------- strhalt = get(findobj('parent', fig, 'tag', 'ok'), 'userdata'); [resstruct,result] = outstruct(allobj); % Output parameters userdat = get(fig, 'userdata'); % if nargout >= 4 % resstruct = myguihandles(fig, g); % end; if isempty(g.getresult) && isstr(g.mode) && ( strcmp(g.mode, 'normal') || strcmp(g.mode, 'return') ) close(fig); end; drawnow; % for windows % function for gui res (deprecated) % -------------------- % function g = myguihandles(fig, g) % h = findobj('parent', fig); % if ~isempty(get(h(index), 'tag')) % try, % switch get(h(index), 'style') % case 'edit', g = setfield(g, get(h(index), 'tag'), get(h(index), 'string')); % case { 'value' 'radio' 'checkbox' 'listbox' 'popupmenu' 'radiobutton' }, ... % g = setfield(g, get(h(index), 'tag'), get(h(index), 'value')); % end; % catch, end; % end; function [resstructout, resultout] = outstruct(allobj) counter = 1; resultout = {}; resstructout = []; for index=1:length(allobj) if isnumeric(allobj), currentobj = allobj(index); else currentobj = allobj{index}; end; if isnumeric(currentobj) | ~isprop(currentobj,'GetPropertySpecification') % To allow new object handles try, objstyle = get(currentobj, 'style'); switch lower( objstyle ) case { 'listbox', 'checkbox', 'radiobutton' 'popupmenu' 'radio' } resultout{counter} = get( currentobj, 'value'); if ~isempty(get(currentobj, 'tag')), resstructout = setfield(resstructout, get(currentobj, 'tag'), resultout{counter}); end; counter = counter+1; case 'edit' resultout{counter} = get( currentobj, 'string'); if ~isempty(get(currentobj, 'tag')), resstructout = setfield(resstructout, get(currentobj, 'tag'), resultout{counter}); end; counter = counter+1; end; catch, end; else ps = currentobj.GetPropertySpecification; resultout{counter} = arg_tovals(ps,false); count = 1; while isfield(resstructout, ['propgrid' int2str(count)]) count = count + 1; end; resstructout = setfield(resstructout, ['propgrid' int2str(count)], arg_tovals(ps,false)); end; end;
github
lcnbeapp/beapp-master
ft_channelselection.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_channelselection.m
21,836
utf_8
28496cbe0aca921c174ce4c277f55e6a
function [channel] = ft_channelselection(desired, datachannel, senstype) % FT_CHANNELSELECTION makes a selection of EEG and/or MEG channel labels. % This function translates the user-specified list of channels into channel % labels as they occur in the data. This channel selection procedure can be % used throughout FieldTrip. % % Use as: % channel = ft_channelselection(desired, datachannel) % % You can specify a mixture of real channel labels and of special strings, % or index numbers that will be replaced by the corresponding channel % labels. Channels that are not present in the raw datafile are % automatically removed from the channel list. % % E.g. the input 'channel' can be: % 'all' is replaced by all channels in the datafile % 'gui' a graphical user interface will pop up to select the channels % 'C*' is replaced by all channels that match the wildcard, e.g. C1, C2, C3, ... % '*1' is replaced by all channels that match the wildcard, e.g. C1, P1, F1, ... % 'M*1' is replaced by all channels that match the wildcard, e.g. MEG0111, MEG0131, MEG0131, ... % 'meg' is replaced by all MEG channels (works for CTF, 4D, Neuromag and Yokogawa) % 'megref' is replaced by all MEG reference channels (works for CTF and 4D) % 'meggrad' is replaced by all MEG gradiometer channels (works for Yokogawa and Neuromag-306) % 'megmag' is replaced by all MEG magnetometer channels (works for Yokogawa and Neuromag-306) % 'eeg' is replaced by all recognized EEG channels (this is system dependent) % 'eeg1020' is replaced by 'Fp1', 'Fpz', 'Fp2', 'F7', 'F3', ... % 'eog' is replaced by all recognized EOG channels % 'ecg' is replaced by all recognized ECG channels % 'nirs' is replaced by all channels recognized as NIRS channels % 'emg' is replaced by all channels in the datafile starting with 'EMG' % 'lfp' is replaced by all channels in the datafile starting with 'lfp' % 'mua' is replaced by all channels in the datafile starting with 'mua' % 'spike' is replaced by all channels in the datafile starting with 'spike' % 10 is replaced by the 10th channel in the datafile % % Other channel groups are % 'EEG1010' with approximately 90 electrodes % 'EEG1005' with approximately 350 electrodes % 'EEGCHWILLA' for Dorothee Chwilla's electrode caps (used at the DCC) % 'EEGBHAM' for the 128 channel EEG system used in Birmingham % 'EEGREF' for mastoid and ear electrodes (M1, M2, LM, RM, A1, A2) % 'MZ' for MEG zenith % 'ML' for MEG left % 'MR' for MEG right % 'MLx', 'MRx' and 'MZx' with x=C,F,O,P,T for left/right central, frontal, occipital, parietal and temporal % % You can also exclude channels or channel groups using the following syntax % {'all', '-POz', '-Fp1', -EOG'} % % See also FT_PREPROCESSING, FT_SENSLABEL, FT_MULTIPLOTER, FT_MULTIPLOTTFR, % FT_SINGLEPLOTER, FT_SINGLEPLOTTFR % Note that the order of channels that is returned should correspond with % the order of the channels in the data. % Copyright (C) 2003-2014, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % this is to avoid a recursion loop persistent recursion if isempty(recursion) recursion = false; end if nargin<3 senstype = ft_senstype(datachannel); end if ~iscell(datachannel) if ischar(datachannel) datachannel = {datachannel}; else error('please specify the data channels as a cell-array'); end end if ~ischar(desired) && ~isnumeric(desired) && ~iscell(desired) error('please specify the desired channels as a cell-array or a string'); end % start with the list of desired channels, this will be pruned/expanded channel = desired; if length(datachannel)~=length(unique(datachannel)) warning('discarding non-unique channel names'); sel = false(size(datachannel)); for i=1:length(datachannel) sel(i) = sum(strcmp(datachannel, datachannel{i}))==1; end datachannel = datachannel(sel); end if any(size(channel) == 0) % there is nothing to do if it is empty return end if ~iscell(datachannel) % ensure that a single input argument like 'all' also works datachannel = {datachannel}; end if isnumeric(channel) % remove channels tha fall outside the range channel = channel(channel>=1 & channel<=numel(datachannel)); % change index into channelname channel = datachannel(channel); return end if ~iscell(channel) % ensure that a single input argument like 'all' also works % the case of a vector with channel indices has already been dealt with channel = {channel}; end % ensure that both inputs are column vectors channel = channel(:); datachannel = datachannel(:); % remove channels that occur more than once, this sorts the channels alphabetically [channel, indx] = unique(channel); % undo the sorting, make the order identical to that of the data channels [dum, indx] = sort(indx); channel = channel(indx); [dataindx, chanindx] = match_str(datachannel, channel); if length(chanindx)==length(channel) % there is a perfect match between the channels and the datachannels, only some reordering is needed channel = channel(chanindx); % no need to look at channel groups return end % define the known groups with channel labels labelall = datachannel; label1020 = ft_senslabel('eeg1020'); % use external helper function label1010 = ft_senslabel('eeg1010'); % use external helper function label1005 = ft_senslabel('eeg1005'); % use external helper function labelchwilla = {'Fz', 'Cz', 'Pz', 'F7', 'F8', 'LAT', 'RAT', 'LT', 'RT', 'LTP', 'RTP', 'OL', 'OR', 'FzA', 'Oz', 'F7A', 'F8A', 'F3A', 'F4A', 'F3', 'F4', 'P3', 'P4', 'T5', 'T6', 'P3P', 'P4P'}'; labelbham = {'P9', 'PPO9h', 'PO7', 'PPO5h', 'PPO3h', 'PO5h', 'POO9h', 'PO9', 'I1', 'OI1h', 'O1', 'POO1', 'PO3h', 'PPO1h', 'PPO2h', 'POz', 'Oz', 'Iz', 'I2', 'OI2h', 'O2', 'POO2', 'PO4h', 'PPO4h', 'PO6h', 'POO10h', 'PO10', 'PO8', 'PPO6h', 'PPO10h', 'P10', 'P8', 'TPP9h', 'TP7', 'TTP7h', 'CP5', 'TPP7h', 'P7', 'P5', 'CPP5h', 'CCP5h', 'CP3', 'P3', 'CPP3h', 'CCP3h', 'CP1', 'P1', 'Pz', 'CPP1h', 'CPz', 'CPP2h', 'P2', 'CPP4h', 'CP2', 'CCP4h', 'CP4', 'P4', 'P6', 'CPP6h', 'CCP6h', 'CP6', 'TPP8h', 'TP8', 'TPP10h', 'T7', 'FTT7h', 'FT7', 'FC5', 'FCC5h', 'C5', 'C3', 'FCC3h', 'FC3', 'FC1', 'C1', 'CCP1h', 'Cz', 'FCC1h', 'FCz', 'FFC1h', 'Fz', 'FFC2h', 'FC2', 'FCC2h', 'CCP2h', 'C2', 'C4', 'FCC4h', 'FC4', 'FC6', 'FCC6h', 'C6', 'TTP8h', 'T8', 'FTT8h', 'FT8', 'FT9', 'FFT9h', 'F7', 'FFT7h', 'FFC5h', 'F5', 'AFF7h', 'AF7', 'AF5h', 'AFF5h', 'F3', 'FFC3h', 'F1', 'AF3h', 'Fp1', 'Fpz', 'Fp2', 'AFz', 'AF4h', 'F2', 'FFC4h', 'F4', 'AFF6h', 'AF6h', 'AF8', 'AFF8h', 'F6', 'FFC6h', 'FFT8h', 'F8', 'FFT10h', 'FT10'}; labelref = {'M1', 'M2', 'LM', 'RM', 'A1', 'A2'}'; labeleog = datachannel(strncmp('EOG', datachannel, length('EOG'))); % anything that starts with EOG labeleog = [labeleog(:); {'HEOG', 'VEOG', 'VEOG-L', 'VEOG-R', 'hEOG', 'vEOG', 'Eye_Ver', 'Eye_Hor'}']; % or any of these labelecg = datachannel(strncmp('ECG', datachannel, length('ECG'))); labelemg = datachannel(strncmp('EMG', datachannel, length('EMG'))); labellfp = datachannel(strncmp('lfp', datachannel, length('lfp'))); labelmua = datachannel(strncmp('mua', datachannel, length('mua'))); labelspike = datachannel(strncmp('spike', datachannel, length('spike'))); labelnirs = datachannel(~cellfun(@isempty, regexp(datachannel, sprintf('%s%s', regexptranslate('wildcard','Rx*-Tx*[*]'), '$')))); % use regular expressions to deal with the wildcards labelreg = false(size(datachannel)); findreg = []; for i=1:length(channel) if length(channel{i}) < 1 continue; end if strcmp((channel{i}(1)), '-') % skip channels to be excluded continue; end rexp = sprintf('%s%s%s', '^', regexptranslate('wildcard',channel{i}), '$'); lreg = ~cellfun(@isempty, regexp(datachannel, rexp)); if any(lreg) labelreg = labelreg | lreg; findreg = [findreg; i]; end end if ~isempty(findreg) findreg = unique(findreg); % remove multiple occurances due to multiple wildcards labelreg = datachannel(labelreg); end % initialize all the system-specific variables to empty labelmeg = []; labelmeggrad = []; labelmegref = []; labelmegmag = []; labeleeg = []; switch senstype case {'yokogawa', 'yokogawa160', 'yokogawa160_planar', 'yokogawa64', 'yokogawa64_planar', 'yokogawa440', 'yokogawa440_planar'} % Yokogawa axial gradiometers channels start with AG, hardware planar gradiometer % channels start with PG, magnetometers start with M megax = strncmp('AG', datachannel, length('AG')); megpl = strncmp('PG', datachannel, length('PG')); megmag = strncmp('M', datachannel, length('M' )); megind = logical( megax + megpl + megmag); labelmeg = datachannel(megind); labelmegmag = datachannel(megmag); labelmeggrad = datachannel(megax | megpl); case {'ctf64'} labelml = datachannel(~cellfun(@isempty, regexp(datachannel, '^SL'))); % left MEG channels labelmr = datachannel(~cellfun(@isempty, regexp(datachannel, '^SR'))); % right MEG channels labelmeg = cat(1, labelml, labelmr); labelmegref = [datachannel(strncmp('B' , datachannel, 1)); datachannel(strncmp('G' , datachannel, 1)); datachannel(strncmp('P' , datachannel, 1)); datachannel(strncmp('Q' , datachannel, 1)); datachannel(strncmp('R' , datachannel, length('G' )))]; case {'ctf', 'ctf275', 'ctf151', 'ctf275_planar', 'ctf151_planar'} % all CTF MEG channels start with "M" % all CTF reference channels start with B, G, P, Q or R % all CTF EEG channels start with "EEG" labelmeg = datachannel(strncmp('M' , datachannel, length('M' ))); labelmegref = [datachannel(strncmp('B' , datachannel, 1)); datachannel(strncmp('G' , datachannel, 1)); datachannel(strncmp('P' , datachannel, 1)); datachannel(strncmp('Q' , datachannel, 1)); datachannel(strncmp('R' , datachannel, length('G' )))]; labeleeg = datachannel(strncmp('EEG', datachannel, length('EEG'))); % Not sure whether this should be here or outside the switch or % whether these specifications should be supported for systems % other than CTF. labelmz = datachannel(strncmp('MZ' , datachannel, length('MZ' ))); % central MEG channels labelml = datachannel(strncmp('ML' , datachannel, length('ML' ))); % left MEG channels labelmr = datachannel(strncmp('MR' , datachannel, length('MR' ))); % right MEG channels labelmlc = datachannel(strncmp('MLC', datachannel, length('MLC'))); labelmlf = datachannel(strncmp('MLF', datachannel, length('MLF'))); labelmlo = datachannel(strncmp('MLO', datachannel, length('MLO'))); labelmlp = datachannel(strncmp('MLP', datachannel, length('MLP'))); labelmlt = datachannel(strncmp('MLT', datachannel, length('MLT'))); labelmrc = datachannel(strncmp('MRC', datachannel, length('MRC'))); labelmrf = datachannel(strncmp('MRF', datachannel, length('MRF'))); labelmro = datachannel(strncmp('MRO', datachannel, length('MRO'))); labelmrp = datachannel(strncmp('MRP', datachannel, length('MRP'))); labelmrt = datachannel(strncmp('MRT', datachannel, length('MRT'))); labelmzc = datachannel(strncmp('MZC', datachannel, length('MZC'))); labelmzf = datachannel(strncmp('MZF', datachannel, length('MZF'))); labelmzo = datachannel(strncmp('MZO', datachannel, length('MZO'))); labelmzp = datachannel(strncmp('MZP', datachannel, length('MZP'))); case {'bti', 'bti248', 'bti248grad', 'bti148', 'bti248_planar', 'bti148_planar'} % all 4D-BTi MEG channels start with "A" % all 4D-BTi reference channels start with M or G labelmeg = datachannel(myregexp('^A[0-9]+$', datachannel)); labelmegref = [datachannel(myregexp('^M[CLR][xyz][aA]*$', datachannel)); datachannel(myregexp('^G[xyz][xyz]A$', datachannel)); datachannel(myregexp('^M[xyz][aA]*$', datachannel))]; labelmegrefa = datachannel(~cellfun(@isempty,strfind(datachannel, 'a'))); labelmegrefc = datachannel(strncmp('MC', datachannel, 2)); labelmegrefg = datachannel(myregexp('^G[xyz][xyz]A$', datachannel)); labelmegrefl = datachannel(strncmp('ML', datachannel, 2)); labelmegrefr = datachannel(strncmp('MR', datachannel, 2)); labelmegrefm = datachannel(myregexp('^M[xyz][aA]*$', datachannel)); case {'neuromag122' 'neuromag122alt'} % all neuromag MEG channels start with MEG % all neuromag EEG channels start with EEG labelmeg = datachannel(strncmp('MEG', datachannel, length('MEG'))); labeleeg = datachannel(strncmp('EEG', datachannel, length('EEG'))); case {'neuromag306' 'neuromag306alt'} % all neuromag MEG channels start with MEG % all neuromag EEG channels start with EEG % all neuromag-306 gradiometers follow pattern MEG*2,MEG*3 % all neuromag-306 magnetometers follow pattern MEG*1 labelmeg = datachannel(strncmp('MEG', datachannel, length('MEG'))); labeleeg = datachannel(strncmp('EEG', datachannel, length('EEG'))); labelmeggrad = labelmeg(~cellfun(@isempty, regexp(labelmeg, '^MEG.*[23]$'))); labelmegmag = labelmeg(~cellfun(@isempty, regexp(labelmeg, '^MEG.*1$'))); case {'ant128', 'biosemi64', 'biosemi128', 'biosemi256', 'egi32', 'egi64', 'egi128', 'egi256', 'eeg1020', 'eeg1010', 'eeg1005', 'ext1020'} % use an external helper function to define the list with EEG channel names labeleeg = ft_senslabel(ft_senstype(datachannel)); case {'itab153' 'itab28' 'itab28_old'} % all itab MEG channels start with MAG labelmeg = datachannel(strncmp('MAG', datachannel, length('MAG'))); end % switch ft_senstype % figure out if there are bad channels or channel groups that should be excluded findbadchannel = strncmp('-', channel, length('-')); % bad channels start with '-' badchannel = channel(findbadchannel); if ~isempty(badchannel) for i=1:length(badchannel) badchannel{i} = badchannel{i}(2:end); % remove the '-' from the channel label end badchannel = ft_channelselection(badchannel, datachannel); % support exclusion of channel groups end % determine if any of the known groups is mentioned in the channel list findall = find(strcmp(channel, 'all')); % findreg (for the wildcards) is dealt with in the channel group specification above findmeg = find(strcmpi(channel, 'MEG')); findemg = find(strcmpi(channel, 'EMG')); findecg = find(strcmpi(channel, 'ECG')); findeeg = find(strcmpi(channel, 'EEG')); findeeg1020 = find(strcmpi(channel, 'EEG1020')); findeeg1010 = find(strcmpi(channel, 'EEG1010')); findeeg1005 = find(strcmpi(channel, 'EEG1005')); findeegchwilla = find(strcmpi(channel, 'EEGCHWILLA')); findeegbham = find(strcmpi(channel, 'EEGBHAM')); findeegref = find(strcmpi(channel, 'EEGREF')); findmegref = find(strcmpi(channel, 'MEGREF')); findmeggrad = find(strcmpi(channel, 'MEGGRAD')); findmegmag = find(strcmpi(channel, 'MEGMAG')); findmegrefa = find(strcmpi(channel, 'MEGREFA')); findmegrefc = find(strcmpi(channel, 'MEGREFC')); findmegrefg = find(strcmpi(channel, 'MEGREFG')); findmegrefl = find(strcmpi(channel, 'MEGREFL')); findmegrefr = find(strcmpi(channel, 'MEGREFR')); findmegrefm = find(strcmpi(channel, 'MEGREFM')); findeog = find(strcmpi(channel, 'EOG')); findmz = find(strcmp(channel, 'MZ' )); findml = find(strcmp(channel, 'ML' )); findmr = find(strcmp(channel, 'MR' )); findmlc = find(strcmp(channel, 'MLC')); findmlf = find(strcmp(channel, 'MLF')); findmlo = find(strcmp(channel, 'MLO')); findmlp = find(strcmp(channel, 'MLP')); findmlt = find(strcmp(channel, 'MLT')); findmrc = find(strcmp(channel, 'MRC')); findmrf = find(strcmp(channel, 'MRF')); findmro = find(strcmp(channel, 'MRO')); findmrp = find(strcmp(channel, 'MRP')); findmrt = find(strcmp(channel, 'MRT')); findmzc = find(strcmp(channel, 'MZC')); findmzf = find(strcmp(channel, 'MZF')); findmzo = find(strcmp(channel, 'MZO')); findmzp = find(strcmp(channel, 'MZP')); findnirs = find(strcmpi(channel, 'NIRS')); findlfp = find(strcmpi(channel, 'lfp')); findmua = find(strcmpi(channel, 'mua')); findspike = find(strcmpi(channel, 'spike')); findgui = find(strcmpi(channel, 'gui')); % remove any occurences of groups in the channel list channel([ findall findreg findmeg findemg findecg findeeg findeeg1020 findeeg1010 findeeg1005 findeegchwilla findeegbham findeegref findmegref findmeggrad findmegmag findeog findmz findml findmr findmlc findmlf findmlo findmlp findmlt findmrc findmrf findmro findmrp findmrt findmzc findmzf findmzo findmzp findlfp findmua findspike findnirs findgui ]) = []; % add the full channel labels to the channel list if findall, channel = [channel; labelall]; end if findreg, channel = [channel; labelreg]; end if findmeg, channel = [channel; labelmeg]; end if findecg, channel = [channel; labelecg]; end if findemg, channel = [channel; labelemg]; end if findeeg, channel = [channel; labeleeg]; end if findeeg1020, channel = [channel; label1020]; end if findeeg1010, channel = [channel; label1010]; end if findeeg1005, channel = [channel; label1005]; end if findeegchwilla, channel = [channel; labelchwilla]; end if findeegbham, channel = [channel; labelbham]; end if findeegref, channel = [channel; labelref]; end if findmegref, channel = [channel; labelmegref]; end if findmeggrad, channel = [channel; labelmeggrad]; end if findmegmag, channel = [channel; labelmegmag]; end if findmegrefa, channel = [channel; labelmegrefa]; end if findmegrefc, channel = [channel; labelmegrefc]; end if findmegrefg, channel = [channel; labelmegrefg]; end if findmegrefl, channel = [channel; labelmegrefl]; end if findmegrefr, channel = [channel; labelmegrefr]; end if findmegrefm, channel = [channel; labelmegrefm]; end if findeog, channel = [channel; labeleog]; end if findmz , channel = [channel; labelmz ]; end if findml , channel = [channel; labelml ]; end if findmr , channel = [channel; labelmr ]; end if findmlc, channel = [channel; labelmlc]; end if findmlf, channel = [channel; labelmlf]; end if findmlo, channel = [channel; labelmlo]; end if findmlp, channel = [channel; labelmlp]; end if findmlt, channel = [channel; labelmlt]; end if findmrc, channel = [channel; labelmrc]; end if findmrf, channel = [channel; labelmrf]; end if findmro, channel = [channel; labelmro]; end if findmrp, channel = [channel; labelmrp]; end if findmrt, channel = [channel; labelmrt]; end if findmzc, channel = [channel; labelmzc]; end if findmzf, channel = [channel; labelmzf]; end if findmzo, channel = [channel; labelmzo]; end if findmzp, channel = [channel; labelmzp]; end if findlfp, channel = [channel; labellfp]; end if findmua, channel = [channel; labelmua]; end if findspike, channel = [channel; labelspike]; end if findnirs, channel = [channel; labelnirs]; end % remove channel labels that have been excluded by the user badindx = match_str(channel, badchannel); channel(badindx) = []; % remove channel labels that are not present in the data chanindx = match_str(channel, datachannel); channel = channel(chanindx); if findgui indx = select_channel_list(datachannel, match_str(datachannel, channel), 'Select channels'); channel = datachannel(indx); end % remove channels that occur more than once, this sorts the channels alphabetically channel = unique(channel); if isempty(channel) && ~recursion % try whether only lowercase channel labels makes a difference recursion = true; channel = ft_channelselection(desired, lower(datachannel)); recursion = false; % undo the conversion to lowercase, this sorts the channels alphabetically [c, ia, ib] = intersect(channel, lower(datachannel)); channel = datachannel(ib); end if isempty(channel) && ~recursion % try whether only uppercase channel labels makes a difference recursion = true; channel = ft_channelselection(desired, upper(datachannel)); recursion = false; % undo the conversion to uppercase, this sorts the channels alphabetically [c, ia, ib] = intersect(channel, lower(datachannel)); channel = datachannel(ib); end % undo the sorting, make the order identical to that of the data channels [tmp, indx] = match_str(datachannel, channel); channel = channel(indx); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function match = myregexp(pat, list) match = false(size(list)); for i=1:numel(list) match(i) = ~isempty(regexp(list{i}, pat, 'once')); end
github
lcnbeapp/beapp-master
ft_prepare_layout.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_prepare_layout.m
41,723
utf_8
f9b5585b829110b574694613d0a47fab
function [layout, cfg] = ft_prepare_layout(cfg, data) % FT_PREPARE_LAYOUT loads or creates a 2-D layout of the channel locations. % This layout is required for plotting the topographical distribution of % the potential or field distribution, or for plotting timecourses in a % topographical arrangement. % % Use as % layout = ft_prepare_layout(cfg, data) % % There are several ways in which a 2-D layout can be made: it can be read % directly from a *.mat file containing a variable 'lay', it can be created % based on 3-D electrode or gradiometer positions in the configuration or % in the data, or it can be created based on the specification of an % electrode or gradiometer file. Layouts can also come from an ASCII *.lay % file, but this type of layout is no longer recommended. % % You can specify any one of the following configuration options % cfg.layout filename containg the layout (.mat or .lay file) % can also be a layout structure, which is simply % returned as-is (see below for details) % cfg.rotate number, rotation around the z-axis in degrees (default = [], which means automatic) % cfg.projection string, 2D projection method can be 'stereographic', 'orthographic', % 'polar', 'gnomic' or 'inverse' (default = 'polar') % cfg.elec structure with electrode definition, or % cfg.elecfile filename containing electrode definition % cfg.grad structure with gradiometer definition, or % cfg.gradfile filename containing gradiometer definition % cfg.opto structure with optode structure definition, or % cfg.optofile filename containing optode structure definition % cfg.output filename (ending in .mat or .lay) to which the layout % will be written (default = []) % cfg.montage 'no' or a montage structure (default = 'no') % cfg.image filename, use an image to construct a layout (e.g. useful for ECoG grids) % cfg.bw if an image is used and bw = 1 transforms the image in % black and white (default = 0, do not transform) % cfg.overlap string, how to deal with overlapping channels when % layout is constructed from a sensor configuration % structure (can be 'shift' (shift the positions in 2D % space to remove the overlap (default)), 'keep' (don't % shift, retain the overlap), 'no' (throw error when % overlap is present)) % cfg.skipscale 'yes' or 'no', whether the scale should be included in the layout or not (default = 'no') % cfg.skipcomnt 'yes' or 'no', whether the comment should be included in the layout or not (default = 'no') % % Alternatively the layout can be constructed from either % data.elec structure with electrode positions % data.grad structure with gradiometer definition % data.opto structure with optode structure definition % % Alternatively you can specify the following layouts which will be % generated for all channels present in the data. Note that these layouts % are suitable for multiplotting, but not for topoplotting. % cfg.layout = 'ordered' will give you a NxN ordered layout % cfg.layout = 'vertical' will give you a Nx1 ordered layout % cfg.layout = 'butterfly' will give you a layout with all channels on top of each other % cfg.layout = 'circular' will distribute the channels on a circle % % The output layout structure will contain the following fields % layout.label = Nx1 cell-array with channel labels % layout.pos = Nx2 matrix with channel positions % layout.width = Nx1 vector with the width of each box for multiplotting % layout.height = Nx1 matrix with the height of each box for multiplotting % layout.mask = optional cell-array with line segments that determine the area for topographic interpolation % layout.outline = optional cell-array with line segments that represent % the head, nose, ears, sulci or other anatomical features % % See also FT_TOPOPLOTER, FT_TOPOPLOTTFR, FT_MULTIPLOTER, FT_MULTIPLOTTFR, FT_PLOT_LAY % undocumented and non-recommended option (for SPM only) % cfg.style string, '2d' or '3d' (default = '2d') % Copyright (C) 2007-2013, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble loadvar data ft_preamble provenance data % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % the data can be passed as input argument or can be read from disk hasdata = exist('data', 'var'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % basic check/initialization of input arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~hasdata data = struct([]); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % set default configuration options %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% cfg.rotate = ft_getopt(cfg, 'rotate', []); % [] => rotation is determined based on the type of sensors cfg.style = ft_getopt(cfg, 'style', '2d'); cfg.projection = ft_getopt(cfg, 'projection', 'polar'); cfg.layout = ft_getopt(cfg, 'layout', []); cfg.grad = ft_getopt(cfg, 'grad', []); cfg.elec = ft_getopt(cfg, 'elec', []); cfg.opto = ft_getopt(cfg, 'opto', []); cfg.gradfile = ft_getopt(cfg, 'gradfile', []); cfg.elecfile = ft_getopt(cfg, 'elecfile', []); cfg.optofile = ft_getopt(cfg, 'optofile', []); cfg.output = ft_getopt(cfg, 'output', []); cfg.feedback = ft_getopt(cfg, 'feedback', 'no'); cfg.montage = ft_getopt(cfg, 'montage', 'no'); cfg.image = ft_getopt(cfg, 'image', []); cfg.mesh = ft_getopt(cfg, 'mesh', []); % experimental, should only work with meshes defined in 2D cfg.bw = ft_getopt(cfg, 'bw', 0); cfg.channel = ft_getopt(cfg, 'channel', 'all'); cfg.skipscale = ft_getopt(cfg, 'skipscale', 'no'); cfg.skipcomnt = ft_getopt(cfg, 'skipcomnt', 'no'); cfg.overlap = ft_getopt(cfg, 'overlap', 'shift'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % try to generate the layout structure %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% skipscale = strcmp(cfg.skipscale, 'yes'); % in general a scale is desired skipcomnt = strcmp(cfg.skipcomnt, 'yes'); % in general a comment desired if isa(cfg.layout, 'config') % convert the nested config-object back into a normal structure cfg.layout = struct(cfg.layout); end % ensure that there is a label field in the data, which is needed for % ordered/vertical/butterfly modes if hasdata && ~isfield(data, 'label') && isfield(data, 'labelcmb') data.label = unique(data.labelcmb(:)); end % check whether cfg.layout already contains a valid layout structure (this can % happen when higher level plotting functions are called with cfg.layout set to % a layout structure) if isstruct(cfg.layout) && isfield(cfg.layout, 'pos') && isfield(cfg.layout, 'label') && isfield(cfg.layout, 'width') && isfield(cfg.layout, 'height') layout = cfg.layout; elseif isstruct(cfg.layout) && isfield(cfg.layout, 'pos') && isfield(cfg.layout, 'label') && (~isfield(cfg.layout, 'width') || ~isfield(cfg.layout, 'height')) layout = cfg.layout; % add width and height for multiplotting d = dist(layout.pos'); nchans = length(layout.label); for i=1:nchans d(i,i) = inf; % exclude the diagonal end mindist = min(d(:)); layout.width = ones(nchans,1) * mindist * 0.8; layout.height = ones(nchans,1) * mindist * 0.6; elseif isequal(cfg.layout, 'circular') rho = ft_getopt(cfg, 'rho', []); if hasdata && ~isempty(data) % look at the data to determine the overlapping channels cfg.channel = ft_channelselection(cfg.channel, data.label); chanindx = match_str(data.label, cfg.channel); nchan = length(data.label(chanindx)); layout.label = data.label(chanindx); else assert(iscell(cfg.channel), 'cfg.channel should be a valid set of channels'); nchan = length(cfg.channel); layout.label = cfg.channel; end if isempty(rho) % do an equally spaced layout, starting at 12 o'clock, going clockwise rho = linspace(0,1,nchan+1); rho = 2.*pi.*rho(1:end-1); else if numel(rho) ~= nchan error('the number of elements in the polar angle vector should be equal to the number of channels'); end % convert to radians rho = 2.*pi.*rho./360; end x = sin(rho); y = cos(rho); layout.pos = [x(:) y(:)]; layout.width = ones(nchan,1) * 0.01; layout.height = ones(nchan,1) * 0.01; layout.mask = {}; layout.outline = {}; skipscale = true; % a scale is not desired skipcomnt = true; % a comment is initially not desired, or at least requires more thought elseif isequal(cfg.layout, 'butterfly') if hasdata && ~isempty(data) % look at the data to determine the overlapping channels cfg.channel = ft_channelselection(cfg.channel, data.label); chanindx = match_str(data.label, cfg.channel); nchan = length(data.label(chanindx)); layout.label = data.label(chanindx); else assert(iscell(cfg.channel), 'cfg.channel should be a valid set of channels'); nchan = length(cfg.channel); layout.label = cfg.channel; end layout.pos = zeros(nchan,2); % centered at (0,0) layout.width = ones(nchan,1) * 1.0; layout.height = ones(nchan,1) * 1.0; layout.mask = {}; layout.outline = {}; skipscale = true; % a scale is not desired skipcomnt = true; % a comment is initially not desired, or at least requires more thought elseif isequal(cfg.layout, 'vertical') if hasdata && ~isempty(data) % look at the data to determine the overlapping channels data = ft_checkdata(data); originalorder = cfg.channel; cfg.channel = ft_channelselection(cfg.channel, data.label); if iscell(originalorder) && length(originalorder)==length(cfg.channel) % try to keep the order identical to that specified in the configuration [sel1, sel2] = match_str(originalorder, cfg.channel); % re-order them according to the cfg specified by the user cfg.channel = cfg.channel(sel2); end assert(iscell(cfg.channel), 'cfg.channel should be a valid set of channels'); nchan = length(cfg.channel); layout.label = cfg.channel; else assert(iscell(cfg.channel), 'cfg.channel should be a valid set of channels'); nchan = length(cfg.channel); layout.label = cfg.channel; end for i=1:(nchan+2) x = 0.5; y = 1-i/(nchan+1+2); layout.pos (i,:) = [x y]; layout.width (i,1) = 0.9; layout.height(i,1) = 0.9 * 1/(nchan+1+2); if i==(nchan+1) layout.label{i} = 'SCALE'; elseif i==(nchan+2) layout.label{i} = 'COMNT'; end end layout.mask = {}; layout.outline = {}; elseif any(strcmp(cfg.layout, {'1column', '2column', '3column', '4column', '5column', '6column', '7column', '8column', '9column'})) % it can be 2column, 3column, etcetera % note that this code (in combination with the code further down) fails for 1column if hasdata && ~isempty(data) % look at the data to determine the overlapping channels data = ft_checkdata(data); originalorder = cfg.channel; cfg.channel = ft_channelselection(cfg.channel, data.label); if iscell(originalorder) && length(originalorder)==length(cfg.channel) % try to keep the order identical to that specified in the configuration [sel1, sel2] = match_str(originalorder, cfg.channel); % re-order them according to the cfg specified by the user cfg.channel = cfg.channel(sel2); end assert(iscell(cfg.channel), 'cfg.channel should be a valid set of channels'); nchan = length(cfg.channel); layout.label = cfg.channel; else assert(iscell(cfg.channel), 'cfg.channel should be a valid set of channels'); nchan = length(cfg.channel); layout.label = cfg.channel; end ncol = find(strcmp(cfg.layout, {'1column', '2column', '3column', '4column', '5column', '6column', '7column', '8column', '9column'})); nrow = ceil(nchan/ncol); k = 0; for i=1:ncol for j=1:nrow k = k+1; if k>nchan continue end x = i/ncol - 1/(ncol*2); y = 1-j/(nrow+1); layout.pos (k,:) = [x y]; layout.width (k,1) = 0.85/ncol; layout.height(k,1) = 0.9 * 1/(nrow+1); end end layout.mask = {}; layout.outline = {}; skipscale = true; % a scale is not desired skipcomnt = true; % a comment is initially not desired, or at least requires more thought elseif isequal(cfg.layout, 'ordered') if hasdata && ~isempty(data) % look at the data to determine the overlapping channels data = ft_checkdata(data); cfg.channel = ft_channelselection(cfg.channel, data.label); chanindx = match_str(data.label, cfg.channel); nchan = length(data.label(chanindx)); layout.label = data.label(chanindx); else assert(iscell(cfg.channel), 'cfg.channel should be a valid set of channels'); nchan = length(cfg.channel); layout.label = cfg.channel; end ncol = ceil(sqrt(nchan))+1; nrow = ceil(sqrt(nchan))+1; k = 0; for i=1:nrow for j=1:ncol k = k+1; if k<=nchan x = (j-1)/ncol; y = (nrow-i-1)/nrow; layout.pos(k,:) = [x y]; layout.width(k,1) = 0.8 * 1/ncol; layout.height(k,1) = 0.8 * 1/nrow; end end end layout.label{end+1} = 'SCALE'; layout.width(end+1) = 0.8 * 1/ncol; layout.height(end+1) = 0.8 * 1/nrow; x = (ncol-2)/ncol; y = 0/nrow; layout.pos(end+1,:) = [x y]; layout.label{end+1} = 'COMNT'; layout.width(end+1) = 0.8 * 1/ncol; layout.height(end+1) = 0.8 * 1/nrow; x = (ncol-1)/ncol; y = 0/nrow; layout.pos(end+1,:) = [x y]; % try to generate layout from other configuration options elseif ischar(cfg.layout) % layout file name specified if isempty(strfind(cfg.layout, '.')) cfg.layout = [cfg.layout '.mat']; if exist(cfg.layout, 'file') fprintf('layout file without .mat (or .lay) extension specified, appending .mat\n'); layout = ft_prepare_layout(cfg); return; else cfg.layout = [cfg.layout(1:end-3) 'lay']; layout = ft_prepare_layout(cfg); return; end elseif ft_filetype(cfg.layout, 'matlab') fprintf('reading layout from file %s\n', cfg.layout); if ~exist(cfg.layout, 'file') error('the specified layout file %s was not found', cfg.layout); end tmp = load(cfg.layout, 'lay*'); if isfield(tmp, 'layout') layout = tmp.layout; elseif isfield(tmp, 'lay') layout = tmp.lay; else error('mat file does not contain a layout'); end elseif ft_filetype(cfg.layout, 'layout') if exist(cfg.layout, 'file') fprintf('reading layout from file %s\n', cfg.layout); layout = readlay(cfg.layout); else ft_warning(sprintf('layout file %s was not found on your path, attempting to use a similarly named .mat file instead',cfg.layout)); cfg.layout = [cfg.layout(1:end-3) 'mat']; layout = ft_prepare_layout(cfg); return; end elseif ~ft_filetype(cfg.layout, 'layout') % assume that cfg.layout is an electrode file fprintf('creating layout from electrode file %s\n', cfg.layout); layout = sens2lay(ft_read_sens(cfg.layout), cfg.rotate, cfg.projection, cfg.style, cfg.overlap); end elseif ischar(cfg.elecfile) fprintf('creating layout from electrode file %s\n', cfg.elecfile); layout = sens2lay(ft_read_sens(cfg.elecfile), cfg.rotate, cfg.projection, cfg.style, cfg.overlap); elseif ~isempty(cfg.elec) && isstruct(cfg.elec) fprintf('creating layout from cfg.elec\n'); layout = sens2lay(cfg.elec, cfg.rotate, cfg.projection, cfg.style, cfg.overlap); elseif isfield(data, 'elec') && isstruct(data.elec) fprintf('creating layout from data.elec\n'); data = ft_checkdata(data); layout = sens2lay(data.elec, cfg.rotate, cfg.projection, cfg.style, cfg.overlap); elseif ischar(cfg.gradfile) fprintf('creating layout from gradiometer file %s\n', cfg.gradfile); layout = sens2lay(ft_read_sens(cfg.gradfile), cfg.rotate, cfg.projection, cfg.style, cfg.overlap); elseif ~isempty(cfg.grad) && isstruct(cfg.grad) fprintf('creating layout from cfg.grad\n'); layout = sens2lay(cfg.grad, cfg.rotate, cfg.projection, cfg.style, cfg.overlap); elseif isfield(data, 'grad') && isstruct(data.grad) fprintf('creating layout from data.grad\n'); data = ft_checkdata(data); layout = sens2lay(data.grad, cfg.rotate, cfg.projection, cfg.style, cfg.overlap); elseif ischar(cfg.optofile) fprintf('creating layout from optode file %s\n', cfg.optofile); opto = ft_read_sens(cfg.optofile); if (hasdata) layout = opto2lay(opto, data.label); else layout = opto2lay(opto, opto.label); end elseif ~isempty(cfg.opto) && isstruct(cfg.opto) fprintf('creating layout from cfg.opto\n'); opto = cfg.opto; if (hasdata) layout = opto2lay(opto, data.label); else layout = opto2lay(opto, opto.label); end; elseif isfield(data, 'opto') && isstruct(data.opto) fprintf('creating layout from data.opto\n'); opto = data.opto; if (hasdata) layout = opto2lay(opto, data.label); else layout = opto2lay(opto, opto.label); end; elseif (~isempty(cfg.image) || ~isempty(cfg.mesh)) && isempty(cfg.layout) % deal with image file if ~isempty(cfg.image) fprintf('reading background image from %s\n', cfg.image); [p,f,e] = fileparts(cfg.image); switch e case '.mat' tmp = load(cfg.image); fnames = fieldnames(tmp); if numel(fnames)~=1 error('there is not just a single variable in %s', cfg.image); else img = tmp.(fname{1}); end otherwise img = imread(cfg.image); end img = flipdim(img, 1); % in combination with "axis xy" figure bw = cfg.bw; if bw % convert to greyscale image img = mean(img, 3); imagesc(img); colormap gray else % plot as RGB image image(img); end elseif ~isempty(cfg.mesh) if isfield(cfg.mesh, 'sulc') ft_plot_mesh(cfg.mesh, 'edgecolor','none','vertexcolor',cfg.mesh.sulc);colormap gray; else ft_plot_mesh(cfg.mesh, 'edgecolor','none'); end end hold on axis equal axis off axis xy % get the electrode positions pos = zeros(0,2); electrodehelp = [ ... '-----------------------------------------------------\n' ... 'specify electrode locations\n' ... 'press the right mouse button to add another electrode\n' ... 'press backspace on the keyboard to remove the last electrode\n' ... 'press "q" on the keyboard to continue\n' ... ]; again = 1; while again fprintf(electrodehelp) disp(round(pos)); % values are integers/pixels try [x, y, k] = ginput(1); catch % this happens if the figure is closed return; end switch k case 1 pos = cat(1, pos, [x y]); % add it to the figure plot(x, y, 'b.'); plot(x, y, 'yo'); case 8 if size(pos,1)>0 % remove the last point pos = pos(1:end-1,:); % completely redraw the figure cla if ~isempty(cfg.image) h = image(img); else h = ft_plot_mesh(cfg.mesh,'edgecolor','none','vertexcolor',cfg.mesh.sulc); end hold on axis equal axis off plot(pos(:,1), pos(:,2), 'b.'); plot(pos(:,1), pos(:,2), 'yo'); end case 'q' again = 0; otherwise warning('invalid button (%d)', k); end end % get the mask outline polygon = {}; thispolygon = 1; polygon{thispolygon} = zeros(0,2); maskhelp = [ ... '------------------------------------------------------------------------\n' ... 'specify polygons for masking the topgraphic interpolation\n' ... 'press the right mouse button to add another point to the current polygon\n' ... 'press backspace on the keyboard to remove the last point\n' ... 'press "c" on the keyboard to close this polygon and start with another\n' ... 'press "q" on the keyboard to continue\n' ... ]; again = 1; while again fprintf(maskhelp); fprintf('\n'); for i=1:length(polygon) fprintf('polygon %d has %d points\n', i, size(polygon{i},1)); end try [x, y, k] = ginput(1); catch % this happens if the figure is closed return; end switch k case 1 polygon{thispolygon} = cat(1, polygon{thispolygon}, [x y]); % add the last line segment to the figure if size(polygon{thispolygon},1)>1 x = polygon{i}([end-1 end],1); y = polygon{i}([end-1 end],2); end plot(x, y, 'g.-'); case 8 % backspace if size(polygon{thispolygon},1)>0 % remove the last point polygon{thispolygon} = polygon{thispolygon}(1:end-1,:); % completely redraw the figure cla if ~isempty(cfg.image) h = image(img); else h = ft_plot_mesh(cfg.mesh,'edgecolor','none','vertexcolor',cfg.mesh.sulc); end hold on axis equal axis off % plot the electrode positions plot(pos(:,1), pos(:,2), 'b.'); plot(pos(:,1), pos(:,2), 'yo'); for i=1:length(polygon) x = polygon{i}(:,1); y = polygon{i}(:,2); if i~=thispolygon % close the polygon in the figure x(end) = x(1); y(end) = y(1); end plot(x, y, 'g.-'); end end case 'c' if size(polygon{thispolygon},1)>0 % close the polygon polygon{thispolygon}(end+1,:) = polygon{thispolygon}(1,:); % close the polygon in the figure x = polygon{i}([end-1 end],1); y = polygon{i}([end-1 end],2); plot(x, y, 'g.-'); % switch to the next polygon thispolygon = thispolygon + 1; polygon{thispolygon} = zeros(0,2); end case 'q' if size(polygon{thispolygon},1)>0 % close the polygon polygon{thispolygon}(end+1,:) = polygon{thispolygon}(1,:); % close the polygon in the figure x = polygon{i}([end-1 end],1); y = polygon{i}([end-1 end],2); plot(x, y, 'g.-'); end again = 0; otherwise warning('invalid button (%d)', k); end end % remember this set of polygons as the mask mask = polygon; % get the outline, e.g. head shape and sulci polygon = {}; thispolygon = 1; polygon{thispolygon} = zeros(0,2); maskhelp = [ ... '-----------------------------------------------------------------------------------\n' ... 'specify polygons for adding outlines (e.g. head shape and sulci) to the layout\n' ... 'press the right mouse button to add another point to the current polygon\n' ... 'press backspace on the keyboard to remove the last point\n' ... 'press "c" on the keyboard to close this polygon and start with another\n' ... 'press "n" on the keyboard to start with another without closing the current polygon\n' ... 'press "q" on the keyboard to continue\n' ... ]; again = 1; while again fprintf(maskhelp); fprintf('\n'); for i=1:length(polygon) fprintf('polygon %d has %d points\n', i, size(polygon{i},1)); end try [x, y, k] = ginput(1); catch % this happens if the figure is closed return; end switch k case 1 polygon{thispolygon} = cat(1, polygon{thispolygon}, [x y]); % add the last line segment to the figure if size(polygon{thispolygon},1)>1 x = polygon{i}([end-1 end],1); y = polygon{i}([end-1 end],2); end plot(x, y, 'm.-'); case 8 % backspace if size(polygon{thispolygon},1)>0 % remove the last point polygon{thispolygon} = polygon{thispolygon}(1:end-1,:); % completely redraw the figure cla if ~isempty(cfg.image) h = image(img); else h = ft_plot_mesh(cfg.mesh,'edgecolor','none','vertexcolor',cfg.mesh.sulc); end hold on axis equal axis off % plot the electrode positions plot(pos(:,1), pos(:,2), 'b.'); plot(pos(:,1), pos(:,2), 'yo'); for i=1:length(polygon) x = polygon{i}(:,1); y = polygon{i}(:,2); if i~=thispolygon % close the polygon in the figure x(end) = x(1); y(end) = y(1); end plot(x, y, 'm.-'); end end case 'c' if size(polygon{thispolygon},1)>0 x = polygon{thispolygon}(1,1); y = polygon{thispolygon}(1,2); polygon{thispolygon} = cat(1, polygon{thispolygon}, [x y]); % add the last line segment to the figure x = polygon{i}([end-1 end],1); y = polygon{i}([end-1 end],2); plot(x, y, 'm.-'); % switch to the next polygon thispolygon = thispolygon + 1; polygon{thispolygon} = zeros(0,2); end case 'n' if size(polygon{thispolygon},1)>0 % switch to the next polygon thispolygon = thispolygon + 1; polygon{thispolygon} = zeros(0,2); end case 'q' again = 0; otherwise warning('invalid button (%d)', k); end end % remember this set of polygons as the outline outline = polygon; % convert electrode positions into a layout structure layout.pos = pos; nchans = size(pos,1); for i=1:nchans layout.label{i,1} = sprintf('chan%03d', i); end % add width and height for multiplotting d = dist(pos'); for i=1:nchans d(i,i) = inf; % exclude the diagonal end mindist = min(d(:)); layout.width = ones(nchans,1) * mindist * 0.8; layout.height = ones(nchans,1) * mindist * 0.6; % add mask and outline polygons layout.mask = mask; layout.outline = outline; else error('no layout detected, please specify cfg.layout') end % FIXME there is a conflict between the use of cfg.style here and in topoplot if ~strcmp(cfg.style, '3d') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check whether outline and mask are available % if not, add default "circle with triangle" to resemble the head % in case of "circle with triangle", the electrode positions should also be % scaled %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isfield(layout, 'outline') || ~isfield(layout, 'mask') rmax = 0.5; l = 0:2*pi/100:2*pi; HeadX = cos(l).*rmax; HeadY = sin(l).*rmax; NoseX = [0.18*rmax 0 -0.18*rmax]; NoseY = [rmax-.004 rmax*1.15 rmax-.004]; EarX = [.497 .510 .518 .5299 .5419 .54 .547 .532 .510 .489]; EarY = [.0555 .0775 .0783 .0746 .0555 -.0055 -.0932 -.1313 -.1384 -.1199]; % Scale the electrode positions to fit within a unit circle, i.e. electrode radius = 0.45 ind_scale = strmatch('SCALE', layout.label); ind_comnt = strmatch('COMNT', layout.label); sel = setdiff(1:length(layout.label), [ind_scale ind_comnt]); % these are excluded for scaling x = layout.pos(sel,1); y = layout.pos(sel,2); xrange = range(x); yrange = range(y); % First scale the width and height of the box for multiplotting layout.width = layout.width./xrange; layout.height = layout.height./yrange; % Then shift and scale the electrode positions layout.pos(:,1) = 0.9*((layout.pos(:,1)-min(x))/xrange-0.5); layout.pos(:,2) = 0.9*((layout.pos(:,2)-min(y))/yrange-0.5); % Define the outline of the head, ears and nose layout.outline{1} = [HeadX(:) HeadY(:)]; layout.outline{2} = [NoseX(:) NoseY(:)]; layout.outline{3} = [ EarX(:) EarY(:)]; layout.outline{4} = [-EarX(:) EarY(:)]; % Define the anatomical mask based on a circular head layout.mask{1} = [HeadX(:) HeadY(:)]; end end % make the subset as specified in cfg.channel cfg.channel = ft_channelselection(cfg.channel, setdiff(layout.label, {'COMNT', 'SCALE'})); % COMNT and SCALE are not really channels chansel = match_str(layout.label, cat(1, cfg.channel(:), 'COMNT', 'SCALE')); % include COMNT and SCALE, keep all channels in the order of the layout % return the layout for the subset of channels layout.pos = layout.pos(chansel,:); layout.label = layout.label(chansel); if ~strcmp(cfg.style, '3d') % these don't exist for the 3D layout layout.width = layout.width(chansel); layout.height = layout.height(chansel); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % apply the montage, i.e. combine bipolar channels into a new representation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~strcmp(cfg.montage, 'no') Norg = length(cfg.montage.labelorg); Nnew = length(cfg.montage.labelnew); for i=1:Nnew cfg.montage.tra(i,:) = abs(cfg.montage.tra(i,:)); cfg.montage.tra(i,:) = cfg.montage.tra(i,:) ./ sum(cfg.montage.tra(i,:)); end % pretend it is a sensor structure, this achieves averaging after channel matching tmp.tra = layout.pos; tmp.label = layout.label; new = ft_apply_montage(tmp, cfg.montage); layout.pos = new.tra; layout.label = new.label; % do the same for the width and height tmp.tra = layout.width(:); new = ft_apply_montage(tmp, cfg.montage); layout.width = new.tra; tmp.tra = layout.height(:); new = ft_apply_montage(tmp, cfg.montage); layout.height = new.tra; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % add axes positions for comments and scale information if required %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~any(strcmp('COMNT', layout.label)) && strcmpi(cfg.style, '2d') && ~skipcomnt % add a placeholder for the comment in the upper left corner layout.label{end+1} = 'COMNT'; layout.width(end+1) = mean(layout.width); layout.height(end+1) = mean(layout.height); if ~isempty(layout.pos) XY = layout.pos; else XY = cat(1, layout.outline{:}, layout.mask{:}); end layout.pos(end+1,:) = [min(XY(:,1)) min(XY(:,2))]; elseif any(strcmp('COMNT', layout.label)) && skipcomnt % remove the scale entry sel = find(strcmp('COMNT', layout.label)); layout.label(sel) = []; layout.pos(sel,:) = []; layout.width(sel) = []; layout.height(sel) = []; end if ~any(strcmp('SCALE', layout.label)) && strcmpi(cfg.style, '2d') && ~skipscale % add a placeholder for the scale in the upper right corner layout.label{end+1} = 'SCALE'; layout.width(end+1) = mean(layout.width); layout.height(end+1) = mean(layout.height); if ~isempty(layout.pos) XY = layout.pos; else XY = cat(1, layout.outline{:}, layout.mask{:}); end layout.pos(end+1,:) = [max(XY(:,1)) min(XY(:,2))]; elseif any(strcmp('SCALE', layout.label)) && skipscale % remove the scale entry sel = find(strcmp('SCALE', layout.label)); layout.label(sel) = []; layout.pos(sel,:) = []; layout.width(sel) = []; layout.height(sel) = []; end % ensure proper format of some of label (see bug 1909 -roevdmei) layout.label = layout.label(:); % to plot the layout for debugging, you can use this code snippet if strcmp(cfg.feedback, 'yes') && strcmpi(cfg.style, '2d') tmpcfg = []; tmpcfg.layout = layout; ft_layoutplot(tmpcfg); end % to write the layout to a .mat or text file, you can use this code snippet if ~isempty(cfg.output) && strcmpi(cfg.style, '2d') fprintf('writing layout to ''%s''\n', cfg.output); if strcmpi(cfg.output((end-3):end), '.mat') save(cfg.output,'layout'); else fid = fopen(cfg.output, 'wt'); for i=1:numel(layout.label) fprintf(fid, '%d %f %f %f %f %s\n', i, layout.pos(i,1), layout.pos(i,2), ... layout.width(i), layout.height(i), layout.label{i}); end fclose(fid); end elseif ~isempty(cfg.output) && strcmpi(cfg.style, '3d') % the layout file format does not support 3D positions, furthermore for % a 3D layout the width and height are currently set to NaN error('writing a 3D layout to an output file is not supported'); end % do the general cleanup and bookkeeping at the end of the function ft_postamble provenance ft_postamble previous data ft_postamble history layout %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION % read the layout information from the ascii file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function layout = readlay(filename) if ~exist(filename, 'file') error(sprintf('could not open layout file: %s', filename)); end fid=fopen(filename); lay_string=fread(fid,inf,'char=>char')'; fclose(fid); % pattern to match is integer, than 4 numeric values followed by a % string that can contain whitespaces and plus characters, followed by % newline integer='(\d+)'; float='([\d\.-]+)'; space='\s+'; channel_label='([\w \t\r\f\v\-\+]+)'; single_newline='\n'; pat=[integer, space, ... float, space, ... float, space, ... float, space, ... float, space, ... channel_label, single_newline]; matches=regexp(sprintf('%s\n',lay_string),pat,'tokens'); % convert to (nchannel x 6) matrix layout_matrix=cat(1,matches{:}); % convert values in first five columns to numeric num_values_cell=layout_matrix(:,1:5)'; str_values=sprintf('%s %s %s %s %s; ', num_values_cell{:}); num_values=str2num(str_values); % store layout information (omit channel number in first column) layout.pos = num_values(:,2:3); layout.width = num_values(:,4); layout.height = num_values(:,5); % trim whitespace around channel names label=layout_matrix(:,6); label=regexprep(label,'^\s*',''); label=regexprep(label,'\s*$',''); layout.label = label; return % function readlay %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION % convert 3D electrode positions into 2D layout %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function layout = sens2lay(sens, rz, method, style, overlap) % ensure that the sens structure is according to the latest conventions, % i.e. deal with backward compatibility sens = ft_datatype_sens(sens); % remove the balancing from the sensor definition, e.g. 3rd order gradients, PCA-cleaned data or ICA projections % this not only removed the linear projections, but also ensures that the channel labels are correctly named if isfield(sens, 'chanposorg') chanposorg = sens.chanposorg; else chanposorg = []; end if isfield(sens, 'balance') && ~strcmp(sens.balance.current, 'none') sens = undobalancing(sens); if size(chanposorg, 1) == numel(sens.label) sens.chanpos = chanposorg; end % In case not all the locations have NaNs it might still be useful to plot them % But perhaps it'd be better to have any(any elseif any(all(isnan(sens.chanpos))) [sel1, sel2] = match_str(sens.label, sens.labelorg); sens.chanpos = chanposorg(sel2, :); sens.label = sens.labelorg(sel2); end fprintf('creating layout for %s system\n', ft_senstype(sens)); % apply rotation if isempty(rz) switch ft_senstype(sens) case {'ctf151', 'ctf275', 'bti148', 'bti248', 'ctf151_planar', 'ctf275_planar', 'bti148_planar', 'bti248_planar', 'yokogawa160', 'yokogawa160_planar', 'yokogawa64', 'yokogawa64_planar', 'yokogawa440', 'yokogawa440_planar', 'magnetometer', 'meg'} rz = 90; case {'neuromag122', 'neuromag306'} rz = 0; case 'electrode' rz = 90; otherwise rz = 0; end end sens.chanpos = ft_warp_apply(rotate([0 0 rz]), sens.chanpos, 'homogenous'); % determine the 3D channel positions pnt = sens.chanpos; label = sens.label; if strcmpi(style, '3d') layout.pos = pnt; layout.label = label; else prj = elproj(pnt, method); % this copy will be used to determine the minimum distance between channels % we need a copy because prj retains the original positions, and % prjForDist might need to be changed if the user wants to keep % overlapping channels prjForDist = prj; % check whether many channels occupy identical positions, if so shift % them around if requested if size(unique(prj,'rows'),1) / size(prj,1) < 0.8 if strcmp(overlap, 'shift') ft_warning('the specified sensor configuration has many overlapping channels, creating a layout by shifting them around (use a template layout for better control over the positioning)'); prj = shiftxy(prj', 0.2)'; prjForDist = prj; elseif strcmp(overlap, 'no') error('the specified sensor configuration has many overlapping channels, you specified not to allow that'); elseif strcmp(overlap, 'keep') prjForDist = unique(prj, 'rows'); else error('unknown value for cfg.overlap = ''%s''', overlap); end end d = dist(prjForDist'); d(logical(eye(size(d)))) = inf; % This is a fix for .sfp files, containing positions of 'fiducial % electrodes'. Their presence determines the minimum distance between % projected electrode positions, leading to very small boxes. % This problem has been detected and reported by Matt Mollison. % FIXME: consider changing the box-size being determined by mindist % by a mean distance or so; this leads to overlapping boxes, but that % also exists for some .lay files if any(strmatch('Fid', label)) tmpsel = strmatch('Fid', label); d(tmpsel, :) = inf; d(:, tmpsel) = inf; end if any(isfinite(d(:))) % take mindist as the median of the first quartile of closest channel pairs with non-zero distance mindist = min(d); % get closest neighbour for all channels mindist = sort(mindist(mindist>1e-6),'ascend'); mindist = mindist(1:round(numel(label)/4)); mindist = median(mindist); else mindist = eps; % not sure this is a good value but it's just to prevent crashes when % the EEG sensor definition is meaningless end X = prj(:,1); Y = prj(:,2); Width = ones(size(X)) * mindist * 0.8; Height = ones(size(X)) * mindist * 0.6; layout.pos = [X Y]; layout.width = Width; layout.height = Height; layout.label = label; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION % convert 2D optode positions into 2D layout %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function layout = opto2lay(opto, label) layout = []; layout.pos = []; layout.label = {}; layout.width = []; layout.height = []; [rxnames, rem] = strtok(label, {'-', ' '}); [txnames, rem] = strtok(rem, {'-', ' '}); for i=1:numel(label) % create average positions rxid = ismember(opto.fiberlabel, rxnames(i)); txid = ismember(opto.fiberlabel, txnames(i)); layout.pos(i, :) = opto.fiberpos(rxid, :)/2 + opto.fiberpos(txid, :)/2; layout.label(end+1) = label(i); layout.width(end+1) = 1; layout.height(end+1) = 1; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION % shift 2D positions around so that the minimum distance between any pair % is mindist % % Credit for this code goes to Laurence Hunt at UCL. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function xy = shiftxy(xy,mindist) x = xy(1,:); y = xy(2,:); l=1; i=1; %filler mindist = mindist/0.999; % limits the number of loops while (~isempty(i) && l<50) xdiff = repmat(x,length(x),1) - repmat(x',1,length(x)); ydiff = repmat(y,length(y),1) - repmat(y',1,length(y)); xydist= sqrt(xdiff.^2 + ydiff.^2); %euclidean distance between all sensor pairs [i,j] = find(xydist<mindist*0.999); rm=(i<=j); i(rm)=[]; j(rm)=[]; %only look at i>j for m = 1:length(i); if (xydist(i(m),j(m)) == 0) diffvec = [mindist./sqrt(2) mindist./sqrt(2)]; else xydiff = [xdiff(i(m),j(m)) ydiff(i(m),j(m))]; diffvec = xydiff.*mindist./xydist(i(m),j(m)) - xydiff; end x(i(m)) = x(i(m)) - diffvec(1)/2; y(i(m)) = y(i(m)) - diffvec(2)/2; x(j(m)) = x(j(m)) + diffvec(1)/2; y(j(m)) = y(j(m)) + diffvec(2)/2; end l = l+1; end xy = [x; y];
github
lcnbeapp/beapp-master
ft_analysispipeline.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_analysispipeline.m
26,488
utf_8
6bafec86c50ded1898215065e0d9da10
function [pipeline] = ft_analysispipeline(cfg, data) % FT_ANALYSIPIPELINE reconstructs the complete analysis pipeline that was used to create % the input FieldTrip data structure. The pipeline will be visualized as a flowchart. % In the future it will be possible to output the complete pipeline as a MATLAB script % or in a specialized pipeline format (e.g. PSOM, JIST, LONI, Taverna). % % Use as % output = ft_analysispipeline(cfg, data) % % The first cfg input contains the settings that apply to the behaviour of this % particular function and the second data input argument can be the output of any % FieldTrip function, e.g. FT_PREPROCESSING, FT_TIMELOCKANALYSIS, FT_SOURCEANALYSIS, % FT_FREQSTATISTICS or whatever you like. % % Alternatively, for the second input argument you can also only give the configuration % of the processed data (i.e. "data.cfg") instead of the full data. % % The configuration options that apply to the behaviour of this function are % cfg.filename = string, filename without the extension % cfg.filetype = string, can be 'matlab', 'html' or 'dot' % cfg.feedback = string, 'no', 'text', 'gui' or 'yes', whether text and/or % graphical feedback should be presented (default = 'yes') % cfg.showinfo = string or cell array of strings, information to display % in the gui boxes, can be any combination of % 'functionname', 'revision', 'matlabversion', % 'computername', 'username', 'calltime', 'timeused', % 'memused', 'workingdir', 'scriptpath' (default = % 'functionname', only display function name). Can also % be 'all', show all pipeline. Please note that if you want % to show a lot of information, this will require a lot % of screen real estate. % cfg.remove = cell-array with strings, determines which objects will % be removed from the configuration prior to writing it to % file. For readibility of the script, you may want to % remove the large objectssuch as event structure, trial % definition, source positions % cfg.keepremoved = 'yes' or 'no', determines whether removed fields are % completely removed, or only replaced by a short textual % description (default = 'no') % % This function uses the nested cfg and cfg.previous that are present in % the data structure. It will use the configuration and the nested previous % configurations to climb all the way back into the tree. This funtction % will print a complete MATLAB script to screen (and optionally to file). % Furthermore, it will show an interactive graphical flowchart % representation of the steps taken during the pipeline(i). In the flowchart % you can click on one of the steps to see the configuration details of % that pipeline(i). % % Note that the nested cfg and cfg.previous in your data might not contain % all details that are required to reconstruct a complete and valid % analysis script. % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % If you specify this, the input data will be read from a *.mat file on disk. The % file should contain only a single variable, corresponding with the input structure. % % See also FT_PREPROCESSING, FT_TIMELOCKANALYSIS, FT_FREQANALYSIS, FT_SOURCEANALYSIS, % FT_CONNECTIVITYANALYSIS, FT_NETWORKANALYSIS % Copyright (C) 2014-2015, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % callinfo feedback is highly annoying in this recursive function % do this here, otherwise ft_defaults will override our setting if ~isfield(cfg, 'showcallinfo'), cfg.showcallinfo = 'no'; end % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar data ft_preamble provenance data ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % set the defaults cfg.filename = ft_getopt(cfg, 'filename'); cfg.showinfo = ft_getopt(cfg, 'showinfo', {'functionname'}); cfg.keepremoved = ft_getopt(cfg, 'keepremoved', 'no'); cfg.feedback = ft_getopt(cfg, 'feedback', 'text'); cfg.prune = ft_getopt(cfg, 'prune', 'yes'); cfg.filetype = ft_getopt(cfg, 'filetype'); cfg.fontsize = ft_getopt(cfg, 'fontsize', 10); if isempty(cfg.filetype) && ~isempty(cfg.filename) [p, f, x] = fileparts(cfg.filename); switch x case '.m' cfg.filetype = 'matlab'; case '.html' cfg.filetype = 'html'; case '.dot' cfg.filetype = 'dot'; otherwise error('cannot determine filetype'); end end if ~isfield(cfg, 'remove') % this is the default list of configuration elements to be removed. These % elements would be very large to print and make the script difficult to % read. To get a correctly behaving script, you may have to change this. cfg.remove = { 'sgncmb' 'channelcmb' 'event' 'trl' 'trlold' 'artfctdef.eog.trl' 'artfctdef.jump.trl' 'artfctdef.muscle.trl' 'pos' 'inside' 'outside' 'grid.pos' 'grid.inside' 'grid.outside' 'vol.bnd.pos' 'vol.bnd.tri' 'headmodel.bnd.pos' 'headmodel.bnd.tri' }; elseif ~iscell(cfg.remove) cfg.remove = {cfg.remove}; end if strcmp(cfg.showinfo, 'all') cfg.showinfo = { 'functionname' 'revision' 'matlabversion' 'computername' 'architecture' 'username' 'calltime' 'timeused' 'memused' 'workingdir' 'scriptpath' }; end if ~isfield(cfg, 'showinfo') cfg.showinfo = {'functionname'}; elseif ~iscell(cfg.showinfo) cfg.showinfo = {cfg.showinfo}; end % we are only interested in the cfg-part of the data if isfield(data, 'cfg') datacfg = data.cfg; else datacfg = data; end clear data % walk the tree, gather information about each node ft_progress('init', cfg.feedback, 'parsing provenance...'); pipeline = walktree(datacfg); ft_progress('close'); % convert the cell array into a structure array for i=1:length(pipeline) tmp(i) = pipeline{i}; end pipeline = tmp; if istrue(cfg.prune) % prune the double occurences [dummy, indx] = unique({pipeline.this}); pipeline = pipeline(sort(indx)); end % start at the end of the tree and determine the level of each of the parents hasparent = false(size(pipeline)); haschild = false(size(pipeline)); for i=1:length(pipeline) hasparent(i) = ~isempty(pipeline(i).parent); haschild(i) = any(strcmp(pipeline(i).this, [pipeline.parent])); end % construct a matrix with all pipeline steps width = zeros(size(pipeline)); height = zeros(size(pipeline)); level = 1; % the items without children start at height 1 sel = find(~haschild); while ~isempty(sel) height(sel) = level; % find the parents of the items at this level sel = match_str({pipeline.this}, [pipeline(sel).parent]); % the parents should be at least one level higher height(sel) = level + 1; % continue with the next level level = level + 1; end for i=1:max(height) sel = find(height==i); width(sel) = 1:length(sel); end for i=1:length(pipeline) pipeline(i).position = [height(i) width(i)]; end % sort according to a decreasing level, i.e. the last pipeline(i) at the end [dummy, indx] = sortrows(-[height(:) width(:)]); pipeline = pipeline(indx); if isempty(cfg.filename) pipeline2matlabfigure(cfg, pipeline); else switch cfg.filetype case 'matlab' pipeline2matlabscript(cfg, pipeline); case 'dot' pipeline2dotfile(cfg, pipeline); case 'html' pipeline2htmlfile(cfg, pipeline); otherwise error('unsupported filetype'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for recursive walking along the cfg.previous.previous info %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function info = walktree(cfg) if isempty(cfg) || (isstruct(cfg) && numel(fieldnames(cfg))==0) info = []; return end this = getnode(cfg); % parse all previous steps if isfield(cfg, 'previous') && ~isempty(cfg.previous) && iscell(cfg.previous) previous = cellfun(@walktree, cfg.previous, 'UniformOutput', false); if iscell(previous{1}) previous = cat(2, previous{:}); end elseif isfield(cfg, 'previous') && ~isempty(cfg.previous) && isstruct(cfg.previous) previous = walktree(cfg.previous); elseif isfield(cfg, 'previous') && ~isempty(cfg.previous) error('unexpected content in cfg.previous'); else previous = {}; end % parse the side branches, e.g. cfg.vol/cfg.headmodel and cfg.layout fn = fieldnames(cfg); branch = {}; for i=1:numel(fn) if isstruct(cfg.(fn{i})) && isfield(cfg.(fn{i}), 'cfg') branch = [walktree(cfg.(fn{i}).cfg) branch]; this.parent{end+1} = branch{1}.this; % the start of the branch is a parent to this element end end ft_progress(rand(1), 'parsing provenance for %s\n', this.name); % FIXME no percentage complete known drawnow % the order of the output elements matters for the recursion info = [{this} branch previous]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for gathering the information about each pipeline %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function node = getnode(cfg) [p, f, x] = myfileparts(getvalue(cfg, 'version.name')); node.cfg = cfg; node.name = f; node.id = getvalue(cfg, 'version.id'); node.this = ft_hash(cfg); if isfield(cfg, 'previous') && ~isempty(cfg.previous) && iscell(cfg.previous) % skip the entries that are empty cfg.previous = cfg.previous(~cellfun(@isempty, cfg.previous)); node.parent = cellfun(@ft_hash, cfg.previous, 'UniformOutput', false); elseif isfield(cfg, 'previous') && ~isempty(cfg.previous) && isstruct(cfg.previous) node.parent = {ft_hash(cfg.previous)}; elseif isfield(cfg, 'previous') && ~isempty(cfg.previous) error('unexpected content in cfg.previous'); else node.parent = {}; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function v = getvalue(s, f) if issubfield(s, f) v = getsubfield(s, f); else v = 'unknown'; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [p, f, x] = myfileparts(filename) if ispc filename(filename=='/') = filesep; else filename(filename=='\') = filesep; end [p, f, x] = fileparts(filename); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function varargout = button(h, eventdata, handles, varargin) pos = get(get(gcbo, 'CurrentAxes'), 'CurrentPoint'); x = pos(1,1); y = pos(1,2); pipeline = guidata(h); for i=1:numel(pipeline) if (x >= pipeline(i).x(1) && x <= pipeline(i).x(2) && y >= pipeline(i).y(1) && y <= pipeline(i).y(3)) cfg = pipeline(i).cfg; if isfield(cfg, 'previous') cfg = rmfield(cfg, 'previous'); end % use a helper function to remove uninteresting fields cfg = removefields(cfg, ignorefields('pipeline'), 'recursive', 'yes'); % use a helper function to remove too large fields cfg.checksize = 3000; cfg = ft_checkconfig(cfg, 'checksize', 'yes'); cfg = rmfield(cfg, 'checksize'); script = printstruct('cfg', cfg); uidisplaytext(script, pipeline(i).name); break; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function pipeline2matlabfigure(cfg, pipeline) fprintf('plotting pipeline as MATLAB figure\n'); layout = cell(numel(pipeline)); for i=1:length(pipeline) % get the vertical and horizontal position in integer values % high numbers are towards the begin, low numbers are towards the end of the pipeline v = pipeline(i).position(1); h = pipeline(i).position(2); layout{v,h} = pipeline(i).this; end % remove the empty columns maxheight = max(sum(~cellfun(@isempty, layout),1)); maxwidth = max(sum(~cellfun(@isempty, layout),2)); layout = layout(1:maxheight,1:maxwidth); fig = figure; hold on axis manual; % the axis should not change during the contruction of the arrows, otherwise the arrowheads will be distorted set(gca,'Units','normalized'); % use normalized units set(gcf, 'ToolBar', 'none'); axis([0 1 0 1]) axis off; axis tight; for i=1:numel(pipeline) label = makelabel(pipeline(i), cfg.showinfo); % dublicate backslashes to escape tex interpreter (in case of windows filenames) label = strrep(label, '\', '\\'); label = strrep(label, '{\\bf', '{\bf'); % undo for bold formatting % escape underscores label = strrep(label, '_', '\_'); % strip blank line if present and not needed if strcmp(label{end},'') label(end) = []; end % compute width and height of each box, note that axis Units are set to Normalized boxsize = 1./[maxwidth+1 maxheight+3]; % create the 4 corners for our patch, close the patch by returning to the start point x = ([0 1 1 0 0]-0.5) .* boxsize(1); y = ([0 0 1 1 0]-0.5) .* boxsize(2); % position the patch location = pipeline(i).position([2 1]); location(1) = (location(1)-0.5)/maxwidth; location(2) = (location(2)-0.5)/maxheight; % the location specifies the center of the patch x = x + location(1); y = y + location(2); p = patch(x', y', 0); set(p, 'Facecolor', [1 1 0.6]) pipeline(i).x = x; pipeline(i).y = y; guidata(fig, pipeline); if length(label)==1 textloc = location; l = text(textloc(1), textloc(2), label); set(l, 'HorizontalAlignment', 'center'); set(l, 'VerticalAlignment', 'middle'); set(l, 'fontUnits', 'points'); set(l, 'fontSize', cfg.fontsize); set(l, 'interpreter', 'tex'); else textloc = location; textloc(1) = textloc(1)-boxsize(1)/2; textloc(2) = textloc(2)+boxsize(2)/2; l = text(textloc(1), textloc(2), label); set(l, 'HorizontalAlignment', 'left'); set(l, 'VerticalAlignment', 'top'); set(l, 'fontUnits', 'points'); set(l, 'fontSize', cfg.fontsize); set(l, 'interpreter', 'tex'); end % draw an arrow if appropriate n = length(pipeline(i).parent); for j=1:n [parentlocation(2), parentlocation(1)] = ind2sub([maxheight, maxwidth], find(strcmp(layout(:), pipeline(i).parent{j}), 1, 'first')); % parentlocation = info(find(strcmp({pipeline.this}, analysis.parent{j}), 1, 'first')).position; parentlocation(1) = (parentlocation(1)-0.5)/maxwidth; parentlocation(2) = (parentlocation(2)-0.5)/maxheight; base = parentlocation + [0 -0.5].*boxsize; if false % n>1 % distribute the inputs evenly over the box rel = 2*(j+n-1)/(n-1)-1; % relative location between -1.0 and 1.0 rel = rel*(n-1)/(n+3); % compress the relative location tip = location + [0 0.5].*boxsize + [rel 0].*boxsize/2; else % put it in the centre tip = location + [0 0.5].*boxsize; end arrow(base, tip, 'length', 8, 'lineWidth', 1); end end % for numel(info) set(fig, 'WindowButtonUpFcn', @button); % set(fig, 'KeyPressFcn', @key); % add a context menu to the figure % ftmenu = uicontextmenu; set(gcf, 'uicontextmenu', ftmenu) % add a regular menu item to the figure ftmenu = uimenu(fig, 'Label', 'FieldTrip'); % ftmenu1 = uimenu(ftmenu, 'Label', 'Save pipeline'); % ftmenu2 = uimenu(ftmenu, 'Label', 'Share pipeline'); uimenu(ftmenu, 'Label', 'About', 'Separator', 'on', 'Callback', @menu_about); % uimenu(ftmenu1, 'Label', 'Save as MATLAB script'); % uimenu(ftmenu1, 'Label', 'Save as PSOM pipeline'); % uimenu(ftmenu1, 'Label', 'Save as HTML page'); % uimenu(ftmenu2, 'Label', 'Share within DCCN'); % uimenu(ftmenu2, 'Label', 'Share on PasteBin.com'); % uimenu(ftmenu2, 'Label', 'Share on MyExperiment.org'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label = makelabel(pipeline, showinfo) % create the text information to display label = {}; for k = 1:numel(showinfo) switch showinfo{k} case 'functionname' % label{end+1} = ['{\bf ' pipeline(i).name '}']; label{end+1} = pipeline.name; if k == 1 % add blank line if function name is on top, looks nice label{end+1} = ''; end case 'revision' if isfield(pipeline.cfg, 'version') && isfield(pipeline.cfg.version, 'id') label{end+1} = pipeline.cfg.version.id; else label{end+1} = '<revision unknown>'; end case 'matlabversion' if isfield(pipeline.cfg, 'callinfo') && isfield(pipeline.cfg.callinfo, 'matlab') label{end+1} = ['MATLAB ' pipeline.cfg.callinfo.matlab]; else label{end+1} = '<MATLAB version unknown>'; end case 'computername' if isfield(pipeline.cfg, 'callinfo') && isfield(pipeline.cfg.callinfo, 'hostname') label{end+1} = ['Hostname: ' pipeline.cfg.callinfo.hostname]; else label{end+1} = '<hostname unknown>'; end case 'architecture' if isfield(pipeline.cfg, 'callinfo') && isfield(pipeline.cfg.callinfo, 'hostname') label{end+1} = ['Architecture: ' pipeline.cfg.callinfo.computer]; else label{end+1} = '<architecture unknown>'; end case 'username' if isfield(pipeline.cfg, 'callinfo') && isfield(pipeline.cfg.callinfo, 'user') label{end+1} = ['Username: ' pipeline.cfg.callinfo.user]; else label{end+1} = '<username unknown>'; end case 'calltime' if isfield(pipeline.cfg, 'callinfo') && isfield(pipeline.cfg.callinfo, 'calltime') label{end+1} = ['Function called at ' datestr(pipeline.cfg.callinfo.calltime)]; else label{end+1} = '<function call time unknown>'; end case 'timeused' if isfield(pipeline.cfg, 'callinfo') && isfield(pipeline.cfg.callinfo, 'proctime') label{end+1} = sprintf('Function call required %d seconds', round(pipeline.cfg.callinfo.proctime)); else label{end+1} = '<processing time unknown>'; end case 'memused' if isfield(pipeline.cfg, 'callinfo') && isfield(pipeline.cfg.callinfo, 'procmem') label{end+1} = sprintf('Function call required %d MB', round(pipeline.cfg.callinfo.procmem/1024/1024)); else label{end+1} = '<memory requirement unknown>'; end case 'workingdir' if isfield(pipeline.cfg, 'callinfo') && isfield(pipeline.cfg.callinfo, 'pwd') label{end+1} = sprintf('Working directory was %s', pipeline.cfg.callinfo.pwd); else label{end+1} = '<working directory unknown>'; end case 'scriptpath' if isfield(pipeline.cfg, 'version') && isfield(pipeline.cfg.version, 'name') label{end+1} = sprintf('Full path to script was %s', pipeline.cfg.version.name); else label{end+1} = '<script path unknown>'; end end end % for numel(showinfo) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function pipeline2matlabscript(cfg, pipeline) [p, f, x] = fileparts(cfg.filename); filename = fullfile(p, [f '.m']); fprintf('exporting MATLAB script to file ''%s''\n', filename); varname = {}; varhash = {}; for i=1:length(pipeline) varname{end+1} = sprintf('variable_%d_%d', pipeline(i).position(1), pipeline(i).position(2)); varhash{end+1} = pipeline(i).this; end for i=1:length(pipeline) pipeline(i).inputvar = {}; pipeline(i).outputvar = varname{strcmp(varhash, pipeline(i).this)}; for j=1:length(pipeline(i).parent) pipeline(i).inputvar{j} = varname{strcmp(varhash, pipeline(i).parent{j})}; end end sep = sprintf('\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n'); script = sep; for i=1:length(pipeline) thiscfg = pipeline(i).cfg; if isfield(thiscfg, 'previous') thiscfg = rmfield(thiscfg, 'previous'); end cfgstr = printstruct('cfg', thiscfg); if ~isempty(pipeline(i).inputvar) inputvar = sprintf(', %s', pipeline(i).inputvar{:}); else inputvar = ''; end cmd = sprintf('\n%s = %s(cfg%s);', pipeline(i).outputvar, pipeline(i).name, inputvar); script = cat(2, script, cfgstr, cmd, sep); end % write the complete script to file fid = fopen(filename, 'wb'); fprintf(fid, '%s', script); fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function pipeline2dotfile(cfg, pipeline) [p, f, x] = fileparts(cfg.filename); filename = fullfile(p, [f '.dot']); fprintf('exporting DOT file to ''%s''\n', filename); % write the complete script to file fid = fopen(filename, 'wb'); fprintf(fid, 'digraph {\n'); varhash = {pipeline.this}; for i=1:length(pipeline) for j=1:length(pipeline(i).parent) fprintf(fid, '%d -> %d\n', find(strcmp(varhash, pipeline(i).parent{j})), i); end end for i=1:length(pipeline) label = makelabel(pipeline(i), cfg.showinfo); if numel(label)>2 % left justified label = sprintf('%s\\l', label{:}); label = label(1:end-2); else % centered label = sprintf('%s\\n', label{:}); label = label(1:end-2); end fprintf(fid, '%d [label="%s",shape=box,fontsize=%d,URL="http://www.fieldtriptoolbox.org/reference/%s"]\n', i, label, cfg.fontsize, pipeline(i).name); end fprintf(fid, '}\n'); fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function pipeline2htmlfile(cfg, pipeline) [p, f, x] = fileparts(cfg.filename); filename = fullfile(p, [f '.html']); % skip the data-like fields and the fields that probably were not added by the user himself skipfields = {'previous', 'grid', 'headmodel', 'event', 'warning', 'progress', 'trackconfig', 'checkconfig', 'checksize', 'showcallinfo', 'debug', 'outputfilepresent', 'trackcallinfo', 'trackdatainfo', 'trackusage'}; fprintf('exporting HTML file to ''%s''\n', filename); html = ''; totalproctime = 0; ft_progress('init', cfg.feedback, 'serialising cfg-structures...'); for k = 1:numel(pipeline) ft_progress(k/numel(pipeline), 'serialising cfg-structure %d from %d', k, numel(pipeline)); % strip away the cfg.previous fields, and all data-like fields tmpcfg = removefields(pipeline(k).cfg, skipfields); usercfg = []; % record the usercfg and proctime if present if isfield(tmpcfg, 'callinfo') if isfield(tmpcfg.callinfo, 'usercfg') usercfg = removefields(tmpcfg.callinfo.usercfg, skipfields); % avoid processing usercfg twice tmpcfg.callinfo = rmfield(tmpcfg.callinfo, 'usercfg'); end if isfield(tmpcfg.callinfo, 'proctime') totalproctime = totalproctime + tmpcfg.callinfo.proctime; end end html = [html sprintf('nodes["%s"] = {"id": "%s", "name": "%s", "cfg": "%s", "usercfg": "%s", "parentIds": [',... pipeline(k).this, pipeline(k).this, pipeline(k).name, escapestruct(tmpcfg), escapestruct(usercfg))]; if ~isempty(pipeline(k).parent) for j = 1:numel(pipeline(k).parent) html = [html '"' pipeline(k).parent{j} '"']; if j < numel(pipeline(k).parent) html = [html ',']; end end end html = [html sprintf(']};\n')]; if k == numel(pipeline) % we are at the single leaf node html = [html sprintf('var leafId = "%s";\n', pipeline(k).this)]; end end ft_progress('close'); html = [html(1:end-2) sprintf('\n')]; % load the skeleton and put in the html code thispath = fileparts(mfilename('fullpath')); htmlfile = fileread([thispath '/private/pipeline-skeleton.html']); timestamp = [datestr(now(), 'ddd') ' ' datestr(now())]; proctimestr = print_tim(totalproctime); htmlfile = strrep(htmlfile, '${TIMESTAMP}', timestamp); htmlfile = strrep(htmlfile, '${PIPELINE}', html); htmlfile = strrep(htmlfile, '${USER}', getusername()); htmlfile = strrep(htmlfile, '${PROCTIME}', proctimestr); % write the file fid = fopen(filename, 'w'); fwrite(fid, htmlfile, 'uchar'); fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cfghtml = escapestruct(tmpcfg) % convert the cfg structure to a suitable string (escape newlines and % quotes) % strip away big numeric fields if isstruct(tmpcfg) fields = fieldnames(tmpcfg); for k = 1:numel(fields) if isnumeric(tmpcfg.(fields{k})) && numel(tmpcfg.(fields{k})) > 400 tmpcfg.(fields{k}) = '[numeric data of &gt;400 elements stripped]'; end end end cfghtml = strrep(printstruct('cfg', tmpcfg), '\', '\\'); cfghtml = strrep(cfghtml, sprintf('\r'), '\r'); cfghtml = strrep(cfghtml, sprintf('\n'), '\n'); cfghtml = strrep(cfghtml, sprintf('\t'), '\t'); cfghtml = strrep(cfghtml, '"', '\"');
github
lcnbeapp/beapp-master
ft_freqbaseline.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_freqbaseline.m
6,802
utf_8
e4e887917081deb423ef3b59f99497b1
function [freq] = ft_freqbaseline(cfg, freq) % FT_FREQBASELINE performs baseline normalization for time-frequency data % % Use as % [freq] = ft_freqbaseline(cfg, freq) % where the freq data comes from FT_FREQANALYSIS and the configuration % should contain % cfg.baseline = [begin end] (default = 'no') % cfg.baselinetype = 'absolute', 'relative', 'relchange', 'normchange' or 'db' (default = 'absolute') % cfg.parameter = field for which to apply baseline normalization, or % cell array of strings to specify multiple fields to normalize % (default = 'powspctrm') % % See also FT_FREQANALYSIS, FT_TIMELOCKBASELINE, FT_FREQCOMPARISON, % FT_FREQGRANDAVERAGE % Undocumented local options: % cfg.inputfile = one can specifiy preanalysed saved data as input % cfg.outputfile = one can specify output as file to save to disk % Copyright (C) 2004-2006, Marcel Bastiaansen % Copyright (C) 2005-2006, Robert Oostenveld % Copyright (C) 2011, Eelke Spaak % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar freq ft_preamble provenance freq ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input data is valid for this function freq = ft_checkdata(freq, 'datatype', {'freq+comp', 'freq'}, 'feedback', 'yes'); % update configuration fieldnames cfg = ft_checkconfig(cfg, 'renamed', {'param', 'parameter'}); % set the defaults cfg.baseline = ft_getopt(cfg, 'baseline', 'no'); cfg.baselinetype = ft_getopt(cfg, 'baselinetype', 'absolute'); cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm'); % check validity of input options cfg = ft_checkopt(cfg, 'baseline', {'char', 'doublevector'}); cfg = ft_checkopt(cfg, 'baselinetype', 'char', {'absolute', 'relative', 'relchange','db', 'vssum'}); cfg = ft_checkopt(cfg, 'parameter', {'char', 'charcell'}); % make sure cfg.parameter is a cell array of strings if (~isa(cfg.parameter, 'cell')) cfg.parameter = {cfg.parameter}; end % is input consistent? if ischar(cfg.baseline) && strcmp(cfg.baseline, 'no') && ~isempty(cfg.baselinetype) warning('no baseline correction done'); end % process possible yes/no value of cfg.baseline if ischar(cfg.baseline) && strcmp(cfg.baseline, 'yes') % default is to take the prestimulus interval cfg.baseline = [-inf 0]; elseif ischar(cfg.baseline) && strcmp(cfg.baseline, 'no') % nothing to do return end % check if the field of interest is present in the data if (~all(isfield(freq, cfg.parameter))) error('cfg.parameter should be a string or cell array of strings referring to (a) field(s) in the freq input structure') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Computation of output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % initialize output structure freqOut = []; freqOut.label = freq.label; freqOut.freq = freq.freq; freqOut.dimord = freq.dimord; freqOut.time = freq.time; freqOut = copyfields(freq, freqOut,... {'grad', 'elec', 'trialinfo','topo', 'topolabel', 'unmixing'}); % loop over all fields that should be normalized for k = 1:numel(cfg.parameter) par = cfg.parameter{k}; if strcmp(freq.dimord, 'chan_freq_time') freqOut.(par) = ... performNormalization(freq.time, freq.(par), cfg.baseline, cfg.baselinetype); elseif strcmp(freq.dimord, 'rpt_chan_freq_time') || strcmp(freq.dimord, 'chan_chan_freq_time') || strcmp(freq.dimord, 'subj_chan_freq_time') freqOut.(par) = zeros(size(freq.(par))); % loop over trials, perform normalization per trial for l = 1:size(freq.(par), 1) tfdata = freq.(par)(l,:,:,:); siz = size(tfdata); tfdata = reshape(tfdata, siz(2:end)); freqOut.(par)(l,:,:,:) = ... performNormalization(freq.time, tfdata, cfg.baseline, cfg.baselinetype); end else error('unsupported data dimensions: %s', freq.dimord); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Output scaffolding %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if numel(cfg.parameter)==1 % convert from cell-array to string cfg.parameter = cfg.parameter{1}; end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous freq % rename the output variable to accomodate the savevar postamble freq = freqOut; ft_postamble provenance freq ft_postamble history freq ft_postamble savevar freq %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that actually performs the normalization on an arbitrary quantity %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = performNormalization(timeVec, data, baseline, baselinetype) baselineTimes = (timeVec >= baseline(1) & timeVec <= baseline(2)); if length(size(data)) ~= 3, error('time-frequency matrix should have three dimensions (chan,freq,time)'); end % compute mean of time/frequency quantity in the baseline interval, % ignoring NaNs, and replicate this over time dimension meanVals = repmat(nanmean(data(:,:,baselineTimes), 3), [1 1 size(data, 3)]); if (strcmp(baselinetype, 'absolute')) data = data - meanVals; elseif (strcmp(baselinetype, 'relative')) data = data ./ meanVals; elseif (strcmp(baselinetype, 'relchange')) data = (data - meanVals) ./ meanVals; elseif (strcmp(baselinetype, 'normchange')) || (strcmp(baselinetype, 'vssum')) data = (data - meanVals) ./ (data + meanVals); elseif (strcmp(baselinetype, 'db')) data = 10*log10(data ./ meanVals); else error('unsupported method for baseline normalization: %s', baselinetype); end
github
lcnbeapp/beapp-master
ft_sourceinterpolate.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_sourceinterpolate.m
26,491
utf_8
1e48e1da73c6a1582abf8378c324f996
function [interp] = ft_sourceinterpolate(cfg, functional, anatomical) % FT_SOURCEINTERPOLATE interpolates source activity or statistical maps onto the % voxels or vertices of an anatomical description of the brain. Both the functional % and the anatomical data can either describe a volumetric 3D regular grid, a % triangulated description of the cortical sheet or an arbitrary cloud of points. % % The functional data in the output data will be interpolated at the locations at % which the anatomical data are defined. For example, if the anatomical data was % volumetric, the output data is a volume-structure, containing the resliced source % and the anatomical volume that can be visualized using FT_SOURCEPLOT or written to % file using FT_SOURCEWRITE. % % The following scenarios are possible: % % - Both functional data and anatomical data are defined on 3D regular grids, for % example with a low-res grid for the functional data and a high-res grid for the % anatomy. % % - The functional data is defined on a 3D regular grid of source positions % and the anatomical data is defined on an irregular point cloud, which can be a % 2D triangulated mesh. % % - The functional data is defined on an irregular point cloud, which can be a 2D % triangulated mesh, and the anatomical data is defined on a 3D regular grid. % % - Both the functional and the anatomical data are defined on an irregular % point cloud, which can be a 2D triangulated mesh. % % - The functional data is defined on a low resolution 2D triangulated mesh and the % anatomical data is defined on a high resolution mesh, where the low-res vertices % form a subset of the high-res vertices. This allows for mesh based interpolation. % The algorithm currently implemented is so-called 'smudging' as it is also applied % by the MNE-suite software. % % Use as % [interp] = ft_sourceinterpolate(cfg, source, anatomy) % [interp] = ft_sourceinterpolate(cfg, stat, anatomy) % where % source is the output of FT_SOURCEANALYSIS % stat is the output of FT_SOURCESTATISTICS % anatomy is the output of FT_READ_MRI or one of the FT_VOLUMExxx functions, % a cortical sheet that was read with FT_READ_HEADSHAPE, or a regular % 3D grid created with FT_PREPARE_SOURCEMODEL. % and cfg is a structure with any of the following fields % cfg.parameter = string (or cell-array) of the parameter(s) to be interpolated % cfg.downsample = integer number (default = 1, i.e. no downsampling) % cfg.interpmethod = string, can be 'nearest', 'linear', 'cubic', 'spline', 'sphere_avg' or 'smudge' (default = 'linear for interpolating two 3D volumes, 'nearest' for all other cases) % % The supported interpolation methods are 'nearest', 'linear', 'cubic' or 'spline' % for interpolating two 3D volumes onto each other. For all other cases the supported % interpolation methods are 'nearest', 'sphere_avg' or 'smudge'. % % The functional and anatomical data should be expressed in the same % coordinate sytem, i.e. either both in MEG headcoordinates (NAS/LPA/RPA) % or both in SPM coordinates (AC/PC). % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % cfg.outputfile = ... % If you specify one of these (or both) the input data will be read from a *.mat % file on disk and/or the output data will be written to a *.mat file. These mat % files should contain only a single variable, corresponding with the % input/output structure. % % See also FT_READ_MRI, FT_SOURCEANALYSIS, FT_SOURCESTATISTICS, % FT_READ_HEADSHAPE, FT_SOURCEPLOT, FT_SOURCEWRITE % Copyright (C) 2003-2007, Robert Oostenveld % Copyright (C) 2011-2014, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar functional anatomical ft_preamble provenance functional anatomical ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % this is not supported any more as of 26/10/2011 if ischar(anatomical), error('please use cfg.inputfile instead of specifying the input variable as a sting'); end % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'unused', {'keepinside' 'voxelcoord'}); cfg = ft_checkconfig(cfg, 'deprecated', {'sourceunits', 'mriunits'}); cfg = ft_checkconfig(cfg, 'required', 'parameter'); cfg = ft_checkconfig(cfg, 'renamedval', {'parameter', 'avg.pow', 'pow'}); cfg = ft_checkconfig(cfg, 'renamedval', {'parameter', 'avg.coh', 'coh'}); cfg = ft_checkconfig(cfg, 'renamedval', {'parameter', 'avg.mom', 'mom'}); % set the defaults cfg.downsample = ft_getopt(cfg, 'downsample', 1); cfg.feedback = ft_getopt(cfg, 'feedback', 'text'); % cfg.interpmethod depends on how the interpolation should be done and will be specified below % replace pnt by pos anatomical = fixpos(anatomical); functional = fixpos(functional); % ensure the functional data to be in double precision functional = ft_struct2double(functional); if isfield(anatomical, 'transform') && isfield(anatomical, 'dim') % anatomical volume isUnstructuredAna = false; elseif isfield(anatomical, 'pos') && isfield(anatomical, 'dim') % positions that can be mapped onto a 3D regular grid isUnstructuredAna = false; elseif isfield(anatomical, 'pos') % anatomical data that consists of a mesh, but no smudging possible isUnstructuredAna = true; end if isfield(functional, 'transform') && isfield(functional, 'dim') % functional volume isUnstructuredFun = false; elseif isfield(functional, 'pos') && isfield(functional, 'dim') % positions that can be mapped onto a 3D regular grid isUnstructuredFun = false; else isUnstructuredFun = true; end if isUnstructuredAna anatomical = ft_checkdata(anatomical, 'datatype', 'source', 'inside', 'logical', 'feedback', 'yes', 'hasunit', 'yes'); else anatomical = ft_checkdata(anatomical, 'datatype', 'volume', 'inside', 'logical', 'feedback', 'yes', 'hasunit', 'yes'); end if isUnstructuredFun functional = ft_checkdata(functional, 'datatype', 'source', 'inside', 'logical', 'feedback', 'yes', 'hasunit', 'yes'); else functional = ft_checkdata(functional, 'datatype', 'volume', 'inside', 'logical', 'feedback', 'yes', 'hasunit', 'yes'); end if ~isa(cfg.parameter, 'cell') cfg.parameter = {cfg.parameter}; end % try to select all relevant parameters present in the data if any(strcmp(cfg.parameter, 'all')) cfg.parameter = parameterselection('all', functional); for k = numel(cfg.parameter):-1:1 % check whether the field is numeric tmp = getsubfield(functional, cfg.parameter{k}); if iscell(tmp) cfg.parameter(k) = []; elseif strcmp(cfg.parameter{k}, 'pos') cfg.parameter(k) = []; end end end % ensure that the functional data has the same unit as the anatomical data functional = ft_convert_units(functional, anatomical.unit); if isfield(functional, 'coordsys') && isfield(anatomical, 'coordsys') && ~isequal(functional.coordsys, anatomical.coordsys) % FIXME is this different when smudged or not? % warning('the coordinate systems are not aligned'); % error('the coordinate systems are not aligned'); end if ~isUnstructuredAna && cfg.downsample~=1 % downsample the anatomical volume tmpcfg = keepfields(cfg, {'downsample'}); orgcfg.parameter = cfg.parameter; tmpcfg.parameter = 'anatomy'; anatomical = ft_volumedownsample(tmpcfg, anatomical); % restore the provenance information [cfg, anatomical] = rollback_provenance(cfg, anatomical); % restore the original parameter, it should not be 'anatomy' cfg.parameter = orgcfg.parameter; end % collect the functional volumes that should be converted dat_name = {}; dat_array = {}; for i=1:length(cfg.parameter) if ~iscell(getsubfield(functional, cfg.parameter{i})) dat_name{end+1} = cfg.parameter{i}; dat_array{end+1} = getsubfield(functional, cfg.parameter{i}); else fprintf('not interpolating %s, since it is represented in a cell-array\n', cfg.parameter{i}); end end % hmmmm, if the input data contains a time and/or freq dimension, then the output % may be terribly blown up; most convenient would be to output only the % smudging matrix, and project the data when plotting if isUnstructuredFun && isUnstructuredAna && isfield(anatomical, 'orig') && isfield(anatomical.orig, 'pos') && isfield(anatomical.orig, 'tri') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % functional data defined on subset of vertices in an anatomical mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % FIXME this should not be decided on the basis of the data structures but on the basis of the cfg.interpmethod option % FIXME the distribution of 3 geometries over the 2 structures is weird % FIXME a (perhaps extreme) application of this would be to interpolate data from parcels on the sheet, i.e. an inverse parcellation % anatomical data consists of a decimated triangulated mesh, containing % the original description, allowing for smudging. % smudge the low resolution functional data according to the strategy in % MNE-suite (chapter 8.3 of the manual) interpmat = interp_ungridded(anatomical.pos, anatomical.orig.pos, 'projmethod', 'smudge', 'triout', anatomical.orig.tri); interpmat(~anatomical.inside(:), :) = 0; % start with an empty structure, keep only some fields interp = keepfields(functional, {'time', 'freq'}); interp = copyfields(anatomical, interp, {'coordsys', 'unit'}); interp = copyfields(anatomical.orig, interp, {'pos', 'tri'}); % identify the inside voxels after interpolation nzeros = sum(interpmat~=0,2); newinside = (nzeros~=0); newoutside = (nzeros==0); interp.inside = false(size(anatomical.pos,1),1); interp.inside(newinside) = true; % interpolate all functional data for i=1:length(dat_name) fprintf('interpolating %s\n', dat_name{i}); dimord = getdimord(functional, dat_name{i}); dimtok = tokenize(dimord, '_'); dimf = getdimsiz(functional, dat_name{i}); dimf(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions % should be 3-D array, can have trailing singleton dimensions if numel(dimf)<2 dimf(2) = 1; end if numel(dimf)<3 dimf(3) = 1; end allav = zeros([size(anatomical.orig.pos,1), dimf(2:end)]); for k=1:dimf(2) for m=1:dimf(3) fv = dat_array{i}(:,k,m); av = interpmat*fv; av(newoutside) = nan; allav(:,k,m) = av; end end interp = setsubfield(interp, dat_name{i}, allav); end elseif isUnstructuredFun && isUnstructuredAna %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % functional data defined on a point cloud/mesh, anatomy on a volume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % set default interpmethod for this situation cfg.interpmethod = ft_getopt(cfg, 'interpmethod', 'nearest'); cfg.sphereradius = ft_getopt(cfg, 'sphereradius', 0.5); cfg.power = ft_getopt(cfg, 'power', 1); interpmat = interp_ungridded(functional.pos, anatomical.pos, 'projmethod', cfg.interpmethod, 'sphereradius', cfg.sphereradius, 'power', cfg.power); % FIXME include other key-value pairs as well interpmat(~anatomical.inside(:), :) = 0; % start with an empty structure, keep only some fields interp = keepfields(functional, {'time', 'freq'}); interp = copyfields(anatomical, interp, {'pos', 'tri', 'dim', 'transform', 'coordsys', 'unit'}); % identify the inside voxels after interpolation nzeros = sum(interpmat~=0,2); newinside = (nzeros~=0); newoutside = (nzeros==0); interp.inside = false(size(anatomical.pos,1),1); interp.inside(newinside) = true; % interpolate all functional data for i=1:length(dat_name) fprintf('interpolating %s\n', dat_name{i}); dimord = getdimord(functional, dat_name{i}); dimtok = tokenize(dimord, '_'); dimf = getdimsiz(functional, dat_name{i}); dimf(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions % should be 3-D array, can have trailing singleton dimensions if numel(dimf)<2 dimf(2) = 1; end if numel(dimf)<3 dimf(3) = 1; end allav = zeros([size(anatomical.pos,1), dimf(2:end)]); for k=1:dimf(2) for m=1:dimf(3) fv = dat_array{i}(:,k,m); av = interpmat*fv; av(newoutside) = nan; allav(:,k,m) = av; end end interp = setsubfield(interp, dat_name{i}, allav); end elseif isUnstructuredFun && ~isUnstructuredAna %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % functional data defined on a point cloud/mesh, anatomy on a point cloud/mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % set default interpmethod for this situation cfg.interpmethod = ft_getopt(cfg, 'interpmethod', 'nearest'); cfg.sphereradius = ft_getopt(cfg, 'sphereradius', 0.5); cfg.power = ft_getopt(cfg, 'power', 1); [ax, ay, az] = voxelcoords(anatomical.dim, anatomical.transform); anatomical.pos = [ax(:) ay(:) az(:)]; clear ax ay az interpmat = interp_ungridded(functional.pos, anatomical.pos, 'projmethod', cfg.interpmethod, 'sphereradius', cfg.sphereradius, 'power', cfg.power); % FIXME include other key-value pairs as well interpmat(~anatomical.inside(:), :) = 0; % start with an empty structure, keep only some fields interp = keepfields(functional, {'time', 'freq'}); interp = copyfields(anatomical, interp, {'pos', 'tri', 'dim', 'transform', 'coordsys', 'unit', 'anatomy'}); % identify the inside voxels after interpolation nzeros = sum(interpmat~=0,2); newinside = (nzeros~=0); newoutside = (nzeros==0); interp.inside = false(anatomical.dim); interp.inside(newinside) = true; % interpolate all functional data for i=1:length(dat_name) fprintf('interpolating %s\n', dat_name{i}); dimord = getdimord(functional, dat_name{i}); dimtok = tokenize(dimord, '_'); dimf = getdimsiz(functional, dat_name{i}); dimf(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions % should be 3-D array, can have trailing singleton dimensions if numel(dimf)<2 dimf(2) = 1; end if numel(dimf)<3 dimf(3) = 1; end av = zeros([anatomical.dim ]); allav = zeros([anatomical.dim dimf(2:end)]); for k=1:dimf(2) for m=1:dimf(3) fv = dat_array{i}(:,k,m); av(:) = interpmat*fv; av(newoutside) = nan; allav(:,:,:,k,m) = av; end end if isfield(interp, 'freq') || isfield(interp, 'time') % the output should be a source representation, not a volume allav = reshape(allav, prod(anatomical.dim), dimf(2), dimf(3)); end interp = setsubfield(interp, dat_name{i}, allav); end if ~isfield(interp, 'freq') && ~isfield(interp, 'time') % the output should be a volume representation, not a source interp = rmfield(interp, 'pos'); end elseif ~isUnstructuredFun && isUnstructuredAna %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % functional data defined on a volume, anatomy on a point cloud/mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % set default interpmethod for this situation cfg.interpmethod = ft_getopt(cfg, 'interpmethod', 'nearest'); cfg.sphereradius = ft_getopt(cfg, 'sphereradius', []); cfg.power = ft_getopt(cfg, 'power', 1); % interpolate the 3D volume onto the anatomy if ~strcmp(cfg.interpmethod, 'project') % use interp_gridded [interpmat, dummy] = interp_gridded(functional.transform, zeros(functional.dim), anatomical.pos, 'projmethod', cfg.interpmethod, 'sphereradius', cfg.sphereradius, 'inside', functional.inside, 'power', cfg.power); % use interp_ungridded % interpmat = interp_ungridded(functional.pos, anatomical.pos, 'projmethod', cfg.interpmethod, 'sphereradius', cfg.sphereradius, 'inside', functional.inside, 'power', cfg.power); else % do the interpolation below, the current implementation of the % 'project' method does not output an interpmat (and is therefore quite % inefficient % set the defaults cfg.projvec = ft_getopt(cfg, 'projvec', 1); cfg.projweight = ft_getopt(cfg, 'projweight', ones(size(cfg.projvec))); cfg.projcomb = ft_getopt(cfg, 'projcomb', 'mean'); % or max cfg.projthresh = ft_getopt(cfg, 'projthresh', []); end % start with an empty structure, keep some fields interp = keepfields(functional, {'time', 'freq'}); interp = copyfields(anatomical, interp, {'pos', 'tri', 'dim', 'transform', 'coordsys', 'unit'}); % identify the inside voxels after interpolation interp.inside = true(size(anatomical.pos,1),1); % interpolate all functional data for i=1:length(dat_name) fprintf('interpolating %s\n', dat_name{i}); dimord = getdimord(functional, dat_name{i}); dimtok = tokenize(dimord, '_'); dimf = getdimsiz(functional, dat_name{i}); dimf(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions if prod(functional.dim)==dimf(1) % convert into 3-D, 4-D or 5-D array dimf = [functional.dim dimf(2:end)]; dat_array{i} = reshape(dat_array{i}, dimf); end % should be 5-D array, can have trailing singleton dimensions if numel(dimf)<4 dimf(4) = 1; end if numel(dimf)<5 dimf(5) = 1; end allav = zeros([size(anatomical.pos,1), dimf(4:end)]); if ~strcmp(cfg.interpmethod, 'project') for k=1:dimf(4) for m=1:dimf(5) fv = dat_array{i}(:,:,:,k,m); fv = fv(functional.inside(:)); av = interpmat*fv; allav(:,k,m) = av; end end else for k=1:dimf(4) for m=1:dimf(5) fv = dat_array{i}(:,:,:,k,m); av = interp_gridded(functional.transform, fv, anatomical.pos, 'dim', functional.dim, 'projmethod', 'project', 'projvec', cfg.projvec, 'projweight', cfg.projweight, 'projcomb', cfg.projcomb, 'projthresh', cfg.projthresh); allav(:,k,m) = av; end end end interp = setsubfield(interp, dat_name{i}, allav); end elseif ~isUnstructuredFun && ~isUnstructuredAna %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % functional data defined on a volume, anatomy on a differently sampled volume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % set default interpmethod for this situation cfg.interpmethod = ft_getopt(cfg, 'interpmethod', 'linear'); % start with an empty structure, keep some fields interp = keepfields(functional, {'time', 'freq'}); interp = copyfields(anatomical, interp, {'pos', 'tri', 'dim', 'transform', 'coordsys', 'unit', 'anatomy'}); % convert the anatomical voxel positions into voxel indices into the functional volume anatomical.transform = functional.transform \ anatomical.transform; functional.transform = eye(4); [fx, fy, fz] = voxelcoords(functional.dim, functional.transform); [ax, ay, az] = voxelcoords(anatomical.dim, anatomical.transform); % estimate the subvolume of the anatomy that is spanned by the functional volume minfx = 1; minfy = 1; minfz = 1; maxfx = functional.dim(1); maxfy = functional.dim(2); maxfz = functional.dim(3); sel = ax(:)>=minfx & ... ax(:)<=maxfx & ... ay(:)>=minfy & ... ay(:)<=maxfy & ... az(:)>=minfz & ... az(:)<=maxfz; fprintf('selecting subvolume of %.1f%%\n', 100*sum(sel)./prod(anatomical.dim)); if all(functional.inside(:)) % keep all voxels marked as inside interp.inside = true(anatomical.dim); else % reslice and interpolate inside interp.inside = zeros(anatomical.dim); % interpolate with method nearest interp.inside( sel) = my_interpn(double(functional.inside), ax(sel), ay(sel), az(sel), 'nearest', cfg.feedback); interp.inside(~sel) = 0; interp.inside = logical(interp.inside); end % prepare the grid that is used in the interpolation fg = [fx(:) fy(:) fz(:)]; clear fx fy fz % reslice and interpolate all functional volumes for i=1:length(dat_name) fprintf('reslicing and interpolating %s\n', dat_name{i}); dimord = getdimord(functional, dat_name{i}); dimtok = tokenize(dimord, '_'); dimf = getdimsiz(functional, dat_name{i}); dimf(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions if prod(functional.dim)==dimf(1) % convert into 3-D, 4-D or 5-D array dimf = [functional.dim dimf(2:end)]; dat_array{i} = reshape(dat_array{i}, dimf); end % should be 5-D array, can have trailing singleton dimensions if numel(dimf)<4 dimf(4) = 1; end if numel(dimf)<5 dimf(5) = 1; end av = zeros([anatomical.dim ]); allav = zeros([anatomical.dim dimf(4:end)]); functional.inside = functional.inside(:,:,:,1,1); if any(dimf(4:end)>1) && ~strcmp(cfg.feedback, 'none') % this is needed to prevent feedback to be displayed for every time-frequency point warning('disabling feedback'); cfg.feedback = 'none'; end for k=1:dimf(4) for m=1:dimf(5) fv = dat_array{i}(:,:,:,k,m); if ~isa(fv, 'double') % only convert if needed, this saves memory fv = double(fv); end % av( sel) = my_interpn(fx, fy, fz, fv, ax(sel), ay(sel), az(sel), cfg.interpmethod, cfg.feedback); if islogical(dat_array{i}) % interpolate always with method nearest av( sel) = my_interpn(fv, ax(sel), ay(sel), az(sel), 'nearest', cfg.feedback); av = logical(av); else if ~all(functional.inside(:)) % extrapolate the outside of the functional volumes for better interpolation at the edges fv(~functional.inside) = griddatan(fg(functional.inside(:), :), fv(functional.inside(:)), fg(~functional.inside(:), :), 'nearest'); end % interpolate functional onto anatomical grid av( sel) = my_interpn(fv, ax(sel), ay(sel), az(sel), cfg.interpmethod, cfg.feedback); av(~sel) = nan; av(~interp.inside) = nan; end allav(:,:,:,k,m) = av; end end if isfield(interp, 'freq') || isfield(interp, 'time') % the output should be a source representation, not a volume allav = reshape(allav, prod(anatomical.dim), dimf(4), dimf(5)); end interp = setsubfield(interp, dat_name{i}, allav); end end % computing the interpolation according to the input data if isfield(interp, 'freq') || isfield(interp, 'time') % the output should be a source representation, not a volumetric representation if ~isfield(interp, 'pos') [x, y, z] = voxelcoords(interp.dim, interp.transform); interp.pos = [x(:) y(:) z(:)]; end end if exist('interpmat', 'var') cfg.interpmat = interpmat; cfg.interpmat; % access it once to fool the cfg-tracking end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous functional anatomical ft_postamble provenance interp ft_postamble history interp ft_postamble savevar interp %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION this function computes the location of all voxels in head % coordinates in a memory efficient manner %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [x, y, z] = voxelcoords(dim, transform) xgrid = 1:dim(1); ygrid = 1:dim(2); zgrid = 1:dim(3); npix = prod(dim(1:2)); % number of voxels in a single slice x = zeros(dim); y = zeros(dim); z = zeros(dim); X = zeros(1,npix); Y = zeros(1,npix); Z = zeros(1,npix); E = ones(1,npix); % determine the voxel locations per slice for i=1:dim(3) [X(:), Y(:), Z(:)] = ndgrid(xgrid, ygrid, zgrid(i)); tmp = transform*[X; Y; Z; E]; x((1:npix)+(i-1)*npix) = tmp(1,:); y((1:npix)+(i-1)*npix) = tmp(2,:); z((1:npix)+(i-1)*npix) = tmp(3,:); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for memory efficient interpolation % the only reason for this function is that it does the interpolation in smaller chuncks % this prevents memory problems that I often encountered here %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function [av] = my_interpn(fx, fy, fz, fv, ax, ay, az, interpmethod, feedback); function [av] = my_interpn(fv, ax, ay, az, interpmethod, feedback) num = numel(ax); % total number of voxels blocksize = floor(num/20); % number of voxels to interpolate at once, split it into 20 chuncks lastblock = 0; % boolean flag for while loop sel = 1:blocksize; % selection of voxels that are interpolated, this is the first chunck av = zeros(size(ax)); ft_progress('init', feedback, 'interpolating'); while (1) ft_progress(sel(1)/num, 'interpolating %.1f%%\n', 100*sel(1)/num); if sel(end)>=num sel = sel(1):num; lastblock = 1; end av(sel) = interpn(fv, ax(sel), ay(sel), az(sel), interpmethod); if lastblock break end sel = sel + blocksize; end ft_progress('close');
github
lcnbeapp/beapp-master
ft_megplanar.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_megplanar.m
16,100
utf_8
018d90ee64dbbd703cf6575665f3e5f1
function [data] = ft_megplanar(cfg, data) % FT_MEGPLANAR computes planar MEG gradients gradients for raw data or average % event-related field data. It can also convert frequency-domain data that was computed % using FT_FREQANALYSIS, as long as it contains the complex-valued fourierspcrm and not % only the powspctrm. % % Use as % [interp] = ft_megplanar(cfg, data) % where the input data corresponds to the output from FT_PREPROCESSING, % FT_TIMELOCKANALYSIS or FT_FREQANALYSIS (with output='fourierspcrm'). % % The configuration should contain % cfg.planarmethod = string, can be 'sincos', 'orig', 'fitplane', 'sourceproject' (default = 'sincos') % cfg.channel = Nx1 cell-array with selection of channels (default = 'MEG'), see FT_CHANNELSELECTION for details % cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') % % The methods orig, sincos and fitplane are all based on a neighbourhood interpolation. % For these methods you need to specify % cfg.neighbours = neighbourhood structure, see FT_PREPARE_NEIGHBOURS % % In the 'sourceproject' method a minumum current estimate is done using a large number % of dipoles that are placed in the upper layer of the brain surface, followed by a % forward computation towards a planar gradiometer array. This requires the % specification of a volume conduction model of the head and of a source model. The % 'sourceproject' method is not supported for frequency domain data. % % A dipole layer representing the brain surface must be specified with % cfg.inwardshift = depth of the source layer relative to the head model surface (default = 2.5 cm, which is appropriate for a skin-based head model) % cfg.spheremesh = number of dipoles in the source layer (default = 642) % cfg.pruneratio = for singular values, default is 1e-3 % cfg.headshape = a filename containing headshape, a structure containing a % single triangulated boundary, or a Nx3 matrix with surface % points % If no headshape is specified, the dipole layer will be based on the inner compartment % of the volume conduction model. % % The volume conduction model of the head should be specified as % cfg.headmodel = structure with volume conduction model, see FT_PREPARE_HEADMODEL % % The following cfg fields are optional: % cfg.feedback % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % cfg.outputfile = ... % If you specify one of these (or both) the input data will be read from a *.mat % file on disk and/or the output data will be written to a *.mat file. These mat % files should contain only a single variable, corresponding with the % input/output structure. % % See also FT_COMBINEPLANAR, FT_NEIGHBOURSELECTION % Copyright (C) 2004, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar data ft_preamble provenance data ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % store the original input representation of the data, this is used later on to convert it back isfreq = ft_datatype(data, 'freq'); israw = ft_datatype(data, 'raw'); istlck = ft_datatype(data, 'timelock'); % this will be temporary converted into raw % check if the input data is valid for this function, this converts the data if needed data = ft_checkdata(data, 'datatype', {'raw' 'freq'}, 'feedback', 'yes', 'hassampleinfo', 'yes', 'ismeg', 'yes', 'senstype', {'ctf151', 'ctf275', 'bti148', 'bti248', 'itab153', 'yokogawa160', 'yokogawa64'}); if istlck % the timelocked data has just been converted to a raw representation % and will be converted back to timelocked at the end of this function israw = true; end if isfreq, if ~isfield(data, 'fourierspctrm'), error('freq data should contain Fourier spectra'); end end cfg = ft_checkconfig(cfg, 'renamed', {'hdmfile', 'headmodel'}); cfg = ft_checkconfig(cfg, 'renamed', {'vol', 'headmodel'}); % set the default configuration cfg.channel = ft_getopt(cfg, 'channel', 'MEG'); cfg.trials = ft_getopt(cfg, 'trials', 'all', 1); cfg.planarmethod = ft_getopt(cfg, 'planarmethod', 'sincos'); cfg.feedback = ft_getopt(cfg, 'feedback', 'text'); % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'renamedval', {'headshape', 'headmodel', []}); if ~strcmp(cfg.planarmethod, 'sourceproject') cfg = ft_checkconfig(cfg, 'required', {'neighbours'}); end if isfield(cfg, 'headshape') && isa(cfg.headshape, 'config') % convert the nested config-object back into a normal structure cfg.headshape = struct(cfg.headshape); end if isfield(cfg, 'neighbours') && isa(cfg.neighbours, 'config') % convert the nested config-object back into a normal structure cfg.neighbours = struct(cfg.neighbours); end % put the low-level options pertaining to the dipole grid in their own field cfg = ft_checkconfig(cfg, 'renamed', {'tightgrid', 'tight'}); % this is moved to cfg.grid.tight by the subsequent createsubcfg cfg = ft_checkconfig(cfg, 'renamed', {'sourceunits', 'unit'}); % this is moved to cfg.grid.unit by the subsequent createsubcfg cfg = ft_checkconfig(cfg, 'createsubcfg', {'grid'}); % select trials of interest tmpcfg = []; tmpcfg.trials = cfg.trials; tmpcfg.channel = cfg.channel; data = ft_selectdata(tmpcfg, data); % restore the provenance information [cfg, data] = rollback_provenance(cfg, data); if strcmp(cfg.planarmethod, 'sourceproject') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Do an inverse computation with a simplified distributed source model % and compute forward again with the axial gradiometer array replaced by % a planar one. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % method specific configuration options cfg.headshape = ft_getopt(cfg, 'headshape', []); cfg.inwardshift = ft_getopt(cfg, 'inwardshift', 2.5); % this number assumes that all other inputs are in cm cfg.pruneratio = ft_getopt(cfg, 'pruneratio', 1e-3); cfg.spheremesh = ft_getopt(cfg, 'spheremesh', 642); if isfreq error('the method ''sourceproject'' is not supported for frequency data as input'); end Nchan = length(data.label); Ntrials = length(data.trial); % FT_PREPARE_VOL_SENS will match the data labels, the gradiometer labels and the % volume model labels (in case of a localspheres model) and result in a gradiometer % definition that only contains the gradiometers that are present in the data. [headmodel, axial.grad, cfg] = prepare_headmodel(cfg, data); % determine the dipole layer that represents the surface of the brain if isempty(cfg.headshape) % construct from the inner layer of the volume conduction model pos = headsurface(headmodel, axial.grad, 'surface', 'cortex', 'inwardshift', cfg.inwardshift, 'npnt', cfg.spheremesh); else % get the surface describing the head shape if isstruct(cfg.headshape) && isfield(cfg.headshape, 'pnt') % use the headshape surface specified in the configuration headshape = cfg.headshape; elseif isnumeric(cfg.headshape) && size(cfg.headshape,2)==3 % use the headshape points specified in the configuration headshape.pos = cfg.headshape; elseif ischar(cfg.headshape) % read the headshape from file headshape = ft_read_headshape(cfg.headshape); else error('cfg.headshape is not specified correctly') end if ~isfield(headshape, 'tri') % generate a closed triangulation from the surface points headshape.pos = unique(headshape.pos, 'rows'); headshape.tri = projecttri(headshape.pos); end % construct from the head surface pos = headsurface([], [], 'headshape', headshape, 'inwardshift', cfg.inwardshift, 'npnt', cfg.spheremesh); end % compute the forward model for the axial gradiometers fprintf('computing forward model for %d dipoles\n', size(pos,1)); lfold = ft_compute_leadfield(pos, axial.grad, headmodel); % construct the planar gradient definition and compute its forward model % this will not work for a localspheres model, compute_leadfield will catch % the error planar.grad = constructplanargrad([], axial.grad); lfnew = ft_compute_leadfield(pos, planar.grad, headmodel); % compute the interpolation matrix transform = lfnew * prunedinv(lfold, cfg.pruneratio); planarmontage = []; planarmontage.tra = transform; planarmontage.labelorg = axial.grad.label; planarmontage.labelnew = planar.grad.label; % apply the linear transformation to the data interp = ft_apply_montage(data, planarmontage, 'keepunused', 'yes'); % also apply the linear transformation to the gradiometer definition interp.grad = ft_apply_montage(data.grad, planarmontage, 'balancename', 'planar', 'keepunused', 'yes'); % ensure there is a type string describing the gradiometer definition if ~isfield(interp.grad, 'type') % put the original gradiometer type in (will get _planar appended) interp.grad.type = ft_senstype(data.grad); end interp.grad.type = [interp.grad.type '_planar']; % % interpolate the data towards the planar gradiometers % for i=1:Ntrials % fprintf('interpolating trial %d to planar gradiometer\n', i); % interp.trial{i} = transform * data.trial{i}(dataindx,:); % end % for Ntrials % % % all planar gradiometer channels are included in the output % interp.grad = planar.grad; % interp.label = planar.grad.label; % % % copy the non-gradiometer channels back into the output data % other = setdiff(1:Nchan, dataindx); % for i=other % interp.label{end+1} = data.label{i}; % for j=1:Ntrials % interp.trial{j}(end+1,:) = data.trial{j}(i,:); % end % end % else sens = ft_convert_units(data.grad); chanposnans = any(isnan(sens.chanpos(:))) || any(isnan(sens.chanori(:))); if chanposnans if isfield(sens, 'chanposorg') % temporarily replace chanpos and chanorig with the original values sens.chanpos = sens.chanposorg; sens.chanori = sens.chanoriorg; sens.label = sens.labelorg; sens = rmfield(sens, {'chanposorg', 'chanoriorg', 'labelorg'}); else error('The channel positions (and/or orientations) contain NaNs; this prohibits correct behavior of the function. Please replace the input channel definition with one that contains valid channel positions'); end end cfg.channel = ft_channelselection(cfg.channel, sens.label); cfg.channel = ft_channelselection(cfg.channel, data.label); % ensure channel order according to cfg.channel (there might be one check % too much in here somewhere or in the subfunctions, but I don't care. % Better one too much than one too little - JMH @ 09/19/12 cfg = struct(cfg); [neighbsel] = match_str({cfg.neighbours.label}, cfg.channel); cfg.neighbours = cfg.neighbours(neighbsel); cfg.neighbsel = channelconnectivity(cfg); % determine fprintf('average number of neighbours is %.2f\n', mean(sum(cfg.neighbsel))); Ngrad = length(sens.label); distance = zeros(Ngrad,Ngrad); for i=1:size(cfg.neighbsel,1) j=find(cfg.neighbsel(i, :)); d = sqrt(sum((sens.chanpos(j,:) - repmat(sens.chanpos(i, :), numel(j), 1)).^2, 2)); distance(i,j) = d; distance(j,i) = d; end fprintf('minimum distance between neighbours is %6.2f %s\n', min(distance(distance~=0)), sens.unit); fprintf('maximum distance between gradiometers is %6.2f %s\n', max(distance(distance~=0)), sens.unit); % The following does not work when running in deployed mode because the % private functions that compute the planar montage are not recognized as % such and won't be compiled, unless explicitly specified. % % generically call megplanar_orig megplanar_sincos or megplanar_fitplane %fun = ['megplanar_' cfg.planarmethod]; %if ~exist(fun, 'file') % error('unknown method for computation of planar gradient'); %end %planarmontage = eval([fun '(cfg, data.grad)']); switch cfg.planarmethod case 'sincos' planarmontage = megplanar_sincos(cfg, sens); case 'orig' % method specific info that is needed cfg.distance = distance; planarmontage = megplanar_orig(cfg, sens); case 'fitplane' planarmontage = megplanar_fitplane(cfg, sens); otherwise fun = ['megplanar_' cfg.planarmethod]; if ~exist(fun, 'file') error('unknown method for computation of planar gradient'); end planarmontage = eval([fun '(cfg, data.grad)']); end % apply the linear transformation to the data interp = ft_apply_montage(data, planarmontage, 'keepunused', 'yes', 'feedback', cfg.feedback); % also apply the linear transformation to the gradiometer definition interp.grad = ft_apply_montage(sens, planarmontage, 'balancename', 'planar', 'keepunused', 'yes'); % ensure there is a type string describing the gradiometer definition if ~isfield(interp.grad, 'type') % put the original gradiometer type in (will get _planar appended) interp.grad.type = ft_senstype(sens); end interp.grad.type = [interp.grad.type '_planar']; % add the chanpos info back into the gradiometer description tmplabel = interp.grad.label; for k = 1:numel(tmplabel) if ~isempty(strfind(tmplabel{k}, '_dV')) || ~isempty(strfind(tmplabel{k}, '_dH')) tmplabel{k} = tmplabel{k}(1:end-3); end end [ix,iy] = match_str(tmplabel, sens.label); interp.grad.chanpos(ix,:) = sens.chanpos(iy,:); % if the original chanpos contained nans, make sure to put nans in the % updated one as well, and move the updated chanpos values to chanposorg if chanposnans interp.grad.chanposorg = sens.chanpos; interp.grad.chanoriorg = sens.chanori; interp.grad.labelorg = sens.label; interp.grad.chanpos = nan(size(interp.grad.chanpos)); interp.grad.chanori = nan(size(interp.grad.chanori)); end end if istlck % convert the raw structure back into a timelock structure interp = ft_checkdata(interp, 'datatype', 'timelock'); israw = false; end % copy the trial specific information into the output if isfield(data, 'trialinfo') interp.trialinfo = data.trialinfo; end % copy the sampleinfo field as well if isfield(data, 'sampleinfo') interp.sampleinfo = data.sampleinfo; end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous data % rename the output variable to accomodate the savevar postamble data = interp; ft_postamble provenance data ft_postamble history data ft_postamble savevar data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that computes the inverse using a pruned SVD %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [lfi] = prunedinv(lf, r) [u, s, v] = svd(lf); p = find(s<(s(1,1)*r) & s~=0); fprintf('pruning %d out of %d singular values\n', length(p), min(size(s))); s(p) = 0; s(find(s~=0)) = 1./s(find(s~=0)); lfi = v * s' * u';
github
lcnbeapp/beapp-master
ft_movieplotTFR.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_movieplotTFR.m
17,026
utf_8
76fa25699ee966caae0c04b52d9eabea
function [cfg] = ft_movieplotTFR(cfg, data) % FT_MOVIEPLOTTFR makes a movie of the time-frequency representation of power or % coherence. % % Use as % ft_movieplotTFR(cfg, data) % where the input data comes from FT_FREQANALYSIS or FT_FREQDESCRIPTIVES and the % configuration is a structure that can contain % cfg.parameter = string, parameter that is color coded (default = 'avg') % cfg.xlim = selection boundaries over first dimension in data (e.g., time) % 'maxmin' or [xmin xmax] (default = 'maxmin') % cfg.ylim = selection boundaries over second dimension in data (e.g., freq) % 'maxmin' or [xmin xmax] (default = 'maxmin') % cfg.zlim = plotting limits for color dimension, 'maxmin', % 'maxabs', 'zeromax', 'minzero', or [zmin zmax] (default = 'maxmin') % cfg.samperframe = number, samples per fram (default = 1) % cfg.framespersec = number, frames per second (default = 5) % cfg.framesfile = [] (optional), no file saved, or 'string', filename of saved frames.mat (default = []); % cfg.moviefreq = number, movie frames are all time points at the fixed frequency moviefreq (default = []); % cfg.movietime = number, movie frames are all frequencies at the fixed time movietime (default = []); % cfg.layout = specification of the layout, see below % cfg.interactive = 'no' or 'yes', make it interactive % cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see FT_TIMELOCKBASELINE or FT_FREQBASELINE % cfg.baselinetype = 'absolute' or 'relative' (default = 'absolute') % cfg.colorbar = 'yes', 'no' (default = 'no') % % the layout defines how the channels are arranged. you can specify the % layout in a variety of ways: % - you can provide a pre-computed layout structure (see prepare_layout) % - you can give the name of an ascii layout file with extension *.mat % - you can give the name of an electrode file % - you can give an electrode definition, i.e. "elec" structure % - you can give a gradiometer definition, i.e. "grad" structure % if you do not specify any of these and the data structure contains an % electrode or gradiometer structure, that will be used for creating a % layout. if you want to have more fine-grained control over the layout % of the subplots, you should create your own layout file. % % to facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % if you specify this option the input data will be read from a *.mat % file on disk. this mat files should contain only a single variable named 'data', % corresponding to the input structure. % Copyright (c) 2009, Ingrid Nieuwenhuis % Copyright (c) 2011, jan-Mathijs Schoffelen, Robert Oostenveld, Cristiano Micheli % % this file is part of fieldtrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the gnu general public license as published by % the free software foundation, either version 3 of the license, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but without any warranty; without even the implied warranty of % merchantability or fitness for a particular purpose. see the % gnu general public license for more details. % % you should have received a copy of the gnu general public license % along with fieldtrip. if not, see <http://www.gnu.org/licenses/>. % % $id: ft_movieploter.m 4354 2011-10-05 15:06:02z crimic $ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar data ft_preamble provenance data ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input data is valid for this function % note that this function is also called from ft_movieplotER data = ft_checkdata(data, 'datatype', {'timelock', 'freq'}); % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'}); cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'parameter'}); cfg = ft_checkconfig(cfg, 'deprecated', {'xparam'}); % set the defaults cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin'); cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin'); cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin'); cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm'); % use power as default cfg.inputfile = ft_getopt(cfg, 'inputfile', []); cfg.samperframe = ft_getopt(cfg, 'samperframe', 1); cfg.framespersec = ft_getopt(cfg, 'framespersec', 5); cfg.framesfile = ft_getopt(cfg, 'framesfile', []); cfg.moviefreq = ft_getopt(cfg, 'moviefreq', []); cfg.movietime = ft_getopt(cfg, 'movietime', []); cfg.movierpt = ft_getopt(cfg, 'movierpt', 1); cfg.baseline = ft_getopt(cfg, 'baseline', 'no'); cfg.colorbar = ft_getopt(cfg, 'colorbar', 'no'); cfg.interactive = ft_getopt(cfg, 'interactive', 'yes'); dointeractive = istrue(cfg.interactive); xparam = 'time'; if isfield(data, 'freq') yparam = 'freq'; end % read or create the layout that will be used for plotting: layout = ft_prepare_layout(cfg, data); % apply optional baseline correction if ~strcmp(cfg.baseline, 'no') tmpcfg = keepfields(cfg, {'baseline', 'baselinetype', 'parameter'}); data = ft_freqbaseline(tmpcfg, data); [cfg, data] = rollback_provenance(cfg, data); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the actual computation is done in the middle part %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% xvalues = data.(xparam); parameter = data.(cfg.parameter); if exist('yparam', 'var') yvalues = data.(yparam); end % check consistency of xparam and yparam % NOTE: i set two different defaults for the 'chan_time' and the 'chan_freq_time' case if isfield(data,'dimord') if strcmp(data.dimord,'chan_freq_time') if length(xvalues)~=size(parameter,3) error('inconsistent size of "%s" compared to "%s"', cfg.parameter, xparam); end if length(yvalues)~=size(parameter,2) error('inconsistent size of "%s" compared to "%s"', cfg.parameter, yparam); end elseif strcmp(data.dimord,'chan_time') if length(xvalues)~=size(parameter,2) error('inconsistent size of "%s" compared to "%s"', cfg.parameter, xparam); end else error('input data is incompatible') end end if ischar(cfg.xlim) && strcmp(cfg.xlim, 'maxmin') cfg.xlim = []; cfg.xlim(1) = min(xvalues); cfg.xlim(2) = max(xvalues); end xbeg = nearest(xvalues, cfg.xlim(1)); xend = nearest(xvalues, cfg.xlim(2)); % update the configuration cfg.xlim = xvalues([xbeg xend]); if exist('yparam', 'var') if ischar(cfg.ylim) && strcmp(cfg.ylim, 'maxmin') cfg.ylim = []; cfg.ylim(1) = min(yvalues); cfg.ylim(2) = max(yvalues); end ybeg = nearest(yvalues, cfg.ylim(1)); yend = nearest(yvalues, cfg.ylim(2)); % update the configuration cfg.ylim = yvalues([ybeg yend]); hasyparam = true; else % this allows us not to worry about the yparam any more yvalues = nan; yparam = nan; ybeg = 1; yend = 1; cfg.ylim = []; hasyparam = false; end % select the channels in the data that match with the layout: [seldat, sellay] = match_str(data.label, layout.label); if isempty(seldat) error('labels in data and labels in layout do not match'); end % make a subselection of the data xvalues = xvalues(xbeg:xend); yvalues = yvalues(ybeg:yend); if all(isnan(yvalues)) parameter = parameter(seldat, xbeg:xend); else parameter = parameter(seldat, ybeg:yend, xbeg:xend); end clear xbeg xend ybeg yend % get the x and y coordinates and labels of the channels in the data chanx = layout.pos(sellay,1); chany = layout.pos(sellay,2); % get the z-range if ischar(cfg.zlim) && strcmp(cfg.zlim, 'maxmin') cfg.zlim = []; cfg.zlim(1) = min(parameter(:)); cfg.zlim(2) = max(parameter(:)); elseif ischar(cfg.zlim) && strcmp(cfg.zlim,'maxabs') cfg.zlim = []; cfg.zlim(1) = -max(abs(parameter(:))); cfg.zlim(2) = max(abs(parameter(:))); elseif ischar(cfg.zlim) && strcmp(cfg.zlim,'zeromax') cfg.zlim = []; cfg.zlim(1) = 0; cfg.zlim(2) = max(parameter(:)); elseif ischar(cfg.zlim) && strcmp(cfg.zlim,'minzero') cfg.zlim = []; cfg.zlim(1) = min(parameter(:)); cfg.zlim(2) = 0; end h = gcf; pos = get(gcf, 'position'); set(h, 'toolbar', 'figure'); if dointeractive % add the gui elements for changing the speed p = uicontrol('style', 'text'); set(p, 'position', [20 75 50 20]); set(p, 'string', 'speed') button_slower = uicontrol('style', 'pushbutton'); set(button_slower, 'position', [75 75 20 20]); set(button_slower, 'string', '-') set(button_slower, 'callback', @cb_speed); button_faster = uicontrol('style', 'pushbutton'); set(button_faster, 'position', [100 75 20 20]); set(button_faster, 'string', '+') set(button_faster, 'callback', @cb_speed); % add the gui elements for changing the color limits p = uicontrol('style', 'text'); set(p, 'position', [20 100 50 20]); set(p, 'string', 'zlim') button_slower = uicontrol('style', 'pushbutton'); set(button_slower, 'position', [75 100 20 20]); set(button_slower, 'string', '-') set(button_slower, 'callback', @cb_zlim); button_faster = uicontrol('style', 'pushbutton'); set(button_faster, 'position', [100 100 20 20]); set(button_faster, 'string', '+') set(button_faster, 'callback', @cb_zlim); sx = uicontrol('style', 'slider'); set(sx, 'position', [20 5 pos(3)-160 20]); % note that "sx" is needed further down sy = uicontrol('style', 'slider'); set(sy, 'position', [20 30 pos(3)-160 20]); % note that "sy" is needed further down p = uicontrol('style', 'pushbutton'); set(p, 'position', [20 50 50 20]); set(p, 'string', 'play') % note that "p" is needed further down hx = uicontrol('style', 'text'); set(hx, 'position', [pos(3)-140 5 120 20]); set(hx, 'string', sprintf('%s = ', xparam)); set(hx, 'horizontalalignment', 'left'); hy = uicontrol('style', 'text'); set(hy, 'position', [pos(3)-140 30 120 20]); set(hy, 'string', sprintf('%s = ', yparam)); set(hy, 'horizontalalignment', 'left'); if ~hasyparam set(hy, 'visible', 'off') set(sy, 'visible', 'off') end t = timer; set(t, 'timerfcn', {@cb_timer, h}, 'period', 0.1, 'executionmode', 'fixedspacing'); % collect the data and the options to be used in the figure opt.lay = layout; opt.chanx = chanx; opt.chany = chany; opt.xvalues = xvalues; % freq opt.yvalues = yvalues; % time opt.xparam = xparam; opt.yparam = yparam; opt.dat = parameter; opt.zlim = cfg.zlim; opt.speed = 1; opt.cfg = cfg; opt.sx = sx; % slider freq opt.sy = sy; % slider time opt.p = p; opt.t = t; opt.colorbar = istrue(cfg.colorbar); if ~hasyparam opt.timdim = 2; else opt.timdim = 3; end [dum, hs] = ft_plot_topo(chanx, chany, zeros(numel(chanx),1), 'mask', layout.mask, 'outline', layout.outline, 'interpmethod', 'v4', 'interplim', 'mask'); caxis(cfg.zlim); axis off; if opt.colorbar colorbar end % add sum stuff at a higher level for quicker access in the callback % routine opt.xdata = get(hs, 'xdata'); opt.ydata = get(hs, 'ydata'); opt.nanmask = get(hs, 'cdata'); % add the handle to the mesh opt.hs = hs; % add the text-handle to the guidata opt.hx = hx; opt.hy = hy; guidata(h, opt); % from now it is safe to hand over the control to the callback function set(sx, 'callback', @cb_slider); set(sy, 'callback', @cb_slider); % from now it is safe to hand over the control to the callback function set(p, 'callback', @cb_playbutton); else % non interactive mode [tmp, hs] = ft_plot_topo(chanx, chany, zeros(numel(chanx),1), 'mask', layout.mask, 'outline', layout.outline, 'interpmethod', 'v4'); caxis(cfg.zlim); axis off; xdata = get(hs, 'xdata'); ydata = get(hs, 'ydata'); nanmask = get(hs, 'cdata'); % frequency/time selection if exist('yparam', 'var') && any(~isnan(yvalues)) if ~isempty(cfg.movietime) indx = cfg.movietime; for iFrame = 1:floor(size(parameter, 2)/cfg.samperframe) indy = ((iFrame-1)*cfg.samperframe+1):iFrame*cfg.samperframe; datavector = reshape(mean(parameter(:, indy,indx), 2), [size(parameter,1) 1]); datamatrix = griddata(chanx, chany, datavector, xdata, ydata, 'v4'); set(hs, 'cdata', datamatrix + nanmask); F(iFrame) = getframe; end elseif ~isempty(cfg.moviefreq) indy = cfg.moviefreq; for iFrame = 1:floor(size(parameter, 3)/cfg.samperframe) indx = ((iFrame-1)*cfg.samperframe+1):iFrame*cfg.samperframe; datavector = reshape(mean(parameter(:, indy,indx), 3), [size(parameter,1) 1]); datamatrix = griddata(chanx, chany, datavector, xdata, ydata, 'v4'); set(hs, 'cdata', datamatrix + nanmask); F(iFrame) = getframe; end else error('Either moviefreq or movietime should contain a bin number') end else for iFrame = 1:floor(size(parameter, 2)/cfg.samperframe) indx = ((iFrame-1)*cfg.samperframe+1):iFrame*cfg.samperframe; datavector = mean(parameter(:, indx), 2); datamatrix = griddata(chanx, chany, datavector, xdata, ydata, 'v4'); set(hs, 'cdata', datamatrix + nanmask); F(iFrame) = getframe; end end % save movie if ~isempty(cfg.framesfile) save(cfg.framesfile, 'F'); end % play movie movie(F, cfg.movierpt, cfg.framespersec); end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous data ft_postamble provenance data ft_postamble history data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % subfunction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_slider(h, eventdata) opt = guidata(h); xdim = opt.timdim; valx = get(opt.sx, 'value'); valx = round(valx*(size(opt.dat,xdim)-1))+1; valx = min(valx, size(opt.dat,xdim)); valx = max(valx, 1); if valx>size(opt.dat,opt.timdim) valx = size(opt.dat,opt.timdim)-1; end if length(size(opt.dat))>2 ydim = 2; valy = get(opt.sy, 'value'); valy = round(valy*(size(opt.dat,ydim)-1))+1; valy = min(valy, size(opt.dat,ydim)); valy = max(valy, 1); set(opt.hx, 'string', sprintf('%s = %f\n', opt.xparam, opt.xvalues(valx))); set(opt.hy, 'string', sprintf('%s = %f\n', opt.yparam, opt.yvalues(valy))); % update data, interpolate and render datamatrix = griddata(opt.chanx, opt.chany, opt.dat(:,valy,valx), opt.xdata, opt.ydata, 'v4'); else set(opt.hx, 'string', sprintf('%s = %f\n', opt.xparam, opt.xvalues(valx))); % update data, interpolate and render datamatrix = griddata(opt.chanx, opt.chany, opt.dat(:,valx), opt.xdata, opt.ydata, 'v4'); end set(opt.hs, 'cdata', datamatrix + opt.nanmask); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % subfunction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_playbutton(h, eventdata) if ~ishandle(h) return end opt = guidata(h); switch get(h, 'string') case 'play' set(h, 'string', 'stop'); start(opt.t); case 'stop' set(h, 'string', 'play'); stop(opt.t); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % subfunction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_timer(obj, event, h) if ~ishandle(h) return end opt = guidata(h); delta = opt.speed/size(opt.dat,opt.timdim); val = get(opt.sx, 'value'); val = val + delta; % to avoid the slider to go out of range when the speed is too high if val+delta>2 val = get(opt.sx, 'value'); end if val>1 val = val-1; end set(opt.sx, 'value', val); cb_slider(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % subfunction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_zlim(h, eventdata) if ~ishandle(h) return end opt = guidata(h); switch get(h, 'string') case '+' caxis(caxis*sqrt(2)); case '-' caxis(caxis/sqrt(2)); end % switch guidata(h, opt); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % subfunction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_speed(h, eventdata) if ~ishandle(h) return end opt = guidata(h); switch get(h, 'string') case '+' opt.speed = opt.speed*sqrt(2); case '-' opt.speed = opt.speed/sqrt(2); % opt.speed = max(opt.speed, 1); % should not be smaller than 1 end % switch guidata(h, opt);
github
lcnbeapp/beapp-master
ft_volumerealign.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_volumerealign.m
81,513
utf_8
3af8300d106ef74f24d3ed3a77669407
function [realign, snap] = ft_volumerealign(cfg, mri, target) % FT_VOLUMEREALIGN spatially aligns an anatomical MRI with head coordinates based on % external fiducials or anatomical landmarks. This function does not change the % anatomical MRI volume itself, but only adjusts the homogeneous transformation % matrix that describes the mapping from voxels to the coordinate system. It also % appends a coordsys-field to the output data, or it updates it. This field specifies % how the x/y/z-axes of the coordinate system should be interpreted. % % For spatial normalisation and deformation (i.e. warping) an MRI to a template brain % you should use the FT_VOLUMENORMALISE function. % % Different methods for aligning the anatomical MRI to a coordinate system are % implemented, which are described in detail below: % % INTERACTIVE - Use a graphical user interface to click on the location of anatomical % fiducials. The coordinate system is updated according to the definition of the % coordinates of these fiducials. % % FIDUCIAL - The coordinate system is updated according to the definition of the % coordinates of fiducials that are specified in the configuration. % % HEADSHAPE - Match the head surface from the MRI with a measured head surface using % an iterative closest point procedure. The MRI will be updated to match the measured % head surface. This includes an optional manual coregistration of the two head % surfaces. % % SPM - align the individual MRI to the coordinate system of a target or template MRI % by matching the two volumes. % % FSL - align the individual MRI to the coordinate system of a target or template MRI % by matching the two volumes. % % Use as % [mri] = ft_volumerealign(cfg, mri) % or % [mri] = ft_volumerealign(cfg, mri, target) % where the input MRI should be an anatomical or functional MRI volume and the third % input argument is the the target anatomical MRI for SPM or FSL. % % The configuration can contain the following options % cfg.method = string representing the method for aligning % 'interactive' use the GUI to specify the fiducials % 'fiducial' use pre-specified fiducials % 'headshape' match the MRI surface to a headshape % 'spm' match to template anatomical MRI % 'fsl' match to template anatomical MRI % cfg.coordsys = string specifying the origin and the axes of the coordinate % system. Supported coordinate systems are 'ctf', '4d', % 'bti', 'yokogawa', 'asa', 'itab', 'neuromag', 'spm', % 'tal' and 'paxinos'. See http://tinyurl.com/ojkuhqz % cfg.clim = [min max], scaling of the anatomy color (default % is to adjust to the minimum and maximum) % cfg.parameter = 'anatomy' the parameter which is used for the % visualization % cfg.viewresult = string, 'yes' or 'no', whether or not to visualize aligned volume(s) % after realignment (default = 'no') % % When cfg.method = 'fiducial' and a coordinate system that is based on external % facial anatomical landmarks (common for EEG and MEG), the following is required to % specify the voxel indices of the fiducials: % cfg.fiducial.nas = [i j k], position of nasion % cfg.fiducial.lpa = [i j k], position of LPA % cfg.fiducial.rpa = [i j k], position of RPA % cfg.fiducial.zpoint = [i j k], a point on the positive z-axis. This is % an optional 'fiducial', and can be used to determine % whether the input voxel coordinate axes are left-handed % (i.e. flipped in one of the dimensions). If this additional % point is specified, and the voxel coordinate axes are left % handed, the volume is flipped to yield right handed voxel % axes. % % When cfg.method = 'fiducial' and cfg.coordsys = 'spm' or 'tal', the following % is required to specify the voxel indices of the fiducials: % cfg.fiducial.ac = [i j k], position of anterior commissure % cfg.fiducial.pc = [i j k], position of posterior commissure % cfg.fiducial.xzpoint = [i j k], point on the midsagittal-plane with a % positive Z-coordinate, i.e. an interhemispheric % point above ac and pc % The coordinate system will be according to the RAS_Tal convention i.e. % the origin corresponds with the anterior commissure the Y-axis is along % the line from the posterior commissure to the anterior commissure the % Z-axis is towards the vertex, in between the hemispheres the X-axis is % orthogonal to the YZ-plane, positive to the right % % When cfg.method = 'interactive', a user interface allows for the specification of % the fiducials or landmarks using the mouse, cursor keys and keyboard.The fiducials % can be specified by pressing the corresponding key on the keyboard (n/l/r or % a/p/z). When pressing q the interactive mode will stop and the transformation % matrix is computed. This method supports the following options: % cfg.viewmode = 'ortho' or 'surface', visualize the anatomical MRI as three % slices or visualize the extracted head surface (default = 'ortho') % cfg.snapshot = 'no' ('yes'), making a snapshot of the image once a % fiducial or landmark location is selected. The optional second % output argument to the function will contain the handles to these % figures. % cfg.snapshotfile = 'ft_volumerealign_snapshot' or string, the root of % the filename for the snapshots, including the path. If no path % is given the files are saved to the pwd. The consecutive % figures will be numbered and saved as png-file. % % When cfg.method = 'headshape', the function extracts the scalp surface from the % anatomical MRI, and aligns this surface with the user-supplied headshape. % Additional options pertaining to this method should be defined in the subcfg % cfg.headshape. The following option is required: % cfg.headshape.headshape = string pointing to a file describing a headshape or a % FieldTrip-structure describing a headshape, see FT_READ_HEADSHAPE % The following options are optional: % cfg.headshape.scalpsmooth = scalar, smoothing parameter for the scalp % extraction (default = 2) % cfg.headshape.scalpthreshold = scalar, threshold parameter for the scalp % extraction (default = 0.1) % cfg.headshape.interactive = 'yes' or 'no', use interactive realignment to % align headshape with scalp surface (default = % 'yes') % cfg.headshape.icp = 'yes' or 'no', use automatic realignment % based on the icp-algorithm. If both 'interactive' % and 'icp' are executed, the icp step follows the % interactive realignment step (default = 'yes') % % When cfg.method is 'fsl', a third input argument is required. The input volume is % coregistered to this target volume, using FSL-flirt. Additional options pertaining % to this method should be defined in the sub-structure cfg.fsl and can include: % cfg.fsl.path = string, specifying the path to fsl % cfg.fsl.costfun = string, specifying the cost-function used for % coregistration % cfg.fsl.interpmethod = string, specifying the interpolation method, can be % 'trilinear', 'nearestneighbour', or 'sinc' % cfg.fsl.dof = scalar, specifying the number of parameters for the % affine transformation. 6 (rigid body), 7 (global % rescale), 9 (traditional) or 12. % cfg.fsl.reslice = string, specifying whether the output image will be % resliced conform the target image (default = 'yes') % % When cfg.method = 'spm', a third input argument is required. The input volume is % coregistered to this target volume, using SPM. Additional options pertaining % to this method should be defined in the sub-structure cfg.spm and can include: % cfg.spm.regtype = 'subj', 'rigid' % cfg.spm.smosrc = scalar value % cfg.spm.smoref = scalar value % When cfg.spmversion is 'spm12', the following options apply: % cfg.spm.sep = optimisation sampling steps (mm), default: [4 2] % cfg.spm.params = starting estimates (6 elements), default: [0 0 0 0 0 0] % cfg.spm.cost_fun = cost function string: % 'mi' - Mutual Information (default) % 'nmi' - Normalised Mutual Information % 'ecc' - Entropy Correlation Coefficient % 'ncc' - Normalised Cross Correlation % cfg.spm.tol = tolerences for accuracy of each param, default: [0.02 0.02 0.02 0.001 0.001 0.001] % cfg.spm.fwhm = smoothing to apply to 256x256 joint histogram, default: [7 7] % % With the 'interactive' and 'fiducial' methods it is possible to define an % additional point (with the key 'z'), which should be a point on the positive side % of the xy-plane, i.e. with a positive z-coordinate in world coordinates. This point % will subsequently be used to check whether the input coordinate system is left or % right-handed. For the 'interactive' method you can also specify an additional % control point (with the key 'r'), that should be a point with a positive coordinate % on the left-right axis. % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % cfg.outputfile = ... % If you specify one of these (or both) the input data will be read from a % *.mat file on disk and/or the output data will be written to a *.mat % file. These mat files should contain only a single variable, % corresponding with the input/output structure. % % See also FT_READ_MRI, FT_ELECTRODEREALIGN, FT_DETERMINE_COORDSYS, SPM_AFFREG, % SPM_NORMALISE, SPM_COREG % Undocumented options: % % cfg.weights = vector of weights that is used to weight the individual headshape % points in the icp algorithm. Used optionally in cfg.method = 'headshape'. If not % specified, weights are put on points with z-coordinate<0 (assuming those to be eye % rims and nose ridges, i.e. important points. % Copyright (C) 2006-2014, Robert Oostenveld, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify it % under the terms of the GNU General Public License as published by the % Free Software Foundation, either version 3 of the License, or (at your % option) any later version. % % FieldTrip is distributed in the hope that it will be useful, but % WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU % General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar mri ft_preamble provenance mri ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % the data can be passed as input argument or can be read from disk hastarget = exist('target', 'var'); % check if the input data is valid for this function mri = ft_checkdata(mri, 'datatype', 'volume', 'feedback', 'yes'); % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'realignfiducial', 'fiducial'}); cfg = ft_checkconfig(cfg, 'renamed', {'landmark', 'fiducial'}); % cfg.landmark -> cfg.fiducial % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=2837 cfg = ft_checkconfig(cfg, 'renamed', {'viewdim', 'axisratio'}); % set the defaults cfg.coordsys = ft_getopt(cfg, 'coordsys', []); cfg.method = ft_getopt(cfg, 'method', []); % deal with this below cfg.fiducial = ft_getopt(cfg, 'fiducial', []); cfg.parameter = ft_getopt(cfg, 'parameter', 'anatomy'); cfg.clim = ft_getopt(cfg, 'clim', []); cfg.viewmode = ft_getopt(cfg, 'viewmode', 'ortho'); % for method=interactive cfg.snapshot = ft_getopt(cfg, 'snapshot', false); cfg.snapshotfile = ft_getopt(cfg, 'snapshotfile', fullfile(pwd, 'ft_volumerealign_snapshot')); cfg.spmversion = ft_getopt(cfg, 'spmversion', 'spm8'); cfg.voxelratio = ft_getopt(cfg, 'voxelratio', 'data'); % display size of the voxel, 'data' or 'square' cfg.axisratio = ft_getopt(cfg, 'axisratio', 'data'); % size of the axes of the three orthoplots, 'square', 'voxel', or 'data' cfg.viewresult = ft_getopt(cfg, 'viewresult', 'no'); % viewresult = istrue(cfg.viewresult); if isempty(cfg.method) if isempty(cfg.fiducial) % fiducials have not yet been specified cfg.method = 'interactive'; else % fiducials have already been specified cfg.method = 'fiducial'; end end if isempty(cfg.coordsys) if isstruct(cfg.fiducial) && all(ismember(fieldnames(cfg.fiducial), {'lpa', 'rpa', 'nas', 'zpoint'})) cfg.coordsys = 'ctf'; elseif isstruct(cfg.fiducial) && all(ismember(fieldnames(cfg.fiducial), {'ac', 'pc', 'xzpoint', 'right'})) cfg.coordsys = 'spm'; elseif strcmp(cfg.method, 'interactive') cfg.coordsys = 'ctf'; else error('you should specify the desired head coordinate system in cfg.coordsys') end warning('defaulting to %s coordinate system', cfg.coordsys); end % these two have to be simultaneously true for a snapshot to be taken dosnapshot = istrue(cfg.snapshot); if dosnapshot, % create an empty array of handles snap = []; end % select the parameter that should be displayed cfg.parameter = parameterselection(cfg.parameter, mri); if iscell(cfg.parameter) && ~isempty(cfg.parameter) cfg.parameter = cfg.parameter{1}; elseif iscell(cfg.parameter) && isempty(cfg.parameter) % cfg.parameter has been cleared by parameterselection due to a % dimensionality mismatch. Most probable cause here is the fact that a 4D % volume (e.g. DTI data) is in the input. This needs to be patched in a % more structural way at some point, but for the time being we'll use a % workaround here. % assume anatomy to be the parameter of interest siz = size(mri.anatomy); if all(siz(1:3)==mri.dim) && numel(siz)==4, % it's OK cfg.parameter= 'anatomy'; else error('there''s an unexpected dimension mismatch'); end end % start with an empty transform and coordsys transform = []; coordsys = []; if any(strcmp(cfg.method, {'fiducial', 'interactive'})) switch cfg.coordsys case {'ctf' '4d' 'bti' 'yokogawa' 'asa' 'itab' 'neuromag'} fidlabel = {'nas', 'lpa', 'rpa', 'zpoint'}; fidletter = {'n', 'l', 'r', 'z'}; fidexplanation1 = ' press n for nas, l for lpa, r for rpa\n'; fidexplanation2 = ' press z for an extra control point that should have a positive z-value\n'; case {'spm' 'tal'} fidlabel = {'ac', 'pc', 'xzpoint', 'right'}; fidletter = {'a', 'p', 'z', 'r'}; fidexplanation1 = ' press a for ac, p for pc, z for xzpoint\n'; fidexplanation2 = ' press r for an extra control point that should be on the right side\n'; case 'paxinos' fidlabel = {'bregma', 'lambda', 'yzpoint'}; fidletter = {'b', 'l', 'z'}; fidexplanation1 = ' press b for bregma, l for lambda, z for yzpoint\n'; fidexplanation2 = ''; otherwise error('unknown coordinate system "%s"', cfg.coordsys); end for i=1:length(fidlabel) if ~isfield(cfg.fiducial, fidlabel{i}) || isempty(cfg.fiducial.(fidlabel{i})) cfg.fiducial.(fidlabel{i}) = [nan nan nan]; end end end % interactive or fiducial switch cfg.method case 'fiducial' % the actual coordinate transformation will be done further down case 'landmark' % the actual coordinate transformation will be done further down case 'interactive' switch cfg.viewmode case 'ortho' % start building the figure h = figure; %set(h, 'color', [1 1 1]); set(h, 'visible', 'on'); % axes settings if strcmp(cfg.axisratio, 'voxel') % determine the number of voxels to be plotted along each axis axlen1 = mri.dim(1); axlen2 = mri.dim(2); axlen3 = mri.dim(3); elseif strcmp(cfg.axisratio, 'data') % determine the length of the edges along each axis [cp_voxel, cp_head] = cornerpoints(mri.dim, mri.transform); axlen1 = norm(cp_head(2,:)-cp_head(1,:)); axlen2 = norm(cp_head(4,:)-cp_head(1,:)); axlen3 = norm(cp_head(5,:)-cp_head(1,:)); elseif strcmp(cfg.axisratio, 'square') % the length of the axes should be equal axlen1 = 1; axlen2 = 1; axlen3 = 1; end % this is the size reserved for subplot h1, h2 and h3 h1size(1) = 0.82*axlen1/(axlen1 + axlen2); h1size(2) = 0.82*axlen3/(axlen2 + axlen3); h2size(1) = 0.82*axlen2/(axlen1 + axlen2); h2size(2) = 0.82*axlen3/(axlen2 + axlen3); h3size(1) = 0.82*axlen1/(axlen1 + axlen2); h3size(2) = 0.82*axlen2/(axlen2 + axlen3); if strcmp(cfg.voxelratio, 'square') voxlen1 = 1; voxlen2 = 1; voxlen3 = 1; elseif strcmp(cfg.voxelratio, 'data') % the size of the voxel is scaled with the data [cp_voxel, cp_head] = cornerpoints(mri.dim, mri.transform); voxlen1 = norm(cp_head(2,:)-cp_head(1,:))/norm(cp_voxel(2,:)-cp_voxel(1,:)); voxlen2 = norm(cp_head(4,:)-cp_head(1,:))/norm(cp_voxel(4,:)-cp_voxel(1,:)); voxlen3 = norm(cp_head(5,:)-cp_head(1,:))/norm(cp_voxel(5,:)-cp_voxel(1,:)); end %% the figure is interactive, add callbacks set(h, 'windowbuttondownfcn', @cb_buttonpress); set(h, 'windowbuttonupfcn', @cb_buttonrelease); set(h, 'windowkeypressfcn', @cb_keyboard); set(h, 'CloseRequestFcn', @cb_cleanup); % axis handles will hold the anatomical functional if present, along with labels etc. h1 = axes('position', [0.06 0.06+0.06+h3size(2) h1size(1) h1size(2)]); h2 = axes('position', [0.06+0.06+h1size(1) 0.06+0.06+h3size(2) h2size(1) h2size(2)]); h3 = axes('position', [0.06 0.06 h3size(1) h3size(2)]); set(h1, 'Tag', 'ik', 'Visible', 'off', 'XAxisLocation', 'top'); set(h2, 'Tag', 'jk', 'Visible', 'off', 'YAxisLocation', 'right'); % after rotating in ft_plot_ortho this becomes top set(h3, 'Tag', 'ij', 'Visible', 'off'); set(h1, 'DataAspectRatio', 1./[voxlen1 voxlen2 voxlen3]); set(h2, 'DataAspectRatio', 1./[voxlen1 voxlen2 voxlen3]); set(h3, 'DataAspectRatio', 1./[voxlen1 voxlen2 voxlen3]); xc = round(mri.dim(1)/2); % start with center view yc = round(mri.dim(2)/2); zc = round(mri.dim(3)/2); dat = double(mri.(cfg.parameter)); dmin = min(dat(:)); dmax = max(dat(:)); dat = (dat-dmin)./(dmax-dmin); if isfield(cfg, 'pnt') pnt = cfg.pnt; else pnt = zeros(0,3); end markerpos = zeros(0,3); markerlabel = {}; markercolor = {}; % determine clim if empty (setting to [0 1] could be done at the top, but not sure yet if it interacts with the other visualizations -roevdmei) if isempty(cfg.clim) cfg.clim = [min(dat(:)) min([.5 max(dat(:))])]; % end % determine apprioriate [left bottom width height] of intensity range sliders posbase = []; posbase(1) = h1size(1) + h2size(1)/2 + 0.06*2; % horizontal center of the second plot posbase(2) = h3size(2)/2 + 0.06; % vertical center of the third plot posbase(3) = 0.01; % width of the sliders is not so important, if it falls below a certain value, it's a vertical slider, otherwise a horizontal one posbase(4) = h3size(2)/3 + 0.06; % a third of the height of the third plot % posh45text = [posbase(1)-posbase(3)*5 posbase(2)-.1 posbase(3)*10 posbase(4)+0.07]; posh4text = [posbase(1)-.04-posbase(3)*2 posbase(2)-.1 posbase(3)*5 posbase(4)+0.035]; posh5text = [posbase(1)+.04-posbase(3)*2 posbase(2)-.1 posbase(3)*5 posbase(4)+0.035]; posh4slid = [posbase(1)-.04 posbase(2)-.1 posbase(3) posbase(4)]; posh5slid = [posbase(1)+.04 posbase(2)-.1 posbase(3) posbase(4)]; % intensity range sliders h45text = uicontrol('Style', 'text',... 'String', 'Intensity',... 'Units', 'normalized', ... 'Position',posh45text,... % text is centered, so height adjust vertical position 'HandleVisibility', 'on'); h4text = uicontrol('Style', 'text',... 'String', 'Min',... 'Units', 'normalized', ... 'Position',posh4text,... 'HandleVisibility', 'on'); h5text = uicontrol('Style', 'text',... 'String', 'Max',... 'Units', 'normalized', ... 'Position',posh5text,... 'HandleVisibility', 'on'); h4 = uicontrol('Style', 'slider', ... 'Parent', h, ... 'Min', 0, 'Max', 1, ... 'Value', cfg.clim(1), ... 'Units', 'normalized', ... 'Position', posh4slid, ... 'Callback', @cb_minslider); h5 = uicontrol('Style', 'slider', ... 'Parent', h, ... 'Min', 0, 'Max', 1, ... 'Value', cfg.clim(2), ... 'Units', 'normalized', ... 'Position', posh5slid, ... 'Callback', @cb_maxslider); % instructions to the user fprintf(strcat(... '1. To change the slice viewed in one plane, either:\n',... ' a. click (left mouse) in the image on a different plane. Eg, to view a more\n',... ' superior slice in the horizontal plane, click on a superior position in the\n',... ' coronal plane, or\n',... ' b. use the arrow keys to increase or decrease the slice number by one\n',... '2. To mark a fiducial position or anatomical landmark, do BOTH:\n',... ' a. select the position by clicking on it in any slice with the left mouse button\n',... ' b. identify it by pressing the letter corresponding to the fiducial/landmark:\n', fidexplanation1, fidexplanation2, ... ' You can mark the fiducials multiple times, until you are satisfied with the positions.\n',... '3. To change the display:\n',... ' a. press c on keyboard to toggle crosshair visibility\n',... ' b. press f on keyboard to toggle fiducial visibility\n',... ' c. press + or - on (numeric) keyboard to change the color range''s upper limit\n',... '4. To finalize markers and quit interactive mode, press q on keyboard\n')); % create structure to be passed to gui opt = []; opt.viewresult = false; % flag to use for certain keyboard/redraw calls opt.twovol = false; % flag to use for certain options of viewresult opt.dim = mri.dim; opt.ijk = [xc yc zc]; opt.h1size = h1size; opt.h2size = h2size; opt.h3size = h3size; opt.handlesaxes = [h1 h2 h3]; opt.handlesfigure = h; opt.quit = false; opt.ana = dat; opt.update = [1 1 1]; opt.init = true; opt.tag = 'ik'; opt.mri = mri; opt.showcrosshair = true; opt.showmarkers = false; opt.markers = {markerpos markerlabel markercolor}; opt.clim = cfg.clim; opt.fiducial = cfg.fiducial; opt.fidlabel = fidlabel; opt.fidletter = fidletter; opt.pnt = pnt; if isfield(mri, 'unit') && ~strcmp(mri.unit, 'unknown') opt.unit = mri.unit; % this is shown in the feedback on screen else opt.unit = ''; % this is not shown end setappdata(h, 'opt', opt); cb_redraw(h); case 'surface' % make a mesh from the skin surface cfg.headshape = ft_getopt(cfg, 'headshape'); cfg.headshape.scalpsmooth = ft_getopt(cfg.headshape, 'scalpsmooth', 2, 1); % empty is OK cfg.headshape.scalpthreshold = ft_getopt(cfg.headshape, 'scalpthreshold', 0.1); if ~isfield(mri, 'scalp') || ~islogical(mri.scalp) % extract the scalp surface from the anatomical image tmpcfg = []; tmpcfg.output = 'scalp'; tmpcfg.scalpsmooth = cfg.headshape.scalpsmooth; tmpcfg.scalpthreshold = cfg.headshape.scalpthreshold; if isfield(cfg, 'template') tmpcfg.template = cfg.template; end seg = ft_volumesegment(tmpcfg, mri); else % use the scalp segmentation that is provided seg = mri; end tmpcfg = []; tmpcfg.tissue = 'scalp'; tmpcfg.method = 'isosurface'; tmpcfg.numvertices = inf; scalp = ft_prepare_mesh(tmpcfg, seg); scalp = ft_convert_units(scalp, 'mm'); fprintf('\n'); fprintf(strcat(... '1. To change the orientation of the head surface, use the\n',... '"Rotate 3D" option in the figure toolbar\n',... '2. To mark a fiducial position or anatomical landmark, do BOTH:\n',... ' a. select the position by clicking on it with the left mouse button\n',... ' b. specify it by pressing the letter corresponding to the fiducial/landmark:\n', fidexplanation1, fidexplanation2, ... ' You can mark the fiducials multiple times, until you are satisfied with the positions.\n',... '3. To finalize markers and quit interactive mode, press q on keyboard\n')); % start building the figure h = figure; set(h, 'color', [1 1 1]); set(h, 'visible', 'on'); % add callbacks set(h, 'windowkeypressfcn', @cb_keyboard_surface); set(h, 'CloseRequestFcn', @cb_cleanup); % create figure handles h1 = axes; % create structure to be passed to gui opt = []; opt.viewresult = false; % flag to use for certain keyboard/redraw calls opt.handlesfigure = h; opt.handlesaxes = h1; opt.handlesfigure = h; opt.handlesmarker = []; opt.camlighthandle = []; opt.init = true; opt.quit = false; opt.scalp = scalp; opt.showmarkers = false; opt.mri = mri; opt.fiducial = cfg.fiducial; opt.fidlabel = fidlabel; opt.fidletter = fidletter; opt.fidexplanation1 = fidexplanation1; if isfield(scalp, 'unit') && ~strcmp(scalp.unit, 'unknown') opt.unit = scalp.unit; % this is shown in the feedback on screen else opt.unit = ''; % this is not shown end setappdata(h, 'opt', opt); cb_redraw_surface(h); end % switch viewmode while(opt.quit==0) uiwait(h); opt = getappdata(h, 'opt'); end delete(h); % store the interactively determined fiducials in the configuration % the actual coordinate transformation will be done further down cfg.fiducial = opt.fiducial; case 'headshape' if isa(cfg.headshape, 'config') cfg.headshape = struct(cfg.headshape); end if ischar(cfg.headshape) % old-style specification, convert cfg into new representation cfg.headshape = struct('headshape', cfg.headshape); if isfield(cfg, 'scalpsmooth'), cfg.headshape.scalpsmooth = cfg.scalpsmooth; cfg = rmfield(cfg, 'scalpsmooth'); end if isfield(cfg, 'scalpthreshold'), cfg.headshape.scalpthreshold = cfg.scalpthreshold; cfg = rmfield(cfg, 'scalpthreshold'); end elseif isstruct(cfg.headshape) && isfield(cfg.headshape, 'pos') % old-style specification, convert into new representation cfg.headshape = struct('headshape', cfg.headshape); if isfield(cfg, 'scalpsmooth'), cfg.headshape.scalpsmooth = cfg.scalpsmooth; cfg = rmfield(cfg, 'scalpsmooth'); end if isfield(cfg, 'scalpthreshold'), cfg.headshape.scalpthreshold = cfg.scalpthreshold; cfg = rmfield(cfg, 'scalpthreshold'); end elseif isstruct(cfg.headshape) % new-style specification, do nothing else error('incorrect specification of cfg.headshape'); end if ischar(cfg.headshape.headshape) shape = ft_read_headshape(cfg.headshape.headshape); else shape = cfg.headshape.headshape; end shape = ft_convert_units(shape, mri.unit); % make the units of the headshape consistent with the MRI cfg.headshape.interactive = ft_getopt(cfg.headshape, 'interactive', true); cfg.headshape.icp = ft_getopt(cfg.headshape, 'icp', true); cfg.headshape.scalpsmooth = ft_getopt(cfg.headshape, 'scalpsmooth', 2, 1); % empty is OK cfg.headshape.scalpthreshold = ft_getopt(cfg.headshape, 'scalpthreshold', 0.1); dointeractive = istrue(cfg.headshape.interactive); doicp = istrue(cfg.headshape.icp); if ~isfield(mri, 'scalp') || ~islogical(mri.scalp) % extract the scalp surface from the anatomical image tmpcfg = []; tmpcfg.output = 'scalp'; tmpcfg.scalpsmooth = cfg.headshape.scalpsmooth; tmpcfg.scalpthreshold = cfg.headshape.scalpthreshold; if isfield(cfg, 'template') tmpcfg.template = cfg.template; end seg = ft_volumesegment(tmpcfg, mri); else % use the scalp segmentation that is provided seg = mri; end tmpcfg = []; tmpcfg.tissue = 'scalp'; tmpcfg.method = 'projectmesh';%'isosurface'; tmpcfg.numvertices = 20000; scalp = ft_prepare_mesh(tmpcfg, seg); if dointeractive, fprintf('doing interactive realignment with headshape\n'); tmpcfg = []; tmpcfg.template.elec = shape; % this is the Polhemus recorded headshape tmpcfg.template.elec.chanpos = shape.pos; % ft_interactiverealign needs the field chanpos tmpcfg.template.elec.label = cellstr(num2str((1:size(shape.pos,1))')); tmpcfg.individual.headshape = scalp; % this is the headshape extracted from the anatomical MRI tmpcfg.individual.headshapestyle = 'surface'; tmpcfg = ft_interactiverealign(tmpcfg); M = tmpcfg.m; cfg.transform_interactive = M; % touch it to survive trackconfig cfg.transform_interactive; % update the relevant geometrical info scalp = ft_transform_geometry(M, scalp); end % dointeractive % always perform an icp-step, because this will give an estimate of the % initial distance of the corresponding points. depending on the value % for doicp, deal with the output differently if doicp, numiter = 50; else numiter = 1; end if ~isfield(cfg, 'weights') w = ones(size(shape.pos,1),1); else w = cfg.weights(:); if numel(w)~=size(shape.pos,1), error('number of weights should be equal to the number of points in the headshape'); end end % the icp function wants this as a function handle. weights = @(x)assignweights(x,w); ft_hastoolbox('fileexchange',1); % construct the coregistration matrix nrm = normals(scalp.pos, scalp.tri, 'vertex'); [R, t, err, dummy, info] = icp(scalp.pos', shape.pos', numiter, 'Minimize', 'plane', 'Normals', nrm', 'Weight', weights, 'Extrapolation', true, 'WorstRejection', 0.05); if doicp, fprintf('doing iterative closest points realignment with headshape\n'); % create the additional transformation matrix and compute the % distance between the corresponding points, both prior and after icp % this one transforms from scalp 'headspace' to shape 'headspace' M2 = inv([R t;0 0 0 1]); % warp the extracted scalp points to the new positions scalp.pos = ft_warp_apply(M2, scalp.pos); target = scalp; target.pos = target.pos; target.inside = (1:size(target.pos,1))'; functional = rmfield(shape, 'pos'); functional.distance = info.distanceout(:); functional.pos = info.qout'; tmpcfg = []; tmpcfg.parameter = 'distance'; tmpcfg.interpmethod = 'sphere_avg'; tmpcfg.sphereradius = 10; tmpcfg.feedback = 'none'; smoothdist = ft_sourceinterpolate(tmpcfg, functional, target); scalp.distance = smoothdist.distance(:); functional.pow = info.distancein(:); smoothdist = ft_sourceinterpolate(tmpcfg, functional, target); scalp.distancein = smoothdist.distance(:); cfg.icpinfo = info; cfg.transform_icp = M2; % touch it to survive trackconfig cfg.icpinfo; cfg.transform_icp; else % compute the distance between the corresponding points, prior to icp: % this corresponds to the final result after interactive only M2 = eye(4); % this is needed later on target = scalp; target.pos = target.pos; target.inside = (1:size(target.pos,1))'; functional = rmfield(shape, 'pos'); functional.pow = info.distancein(:); functional.pos = info.qout'; tmpcfg = []; tmpcfg.parameter = 'pow'; tmpcfg.interpmethod = 'sphere_avg'; tmpcfg.sphereradius = 10; smoothdist = ft_sourceinterpolate(tmpcfg, functional, target); scalp.distance = smoothdist.pow(:); end % doicp % create headshape structure for mri-based surface point cloud if isfield(mri, 'coordsys') scalp.coordsys = mri.coordsys; % coordsys is the same as input mri coordsys = mri.coordsys; else coordsys = 'unknown'; end % update the cfg cfg.headshape.headshape = shape; cfg.headshape.headshapemri = scalp; % touch it to survive trackconfig cfg.headshape; if doicp && dointeractive transform = M2*M; elseif doicp transform = M2; elseif dointeractive transform = M; end case 'fsl' if ~isfield(cfg, 'fsl'), cfg.fsl = []; end cfg.fsl.path = ft_getopt(cfg.fsl, 'path', ''); cfg.fsl.costfun = ft_getopt(cfg.fsl, 'costfun', 'corratio'); cfg.fsl.interpmethod = ft_getopt(cfg.fsl, 'interpmethod', 'trilinear'); cfg.fsl.dof = ft_getopt(cfg.fsl, 'dof', 6); cfg.fsl.reslice = ft_getopt(cfg.fsl, 'reslice', 'yes'); cfg.fsl.searchrange = ft_getopt(cfg.fsl, 'searchrange', [-180 180]); % write the input and target to a temporary file % and create some additional temporary file names to contain the output tmpname1 = tempname; tmpname2 = tempname; tmpname3 = tempname; tmpname4 = tempname; tmpcfg = []; tmpcfg.parameter = 'anatomy'; tmpcfg.filename = tmpname1; tmpcfg.filetype = 'nifti'; fprintf('writing the input volume to a temporary file: %s\n', [tmpname1, '.nii']); ft_volumewrite(tmpcfg, mri); tmpcfg.filename = tmpname2; fprintf('writing the target volume to a temporary file: %s\n', [tmpname2, '.nii']); ft_volumewrite(tmpcfg, target); % create the command to call flirt fprintf('using flirt for the coregistration\n'); r1 = num2str(cfg.fsl.searchrange(1)); r2 = num2str(cfg.fsl.searchrange(2)); str = sprintf('%s/flirt -in %s -ref %s -out %s -omat %s -bins 256 -cost %s -searchrx %s %s -searchry %s %s -searchrz %s %s -dof %s -interp %s',... cfg.fsl.path, tmpname1, tmpname2, tmpname3, tmpname4, cfg.fsl.costfun, r1, r2, r1, r2, r1, r2, num2str(cfg.fsl.dof), cfg.fsl.interpmethod); if isempty(cfg.fsl.path), str = str(2:end); end % remove the first filesep, assume path to flirt to be known % system call system(str); % process the output if ~istrue(cfg.fsl.reslice) % get the transformation that corresponds to the coregistration and % reconstruct the mapping from the target's world coordinate system % to the input's voxel coordinate system vox = fopen(tmpname4); tmp = textscan(vox, '%f'); fclose(vox); % this transforms from input voxels to target voxels vox2vox = reshape(tmp{1},4,4)'; if det(target.transform(1:3,1:3))>0 % flirt apparently flips along the x-dim if the det < 0 % if images are not radiological, the x-axis is flipped, see: % https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=ind0810&L=FSL&P=185638 % https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=ind0903&L=FSL&P=R93775 % flip back flipmat = eye(4); flipmat(1,1) = -1; flipmat(1,4) = target.dim(1); vox2vox = flipmat*vox2vox; end if det(mri.transform(1:3,1:3))>0 % flirt apparently flips along the x-dim if the det < 0 % flip back flipmat = eye(4); flipmat(1,1) = -1; flipmat(1,4) = mri.dim(1); vox2vox = vox2vox*flipmat; end % very not sure about this (e.g. is vox2vox really doing what I think % it is doing? should I care about 0 and 1 based conventions?) % changing handedness? mri.transform = target.transform*vox2vox; transform = eye(4); if isfield(target, 'coordsys') coordsys = target.coordsys; else coordsys = 'unknown'; end else % get the updated anatomy mrinew = ft_read_mri([tmpname3, '.nii.gz']); mri.anatomy = mrinew.anatomy; mri.transform = mrinew.transform; mri.dim = mrinew.dim; transform = eye(4); if isfield(target, 'coordsys') coordsys = target.coordsys; else coordsys = 'unknown'; end end delete([tmpname1, '.nii']); delete([tmpname2, '.nii']); delete([tmpname3, '.nii.gz']); delete(tmpname4); case 'spm' % ensure that SPM is on the path if strcmpi(cfg.spmversion, 'spm2'), ft_hastoolbox('SPM2',1); elseif strcmpi(cfg.spmversion, 'spm8'), ft_hastoolbox('SPM8',1); elseif strcmpi(cfg.spmversion, 'spm12'), ft_hastoolbox('SPM12',1); end if strcmpi(cfg.spmversion, 'spm2') || strcmpi(cfg.spmversion, 'spm8') if ~isfield(cfg, 'spm'), cfg.spm = []; end cfg.spm.regtype = ft_getopt(cfg.spm, 'regtype', 'subj'); cfg.spm.smosrc = ft_getopt(cfg.spm, 'smosrc', 2); cfg.spm.smoref = ft_getopt(cfg.spm, 'smoref', 2); if ~isfield(mri, 'coordsys'), mri = ft_convert_coordsys(mri); else fprintf('Input volume has coordinate system ''%s''\n', mri.coordsys); end if ~isfield(target, 'coordsys'), target = ft_convert_coordsys(target); else fprintf('Target volume has coordinate system ''%s''\n', target.coordsys); end if strcmp(mri.coordsys, target.coordsys) % this should hopefully work else % only works when it is possible to approximately align the input to % the target coordsys if strcmp(target.coordsys, 'spm') mri = ft_convert_coordsys(mri, 'spm'); else error('The coordinate systems of the input and target volumes are different, coregistration is not possible'); end end % flip and permute the 3D volume itself, so that the voxel and % headcoordinates approximately correspond [tmp, pvec_mri, flip_mri, T] = align_ijk2xyz(mri); [target] = align_ijk2xyz(target); tname1 = [tempname, '.img']; tname2 = [tempname, '.img']; V1 = ft_write_mri(tname1, mri.anatomy, 'transform', mri.transform, 'spmversion', spm('ver'), 'dataformat', 'nifti_spm'); V2 = ft_write_mri(tname2, target.anatomy, 'transform', target.transform, 'spmversion', spm('ver'), 'dataformat', 'nifti_spm'); flags = cfg.spm; flags.nits = 0; %set number of non-linear iterations to zero params = spm_normalise(V2,V1, [], [], [],flags); %mri.transform = (target.transform/params.Affine)/T; transform = (target.transform/params.Affine)/T/mri.transform; % transform = eye(4); elseif strcmpi(cfg.spmversion, 'spm12') if ~isfield(cfg, 'spm'), cfg.spm = []; end tname1 = [tempname, '.nii']; tname2 = [tempname, '.nii']; V1 = ft_write_mri(tname1, mri.anatomy, 'transform', mri.transform, 'spmversion', spm('ver'), 'dataformat', 'nifti_spm'); % source (moved) image V2 = ft_write_mri(tname2, target.anatomy, 'transform', target.transform, 'spmversion', spm('ver'), 'dataformat', 'nifti_spm'); % reference image flags = cfg.spm; x = spm_coreg(V2,V1,flags); % spm_realign does within modality rigid body movement parameter estimation transform = inv(spm_matrix(x(:)')); % from V1 to V2, to be multiplied still with the original transform (mri.transform), see below end if isfield(target, 'coordsys') coordsys = target.coordsys; else coordsys = 'unknown'; end % delete the temporary files delete(tname1); delete(tname2); otherwise error('unsupported method "%s"', cfg.method); end if any(strcmp(cfg.method, {'fiducial', 'interactive'})) % the fiducial locations are specified in voxels, convert them to head % coordinates according to the existing transform matrix fid1_vox = cfg.fiducial.(fidlabel{1}); fid2_vox = cfg.fiducial.(fidlabel{2}); fid3_vox = cfg.fiducial.(fidlabel{3}); fid1_head = ft_warp_apply(mri.transform, fid1_vox); fid2_head = ft_warp_apply(mri.transform, fid2_vox); fid3_head = ft_warp_apply(mri.transform, fid3_vox); if length(fidlabel)>3 % the 4th point is optional fid4_vox = cfg.fiducial.(fidlabel{4}); fid4_head = ft_warp_apply(mri.transform, fid4_vox); else fid4_head = [nan nan nan]; end if ~any(isnan(fid4_head)) [transform, coordsys] = ft_headcoordinates(fid1_head, fid2_head, fid3_head, fid4_head, cfg.coordsys); else [transform, coordsys] = ft_headcoordinates(fid1_head, fid2_head, fid3_head, cfg.coordsys); end end % copy the input anatomical or functional volume realign = mri; if ~isempty(transform) && ~any(isnan(transform(:))) % combine the additional transformation with the original one realign.transformorig = mri.transform; realign.transform = transform * mri.transform; realign.coordsys = coordsys; else warning('no coordinate system realignment has been done'); end % visualize result % all plotting for the realignment is done in voxel space % for view the results however, it needs be in coordinate system space (necessary for the two volume case below) % to be able to reuse all the plotting code, several workarounds are in place, which convert the indices % from voxel space to the target coordinate system space if viewresult % set flags for one or twovol case if hastarget twovol = true; % input was two volumes, base to be plotted on is called target, the aligned mri is named realign basevol = target; else twovol = false; % input was one volumes, base is called realign basevol = realign; end % input was a single vol % start building the figure h = figure('numbertitle', 'off', 'name', 'realignment result'); set(h, 'visible', 'on'); % axes settings if strcmp(cfg.axisratio, 'voxel') % determine the number of voxels to be plotted along each axis axlen1 = basevol.dim(1); axlen2 = basevol.dim(2); axlen3 = basevol.dim(3); elseif strcmp(cfg.axisratio, 'data') % determine the length of the edges along each axis [cp_voxel, cp_head] = cornerpoints(basevol.dim, basevol.transform); axlen1 = norm(cp_head(2,:)-cp_head(1,:)); axlen2 = norm(cp_head(4,:)-cp_head(1,:)); axlen3 = norm(cp_head(5,:)-cp_head(1,:)); elseif strcmp(cfg.axisratio, 'square') % the length of the axes should be equal axlen1 = 1; axlen2 = 1; axlen3 = 1; end % this is the size reserved for subplot h1, h2 and h3 h1size(1) = 0.82*axlen1/(axlen1 + axlen2); h1size(2) = 0.82*axlen3/(axlen2 + axlen3); h2size(1) = 0.82*axlen2/(axlen1 + axlen2); h2size(2) = 0.82*axlen3/(axlen2 + axlen3); h3size(1) = 0.82*axlen1/(axlen1 + axlen2); h3size(2) = 0.82*axlen2/(axlen2 + axlen3); if strcmp(cfg.voxelratio, 'square') voxlen1 = 1; voxlen2 = 1; voxlen3 = 1; elseif strcmp(cfg.voxelratio, 'data') % the size of the voxel is scaled with the data [cp_voxel, cp_head] = cornerpoints(basevol.dim, basevol.transform); voxlen1 = norm(cp_head(2,:)-cp_head(1,:))/norm(cp_voxel(2,:)-cp_voxel(1,:)); voxlen2 = norm(cp_head(4,:)-cp_head(1,:))/norm(cp_voxel(4,:)-cp_voxel(1,:)); voxlen3 = norm(cp_head(5,:)-cp_head(1,:))/norm(cp_voxel(5,:)-cp_voxel(1,:)); end %% the figure is interactive, add callbacks set(h, 'windowbuttondownfcn', @cb_buttonpress); set(h, 'windowbuttonupfcn', @cb_buttonrelease); set(h, 'windowkeypressfcn', @cb_keyboard); set(h, 'CloseRequestFcn', @cb_cleanup); % axis handles will hold the anatomical functional if present, along with labels etc. h1 = axes('position', [0.06 0.06+0.06+h3size(2) h1size(1) h1size(2)]); h2 = axes('position', [0.06+0.06+h1size(1) 0.06+0.06+h3size(2) h2size(1) h2size(2)]); h3 = axes('position', [0.06 0.06 h3size(1) h3size(2)]); set(h1, 'Tag', 'ik', 'Visible', 'off', 'XAxisLocation', 'top'); set(h2, 'Tag', 'jk', 'Visible', 'off', 'YAxisLocation', 'right'); % after rotating in ft_plot_ortho this becomes top set(h3, 'Tag', 'ij', 'Visible', 'off'); set(h1, 'DataAspectRatio', 1./[voxlen1 voxlen2 voxlen3]); set(h2, 'DataAspectRatio', 1./[voxlen1 voxlen2 voxlen3]); set(h3, 'DataAspectRatio', 1./[voxlen1 voxlen2 voxlen3]); % start with center view xc = round(basevol.dim(1)/2); yc = round(basevol.dim(2)/2); zc = round(basevol.dim(3)/2); % normalize data to go from 0 to 1 dat = double(basevol.(cfg.parameter)); dmin = min(dat(:)); dmax = max(dat(:)); dat = (dat-dmin)./(dmax-dmin); if hastarget % do the same for the target realigndat = double(realign.(cfg.parameter)); dmin = min(realigndat(:)); dmax = max(realigndat(:)); realigndat = (realigndat-dmin)./(dmax-dmin); end if isfield(cfg, 'pnt') pnt = cfg.pnt; else pnt = zeros(0,3); end markerpos = zeros(0,3); markerlabel = {}; markercolor = {}; % determine clim if empty (setting to [0 1] could be done at the top, but not sure yet if it interacts with the other visualizations -roevdmei) if isempty(cfg.clim) cfg.clim = [min(dat(:)) min([.5 max(dat(:))])]; % end % determine apprioriate [left bottom width height] of intensity range sliders posbase = []; posbase(1) = h1size(1) + h2size(1)/2 + 0.06*2; % horizontal center of the second plot posbase(2) = h3size(2)/2 + 0.06; % vertical center of the third plot posbase(3) = 0.01; % width of the sliders is not so important, if it falls below a certain value, it's a vertical slider, otherwise a horizontal one posbase(4) = h3size(2)/3 + 0.06; % a third of the height of the third plot % posh45text = [posbase(1)-posbase(3)*5 posbase(2)-.1 posbase(3)*10 posbase(4)+0.07]; posh4text = [posbase(1)-.04-posbase(3)*2 posbase(2)-.1 posbase(3)*5 posbase(4)+0.035]; posh5text = [posbase(1)+.04-posbase(3)*2 posbase(2)-.1 posbase(3)*5 posbase(4)+0.035]; posh4slid = [posbase(1)-.04 posbase(2)-.1 posbase(3) posbase(4)]; posh5slid = [posbase(1)+.04 posbase(2)-.1 posbase(3) posbase(4)]; % intensity range sliders if twovol h45texttar = uicontrol('Style', 'text',... 'String', 'Intensity target volume (red)',... 'Units', 'normalized', ... 'Position',posh45text,... 'HandleVisibility', 'on'); h4texttar = uicontrol('Style', 'text',... 'String', 'Min',... 'Units', 'normalized', ... 'Position',posh4text,... 'HandleVisibility', 'on'); h5texttar = uicontrol('Style', 'text',... 'String', 'Max',... 'Units', 'normalized', ... 'Position',posh5text,... 'HandleVisibility', 'on'); h4tar = uicontrol('Style', 'slider', ... 'Parent', h, ... 'Min', 0, 'Max', 1, ... 'Value', cfg.clim(1), ... 'Units', 'normalized', ... 'Position', posh4slid, ... 'Callback', @cb_minslider,... 'tag', 'tar'); h5tar = uicontrol('Style', 'slider', ... 'Parent', h, ... 'Min', 0, 'Max', 1, ... 'Value', cfg.clim(2), ... 'Units', 'normalized', ... 'Position', posh5slid, ... 'Callback', @cb_maxslider,... 'tag', 'tar'); end % intensity range sliders if ~twovol str = 'Intensity realigned volume'; else str = 'Intensity realigned volume (blue)'; end h45textrel = uicontrol('Style', 'text',... 'String',str,... 'Units', 'normalized', ... 'Position',posh45text,... 'HandleVisibility', 'on'); h4textrel = uicontrol('Style', 'text',... 'String', 'Min',... 'Units', 'normalized', ... 'Position',posh4text,... 'HandleVisibility', 'on'); h5textrel = uicontrol('Style', 'text',... 'String', 'Max',... 'Units', 'normalized', ... 'Position',posh5text,... 'HandleVisibility', 'on'); h4rel = uicontrol('Style', 'slider', ... 'Parent', h, ... 'Min', 0, 'Max', 1, ... 'Value', cfg.clim(1), ... 'Units', 'normalized', ... 'Position', posh4slid, ... 'Callback', @cb_minslider,... 'tag', 'rel'); h5rel = uicontrol('Style', 'slider', ... 'Parent', h, ... 'Min', 0, 'Max', 1, ... 'Value', cfg.clim(2), ... 'Units', 'normalized', ... 'Position', posh5slid, ... 'Callback', @cb_maxslider,... 'tag', 'rel'); % create structure to be passed to gui opt = []; opt.twovol = twovol; opt.viewresult = true; % flag to use for certain keyboard/redraw calls opt.dim = basevol.dim; opt.ijk = [xc yc zc]; opt.h1size = h1size; opt.h2size = h2size; opt.h3size = h3size; opt.handlesaxes = [h1 h2 h3]; opt.handlesfigure = h; opt.quit = false; opt.ana = dat; % keep this as is, to avoid making exceptions for opt.viewresult all over the plotting code if twovol opt.realignana = realigndat; % set up the masks in an intelligent way based on the percentile of the anatomy (this avoids extremely skewed data making one of the vols too transparent) sortana = sort(dat(:)); cutoff = sortana(find(cumsum(sortana ./ sum(sortana(:)))>.99,1)); mask = dat; mask(mask>cutoff) = cutoff; mask = (mask ./ cutoff) .* .5; opt.targetmask = mask; sortana = sort(realigndat(:)); cutoff = sortana(find(cumsum(sortana ./ sum(sortana(:)))>.99,1)); mask = realigndat; mask(mask>cutoff) = cutoff; mask = (mask ./ cutoff) .* .5; opt.realignmask = mask; end opt.update = [1 1 1]; opt.init = true; opt.tag = 'ik'; opt.mri = basevol; if twovol opt.realignvol = realign; end opt.showcrosshair = true; opt.showmarkers = false; opt.markers = {markerpos markerlabel markercolor}; if ~twovol opt.realignclim = cfg.clim; else opt.realignclim = cfg.clim; opt.targetclim = cfg.clim; end opt.fiducial = []; opt.fidlabel = []; opt.fidletter = []; opt.pnt = pnt; if isfield(mri, 'unit') && ~strcmp(mri.unit, 'unknown') opt.unit = mri.unit; % this is shown in the feedback on screen else opt.unit = ''; % this is not shown end % add to figure and start initial draw setappdata(h, 'opt', opt); cb_redraw(h); end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous mri ft_postamble provenance realign ft_postamble history realign ft_postamble savevar realign %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = assignweights(x, w) % x is an indexing vector with the same number of arguments as w y = w(:)'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_redraw_surface(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); markercolor = {'r', 'g', 'b', 'y'}; if opt.init ft_plot_mesh(opt.scalp, 'edgecolor', 'none', 'facecolor', 'skin') hold on end % recreate the camera lighting delete(opt.camlighthandle); opt.camlighthandle = camlight; % remove the previous fiducials delete(opt.handlesmarker(opt.handlesmarker(:)>0)); opt.handlesmarker = []; % redraw the fiducials for i=1:length(opt.fidlabel) lab = opt.fidlabel{i}; pos = ft_warp_apply(opt.mri.transform, opt.fiducial.(lab)); if all(~isnan(pos)) opt.handlesmarker(i,1) = plot3(pos(1), pos(2), pos(3), 'marker', 'o', 'color', markercolor{i}); opt.handlesmarker(i,2) = text(pos(1), pos(2), pos(3), lab); end end opt.init = false; setappdata(h, 'opt', opt); uiresume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_keyboard_surface(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); if isempty(eventdata) % determine the key that corresponds to the uicontrol element that was activated key = get(h, 'userdata'); else % determine the key that was pressed on the keyboard key = parseKeyboardEvent(eventdata); end % get the most recent surface position that was clicked with the mouse pos = select3d(opt.handlesaxes); sel = find(strcmp(opt.fidletter, key)); if ~isempty(sel) % update the corresponding fiducial opt.fiducial.(opt.fidlabel{sel}) = ft_warp_apply(inv(opt.mri.transform), pos(:)'); end fprintf('==================================================================================\n'); for i=1:length(opt.fidlabel) lab = opt.fidlabel{i}; vox = opt.fiducial.(lab); ind = sub2ind(opt.mri.dim(1:3), round(vox(1)), round(vox(2)), round(vox(3))); pos = ft_warp_apply(opt.mri.transform, vox); switch opt.unit case 'mm' fprintf('%10s: voxel %9d, index = [%3d %3d %3d], head = [%.1f %.1f %.1f] %s\n', lab, ind, round(vox), pos, opt.unit); case 'cm' fprintf('%10s: voxel %9d, index = [%3d %3d %3d], head = [%.2f %.2f %.2f] %s\n', lab, ind, round(vox), pos, opt.unit); case 'm' fprintf('%10s: voxel %9d, index = [%3d %3d %3d], head = [%.4f %.4f %.4f] %s\n', lab, ind, round(vox), pos, opt.unit); otherwise fprintf('%10s: voxel %9d, index = [%3d %3d %3d], head = [%f %f %f] %s\n', lab, ind, round(vox), pos, opt.unit); end end setappdata(h, 'opt', opt); if isequal(key, 'q') cb_cleanup(h); else cb_redraw_surface(h); end uiresume(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_redraw(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); curr_ax = get(h, 'currentaxes'); tag = get(curr_ax, 'tag'); mri = opt.mri; h1 = opt.handlesaxes(1); h2 = opt.handlesaxes(2); h3 = opt.handlesaxes(3); % extract to-be-plotted/clicked location and check whether inside figure xi = opt.ijk(1); yi = opt.ijk(2); zi = opt.ijk(3); if any([xi yi zi] > mri.dim) || any([xi yi zi] <= 0) return; end % transform here to coordinate system space instead of voxel space if viewing results % the code were this transform will impact fiducial/etc coordinates is unaffected, as it is switched off % (note: fiducial/etc coordinates are transformed into coordinate space in the code dealing with realignment) if opt.viewresult tmp = ft_warp_apply(mri.transform, [xi yi zi]); xi = tmp(1); yi = tmp(2); zi = tmp(3); end if opt.init % create the initial figure if ~opt.viewresult % if realigning, plotting is done in voxel space ft_plot_ortho(opt.ana, 'transform', eye(4), 'location', [xi yi zi], 'style', 'subplot', 'parents', [h1 h2 h3], 'update', opt.update, 'doscale', false, 'clim', opt.clim); else % if viewing result, plotting is done in head coordinate system space if ~opt.twovol % one vol case ft_plot_ortho(opt.ana, 'transform', mri.transform, 'location', [xi yi zi], 'style', 'subplot', 'parents', [h1 h2 h3], 'update', opt.update, 'doscale', false, 'clim', opt.realignclim); else % two vol case % base volume, with color red hbase = []; % need the handle for the individual surfs [hbase(1), hbase(2), hbase(3)] = ft_plot_ortho(opt.ana, 'transform', mri.transform, 'unit', mri.unit, 'location', [xi yi zi], 'style', 'subplot', 'parents', [h1 h2 h3], 'update', opt.update, 'doscale', false, 'clim', opt.targetclim, 'datmask',opt.targetmask, 'opacitylim', [0 1]); for ih = 1:3 col = get(hbase(ih), 'CData'); col(:,:,2:3) = 0; set(hbase(ih), 'CData',col); end % aligned volume, with color blue hreal = []; % need the handle for the individual surfs [hreal(1), hreal(2), hreal(3)] = ft_plot_ortho(opt.realignana, 'transform', opt.realignvol.transform, 'unit', opt.realignvol.unit, 'location', [xi yi zi], 'style', 'subplot', 'parents', [h1 h2 h3], 'update', opt.update, 'doscale', false, 'clim', opt.realignclim, 'datmask',opt.realignmask, 'opacitylim', [0 1]); for ih = 1:3 col = get(hreal(ih), 'CData'); col(:,:,1:2) = 0; set(hreal(ih), 'CData',col); end end end % if ~opt.viewresult % fetch surf objects, set ana tag, and put in surfhandles if ~opt.viewresult || (opt.viewresult && ~opt.twovol) opt.anahandles = findobj(opt.handlesfigure, 'type', 'surface')'; parenttag = get(opt.anahandles, 'parent'); parenttag{1} = get(parenttag{1}, 'tag'); parenttag{2} = get(parenttag{2}, 'tag'); parenttag{3} = get(parenttag{3}, 'tag'); [i1,i2,i3] = intersect(parenttag, {'ik';'jk';'ij'}); opt.anahandles = opt.anahandles(i3(i2)); % seems like swapping the order opt.anahandles = opt.anahandles(:)'; set(opt.anahandles, 'tag', 'ana'); else % this should do the same as the above set(hbase, 'tag', 'ana'); set(hreal, 'tag', 'ana'); opt.anahandles = {hbase, hreal}; end else % update the existing figure if ~opt.viewresult % if realigning, plotting is done in voxel space ft_plot_ortho(opt.ana, 'transform', eye(4), 'location', [xi yi zi], 'style', 'subplot', 'surfhandle', opt.anahandles, 'update', opt.update, 'doscale', false, 'clim', opt.clim); else % if viewing result, plotting is done in head coordinate system space if ~opt.twovol % one vol case ft_plot_ortho(opt.ana, 'transform', mri.transform, 'unit', mri.unit, 'location', [xi yi zi], 'style', 'subplot', 'surfhandle', opt.anahandles, 'update', opt.update, 'doscale', false, 'clim', opt.realignclim); else % two vol case % base volume, with color red hbase = []; % need the handle for the individual surfs [hbase(1), hbase(2), hbase(3)] = ft_plot_ortho(opt.ana, 'transform', mri.transform, 'unit', mri.unit, 'location', [xi yi zi], 'style', 'subplot', 'surfhandle', opt.anahandles{1}, 'update', opt.update, 'doscale', false, 'clim', opt.targetclim, 'datmask', opt.targetmask, 'opacitylim', [0 1]); for ih = 1:3 col = get(hbase(ih), 'CData'); col(:,:,2:3) = 0; set(hbase(ih), 'CData', col); end % aligned volume, with color blue hreal = []; % need the handle for the individual surfs [hreal(1), hreal(2), hreal(3)] = ft_plot_ortho(opt.realignana, 'transform', opt.realignvol.transform, 'unit', opt.realignvol.unit, 'location', [xi yi zi], 'style', 'subplot', 'surfhandle', opt.anahandles{2}, 'update', opt.update, 'doscale', false, 'clim', opt.realignclim, 'datmask', opt.realignmask, 'opacitylim', [0 1]); for ih = 1:3 col = get(hreal(ih), 'CData'); col(:,:,1:2) = 0; set(hreal(ih), 'CData', col); end end end % if ~opt.viewresult % display current location if ~opt.viewresult % if realigning, plotting is done in voxel space if all(round([xi yi zi])<=mri.dim) && all(round([xi yi zi])>0) fprintf('==================================================================================\n'); lab = 'crosshair'; vox = [xi yi zi]; ind = sub2ind(mri.dim(1:3), round(vox(1)), round(vox(2)), round(vox(3))); pos = ft_warp_apply(mri.transform, vox); switch opt.unit case 'mm' fprintf('%10s: voxel %9d, index = [%3d %3d %3d], head = [%.1f %.1f %.1f] %s\n', lab, ind, vox, pos, opt.unit); case 'cm' fprintf('%10s: voxel %9d, index = [%3d %3d %3d], head = [%.2f %.2f %.2f] %s\n', lab, ind, vox, pos, opt.unit); case 'm' fprintf('%10s: voxel %9d, index = [%3d %3d %3d], head = [%.4f %.4f %.4f] %s\n', lab, ind, vox, pos, opt.unit); otherwise fprintf('%10s: voxel %9d, index = [%3d %3d %3d], head = [%f %f %f] %s\n', lab, ind, vox, pos, opt.unit); end end for i=1:length(opt.fidlabel) lab = opt.fidlabel{i}; vox = opt.fiducial.(lab); ind = sub2ind(mri.dim(1:3), round(vox(1)), round(vox(2)), round(vox(3))); pos = ft_warp_apply(mri.transform, vox); switch opt.unit case 'mm' fprintf('%10s: voxel %9d, index = [%3d %3d %3d], head = [%.1f %.1f %.1f] %s\n', lab, ind, vox, pos, opt.unit); case 'cm' fprintf('%10s: voxel %9d, index = [%3d %3d %3d], head = [%.2f %.2f %.2f] %s\n', lab, ind, vox, pos, opt.unit); case 'm' fprintf('%10s: voxel %9d, index = [%3d %3d %3d], head = [%.4f %.4f %.4f] %s\n', lab, ind, vox, pos, opt.unit); otherwise fprintf('%10s: voxel %9d, index = [%3d %3d %3d], head = [%f %f %f] %s\n', lab, ind, vox, pos, opt.unit); end end else % if viewing result, plotting is done in head coordinate system space lab = 'crosshair'; pos = [xi yi zi]; switch opt.unit case 'mm' fprintf('%10s: head = [%.1f %.1f %.1f] %s\n', lab, pos, opt.unit); case 'cm' fprintf('%10s: head = [%.2f %.2f %.2f] %s\n', lab, pos, opt.unit); case 'm' fprintf('%10s: head = [%.4f %.4f %.4f] %s\n', lab, pos, opt.unit); otherwise fprintf('%10s: head = [%f %f %f] %s\n', lab, pos, opt.unit); end end % if ~opt.viewresult end % if opt.init set(opt.handlesaxes(1), 'Visible', 'on'); set(opt.handlesaxes(2), 'Visible', 'on'); set(opt.handlesaxes(3), 'Visible', 'on'); if opt.viewresult set(opt.handlesaxes(1), 'color', [.94 .94 .94]); set(opt.handlesaxes(2), 'color', [.94 .94 .94]); set(opt.handlesaxes(3), 'color', [.94 .94 .94]); end % make the last current axes current again sel = findobj('type', 'axes', 'tag',tag); if ~isempty(sel) set(opt.handlesfigure, 'currentaxes', sel(1)); end % set crosshair coordinates dependent on voxel/system coordinate space % crosshair needs to be plotted 'towards' the viewing person, i.e. with a little offset % i.e. this is the coordinate of the 'flat' axes with a little bit extra in the direction of the axis % this offset cannot be higher than the to be plotted data, or it will not be visible (i.e. be outside of the visible axis) if ~opt.viewresult crossoffs = opt.dim; crossoffs(2) = 1; % workaround to use the below else % because the orientation of the three slices are determined by eye(3) (no orientation is specified above), % the direction of view is always: % h1 -to+ % h2 +to- % h3 -to+ % use this to create the offset for viewing the crosshair mincoordstep = abs(ft_warp_apply(mri.transform, [1 1 1]) - ft_warp_apply(mri.transform, [2 2 2])); crossoffs = [xi yi zi] + [1 -1 1].*mincoordstep; end if opt.init % draw the crosshairs for the first time hch1 = crosshair([xi crossoffs(2) zi], 'parent', h1, 'color', 'yellow'); hch2 = crosshair([crossoffs(1) yi zi], 'parent', h2, 'color', 'yellow'); hch3 = crosshair([xi yi crossoffs(3)], 'parent', h3, 'color', 'yellow'); opt.handlescross = [hch1(:)';hch2(:)';hch3(:)']; opt.handlesmarker = []; else % update the existing crosshairs, don't change the handles crosshair([xi crossoffs(2) zi], 'handle', opt.handlescross(1, :)); crosshair([crossoffs(1) yi zi], 'handle', opt.handlescross(2, :)); crosshair([xi yi crossoffs(3)], 'handle', opt.handlescross(3, :)); end % For some unknown god-awful reason, the line command 'disables' all transparency. % The below command resets it. It was the only axes property that I (=roemei) could % find that changed after adding the crosshair, and putting it back to 'childorder' % instead of 'depth' fixes the problem. Lucky, the line command only 'disables' in % the new graphics system introduced in 2014b (any version below is fine, and does % not contain the sortmethod property --> crash) if ~verLessThan('matlab', '8.4') % 8.4 = 2014b set(h1, 'sortMethod', 'childorder') set(h2, 'sortMethod', 'childorder') set(h3, 'sortMethod', 'childorder') end if opt.showcrosshair set(opt.handlescross, 'Visible', 'on'); else set(opt.handlescross, 'Visible', 'off'); end markercolor = {'r', 'g', 'b', 'y'}; delete(opt.handlesmarker(opt.handlesmarker(:)>0)); opt.handlesmarker = []; if ~opt.viewresult for i=1:length(opt.fidlabel) pos = opt.fiducial.(opt.fidlabel{i}); % if any(isnan(pos)) % continue % end posi = pos(1); posj = pos(2); posk = pos(3); subplot(h1); hold on opt.handlesmarker(i,1) = plot3(posi, 1, posk, 'marker', 'o', 'color', markercolor{i}); hold off subplot(h2); hold on opt.handlesmarker(i,2) = plot3(opt.dim(1), posj, posk, 'marker', 'o', 'color', markercolor{i}); hold off subplot(h3); hold on opt.handlesmarker(i,3) = plot3(posi, posj, opt.dim(3), 'marker', 'o', 'color', markercolor{i}); hold off end % for each fiducial end if opt.showmarkers set(opt.handlesmarker, 'Visible', 'on'); else set(opt.handlesmarker, 'Visible', 'off'); end opt.init = false; setappdata(h, 'opt', opt); set(h, 'currentaxes', curr_ax); uiresume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_keyboard(h, eventdata) if isempty(eventdata) % determine the key that corresponds to the uicontrol element that was activated key = get(h, 'userdata'); else % determine the key that was pressed on the keyboard key = parseKeyboardEvent(eventdata); end % get focus back to figure if ~strcmp(get(h, 'type'), 'figure') set(h, 'enable', 'off'); drawnow; set(h, 'enable', 'on'); end h = getparent(h); opt = getappdata(h, 'opt'); curr_ax = get(h, 'currentaxes'); tag = get(curr_ax, 'tag'); if isempty(key) % this happens if you press the apple key key = ''; end % the following code is largely shared with FT_SOURCEPLOT switch key case {'' 'shift+shift' 'alt-alt' 'control+control' 'command-0'} % do nothing case '1' subplot(opt.handlesaxes(1)); case '2' subplot(opt.handlesaxes(2)); case '3' subplot(opt.handlesaxes(3)); case opt.fidletter if ~opt.viewresult sel = strcmp(key, opt.fidletter); fprintf('==================================================================================\n'); fprintf('selected %s\n', opt.fidlabel{sel}); opt.fiducial.(opt.fidlabel{sel}) = opt.ijk; setappdata(h, 'opt', opt); cb_redraw(h); end case 'q' setappdata(h, 'opt', opt); cb_cleanup(h); case {'i' 'j' 'k' 'm' 28 29 30 31 'leftarrow' 'rightarrow' 'uparrow' 'downarrow'} % TODO FIXME use leftarrow rightarrow uparrow downarrow % update the view to a new position if strcmp(tag,'ik') && (strcmp(key,'i') || strcmp(key,'uparrow') || isequal(key, 30)), opt.ijk(3) = opt.ijk(3)+1; opt.update = [0 0 1]; elseif strcmp(tag,'ik') && (strcmp(key,'j') || strcmp(key,'leftarrow') || isequal(key, 28)), opt.ijk(1) = opt.ijk(1)-1; opt.update = [0 1 0]; elseif strcmp(tag,'ik') && (strcmp(key,'k') || strcmp(key,'rightarrow') || isequal(key, 29)), opt.ijk(1) = opt.ijk(1)+1; opt.update = [0 1 0]; elseif strcmp(tag,'ik') && (strcmp(key,'m') || strcmp(key,'downarrow') || isequal(key, 31)), opt.ijk(3) = opt.ijk(3)-1; opt.update = [0 0 1]; elseif strcmp(tag,'ij') && (strcmp(key,'i') || strcmp(key,'uparrow') || isequal(key, 30)), opt.ijk(2) = opt.ijk(2)+1; opt.update = [1 0 0]; elseif strcmp(tag,'ij') && (strcmp(key,'j') || strcmp(key,'leftarrow') || isequal(key, 28)), opt.ijk(1) = opt.ijk(1)-1; opt.update = [0 1 0]; elseif strcmp(tag,'ij') && (strcmp(key,'k') || strcmp(key,'rightarrow') || isequal(key, 29)), opt.ijk(1) = opt.ijk(1)+1; opt.update = [0 1 0]; elseif strcmp(tag,'ij') && (strcmp(key,'m') || strcmp(key,'downarrow') || isequal(key, 31)), opt.ijk(2) = opt.ijk(2)-1; opt.update = [1 0 0]; elseif strcmp(tag,'jk') && (strcmp(key,'i') || strcmp(key,'uparrow') || isequal(key, 30)), opt.ijk(3) = opt.ijk(3)+1; opt.update = [0 0 1]; elseif strcmp(tag,'jk') && (strcmp(key,'j') || strcmp(key,'leftarrow') || isequal(key, 28)), opt.ijk(2) = opt.ijk(2)-1; opt.update = [1 0 0]; elseif strcmp(tag,'jk') && (strcmp(key,'k') || strcmp(key,'rightarrow') || isequal(key, 29)), opt.ijk(2) = opt.ijk(2)+1; opt.update = [1 0 0]; elseif strcmp(tag,'jk') && (strcmp(key,'m') || strcmp(key,'downarrow') || isequal(key, 31)), opt.ijk(3) = opt.ijk(3)-1; opt.update = [0 0 1]; else % do nothing end; setappdata(h, 'opt', opt); cb_redraw(h); % contrast scaling case {43 'shift+equal'} % numpad + % disable if viewresult if ~opt.viewresult if isempty(opt.clim) opt.clim = [min(opt.ana(:)) max(opt.ana(:))]; end % reduce color scale range by 10% cscalefactor = (opt.clim(2)-opt.clim(1))/10; %opt.clim(1) = opt.clim(1)+cscalefactor; opt.clim(2) = opt.clim(2)-cscalefactor; setappdata(h, 'opt', opt); cb_redraw(h); end case {45 'shift+hyphen'} % numpad - % disable if viewresult if ~opt.viewresult if isempty(opt.clim) opt.clim = [min(opt.ana(:)) max(opt.ana(:))]; end % increase color scale range by 10% cscalefactor = (opt.clim(2)-opt.clim(1))/10; %opt.clim(1) = opt.clim(1)-cscalefactor; opt.clim(2) = opt.clim(2)+cscalefactor; setappdata(h, 'opt', opt); cb_redraw(h); end case 99 % 'c' opt.showcrosshair = ~opt.showcrosshair; setappdata(h, 'opt', opt); cb_redraw(h); case 102 % 'f' if ~opt.viewresult opt.showmarkers = ~opt.showmarkers; setappdata(h, 'opt', opt); cb_redraw(h); end case 3 % right mouse click % add point to a list l1 = get(get(gca, 'xlabel'), 'string'); l2 = get(get(gca, 'ylabel'), 'string'); switch l1, case 'i' xc = d1; case 'j' yc = d1; case 'k' zc = d1; end switch l2, case 'i' xc = d2; case 'j' yc = d2; case 'k' zc = d2; end pnt = [pnt; xc yc zc]; case 2 % middle mouse click l1 = get(get(gca, 'xlabel'), 'string'); l2 = get(get(gca, 'ylabel'), 'string'); % remove the previous point if size(pnt,1)>0 pnt(end,:) = []; end if l1=='i' && l2=='j' updatepanel = [1 2 3]; elseif l1=='i' && l2=='k' updatepanel = [2 3 1]; elseif l1=='j' && l2=='k' updatepanel = [3 1 2]; end otherwise % do nothing end % switch key if ~opt.viewresult uiresume(h) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_buttonpress(h, eventdata) h = getparent(h); cb_getposition(h); switch get(h, 'selectiontype') case 'normal' % just update to new position, nothing else to be done here cb_redraw(h); case 'alt' set(h, 'windowbuttonmotionfcn', @cb_tracemouse); cb_redraw(h); otherwise end uiresume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_buttonrelease(h, eventdata) set(h, 'windowbuttonmotionfcn', ''); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_tracemouse(h, eventdata) h = getparent(h); cb_getposition(h); cb_redraw(h); uiresume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_getposition(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); curr_ax = get(h, 'currentaxes'); pos = mean(get(curr_ax, 'currentpoint')); tag = get(curr_ax, 'tag'); % transform pos from coordinate system space to voxel space if viewing results if opt.viewresult pos = ft_warp_apply(inv(opt.mri.transform),pos); % not sure under which circumstances the transformation matrix is not invertible... end if ~isempty(tag) && ~opt.init if strcmp(tag, 'ik') opt.ijk([1 3]) = round(pos([1 3])); opt.update = [1 1 1]; elseif strcmp(tag, 'ij') opt.ijk([1 2]) = round(pos([1 2])); opt.update = [1 1 1]; elseif strcmp(tag, 'jk') opt.ijk([2 3]) = round(pos([2 3])); opt.update = [1 1 1]; end end opt.ijk = min(opt.ijk(:)', opt.dim); opt.ijk = max(opt.ijk(:)', [1 1 1]); setappdata(h, 'opt', opt); uiresume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_cleanup(h, eventdata) opt = getappdata(h, 'opt'); if ~opt.viewresult opt.quit = true; setappdata(h, 'opt', opt); uiresume else % not part of interactive process requiring output handling, quite immediately delete(h); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = getparent(h) p = h; while p~=0 h = p; p = get(h, 'parent'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key = parseKeyboardEvent(eventdata) key = eventdata.Key; % handle possible numpad events (different for Windows and UNIX systems) % NOTE: shift+numpad number does not work on UNIX, since the shift % modifier is always sent for numpad events if isunix() shiftInd = match_str(eventdata.Modifier, 'shift'); if ~isnan(str2double(eventdata.Character)) && ~isempty(shiftInd) % now we now it was a numpad keystroke (numeric character sent AND % shift modifier present) key = eventdata.Character; eventdata.Modifier(shiftInd) = []; % strip the shift modifier end elseif ispc() if strfind(eventdata.Key, 'numpad') key = eventdata.Character; end end if ~isempty(eventdata.Modifier) key = [eventdata.Modifier{1} '+' key]; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_minslider(h4, eventdata) tag = get(h4, 'tag'); newlim = get(h4, 'value'); h = getparent(h4); opt = getappdata(h, 'opt'); if isempty(tag) opt.clim(1) = newlim; elseif strcmp(tag, 'rel') opt.realignclim(1) = newlim; elseif strcmp(tag, 'tar') opt.targetclim(1) = newlim; end if isempty(tag) fprintf('contrast limits updated to [%.03f %.03f]\n', opt.clim); elseif strcmp(tag, 'rel') fprintf('realigned contrast limits updated to [%.03f %.03f]\n', opt.realignclim); elseif strcmp(tag, 'tar') fprintf('target cfontrast limits updated to [%.03f %.03f]\n', opt.targetclim); end setappdata(h, 'opt', opt); cb_redraw(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_maxslider(h5, eventdata) tag = get(h5, 'tag'); newlim = get(h5, 'value'); h = getparent(h5); opt = getappdata(h, 'opt'); if isempty(tag) opt.clim(2) = newlim; elseif strcmp(tag, 'rel') opt.realignclim(2) = newlim; elseif strcmp(tag, 'tar') opt.targetclim(2) = newlim; end if isempty(tag) fprintf('contrast limits updated to [%.03f %.03f]\n', opt.clim); elseif strcmp(tag, 'rel') fprintf('realigned contrast limits updated to [%.03f %.03f]\n', opt.realignclim); elseif strcmp(tag, 'tar') fprintf('target contrast limits updated to [%.03f %.03f]\n', opt.targetclim); end setappdata(h, 'opt', opt); cb_redraw(h);
github
lcnbeapp/beapp-master
ft_qualitycheck.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_qualitycheck.m
25,590
utf_8
a401e78252691eab2e35c944b5a3c39b
function [varargout] = ft_qualitycheck(cfg) % FT_QUALITYCHECK performs a quality inspection of a given MEG/EEG dataset, % stores (.mat), and visualizes the result (.png and .pdf). % % This function segments the data into 10-second pieces and performs the % following analyses: % 1) reads the properties of the dataset % 2) computes the headpositions and distance covered from recording onset (CTF only) % 3) computes the mean, max, min, and range of the signal amplitude % 4) detects trigger events % 5) detects jump artifacts % 6) computes the powerspectrum % 7) estimates the low-frequency (<2 Hz) and line noise (~50 Hz) % % Use as % [info, timelock, freq, summary, headpos] = ft_qualitycheck(cfg) % where info contains the dataset properties, timelock the timelocked data, % freq the powerspectra, summary the mean descriptives, and headpos the % headpositions throughout the recording % % The configuration should contain: % cfg.dataset = a string (e.g. 'dataset.ds') % % The following parameters can be used: % cfg.analyze = string, 'yes' or 'no' to analyze the dataset (default = 'yes') % cfg.savemat = string, 'yes' or 'no' to save the analysis (default = 'yes') % cfg.matfile = string, filename (e.g. 'previousoutput.mat'), preferably in combination % with analyze = 'no' % cfg.visualize = string, 'yes' or 'no' to visualize the analysis (default = 'yes') % cfg.saveplot = string, 'yes' or 'no' to save the visualization (default = 'yes') % cfg.linefreq = scalar, frequency of power line (default = 50) % cfg.plotunit = scalar, the length of time to be plotted in one panel (default = 3600) % % See also FT_PREPROCESSING, FT_READ_HEADER, FT_READ_DATA, FT_READ_EVENT % Copyright (C) 2010-2011, Arjen Stolk, Bram Daams, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id:% % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble provenance ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % set the defaults cfg.analyze = ft_getopt(cfg, 'analyze', 'yes'); cfg.savemat = ft_getopt(cfg, 'savemat', 'yes'); cfg.matfile = ft_getopt(cfg, 'matfile', []); cfg.visualize = ft_getopt(cfg, 'visualize', 'yes'); cfg.saveplot = ft_getopt(cfg, 'saveplot', 'yes'); cfg.linefreq = ft_getopt(cfg, 'linefreq', 50); cfg.plotunit = ft_getopt(cfg, 'plotunit', 3600); %% ANALYSIS if strcmp(cfg.analyze,'yes') tic % checks cfg = ft_checkconfig(cfg, 'dataset2files', 'yes'); % translate into datafile+headerfile % these will be replaced by more appropriate values info.datasetname = 'unknown'; info.starttime = 'unknown'; info.startdate = 'unknown'; info.stoptime = 'unknown'; info.stopdate = 'unknown'; % the exportname is also used in the cron job exportname = qualitycheck_exportname(cfg.dataset); [iseeg, ismeg, isctf, fltp] = filetyper(cfg.dataset); if isctf try % update the info fields info = read_ctf_hist(cfg.dataset); end end % add info info.event = ft_read_event(cfg.dataset); info.hdr = ft_read_header(cfg.dataset); info.filetype = fltp; % trial definition cfgdef = []; cfgdef.dataset = cfg.dataset; cfgdef.trialdef.triallength = 10; %cfgdef.trialdef.ntrials = 3; cfgdef.continuous = 'yes'; cfgdef = ft_definetrial(cfgdef); ntrials = size(cfgdef.trl,1)-1; % remove last trial timeunit = cfgdef.trialdef.triallength; % channelselection for jump detection (all) and for FFT (brain) if ismeg allchans = ft_channelselection({'MEG','MEGREF'}, info.hdr.label); chans = ft_channelselection('MEG', info.hdr.label); % brain allchanindx = match_str(info.hdr.label, allchans); chanindx = match_str(chans, allchans); jumpthreshold = 1e-10; elseif iseeg allchans = ft_channelselection('EEG', info.hdr.label); chans = allchans; % brain allchanindx = match_str(info.hdr.label, allchans); chanindx = match_str(chans, allchans); jumpthreshold = 1e4; end % find headcoil channels if isctf % this fails for older CTF data sets Nx = strmatch('HLC0011', info.hdr.label); % x nasion coil Ny = strmatch('HLC0012', info.hdr.label); % y nasion Nz = strmatch('HLC0013', info.hdr.label); % z nasion Lx = strmatch('HLC0021', info.hdr.label); % x left coil Ly = strmatch('HLC0022', info.hdr.label); % y left Lz = strmatch('HLC0023', info.hdr.label); % z left Rx = strmatch('HLC0031', info.hdr.label); % x right coil Ry = strmatch('HLC0032', info.hdr.label); % y right Rz = strmatch('HLC0033', info.hdr.label); % z right headpos.dimord = 'chan_time'; headpos.time = (timeunit-timeunit/2:timeunit:timeunit*ntrials-timeunit/2); headpos.label = {'Nx';'Ny';'Nz';'Lx';'Ly';'Lz';'Rx';'Ry';'Rz'}; headpos.avg = NaN(length(headpos.label), ntrials); headpos.grad = info.hdr.grad; if numel(cat(1,Nx,Ny,Nz,Lx,Ly,Lz,Rx,Ry,Rz))==9 hasheadpos = true; else hasheadpos = false; end end % if % analysis settings cfgredef = []; cfgredef.length = 1; cfgredef.overlap = 0; cfgfreq = []; cfgfreq.output = 'pow'; cfgfreq.channel = allchans; cfgfreq.method = 'mtmfft'; cfgfreq.taper = 'hanning'; cfgfreq.keeptrials = 'no'; cfgfreq.foilim = [0 min(info.hdr.Fs/2, 400)]; % output variables timelock.dimord = 'chan_time'; timelock.label = allchans; timelock.time = (timeunit-timeunit/2:timeunit:timeunit*ntrials-timeunit/2); timelock.avg = NaN(length(allchans), ntrials); % updated in loop timelock.median = NaN(length(allchans), ntrials); % updated in loop timelock.jumps = NaN(length(allchans), ntrials); % updated in loop timelock.range = NaN(length(allchans), ntrials); % updated in loop timelock.min = NaN(length(allchans), ntrials); % updated in loop timelock.max = NaN(length(allchans), ntrials); % updated in loop freq.dimord = 'chan_freq_time'; freq.label = allchans; freq.freq = (cfgfreq.foilim(1):cfgfreq.foilim(2)); freq.time = (timeunit-timeunit/2:timeunit:timeunit*ntrials-timeunit/2); freq.powspctrm = NaN(length(allchans), length(freq.freq), ntrials); % updated in loop summary.dimord = 'chan_time'; summary.time = (timeunit-timeunit/2:timeunit:timeunit*ntrials-timeunit/2); summary.label = {'Mean';'Median';'Min';'Max';'Range';'HmotionN';'HmotionL';'HmotionR';'LowFreqPower';'LineFreqPower';'Jumps'}; summary.avg = NaN(length(summary.label), ntrials); % updated in loop % try add gradiometer info if isfield(info.hdr, 'grad'), timelock.grad = info.hdr.grad; freq.grad = info.hdr.grad; summary.grad = info.hdr.grad; end % process trial by trial for t = 1:ntrials fprintf('analyzing trial %s of %s \n', num2str(t), num2str(ntrials)); % preprocess cfgpreproc = cfgdef; cfgpreproc.trl = cfgdef.trl(t,:); data = ft_preprocessing(cfgpreproc); clear cfgpreproc; % determine headposition if isctf && hasheadpos headpos.avg(1,t) = mean(data.trial{1,1}(Nx,:) * 100); % meter to cm headpos.avg(2,t) = mean(data.trial{1,1}(Ny,:) * 100); headpos.avg(3,t) = mean(data.trial{1,1}(Nz,:) * 100); headpos.avg(4,t) = mean(data.trial{1,1}(Lx,:) * 100); headpos.avg(5,t) = mean(data.trial{1,1}(Ly,:) * 100); headpos.avg(6,t) = mean(data.trial{1,1}(Lz,:) * 100); headpos.avg(7,t) = mean(data.trial{1,1}(Rx,:) * 100); headpos.avg(8,t) = mean(data.trial{1,1}(Ry,:) * 100); headpos.avg(9,t) = mean(data.trial{1,1}(Rz,:) * 100); end % update values timelock.avg(:,t) = mean(data.trial{1}(allchanindx,:),2); timelock.median(:,t) = median(data.trial{1}(allchanindx,:),2); timelock.range(:,t) = max(data.trial{1}(allchanindx,:),[],2) - min(data.trial{1}(allchanindx,:),[],2); timelock.min(:,t) = min(data.trial{1}(allchanindx,:),[],2); timelock.max(:,t) = max(data.trial{1}(allchanindx,:),[],2); % detect jumps for c = 1:size(data.trial{1}(allchanindx,:),1) timelock.jumps(c,t) = length(find(diff(data.trial{1,1}(allchanindx(c),:)) > jumpthreshold)); end % FFT and noise estimation redef = ft_redefinetrial(cfgredef, data); clear data; FFT = ft_freqanalysis(cfgfreq, redef); clear redef; freq.powspctrm(:,:,t) = FFT.powspctrm; summary.avg(9,t) = mean(mean(findpower(0, 2, FFT, chanindx))); % Low Freq Power summary.avg(10,t) = mean(mean(findpower(cfg.linefreq-1, cfg.linefreq+1, FFT, chanindx))); clear FFT; % Line Freq Power toc end % end of trial loop % determine headmotion: distance from initial trial (in cm) if isctf && hasheadpos summary.avg(6,:) = sqrt(sum((headpos.avg(1:3,:)-repmat(headpos.avg(1:3,1),1,size(headpos.avg,2))).^2,1)); % N summary.avg(7,:) = sqrt(sum((headpos.avg(4:6,:)-repmat(headpos.avg(4:6,1),1,size(headpos.avg,2))).^2,1)); % L summary.avg(8,:) = sqrt(sum((headpos.avg(7:9,:)-repmat(headpos.avg(7:9,1),1,size(headpos.avg,2))).^2,1)); % R end % summarize/mean and store variables of brain info only summary.avg(1,:) = mean(timelock.avg(chanindx,:),1); summary.avg(2,:) = mean(timelock.median(chanindx,:),1); summary.avg(3,:) = mean(timelock.min(chanindx,:),1); summary.avg(4,:) = mean(timelock.max(chanindx,:),1); summary.avg(5,:) = mean(timelock.range(chanindx,:),1); summary.avg(11,:) = mean(timelock.jumps(chanindx,:),1); % save to .mat if strcmp(cfg.savemat, 'yes') if isctf && hasheadpos headpos.cfg = cfg; save(exportname, 'info','timelock','freq','summary','headpos'); else save(exportname, 'info','timelock','freq','summary'); end end end % end of analysis %% VISUALIZATION if strcmp(cfg.visualize, 'yes') % load data if strcmp(cfg.analyze, 'no') if ~isempty(cfg.matfile) exportname = cfg.matfile; else exportname = qualitycheck_exportname(cfg.dataset); end fprintf('loading %s \n', exportname); load(exportname); end % determine number of 1-hour plots to be made nplots = ceil(length(freq.time)/(cfg.plotunit/10)); % create GUI-like figure(s) for p = 1:nplots fprintf('visualizing %s of %s \n', num2str(p), num2str(nplots)); toi = [p*cfg.plotunit-(cfg.plotunit-5) p*cfg.plotunit-5]; % select 1-hour chunks tmpcfg.toi = toi; temp_timelock = ft_selectdata(tmpcfg, timelock); temp_timelock.cfg = cfg; % be sure to add the cfg here temp_freq = ft_selectdata(tmpcfg, freq); temp_summary = ft_selectdata(tmpcfg, summary); if exist('headpos','var') temp_headpos = ft_selectdata(tmpcfg, headpos); draw_figure(info, temp_timelock, temp_freq, temp_summary, temp_headpos, toi); clear temp_timelock; clear temp_freq; clear temp_summary; clear temp_headpos; clear toi; else draw_figure(info, temp_timelock, temp_freq, temp_summary, toi); clear temp_timelock; clear temp_freq; clear temp_summary; clear toi; end % export to .PNG and .PDF if strcmp(cfg.saveplot, 'yes') [pathstr,name,extr] = fileparts(exportname); if p == 1 exportfilename = name; else exportfilename = strcat(name,'_pt',num2str(p)); end fprintf('exporting %s of %s \n', num2str(p), num2str(nplots)); set(gcf, 'PaperType', 'a4'); print(gcf, '-dpng', strcat(exportfilename,'.png')); orient landscape; print(gcf, '-dpdf', strcat(exportfilename,'.pdf')); close end end % end of nplots end % end of visualization % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble provenance ft_postamble history timelock % add the input cfg to multiple outputs ft_postamble history freq % add the input cfg to multiple outputs ft_postamble history summary % add the input cfg to multiple outputs %% VARARGOUT if nargout>0 mOutputArgs{1} = info; mOutputArgs{2} = timelock; mOutputArgs{3} = freq; mOutputArgs{4} = summary; try mOutputArgs{5} = headpos; end [varargout{1:nargout}] = mOutputArgs{:}; clearvars -except varargout else clear end %%%%%%%%%%%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%% function [x] = clipat(x, v, v2) v = [v v2]; % clip between value v and v2 if length(v) == 1 x(x>v) = v; elseif length(v) == 2 x(x<v(1)) = v(1); x(x>v(2)) = v(2); end %%%%%%%%%%%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%% function [iseeg, ismeg, isctf, fltp] = filetyper(dataset) fltp = ft_filetype(dataset); iseeg = ft_filetype(dataset,'brainvision_eeg') | ... ft_filetype(dataset,'ns_eeg') | ... ft_filetype(dataset,'bci2000_dat') | ... ft_filetype(dataset,'neuroprax_eeg') | ... ft_filetype(dataset,'egi_sbin') | ... ft_filetype(dataset,'biosemi_bdf'); ismeg = ft_filetype(dataset,'ctf_ds') | ... ft_filetype(dataset,'4d') | ... ft_filetype(dataset,'neuromag_fif') | ... ft_filetype(dataset,'itab_raw'); isctf = ft_filetype(dataset, 'ctf_ds'); if ~ismeg && ~iseeg % if none found, try less strict checks [p, f, ext] = fileparts(dataset); if strcmp(ext, '.eeg') fltp = 'brainvision_eeg'; iseeg = 1; elseif strcmp(ext, '.bdf') fltp = 'biosemi_bdf'; iseeg = 1; elseif strcmp(ext, '.ds') fltp = 'ctf_ds'; ismeg = 1; else % otherwise use eeg settings for stability reasons iseeg = 1; end end %%%%%%%%%%%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%% function [power, freq] = findpower(low, high, freqinput, chans) % replace value with the index of the nearest bin xmin = nearest(getsubfield(freqinput, 'freq'), low); xmax = nearest(getsubfield(freqinput, 'freq'), high); % select the freq range power = freqinput.powspctrm(chans, xmin:xmax); freq = freqinput.freq(:, xmin:xmax); %%%%%%%%%%%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%% function draw_figure(varargin) % deal with input if nargin == 6 info = varargin{1}; timelock = varargin{2}; freq = varargin{3}; summary = varargin{4}; headpos = varargin{5}; toi = varargin{6}; elseif nargin == 5 info = varargin{1}; timelock = varargin{2}; freq = varargin{3}; summary = varargin{4}; toi = varargin{5}; end % determine whether it is EEG or MEG try [iseeg, ismeg, isctf, fltp] = filetyper(timelock.cfg.dataset); catch % in case the input is a matfile (and the dataset field does not exist): ugly workaround [iseeg, ismeg, isctf, fltp] = filetyper(headpos.cfg.dataset); end if ismeg scaling = 1e15; % assuming data is in T and needs to become fT powscaling = scaling^2; ylab = 'fT'; elseif iseeg scaling = 1e0; % assuming data is in muV already powscaling = scaling^2; ylab = '\muV'; end % PARENT FIGURE h.MainFigure = figure(... 'MenuBar','none',... 'Name','ft_qualitycheck',... 'Units','normalized',... 'color','white',... 'Position',[0.01 0.01 .99 .99]); % nearly fullscreen if strcmp(info.startdate,'unknown') tmp = 'unknown'; else [d,w] = weekday(info.startdate); tmp = [w ' ' info.startdate]; end h.MainText = uicontrol(... 'Parent',h.MainFigure,... 'Style','text',... 'Units','normalized',... 'FontSize',10,... 'String',tmp,... 'Backgroundcolor','white',... 'Position',[.06 .96 .15 .02]); h.MainText2 = uicontrol(... 'Parent',h.MainFigure,... 'Style','text',... 'Units','normalized',... 'FontSize',10,... 'String','Jump artefacts',... 'Backgroundcolor','white',... 'Position',[.08 .46 .12 .02]); h.MainText3 = uicontrol(... 'Parent',h.MainFigure,... 'Style','text',... 'Units','normalized',... 'FontSize',10,... 'String','Mean powerspectrum',... 'Backgroundcolor','white',... 'Position',[.4 .3 .15 .02]); h.MainText4 = uicontrol(... 'Parent',h.MainFigure,... 'Style','text',... 'Units','normalized',... 'FontSize',10,... 'String','Timecourses',... 'Backgroundcolor','white',... 'Position',[.5 .96 .11 .02]); h.MainText5 = uicontrol(... 'Parent',h.MainFigure,... 'Style','text',... 'Units','normalized',... 'FontSize',10,... 'String','Events',... 'Backgroundcolor','white',... 'Position',[.81 .3 .06 .02]); % HEADMOTION PANEL h.HmotionPanel = uipanel(... 'Parent',h.MainFigure,... 'Units','normalized',... 'Backgroundcolor','white',... 'Position',[.01 .5 .25 .47]); h.DataText = uicontrol(... 'Parent',h.HmotionPanel,... 'Style','text',... 'Units','normalized',... 'FontSize',10,... 'String',info.datasetname,... 'Backgroundcolor','white',... 'Position',[.01 .85 .99 .1]); h.TimeText = uicontrol(... 'Parent',h.HmotionPanel,... 'Style','text',... 'Units','normalized',... 'FontSize',10,... 'String',[info.starttime ' - ' info.stoptime],... 'Backgroundcolor','white',... 'Position',[.01 .78 .99 .1]); if ismeg allchans = ft_senslabel(ft_senstype(timelock)); misschans = setdiff(ft_channelselection('MEG', info.hdr.label), allchans); nchans = num2str(size(ft_channelselection('MEG', info.hdr.label),1)); else misschans = ''; nchans = num2str(size(ft_channelselection('EEG', info.hdr.label),1)); end h.DataText2 = uicontrol(... 'Parent',h.HmotionPanel,... 'Style','text',... 'Units','normalized',... 'FontSize',10,... 'String',[fltp ', fs: ' num2str(info.hdr.Fs) ', nchans: ' nchans],... 'Backgroundcolor','white',... 'Position',[.01 .71 .99 .1]); h.DataText3 = uicontrol(... 'Parent',h.HmotionPanel,... 'Style','text',... 'Units','normalized',... 'FontSize',10,... 'String',['missing chans: ' misschans'],... 'Backgroundcolor','white',... 'Position',[.01 .64 .99 .1]); % boxplot headmotion (*10; cm-> mm) per coil if exist('headpos','var') h.HmotionAxes = axes(... 'Parent',h.HmotionPanel,... 'Units','normalized',... 'color','white',... 'Position',[.05 .08 .9 .52]); hmotions = ([summary.avg(8,:)' summary.avg(7,:)' summary.avg(6,:)'])*10; boxplot(h.HmotionAxes, hmotions, 'orientation', 'horizontal', 'notch', 'on'); set(h.HmotionAxes,'YTick',1:3); set(h.HmotionAxes,'YTickLabel',{'R','L','N'}); xlim(h.HmotionAxes, [0 10]); xlabel(h.HmotionAxes, 'Headmotion from start [mm]'); end % TIMECOURSE PANEL h.SignalPanel = uipanel(... 'Parent',h.MainFigure,... 'Units','normalized',... 'Backgroundcolor','white',... 'Position',[.28 .34 .71 .63]); h.SignalAxes = axes(... 'Parent',h.SignalPanel,... 'Units','normalized',... 'color','white',... 'Position',[.08 .36 .89 .3]); h.LinenoiseAxes = axes(... 'Parent',h.SignalPanel,... 'Units','normalized',... 'color','white',... 'Position',[.08 .23 .89 .1]); h.LowfreqnoiseAxes = axes(... 'Parent',h.SignalPanel,... 'Units','normalized',... 'color','white',... 'Position',[.08 .1 .89 .1]); % plot hmotion timecourses per coil (*10; cm-> mm) if exist('headpos','var') h.HmotionTimecourseAxes = axes(... 'Parent',h.SignalPanel,... 'Units','normalized',... 'color','white',... 'Position',[.08 .73 .89 .22]); plot(h.HmotionTimecourseAxes, summary.time, clipat(summary.avg(6,:)*10, 0, 10), ... summary.time, clipat(summary.avg(7,:)*10, 0, 10), ... summary.time, clipat(summary.avg(8,:)*10, 0, 10), 'LineWidth',2); ylim(h.HmotionTimecourseAxes,[0 10]); ylabel(h.HmotionTimecourseAxes, 'Coil distance [mm]'); xlim(h.HmotionTimecourseAxes,toi); grid(h.HmotionTimecourseAxes,'on'); legend(h.HmotionTimecourseAxes, 'N','L','R'); end % plot mean and range of the raw signal plot(h.SignalAxes, summary.time, summary.avg(5,:)*scaling, summary.time, summary.avg(1,:)*scaling, 'LineWidth', 2); set(h.SignalAxes,'Nextplot','add'); plot(h.SignalAxes, summary.time, summary.avg(3,:)*scaling, summary.time, summary.avg(4,:)*scaling, 'LineWidth', 1, 'Color', [255/255 127/255 39/255]); grid(h.SignalAxes,'on'); ylabel(h.SignalAxes, ['Amplitude [' ylab ']']); xlim(h.SignalAxes,toi); legend(h.SignalAxes,'Range','Mean','Min','Max'); set(h.SignalAxes,'XTickLabel',''); % plot linenoise semilogy(h.LinenoiseAxes, summary.time, clipat(summary.avg(10,:)*powscaling, 1e2, 1e4), 'LineWidth',2); grid(h.LinenoiseAxes,'on'); legend(h.LinenoiseAxes, ['LineFreq [' ylab '^2/Hz]']); set(h.LinenoiseAxes,'XTickLabel',''); xlim(h.LinenoiseAxes,toi); ylim(h.LinenoiseAxes,[1e2 1e4]); % before april 28th this was 1e0 - 1e3 % plot lowfreqnoise semilogy(h.LowfreqnoiseAxes, summary.time, clipat(summary.avg(9,:)*powscaling, 1e10, 1e12), 'LineWidth',2); grid(h.LowfreqnoiseAxes,'on'); xlim(h.LowfreqnoiseAxes,toi); ylim(h.LowfreqnoiseAxes,[1e10 1e12]); legend(h.LowfreqnoiseAxes, ['LowFreq [' ylab '^2/Hz]']); xlabel(h.LowfreqnoiseAxes, 'Time [seconds]'); % before april 28th this was 1e0 - 1e10 % EVENT PANEL h.EventPanel = uipanel(... 'Parent',h.MainFigure,... 'Units','normalized',... 'Backgroundcolor','white',... 'Position',[.7 .01 .29 .3]); % event details eventtypes = {}; eventtriggers = {}; eventvalues = {}; if ~isempty(info.event) [a,b,c] = unique({info.event.type}); for j=1:length(a) eventtypes{j,1} = a{j}; eventtriggers{j,1} = sum(c==j); eventvalues{j,1} = length(unique([info.event(c==j).value])); end end if isempty(eventtypes) eventtypes{1,1} = 'no triggers found'; end h.EventText = uicontrol(... 'Parent',h.EventPanel,... 'Style','text',... 'Units','normalized',... 'FontSize',10,... 'String',['Types'; ' '; eventtypes],... 'Backgroundcolor','white',... 'Position',[.05 .05 .4 .85]); h.EventText2 = uicontrol(... 'Parent',h.EventPanel,... 'Style','text',... 'Units','normalized',... 'FontSize',10,... 'String',['Triggers'; ' '; eventtriggers],... 'Backgroundcolor','white',... 'Position',[.55 .05 .2 .85]); h.EventText3 = uicontrol(... 'Parent',h.EventPanel,... 'Style','text',... 'Units','normalized',... 'FontSize',10,... 'String',['Values'; ' '; eventvalues],... 'Backgroundcolor','white',... 'Position',[.8 .05 .15 .85]); % POWERSPECTRUM PANEL h.SpectrumPanel = uipanel(... 'Parent',h.MainFigure,... 'Units','normalized',... 'Backgroundcolor','white',... 'Position',[.28 .01 .4 .3]); h.SpectrumAxes = axes(... 'Parent',h.SpectrumPanel,... 'Units','normalized',... 'color','white',... 'Position',[.15 .2 .8 .7]); % plot powerspectrum loglog(h.SpectrumAxes, freq.freq, mean(mean(freq.powspctrm,1),3)*powscaling,'r','LineWidth',2); xlabel(h.SpectrumAxes, 'Frequency [Hz]'); ylabel(h.SpectrumAxes, ['Power [' ylab '^2/Hz]']); % ARTEFACT PANEL h.JumpPanel = uipanel(... 'Parent',h.MainFigure,... 'Units','normalized',... 'Backgroundcolor','white',... 'Position',[.01 .01 .25 .46]); % jump details jumpchans = {}; jumpcounts = {}; [jumps,i] = find(timelock.jumps>0); % find all jumps [a,b,c] = unique(jumps); for j=1:length(a) jumpchans{j,1} = timelock.label{a(j)}; jumpcounts{j,1} = sum(c==j); end if isempty(jumpchans) jumpchans{1,1} = 'no jumps detected'; end h.JumpText = uicontrol(... 'Parent',h.JumpPanel,... 'Style','text',... 'Units','normalized',... 'FontSize',10,... 'String',jumpchans,... 'Backgroundcolor','white',... 'Position',[.15 .5 .25 .4]); h.JumpText2 = uicontrol(... 'Parent',h.JumpPanel,... 'Style','text',... 'Units','normalized',... 'FontSize',10,... 'String',jumpcounts,... 'Backgroundcolor','white',... 'Position',[.65 .5 .2 .4]); % plot jumps on the dewar sensors if ismeg h.TopoMEG = axes(... 'Parent',h.JumpPanel,... 'color','white',... 'Units','normalized',... 'Position',[0.4 0.05 0.55 0.4]); MEGchans = ft_channelselection('MEG', timelock.label); MEGchanindx = match_str(timelock.label, MEGchans); cfgtopo = []; cfgtopo.marker = 'off'; cfgtopo.colorbar = 'no'; cfgtopo.comment = 'no'; cfgtopo.style = 'blank'; cfgtopo.layout = ft_prepare_layout(timelock); cfgtopo.highlight = 'on'; cfgtopo.highlightsymbol = '.'; cfgtopo.highlightsize = 14; cfgtopo.highlightchannel = find(sum(timelock.jumps(MEGchanindx,:),2)>0); data.label = MEGchans; data.powspctrm = sum(timelock.jumps(MEGchanindx,:),2); data.dimord = 'chan_freq'; data.freq = 1; axes(h.TopoMEG); ft_topoplotTFR(cfgtopo, data); clear data; end
github
lcnbeapp/beapp-master
ft_denoise_pca.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_denoise_pca.m
17,813
utf_8
ae42782c1e01befe56fb6dfb726bdc5e
function data = ft_denoise_pca(cfg, varargin) % FT_DENOISE_PCA performs a principal component analysis (PCA) on specified reference % channels and subtracts the projection of the data of interest onto this orthogonal % basis from the data of interest. This is the algorithm which is applied by 4D to % compute noise cancellation weights on a dataset of interest. This function has been % designed for 4D MEG data, but can also be applied to data from other MEG systems. % % Use as % [dataout] = ft_denoise_pca(cfg, data) % or as % [dataout] = ft_denoise_pca(cfg, data, refdata) % where "data" is a raw data structure that was obtained with FT_PREPROCESSING. If % you specify the additional input "refdata", the specified reference channels for % the regression will be taken from this second data structure. This can be useful % when reference-channel specific preprocessing needs to be done (e.g. low-pass % filtering). % % The output structure dataout contains the denoised data in a format that is % consistent with the output of FT_PREPROCESSING. % % The configuration should be according to % cfg.refchannel = the channels used as reference signal (default = 'MEGREF') % cfg.channel = the channels to be denoised (default = 'MEG') % cfg.truncate = optional truncation of the singular value spectrum (default = 'no') % cfg.zscore = standardise reference data prior to PCA (default = 'no') % cfg.pertrial = 'no' (default) or 'yes'. Regress out the references on a per trial basis % cfg.trials = list of trials that are used (default = 'all') % % if cfg.truncate is integer n > 1, n will be the number of singular values kept. % if 0 < cfg.truncate < 1, the singular value spectrum will be thresholded at the % fraction cfg.truncate of the largest singular value. % % See also FT_PREPROCESSING, FT_DENOISE_SYNTHETIC % Undocumented cfg-option: cfg.pca the output structure of an earlier call % to the function. Can be used regress out the reference channels from % another data set. % Copyright (c) 2008-2009, Jan-Mathijs Schoffelen, CCNi Glasgow % Copyright (c) 2010-2011, Jan-Mathijs Schoffelen, DCCN Nijmegen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble provenance varargin ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input data is valid for this function for i=1:length(varargin) varargin{i} = ft_checkdata(varargin{i}, 'datatype', 'raw'); end % set the defaults cfg.refchannel = ft_getopt(cfg, 'refchannel', 'MEGREF'); cfg.channel = ft_getopt(cfg, 'channel', 'MEG'); cfg.truncate = ft_getopt(cfg, 'truncate', 'no'); cfg.zscore = ft_getopt(cfg, 'zscore', 'no'); cfg.trials = ft_getopt(cfg, 'trials', 'all', 1); cfg.pertrial = ft_getopt(cfg, 'pertrial', 'no'); cfg.feedback = ft_getopt(cfg, 'feedback', 'none'); if strcmp(cfg.pertrial, 'yes'), %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % iterate over trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% tmpcfg = keepfields(cfg, 'trials'); % select trials of interest for i=1:numel(varargin) varargin{i} = ft_selectdata(tmpcfg, varargin{i}); [cfg, varargin{i}] = rollback_provenance(cfg, varargin{i}); end tmp = cell(numel(varargin{1}.trial),1); tmpcfg = cfg; tmpcfg.pertrial = 'no'; for k = 1:numel(varargin{1}.trial) tmpcfg.trials = k; % select a single trial tmp{k} = ft_denoise_pca(tmpcfg, varargin{:}); [dum, tmp{k}] = rollback_provenance(tmpcfg, tmp{k}); end data = ft_appenddata([], tmp{:}); [cfg, data] = rollback_provenance(cfg, data); else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute it for the data concatenated over all trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% computeweights = ~isfield(cfg, 'pca'); if length(varargin)==1, % channel data and reference channel data are in 1 data structure data = varargin{1}; megchan = ft_channelselection(cfg.channel, data.label); refchan = ft_channelselection(cfg.refchannel, data.label); % split data into data and refdata tmpcfg = []; tmpcfg.channel = refchan; tmpcfg.feedback = cfg.feedback; refdata = ft_preprocessing(tmpcfg, data); tmpcfg.channel = megchan; data = ft_preprocessing(tmpcfg, data); else % channel data and reference channel data are in 2 data structures data = varargin{1}; refdata = varargin{2}; megchan = ft_channelselection(cfg.channel, data.label); refchan = ft_channelselection(cfg.refchannel, refdata.label); % split data into data and refdata tmpcfg = []; tmpcfg.channel = refchan; tmpcfg.feedback = cfg.feedback; refdata = ft_preprocessing(tmpcfg, refdata); tmpcfg.channel = megchan; data = ft_preprocessing(tmpcfg, data); % FIXME do compatibility check on data vs refdata with respect to dimensions (time-trials) end % select trials of interest tmpcfg = keepfields(cfg, 'trials'); data = ft_selectdata(tmpcfg, data); refdata = ft_selectdata(tmpcfg, refdata); % restore the provenance information [cfg, data] = rollback_provenance(cfg, data); [dum, refdata] = rollback_provenance(cfg, refdata); refchan = ft_channelselection(cfg.refchannel, refdata.label); refindx = match_str(refdata.label, refchan); megchan = ft_channelselection(cfg.channel, data.label); megindx = match_str(data.label, megchan); nref = length(refindx); ntrl = length(data.trial); if ischar(cfg.truncate) && strcmp(cfg.truncate, 'no') cfg.truncate = length(refindx); elseif ischar(cfg.truncate) || (cfg.truncate>1 && cfg.truncate/round(cfg.truncate)~=1) || cfg.truncate>length(refindx) error('cfg.truncate should be either ''no'', an integer number <= the number of references, or a number between 0 and 1'); % FIXME the default truncation applied by 4D is 1x10^-8 end % compute and remove mean from data fprintf('removing the mean from the channel data and reference channel data\n'); m = cellmean(data.trial, 2); data.trial = cellvecadd(data.trial, -m); m = cellmean(refdata.trial, 2); refdata.trial = cellvecadd(refdata.trial, -m); % compute std of data before the regression stdpre = cellstd(data.trial, 2); if computeweights, % zscore if strcmp(cfg.zscore, 'yes'), fprintf('zscoring the reference channel data\n'); [refdata.trial, sdref] = cellzscore(refdata.trial, 2, 0); %forced demeaned already else sdref = ones(nref, 1); end % compute covariance of refchannels and do svd fprintf('performing pca on the reference channel data\n'); crefdat = cellcov(refdata.trial, [], 2, 0); [u,s,v] = svd(crefdat); % determine the truncation and rotation if cfg.truncate<1 % keep all singular vectors with singular values >= cfg.truncate*s(1,1) s1 = s./max(s(:)); keep = find(diag(s1)>cfg.truncate); else keep = 1:cfg.truncate; end fprintf('keeping %d out of %d components\n',numel(keep),size(u,2)); rotmat = u(:, keep)'; % rotate the refdata fprintf('projecting the reference data onto the pca-subspace\n'); refdata.trial = cellfun(@mtimes, repmat({rotmat}, 1, ntrl), refdata.trial, 'UniformOutput', 0); % project megdata onto the orthogonal basis fprintf('computing the regression weights\n'); nom = cellcov(data.trial, refdata.trial, 2, 0); denom = cellcov(refdata.trial, [], 2, 0); rw = (pinv(denom)*nom')'; % subtract projected data fprintf('subtracting the reference channel data from the channel data\n'); for k = 1:ntrl data.trial{k} = data.trial{k} - rw*refdata.trial{k}; end % rotate back and 'unscale' pca.w = rw*rotmat*diag(1./sdref); pca.label = data.label; pca.reflabel = refdata.label; pca.rotmat = rotmat; cfg.pca = pca; else fprintf('applying precomputed weights to the data\n'); % check whether the weight table contains the specified references % ensure the ordering of the meg-data to be consistent with the weights % ensure the ordering of the ref-data to be consistent with the weights [i1,i2] = match_str(refchan, cfg.pca.reflabel); [i3,i4] = match_str(megchan, cfg.pca.label); if length(i2)~=length(cfg.pca.reflabel), error('you specified fewer references to use as there are in the precomputed weight table'); end refindx = refindx(i1); megindx = megindx(i3); cfg.pca.w = cfg.pca.w(i4,i2); cfg.pca.label = cfg.pca.label(i4); cfg.pca.reflabel= cfg.pca.reflabel(i2); if isfield(cfg.pca, 'rotmat'), cfg.pca = rmfield(cfg.pca, 'rotmat'); % dont know end for k = 1:ntrl data.trial{k} = data.trial{k} - cfg.pca.w*refdata.trial{k}; end pca = cfg.pca; end % compute std of data after stdpst = cellstd(data.trial, 2); % demean FIXME is this needed m = cellmean(data.trial, 2); data.trial = cellvecadd(data.trial, -m); % apply weights to the gradiometer-array if isfield(data, 'grad') fprintf('applying the weights to the gradiometer balancing matrix\n'); montage = []; labelnew = pca.label; nlabelnew = length(labelnew); % add columns of refchannels not yet present in labelnew % [id, i1] = setdiff(pca.reflabel, labelnew); % labelorg = [labelnew; pca.reflabel(sort(i1))]; labelorg = data.grad.label; nlabelorg = length(labelorg); % start with identity montage.tra = eye(nlabelorg); % subtract weights [i1, i2] = match_str(labelorg, pca.reflabel); [i3, i4] = match_str(labelorg, pca.label); montage.tra(i3,i1) = montage.tra(i3,i1) - pca.w(i4,i2); montage.labelorg = labelorg; montage.labelnew = labelorg; data.grad = ft_apply_montage(data.grad, montage, 'keepunused', 'yes', 'balancename', 'pca'); % order the fields fnames = fieldnames(data.grad.balance); tmp = false(1,numel(fnames)); for k = 1:numel(fnames) tmp(k) = isstruct(data.grad.balance.(fnames{k})); end [tmp, ix] = sort(tmp,'descend'); data.grad.balance = orderfields(data.grad.balance, fnames(ix)); else warning('fieldtrip:ft_denoise_pca:WeightsNotAppliedToSensors', 'weights have been applied to the data only, not to the sensors'); end end % if pertrial % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous varargin ft_postamble provenance data ft_postamble history data ft_postamble savevar data %%%%%%%%%%%%%%%%% % SUBFUNCTIONS %%%%%%%%%%%%%%%%% %-----cellcov function [c] = cellcov(x, y, dim, flag) % [C] = CELLCOV(X, DIM) computes the covariance, across all cells in x along % the dimension dim. When there are three inputs, covariance is computed between % all cells in x and y % % X (and Y) should be linear cell-array(s) of matrices for which the size in at % least one of the dimensions should be the same for all cells if nargin==2, flag = 1; dim = y; y = []; elseif nargin==3, flag = 1; end nx = size(x); if ~iscell(x) || length(nx)>2 || all(nx>1), error('incorrect input for cellmean'); end if nargin==1, scx1 = cellfun('size', x, 1); scx2 = cellfun('size', x, 2); if all(scx2==scx2(1)), dim = 2; %let second dimension prevail elseif all(scx1==scx1(1)), dim = 1; else error('no dimension to compute covariance for'); end end if flag, mx = cellmean(x, 2); x = cellvecadd(x, -mx); if ~isempty(y), my = cellmean(y, 2); y = cellvecadd(y, -my); end end nx = max(nx); nsmp = cellfun('size', x, dim); if isempty(y), csmp = cellfun(@covc, x, repmat({dim},1,nx), 'UniformOutput', 0); else csmp = cellfun(@covc, x, y, repmat({dim},1,nx), 'UniformOutput', 0); end nc = size(csmp{1}); c = sum(reshape(cell2mat(csmp), [nc(1) nc(2) nx]), 3)./sum(nsmp); function [c] = covc(x, y, dim) if nargin==2, dim = y; y = x; end if dim==1, c = x'*y; elseif dim==2, c = x*y'; end %-----cellmean function [m] = cellmean(x, dim) % [M] = CELLMEAN(X, DIM) computes the mean, across all cells in x along % the dimension dim. % % X should be an linear cell-array of matrices for which the size in at % least one of the dimensions should be the same for all cells nx = size(x); if ~iscell(x) || length(nx)>2 || all(nx>1), error('incorrect input for cellmean'); end if nargin==1, scx1 = cellfun('size', x, 1); scx2 = cellfun('size', x, 2); if all(scx2==scx2(1)), dim = 2; %let second dimension prevail elseif all(scx1==scx1(1)), dim = 1; else error('no dimension to compute mean for'); end end nx = max(nx); nsmp = cellfun('size', x, dim); ssmp = cellfun(@sum, x, repmat({dim},1,nx), 'UniformOutput', 0); m = sum(cell2mat(ssmp), dim)./sum(nsmp); %-----cellstd function [sd] = cellstd(x, dim, flag) % [M] = CELLSTD(X, DIM, FLAG) computes the standard deviation, across all cells in x along % the dimension dim, normalising by the total number of samples % % X should be an linear cell-array of matrices for which the size in at % least one of the dimensions should be the same for all cells. If flag==1, the mean will % be subtracted first (default behaviour, but to save time on already demeaned data, it % can be set to 0). nx = size(x); if ~iscell(x) || length(nx)>2 || all(nx>1), error('incorrect input for cellstd'); end if nargin<2, scx1 = cellfun('size', x, 1); scx2 = cellfun('size', x, 2); if all(scx2==scx2(1)), dim = 2; %let second dimension prevail elseif all(scx1==scx1(1)), dim = 1; else error('no dimension to compute mean for'); end elseif nargin==2, flag = 1; end if flag, m = cellmean(x, dim); x = cellvecadd(x, -m); end nx = max(nx); nsmp = cellfun('size', x, dim); ssmp = cellfun(@sumsq, x, repmat({dim},1,nx), 'UniformOutput', 0); sd = sqrt(sum(cell2mat(ssmp), dim)./sum(nsmp)); function [s] = sumsq(x, dim) s = sum(x.^2, dim); %-----cellvecadd function [y] = cellvecadd(x, v) % [Y]= CELLVECADD(X, V) - add vector to all rows or columns of each matrix % in cell-array X % check once and for all to save time persistent bsxfun_exists; if isempty(bsxfun_exists); bsxfun_exists=exist('bsxfun','builtin'); if ~bsxfun_exists; error('bsxfun not found.'); end end nx = size(x); if ~iscell(x) || length(nx)>2 || all(nx>1), error('incorrect input for cellmean'); end if ~iscell(v), v = repmat({v}, nx); end y = cellfun(@bsxfun, repmat({@plus}, nx), x, v, 'UniformOutput', 0); %-----cellvecmult function [y] = cellvecmult(x, v) % [Y]= CELLVECMULT(X, V) - multiply vectors in cell-array V % to all rows or columns of each matrix in cell-array X % V can be a vector or a cell-array of vectors % check once and for all to save time persistent bsxfun_exists; if isempty(bsxfun_exists); bsxfun_exists=exist('bsxfun','builtin'); if ~bsxfun_exists; error('bsxfun not found.'); end end nx = size(x); if ~iscell(x) || length(nx)>2 || all(nx>1), error('incorrect input for cellmean'); end if ~iscell(v), v = repmat({v}, nx); end sx1 = cellfun('size', x, 1); sx2 = cellfun('size', x, 2); sv1 = cellfun('size', v, 1); sv2 = cellfun('size', v, 2); if all(sx1==sv1) && all(sv2==1), elseif all(sx2==sv2) && all(sv1==1), elseif all(sv1==1) && all(sv2==1), else error('inconsistent input'); end y = cellfun(@bsxfun, repmat({@times}, nx), x, v, 'UniformOutput', 0); %-----cellzscore function [z, sd, m] = cellzscore(x, dim, flag) % [Z, SD] = CELLZSCORE(X, DIM, FLAG) computes the zscore, across all cells in x along % the dimension dim, normalising by the total number of samples % % X should be an linear cell-array of matrices for which the size in at % least one of the dimensions should be the same for all cells. If flag==1, the mean will % be subtracted first (default behaviour, but to save time on already demeaned data, it % can be set to 0). SD is a vector containing the standard deviations, used for the normalisation. nx = size(x); if ~iscell(x) || length(nx)>2 || all(nx>1), error('incorrect input for cellstd'); end if nargin<2, scx1 = cellfun('size', x, 1); scx2 = cellfun('size', x, 2); if all(scx2==scx2(1)), dim = 2; %let second dimension prevail elseif all(scx1==scx1(1)), dim = 1; else error('no dimension to compute mean for'); end elseif nargin==2, flag = 1; end if flag, m = cellmean(x, dim); x = cellvecadd(x, -m); end sd = cellstd(x, dim, 0); z = cellvecmult(x, 1./sd);
github
lcnbeapp/beapp-master
ft_sensorrealign.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_sensorrealign.m
35,660
utf_8
72c147097c88c1c750a4b90386ece4b4
function [elec_realigned] = ft_sensorrealign(cfg, elec_original) % FT_SENSORREALIGN rotates and translates electrode and gradiometer % sensor positions to template electrode positions or towards the head % surface. It can either perform a rigid body transformation, in which only % the coordinate system is changed, or it can apply additional deformations % to the input sensors. Different methods for aligning the input electrodes % to the subjects head are implemented, which are described in detail % below. % % FIDUCIAL - You can apply a rigid body realignment based on three fiducial % locations. After realigning, the fiducials in the input electrode set % (typically nose, left and right ear) are along the same axes as the % fiducials in the template electrode set. % % TEMPLATE - You can apply a spatial transformation/deformation that % automatically minimizes the distance between the electrodes or % gradiometers and a template or sensor array. The warping methods use a % non-linear search to minimize the distance between the input sensor % positions and the corresponding template sensors. % % INTERACTIVE - You can display the skin surface together with the % electrode or gradiometer positions, and manually (using the graphical % user interface) adjust the rotation, translation and scaling parameters, % so that the electrodes correspond with the skin. % % MANUAL - You can display the skin surface and manually determine the % electrode positions by clicking on the skin surface. % % HEADSHAPE - You can apply a spatial transformation/deformation that % automatically minimizes the distance between the electrodes and the head % surface. The warping methods use a non-linear search to minimize the % distance between the input sensor positions and the projection of the % electrodes on the head surface. % % Use as % [sensor] = ft_sensorrealign(cfg) or % [sensor] = ft_sensorrealign(cfg, sensor) % where you specify the electrodes or gradiometers in the configuration % structure (see below) or as the second input argument. % % The configuration can contain the following options % cfg.method = string representing the method for aligning or placing the electrodes % 'fiducial' realign using three fiducials (e.g. NAS, LPA and RPA) % 'template' realign the sensors to match a template set % 'interactive' realign manually using a graphical user interface % 'manual' manual positioning of the electrodes by clicking in a graphical user interface % 'headshape' realign the sensors to fit the head surface % cfg.warp = string describing the spatial transformation for the template method % 'rigidbody' apply a rigid-body warp (default) % 'globalrescale' apply a rigid-body warp with global rescaling % 'traditional' apply a rigid-body warp with individual axes rescaling % 'nonlin1' apply a 1st order non-linear warp % 'nonlin2' apply a 2nd order non-linear warp % 'nonlin3' apply a 3rd order non-linear warp % 'nonlin4' apply a 4th order non-linear warp % 'nonlin5' apply a 5th order non-linear warp % cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), % see FT_CHANNELSELECTION for details % cfg.fiducial = cell-array with the name of three fiducials used for % realigning (default = {'nasion', 'lpa', 'rpa'}) % cfg.casesensitive = 'yes' or 'no', determines whether string comparisons % between electrode labels are case sensitive (default = 'yes') % cfg.feedback = 'yes' or 'no' (default = 'no') % % The EEG or MEG sensor positions can be present in the second input argument or can be specified as % cfg.elec = structure with electrode positions, see FT_DATATYPE_SENS % cfg.grad = structure with gradiometer definition, see FT_DATATYPE_SENS % cfg.elecfile = name of file containing the electrode positions, see FT_READ_SENS % cfg.gradfile = name of file containing the gradiometer definition, see FT_READ_SENS % % To realign the sensors using the fiducials, the target has to contain the % three template fiducials, e.g. % cfg.target.pos(1,:) = [110 0 0] % location of the nose % cfg.target.pos(2,:) = [0 90 0] % location of the left ear % cfg.target.pos(3,:) = [0 -90 0] % location of the right ear % cfg.target.label = {'NAS', 'LPA', 'RPA'} % % To align the sensors to a single template set or to multiple electrode % sets (which will be averaged), you should specify the target as % cfg.target = single electrode or gradiometer set that serves as standard % or % cfg.target(1..N) = list of electrode or gradiometer sets that are averaged into the standard % The target electrode or gradiometer sets can be specified either as % structures (i.e. when they are already read in memory) or as file names. % % To align existing electrodes to the head surface, or to manually position % new electrodes using the head surface, you should specify % cfg.headshape = a filename containing headshape, a structure containing a % single triangulated boundary, or a Nx3 matrix with surface % points % % See also FT_READ_SENS, FT_VOLUMEREALIGN, FT_INTERACTIVEREALIGN % Copyright (C) 2005-2011, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % DEPRECATED by roboos on 11 November 2015 % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=1830 % support for this functionality can be removed mid 2016 warning('FT_SENSORREALIGN is deprecated, please use FT_ELECTRODEREALIGN instead.') % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble provenance elec_original ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % the interactive method uses a global variable to get the data from the figure when it is closed global norm % set the defaults if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end if ~isfield(cfg, 'coordsys'), cfg.coordsys = []; end if ~isfield(cfg, 'feedback'), cfg.feedback = 'no'; end if ~isfield(cfg, 'casesensitive'), cfg.casesensitive = 'yes'; end if ~isfield(cfg, 'warp'), cfg.warp = 'rigidbody'; end if ~isfield(cfg, 'label'), cfg.label = 'off'; end cfg = ft_checkconfig(cfg, 'renamed', {'template', 'target'}); cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'realignfiducials', 'fiducial'}); cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'realignfiducial', 'fiducial'}); cfg = ft_checkconfig(cfg, 'renamedval', {'warp', 'homogenous', 'rigidbody'}); cfg = ft_checkconfig(cfg, 'forbidden', 'outline'); if isfield(cfg, 'headshape') && isa(cfg.headshape, 'config') % convert the nested config-object back into a normal structure cfg.headshape = struct(cfg.headshape); end if ~isempty(cfg.coordsys) switch lower(cfg.coordsys) case 'ctf' cfg.target = []; cfg.target.pos(1,:) = [100 0 0]; cfg.target.pos(2,:) = [0 80 0]; cfg.target.pos(3,:) = [0 -80 0]; cfg.target.label{1} = 'NAS'; cfg.target.label{2} = 'LPA'; cfg.target.label{3} = 'RPA'; otherwise error('the %s coordinate system is not automatically supported, please specify the details in cfg.target') end end % ensure that the right cfg options have been set corresponding to the method switch cfg.method case 'template' % realign the sensors to match a template set cfg = ft_checkconfig(cfg, 'required', 'target', 'forbidden', 'headshape'); case 'headshape' % realign the sensors to fit the head surface cfg = ft_checkconfig(cfg, 'required', 'headshape', 'forbidden', 'target'); case 'fiducial' % realign using the NAS, LPA and RPA fiducials cfg = ft_checkconfig(cfg, 'required', 'target', 'forbidden', 'headshape'); case 'interactive' % realign manually using a graphical user interface cfg = ft_checkconfig(cfg, 'required', 'headshape'); case 'manual' % manual positioning of the electrodes by clicking in a graphical user interface cfg = ft_checkconfig(cfg, 'required', 'headshape', 'forbidden', 'target'); end % switch cfg.method % the data can be passed as input arguments or can be read from disk hasdata = exist('data', 'var'); % get the electrode definition that should be warped if ~hasdata try % try to get the description from the cfg elec_original = ft_fetch_sens(cfg); catch % the "catch me" syntax is broken on MATLAB74, this fixes it me = lasterror; % start with an empty set of electrodes, this is useful for manual positioning elec_original = []; elec_original.pos = zeros(0,3); elec_original.label = cell(0,1); elec_original.unit = 'mm'; warning(me.message, me.identifier); end else % the input electrodes were specified as second input argument % or read from cfg.inputfile end % ensure that the units are specified elec_original = ft_convert_units(elec_original); elec_original = ft_datatype_sens(elec_original); % ensure up-to-date sensor description (Oct 2011) % remember the original electrode locations and labels and do all the work % with a temporary copy, this involves channel selection and changing to % lower case elec = elec_original; if strcmp(cfg.method, 'fiducial') && isfield(elec, 'fid') % instead of working with all sensors, only work with the fiducials % this is useful for gradiometer structures fprintf('using the fiducials instead of the sensor positions\n'); elec.fid.unit = elec.unit; elec = elec.fid; end usetemplate = isfield(cfg, 'target') && ~isempty(cfg.target); useheadshape = isfield(cfg, 'headshape') && ~isempty(cfg.headshape); if usetemplate % get the template electrode definitions if ~iscell(cfg.target) cfg.target = {cfg.target}; end Ntemplate = length(cfg.target); for i=1:Ntemplate if isstruct(cfg.target{i}) template(i) = cfg.target{i}; else template(i) = ft_read_sens(cfg.target{i}); end end clear tmp for i=1:Ntemplate tmp(i) = ft_datatype_sens(template(i)); % ensure up-to-date sensor description tmp(i) = ft_convert_units(template(i), elec.unit); % ensure that the units are consistent with the electrodes end template = tmp; end if useheadshape % get the surface describing the head shape if isstruct(cfg.headshape) % use the headshape surface specified in the configuration headshape = fixpos(cfg.headshape); elseif isnumeric(cfg.headshape) && size(cfg.headshape,2)==3 % use the headshape points specified in the configuration headshape.pos = cfg.headshape; elseif ischar(cfg.headshape) % read the headshape from file headshape = ft_read_headshape(cfg.headshape); else error('cfg.headshape is not specified correctly') end if ~isfield(headshape, 'tri') % generate a closed triangulation from the surface points headshape.pos = unique(headshape.pos, 'rows'); headshape.tri = projecttri(headshape.pos); end headshape = ft_convert_units(headshape, elec.unit); % ensure that the units are consistent with the electrodes end % convert all labels to lower case for string comparisons % this has to be done AFTER keeping the original labels and positions if strcmp(cfg.casesensitive, 'no') for i=1:length(elec.label) elec.label{i} = lower(elec.label{i}); end for j=1:length(template) for i=1:length(template(j).label) template(j).label{i} = lower(template(j).label{i}); end end end if strcmp(cfg.feedback, 'yes') % create an empty figure, continued below... figure axis equal axis vis3d hold on xlabel('x') ylabel('y') zlabel('z') end % start with an empty structure, this will be returned at the end norm = []; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(cfg.method, 'template') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % determine electrode selection and overlapping subset for warping cfg.channel = ft_channelselection(cfg.channel, elec.label); for i=1:Ntemplate cfg.channel = ft_channelselection(cfg.channel, template(i).label); end % make consistent subselection of electrodes [cfgsel, datsel] = match_str(cfg.channel, elec.label); elec.label = elec.label(datsel); elec.chanpos = elec.chanpos(datsel,:); for i=1:Ntemplate [cfgsel, datsel] = match_str(cfg.channel, template(i).label); template(i).label = template(i).label(datsel); template(i).pos = template(i).pos(datsel,:); end % compute the average of the template electrode positions average = ft_average_sens(template); fprintf('warping electrodes to average template... '); % the newline comes later [norm.chanpos, norm.m] = ft_warp_optim(elec.chanpos, average.chanpos, cfg.warp); norm.label = elec.label; dpre = mean(sqrt(sum((average.chanpos - elec.chanpos).^2, 2))); dpost = mean(sqrt(sum((average.chanpos - norm.chanpos).^2, 2))); fprintf('mean distance prior to warping %f, after warping %f\n', dpre, dpost); if strcmp(cfg.feedback, 'yes') % plot all electrodes before warping ft_plot_sens(elec, 'r*'); % plot all electrodes after warping ft_plot_sens(norm, 'm.', 'label', 'label'); % plot the template electrode locations ft_plot_sens(average, 'b.'); % plot lines connecting the input and the realigned electrode locations with the template locations my_line3(elec.chanpos, average.chanpos, 'color', 'r'); my_line3(norm.chanpos, average.chanpos, 'color', 'm'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(cfg.method, 'headshape') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % determine electrode selection and overlapping subset for warping cfg.channel = ft_channelselection(cfg.channel, elec.label); % make subselection of electrodes [cfgsel, datsel] = match_str(cfg.channel, elec.label); elec.label = elec.label(datsel); elec.chanpos = elec.chanpos(datsel,:); fprintf('warping electrodes to skin surface... '); % the newline comes later [norm.chanpos, norm.m] = ft_warp_optim(elec.chanpos, headshape, cfg.warp); norm.label = elec.label; dpre = ft_warp_error([], elec.chanpos, headshape, cfg.warp); dpost = ft_warp_error(norm.m, elec.chanpos, headshape, cfg.warp); fprintf('mean distance prior to warping %f, after warping %f\n', dpre, dpost); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(cfg.method, 'fiducial') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the fiducials have to be present in the electrodes and in the template set label = intersect(lower(elec.label), lower(template.label)); if ~isfield(cfg, 'fiducial') || isempty(cfg.fiducial) % try to determine the names of the fiducials automatically option1 = {'nasion' 'left' 'right'}; option2 = {'nasion' 'lpa' 'rpa'}; option3 = {'nz' 'left' 'right'}; option4 = {'nz' 'lpa' 'rpa'}; option5 = {'nas' 'left' 'right'}; option6 = {'nas' 'lpa' 'rpa'}; if length(match_str(label, option1))==3 cfg.fiducial = option1; elseif length(match_str(label, option2))==3 cfg.fiducial = option2; elseif length(match_str(label, option3))==3 cfg.fiducial = option3; elseif length(match_str(label, option4))==3 cfg.fiducial = option4; elseif length(match_str(label, option5))==3 cfg.fiducial = option5; elseif length(match_str(label, option6))==3 cfg.fiducial = option6; else error('could not determine consistent fiducials in the input and the target, please specify cfg.fiducial or cfg.coordsys') end end fprintf('matching fiducials {''%s'', ''%s'', ''%s''}\n', cfg.fiducial{1}, cfg.fiducial{2}, cfg.fiducial{3}); % determine electrode selection cfg.channel = ft_channelselection(cfg.channel, elec.label); [cfgsel, datsel] = match_str(cfg.channel, elec.label); elec.label = elec.label(datsel); elec.chanpos = elec.chanpos(datsel,:); if length(cfg.fiducial)~=3 error('you must specify three fiducials'); end % do case-insensitive search for fiducial locations nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1})); lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2})); rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3})); if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1 error('not all fiducials were found in the electrode set'); end elec_nas = elec.chanpos(nas_indx,:); elec_lpa = elec.chanpos(lpa_indx,:); elec_rpa = elec.chanpos(rpa_indx,:); % FIXME change the flow in the remainder % if one or more template electrode sets are specified, then align to the average of those % if no template is specified, then align so that the fiducials are along the axis % find the matching fiducials in the template and average them templ_nas = nan(Ntemplate,3); templ_lpa = nan(Ntemplate,3); templ_rpa = nan(Ntemplate,3); for i=1:Ntemplate nas_indx = match_str(lower(template(i).label), lower(cfg.fiducial{1})); lpa_indx = match_str(lower(template(i).label), lower(cfg.fiducial{2})); rpa_indx = match_str(lower(template(i).label), lower(cfg.fiducial{3})); if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1 error(sprintf('not all fiducials were found in template %d', i)); end templ_nas(i,:) = template(i).pos(nas_indx,:); templ_lpa(i,:) = template(i).pos(lpa_indx,:); templ_rpa(i,:) = template(i).pos(rpa_indx,:); end templ_nas = mean(templ_nas,1); templ_lpa = mean(templ_lpa,1); templ_rpa = mean(templ_rpa,1); % realign both to a common coordinate system elec2common = ft_headcoordinates(elec_nas, elec_lpa, elec_rpa); templ2common = ft_headcoordinates(templ_nas, templ_lpa, templ_rpa); % compute the combined transform and realign the electrodes to the template norm = []; norm.m = elec2common * inv(templ2common); norm.chanpos = ft_warp_apply(norm.m, elec.chanpos, 'homogeneous'); norm.label = elec.label; nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1})); lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2})); rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3})); dpre = mean(sqrt(sum((elec.chanpos([nas_indx lpa_indx rpa_indx],:) - [templ_nas; templ_lpa; templ_rpa]).^2, 2))); nas_indx = match_str(lower(norm.label), lower(cfg.fiducial{1})); lpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{2})); rpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{3})); dpost = mean(sqrt(sum((norm.chanpos([nas_indx lpa_indx rpa_indx],:) - [templ_nas; templ_lpa; templ_rpa]).^2, 2))); fprintf('mean distance between fiducials prior to realignment %f, after realignment %f\n', dpre, dpost); if strcmp(cfg.feedback, 'yes') % plot the first three electrodes before transformation my_plot3(elec.chanpos(1,:), 'r*'); my_plot3(elec.chanpos(2,:), 'r*'); my_plot3(elec.chanpos(3,:), 'r*'); my_text3(elec.chanpos(1,:), elec.label{1}, 'color', 'r'); my_text3(elec.chanpos(2,:), elec.label{2}, 'color', 'r'); my_text3(elec.chanpos(3,:), elec.label{3}, 'color', 'r'); % plot the template fiducials my_plot3(templ_nas, 'b*'); my_plot3(templ_lpa, 'b*'); my_plot3(templ_rpa, 'b*'); my_text3(templ_nas, ' nas', 'color', 'b'); my_text3(templ_lpa, ' lpa', 'color', 'b'); my_text3(templ_rpa, ' rpa', 'color', 'b'); % plot all electrodes after transformation my_plot3(norm.chanpos, 'm.'); my_plot3(norm.chanpos(1,:), 'm*'); my_plot3(norm.chanpos(2,:), 'm*'); my_plot3(norm.chanpos(3,:), 'm*'); my_text3(norm.chanpos(1,:), norm.label{1}, 'color', 'm'); my_text3(norm.chanpos(2,:), norm.label{2}, 'color', 'm'); my_text3(norm.chanpos(3,:), norm.label{3}, 'color', 'm'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(cfg.method, 'interactive') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % give the user instructions disp('Use the mouse to rotate the head and the electrodes around, and click "redisplay"'); disp('Close the figure when you are done'); % open a figure fig = figure; % add the data to the figure set(fig, 'CloseRequestFcn', @cb_close); setappdata(fig, 'elec', elec); setappdata(fig, 'transform', eye(4)); if useheadshape setappdata(fig, 'headshape', headshape); end if usetemplate % FIXME interactive realigning to template electrodes is not yet supported % this requires a consistent handling of channel selection etc. setappdata(fig, 'template', template); end % add the GUI elements cb_creategui(gca); cb_redraw(gca); rotate3d on waitfor(fig); % get the data from the figure that was left behind as global variable tmp = norm; clear global norm norm = tmp; clear tmp %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(cfg.method, 'manual') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % give the user instructions disp('Use the mouse to click on the desired electrode positions'); disp('Afterwards you manually have to assign the electrode names to "elec.label"'); disp('Close the figure or press "q" when you are done'); % open a figure figure; % plot the faces of the 2D or 3D triangulation skin = [255 213 119]/255; ft_plot_mesh(headshape,'facecolor', skin,'EdgeColor','none','facealpha',0.7); lighting gouraud material shiny camlight % rotate3d on xyz = ft_select_point3d(headshape, 'multiple', true); norm.chanpos = xyz; for i=1:size(norm.chanpos,1) norm.label{i,1} = sprintf('%d', i); end else error('unknown method'); end % apply the spatial transformation to all electrodes, and replace the % electrode labels by their case-sensitive original values switch cfg.method case {'template', 'headshape'} try % convert the vector with fitted parameters into a 4x4 homogenous transformation % apply the transformation to the original complete set of sensors elec_realigned = ft_transform_sens(feval(cfg.warp, norm.m), elec_original); catch % the previous section will fail for nonlinear transformations elec_realigned.label = elec_original.label; elec_realigned.chanpos = ft_warp_apply(norm.m, elec_original.chanpos, cfg.warp); end % remember the transformation elec_realigned.(cfg.warp) = norm.m; case {'fiducial', 'interactive'} % the transformation is a 4x4 homogenous matrix homogenous = norm.m; % apply the transformation to the original complete set of sensors elec_realigned = ft_transform_sens(homogenous, elec_original); % remember the transformation elec_realigned.homogenous = norm.m; case 'manual' % the positions are already assigned in correspondence with the mesh elec_realigned = norm; otherwise error('unknown method'); end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous elec_original ft_postamble provenance elec_realigned ft_postamble history elec_realigned %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % some simple SUBFUNCTIONs that facilitate 3D plotting %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = my_plot3(xyz, varargin) h = plot3(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:}); function h = my_text3(xyz, varargin) h = text(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:}); function my_line3(xyzB, xyzE, varargin) for i=1:size(xyzB,1) line([xyzB(i,1) xyzE(i,1)], [xyzB(i,2) xyzE(i,2)], [xyzB(i,3) xyzE(i,3)], varargin{:}) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_creategui(hObject, eventdata, handles) % % define the position of each GUI element fig = get(hObject, 'parent'); % constants CONTROL_WIDTH = 0.05; CONTROL_HEIGHT = 0.06; CONTROL_HOFFSET = 0.7; CONTROL_VOFFSET = 0.5; % rotateui uicontrol('tag', 'rotateui', 'parent', fig, 'units', 'normalized', 'style', 'text', 'string', 'rotate', 'callback', []) uicontrol('tag', 'rx', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) uicontrol('tag', 'ry', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) uicontrol('tag', 'rz', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) ft_uilayout(fig, 'tag', 'rotateui', 'BackgroundColor', [0.8 0.8 0.8], 'width', 2*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET, 'vpos', CONTROL_VOFFSET); ft_uilayout(fig, 'tag', 'rx', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+3*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET); ft_uilayout(fig, 'tag', 'ry', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+4*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET); ft_uilayout(fig, 'tag', 'rz', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+5*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET); % scaleui uicontrol('tag', 'scaleui', 'parent', fig, 'units', 'normalized', 'style', 'text', 'string', 'scale', 'callback', []) uicontrol('tag', 'sx', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '1', 'callback', @cb_redraw) uicontrol('tag', 'sy', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '1', 'callback', @cb_redraw) uicontrol('tag', 'sz', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '1', 'callback', @cb_redraw) ft_uilayout(fig, 'tag', 'scaleui', 'BackgroundColor', [0.8 0.8 0.8], 'width', 2*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET, 'vpos', CONTROL_VOFFSET-CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'sx', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+3*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'sy', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+4*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'sz', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+5*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-CONTROL_HEIGHT); % translateui uicontrol('tag', 'translateui', 'parent', fig, 'units', 'normalized', 'style', 'text', 'string', 'translate', 'callback', []) uicontrol('tag', 'tx', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) uicontrol('tag', 'ty', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) uicontrol('tag', 'tz', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) ft_uilayout(fig, 'tag', 'translateui', 'BackgroundColor', [0.8 0.8 0.8], 'width', 2*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET, 'vpos', CONTROL_VOFFSET-2*CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'tx', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+3*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-2*CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'ty', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+4*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-2*CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'tz', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+5*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-2*CONTROL_HEIGHT); % control buttons uicontrol('tag', 'redisplaybtn', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'redisplay', 'value', [], 'callback', @cb_redraw); uicontrol('tag', 'applybtn', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'apply', 'value', [], 'callback', @cb_apply); uicontrol('tag', 'toggle labels', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'toggle label', 'value', 0, 'callback', @cb_redraw); uicontrol('tag', 'toggle axes', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'toggle axes', 'value', 0, 'callback', @cb_redraw); ft_uilayout(fig, 'tag', 'redisplaybtn', 'BackgroundColor', [0.8 0.8 0.8], 'width', 6*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-3*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); ft_uilayout(fig, 'tag', 'applybtn', 'BackgroundColor', [0.8 0.8 0.8], 'width', 6*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-4*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); ft_uilayout(fig, 'tag', 'toggle labels', 'BackgroundColor', [0.8 0.8 0.8], 'width', 6*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-5*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); ft_uilayout(fig, 'tag', 'toggle axes', 'BackgroundColor', [0.8 0.8 0.8], 'width', 6*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-6*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); % alpha ui (somehow not implemented, facealpha is fixed at 0.7 uicontrol('tag', 'alphaui', 'parent', fig, 'units', 'normalized', 'style', 'text', 'string', 'alpha', 'value', [], 'callback', []); uicontrol('tag', 'alpha', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0.7', 'value', [], 'callback', @cb_redraw); ft_uilayout(fig, 'tag', 'alphaui', 'BackgroundColor', [0.8 0.8 0.8], 'width', 3*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-7*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); ft_uilayout(fig, 'tag', 'alpha', 'BackgroundColor', [0.8 0.8 0.8], 'width', 3*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-7*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+3*CONTROL_WIDTH); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_redraw(hObject, eventdata, handles) fig = get(hObject, 'parent'); headshape = getappdata(fig, 'headshape'); elec = getappdata(fig, 'elec'); template = getappdata(fig, 'template'); % get the transformation details rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string')); ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string')); rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string')); tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string')); ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string')); tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string')); sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string')); sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string')); sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string')); R = rotate ([rx ry rz]); T = translate([tx ty tz]); S = scale ([sx sy sz]); H = S * T * R; elec = ft_transform_sens(H, elec); axis vis3d; cla xlabel('x') ylabel('y') zlabel('z') if ~isempty(template) disp('Plotting the template electrodes in blue'); if size(template.chanpos, 2)==2 hs = plot(template.chanpos(:,1), template.chanpos(:,2), 'b.', 'MarkerSize', 20); else hs = plot3(template.chanpos(:,1), template.chanpos(:,2), template.chanpos(:,3), 'b.', 'MarkerSize', 20); end end if ~isempty(headshape) % plot the faces of the 2D or 3D triangulation skin = [255 213 119]/255; ft_plot_mesh(headshape,'facecolor', skin,'EdgeColor','none','facealpha',0.7); lighting gouraud material shiny camlight end if isfield(elec, 'fid') && ~isempty(elec.fid.pos) disp('Plotting the fiducials in red'); ft_plot_sens(elec.fid,'style', 'r*'); end if get(findobj(fig, 'tag', 'toggle axes'), 'value') axis on grid on else axis off grid on end hold on if get(findobj(fig, 'tag', 'toggle labels'), 'value') ft_plot_sens(elec,'label', 'on'); else ft_plot_sens(elec,'label', 'off'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_apply(hObject, eventdata, handles) fig = get(hObject, 'parent'); elec = getappdata(fig, 'elec'); transform = getappdata(fig, 'transform'); % get the transformation details rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string')); ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string')); rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string')); tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string')); ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string')); tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string')); sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string')); sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string')); sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string')); R = rotate ([rx ry rz]); T = translate([tx ty tz]); S = scale ([sx sy sz]); H = S * T * R; elec = ft_transform_headshape(H, elec); transform = H * transform; set(findobj(fig, 'tag', 'rx'), 'string', 0); set(findobj(fig, 'tag', 'ry'), 'string', 0); set(findobj(fig, 'tag', 'rz'), 'string', 0); set(findobj(fig, 'tag', 'tx'), 'string', 0); set(findobj(fig, 'tag', 'ty'), 'string', 0); set(findobj(fig, 'tag', 'tz'), 'string', 0); set(findobj(fig, 'tag', 'sx'), 'string', 1); set(findobj(fig, 'tag', 'sy'), 'string', 1); set(findobj(fig, 'tag', 'sz'), 'string', 1); setappdata(fig, 'elec', elec); setappdata(fig, 'transform', transform); cb_redraw(hObject); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_close(hObject, eventdata, handles) % make the current transformation permanent and subsequently allow deleting the figure cb_apply(gca); % get the updated electrode from the figure fig = hObject; % hmmm, this is ugly global norm norm = getappdata(fig, 'elec'); norm.m = getappdata(fig, 'transform'); set(fig, 'CloseRequestFcn', @delete); delete(fig);
github
lcnbeapp/beapp-master
ft_databrowser.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_databrowser.m
95,614
utf_8
24d0f781128b15ffc93ac40b8f45feff
function [cfg] = ft_databrowser(cfg, data) % FT_DATABROWSER can be used for visual inspection of data. Artifacts that were % detected by artifact functions (see FT_ARTIFACT_xxx functions where xxx is the type % of artifact) are marked. Additionally data pieces can be marked and unmarked as % artifact by manual selection. The output cfg contains the updated specification of % the artifacts. % % Use as % cfg = ft_databrowser(cfg) % cfg = ft_databrowser(cfg, data) % If you only specify the configuration structure, it should contain the name of the % dataset on your hard disk (see below). If you specify input data, it should be a % data structure as obtained from FT_PREPROCESSING or from FT_COMPONENTANALYSIS. % % If you want to browse data that is on disk, you have to specify % cfg.dataset = string with the filename % Instead of specifying the dataset, you can also explicitely specify the name of the % file containing the header information and the name of the file containing the % data, using % cfg.datafile = string with the filename % cfg.headerfile = string with the filename % % The following configuration options are supported: % cfg.ylim = vertical scaling, can be 'maxmin', 'maxabs' or [ymin ymax] (default = 'maxabs') % cfg.zlim = color scaling to apply to component topographies, 'minmax', 'maxabs' (default = 'maxmin') % cfg.blocksize = duration in seconds for cutting the data up % cfg.trl = structure that defines the data segments of interest, only applicable for trial-based data % cfg.continuous = 'yes' or 'no' whether the data should be interpreted as continuous or trial-based % cfg.channel = cell-array with channel labels, see FT_CHANNELSELECTION % cfg.plotlabels = 'yes' (default), 'no', 'some'; whether to plot channel labels in vertical % viewmode ('some' plots one in every ten labels; useful when plotting a % large number of channels at a time) % cfg.ploteventlabels = 'type=value', 'colorvalue' (default = 'type=value'); % cfg.plotevents = 'no' or 'yes', whether to plot event markers. (default is 'yes') % cfg.viewmode = string, 'butterfly', 'vertical', 'component' for visualizing components e.g. from an ICA (default is 'butterfly') % cfg.artfctdef.xxx.artifact = Nx2 matrix with artifact segments see FT_ARTIFACT_xxx functions % cfg.selectfeature = string, name of feature to be selected/added (default = 'visual') % cfg.selectmode = 'markartifact', 'markpeakevent', 'marktroughevent' (default = 'markartifact') % cfg.colorgroups = 'sequential' 'allblack' 'labelcharx' (x = xth character in label), 'chantype' or % vector with length(data/hdr.label) defining groups (default = 'sequential') % cfg.channelcolormap = COLORMAP (default = customized lines map with 15 colors) % cfg.verticalpadding = number or 'auto', padding to be added to top and bottom of plot to avoid channels largely dissappearing when viewmode = 'vertical'/'component' (default = 'auto') % padding is expressed as a proportion of the total height added to the top, and bottom) ('auto' adds padding depending on the number of channels being plotted) % cfg.selfun = string, name of function which is evaluated using the right-click context menu % The selected data and cfg.selcfg are passed on to this function. % cfg.selcfg = configuration options for function in cfg.selfun % cfg.seldat = 'selected' or 'all', specifies whether only the currently selected or all channels % will be passed to the selfun (default = 'selected') % cfg.renderer = string, 'opengl', 'zbuffer', 'painters', see MATLAB Figure Properties. % If the databrowser crashes, set to 'painters'. % % The following options for the scaling of the EEG, EOG, ECG, EMG and MEG channels is % optional and can be used to bring the absolute numbers of the different channel % types in the same range (e.g. fT and uV). The channel types are determined from the % input data using FT_CHANNELSELECTION. % cfg.eegscale = number, scaling to apply to the EEG channels prior to display % cfg.eogscale = number, scaling to apply to the EOG channels prior to display % cfg.ecgscale = number, scaling to apply to the ECG channels prior to display % cfg.emgscale = number, scaling to apply to the EMG channels prior to display % cfg.megscale = number, scaling to apply to the MEG channels prior to display % cfg.gradscale = number, scaling to apply to the MEG gradiometer channels prior to display (in addition to the cfg.megscale factor) % cfg.magscale = number, scaling to apply to the MEG magnetometer channels prior to display (in addition to the cfg.megscale factor) % cfg.mychanscale = number, scaling to apply to the channels specified in cfg.mychan % cfg.mychan = Nx1 cell-array with selection of channels % cfg.chanscale = Nx1 vector with scaling factors, one per channel specified in cfg.channel % cfg.compscale = string, 'global' or 'local', defines whether the colormap for the topographic scaling is % applied per topography or on all visualized components (default 'global') % % You can specify preprocessing options that are to be applied to the data prior to % display. Most options from FT_PREPROCESSING are supported. They should be specified % in the sub-structure cfg.preproc like these examples % cfg.preproc.lpfilter = 'no' or 'yes' lowpass filter (default = 'no') % cfg.preproc.lpfreq = lowpass frequency in Hz % cfg.preproc.demean = 'no' or 'yes', whether to apply baseline correction (default = 'no') % cfg.preproc.detrend = 'no' or 'yes', remove linear trend from the data (done per trial) (default = 'no') % cfg.preproc.baselinewindow = [begin end] in seconds, the default is the complete trial (default = 'all') % % In case of component viewmode, a layout is required. If no layout is specified, an % attempt is made to construct one from the sensor definition that is present in the % data or specified in the configuration. % cfg.layout = filename of the layout, see FT_PREPARE_LAYOUT % cfg.elec = structure with electrode positions, see FT_DATATYPE_SENS % cfg.grad = structure with gradiometer definition, see FT_DATATYPE_SENS % cfg.elecfile = name of file containing the electrode positions, see FT_READ_SENS % cfg.gradfile = name of file containing the gradiometer definition, see FT_READ_SENS % % The default font size might be too small or too large, depending on the number of % channels. You can use the following options to change the size of text inside the % figure and along the axes. % cfg.fontsize = number, fontsize inside the figure (default = 0.03) % cfg.fontunits = string, can be 'normalized', 'points', 'pixels', 'inches' or 'centimeters' (default = 'normalized') % cfg.axisfontsize = number, fontsize along the axes (default = 10) % cfg.axisfontunits = string, can be 'normalized', 'points', 'pixels', 'inches' or 'centimeters' (default = 'points') % cfg.linewidth = number, width of plotted lines (default = 0.5) % % When visually selection data, a right-click will bring up a context-menu containing % functions to be executed on the selected data. You can use your own function using % cfg.selfun and cfg.selcfg. You can use multiple functions by giving the names/cfgs % as a cell-array. % % In butterfly and vertical mode, you can use the "identify" button to reveal the name of a % channel. Please be aware that it searches only vertically. This means that it will % return the channel with the amplitude closest to the point you have clicked at the % specific time point. This might be counterintuitive at first. % % The "cfg.artifact" field in the output cfg is a Nx2 matrix comparable to the % "cfg.trl" matrix of FT_DEFINETRIAL. The first column of which specifying the % beginsamples of an artifact period, the second column contains the endsamples of % the artifactperiods. % % Note for debugging: in case the databrowser crashes, use delete(gcf) to kill the % figure. % % See also FT_PREPROCESSING, FT_REJECTARTIFACT, FT_ARTIFACT_EOG, FT_ARTIFACT_MUSCLE, % FT_ARTIFACT_JUMP, FT_ARTIFACT_MANUAL, FT_ARTIFACT_THRESHOLD, FT_ARTIFACT_CLIP, % FT_ARTIFACT_ECG, FT_COMPONENTANALYSIS % Copyright (C) 2009-2015, Robert Oostenveld, Ingrid Nieuwenhuis % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % FIXME these should be removed or documented % cfg.preproc % cfg.channelcolormap % cfg.colorgroups % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar data ft_preamble provenance data ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % the data can be passed as input arguments or can be read from disk hasdata = exist('data', 'var'); hascomp = hasdata && ft_datatype(data, 'comp'); % can be 'raw+comp' or 'timelock+comp' % for backward compatibility cfg = ft_checkconfig(cfg, 'unused', {'comps', 'inputfile', 'outputfile'}); cfg = ft_checkconfig(cfg, 'renamed', {'zscale', 'ylim'}); cfg = ft_checkconfig(cfg, 'renamedval', {'ylim', 'auto', 'maxabs'}); cfg = ft_checkconfig(cfg, 'renamedval', {'selectmode', 'mark', 'markartifact'}); % ensure that the preproc specific options are located in the cfg.preproc substructure cfg = ft_checkconfig(cfg, 'createsubcfg', {'preproc'}); % set the defaults cfg.ylim = ft_getopt(cfg, 'ylim', 'maxabs'); cfg.artfctdef = ft_getopt(cfg, 'artfctdef', struct); cfg.selectfeature = ft_getopt(cfg, 'selectfeature','visual'); % string or cell-array cfg.selectmode = ft_getopt(cfg, 'selectmode', 'markartifact'); cfg.blocksize = ft_getopt(cfg, 'blocksize'); % now used for both continuous and non-continuous data, defaulting done below cfg.preproc = ft_getopt(cfg, 'preproc'); % see preproc for options cfg.selfun = ft_getopt(cfg, 'selfun'); % default functions: 'simpleFFT', 'multiplotER', 'topoplotER', 'topoplotVAR', 'movieplotER' cfg.selcfg = ft_getopt(cfg, 'selcfg'); % defaulting done below, requires layouts/etc to be processed cfg.seldat = ft_getopt(cfg, 'seldat', 'current'); cfg.colorgroups = ft_getopt(cfg, 'colorgroups', 'sequential'); cfg.channelcolormap = ft_getopt(cfg, 'channelcolormap', [0.75 0 0;0 0 1;0 1 0;0.44 0.19 0.63;0 0.13 0.38;0.5 0.5 0.5;1 0.75 0;1 0 0;0.89 0.42 0.04;0.85 0.59 0.58;0.57 0.82 0.31;0 0.69 0.94;1 0 0.4;0 0.69 0.31;0 0.44 0.75]); cfg.eegscale = ft_getopt(cfg, 'eegscale'); cfg.eogscale = ft_getopt(cfg, 'eogscale'); cfg.ecgscale = ft_getopt(cfg, 'ecgscale'); cfg.emgscale = ft_getopt(cfg, 'emgscale'); cfg.megscale = ft_getopt(cfg, 'megscale'); cfg.magscale = ft_getopt(cfg, 'magscale'); cfg.gradscale = ft_getopt(cfg, 'gradscale'); cfg.chanscale = ft_getopt(cfg, 'chanscale'); cfg.mychanscale = ft_getopt(cfg, 'mychanscale'); cfg.layout = ft_getopt(cfg, 'layout'); cfg.plotlabels = ft_getopt(cfg, 'plotlabels', 'some'); cfg.event = ft_getopt(cfg, 'event'); % this only exists for backward compatibility and should not be documented cfg.continuous = ft_getopt(cfg, 'continuous'); % the default is set further down in the code, conditional on the input data cfg.ploteventlabels = ft_getopt(cfg, 'ploteventlabels', 'type=value'); cfg.plotevents = ft_getopt(cfg, 'plotevents', 'yes'); cfg.precision = ft_getopt(cfg, 'precision', 'double'); cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin'); cfg.compscale = ft_getopt(cfg, 'compscale', 'global'); cfg.renderer = ft_getopt(cfg, 'renderer'); cfg.fontsize = ft_getopt(cfg, 'fontsize', 12); cfg.fontunits = ft_getopt(cfg, 'fontunits', 'points'); % inches, centimeters, normalized, points, pixels cfg.editfontsize = ft_getopt(cfg, 'editfontsize', 12); cfg.editfontunits = ft_getopt(cfg, 'editfontunits', 'points'); % inches, centimeters, normalized, points, pixels cfg.axisfontsize = ft_getopt(cfg, 'axisfontsize', 10); cfg.axisfontunits = ft_getopt(cfg, 'axisfontunits', 'points'); % inches, centimeters, normalized, points, pixels cfg.linewidth = ft_getopt(cfg, 'linewidth', 0.5); cfg.verticalpadding = ft_getopt(cfg, 'verticalpadding', 'auto'); if ~isfield(cfg, 'viewmode') % butterfly, vertical, component if hascomp cfg.viewmode = 'component'; else cfg.viewmode = 'butterfly'; end end if ~isempty(cfg.chanscale) if ~isfield(cfg, 'channel') warning('ignoring cfg.chanscale; this should only be used when an explicit channel selection is being made'); cfg.chanscale = []; elseif numel(cfg.channel) ~= numel(cfg.chanscale) error('cfg.chanscale should have the same number of elements as cfg.channel'); end % make sure chanscale is a column vector, not a row vector if size(cfg.chanscale,2) > size(cfg.chanscale,1) cfg.chanscale = cfg.chanscale'; end end if ~isempty(cfg.mychanscale) && ~isfield(cfg, 'mychan') warning('ignoring cfg.mychanscale; no channels specified in cfg.mychan'); cfg.mychanscale = []; end if ~isfield(cfg, 'channel'), if hascomp if size(data.topo,2)>9 cfg.channel = 1:10; else cfg.channel = 1:size(data.topo,2); end else cfg.channel = 'all'; end end if strcmp(cfg.viewmode, 'component') % read or create the layout that will be used for the topoplots if ~isempty(cfg.layout) tmpcfg = []; tmpcfg.layout = cfg.layout; cfg.layout = ft_prepare_layout(tmpcfg); else warning('No layout specified - will try to construct one using sensor positions'); tmpcfg = []; try, tmpcfg.elec = cfg.elec; end try, tmpcfg.grad = cfg.grad; end try, tmpcfg.elecfile = cfg.elecfile; end try, tmpcfg.gradfile = cfg.gradfile; end if hasdata cfg.layout = ft_prepare_layout(tmpcfg, data); else cfg.layout = ft_prepare_layout(tmpcfg); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % set the defaults and do some preparation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if hasdata % save whether data came from a timelock structure istimelock = strcmp(ft_datatype(data), 'timelock'); % check if the input data is valid for this function data = ft_checkdata(data, 'datatype', {'raw+comp', 'raw'}, 'feedback', 'yes', 'hassampleinfo', 'yes'); % fetch the header from the data structure in memory hdr = ft_fetch_header(data); if isfield(data, 'cfg') && ~isempty(ft_findcfg(data.cfg, 'origfs')) % don't use the events in case the data has been resampled warning('the data has been resampled, not showing the events'); event = []; elseif isfield(data, 'cfg') && isfield(data.cfg, 'event') % use the event structure from the data as per bug #2501 event = data.cfg.event; elseif ~isempty(cfg.event) % use the events that the user passed in the configuration event = cfg.event; else % fetch the events from the data structure in memory %event = ft_fetch_event(data); event = []; end cfg.channel = ft_channelselection(cfg.channel, hdr.label); chansel = match_str(data.label, cfg.channel); Nchans = length(chansel); if isempty(cfg.continuous) if numel(data.trial) == 1 && ~istimelock cfg.continuous = 'yes'; else cfg.continuous = 'no'; end else if strcmp(cfg.continuous, 'yes') && (numel(data.trial) > 1) warning('interpreting trial-based data as continous, time-axis is no longer appropriate. t(0) now corresponds to the first sample of the first trial, and t(end) to the last sample of the last trial') end end % this is how the input data is segmented trlorg = zeros(numel(data.trial), 3); trlorg(:, [1 2]) = data.sampleinfo; % recreate offset vector (databrowser depends on this for visualisation) for ntrl = 1:numel(data.trial) trlorg(ntrl,3) = time2offset(data.time{ntrl}, data.fsample); end Ntrials = size(trlorg, 1); else % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'dataset2files', 'yes'); cfg = ft_checkconfig(cfg, 'required', {'headerfile', 'datafile'}); cfg = ft_checkconfig(cfg, 'renamed', {'datatype', 'continuous'}); cfg = ft_checkconfig(cfg, 'renamedval', {'continuous', 'continuous', 'yes'}); % read the header from file hdr = ft_read_header(cfg.headerfile, 'headerformat', cfg.headerformat); if isempty(cfg.continuous) if hdr.nTrials==1 cfg.continuous = 'yes'; else cfg.continuous = 'no'; end end if ~isempty(cfg.event) % use the events that the user passed in the configuration event = cfg.event; else % read the events from file event = ft_read_event(cfg.dataset); end cfg.channel = ft_channelselection(cfg.channel, hdr.label); chansel = match_str(hdr.label, cfg.channel); Nchans = length(chansel); if strcmp(cfg.continuous, 'yes') Ntrials = 1; else Ntrials = hdr.nTrials; end % FIXME in case of continuous=yes the trl should be [1 hdr.nSamples*nTrials 0] % and a scrollbar should be used % construct trl-matrix for data from file on disk trlorg = zeros(Ntrials,3); if strcmp(cfg.continuous, 'yes') trlorg(1, [1 2]) = [1 hdr.nSamples*hdr.nTrials]; else for k = 1:Ntrials trlorg(k, [1 2]) = [1 hdr.nSamples] + [hdr.nSamples hdr.nSamples] .* (k-1); end end end % if hasdata if strcmp(cfg.continuous, 'no') && isempty(cfg.blocksize) cfg.blocksize = (trlorg(1,2) - trlorg(1,1)+1) ./ hdr.Fs; elseif strcmp(cfg.continuous, 'yes') && isempty(cfg.blocksize) cfg.blocksize = 1; end % FIXME make a check for the consistency of cfg.continous, cfg.blocksize, cfg.trl and the data header if Nchans == 0 error('no channels to display'); end if Ntrials == 0 error('no trials to display'); end if ischar(cfg.selectfeature) % ensure that it is a cell array cfg.selectfeature = {cfg.selectfeature}; end if ~isempty(cfg.selectfeature) for i=1:length(cfg.selectfeature) if ~isfield(cfg.artfctdef, cfg.selectfeature{i}) cfg.artfctdef.(cfg.selectfeature{i}) = []; cfg.artfctdef.(cfg.selectfeature{i}).artifact = zeros(0,2); end end end % determine the vertical scaling if ischar(cfg.ylim) if hasdata % the first trial is used to determine the vertical scaling dat = data.trial{1}(chansel,:); else % one second of data is read from file to determine the vertical scaling dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', 1, 'endsample', round(hdr.Fs), 'chanindx', chansel, 'checkboundary', strcmp(cfg.continuous, 'no'), 'dataformat', cfg.dataformat, 'headerformat', cfg.headerformat); end % if hasdata % convert the data to another numeric precision, i.e. double, single or int32 if ~isempty(cfg.precision) dat = cast(dat, cfg.precision); end minval = min(dat(:)); maxval = max(dat(:)); switch cfg.ylim case 'maxabs' maxabs = max(abs([minval maxval])); scalefac = 10^(fix(log10(maxabs))); if scalefac==0 % this happens if the data is all zeros scalefac=1; end maxabs = (round(maxabs / scalefac * 100) / 100) * scalefac; cfg.ylim = [-maxabs maxabs]; case 'maxmin' if minval==maxval % this happens if the data is constant, e.g. all zero or clipping minval = minval - eps; maxval = maxval + eps; end cfg.ylim = [minval maxval]; otherwise error('unsupported value for cfg.ylim'); end % switch ylim % zoom in a bit when viemode is vertical if strcmp(cfg.viewmode, 'vertical') cfg.ylim = cfg.ylim/10; end else if (numel(cfg.ylim) ~= 2) || ~isnumeric(cfg.ylim) error('cfg.ylim needs to be a 1x2 vector [ymin ymax], describing the upper and lower limits') end end % determine coloring of channels if hasdata labels_all = data.label; else labels_all= hdr.label; end if size(cfg.channelcolormap,2) ~= 3 error('cfg.channelcolormap is not valid, size should be Nx3') end if isnumeric(cfg.colorgroups) % groups defined by user if length(labels_all) ~= length(cfg.colorgroups) error('length(cfg.colorgroups) should be length(data/hdr.label)') end R = cfg.channelcolormap(:,1); G = cfg.channelcolormap(:,2); B = cfg.channelcolormap(:,3); chancolors = [R(cfg.colorgroups(:)) G(cfg.colorgroups(:)) B(cfg.colorgroups(:))]; elseif strcmp(cfg.colorgroups, 'allblack') chancolors = zeros(length(labels_all),3); elseif strcmp(cfg.colorgroups, 'chantype') type = ft_chantype(labels_all); [tmp1 tmp2 cfg.colorgroups] = unique(type); fprintf('%3d colorgroups were identified\n',length(tmp1)) R = cfg.channelcolormap(:,1); G = cfg.channelcolormap(:,2); B = cfg.channelcolormap(:,3); chancolors = [R(cfg.colorgroups(:)) G(cfg.colorgroups(:)) B(cfg.colorgroups(:))]; elseif strcmp(cfg.colorgroups(1:9), 'labelchar') % groups determined by xth letter of label labelchar_num = str2double(cfg.colorgroups(10)); vec_letters = num2str(zeros(length(labels_all),1)); for iChan = 1:length(labels_all) vec_letters(iChan) = labels_all{iChan}(labelchar_num); end [tmp1 tmp2 cfg.colorgroups] = unique(vec_letters); fprintf('%3d colorgroups were identified\n',length(tmp1)) R = cfg.channelcolormap(:,1); G = cfg.channelcolormap(:,2); B = cfg.channelcolormap(:,3); chancolors = [R(cfg.colorgroups(:)) G(cfg.colorgroups(:)) B(cfg.colorgroups(:))]; elseif strcmp(cfg.colorgroups, 'sequential') % no grouping chancolors = lines(length(labels_all)); else error('do not understand cfg.colorgroups') end % collect the artifacts that have been detected from cfg.artfctdef.xxx.artifact artlabel = fieldnames(cfg.artfctdef); sel = zeros(size(artlabel)); artifact = cell(size(artlabel)); for i=1:length(artlabel) sel(i) = isfield(cfg.artfctdef.(artlabel{i}), 'artifact'); if sel(i) artifact{i} = cfg.artfctdef.(artlabel{i}).artifact; fprintf('detected %3d %s artifacts\n', size(artifact{i}, 1), artlabel{i}); end end % get the subset of the artfctdef fields that seem to contain artifacts artifact = artifact(sel==1); artlabel = artlabel(sel==1); if length(artlabel) > 9 error('only up to 9 artifacts groups supported') end % make artdata representing all artifacts in a "raw data" format datendsample = max(trlorg(:,2)); artdata = []; artdata.trial{1} = convert_event(artifact, 'boolvec', 'endsample', datendsample); % every artifact is a "channel" artdata.time{1} = offset2time(0, hdr.Fs, datendsample); artdata.label = artlabel; artdata.fsample = hdr.Fs; artdata.cfg.trl = [1 datendsample 0]; % determine amount of unique event types (for cfg.ploteventlabels) if ~isempty(event) && isstruct(event) eventtypes = unique({event.type}); else eventtypes = []; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % set up default functions to be available in the right-click menu %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % cfg.selfun - labels that are presented in rightclick menu, and is appended using ft_getuserfun(..., 'browse') later on to create a function handle % cfg.selcfg - cfgs for functions to be executed defselfun = {}; defselcfg = {}; % add defselfuns to user-specified defselfuns if ~iscell(cfg.selfun) && ~isempty(cfg.selfun) cfg.selfun = {cfg.selfun}; cfg.selfun = [cfg.selfun defselfun]; % do the same for the cfgs cfg.selcfg = {cfg.selcfg}; % assume the cfg is not a cell-array cfg.selcfg = [cfg.selcfg defselcfg]; else % simplefft defselcfg{1} = []; defselcfg{1}.chancolors = chancolors; defselfun{1} = 'simpleFFT'; % multiplotER defselcfg{2} = []; defselcfg{2}.layout = cfg.layout; defselfun{2} = 'multiplotER'; % topoplotER defselcfg{3} = []; defselcfg{3}.layout = cfg.layout; defselfun{3} = 'topoplotER'; % topoplotVAR defselcfg{4} = []; defselcfg{4}.layout = cfg.layout; defselfun{4} = 'topoplotVAR'; % movieplotER defselcfg{5} = []; defselcfg{5}.layout = cfg.layout; defselcfg{5}.interactive = 'yes'; defselfun{5} = 'movieplotER'; % audiovideo defselcfg{6} = []; defselcfg{6}.audiofile = ft_getopt(cfg, 'audiofile'); defselcfg{6}.videofile = ft_getopt(cfg, 'videofile'); defselcfg{6}.anonimize = ft_getopt(cfg, 'anonimize'); defselfun{6} = 'audiovideo'; cfg.selfun = defselfun; cfg.selcfg = defselcfg; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % set up the data structures used in the GUI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % opt represents the global data/settings, it should contain % - the original data, epoched or continuous % - the artifacts represented as continuous data % - the redraw_cb settings % - the preproc settings % - the select_range_cb settings (also used in keyboard_cb) % these elements are stored inside the figure so that the callback routines can modify them opt = []; if hasdata opt.orgdata = data; else opt.orgdata = []; % this means that it will look in cfg.dataset end if strcmp(cfg.continuous, 'yes') opt.trialviewtype = 'segment'; else opt.trialviewtype = 'trial'; end opt.artdata = artdata; opt.hdr = hdr; opt.event = event; opt.trlop = 1; % the active trial being displayed opt.ftsel = find(strcmp(artlabel,cfg.selectfeature)); % current artifact/feature being selected opt.trlorg = trlorg; opt.fsample = hdr.Fs; opt.artcolors = [0.9686 0.7608 0.7686; 0.7529 0.7098 0.9647; 0.7373 0.9725 0.6824;0.8118 0.8118 0.8118; 0.9725 0.6745 0.4784; 0.9765 0.9176 0.5686; 0.6863 1 1; 1 0.6863 1; 0 1 0.6000]; opt.chancolors = chancolors; opt.cleanup = false; % this is needed for a corrent handling if the figure is closed (either in the corner or by "q") opt.chanindx = []; % this is used to check whether the component topographies need to be redrawn opt.eventtypes = eventtypes; opt.eventtypescolors = [0 0 0; 1 0 0; 0 0 1; 0 1 0; 1 0 1; 0.5 0.5 0.5; 0 1 1; 1 1 0]; opt.eventtypecolorlabels = {'black', 'red', 'blue', 'green', 'cyan', 'grey', 'light blue', 'yellow'}; opt.nanpaddata = []; % this is used to allow horizontal scaling to be constant (when looking at last segment continous data, or when looking at segmented/zoomed-out non-continous data) opt.trllock = []; % this is used when zooming into trial based data % save original layout when viewmode = component if strcmp(cfg.viewmode, 'component') opt.layorg = cfg.layout; end % determine labelling of channels if strcmp(cfg.plotlabels, 'yes') opt.plotLabelFlag = 1; elseif strcmp(cfg.plotlabels, 'some') opt.plotLabelFlag = 2; else opt.plotLabelFlag = 0; end % set changedchanflg as true for initialization opt.changedchanflg = true; % trigger for redrawing channel labels and preparing layout again (see bug 2065 and 2878) % create fig h = figure; % put appdata in figure setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); if ~isempty(cfg.renderer) set(h, 'renderer', cfg.renderer); end % set interruptible to off, see bug 3123 set(h,'Interruptible','off','BusyAction', 'queue'); % enforce busyaction to queue to be sure % enable custom data cursor text dcm = datacursormode(h); set(dcm, 'updatefcn', @datacursortext); % set the figure window title funcname = mfilename(); if ~hasdata if isfield(cfg, 'dataset') dataname = cfg.dataset; elseif isfield(cfg, 'datafile') dataname = cfg.datafile; else dataname = []; end elseif isfield(cfg, 'inputfile') && ~isempty(cfg.inputfile) dataname = cfg.inputfile; else dataname = inputname(2); end set(gcf, 'Name', sprintf('%d: %s: %s', double(gcf), funcname, join_str(', ',dataname))); set(gcf, 'NumberTitle', 'off'); % set zoom option to on % zoom(h, 'on') % set(zoom(h), 'actionPostCallback', @zoom_drawlabels_cb) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % set up the figure and callbacks %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% set(h, 'KeyPressFcn', @keyboard_cb); set(h, 'WindowButtonDownFcn', {@ft_select_range, 'multiple', false, 'xrange', true, 'yrange', false, 'clear', true, 'contextmenu', cfg.selfun, 'callback', {@select_range_cb, h}, 'event', 'WindowButtonDownFcn'}); set(h, 'WindowButtonUpFcn', {@ft_select_range, 'multiple', false, 'xrange', true, 'yrange', false, 'clear', true, 'contextmenu', cfg.selfun, 'callback', {@select_range_cb, h}, 'event', 'WindowButtonUpFcn'}); set(h, 'WindowButtonMotionFcn', {@ft_select_range, 'multiple', false, 'xrange', true, 'yrange', false, 'clear', true, 'contextmenu', cfg.selfun, 'callback', {@select_range_cb, h}, 'event', 'WindowButtonMotionFcn'}); if any(strcmp(cfg.viewmode, {'component', 'vertical'})) set(h, 'ReSizeFcn', @winresize_cb); % resize will now trigger redraw and replotting of labels end % make the user interface elements for the data view uicontrol('tag', 'labels', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', opt.trialviewtype, 'userdata', 't') uicontrol('tag', 'buttons', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'leftarrow') uicontrol('tag', 'buttons', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'rightarrow') if strcmp(cfg.viewmode, 'component') uicontrol('tag', 'labels', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'component', 'userdata', 'c') else uicontrol('tag', 'labels', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'channel', 'userdata', 'c') end uicontrol('tag', 'buttons', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'uparrow') uicontrol('tag', 'buttons', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'downarrow') uicontrol('tag', 'labels', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'horizontal', 'userdata', 'h') uicontrol('tag', 'buttons', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '-', 'userdata', 'shift+leftarrow') uicontrol('tag', 'buttons', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '+', 'userdata', 'shift+rightarrow') uicontrol('tag', 'labels', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'vertical', 'userdata', 'v') uicontrol('tag', 'buttons', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '-', 'userdata', 'shift+downarrow') uicontrol('tag', 'buttons', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '+', 'userdata', 'shift+uparrow') % legend artifacts/features for iArt = 1:length(artlabel) uicontrol('tag', 'artifactui', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', artlabel{iArt}, 'userdata', num2str(iArt), 'position', [0.91, 0.9 - ((iArt-1)*0.09), 0.08, 0.04], 'backgroundcolor', opt.artcolors(iArt,:)) uicontrol('tag', 'artifactui', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', ['shift+' num2str(iArt)], 'position', [0.91, 0.855 - ((iArt-1)*0.09), 0.03, 0.04], 'backgroundcolor', opt.artcolors(iArt,:)) uicontrol('tag', 'artifactui', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', ['control+' num2str(iArt)], 'position', [0.96, 0.855 - ((iArt-1)*0.09), 0.03, 0.04], 'backgroundcolor', opt.artcolors(iArt,:)) end if length(artlabel)>1 % highlight the first one as active arth = findobj(h,'tag','artifactui'); arth = arth(end:-1:1); % order is reversed so reverse it again hsel = [1 2 3] + (opt.ftsel-1) .*3; set(arth(hsel),'fontweight','bold') end if true % strcmp(cfg.viewmode, 'butterfly') % button to find label of nearest channel to datapoint uicontrol('tag', 'buttons', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'identify', 'userdata', 'i', 'position', [0.91, 0.1, 0.08, 0.05], 'backgroundcolor', [1 1 1]) end % 'edit preproc'-button uicontrol('tag', 'preproccfg', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'preproc cfg', 'position', [0.91, 0.55 - ((iArt-1)*0.09), 0.08, 0.04], 'callback', @preproc_cfg1_cb) ft_uilayout(h, 'tag', 'labels', 'width', 0.10, 'height', 0.05); ft_uilayout(h, 'tag', 'buttons', 'width', 0.05, 'height', 0.05); ft_uilayout(h, 'tag', 'labels', 'style', 'pushbutton', 'callback', @keyboard_cb); ft_uilayout(h, 'tag', 'buttons', 'style', 'pushbutton', 'callback', @keyboard_cb); ft_uilayout(h, 'tag', 'artifactui', 'style', 'pushbutton', 'callback', @keyboard_cb); ft_uilayout(h, 'tag', 'labels', 'retag', 'viewui'); ft_uilayout(h, 'tag', 'buttons', 'retag', 'viewui'); ft_uilayout(h, 'tag', 'viewui', 'BackgroundColor', [0.8 0.8 0.8], 'hpos', 'auto', 'vpos', 0); definetrial_cb(h); redraw_cb(h); % %% Scrollbar % % % set initial scrollbar value % dx = maxtime; % % % set scrollbar position % fig_pos=get(gca, 'position'); % scroll_pos=[fig_pos(1) fig_pos(2) fig_pos(3) 0.02]; % % % define callback % S=['set(gca, ''xlim'',get(gcbo, ''value'')+[ ' num2str(mintime) ', ' num2str(maxtime) '])']; % % % Creating Uicontrol % s=uicontrol('style', 'slider',... % 'units', 'normalized', 'position',scroll_pos,... % 'callback',S, 'min',0, 'max',0, ... % 'visible', 'off'); %'value', xmin % set initial scrollbar value % dx = maxtime; % % % set scrollbar position % fig_pos=get(gca, 'position'); % scroll_pos=[fig_pos(1) fig_pos(2) fig_pos(3) 0.02]; % % % define callback % S=['set(gca, ''xlim'',get(gcbo, ''value'')+[ ' num2str(mintime) ', ' num2str(maxtime) '])']; % % % Creating Uicontrol % s=uicontrol('style', 'slider',... % 'units', 'normalized', 'position',scroll_pos,... % 'callback',S, 'min',0, 'max',0, ... % 'visible', 'off'); %'value', xmin %initialize postion of plot % set(gca, 'xlim', [xmin xmin+dx]); if nargout % wait until the user interface is closed, get the user data with the updated artifact details set(h, 'CloseRequestFcn', @cleanup_cb); while ishandle(h) uiwait(h); opt = getappdata(h, 'opt'); if opt.cleanup delete(h); end end % add the updated artifact definitions to the output cfg for i=1:length(opt.artdata.label) cfg.artfctdef.(opt.artdata.label{i}).artifact = convert_event(opt.artdata.trial{1}(i,:), 'artifact'); end % add the updated preproc to the output try browsecfg = getappdata(h, 'cfg'); cfg.preproc = browsecfg.preproc; end % add the update event to the output cfg cfg.event = opt.event; % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous data ft_postamble provenance end % if nargout end % main function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cleanup_cb(h, eventdata) opt = getappdata(h, 'opt'); opt.cleanup = true; setappdata(h, 'opt', opt); uiresume end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function definetrial_cb(h, eventdata) opt = getappdata(h, 'opt'); cfg = getappdata(h, 'cfg'); if strcmp(cfg.continuous, 'no') % when zooming in, lock the trial! one can only go to the next trial when horizontal scaling doesn't segment the data - from ft-meeting: this might be relaxed later on - roevdmei if isempty(opt.trllock) opt.trllock = opt.trlop; end locktrllen = ((opt.trlorg(opt.trllock,2)-opt.trlorg(opt.trllock,1)+1) ./ opt.fsample); % if cfg.blocksize is close to the length of the locked trial, set it to that if (abs(locktrllen-cfg.blocksize) / locktrllen) < 0.1 cfg.blocksize = locktrllen; end %%%%%%%%% % trial is locked, change subdivision of trial if cfg.blocksize < locktrllen % lock the trial if it wasn't locked (and thus trlop refers to the actual trial) if isempty(opt.trllock) opt.trllock = trlop; end % save current position if already if isfield(opt, 'trlvis') thissegbeg = opt.trlvis(opt.trlop,1); end datbegsample = min(opt.trlorg(opt.trllock,1)); datendsample = max(opt.trlorg(opt.trllock,2)); smpperseg = round(opt.fsample * cfg.blocksize); begsamples = datbegsample:smpperseg:datendsample; endsamples = datbegsample+smpperseg-1:smpperseg:datendsample; offset = (((1:numel(begsamples))-1)*smpperseg) + opt.trlorg(opt.trllock,3); if numel(endsamples)<numel(begsamples) endsamples(end+1) = datendsample; end trlvis = []; trlvis(:,1) = begsamples'; trlvis(:,2) = endsamples'; trlvis(:,3) = offset; % determine length of each trial, and determine the offset with the current requested zoom-level trllen = (trlvis(:,2) - trlvis(:,1)+1); sizediff = smpperseg - trllen; opt.nanpaddata = sizediff; if isfield(opt, 'trlvis') % update the current trial counter and try to keep the current sample the same opt.trlop = nearest(begsamples, thissegbeg); end % update trialviewtype opt.trialviewtype = 'trialsegment'; % update button set(findobj(get(h, 'children'), 'string', 'trial'), 'string', 'segment'); %%%%%%%%% %%%%%%%%% % trial is not locked, go to original trial division and zoom out elseif cfg.blocksize >= locktrllen trlvis = opt.trlorg; % set current trlop to locked trial if it was locked before if ~isempty(opt.trllock) opt.trlop = opt.trllock; end smpperseg = round(opt.fsample * cfg.blocksize); % determine length of each trial, and determine the offset with the current requested zoom-level trllen = (trlvis(:,2) - trlvis(:,1)+1); sizediff = smpperseg - trllen; opt.nanpaddata = sizediff; % update trialviewtype opt.trialviewtype = 'trial'; % update button set(findobj(get(h, 'children'), 'string', 'trialsegment'), 'string',opt.trialviewtype); % release trial lock opt.trllock = []; %%%%%%%%% end % save trlvis opt.trlvis = trlvis; else % construct a trial definition for visualisation if isfield(opt, 'trlvis') % if present, remember where we were thistrlbeg = opt.trlvis(opt.trlop,1); end % look at cfg.blocksize and make opt.trl accordingly datbegsample = min(opt.trlorg(:,1)); datendsample = max(opt.trlorg(:,2)); smpperseg = round(opt.fsample * cfg.blocksize); begsamples = datbegsample:smpperseg:datendsample; endsamples = datbegsample+smpperseg-1:smpperseg:datendsample; if numel(endsamples)<numel(begsamples) endsamples(end+1) = datendsample; end trlvis = []; trlvis(:,1) = begsamples'; trlvis(:,2) = endsamples'; % compute the offset. In case if opt.trlorg has multiple trials, the first sample is t=0, otherwise use the offset in opt.trlorg if size(opt.trlorg,1)==1 offset = begsamples - repmat(begsamples(1), [1 numel(begsamples)]); % offset for all segments compared to the first offset = offset + opt.trlorg(1,3); trlvis(:,3) = offset; else offset = begsamples - repmat(begsamples(1), [1 numel(begsamples)]); trlvis(:,3) = offset; end if isfield(opt, 'trlvis') % update the current trial counter and try to keep the current sample the same % opt.trlop = nearest(round((begsamples+endsamples)/2), thissample); opt.trlop = nearest(begsamples, thistrlbeg); end opt.trlvis = trlvis; % NaN-padding when horizontal scaling is bigger than the data % two possible situations, 1) zoomed out so far that all data is one segment, or 2) multiple segments but last segment is smaller than the rest sizediff = smpperseg-(endsamples-begsamples+1); opt.nanpaddata = sizediff; end % if continuous setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function help_cb(h, eventdata) fprintf('------------------------------------------------------------------------------------\n') fprintf('You can use the following keyboard buttons in the databrowser\n') fprintf('1-9 : select artifact type 1-9\n'); fprintf('shift 1-9 : select previous artifact of type 1-9\n'); fprintf(' (does not work with numpad keys)\n'); fprintf('control 1-9 : select next artifact of type 1-9\n'); fprintf('alt 1-9 : select next artifact of type 1-9\n'); fprintf('arrow-left : previous trial\n'); fprintf('arrow-right : next trial\n'); fprintf('shift arrow-up : increase vertical scaling\n'); fprintf('shift arrow-down : decrease vertical scaling\n'); fprintf('shift arrow-left : increase horizontal scaling\n'); fprintf('shift arrow-down : decrease horizontal scaling\n'); fprintf('s : toggles between cfg.selectmode options\n'); fprintf('q : quit\n'); fprintf('------------------------------------------------------------------------------------\n') fprintf('\n') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function select_range_cb(h, range, cmenulab) %range 1X4 in sec relative to current trial opt = getappdata(h, 'opt'); cfg = getappdata(h, 'cfg'); % the range should be in the displayed box range(1) = max(opt.hpos-opt.width/2, range(1)); range(2) = max(opt.hpos-opt.width/2, range(2)); range(1) = min(opt.hpos+opt.width/2, range(1)); range(2) = min(opt.hpos+opt.width/2, range(2)); range = (range-(opt.hpos-opt.width/2)) / opt.width; % left side of the box becomes 0, right side becomes 1 range = range * (opt.hlim(2) - opt.hlim(1)) + opt.hlim(1); % 0 becomes hlim(1), 1 becomes hlim(2) begsample = opt.trlvis(opt.trlop,1); endsample = opt.trlvis(opt.trlop,2); offset = opt.trlvis(opt.trlop,3); % determine the selection begsel = round(range(1)*opt.fsample+begsample-offset-1); endsel = round(range(2)*opt.fsample+begsample-offset); % artifact selection is now always based on begsample/endsample/offset % -roevdmei % the selection should always be confined to the current trial begsel = max(begsample, begsel); endsel = min(endsample, endsel); % mark or execute selfun if isempty(cmenulab) % the left button was clicked INSIDE a selected range, update the artifact definition or event if strcmp(cfg.selectmode, 'markartifact') % mark or unmark artifacts artval = opt.artdata.trial{1}(opt.ftsel, begsel:endsel); artval = any(artval,1); if any(artval) fprintf('there is overlap with the active artifact (%s), disabling this artifact\n',opt.artdata.label{opt.ftsel}); opt.artdata.trial{1}(opt.ftsel, begsel:endsel) = 0; else fprintf('there is no overlap with the active artifact (%s), marking this as a new artifact\n',opt.artdata.label{opt.ftsel}); opt.artdata.trial{1}(opt.ftsel, begsel:endsel) = 1; end % redraw only when marking (so the focus doesn't go back to the databrowser after calling selfuns setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); redraw_cb(h); elseif strcmp(cfg.selectmode, 'markpeakevent') || strcmp(cfg.selectmode, 'marktroughevent') %mark or unmark events, marking at peak/trough of window if any(intersect(begsel:endsel, [opt.event.sample])) fprintf('there is overlap with one or more event(s), disabling this/these event(s)\n'); ind_rem = intersect(begsel:endsel, [opt.event.sample]); for iRemove = 1:length(ind_rem) opt.event([opt.event.sample]==ind_rem(iRemove)) = []; end else fprintf('there is no overlap with any event, adding an event to the peak/trough value\n'); % check if only 1 chan, other wise not clear max in which channel. % % ingnie: would be cool to add the option to select the channel when multiple channels if size(opt.curdata.trial{1},1) > 1 error('cfg.selectmode = ''markpeakevent'' and ''marktroughevent'' only supported with 1 channel in the data') end if strcmp(cfg.selectmode, 'markpeakevent') [dum ind_minmax] = max(opt.curdata.trial{1}(begsel-begsample+1:endsel-begsample+1)); val = 'peak'; elseif strcmp(cfg.selectmode, 'marktroughevent') [dum ind_minmax] = min(opt.curdata.trial{1}(begsel-begsample+1:endsel-begsample+1)); val = 'trough'; end samp_minmax = begsel + ind_minmax - 1; event_new.type = 'ft_databrowser_manual'; event_new.sample = samp_minmax; event_new.value = val; event_new.duration = 1; event_new.offset = 0; % add new event to end opt.event % check if events are in order now if min(diff([opt.event.sample]))>0 % add new event in line with old ones nearest_event = nearest([opt.event.sample], samp_minmax); if opt.event(nearest_event).sample > samp_minmax %place new event before nearest ind_event_new = nearest_event; else %place new event after nearest ind_event_new = nearest_event +1; end event_lastpart = opt.event(ind_event_new:end); opt.event(ind_event_new) = event_new; opt.event(ind_event_new+1:end+1) = event_lastpart; else %just add to end opt.event(end+1) = event_new; end clear event_new ind_event_new event_lastpart val dum ind_minmax end % redraw only when marking (so the focus doesn't go back to the databrowser after calling selfuns setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); redraw_cb(h); end else % the right button was used to activate the context menu and the user made a selection from that menu % execute the corresponding function % get index into cfgs selfunind = strcmp(cfg.selfun, cmenulab); % cut out the requested data segment switch cfg.seldat case 'current' seldata = keepfields(opt.curdata, {'label', 'grad', 'elec', 'hdr'}); seldata.trial{1} = ft_fetch_data(opt.curdata, 'begsample', begsel, 'endsample', endsel); case 'all' seldata = keepfields(opt.org, {'label', 'grad', 'elec', 'hdr'}); seldata.trial{1} = ft_fetch_data(opt.orgdata, 'begsample', begsel, 'endsample', endsel); end seldata.time{1} = offset2time(offset+begsel-begsample, opt.fsample, endsel-begsel+1); seldata.fsample = opt.fsample; seldata.sampleinfo = [begsel endsel offset]; % prepare input funhandle = ft_getuserfun(cmenulab, 'browse'); funcfg = cfg.selcfg{selfunind}; % get windowname and give as input (can be used for the other functions as well, not implemented yet) if ~strcmp(opt.trialviewtype, 'trialsegment') str = sprintf('%s %d/%d, time from %g to %g s', opt.trialviewtype, opt.trlop, size(opt.trlvis,1), seldata.time{1}(1), seldata.time{1}(end)); else str = sprintf('trial %d/%d: segment: %d/%d , time from %g to %g s', opt.trllock, size(opt.trlorg,1), opt.trlop, size(opt.trlvis,1), seldata.time{1}(1), seldata.time{1}(end)); end funcfg.figurename = [cmenulab ': ' str]; feval(funhandle, funcfg, seldata); end end % function select_range_cb %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function preproc_cfg1_cb(h,eventdata) parent = get(h, 'parent'); cfg = getappdata(parent, 'cfg'); editfontsize = cfg.editfontsize; editfontunits = cfg.editfontunits; % parse cfg.preproc if ~isempty(cfg.preproc) code = printstruct('cfg.preproc', cfg.preproc); else code = ''; end % add descriptive lines code = { '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%' '% Add or change options for on-the-fly preprocessing' '% Use as cfg.preproc.option=value' '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%' code }; % make figure displaying the edit box pph = figure; axis off % add save button uicontrol('tag', 'preproccfg_l2', 'parent', pph, 'units', 'normalized', 'style', 'pushbutton', 'string', 'save and close', 'position', [0.81, 0.6 , 0.18, 0.10], 'callback', @preproc_cfg2_cb); % add edit box ppeh = uicontrol('style', 'edit'); set(pph, 'toolBar', 'none') set(pph, 'menuBar', 'none') set(pph, 'Name', 'cfg.preproc editor') set(pph, 'NumberTitle', 'off') set(ppeh, 'Units', 'normalized'); set(ppeh, 'Position', [0 0 .8 1]); set(ppeh, 'backgroundColor', [1 1 1]); set(ppeh, 'horizontalAlign', 'left'); set(ppeh, 'max', 2); set(ppeh, 'min', 0); set(ppeh, 'FontName', 'Courier', 'FontSize', editfontsize, 'FontUnits', editfontunits); set(ppeh, 'string', code); % add handle for the edit style to figure setappdata(pph, 'superparent', parent); % superparent is the main ft_databrowser window setappdata(pph, 'ppeh', ppeh); end % function preproc_cfg1_cb %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function preproc_cfg2_cb(h,eventdata) parent = get(h, 'parent'); superparent = getappdata(parent, 'superparent'); ppeh = getappdata(parent, 'ppeh'); code = get(ppeh, 'string'); % get rid of empty lines and white space skip = []; for iline = 1:numel(code) code{iline} = strtrim(code{iline}); if isempty(code{iline}) skip = [skip iline]; continue end if code{iline}(1)=='%' skip = [skip iline]; continue end end code(skip) = []; if ~isempty(code) ispreproccfg = strncmp(code, 'cfg.preproc.',12); if ~all(ispreproccfg) errordlg('cfg-options must be specified as cfg.preproc.xxx', 'cfg.preproc editor', 'modal') end % eval the code for icomm = 1:numel(code) eval([code{icomm} ';']); end % check for cfg and output into the original appdata-window if ~exist('cfg', 'var') cfg = []; cfg.preproc = []; end maincfg = getappdata(superparent, 'cfg'); maincfg.preproc = cfg.preproc; setappdata(superparent, 'cfg', maincfg) end close(parent) redraw_cb(superparent) end % function preproc_cfg2_cb %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function keyboard_cb(h, eventdata) if (isempty(eventdata) && ft_platform_supports('matlabversion',-Inf, '2014a')) || isa(eventdata, 'matlab.ui.eventdata.ActionData') % determine the key that corresponds to the uicontrol element that was activated key = get(h, 'userdata'); else % determine the key that was pressed on the keyboard key = parseKeyboardEvent(eventdata); end % get focus back to figure if ~strcmp(get(h, 'type'), 'figure') set(h, 'enable', 'off'); drawnow; set(h, 'enable', 'on'); end h = getparent(h); opt = getappdata(h, 'opt'); cfg = getappdata(h, 'cfg'); switch key case {'1' '2' '3' '4' '5' '6' '7' '8' '9'} % switch to another artifact type opt.ftsel = str2double(key); numart = size(opt.artdata.trial{1}, 1); if opt.ftsel > numart fprintf('data has no artifact type %i \n', opt.ftsel) else % bold the active one arth = findobj(h,'tag','artifactui'); arth = arth(end:-1:1); % order is reversed so reverse it again hsel = [1 2 3] + (opt.ftsel-1) .*3 ; set(arth(hsel),'fontweight','bold') % unbold the passive ones set(arth(setdiff(1:numel(arth),hsel)),'fontweight','normal') % redraw setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); fprintf('switching to the "%s" artifact\n', opt.artdata.label{opt.ftsel}); redraw_cb(h, eventdata); end case {'shift+1' 'shift+2' 'shift+3' 'shift+4' 'shift+5' 'shift+6' 'shift+7' 'shift+8' 'shift+9'} % go to previous artifact opt.ftsel = str2double(key(end)); numart = size(opt.artdata.trial{1}, 1); if opt.ftsel > numart fprintf('data has no artifact type %i \n', opt.ftsel) else % find the previous occuring artifact, keeping in mind that: % 1) artifacts can cross trial boundaries % 2) artifacts might not occur inside a trial boundary (when data is segmented differently than during artifact detection) % fetch trl representation of current artifact type arttrl = convert_event(opt.artdata.trial{1}(opt.ftsel,:),'trl'); % discard artifacts in the future curvisend = opt.trlvis(opt.trlop,2); arttrl(arttrl(:,1) > curvisend,:) = []; % find nearest artifact by searching in each trl (we have to do this here everytime, because trlvis can change on the fly because of x-zooming) newtrlop = []; for itrlvis = opt.trlop-1:-1:1 % is either the start or the end of any artifact present? if any(any(opt.trlvis(itrlvis,1)<=arttrl(:,1:2) & opt.trlvis(itrlvis,2)>=arttrl(:,1:2))) % if so, we're done newtrlop = itrlvis; break end end if isempty(newtrlop) fprintf('no earlier %s with "%s" artifact found\n', opt.trialviewtype, opt.artdata.label{opt.ftsel}); else fprintf('going to previous %s with "%s" artifact\n', opt.trialviewtype, opt.artdata.label{opt.ftsel}); opt.trlop = newtrlop; % other artifact type potentially selected, bold the active one arth = findobj(h,'tag','artifactui'); arth = arth(end:-1:1); % order is reversed so reverse it again hsel = [1 2 3] + (opt.ftsel-1) .*3 ; set(arth(hsel),'fontweight','bold') % unbold the passive ones set(arth(setdiff(1:numel(arth),hsel)),'fontweight','normal') % export into fig and continue setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); redraw_cb(h, eventdata); end end case {'control+1' 'control+2' 'control+3' 'control+4' 'control+5' 'control+6' 'control+7' 'control+8' 'control+9' 'alt+1' 'alt+2' 'alt+3' 'alt+4' 'alt+5' 'alt+6' 'alt+7' 'alt+8' 'alt+9'} % go to next artifact opt.ftsel = str2double(key(end)); numart = size(opt.artdata.trial{1}, 1); if opt.ftsel > numart fprintf('data has no artifact type %i \n', opt.ftsel) else % find the next occuring artifact, keeping in mind that: % 1) artifacts can cross trial boundaries % 2) artifacts might not occur inside a trial boundary (when data is segmented differently than during artifact detection) % fetch trl representation of current artifact type arttrl = convert_event(opt.artdata.trial{1}(opt.ftsel,:),'trl'); % discard artifacts in the past curvisbeg = opt.trlvis(opt.trlop,1); arttrl(arttrl(:,2) < curvisbeg,:) = []; % find nearest artifact by searching in each trl (we have to do this here everytime, because trlvis can change on the fly because of x-zooming) newtrlop = []; for itrlvis = opt.trlop+1:size(opt.trlvis,1) % is either the start or the end of any artifact present? if any(any(opt.trlvis(itrlvis,1)<=arttrl(:,1:2) & opt.trlvis(itrlvis,2)>=arttrl(:,1:2))) % if so, we're done newtrlop = itrlvis; break end end if isempty(newtrlop) fprintf('no later %s with "%s" artifact found\n', opt.trialviewtype, opt.artdata.label{opt.ftsel}); else fprintf('going to next %s with "%s" artifact\n', opt.trialviewtype, opt.artdata.label{opt.ftsel}); opt.trlop = newtrlop; % other artifact type potentially selected, bold the active one arth = findobj(h,'tag','artifactui'); arth = arth(end:-1:1); % order is reversed so reverse it again hsel = [1 2 3] + (opt.ftsel-1) .*3 ; set(arth(hsel),'fontweight','bold') % unbold the passive ones set(arth(setdiff(1:numel(arth),hsel)),'fontweight','normal') % export into fig and continue setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); redraw_cb(h, eventdata); end end case 'leftarrow' opt.trlop = max(opt.trlop - 1, 1); % should not be smaller than 1 setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); redraw_cb(h, eventdata); case 'rightarrow' opt.trlop = min(opt.trlop + 1, size(opt.trlvis,1)); % should not be larger than the number of trials setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); redraw_cb(h, eventdata); case 'uparrow' chansel = match_str(opt.hdr.label, cfg.channel); minchan = min(chansel); numchan = length(chansel); chansel = minchan - numchan : minchan - 1; if min(chansel)<1 chansel = chansel - min(chansel) + 1; end % convert numeric array into cell-array with channel labels cfg.channel = opt.hdr.label(chansel); opt.changedchanflg = true; % trigger for redrawing channel labels and preparing layout again (see bug 2065 and 2878) setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); delete(findobj(h, 'tag', 'chanlabel')); % remove channel labels here, and not in redrawing to save significant execution time (see bug 2065) redraw_cb(h, eventdata); case 'downarrow' chansel = match_str(opt.hdr.label, cfg.channel); maxchan = max(chansel); numchan = length(chansel); chansel = maxchan + 1 : maxchan + numchan; if max(chansel)>length(opt.hdr.label) chansel = chansel - (max(chansel) - length(opt.hdr.label)); end % convert numeric array into cell-array with channel labels cfg.channel = opt.hdr.label(chansel); opt.changedchanflg = true; % trigger for redrawing channel labels and preparing layout again (see bug 2065 and 2878) setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); delete(findobj(h, 'tag', 'chanlabel')); % remove channel labels here, and not in redrawing to save significant execution time (see bug 2065) redraw_cb(h, eventdata); case 'shift+leftarrow' cfg.blocksize = cfg.blocksize*sqrt(2); setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); definetrial_cb(h, eventdata); redraw_cb(h, eventdata); case 'shift+rightarrow' cfg.blocksize = cfg.blocksize/sqrt(2); setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); definetrial_cb(h, eventdata); redraw_cb(h, eventdata); case 'shift+uparrow' cfg.ylim = cfg.ylim/sqrt(2); setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); redraw_cb(h, eventdata); case 'shift+downarrow' cfg.ylim = cfg.ylim*sqrt(2); setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); redraw_cb(h, eventdata); case 'q' setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); cleanup_cb(h); case 't' % select the trial to display if ~strcmp(opt.trialviewtype, 'trialsegment') str = sprintf('%s to display (current trial = %d/%d)', opt.trialviewtype, opt.trlop, size(opt.trlvis,1)); else str = sprintf('segment to display (current segment = %d/%d)', opt.trlop, size(opt.trlvis,1)); end response = inputdlg(str, 'specify', 1, {num2str(opt.trlop)}); if ~isempty(response) opt.trlop = str2double(response); opt.trlop = min(opt.trlop, size(opt.trlvis,1)); % should not be larger than the number of trials opt.trlop = max(opt.trlop, 1); % should not be smaller than 1 setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); redraw_cb(h, eventdata); end case 'h' % select the horizontal scaling response = inputdlg('horizontal scale', 'specify', 1, {num2str(cfg.blocksize)}); if ~isempty(response) cfg.blocksize = str2double(response); setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); definetrial_cb(h, eventdata); redraw_cb(h, eventdata); end case 'v' % select the vertical scaling response = inputdlg('vertical scale, [ymin ymax], ''maxabs'' or ''maxmin''', 'specify', 1, {['[ ' num2str(cfg.ylim) ' ]']}); if ~isempty(response) if strcmp(response, 'maxmin') minval = min(opt.curdata.trial{1}(:)); maxval = max(opt.curdata.trial{1}(:)); cfg.ylim = [minval maxval]; elseif strcmp(response, 'maxabs') minval = min(opt.curdata.trial{1}(:)); maxval = max(opt.curdata.trial{1}(:)); cfg.ylim = [-max(abs([minval maxval])) max(abs([minval maxval]))]; else % convert to string and add brackets, just to ensure that str2num will work tmp = str2num(['[' response{1} ']']); if numel(tmp)==2 cfg.ylim = tmp; else warning('incorrect specification of cfg.ylim, not changing the limits for the vertical axes') end end setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); redraw_cb(h, eventdata); end case 'c' % select channels select = match_str(opt.hdr.label, cfg.channel); select = select_channel_list(opt.hdr.label, select); cfg.channel = opt.hdr.label(select); opt.changedchanflg = true; % trigger for redrawing channel labels and preparing layout again (see bug 2065 and 2878) setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); delete(findobj(h, 'tag', 'chanlabel')); % remove channel labels here, and not in redrawing to save significant execution time (see bug 2065) redraw_cb(h, eventdata); case 'i' delete(findobj(h, 'tag', 'identify')); % click in data and get name of nearest channel fprintf('click in the figure to identify the name of the closest channel\n'); val = ginput(1); pos = val(1); if strcmp(cfg.viewmode, 'butterfly') || strcmp(cfg.viewmode, 'vertical') switch cfg.viewmode case 'butterfly' % transform 'val' to match data val(1) = val(1) * range(opt.hlim) + opt.hlim(1); val(2) = val(2) * range(opt.vlim) + opt.vlim(1); channame = val2nearestchan(opt.curdata,val); channb = match_str(opt.curdata.label,channame); % set chanposind chanposind = 1; % butterfly mode, pos is the first for all channels case 'vertical' % find channel identity by extracting timecourse objects and finding the time course closest to the cursor % this is a lot easier than the reverse, determining the y value of each time course scaled by the layout and vlim tcobj = findobj(h,'tag','timecourse'); tmpydat = get(tcobj,'ydata'); tmpydat = cat(1,tmpydat{:}); tmpydat = tmpydat(end:-1:1,:); % order of timecourse objects is reverse of channel order tmpxdat = get(tcobj(1),'xdata'); % first find closest sample on x xsmp = nearest(tmpxdat,val(1)); % then find closes y sample, being the channel number channb = nearest(tmpydat(:,xsmp),val(2)); channame = opt.curdata.label{channb}; % set chanposind chanposind = match_str(opt.laytime.label,channame); end fprintf('channel name: %s\n',channame); redraw_cb(h, eventdata); if strcmp(cfg.viewmode,'vertical') ypos = opt.laytime.pos(chanposind,2)+opt.laytime.height(chanposind)*3; if ypos>.9 % don't let label fall on plot boundary ypos = opt.laytime.pos(chanposind,2)-opt.laytime.height(chanposind)*3; end else ypos = .9; end ft_plot_text(pos, ypos, channame, 'FontSize', cfg.fontsize, 'FontUnits', cfg.fontunits, 'tag', 'identify', 'interpreter', 'none', 'FontSize', cfg.fontsize, 'FontUnits', cfg.fontunits); if ~ishold hold on ft_plot_vector(opt.curdata.time{1}, opt.curdata.trial{1}(channb,:), 'box', false, 'tag', 'identify', 'hpos', opt.laytime.pos(chanposind,1), 'vpos', opt.laytime.pos(chanposind,2), 'width', opt.laytime.width(chanposind), 'height', opt.laytime.height(chanposind), 'hlim', opt.hlim, 'vlim', opt.vlim, 'color', 'k', 'linewidth', 2); hold off else ft_plot_vector(opt.curdata.time{1}, opt.curdata.trial{1}(channb,:), 'box', false, 'tag', 'identify', 'hpos', opt.laytime.pos(chanposind,1), 'vpos', opt.laytime.pos(chanposind,2), 'width', opt.laytime.width(chanposind), 'height', opt.laytime.height(chanposind), 'hlim', opt.hlim, 'vlim', opt.vlim, 'color', 'k', 'linewidth', 2); end else warning('only supported with cfg.viewmode=''butterfly/vertical'''); end case 's' % toggle between selectmode options: switch from 'markartifact', to 'markpeakevent' to 'marktroughevent' and back with on screen feedback curstate = find(strcmp(cfg.selectmode, {'markartifact', 'markpeakevent', 'marktroughevent'})); if curstate == 1 cfg.selectmode = 'markpeakevent'; elseif curstate == 2 cfg.selectmode = 'marktroughevent'; elseif curstate == 3 cfg.selectmode = 'markartifact'; end fprintf('switching to selectmode = %s\n',cfg.selectmode); setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); redraw_cb(h, eventdata); case 'control+control' % do nothing case 'shift+shift' % do nothing case 'alt+alt' % do nothing otherwise setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); help_cb(h); end uiresume(h); end % function keyboard_cb %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function toggle_viewmode_cb(h, eventdata, varargin) % FIXME should be used opt = guidata(getparent(h)); if ~isempty(varargin) && ischar(varargin{1}) cfg.viewmode = varargin{1}; end opt.changedchanflg = true; % trigger for redrawing channel labels and preparing layout again (see bug 2065 and 2878) guidata(getparent(h), opt); delete(findobj(h, 'tag', 'chanlabel')); % remove channel labels here, and not in redrawing to save significant execution time (see bug 2065) redraw_cb(h); end % function toggle_viewmode_cb %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = getparent(h) p = h; while p~=0 h = p; p = get(h, 'parent'); end end % function getparent %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function redraw_cb(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); cfg = getappdata(h, 'cfg'); figure(h); % ensure that the calling figure is in the front %fprintf('redrawing with viewmode %s\n', cfg.viewmode); begsample = opt.trlvis(opt.trlop, 1); endsample = opt.trlvis(opt.trlop, 2); offset = opt.trlvis(opt.trlop, 3); chanindx = match_str(opt.hdr.label, cfg.channel); % parse opt.changedchanflg, and rese changedchanflg = false; if opt.changedchanflg changedchanflg = true; % trigger for redrawing channel labels and preparing layout again (see bug 2065 and 2878) opt.changedchanflg = false; end if ~isempty(opt.event) && isstruct(opt.event) % select only the events in the current time window event = opt.event; evtsample = [event(:).sample]; event = event(evtsample>=begsample & evtsample<=endsample); else event = []; end if isempty(opt.orgdata) dat = ft_read_data(cfg.datafile, 'header', opt.hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', strcmp(cfg.continuous, 'no'), 'dataformat', cfg.dataformat, 'headerformat', cfg.headerformat); else dat = ft_fetch_data(opt.orgdata, 'header', opt.hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'allowoverlap', true); % ALLOWING OVERLAPPING TRIALS end art = ft_fetch_data(opt.artdata, 'begsample', begsample, 'endsample', endsample); % convert the data to another numeric precision, i.e. double, single or int32 if ~isempty(cfg.precision) dat = cast(dat, cfg.precision); end % apply preprocessing and determine the time axis [dat, lab, tim] = preproc(dat, opt.hdr.label(chanindx), offset2time(offset, opt.fsample, size(dat,2)), cfg.preproc); % add NaNs to data for plotting purposes. NaNs will be added when requested horizontal scaling is longer than the data. nsamplepad = opt.nanpaddata(opt.trlop); if nsamplepad>0 dat = [dat NaN(numel(lab), opt.nanpaddata(opt.trlop))]; tim = [tim linspace(tim(end),tim(end)+nsamplepad*mean(diff(tim)),nsamplepad)]; % possible machine precision error here end % apply scaling to selected channels % using wildcard to support subselection of channels if ~isempty(cfg.eegscale) chansel = match_str(lab, ft_channelselection('EEG', lab)); dat(chansel,:) = dat(chansel,:) .* cfg.eegscale; end if ~isempty(cfg.eogscale) chansel = match_str(lab, ft_channelselection('EOG', lab)); dat(chansel,:) = dat(chansel,:) .* cfg.eogscale; end if ~isempty(cfg.ecgscale) chansel = match_str(lab, ft_channelselection('ECG', lab)); dat(chansel,:) = dat(chansel,:) .* cfg.ecgscale; end if ~isempty(cfg.emgscale) chansel = match_str(lab, ft_channelselection('EMG', lab)); dat(chansel,:) = dat(chansel,:) .* cfg.emgscale; end if ~isempty(cfg.megscale) type = opt.hdr.grad.type; chansel = match_str(lab, ft_channelselection('MEG', lab, type)); dat(chansel,:) = dat(chansel,:) .* cfg.megscale; end if ~isempty(cfg.magscale) chansel = match_str(lab, ft_channelselection('MEGMAG', lab)); dat(chansel,:) = dat(chansel,:) .* cfg.magscale; end if ~isempty(cfg.gradscale) chansel = match_str(lab, ft_channelselection('MEGGRAD', lab)); dat(chansel,:) = dat(chansel,:) .* cfg.gradscale; end if ~isempty(cfg.chanscale) chansel = match_str(lab, ft_channelselection(cfg.channel, lab)); dat(chansel,:) = dat(chansel,:) .* repmat(cfg.chanscale,1,size(dat,2)); end if ~isempty(cfg.mychanscale) chansel = match_str(lab, ft_channelselection(cfg.mychan, lab)); dat(chansel,:) = dat(chansel,:) .* cfg.mychanscale; end opt.curdata.label = lab; opt.curdata.time{1} = tim; opt.curdata.trial{1} = dat; opt.curdata.hdr = opt.hdr; opt.curdata.fsample = opt.fsample; opt.curdata.sampleinfo = [begsample endsample offset]; % to assure current feature is plotted on top ordervec = 1:length(opt.artdata.label); ordervec(opt.ftsel) = []; ordervec(end+1) = opt.ftsel; % FIXME speedup ft_prepare_layout if strcmp(cfg.viewmode, 'butterfly') laytime = []; laytime.label = {'dummy'}; laytime.pos = [0.5 0.5]; laytime.width = 1; laytime.height = 1; opt.laytime = laytime; else % this needs to be reconstructed if the channel selection changes if changedchanflg % trigger for redrawing channel labels and preparing layout again (see bug 2065 and 2878) tmpcfg = []; if strcmp(cfg.viewmode, 'component') tmpcfg.layout = 'vertical'; else tmpcfg.layout = cfg.viewmode; end tmpcfg.channel = cfg.channel; tmpcfg.skipcomnt = 'yes'; tmpcfg.skipscale = 'yes'; tmpcfg.showcallinfo = 'no'; opt.laytime = ft_prepare_layout(tmpcfg, opt.orgdata); end end % determine the position of the channel/component labels relative to the real axes % FIXME needs a shift to the left for components labelx = opt.laytime.pos(:,1) - opt.laytime.width/2 - 0.01; labely = opt.laytime.pos(:,2); % determine the total extent of all virtual axes relative to the real axes ax(1) = min(opt.laytime.pos(:,1) - opt.laytime.width/2); ax(2) = max(opt.laytime.pos(:,1) + opt.laytime.width/2); ax(3) = min(opt.laytime.pos(:,2) - opt.laytime.height/2); ax(4) = max(opt.laytime.pos(:,2) + opt.laytime.height/2); % add white space to bottom and top so channels are not out-of-axis for the majority % NOTE: there is a second spot where this is done below, specifically for viewmode = component (also need to be here), which should be kept the same as this if any(strcmp(cfg.viewmode,{'vertical','component'})) % determine amount of vertical padding using cfg.verticalpadding if ~isnumeric(cfg.verticalpadding) && strcmp(cfg.verticalpadding,'auto') % determine amount of padding using the number of channels if numel(cfg.channel)<=6 wsfac = 0; elseif numel(cfg.channel)>6 && numel(cfg.channel)<=10 wsfac = 0.01 * (ax(4)-ax(3)); else wsfac = 0.02 * (ax(4)-ax(3)); end else wsfac = cfg.verticalpadding * (ax(4)-ax(3)); end ax(3) = ax(3) - wsfac; ax(4) = ax(4) + wsfac; end axis(ax) % determine a single local axis that encompasses all channels % this is in relative figure units opt.hpos = (ax(1)+ax(2))/2; opt.vpos = (ax(3)+ax(4))/2; opt.width = ax(2)-ax(1); opt.height = ax(4)-ax(3); % these determine the scaling inside the virtual axes % the hlim will be in seconds, the vlim will be in Tesla or Volt opt.hlim = [tim(1) tim(end)]; opt.vlim = cfg.ylim; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fprintf('plotting artifacts...\n'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% delete(findobj(h, 'tag', 'artifact')); for j = ordervec tmp = diff([0 art(j,:) 0]); artbeg = find(tmp==+1); artend = find(tmp==-1) - 1; for k=1:numel(artbeg) xpos = [tim(artbeg(k)) tim(artend(k))] + ([-.5 +.5]./opt.fsample); h_artifact = ft_plot_box([xpos -1 1], 'facecolor', opt.artcolors(j,:), 'facealpha', .7, 'edgecolor', 'none', 'tag', 'artifact', 'hpos', opt.hpos, 'vpos', opt.vpos, 'width', opt.width, 'height', opt.height, 'hlim', opt.hlim, 'vlim', [-1 1]); end end % for each of the artifact channels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fprintf('plotting events...\n'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% delete(findobj(h, 'tag', 'event')); if strcmp(cfg.plotevents, 'yes') if any(strcmp(cfg.viewmode, {'butterfly', 'component', 'vertical'})) if strcmp(cfg.ploteventlabels , 'colorvalue') && ~isempty(opt.event) eventlabellegend = []; for iType = 1:length(opt.eventtypes) eventlabellegend = [eventlabellegend sprintf('%s = %s\n',opt.eventtypes{iType},opt.eventtypecolorlabels{iType})]; end fprintf(eventlabellegend); end % save stuff to able to shift event labels downwards when they occur at the same time-point eventcol = cell(1,numel(event)); eventstr = cell(1,numel(event)); eventtim = NaN(1,numel(event)); % gather event info and plot lines for ievent = 1:numel(event) try if strcmp(cfg.ploteventlabels , 'type=value') if isempty(event(ievent).value) eventstr{ievent} = ''; else eventstr{ievent} = sprintf('%s = %s', event(ievent).type, num2str(event(ievent).value)); % value can be both number and string end eventcol{ievent} = 'k'; elseif strcmp(cfg.ploteventlabels , 'colorvalue') eventcol{ievent} = opt.eventtypescolors(match_str(opt.eventtypes, event(ievent).type),:); eventstr{ievent} = sprintf('%s', num2str(event(ievent).value)); % value can be both number and string end catch eventstr{ievent} = 'unknown'; eventcol{ievent} = 'k'; end eventtim(ievent) = (event(ievent).sample-begsample)/opt.fsample + opt.hlim(1); lh = ft_plot_line([eventtim(ievent) eventtim(ievent)], [-1 1], 'tag', 'event', 'color', eventcol{ievent}, 'hpos', opt.hpos, 'vpos', opt.vpos, 'width', opt.width, 'height', opt.height, 'hlim', opt.hlim, 'vlim', [-1 1]); % store this data in the line object so that it can be displayed in the % data cursor (see subfunction datacursortext below) setappdata(lh, 'ft_databrowser_linetype', 'event'); setappdata(lh, 'ft_databrowser_eventtime', eventtim(ievent)); setappdata(lh, 'ft_databrowser_eventtype', event(ievent).type); setappdata(lh, 'ft_databrowser_eventvalue', event(ievent).value); end % count the consecutive occurrence of each time point concount = NaN(1,numel(event)); for ievent = 1:numel(event) concount(ievent) = sum(eventtim(ievent)==eventtim(1:ievent-1)); end % plot event labels for ievent = 1:numel(event) ft_plot_text(eventtim(ievent), 0.9-concount(ievent)*.06, eventstr{ievent}, 'tag', 'event', 'Color', eventcol{ievent}, 'hpos', opt.hpos, 'vpos', opt.vpos, 'width', opt.width, 'height', opt.height, 'hlim', opt.hlim, 'vlim', [-1 1], 'interpreter', 'none', 'FontSize', cfg.fontsize, 'FontUnits', cfg.fontunits); end end % if viewmode appropriate for events end % if user wants to see event marks %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %fprintf('plotting data...\n'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% delete(findobj(h, 'tag', 'timecourse')); delete(findobj(h, 'tag', 'identify')); % not removing channel labels, they cause the bulk of redrawing time for the slow text function (note, interpreter = none hardly helps) % warning, when deleting the labels using the line below, one can easily tripple the excution time of redrawing in viewmode = vertical (see bug 2065) %delete(findobj(h, 'tag', 'chanlabel')); if strcmp(cfg.viewmode, 'butterfly') set(gca, 'ColorOrder',opt.chancolors(chanindx,:)) % plot vector does not clear axis, therefore this is possible ft_plot_vector(tim, dat, 'box', false, 'tag', 'timecourse', 'hpos', opt.laytime.pos(1,1), 'vpos', opt.laytime.pos(1,2), 'width', opt.laytime.width(1), 'height', opt.laytime.height(1), 'hlim', opt.hlim, 'vlim', opt.vlim, 'linewidth', cfg.linewidth); set(gca, 'FontSize', cfg.axisfontsize, 'FontUnits', cfg.axisfontunits); % two ticks per channel yTick = sort([ opt.laytime.pos(:,2)+(opt.laytime.height/2) opt.laytime.pos(:,2)+(opt.laytime.height/4) opt.laytime.pos(:,2) opt.laytime.pos(:,2)-(opt.laytime.height/4) opt.laytime.pos(:,2)-(opt.laytime.height/2) ]); % sort yTickLabel = {num2str(yTick.*range(opt.vlim) + opt.vlim(1))}; set(gca, 'yTick', yTick, 'yTickLabel', yTickLabel) elseif any(strcmp(cfg.viewmode, {'component', 'vertical'})) % determine channel indices into data outside of loop laysels = match_str(opt.laytime.label, opt.hdr.label); % delete old chan labels before renewing, if they need to be renewed if changedchanflg % trigger for redrawing channel labels and preparing layout again (see bug 2065 and 2878) delete(findobj(h,'tag', 'chanlabel')); end for i = 1:length(chanindx) if strcmp(cfg.viewmode, 'component') color = 'k'; else color = opt.chancolors(chanindx(i),:); end datsel = i; laysel = laysels(i); if ~isempty(datsel) && ~isempty(laysel) % only plot chanlabels when necessary if changedchanflg % trigger for redrawing channel labels and preparing layout again (see bug 2065 and 2878) % determine how many labels to skip in case of 'some' if opt.plotLabelFlag == 2 && strcmp(cfg.fontunits,'points') % determine number of labels to plot by estimating overlap using current figure size % the idea is that figure height in pixels roughly corresponds to the amount of letters at cfg.fontsize (points) put above each other without overlap figheight = get(h,'Position'); figheight = figheight(4); labdiscfac = ceil(numel(chanindx) ./ (figheight ./ (cfg.fontsize+6))); % 6 added, so that labels are not too close together (i.e. overlap if font was 6 points bigger) else labdiscfac = 10; end if opt.plotLabelFlag == 1 || (opt.plotLabelFlag == 2 && mod(i,labdiscfac)==0) ft_plot_text(labelx(laysel), labely(laysel), opt.hdr.label(chanindx(i)), 'tag', 'chanlabel', 'HorizontalAlignment', 'right', 'interpreter', 'none', 'FontSize', cfg.fontsize, 'FontUnits', cfg.fontunits, 'linewidth', cfg.linewidth); set(gca, 'FontSize', cfg.axisfontsize, 'FontUnits', cfg.axisfontunits); end end lh = ft_plot_vector(tim, dat(datsel, :), 'box', false, 'color', color, 'tag', 'timecourse', 'hpos', opt.laytime.pos(laysel,1), 'vpos', opt.laytime.pos(laysel,2), 'width', opt.laytime.width(laysel), 'height', opt.laytime.height(laysel), 'hlim', opt.hlim, 'vlim', opt.vlim, 'linewidth', cfg.linewidth); % store this data in the line object so that it can be displayed in the % data cursor (see subfunction datacursortext below) setappdata(lh, 'ft_databrowser_linetype', 'channel'); setappdata(lh, 'ft_databrowser_label', opt.hdr.label(chanindx(i))); setappdata(lh, 'ft_databrowser_xaxis', tim); setappdata(lh, 'ft_databrowser_yaxis', dat(datsel,:)); end end % plot yticks if length(chanindx)> 6 % plot yticks at each label in case adaptive labeling is used (cfg.plotlabels = 'some') % otherwise, use the old ytick plotting based on hard-coded number of channels if opt.plotLabelFlag == 2 if opt.plotLabelFlag == 2 && strcmp(cfg.fontunits,'points') % determine number of labels to plot by estimating overlap using current figure size % the idea is that figure height in pixels roughly corresponds to the amount of letters at cfg.fontsize (points) put above each other without overlap figheight = get(h,'Position'); figheight = figheight(4); labdiscfac = ceil(numel(chanindx) ./ (figheight ./ (cfg.fontsize+2))); % 2 added, so that labels are not too close together (i.e. overlap if font was 2 points bigger) else labdiscfac = 10; end yTick = sort(labely(mod(chanindx,labdiscfac)==0),'ascend'); % sort is required, yticks should be increasing in value yTickLabel = []; else if length(chanindx)>19 % no space for yticks yTick = []; yTickLabel = []; elseif length(chanindx)> 6 % one tick per channel yTick = sort([ opt.laytime.pos(:,2)+(opt.laytime.height(laysel)/4) opt.laytime.pos(:,2)-(opt.laytime.height(laysel)/4) ]); yTickLabel = {[.25 .75] .* range(opt.vlim) + opt.vlim(1)}; end end else % two ticks per channel yTick = sort([ opt.laytime.pos(:,2)+(opt.laytime.height(laysel)/2) opt.laytime.pos(:,2)+(opt.laytime.height(laysel)/4) opt.laytime.pos(:,2)-(opt.laytime.height(laysel)/4) opt.laytime.pos(:,2)-(opt.laytime.height(laysel)/2) ]); % sort yTickLabel = {[.0 .25 .75 1] .* range(opt.vlim) + opt.vlim(1)}; end yTickLabel = repmat(yTickLabel, 1, length(chanindx)); set(gca, 'yTick', yTick, 'yTickLabel', yTickLabel); else % the following is implemented for 2column, 3column, etcetera. % it also works for topographic layouts, such as CTF151 % determine channel indices into data outside of loop laysels = match_str(opt.laytime.label, opt.hdr.label); for i = 1:length(chanindx) color = opt.chancolors(chanindx(i),:); datsel = i; laysel = laysels(i); if ~isempty(datsel) && ~isempty(laysel) lh = ft_plot_vector(tim, dat(datsel, :), 'box', false, 'color', color, 'tag', 'timecourse', 'hpos', opt.laytime.pos(laysel,1), 'vpos', opt.laytime.pos(laysel,2), 'width', opt.laytime.width(laysel), 'height', opt.laytime.height(laysel), 'hlim', opt.hlim, 'vlim', opt.vlim, 'linewidth', cfg.linewidth); % store this data in the line object so that it can be displayed in the % data cursor (see subfunction datacursortext below) setappdata(lh, 'ft_databrowser_linetype', 'channel'); setappdata(lh, 'ft_databrowser_label', opt.hdr.label(chanindx(i))); setappdata(lh, 'ft_databrowser_xaxis', tim); setappdata(lh, 'ft_databrowser_yaxis', dat(datsel,:)); end end % ticks are not supported with such a layout yTick = []; yTickLabel = []; yTickLabel = repmat(yTickLabel, 1, length(chanindx)); set(gca, 'yTick', yTick, 'yTickLabel', yTickLabel); end % if strcmp viewmode if any(strcmp(cfg.viewmode, {'butterfly', 'component', 'vertical'})) nticks = 11; xTickLabel = cellstr(num2str( linspace(tim(1), tim(end), nticks)' , '%1.2f'))'; xTick = linspace(ax(1), ax(2), nticks); if nsamplepad>0 nlabindat = sum(linspace(tim(1), tim(end), nticks) < tim(end-nsamplepad)); xTickLabel(nlabindat+1:end) = repmat({' '}, [1 nticks-nlabindat]); end set(gca, 'xTick', xTick, 'xTickLabel', xTickLabel) xlabel('time'); else set(gca, 'xTick', [], 'xTickLabel', []) end if strcmp(cfg.viewmode, 'component') % determine the position of each of the original channels for the topgraphy laychan = opt.layorg; % determine the position of each of the topographies laytopo.pos(:,1) = opt.laytime.pos(:,1) - opt.laytime.width/2 - opt.laytime.height; laytopo.pos(:,2) = opt.laytime.pos(:,2) + opt.laytime.height/2; laytopo.width = opt.laytime.height; laytopo.height = opt.laytime.height; laytopo.label = opt.laytime.label; if ~isequal(opt.chanindx, chanindx) opt.chanindx = chanindx; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fprintf('plotting component topographies...\n'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% delete(findobj(h, 'tag', 'topography')); [sel1, sel2] = match_str(opt.orgdata.topolabel, laychan.label); chanx = laychan.pos(sel2,1); chany = laychan.pos(sel2,2); if strcmp(cfg.compscale, 'global') for i=1:length(chanindx) % loop through all components to get max and min zmin(i) = min(opt.orgdata.topo(sel1,chanindx(i))); zmax(i) = max(opt.orgdata.topo(sel1,chanindx(i))); end if strcmp(cfg.zlim, 'maxmin') zmin = min(zmin); zmax = max(zmax); elseif strcmp(cfg.zlim, 'maxabs') zmax = max([abs(zmin) abs(zmax)]); zmin = -zmax; else error('configuration option for component scaling could not be recognized'); end end for i=1:length(chanindx) % plot the topography of this component laysel = match_str(opt.laytime.label, opt.hdr.label(chanindx(i))); chanz = opt.orgdata.topo(sel1,chanindx(i)); if strcmp(cfg.compscale, 'local') % compute scaling factors here if strcmp(cfg.zlim, 'maxmin') zmin = min(chanz); zmax = max(chanz); elseif strcmp(cfg.zlim, 'maxabs') zmax = max(abs(chanz)); zmin = -zmax; end end % scaling chanz = (chanz - zmin) ./ (zmax- zmin); % laychan is the actual topo layout, in pixel units for .mat files % laytopo is a vertical layout determining where to plot each topo, with one entry per component ft_plot_topo(chanx, chany, chanz, 'mask', laychan.mask, 'interplim', 'mask', 'outline', laychan.outline, 'tag', 'topography', 'hpos', laytopo.pos(laysel,1)-laytopo.width(laysel)/2, 'vpos', laytopo.pos(laysel,2)-laytopo.height(laysel)/2, 'width', laytopo.width(laysel), 'height', laytopo.height(laysel), 'gridscale', 45); %axis equal %drawnow end caxis([0 1]); end % if redraw_topo set(gca, 'yTick', []) ax(1) = min(laytopo.pos(:,1) - laytopo.width); ax(2) = max(opt.laytime.pos(:,1) + opt.laytime.width/2); ax(3) = min(opt.laytime.pos(:,2) - opt.laytime.height/2); ax(4) = max(opt.laytime.pos(:,2) + opt.laytime.height/2); % add white space to bottom and top so channels are not out-of-axis for the majority % NOTE: there is another spot above with the same code, which should be kept the same as this % determine amount of vertical padding using cfg.verticalpadding if ~isnumeric(cfg.verticalpadding) && strcmp(cfg.verticalpadding,'auto') % determine amount of padding using the number of channels if numel(cfg.channel)<=6 wsfac = 0; elseif numel(cfg.channel)>6 && numel(cfg.channel)<=10 wsfac = 0.01 * (ax(4)-ax(3)); else wsfac = 0.02 * (ax(4)-ax(3)); end else wsfac = cfg.verticalpadding * (ax(4)-ax(3)); end ax(3) = ax(3) - wsfac; ax(4) = ax(4) + wsfac; axis(ax) end % plotting topographies startim = tim(1); if nsamplepad>0 endtim = tim(end-nsamplepad); else endtim = tim(end); end if ~strcmp(opt.trialviewtype, 'trialsegment') str = sprintf('%s %d/%d, time from %g to %g s', opt.trialviewtype, opt.trlop, size(opt.trlvis,1), startim, endtim); else str = sprintf('trial %d/%d: segment: %d/%d , time from %g to %g s', opt.trllock, size(opt.trlorg,1), opt.trlop, size(opt.trlvis,1), startim, endtim); end title(str); % possibly adds some responsiveness if the 'thing' is clogged drawnow setappdata(h, 'opt', opt); setappdata(h, 'cfg', cfg); end % function redraw_cb %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key = parseKeyboardEvent(eventdata) key = eventdata.Key; % handle possible numpad events (different for Windows and UNIX systems) % NOTE: shift+numpad number does not work on UNIX, since the shift % modifier is always sent for numpad events if isunix() shiftInd = match_str(eventdata.Modifier, 'shift'); if ~isnan(str2double(eventdata.Character)) && ~isempty(shiftInd) % now we now it was a numpad keystroke (numeric character sent AND % shift modifier present) key = eventdata.Character; eventdata.Modifier(shiftInd) = []; % strip the shift modifier end elseif ispc() if strfind(eventdata.Key, 'numpad') key = eventdata.Character; end end if ~isempty(eventdata.Modifier) key = [eventdata.Modifier{1} '+' key]; end end % function parseKeyboardEvent %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cursortext = datacursortext(obj, event_obj) pos = get(event_obj, 'position'); linetype = getappdata(event_obj.Target, 'ft_databrowser_linetype'); if strcmp(linetype, 'event') cursortext = sprintf('%s = %d\nt = %g s', getappdata(event_obj.Target, 'ft_databrowser_eventtype'), getappdata(event_obj.Target, 'ft_databrowser_eventvalue'), getappdata(event_obj.Target, 'ft_databrowser_eventtime')); elseif strcmp(linetype, 'channel') % get plotted x axis plottedX = get(event_obj.Target, 'xdata'); % determine values of data at real x axis timeAxis = getappdata(event_obj.Target, 'ft_databrowser_xaxis'); dataAxis = getappdata(event_obj.Target, 'ft_databrowser_yaxis'); tInd = nearest(plottedX, pos(1)); % get label chanLabel = getappdata(event_obj.Target, 'ft_databrowser_label'); chanLabel = chanLabel{1}; cursortext = sprintf('t = %g\n%s = %g', timeAxis(tInd), chanLabel, dataAxis(tInd)); else cursortext = '<no cursor available>'; % explicitly tell the user there is no info because the x-axis and % y-axis do not correspond to real data values (both are between 0 and % 1 always) end end % function datacursortext %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function winresize_cb(h,eventdata) % check whether the current figure is the browser if get(0,'currentFigure') ~= h return end % get opt, set flg for redrawing channels, redraw h = getparent(h); opt = getappdata(h, 'opt'); opt.changedchanflg = true; % trigger for redrawing channel labels and preparing layout again (see bug 2065 and 2878) setappdata(h, 'opt', opt); redraw_cb(h,eventdata); end % function datacursortext
github
lcnbeapp/beapp-master
ft_singleplotER.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_singleplotER.m
30,630
utf_8
b819e880153de426498ff70b6e529657
function [cfg] = ft_singleplotER(cfg, varargin) % FT_SINGLEPLOTER plots the event-related fields or potentials of a single % channel or the average over multiple channels. Multiple datasets can be % overlayed. % % Use as % ft_singleplotER(cfg, data) % or % ft_singleplotER(cfg, data1, data2, ..., datan) % % The data can be an erp/erf produced by FT_TIMELOCKANALYSIS, a power % spectrum produced by FT_FREQANALYSIS or connectivity spectrum produced by % FT_CONNECTIVITYANALYSIS. % % The configuration can have the following parameters: % cfg.parameter = field to be plotted on y-axis (default depends on data.dimord) % 'avg', 'powspctrm' or 'cohspctrm' % cfg.maskparameter = field in the first dataset to be used for masking of data % (not possible for mean over multiple channels, or when input contains multiple subjects % or trials) % cfg.maskstyle = style used for masking of data, 'box', 'thickness' or 'saturation' (default = 'box') % cfg.xlim = 'maxmin' or [xmin xmax] (default = 'maxmin') % cfg.ylim = 'maxmin', 'maxabs', 'zeromax', 'minzero', or [ymin ymax] (default = 'maxmin') % cfg.channel = nx1 cell-array with selection of channels (default = 'all'), % see ft_channelselection for details % cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui' % cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see ft_timelockbaseline % cfg.baselinetype = 'absolute' or 'relative' (default = 'absolute') % cfg.trials = 'all' or a selection given as a 1xn vector (default = 'all') % cfg.fontsize = font size of title (default = 8) % cfg.hotkeys = enables hotkeys (up/down/left/right arrows) for dynamic x/y axis translation (Ctrl+) and zoom adjustment % cfg.interactive = interactive plot 'yes' or 'no' (default = 'yes') % in a interactive plot you can select areas and produce a new % interactive plot when a selected area is clicked. multiple areas % can be selected by holding down the shift key. % cfg.renderer = 'painters', 'zbuffer',' opengl' or 'none' (default = []) % cfg.linestyle = linestyle/marker type, see options of the PLOT function (default = '-') % can be a single style for all datasets, or a cell-array containing one style for each dataset % cfg.linewidth = linewidth in points (default = 0.5) % cfg.graphcolor = color(s) used for plotting the dataset(s) (default = 'brgkywrgbkywrgbkywrgbkyw') % alternatively, colors can be specified as nx3 matrix of rgb values % cfg.directionality = '', 'inflow' or 'outflow' specifies for % connectivity measures whether the inflow into a % node, or the outflow from a node is plotted. The % (default) behavior of this option depends on the dimor % of the input data (see below). % % For the plotting of directional connectivity data the cfg.directionality % option determines what is plotted. The default value and the supported % functionality depend on the dimord of the input data. If the input data % is of dimord 'chan_chan_XXX', the value of directionality determines % whether, given the reference channel(s), the columns (inflow), or rows % (outflow) are selected for plotting. In this situation the default is % 'inflow'. Note that for undirected measures, inflow and outflow should % give the same output. If the input data is of dimord 'chancmb_XXX', the % value of directionality determines whether the rows in data.labelcmb are % selected. With 'inflow' the rows are selected if the refchannel(s) occur in % the right column, with 'outflow' the rows are selected if the % refchannel(s) occur in the left column of the labelcmb-field. Default in % this case is '', which means that all rows are selected in which the % refchannel(s) occur. This is to robustly support linearly indexed % undirected connectivity metrics. In the situation where undirected % connectivity measures are linearly indexed, specifying 'inflow' or % 'outflow' can result in unexpected behavior. % % to facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % if you specify this option the input data will be read from a *.mat % file on disk. this mat files should contain only a single variable named 'data', % corresponding to the input structure. % % See also FT_SINGLEPLOTTFR, FT_MULTIPLOTER, FT_MULTIPLOTTFR, FT_TOPOPLOTER, FT_TOPOPLOTTFR % Undocumented local options: % cfg.zlim/xparam (set to a specific frequency range or time range [zmax zmin] for an average % over the frequency/time bins for TFR data. Use in conjunction with e.g. xparam = 'time', and cfg.parameter = 'powspctrm'). % cfg.preproc % Copyright (C) 2003-2006, Ole Jensen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar varargin ft_preamble provenance varargin ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'unused', {'cohtargetchannel'}); cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'}); cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedforward', 'outflow'}); cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedback', 'inflow'}); cfg = ft_checkconfig(cfg, 'renamed', {'matrixside', 'directionality'}); cfg = ft_checkconfig(cfg, 'renamed', {'channelindex', 'channel'}); cfg = ft_checkconfig(cfg, 'renamed', {'channelname', 'channel'}); cfg = ft_checkconfig(cfg, 'renamed', {'cohrefchannel', 'refchannel'}); cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'parameter'}); cfg = ft_checkconfig(cfg, 'deprecated', {'xparam'}); % set the defaults cfg.baseline = ft_getopt(cfg, 'baseline', 'no'); cfg.trials = ft_getopt(cfg, 'trials', 'all', 1); cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin'); cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin'); cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin'); cfg.comment = ft_getopt(cfg, 'comment', strcat([date '\n'])); cfg.axes = ft_getopt(cfg,' axes', 'yes'); cfg.fontsize = ft_getopt(cfg, 'fontsize', 8); cfg.graphcolor = ft_getopt(cfg, 'graphcolor', 'brgkywrgbkywrgbkywrgbkyw'); cfg.hotkeys = ft_getopt(cfg, 'hotkeys', 'no'); cfg.interactive = ft_getopt(cfg, 'interactive', 'yes'); cfg.renderer = ft_getopt(cfg, 'renderer', []); cfg.maskparameter = ft_getopt(cfg, 'maskparameter',[]); cfg.linestyle = ft_getopt(cfg, 'linestyle', '-'); cfg.linewidth = ft_getopt(cfg, 'linewidth', 0.5); cfg.maskstyle = ft_getopt(cfg, 'maskstyle', 'box'); cfg.channel = ft_getopt(cfg, 'channel', 'all'); cfg.directionality = ft_getopt(cfg, 'directionality', []); cfg.figurename = ft_getopt(cfg, 'figurename', []); cfg.preproc = ft_getopt(cfg, 'preproc', []); cfg.frequency = ft_getopt(cfg, 'frequency', 'all'); % needed for frequency selection with TFR data cfg.latency = ft_getopt(cfg, 'latency', 'all'); % needed for latency selection with TFR data, FIXME, probably not used Ndata = numel(varargin); % interactive plotting is not allowed with more than 1 input % if Ndata >1 && strcmp(cfg.interactive, 'yes') % error('interactive plotting is not supported with more than 1 input data set'); % end % FIXME rename directionality and cohrefchannel in more meaningful options if ischar(cfg.graphcolor) graphcolor = ['k' cfg.graphcolor]; elseif isnumeric(cfg.graphcolor) graphcolor = [0 0 0; cfg.graphcolor]; end % check for linestyle being a cell-array, check it's length, and lengthen it if does not have enough styles in it if ischar(cfg.linestyle) cfg.linestyle = {cfg.linestyle}; end if Ndata > 1 if (length(cfg.linestyle) < Ndata ) && (length(cfg.linestyle) > 1) error('either specify cfg.linestyle as a cell-array with one cell for each dataset, or only specify one linestyle') elseif (length(cfg.linestyle) < Ndata ) && (length(cfg.linestyle) == 1) tmpstyle = cfg.linestyle{1}; cfg.linestyle = cell(Ndata , 1); for idataset = 1:Ndata cfg.linestyle{idataset} = tmpstyle; end end end % ensure that the input is correct, also backward compatibility with old data structures: dtype = cell(Ndata, 1); for i=1:Ndata % check if the input data is valid for this function varargin{i} = ft_checkdata(varargin{i}, 'datatype', {'timelock', 'freq'}); dtype{i} = ft_datatype(varargin{i}); % this is needed for correct treatment of graphcolor later on if nargin>1, if ~isempty(inputname(i+1)) iname{i+1} = inputname(i+1); else iname{i+1} = ['input',num2str(i,'%02d')]; end else iname{i+1} = cfg.inputfile{i}; end end if Ndata >1, if ~all(strcmp(dtype{1}, dtype)) error('input data are of different type; this is not supported'); end end dtype = dtype{1}; dimord = varargin{1}.dimord; dimtok = tokenize(dimord, '_'); % ensure that the preproc specific options are located in the cfg.preproc % substructure, but also ensure that the field 'refchannel' is present at the % highest level in the structure. This is a little hack by JM because the field % refchannel can also refer to the plotting of a connectivity metric. Also, % the freq2raw conversion does not work at all in the call to ft_preprocessing. % Therefore, for now, the preprocessing will not be done when there is freq % data in the input. A more generic solution should be considered. if isfield(cfg, 'refchannel'), refchannelincfg = cfg.refchannel; end if ~any(strcmp({'freq','freqmvar'},dtype)), cfg = ft_checkconfig(cfg, 'createsubcfg', {'preproc'}); end if exist('refchannelincfg', 'var'), cfg.refchannel = refchannelincfg; end if ~isempty(cfg.preproc) % preprocess the data, i.e. apply filtering, baselinecorrection, etc. fprintf('applying preprocessing options\n'); if ~isfield(cfg.preproc, 'feedback') cfg.preproc.feedback = cfg.interactive; end for i=1:Ndata varargin{i} = ft_preprocessing(cfg.preproc, varargin{i}); end end % set x/y/parameter defaults according to datatype and dimord switch dtype case 'timelock' xparam = 'time'; yparam = ''; cfg.parameter = ft_getopt(cfg, 'parameter', 'avg'); case 'freq' if sum(ismember(dimtok, 'time')) xparam = 'time'; yparam = 'freq'; cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm'); elseif sum(ismember(dimtok, 'time')) xparam = 'freq'; yparam = 'time'; cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm'); else xparam = 'freq'; yparam = ''; cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm'); end case 'comp' % not supported otherwise % not supported end % user specified own fields, but no yparam (which is not asked in help) if exist('xparam', 'var') && isfield(cfg, 'parameter') && ~exist('yparam', 'var') yparam = ''; end if isfield(cfg, 'channel') && isfield(varargin{1}, 'label') cfg.channel = ft_channelselection(cfg.channel, varargin{1}.label); elseif isfield(cfg, 'channel') && isfield(varargin{1}, 'labelcmb') cfg.channel = ft_channelselection(cfg.channel, unique(varargin{1}.labelcmb(:))); end % check whether rpt/subj is present and remove if necessary and whether hasrpt = sum(ismember(dimtok, {'rpt' 'subj'})); if strcmp(dtype, 'timelock') && hasrpt, tmpcfg = []; tmpcfg.trials = cfg.trials; for i=1:Ndata varargin{i} = ft_timelockanalysis(tmpcfg, varargin{i}); end if ~strcmp(cfg.parameter, 'avg') % rename avg back into the parameter varargin{i}.(cfg.parameter) = varargin{i}.avg; varargin{i} = rmfield(varargin{i}, 'avg'); end dimord = varargin{1}.dimord; dimtok = tokenize(dimord, '_'); elseif strcmp(dtype, 'freq') && hasrpt, % this also deals with fourier-spectra in the input % or with multiple subjects in a frequency domain stat-structure % on the fly computation of coherence spectrum is not supported for i=1:Ndata if isfield(varargin{i}, 'crsspctrm'), varargin{i} = rmfield(varargin{i}, 'crsspctrm'); end end tmpcfg = []; tmpcfg.trials = cfg.trials; tmpcfg.jackknife = 'no'; for i=1:Ndata if isfield(cfg, 'parameter') && ~strcmp(cfg.parameter,'powspctrm') % freqdesctiptives will only work on the powspctrm field % hence a temporary copy of the data is needed tempdata.dimord = varargin{i}.dimord; tempdata.freq = varargin{i}.freq; tempdata.label = varargin{i}.label; tempdata.powspctrm = varargin{i}.(cfg.parameter); if isfield(varargin{i}, 'cfg') tempdata.cfg = varargin{i}.cfg; end tempdata = ft_freqdescriptives(tmpcfg, tempdata); varargin{i}.(cfg.parameter) = tempdata.powspctrm; clear tempdata else varargin{i} = ft_freqdescriptives(tmpcfg, varargin{i}); end end dimord = varargin{1}.dimord; dimtok = tokenize(dimord, '_'); end % apply baseline correction if ~strcmp(cfg.baseline, 'no') for i=1:Ndata if strcmp(dtype, 'timelock') && strcmp(xparam, 'time') varargin{i} = ft_timelockbaseline(cfg, varargin{i}); elseif strcmp(dtype, 'freq') && strcmp(xparam, 'time') varargin{i} = ft_freqbaseline(cfg, varargin{i}); elseif strcmp(dtype, 'freq') && strcmp(xparam, 'freq') error('baseline correction is not supported for spectra without a time dimension'); else warning('baseline correction not applied, please set xparam'); end end end % handle the bivariate case % check for bivariate metric with 'chan_chan' in the dimord selchan = strmatch('chan', dimtok); isfull = length(selchan)>1; % check for bivariate metric with a labelcmb haslabelcmb = isfield(varargin{1}, 'labelcmb'); if (isfull || haslabelcmb) && (isfield(varargin{1}, cfg.parameter) && ~strcmp(cfg.parameter, 'powspctrm')) % a reference channel is required: if ~isfield(cfg, 'refchannel') error('no reference channel is specified'); end % check for refchannel being part of selection if ~strcmp(cfg.refchannel,'gui') if haslabelcmb cfg.refchannel = ft_channelselection(cfg.refchannel, unique(varargin{1}.labelcmb(:))); else cfg.refchannel = ft_channelselection(cfg.refchannel, varargin{1}.label); end if (isfull && ~any(ismember(varargin{1}.label, cfg.refchannel))) || ... (haslabelcmb && ~any(ismember(varargin{1}.labelcmb(:), cfg.refchannel))) error('cfg.refchannel is a not present in the (selected) channels)') end end % interactively select the reference channel if strcmp(cfg.refchannel, 'gui') error('cfg.refchannel = ''gui'' is not supported in ft_singleplotER'); end for i=1:Ndata if ~isfull, % convert 2-dimensional channel matrix to a single dimension: if isempty(cfg.directionality) sel1 = find(strcmp(cfg.refchannel, varargin{i}.labelcmb(:,2))); sel2 = find(strcmp(cfg.refchannel, varargin{i}.labelcmb(:,1))); elseif strcmp(cfg.directionality, 'outflow') sel1 = []; sel2 = find(strcmp(cfg.refchannel, varargin{i}.labelcmb(:,1))); elseif strcmp(cfg.directionality, 'inflow') sel1 = find(strcmp(cfg.refchannel, varargin{i}.labelcmb(:,2))); sel2 = []; end fprintf('selected %d channels for %s\n', length(sel1)+length(sel2), cfg.parameter); if length(sel1)+length(sel2)==0 error('there are no channels selected for plotting: you may need to look at the specification of cfg.directionality'); end varargin{i}.(cfg.parameter) = varargin{i}.(cfg.parameter)([sel1;sel2],:,:); varargin{i}.label = [varargin{i}.labelcmb(sel1,1);varargin{i}.labelcmb(sel2,2)]; varargin{i}.labelcmb = varargin{i}.labelcmb([sel1;sel2],:); varargin{i} = rmfield(varargin{i}, 'labelcmb'); else % general case sel = match_str(varargin{i}.label, cfg.refchannel); siz = [size(varargin{i}.(cfg.parameter)) 1]; if strcmp(cfg.directionality, 'inflow') || isempty(cfg.directionality) %the interpretation of 'inflow' and 'outflow' depend on %the definition in the bivariate representation of the data %data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(:,sel,:),2),[siz(1) 1 siz(3:end)]); sel1 = 1:siz(1); sel2 = sel; meandir = 2; elseif strcmp(cfg.directionality, 'outflow') %data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(sel,:,:),1),[siz(1) 1 siz(3:end)]); sel1 = sel; sel2 = 1:siz(1); meandir = 1; elseif strcmp(cfg.directionality, 'ff-fd') error('cfg.directionality = ''ff-fd'' is not supported anymore, you have to manually subtract the two before the call to ft_singleplotER'); elseif strcmp(cfg.directionality, 'fd-ff') error('cfg.directionality = ''fd-ff'' is not supported anymore, you have to manually subtract the two before the call to ft_singleplotER'); end %if directionality end %if ~isfull end %for i end %handle the bivariate data % get physical min/max range of x if strcmp(cfg.xlim,'maxmin') % find maxmin throughout all varargins: xmin = []; xmax = []; for i=1:Ndata xmin = min([xmin varargin{i}.(xparam)]); xmax = max([xmax varargin{i}.(xparam)]); end else xmin = cfg.xlim(1); xmax = cfg.xlim(2); end % get the index of the nearest bin for i=1:Ndata xidmin(i,1) = nearest(varargin{i}.(xparam), xmin); xidmax(i,1) = nearest(varargin{i}.(xparam), xmax); end if strcmp('freq', yparam) && strcmp('freq', dtype) tmpcfg = keepfields(cfg, {'parameter'}); tmpcfg.avgoverfreq = 'yes'; tmpcfg.frequency = cfg.frequency;%cfg.zlim; [varargin{:}] = ft_selectdata(tmpcfg, varargin{:}); % restore the provenance information [cfg, varargin{:}] = rollback_provenance(cfg, varargin{:}); elseif strcmp('time', yparam) && strcmp('freq', dtype) tmpcfg = keepfields(cfg, {'parameter'}); tmpcfg.avgovertime = 'yes'; tmpcfg.latency = cf.latency;%cfg.zlim; [varargin{:}] = ft_selectdata(tmpcfg, varargin{:}); % restore the provenance information [cfg, varargin{:}] = rollback_provenance(cfg, varargin{:}); end cla hold on; colorlabels = []; % plot each data set: for i=1:Ndata if isfield(varargin{1}, 'label') selchannel = ft_channelselection(cfg.channel, varargin{i}.label); elseif isfield(varargin{1}, 'labelcmb') selchannel = ft_channelselection(cfg.channel, unique(varargin{i}.labelcmb(:))); else error('the input data does not contain a label or labelcmb-field'); end % make vector dat with one value for each channel dat = varargin{i}.(cfg.parameter); % get dimord dimensions dims = textscan(varargin{i}.dimord,'%s', 'Delimiter', '_'); dims = dims{1}; ydim = find(strcmp(yparam, dims)); xdim = find(strcmp(xparam, dims)); zdim = setdiff(1:ndims(dat), [ydim xdim]); % and permute to make sure that dimensions are in the correct order dat = permute(dat, [zdim(:)' ydim xdim]); xval = varargin{i}.(xparam); % take subselection of channels % this works for bivariate data with labelcmb because at this point the % data has a label-field sellab = match_str(varargin{i}.label, selchannel); % if ~isempty(yparam) % if isfull % dat = dat(sel1, sel2, ymin:ymax, xidmin(i):xidmax(i)); % dat = nanmean(nanmean(dat, meandir), 3); % siz = size(dat); % %fixmedat = reshape(dat, [siz(1:2) siz(4)]); % dat = reshape(dat, [siz(1) siz(3)]); % dat = dat(sellab, :); % elseif haslabelcmb % dat = dat(sellab, ymin:ymax, xidmin(i):xidmax(i)); % dat = nanmean(dat, 2); % siz = size(dat); % dat = reshape(dat, [siz(1) siz(3)]); % else % dat = dat(sellab, ymin:ymax, xidmin(i):xidmax(i)); % dat = nanmean(nanmean(dat, 3), 2); % siz = size(dat); % dat = reshape(dat, [siz(1) siz(3)]); % end % else if isfull dat = dat(sel1, sel2, xidmin(i):xidmax(i)); dat = nanmean(dat, meandir); siz = size(dat); siz(find(siz(1:2)==1)) = []; dat = reshape(dat, siz); dat = dat(sellab, :); elseif haslabelcmb dat = dat(sellab, xidmin(i):xidmax(i)); else dat = dat(sellab, xidmin(i):xidmax(i)); end % end xval = xval(xidmin(i):xidmax(i)); datavector = reshape(mean(dat, 1), [1 numel(xval)]); % average over channels % make mask if ~isempty(cfg.maskparameter) datmask = varargin{i}.(cfg.maskparameter)(sellab,:); if size(datmask,2)>1 datmask = datmask(:,xidmin(i):xidmax(i)); else datmask = datmask(xidmin(i):xidmax(i)); end maskdatavector = reshape(mean(datmask,1), [1 numel(xval)]); else maskdatavector = []; end if Ndata > 1 if ischar(graphcolor); colorlabels = [colorlabels iname{i+1} '=' graphcolor(i+1) '\n']; elseif isnumeric(graphcolor); colorlabels = [colorlabels iname{i+1} '=' num2str(graphcolor(i+1,:)) '\n']; end end if ischar(graphcolor); color = graphcolor(i+1); elseif isnumeric(graphcolor); color = graphcolor(i+1,:); end % update ymin and ymax for the current data set: if ischar(cfg.ylim) if i==1 ymin = []; ymax = []; end if strcmp(cfg.ylim,'maxmin') % select the channels in the data that match with the layout: ymin = min([ymin min(datavector)]); ymax = max([ymax max(datavector)]); elseif strcmp(cfg.ylim,'maxabs') ymax = max([ymax max(abs(datavector))]); ymin = -ymax; elseif strcmp(cfg.ylim,'zeromax') ymin = 0; ymax = max([ymax max(datavector)]); elseif strcmp(cfg.ylim,'minzero') ymin = min([ymin min(datavector)]); ymax = 0; end; else ymin = cfg.ylim(1); ymax = cfg.ylim(2); end % only plot the mask once, for the first line (it's the same anyway for % all lines, and if plotted multiple times, it will overlay the others if i>1 && strcmp(cfg.maskstyle, 'box') ft_plot_vector(xval, datavector, 'style', cfg.linestyle{i}, 'color', color, ... 'linewidth', cfg.linewidth, 'hlim', cfg.xlim, 'vlim', cfg.ylim); else ft_plot_vector(xval, datavector, 'style', cfg.linestyle{i}, 'color', color, ... 'highlight', maskdatavector, 'highlightstyle', cfg.maskstyle, 'linewidth', cfg.linewidth, ... 'hlim', cfg.xlim, 'vlim', cfg.ylim); end end % set xlim and ylim: xlim([xmin xmax]); ylim([ymin ymax]); % adjust mask box extents to ymin/ymax if ~isempty(cfg.maskparameter) ptchs = findobj(gcf,'type','patch'); for i = 1:length(ptchs) YData = get(ptchs(i),'YData'); YData(YData == min(YData)) = ymin; YData(YData == max(YData)) = ymax; set(ptchs(i),'YData',YData); end end if strcmp('yes',cfg.hotkeys) % attach data and cfg to figure and attach a key listener to the figure set(gcf, 'keypressfcn', {@key_sub, xmin, xmax, ymin, ymax}) end if isfield(cfg, 'dataname') dataname = cfg.dataname; elseif nargin > 1 dataname = inputname(2); cfg.dataname = {inputname(2)}; for k = 2:Ndata dataname = [dataname ', ' inputname(k+1)]; cfg.dataname{end+1} = inputname(k+1); end else dataname = cfg.inputfile; end % set the figure window title, add the channel labels if number is small if isempty(get(gcf,'Name')) if length(sellab) < 5 chans = join_str(',', cfg.channel); else chans = '<multiple channels>'; end if isempty(cfg.figurename) set(gcf, 'Name', sprintf('%d: %s: %s (%s)', double(gcf), mfilename, join_str(', ',dataname), chans)); set(gcf, 'NumberTitle', 'off'); else set(gcf, 'name', cfg.figurename); set(gcf, 'NumberTitle', 'off'); end end % make the figure interactive if strcmp(cfg.interactive, 'yes') % add the dataname to the figure % this is used in the callbacks info = guidata(gcf); info.dataname = dataname; guidata(gcf, info); % attach data to the figure with the current axis handle as a name dataname = fixname(num2str(double(gca))); setappdata(gcf,dataname,varargin); set(gcf, 'windowbuttonupfcn', {@ft_select_range, 'multiple', false, 'yrange', false, 'callback', {@select_topoplotER, cfg}, 'event', 'windowbuttonupfcn'}); set(gcf, 'windowbuttondownfcn', {@ft_select_range, 'multiple', false, 'yrange', false, 'callback', {@select_topoplotER, cfg}, 'event', 'windowbuttondownfcn'}); set(gcf, 'windowbuttonmotionfcn', {@ft_select_range, 'multiple', false, 'yrange', false, 'callback', {@select_topoplotER, cfg}, 'event', 'windowbuttonmotionfcn'}); end % create title text containing channel name(s) and channel number(s): if length(sellab) == 1 t = [char(cfg.channel) ' / ' num2str(sellab) ]; else t = sprintf('mean(%0s)', join_str(',', cfg.channel)); end h = title(t,'fontsize', cfg.fontsize); % set renderer if specified if ~isempty(cfg.renderer) set(gcf, 'renderer', cfg.renderer) end if false % FIXME this is for testing purposes % Define a context menu; it is not attached to anything cmlines = uicontextmenu; % Define the context menu items and install their callbacks uimenu(cmlines, 'Label', 'dashed', 'Callback', 'set(gco, ''LineStyle'', ''--'')'); uimenu(cmlines, 'Label', 'dotted', 'Callback', 'set(gco, ''LineStyle'', '':'')'); uimenu(cmlines, 'Label', 'solid', 'Callback', 'set(gco, ''LineStyle'', ''-'')'); % Locate line objects hlines = findall(gca, 'Type', 'line'); % Attach the context menu to each line for line = 1:length(hlines) set(hlines(line), 'uicontextmenu', cmlines) end end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous varargin ft_postamble provenance % add a menu to the figure, but only if the current figure does not have subplots % also, delete any possibly existing previous menu, this is safe because delete([]) does nothing delete(findobj(gcf, 'type', 'uimenu', 'label', 'FieldTrip')); if numel(findobj(gcf, 'type', 'axes', '-not', 'tag', 'ft-colorbar')) <= 1 ftmenu = uimenu(gcf, 'Label', 'FieldTrip'); uimenu(ftmenu, 'Label', 'Show pipeline', 'Callback', {@menu_pipeline, cfg}); uimenu(ftmenu, 'Label', 'About', 'Callback', @menu_about); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION which is called after selecting a time range %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function select_topoplotER(cfg, varargin) % first to last callback-input of ft_select_range is range % last callback-input of ft_select_range is contextmenu label, if used range = varargin{end-1}; varargin = varargin(1:end-2); % remove range and last % get appdata belonging to current axis dataname = fixname(num2str(double(gca))); data = getappdata(gcf, dataname); if isfield(cfg, 'inputfile') % the reading has already been done and varargin contains the data cfg = rmfield(cfg, 'inputfile'); end if isfield(cfg, 'showlabels') % this is not allowed in topoplotER cfg = rmfield(cfg, 'showlabels'); end % make sure the topo displays all channels, not just the ones in this singleplot cfg.channel = 'all'; cfg.comment = 'auto'; cfg.xlim = range(1:2); % put data name in here, this cannot be resolved by other means info = guidata(gcf); cfg.dataname = info.dataname; % if user specified a ylim, copy it over to the zlim of topoplot if isfield(cfg, 'ylim') cfg.zlim = cfg.ylim; cfg = rmfield(cfg, 'ylim'); end fprintf('selected cfg.xlim = [%f %f]\n', cfg.xlim(1), cfg.xlim(2)); p = get(gcf, 'position'); f = figure; set(f, 'position', p); ft_topoplotER(cfg, data{:}); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION which handles hot keys in the current plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key_sub(handle, eventdata, varargin) xlimits = xlim; ylimits = ylim; incr_x = abs(xlimits(2) - xlimits(1)) /10; incr_y = abs(ylimits(2) - ylimits(1)) /10; % TRANSLATE by 10% if length(eventdata.Modifier) == 1 && strcmp(eventdata.Modifier{:},'control') && strcmp(eventdata.Key,'leftarrow') xlim([xlimits(1)+incr_x xlimits(2)+incr_x]) elseif length(eventdata.Modifier) == 1 && strcmp(eventdata.Modifier{:},'control') && strcmp(eventdata.Key,'rightarrow') xlim([xlimits(1)-incr_x xlimits(2)-incr_x]) elseif length(eventdata.Modifier) == 1 && strcmp(eventdata.Modifier{:},'control') && strcmp(eventdata.Key,'uparrow') ylim([ylimits(1)-incr_y ylimits(2)-incr_y]) elseif length(eventdata.Modifier) == 1 && strcmp(eventdata.Modifier{:},'control') && strcmp(eventdata.Key,'downarrow') ylim([ylimits(1)+incr_y ylimits(2)+incr_y]) % ZOOM by 10% elseif strcmp(eventdata.Key,'leftarrow') xlim([xlimits(1)-incr_x xlimits(2)+incr_x]) elseif strcmp(eventdata.Key,'rightarrow') xlim([xlimits(1)+incr_x xlimits(2)-incr_x]) elseif strcmp(eventdata.Key,'uparrow') ylim([ylimits(1)-incr_y ylimits(2)+incr_y]) elseif strcmp(eventdata.Key,'downarrow') ylim([ylimits(1)+incr_y ylimits(2)-incr_y]) % resort to minmax of data for x-axis and y-axis elseif strcmp(eventdata.Key,'m') xlim([varargin{1} varargin{2}]) ylim([varargin{3} varargin{4}]) end
github
lcnbeapp/beapp-master
ft_mvaranalysis.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_mvaranalysis.m
21,401
utf_8
88f54e5e33f474697f30b35bf0c74510
function [mvardata] = ft_mvaranalysis(cfg, data) % FT_MVARANALYSIS performs multivariate autoregressive modeling on % time series data over multiple trials. % % Use as % [mvardata] = ft_mvaranalysis(cfg, data) % % The input data should be organised in a structure as obtained from % the FT_PREPROCESSING function. The configuration depends on the type % of computation that you want to perform. % The output is a data structure of datatype 'mvar' which contains the % multivariate autoregressive coefficients in the field coeffs, and the % covariance of the residuals in the field noisecov. % % The configuration should contain: % cfg.toolbox = the name of the toolbox containing the function for the % actual computation of the ar-coefficients % this can be 'biosig' (default) or 'bsmart' % you should have a copy of the specified toolbox in order % to use mvaranalysis (both can be downloaded directly). % cfg.mvarmethod = scalar (only required when cfg.toolbox = 'biosig'). % default is 2, relates to the algorithm used for the % computation of the AR-coefficients by mvar.m % cfg.order = scalar, order of the autoregressive model (default=10) % cfg.channel = 'all' (default) or list of channels for which an mvar model % is fitted. (Do NOT specify if cfg.channelcmb is % defined) % cfg.channelcmb = specify channel combinations as a % two-column cell array with channels in each column between % which a bivariate model will be fit (overrides % cfg.channel) % cfg.keeptrials = 'no' (default) or 'yes' specifies whether the coefficients % are estimated for each trial seperately, or on the % concatenated data % cfg.jackknife = 'no' (default) or 'yes' specifies whether the coefficients % are estimated for all leave-one-out sets of trials % cfg.zscore = 'no' (default) or 'yes' specifies whether the channel data % are z-transformed prior to the model fit. This may be % necessary if the magnitude of the signals is very different % e.g. when fitting a model to combined MEG/EMG data % cfg.demean = 'yes' (default) or 'no' explicit removal of DC-offset % cfg.ems = 'no' (default) or 'yes' explicit removal ensemble mean % % ft_mvaranalysis can be used to obtain one set of coefficients across % all time points in the data, also when the trials are of varying length. % % ft_mvaranalysis can be also used to obtain time-dependent sets of % coefficients based on a sliding window. In this case the input cfg % should contain: % % cfg.t_ftimwin = the width of the sliding window on which the coefficients % are estimated % cfg.toi = [t1 t2 ... tx] the time points at which the windows are % centered % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % cfg.outputfile = ... % If you specify one of these (or both) the input data will be read from a *.mat % file on disk and/or the output data will be written to a *.mat file. These mat % files should contain only a single variable, corresponding with the % input/output structure. % % See also FT_PREPROCESSING, FT_SOURCESTATISTICS, FT_FREQSTATISTICS, % FT_TIMELOCKSTATISTICS % Undocumented local options: % cfg.keeptapers % cfg.taper % cfg.output = 'parameters', 'model', 'residual'. If 'parameters' is % specified, the output is a mdata data structure, containing the % coefficients and the noise covariance. If 'model' or 'residual' is % specified, the output is a data structure containing either the % modeled time series, or the residuals. This is only supported when % the model is estimated across the whole time range. % Copyright (C) 2009, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar data ft_preamble provenance data ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input data is valid for this function data = ft_checkdata(data, 'datatype', 'raw', 'hassampleinfo', 'yes'); % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'renamed', {'blc', 'demean'}); cfg = ft_checkconfig(cfg, 'renamed', {'blcwindow', 'baselinewindow'}); % set default configuration options cfg.toolbox = ft_getopt(cfg, 'toolbox', 'biosig'); cfg.mvarmethod = ft_getopt(cfg, 'mvarmethod', 2); % only relevant for biosig cfg.order = ft_getopt(cfg, 'order', 10); cfg.channel = ft_getopt(cfg, 'channel', 'all'); cfg.keeptrials = ft_getopt(cfg, 'keeptrials', 'no'); cfg.jackknife = ft_getopt(cfg, 'jackknife', 'no'); cfg.zscore = ft_getopt(cfg, 'zscore', 'no'); cfg.feedback = ft_getopt(cfg, 'feedback', 'textbar'); cfg.demean = ft_getopt(cfg, 'demean', 'yes'); cfg.ems = ft_getopt(cfg, 'ems', 'no'); cfg.toi = ft_getopt(cfg, 'toi', []); cfg.t_ftimwin = ft_getopt(cfg, 't_ftimwin', []); cfg.keeptapers = ft_getopt(cfg, 'keeptapers', 'yes'); cfg.taper = ft_getopt(cfg, 'taper', 'rectwin'); cfg.univariate = ft_getopt(cfg, 'univariate', 0); cfg.output = ft_getopt(cfg, 'output', 'parameters'); % check that cfg.channel and cfg.channelcmb are not both specified if ~any(strcmp(cfg.channel, 'all')) && isfield(cfg, 'channelcmb') ft_warning('cfg.channelcmb defined, overriding cfg.channel setting and computing over bivariate pairs'); else % select trials of interest tmpcfg = []; tmpcfg.channel = cfg.channel; data = ft_selectdata(tmpcfg, data); % restore the provenance information [cfg, data] = rollback_provenance(cfg, data); end % check whether the requested toolbox is present and check the configuration switch cfg.toolbox case 'biosig' % check the configuration cfg = ft_checkconfig(cfg, 'required', 'mvarmethod'); ft_hastoolbox('biosig', 1); nnans = cfg.order; case 'bsmart' ft_hastoolbox('bsmart', 1); nnans = 0; otherwise error('toolbox %s is not yet supported', cfg.toolbox); end if isempty(cfg.toi) && isempty(cfg.t_ftimwin) % fit model to entire data segment % check whether this is allowed nsmp = cellfun('size', data.trial, 2); if all(nsmp==nsmp(1)); oktoolbox = {'bsmart' 'biosig'}; else oktoolbox = 'biosig'; % bsmart does not work with variable trials end if ~ismember(cfg.toolbox, oktoolbox), error('fitting the mvar-model is not possible with the ''%s'' toolbox',cfg.toolbox); end latency = [-inf inf]; elseif ~isempty(cfg.toi) && ~isempty(cfg.t_ftimwin) % do sliding window approach for k = 1:numel(cfg.toi) latency(k,:) = cfg.toi + cfg.t_ftimwin.*[-0.5 0.5]; end else error('cfg should contain both cfg.toi and cfg.t_ftimwin'); end keeprpt = istrue(cfg.keeptrials); keeptap = istrue(cfg.keeptapers); dojack = istrue(cfg.jackknife); dozscore = istrue(cfg.zscore); dobvar = isfield(cfg, 'channelcmb'); dounivariate = istrue(cfg. univariate); if ~keeptap, error('not keeping tapers is not possible yet'); end if dojack && keeprpt, error('you cannot simultaneously keep trials and do jackknifing'); end tfwin = round(data.fsample.*cfg.t_ftimwin); ntrl = length(data.trial); ntoi = size(latency, 1); if ~dobvar chanindx = match_str(data.label, cfg.channel); nchan = length(chanindx); label = data.label(chanindx); ncmb = nchan*nchan; cmbindx1 = repmat(chanindx(:), [1 nchan]); cmbindx2 = repmat(chanindx(:)', [nchan 1]); labelcmb = [data.label(cmbindx1(:)) data.label(cmbindx2(:))]; else cfg.channelcmb = ft_channelcombination(cfg.channelcmb, data.label); cmbindx = zeros(size(cfg.channelcmb)); for k = 1:size(cmbindx,1) [tmp, cmbindx(k,:)] = match_str(cfg.channelcmb(k,:)', data.label); end nchan = 2; label = data.label(cmbindx); ncmb = nchan*nchan; labelcmb = cell(0,2); cmb = cfg.channelcmb; for k = 1:size(cmbindx,1) labelcmb{end+1,1} = [cmb{k,1},'[',cmb{k,1},cmb{k,2},']']; labelcmb{end ,2} = [cmb{k,1},'[',cmb{k,1},cmb{k,2},']']; labelcmb{end+1,1} = [cmb{k,2},'[',cmb{k,1},cmb{k,2},']']; labelcmb{end ,2} = [cmb{k,1},'[',cmb{k,1},cmb{k,2},']']; labelcmb{end+1,1} = [cmb{k,1},'[',cmb{k,1},cmb{k,2},']']; labelcmb{end ,2} = [cmb{k,2},'[',cmb{k,1},cmb{k,2},']']; labelcmb{end+1,1} = [cmb{k,2},'[',cmb{k,1},cmb{k,2},']']; labelcmb{end ,2} = [cmb{k,2},'[',cmb{k,1},cmb{k,2},']']; end end %---think whether this makes sense at all if strcmp(cfg.taper, 'dpss') % create a sequence of DPSS (Slepian) tapers % ensure that the input arguments are double precision tap = double_dpss(tfwin,tfwin*(cfg.tapsmofrq./data.fsample))'; tap = tap(1,:); %only use first 'zero-order' taper elseif strcmp(cfg.taper, 'sine') tap = sine_taper(tfwin, tfwin*(cfg.tapsmofrq./data.fsample))'; tap = tap(1,:); else tap = window(cfg.taper, tfwin)'; tap = tap./norm(tap); end ntap = size(tap,1); %---preprocess data if necessary -> changed 20150224, JM does not think %this step is necessary: it creates problems downstream if the time axes of %the trials are different %---cut off the uninteresting data segments %tmpcfg = []; %tmpcfg.toilim = cfg.toi([1 end]) + cfg.t_ftimwin.*[-0.5 0.5]; %data = ft_redefinetrial(tmpcfg, data); %---demean if strcmp(cfg.demean, 'yes'), tmpcfg = []; tmpcfg.demean = 'yes'; tmpcfg.baselinewindow = latency([1 end]); data = ft_preprocessing(tmpcfg, data); else %do nothing end %---ensemble mean subtraction if strcmp(cfg.ems, 'yes') % to be implemented error('ensemble mean subtraction is not yet implemented here'); end %---zscore if dozscore, zwindow = latency([1 end]); sumval = 0; sumsqr = 0; numsmp = 0; trlindx = []; for k = 1:ntrl begsmp = nearest(data.time{k}, zwindow(1)); endsmp = nearest(data.time{k}, zwindow(2)); if endsmp>=begsmp, sumval = sumval + sum(data.trial{k}(:, begsmp:endsmp), 2); sumsqr = sumsqr + sum(data.trial{k}(:, begsmp:endsmp).^2, 2); numsmp = numsmp + endsmp - begsmp + 1; trlindx = [trlindx; k]; end end datavg = sumval./numsmp; datstd = sqrt(sumsqr./numsmp - (sumval./numsmp).^2); data.trial = data.trial(trlindx); data.time = data.time(trlindx); ntrl = length(trlindx); for k = 1:ntrl rvec = ones(1,size(data.trial{k},2)); data.trial{k} = (data.trial{k} - datavg*rvec)./(datstd*rvec); end else %do nothing end %---generate time axis maxtim = -inf; mintim = inf; for k = 1:ntrl maxtim = max(maxtim, data.time{k}(end)); mintim = min(mintim, data.time{k}(1)); end timeaxis = mintim:1/data.fsample:maxtim; %---allocate memory if dobvar && (keeprpt || dojack) % not yet implemented error('doing bivariate model fits in combination with multiple replicates is not yet possible'); elseif dobvar coeffs = zeros(1, size(cmbindx,1), 2*nchan, cfg.order, ntoi, ntap); noisecov = zeros(1, size(cmbindx,1), 2*nchan, ntoi, ntap); elseif dounivariate && (keeprpt || dojack) error('doing univariate model fits in combination with multiple replicates is not yet possible'); elseif dounivariate coeffs = zeros(1, nchan, cfg.order, ntoi, ntap); noisecov = zeros(1, nchan, ntoi, ntap); elseif (keeprpt || dojack) coeffs = zeros(length(data.trial), nchan, nchan, cfg.order, ntoi, ntap); noisecov = zeros(length(data.trial), nchan, nchan, ntoi, ntap); else coeffs = zeros(1, nchan, nchan, cfg.order, ntoi, ntap); noisecov = zeros(1, nchan, nchan, ntoi, ntap); end %---loop over the tois ft_progress('init', cfg.feedback, 'computing AR-model'); for j = 1:ntoi if ~isequal(latency(j,:),[-inf inf]) ft_progress(j/ntoi, 'processing timewindow %d from %d\n', j, ntoi); tmpcfg = []; tmpcfg.toilim = latency(j,:); tmpdata = ft_redefinetrial(tmpcfg, data); else tmpdata = data; end tmpnsmp = cellfun('size', tmpdata.trial, 2); if ntoi>1 && strcmp(cfg.toolbox, 'bsmart') % ensure all segments to be of equal length if ~all(tmpnsmp==tmpnsmp(1)) error('the epochs are of unequal length, possibly due to numerical time axis issues, or due to partial artifacts, use cfg.toolbox=''biosig'''); end ix = find(tmpnsmp==mode(tmpnsmp), 1, 'first'); cfg.toi(j) = mean(tmpdata.time{ix}([1 end]))+0.5./data.fsample; %FIXME think about this end %---create cell-array indexing which original trials should go into each replicate rpt = {}; nrpt = numel(tmpdata.trial); if dojack rpt = cell(nrpt,1); for k = 1:nrpt rpt{k,1} = setdiff(1:nrpt,k); end elseif keeprpt for k = 1:nrpt rpt{k,1} = k; end else rpt{1} = 1:numel(tmpdata.trial); nrpt = 1; end for rlop = 1:nrpt if dobvar % bvar for m = 1:ntap %---construct data-matrix for k = 1:size(cmbindx,1) dat = catnan(tmpdata.trial, cmbindx(k,:), rpt{rlop}, tap(m,:), nnans, dobvar); %---estimate autoregressive model switch cfg.toolbox case 'biosig' [ar, rc, pe] = mvar(dat', cfg.order, cfg.mvarmethod); %---compute noise covariance tmpnoisecov = pe(:,nchan*cfg.order+1:nchan*(cfg.order+1)); case 'bsmart' [ar, tmpnoisecov] = armorf(dat, numel(rpt{rlop}), size(tmpdata.trial{1},2), cfg.order); ar = -ar; %convention is swapped sign with respect to biosig %FIXME check which is which: X(t) = A1*X(t-1) + ... + An*X(t-n) + E %the other is then X(t) + A1*X(t-1) + ... + An*X(t-n) = E end coeffs(rlop,k,:,:,j,m) = reshape(ar, [nchan*2 cfg.order]); %---rescale noisecov if necessary if dozscore, % FIX ME for bvar noisecov(rlop,k,:,:,j,m) = diag(datstd)*tmpnoisecov*diag(datstd); else noisecov(rlop,k,:,j,m) = reshape(tmpnoisecov,[1 4]); end dof(rlop,:,j) = numel(rpt{rlop}); end end else % mvar for m = 1:ntap %---construct data-matrix dat = catnan(tmpdata.trial, chanindx, rpt{rlop}, tap(m,:), nnans, dobvar); %---estimate autoregressive model if dounivariate, %---loop across the channels for p = 1:size(dat,1) switch cfg.toolbox case 'biosig' [ar, rc, pe] = mvar(dat(p,:)', cfg.order, cfg.mvarmethod); %---compute noise covariance tmpnoisecov = pe(:,cfg.order+1:(cfg.order+1)); case 'bsmart' [ar, tmpnoisecov] = armorf(dat(p,:), numel(rpt{rlop}), size(tmpdata.trial{1},2), cfg.order); ar = -ar; %convention is swapped sign with respect to biosig %FIXME check which is which: X(t) = A1*X(t-1) + ... + An*X(t-n) + E %the other is then X(t) + A1*X(t-1) + ... + An*X(t-n) = E end coeffs(rlop,p,:,j,m) = reshape(ar, [1 cfg.order]); %---rescale noisecov if necessary if dozscore, noisecov(rlop,p,j,m) = diag(datstd)*tmpnoisecov*diag(datstd); else noisecov(rlop,p,j,m) = tmpnoisecov; end dof(rlop,:,j) = numel(rpt{rlop}); end else switch cfg.toolbox case 'biosig' [ar, rc, pe] = mvar(dat', cfg.order, cfg.mvarmethod); %---compute noise covariance tmpnoisecov = pe(:,nchan*cfg.order+1:nchan*(cfg.order+1)); case 'bsmart' [ar, tmpnoisecov] = armorf(dat, numel(rpt{rlop}), size(tmpdata.trial{1},2), cfg.order); ar = -ar; %convention is swapped sign with respect to biosig %FIXME check which is which: X(t) = A1*X(t-1) + ... + An*X(t-n) + E %the other is then X(t) + A1*X(t-1) + ... + An*X(t-n) = E end coeffs(rlop,:,:,:,j,m) = reshape(ar, [nchan nchan cfg.order]); %---rescale noisecov if necessary if dozscore, noisecov(rlop,:,:,j,m) = diag(datstd)*tmpnoisecov*diag(datstd); else noisecov(rlop,:,:,j,m) = tmpnoisecov; end dof(rlop,:,j) = numel(rpt{rlop}); end %---dounivariate end %---tapers end end %---replicates end %---tois ft_progress('close'); %---create output-structure mvardata = []; if ~dobvar && ~dounivariate && dojack, mvardata.dimord = 'rptjck_chan_chan_lag'; elseif ~dobvar && ~dounivariate && keeprpt, mvardata.dimord = 'rpt_chan_chan_lag'; elseif ~dobvar && ~dounivariate mvardata.dimord = 'chan_chan_lag'; mvardata.label = label; siz = [size(coeffs) 1]; coeffs = reshape(coeffs, siz(2:end)); siz = [size(noisecov) 1]; if ~all(siz==1) noisecov = reshape(noisecov, siz(2:end)); end elseif dobvar mvardata.dimord = 'chancmb_lag'; siz = [size(coeffs) 1]; coeffs = reshape(coeffs, [siz(2) * siz(3) siz(4) siz(5)]); siz = [size(noisecov) 1]; noisecov = reshape(noisecov, [siz(2) * siz(3) siz(4)]); mvardata.labelcmb = labelcmb; elseif dounivariate mvardata.dimord = 'chan_lag'; mvardata.label = label; siz = [size(coeffs) 1]; coeffs = reshape(coeffs, siz(2:end)); siz = [size(noisecov) 1]; if ~all(siz==1) noisecov = reshape(noisecov, siz(2:end)); end end mvardata.coeffs = coeffs; mvardata.noisecov = noisecov; mvardata.dof = dof; if numel(cfg.toi)>1 mvardata.time = cfg.toi; mvardata.dimord = [mvardata.dimord,'_time']; end mvardata.fsampleorig = data.fsample; switch cfg.output case 'parameters' % no output requested, do not re-compile time-series data case {'model' 'residual'} if keeprpt || dojack error('reconstruction of the residuals with keeprpt or dojack is not yet implemented'); end dataout = keepfields(data, {'hdr','grad','fsample','trialinfo','label','cfg'}); trial = cell(1,numel(data.trial)); time = cell(1,numel(data.time)); for k = 1:numel(data.trial) if strcmp(cfg.output, 'model') trial{k} = zeros(size(data.trial{k},1), size(data.trial{k},2)-cfg.order); else trial{k} = data.trial{k}(:, (cfg.order+1):end); end time{k} = data.time{k}((cfg.order+1):end); for m = 1:cfg.order if dounivariate P = diag(mvardata.coeffs(:,m)); else P = mvardata.coeffs(:,:,m); end if strcmp(cfg.output, 'residual'), P = -P; end trial{k} = trial{k} + P * data.trial{k}(:,(cfg.order+1-m):(end-m)); end end dataout.trial = trial; dataout.time = time; cfg.coeffs = mvardata.coeffs; cfg.noisecov = mvardata.noisecov; mvardata = dataout; clear dataout; otherwise error('output ''%s'' is not supported', cfg.output); end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous data ft_postamble provenance mvardata ft_postamble history mvardata ft_postamble savevar mvardata %---------------------------------------------------- %subfunction to concatenate data with nans in between function [datamatrix] = catnan(datacells, chanindx, trials, taper, nnans, dobvar) nchan = length(chanindx); nsmp = cellfun('size', datacells, 2); nrpt = numel(trials); sumsmp = cumsum([0 nsmp]); %---initialize datamatrix = nan(nchan, sum(nsmp) + nnans*(nrpt-1)); %---fill the matrix for k = 1:nrpt if k==1, begsmp = sumsmp(k) + 1; endsmp = sumsmp(k+1) ; else begsmp = sumsmp(k) + (k-1)*nnans + 1; endsmp = sumsmp(k+1) + (k-1)*nnans; end if ~dobvar && isempty(taper) datamatrix(:,begsmp:endsmp) = datacells{trials(k)}(chanindx,:); elseif ~dobvar && ~isempty(taper) % FIXME this will crash with variable data length and fixed length % taper datamatrix(:,begsmp:endsmp) = datacells{trials(k)}(chanindx,:).*taper(ones(nchan,1),:); elseif dobvar && isempty(taper) datamatrix(:,begsmp:endsmp) = datacells{trials(k)}(chanindx',:); elseif dobvar && ~isempty(taper) datamatrix(:,begsmp:endsmp) = datacells{trials(k)}(chanindx',:).*taper(ones(nchan,1),:); end end %------------------------------------------------------ %---subfunction to ensure that the first two input arguments are of double % precision this prevents an instability (bug) in the computation of the % tapers for MATLAB 6.5 and 7.0 function [tap] = double_dpss(a, b, varargin) tap = dpss(double(a), double(b), varargin{:});
github
lcnbeapp/beapp-master
ft_anonimizedata.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_anonimizedata.m
12,569
utf_8
3b844ea1cf97b9bfafad5d759646ddfc
function data = ft_anonimizedata(cfg, data) % FT_ANONIMIZEDATA clears the value of potentially identifying fields in % the data and in the provenance information, i.e., it updates the data and % the configuration structure and history that is maintained by FieldTrip % in the cfg field. % % Use as % output = ft_anonimizedata(cfg, data) % where data is any FieldTrip data structure and cfg is a configuration % structure that should contain % cfg.keepnumeric = 'yes' or 'no', keep numeric fields (default = 'yes') % cfg.keepfield = cell-array with strings, fields to keep (default = {}) % cfg.removefield = cell-array with strings, fields to remove (default = {}) % cfg.keepvalue = cell-array with strings, values to keep (default = {}) % cfg.removevalue = cell-array with strings, values to remove (default = {}) % % The graphical user interface consists of a table that shows the name and % value of each provenance element, and whether it should be kept or % removed. Furthermore, it has a number of buttons: % - sort specify which column is used for sorting % - apply apply the current selection of "keep" and "remove" and hide the corresponding rows % - keep all toggle all visibe rows to "keep" % - remove all toggle all visibe rows to "keep" % - clear all clear all visibe rows, i.e. neither "keep" nor "remove" % - quit apply the current selection of "keep" and "remove" and exit % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % cfg.outputfile = ... % If you specify one of these (or both) the input data will be read from a *.mat % file on disk and/or the output data will be written to a *.mat file. These mat % files should contain only a single variable, corresponding with the % input/output structure. % % See also FT_ANALYSISPIPELINE % Copyright (C) 2014, Robert Oostenveld, DCCN % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar data ft_preamble provenance data ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % get the options cfg.keepfield = ft_getopt(cfg, 'keepfield', {}); cfg.removefield = ft_getopt(cfg, 'removefield', {}); cfg.keepvalue = ft_getopt(cfg, 'keepvalue', {}); cfg.removevalue = ft_getopt(cfg, 'removevalue', {}); cfg.keepnumeric = ft_getopt(cfg, 'keepnumeric', 'yes'); if isfield(data, 'cfg') % ensure that it is a structure, not a config object data.cfg = struct(data.cfg); end % determine the name and value of each element in the structure [name, value] = splitstruct('data', data); % we can rule out the numeric values as identifying sel = cellfun(@ischar, value); if istrue(cfg.keepnumeric) name = name(sel); value = value(sel); else % the numeric values are also to be judged by the end-user, but cannot be displayed easily % FIXME it would be possible to display single scalar values by converting them to a string value(~sel) = {'<numeric>'}; end % do not bother with fields that are empty sel = cellfun(@numel, value)>0; name = name(sel); value = value(sel); % all values are char, but some might be a char-array rather than a single string sel = cellfun('size', value, 1)>1; value(sel) = {'<multiline char array>'}; for i=1:length(value) % remove all non-printable characters sel = value{i}<32 | value{i}>126; value{i}(sel) = []; end keep = false(size(name)); for i=1:numel(cfg.keepfield) expression = sprintf('\\.%s$', cfg.keepfield{i}); keep = keep | ~cellfun(@isempty, regexp(name, expression), 'uniformoutput', 1); expression = sprintf('\\.%s\\.', cfg.keepfield{i}); keep = keep | ~cellfun(@isempty, regexp(name, expression), 'uniformoutput', 1); expression = sprintf('\\.%s\\(', cfg.keepfield{i}); keep = keep | ~cellfun(@isempty, regexp(name, expression), 'uniformoutput', 1); expression = sprintf('\\.%s\\{', cfg.keepfield{i}); keep = keep | ~cellfun(@isempty, regexp(name, expression), 'uniformoutput', 1); end keep = keep | ismember(value, cfg.keepvalue); remove = false(size(name)); for i=1:numel(cfg.removefield) expression = sprintf('\\.%s$', cfg.removefield{i}); remove = remove | ~cellfun(@isempty, regexp(name, expression), 'uniformoutput', 1); expression = sprintf('\\.%s\\.', cfg.removefield{i}); remove = remove | ~cellfun(@isempty, regexp(name, expression), 'uniformoutput', 1); expression = sprintf('\\.%s\\(', cfg.removefield{i}); remove = remove | ~cellfun(@isempty, regexp(name, expression), 'uniformoutput', 1); expression = sprintf('\\.%s\\{', cfg.removefield{i}); remove = remove | ~cellfun(@isempty, regexp(name, expression), 'uniformoutput', 1); end remove = remove | ismember(value, cfg.removevalue); % ensure there is no overlap keep(remove) = false; %% construct the graphical user interface h = figure; set(h, 'menuBar', 'none') mp = get(0, 'MonitorPosition'); if size(mp,1)==1 % there is only a single monitor, we can try to go fullscreen set(h,'units','normalized','position',[0 0 1 1]) else set(h,'units','normalized'); end %% add the table to the GUI t = uitable; set(t, 'ColumnEditable', [true true false false]); set(t, 'ColumnName', {'keep', 'remove', 'name', 'value'}); set(t, 'RowName', {}); %% add the buttons to the GUI uicontrol('tag', 'button1', 'parent', h, 'units', 'pixels', 'style', 'popupmenu', 'string', {'remove', 'keep', 'name', 'value'}, 'userdata', 'sort', 'callback', @sort_cb); uicontrol('tag', 'button2', 'parent', h, 'units', 'pixels', 'style', 'pushbutton', 'string', 'apply', 'userdata', 'a', 'callback', @keyboard_cb) uicontrol('tag', 'button3', 'parent', h, 'units', 'pixels', 'style', 'pushbutton', 'string', 'keep all', 'userdata', 'ka', 'callback', @keyboard_cb) uicontrol('tag', 'button4', 'parent', h, 'units', 'pixels', 'style', 'pushbutton', 'string', 'remove all', 'userdata', 'ra', 'callback', @keyboard_cb) uicontrol('tag', 'button5', 'parent', h, 'units', 'pixels', 'style', 'pushbutton', 'string', 'clear all', 'userdata', 'ca', 'callback', @keyboard_cb) uicontrol('tag', 'button6', 'parent', h, 'units', 'pixels', 'style', 'pushbutton', 'string', 'quit', 'userdata', 'q', 'callback', @keyboard_cb) % use manual positioning of the buttons in pixel units ft_uilayout(h, 'tag', 'button1', 'hpos', 20+(100+10)*0, 'vpos', 10, 'width', 100, 'height', 25); ft_uilayout(h, 'tag', 'button2', 'hpos', 20+(100+10)*1, 'vpos', 10, 'width', 100, 'height', 25); ft_uilayout(h, 'tag', 'button3', 'hpos', 20+(100+10)*2, 'vpos', 10, 'width', 100, 'height', 25); ft_uilayout(h, 'tag', 'button4', 'hpos', 20+(100+10)*3, 'vpos', 10, 'width', 100, 'height', 25); ft_uilayout(h, 'tag', 'button5', 'hpos', 20+(100+10)*4, 'vpos', 10, 'width', 100, 'height', 25); ft_uilayout(h, 'tag', 'button6', 'hpos', 20+(100+10)*5, 'vpos', 10, 'width', 100, 'height', 25); ft_uilayout(h, 'tag', 'button1', 'retag', 'buttongroup') ft_uilayout(h, 'tag', 'button1', 'retag', 'buttongroup') ft_uilayout(h, 'tag', 'button1', 'retag', 'buttongroup') ft_uilayout(h, 'tag', 'button1', 'retag', 'buttongroup') ft_uilayout(h, 'tag', 'button1', 'retag', 'buttongroup') ft_uilayout(h, 'tag', 'button1', 'retag', 'buttongroup') ft_uilayout(h, 'tag', 'buttongroup', 'BackgroundColor', [0.8 0.8 0.8]); % this structure is passed around as appdata info = []; info.table = t; info.name = name; info.value = value; info.keep = keep; info.remove = remove; info.hide = false(size(name)); info.cleanup = false; info.cfg = cfg; % this is consistent with the sort button [dum, indx] = sort(~info.remove); info.keep = info.keep(indx); info.remove = info.remove(indx); info.name = info.name(indx); info.value = info.value(indx); info.hide = info.hide(indx); % these callbacks need the info appdata setappdata(h, 'info', info); set(h, 'CloseRequestFcn', 'delete(gcf)'); set(h, 'ResizeFcn', @resize_cb); redraw_cb(h); resize_cb(h); while ~info.cleanup uiwait(h); % we only get part this point with abort or cleanup if ~ishandle(h) error('aborted by user'); end info = getappdata(h, 'info'); if info.cleanup if ~all(xor(info.keep, info.remove)) warning('not all fields have been marked as "keep" or "remove"'); info.cleanup = false; else delete(h); end end end fprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n'); name = info.name(info.remove); for i=1:length(name) str = sprintf('%s = ''removed by ft_anonimizedata'';', name{i}); disp(str); eval(str); end fprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n'); % deal with the output ft_postamble debug ft_postamble trackconfig ft_postamble previous data ft_postamble provenance data ft_postamble history data ft_postamble savevar data end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = getparent(h) p = h; while p~=0 h = p; p = get(h, 'parent'); end end % function function redraw_cb(h, eventdata) h = getparent(h); info = getappdata(h, 'info'); data = cat(2, num2cell(info.keep), num2cell(info.remove), info.name, info.value); data = data(~info.hide,:); set(info.table, 'data', data); end % function function keyboard_cb(h, eventdata) if isempty(eventdata) % determine the key that corresponds to the uicontrol element that was activated key = get(h, 'userdata'); else % determine the key that was pressed on the keyboard key = parseKeyboardEvent(eventdata); end h = getparent(h); info = getappdata(h, 'info'); data = get(info.table, 'data'); sel = info.keep & info.remove; if any(sel) warning('items that were marked both as "keep" and "remove" have been cleared'); info.keep(sel) = false; info.remove(sel) = false; end info.keep (~info.hide) = cell2mat(data(:,1)); info.remove(~info.hide) = cell2mat(data(:,2)); switch key case 'q' info.cleanup = true; uiresume case 'a' info.hide(info.keep) = true; info.hide(info.remove) = true; case 'ka' info.keep (~info.hide) = true; info.remove(~info.hide) = false; case 'ra' info.keep (~info.hide) = false; info.remove(~info.hide) = true; case 'ca' info.keep (~info.hide) = false; info.remove(~info.hide) = false; end setappdata(h, 'info', info); redraw_cb(h) end % function function sort_cb(h, eventdata) h = getparent(h); info = getappdata(h, 'info'); val = get(findobj(h, 'userdata', 'sort'), 'value'); str = get(findobj(h, 'userdata', 'sort'), 'string'); switch str{val} case 'remove' [dum, indx] = sort(~info.remove); case 'keep' [dum, indx] = sort(~info.keep); case 'name' [dum, indx] = sort(info.name); case 'value' [dum, indx] = sort(info.value); end info.keep = info.keep(indx); info.remove = info.remove(indx); info.name = info.name(indx); info.value = info.value(indx); info.hide = info.hide(indx); setappdata(h, 'info', info); redraw_cb(h); end % function function resize_cb(h, eventdata) drawnow h = getparent(h); info = getappdata(h, 'info'); set(h, 'units', 'pixels'); siz = get(h, 'position'); % the 15 is for the vertical scrollbar on the right set(info.table, 'units', 'normalized', 'position', [0.05 0.1 0.90 0.85]); set(info.table, 'ColumnWidth', {50 50 300 600}); end
github
lcnbeapp/beapp-master
ft_electrodeplacement.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_electrodeplacement.m
49,055
utf_8
ef6d8bd86678d2f9b53b60cb5f8afb17
function [elec] = ft_electrodeplacement(cfg, varargin) % FT_ELECTRODEPLACEMENT allows placing electrodes on a volume or headshape. % The different methods are described in detail below. % % VOLUME - Navigate an orthographic display of a volume (e.g. CT or % MR scan), and assign an electrode label to the current crosshair location % by clicking on a label in the eletrode list. You can undo the selection by % clicking on the same label again. The electrode labels shown in the list % can be prespecified using cfg.channel when calling ft_electrodeplacement. % The zoom slider allows zooming in at the location of the crosshair. % The intensity sliders allow thresholding the image's low and high values. % The magnet feature transports the crosshair to the nearest peak intensity % voxel, within a certain voxel radius of the selected location. % The labels feature displays the labels of the selected electrodes within % the orthoplot. The global feature allows toggling the view between all % and near-crosshair markers. % % HEADSHAPE - Navigate a triangulated head/brain surface, and assign % an electrode location by clicking on the brain. The electrode % is placed on the triangulation itself. FIXME: this needs updating % % Use as % [elec] = ft_electrodeplacement(cfg, mri) % where the input mri should be an anatomical CT or MRI volume % Use as % [elec] = ft_electrodeplacement(cfg, headshape) % where the input headshape should be a surface triangulation % % The configuration can contain the following options % cfg.method = string representing the method for aligning or placing the electrodes % 'mri' place electrodes in a brain volume % 'headshape' place electrodes on the head surface % cfg.parameter = string, field in data (default = 'anatomy' if present in data) % cfg.channel = Nx1 cell-array with selection of channels (default = '1','2', ...) % cfg.elec = struct containing previously placed electrodes (this overwrites cfg.channel) % cfg.clim = color range of the data (default = [0 1], i.e. the full range) % cfg.magtype = string representing the 'magnet' type used for placing the electrodes % 'peak' place electrodes at peak intensity voxel (default) % 'trough' place electrodes at trough intensity voxel % 'weighted' place electrodes at center-of-mass % cfg.magradius = number representing the radius for the cfg.magtype based search (default = 2) % % See also FT_ELECTRODEREALIGN, FT_VOLUMEREALIGN % Copyright (C) 2015, Arjen Stolk & Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar mri ft_preamble provenance mri ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % ensure that old and unsupported options are not being relied on by the end-user's script % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=2837 cfg = ft_checkconfig(cfg, 'renamed', {'viewdim', 'axisratio'}); % set the defaults cfg.method = ft_getopt(cfg, 'method'); % volume, headshape cfg.parameter = ft_getopt(cfg, 'parameter', 'anatomy'); cfg.channel = ft_getopt(cfg, 'channel', []); % default will be determined further down {'1', '2', ...} cfg.elec = ft_getopt(cfg, 'elec', []); % use previously placed electrodes cfg.renderer = ft_getopt(cfg, 'renderer', 'opengl'); % view options cfg.clim = ft_getopt(cfg, 'clim', [0 1]); % initial volume intensity limit voxels cfg.markerdist = ft_getopt(cfg, 'markerdist', 5); % marker-slice distance for including in the view % magnet options cfg.magtype = ft_getopt(cfg, 'magtype', 'peak'); % detect peaks or troughs or center-of-mass cfg.magradius = ft_getopt(cfg, 'magradius', 2); % specify the physical unit radius cfg.voxelratio = ft_getopt(cfg, 'voxelratio', 'data'); % display size of the voxel, 'data' or 'square' cfg.axisratio = ft_getopt(cfg, 'axisratio', 'data'); % size of the axes of the three orthoplots, 'square', 'voxel', or 'data' if isempty(cfg.method) && ~isempty(varargin) % the default determines on the input data switch ft_datatype(varargin{1}) case 'volume' cfg.method = 'volume'; case 'mesh' cfg.method = 'headshape'; end end % check if the input data is valid for this function switch cfg.method case 'volume' mri = ft_checkdata(varargin{1}, 'datatype', 'volume', 'feedback', 'yes'); case {'headshape'} headshape = fixpos(varargin{1}); headshape = ft_determine_coordsys(headshape); end switch cfg.method case 'headshape' % give the user instructions disp('Use the mouse to click on the desired electrode positions'); disp('Afterwards you may have to update the electrode labels'); disp('Press "r" to delete the last point add'); disp('Press "+/-" to zoom in/out'); disp('Press "w/a/s/d" to rotate'); disp('Press "q" when you are done'); % open a figure figure; % plot the faces of the 2D or 3D triangulation if isfield(headshape, 'color'); skin = 'none'; ft_plot_mesh(headshape); else skin = [255 213 119]/255; ft_plot_mesh(headshape,'facecolor', skin,'EdgeColor','none','facealpha',1); lighting gouraud material shiny camlight end % rotate3d on xyz = ft_select_point3d(headshape, 'nearest', false, 'multiple', true, 'marker', '*'); numelec = size(xyz, 1); % construct the output electrode structure elec = keepfields(headshape, {'unit', 'coordsys'}); elec.elecpos = xyz; for i=1:numelec try elec.label{i} = cfg.channel{i,1}; catch elec.label{i} = sprintf('%d', i); end end case 'volume' % start building the figure h = figure(... 'MenuBar', 'none',... 'Name', mfilename,... 'Units', 'normalized', ... 'Color', [1 1 1], ... 'Visible', 'on'); set(h, 'windowbuttondownfcn', @cb_buttonpress); set(h, 'windowbuttonupfcn', @cb_buttonrelease); set(h, 'windowkeypressfcn', @cb_keyboard); set(h, 'CloseRequestFcn', @cb_cleanup); set(h, 'renderer', cfg.renderer); % axes settings if strcmp(cfg.axisratio, 'voxel') % determine the number of voxels to be plotted along each axis axlen1 = mri.dim(1); axlen2 = mri.dim(2); axlen3 = mri.dim(3); elseif strcmp(cfg.axisratio, 'data') % determine the length of the edges along each axis [cp_voxel, cp_head] = cornerpoints(mri.dim, mri.transform); axlen1 = norm(cp_head(2,:)-cp_head(1,:)); axlen2 = norm(cp_head(4,:)-cp_head(1,:)); axlen3 = norm(cp_head(5,:)-cp_head(1,:)); elseif strcmp(cfg.axisratio, 'square') % the length of the axes should be equal axlen1 = 1; axlen2 = 1; axlen3 = 1; end % this is the size reserved for subplot h1, h2 and h3 h1size(1) = 0.82*axlen1/(axlen1 + axlen2); h1size(2) = 0.82*axlen3/(axlen2 + axlen3); h2size(1) = 0.82*axlen2/(axlen1 + axlen2); h2size(2) = 0.82*axlen3/(axlen2 + axlen3); h3size(1) = 0.82*axlen1/(axlen1 + axlen2); h3size(2) = 0.82*axlen2/(axlen2 + axlen3); if strcmp(cfg.voxelratio, 'square') voxlen1 = 1; voxlen2 = 1; voxlen3 = 1; elseif strcmp(cfg.voxelratio, 'data') % the size of the voxel is scaled with the data [cp_voxel, cp_head] = cornerpoints(mri.dim, mri.transform); voxlen1 = norm(cp_head(2,:)-cp_head(1,:))/norm(cp_voxel(2,:)-cp_voxel(1,:)); voxlen2 = norm(cp_head(4,:)-cp_head(1,:))/norm(cp_voxel(4,:)-cp_voxel(1,:)); voxlen3 = norm(cp_head(5,:)-cp_head(1,:))/norm(cp_voxel(5,:)-cp_voxel(1,:)); end % axis handles will hold the anatomical functional if present, along with labels etc. h1 = axes('position',[0.06 0.06+0.06+h3size(2) h1size(1) h1size(2)]); h2 = axes('position',[0.06+0.06+h1size(1) 0.06+0.06+h3size(2) h2size(1) h2size(2)]); h3 = axes('position',[0.06 0.06 h3size(1) h3size(2)]); set(h1, 'Tag', 'ik', 'Visible', 'off', 'XAxisLocation', 'top'); set(h2, 'Tag', 'jk', 'Visible', 'off', 'YAxisLocation', 'right'); % after rotating in ft_plot_ortho this becomes top set(h3, 'Tag', 'ij', 'Visible', 'off'); set(h1, 'DataAspectRatio', 1./[voxlen1 voxlen2 voxlen3]); set(h2, 'DataAspectRatio', 1./[voxlen1 voxlen2 voxlen3]); set(h3, 'DataAspectRatio', 1./[voxlen1 voxlen2 voxlen3]); xc = round(mri.dim(1)/2); % start with center view yc = round(mri.dim(2)/2); zc = round(mri.dim(3)/2); dat = double(mri.(cfg.parameter)); dmin = min(dat(:)); dmax = max(dat(:)); dat = (dat-dmin)./(dmax-dmin); % range between 0 and 1 % intensity range sliders h45text = uicontrol('Style', 'text',... 'String','Intensity',... 'Units', 'normalized', ... 'Position',[2*h1size(1)+0.03 h3size(2)+0.03 h1size(1)/4 0.04],... 'BackgroundColor', [1 1 1], ... 'HandleVisibility','on'); h4 = uicontrol('Style', 'slider', ... 'Parent', h, ... 'Min', 0, 'Max', 1, ... 'Value', cfg.clim(1), ... 'Units', 'normalized', ... 'Position', [2*h1size(1)+0.02 0.15+h3size(2)/3 0.05 h3size(2)/2-0.05], ... 'Callback', @cb_minslider); h5 = uicontrol('Style', 'slider', ... 'Parent', h, ... 'Min', 0, 'Max', 1, ... 'Value', cfg.clim(2), ... 'Units', 'normalized', ... 'Position', [2*h1size(1)+0.07 0.15+h3size(2)/3 0.05 h3size(2)/2-0.05], ... 'Callback', @cb_maxslider); % java intensity range slider (dual-knob slider): the java component gives issues when wanting to % access the opt structure % [jRangeSlider] = com.jidesoft.swing.RangeSlider(0,1,cfg.clim(1),cfg.clim(2)); % min,max,low,high % [jRangeSlider, h4] = javacomponent(jRangeSlider, [], h); % set(h4, 'Units', 'normalized', 'Position', [0.05+h1size(1) 0.07 0.07 h3size(2)], 'Parent', h); % set(jRangeSlider, 'Orientation', 1, 'PaintTicks', true, 'PaintLabels', true, ... % 'Background', java.awt.Color.white, 'StateChangedCallback', @cb_intensityslider); % electrode listbox if ~isempty(cfg.elec) % re-use previously placed (cfg.elec) electrodes cfg.channel = []; % ensure cfg.channel is empty, for filling it up for e = 1:numel(cfg.elec.label) cfg.channel{e,1} = cfg.elec.label{e}; chanstring{e} = ['<HTML><FONT color="black">' cfg.channel{e,1} '</FONT></HTML>']; % hmtl'ize markerlab{e,1} = cfg.elec.label{e}; markerpos{e,1} = cfg.elec.elecpos(e,:); end else % otherwise use standard / prespecified (cfg.channel) electrode labels if isempty(cfg.channel) for c = 1:150 cfg.channel{c,1} = sprintf('%d', c); end end for c = 1:numel(cfg.channel) chanstring{c} = ['<HTML><FONT color="silver">' cfg.channel{c,1} '</FONT></HTML>']; % hmtl'ize markerlab{c,1} = {}; markerpos{c,1} = zeros(0,3); end end h6 = uicontrol('Style', 'listbox', ... 'Parent', h, ... 'Value', [], 'Min', 0, 'Max', numel(chanstring), ... 'Units', 'normalized', ... 'Position', [0.07+h1size(1)+0.05 0.07 h1size(1)/2 h3size(2)], ... 'Callback', @cb_eleclistbox, ... 'String', chanstring); % switches / radio buttons h7 = uicontrol('Style', 'radiobutton',... 'Parent', h, ... 'Value', 1, ... 'String','Magnet',... 'Units', 'normalized', ... 'Position',[2*h1size(1) 0.22 h1size(1)/3 0.05],... 'BackgroundColor', [1 1 1], ... 'HandleVisibility','on', ... 'Callback', @cb_magnetbutton); h8 = uicontrol('Style', 'radiobutton',... 'Parent', h, ... 'Value', 0, ... 'String','Labels',... 'Units', 'normalized', ... 'Position',[2*h1size(1) 0.17 h1size(1)/3 0.05],... 'BackgroundColor', [1 1 1], ... 'HandleVisibility','on', ... 'Callback', @cb_labelsbutton); h9 = uicontrol('Style', 'radiobutton',... 'Parent', h, ... 'Value', 0, ... 'String','Global',... 'Units', 'normalized', ... 'Position',[2*h1size(1) 0.12 h1size(1)/3 0.05],... 'BackgroundColor', [1 1 1], ... 'HandleVisibility','on', ... 'Callback', @cb_globalbutton); hscatter = uicontrol('Style', 'radiobutton',... 'Parent', h, ... 'Value', 0, ... 'String','Scatter',... 'Units', 'normalized', ... 'Position',[2*h1size(1) 0.07 h1size(1)/3 0.05],... 'BackgroundColor', [1 1 1], ... 'HandleVisibility','on', ... 'Callback', @cb_scatterbutton); % zoom slider h10text = uicontrol('Style', 'text',... 'String','Zoom',... 'Units', 'normalized', ... 'Position',[1.8*h1size(1)+0.01 h3size(2)+0.03 h1size(1)/4 0.04],... 'BackgroundColor', [1 1 1], ... 'HandleVisibility','on'); h10 = uicontrol('Style', 'slider', ... 'Parent', h, ... 'Min', 0, 'Max', 0.9, ... 'Value', 0, ... 'Units', 'normalized', ... 'Position', [1.8*h1size(1)+0.02 0.15+h3size(2)/3 0.05 h3size(2)/2-0.05], ... 'SliderStep', [.1 .1], ... 'Callback', @cb_zoomslider); % instructions to the user fprintf(strcat(... '1. Viewing options:\n',... ' a. use the left mouse button to navigate the image, or\n',... ' b. use the arrow keys to increase or decrease the slice number by one\n',... '2. Placement options:\n',... ' a. click an electrode label in the list to assign the crosshair location, or\n',... ' b. doubleclick a previously assigned electrode label to remove its marker\n',... '3. To finalize, close the window or press q on the keyboard\n')); % create structure to be passed to gui opt = []; opt.dim = mri.dim; opt.ijk = [xc yc zc]; opt.h1size = h1size; opt.h2size = h2size; opt.h3size = h3size; opt.handlesaxes = [h1 h2 h3 h4 h5 h6 h7 h8 h9 h10 hscatter]; opt.handlesfigure = h; opt.handlesmarker = []; opt.quit = false; opt.ana = dat; opt.update = [1 1 1]; opt.init = true; opt.tag = 'ik'; opt.mri = mri; opt.showcrosshair = true; opt.vox = [opt.ijk]; % voxel coordinates (physical units) opt.pos = ft_warp_apply(mri.transform, opt.ijk); % head coordinates (e.g. mm) opt.showlabels = 0; opt.label = cfg.channel; opt.magnet = get(h7, 'Value'); opt.magradius = cfg.magradius; opt.magtype = cfg.magtype; opt.showmarkers = true; opt.global = get(h9, 'Value'); % show all markers in the current slices opt.scatter = get(hscatter, 'Value'); % additional scatterplot opt.slim = [.5 1]; % 50% - maximum opt.markerlab = markerlab; opt.markerpos = markerpos; opt.markerdist = cfg.markerdist; % hidden option opt.clim = cfg.clim; opt.zoom = 0; if isfield(mri, 'unit') && ~strcmp(mri.unit, 'unknown') opt.unit = mri.unit; % this is shown in the feedback on screen else opt.unit = ''; % this is not shown end setappdata(h, 'opt', opt); cb_redraw(h); while(opt.quit==0) uiwait(h); opt = getappdata(h, 'opt'); end delete(h); % collect the results elec.label = {}; elec.elecpos = []; elec.chanpos = []; elec.tra = []; for i=1:length(opt.markerlab) if ~isempty(opt.markerlab{i,1}) elec.label = [elec.label; opt.markerlab{i,1}]; elec.elecpos = [elec.elecpos; opt.markerpos{i,1}]; end end elec.chanpos = elec.elecpos; % identicial to elecpos elec.tra = eye(size(elec.elecpos,1)); if isfield(mri, 'unit') elec.unit = mri.unit; end if isfield(mri, 'coordsys') elec.coordsys = mri.coordsys; end end % switch method % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous mri ft_postamble provenance elec ft_postamble history elec ft_postamble savevar elec %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_redraw(h, eventdata) tic h = getparent(h); opt = getappdata(h, 'opt'); curr_ax = get(h, 'currentaxes'); tag = get(curr_ax, 'tag'); mri = opt.mri; h1 = opt.handlesaxes(1); h2 = opt.handlesaxes(2); h3 = opt.handlesaxes(3); xi = opt.ijk(1); yi = opt.ijk(2); zi = opt.ijk(3); if any([xi yi zi] > mri.dim) || any([xi yi zi] <= 0) return; end opt.ijk = [xi yi zi 1]'; opt.ijk = opt.ijk(1:3)'; % construct a string with user feedback str1 = sprintf('voxel %d, index [%d %d %d]', sub2ind(mri.dim(1:3), xi, yi, zi), opt.ijk); if opt.init ft_plot_ortho(opt.ana, 'transform', eye(4), 'location', opt.ijk, 'style', 'subplot', 'parents', [h1 h2 h3], 'update', opt.update, 'doscale', false,'clim', opt.clim); opt.anahandles = findobj(opt.handlesfigure, 'type', 'surface')'; parenttag = get(opt.anahandles,'parent'); parenttag{1} = get(parenttag{1}, 'tag'); parenttag{2} = get(parenttag{2}, 'tag'); parenttag{3} = get(parenttag{3}, 'tag'); [i1,i2,i3] = intersect(parenttag, {'ik';'jk';'ij'}); opt.anahandles = opt.anahandles(i3(i2)); % seems like swapping the order opt.anahandles = opt.anahandles(:)'; set(opt.anahandles, 'tag', 'ana'); % for zooming purposes opt.axis = zeros(1,6); opt.axis([1 3 5]) = 0.5; opt.axis([2 4 6]) = size(opt.ana) + 0.5; else ft_plot_ortho(opt.ana, 'transform', eye(4), 'location', opt.ijk, 'style', 'subplot', 'surfhandle', opt.anahandles, 'update', opt.update, 'doscale', false,'clim', opt.clim); if all(round([xi yi zi])<=mri.dim) && all(round([xi yi zi])>0) fprintf('==================================================================================\n'); str = sprintf('voxel %d, index [%d %d %d]', sub2ind(mri.dim(1:3), round(xi), round(yi), round(zi)), round([xi yi zi])); lab = 'crosshair'; opt.vox = [xi yi zi]; ind = sub2ind(mri.dim(1:3), round(opt.vox(1)), round(opt.vox(2)), round(opt.vox(3))); opt.pos = ft_warp_apply(mri.transform, opt.vox); switch opt.unit case 'mm' fprintf('%10s: voxel %9d, index = [%3d %3d %3d], head = [%.1f %.1f %.1f] %s\n', lab, ind, opt.vox, opt.pos, opt.unit); case 'cm' fprintf('%10s: voxel %9d, index = [%3d %3d %3d], head = [%.2f %.2f %.2f] %s\n', lab, ind, opt.vox, opt.pos, opt.unit); case 'm' fprintf('%10s: voxel %9d, index = [%3d %3d %3d], head = [%.4f %.4f %.4f] %s\n', lab, ind, opt.vox, opt.pos, opt.unit); otherwise fprintf('%10s: voxel %9d, index = [%3d %3d %3d], head = [%f %f %f] %s\n', lab, ind, opt.vox, opt.pos, opt.unit); end end end % make the last current axes current again sel = findobj('type','axes','tag',tag); if ~isempty(sel) set(opt.handlesfigure, 'currentaxes', sel(1)); end % zoom xloadj = round((xi-opt.axis(1))-(xi-opt.axis(1))*opt.zoom); xhiadj = round((opt.axis(2)-xi)-(opt.axis(2)-xi)*opt.zoom); yloadj = round((yi-opt.axis(3))-(yi-opt.axis(3))*opt.zoom); yhiadj = round((opt.axis(4)-yi)-(opt.axis(4)-yi)*opt.zoom); zloadj = round((zi-opt.axis(5))-(zi-opt.axis(5))*opt.zoom); zhiadj = round((opt.axis(6)-zi)-(opt.axis(6)-zi)*opt.zoom); axis(h1, [xi-xloadj xi+xhiadj yi-yloadj yi+yhiadj zi-zloadj zi+zhiadj]); axis(h2, [xi-xloadj xi+xhiadj yi-yloadj yi+yhiadj zi-zloadj zi+zhiadj]); axis(h3, [xi-xloadj xi+xhiadj yi-yloadj yi+yhiadj]); if opt.init % draw the crosshairs for the first time hch1 = crosshair([xi yi-yloadj zi], 'parent', h1, 'color', 'yellow'); % was [xi 1 zi], now corrected for zoom hch2 = crosshair([xi+xhiadj yi zi], 'parent', h2, 'color', 'yellow'); % was [opt.dim(1) yi zi], now corrected for zoom hch3 = crosshair([xi yi zi], 'parent', h3, 'color', 'yellow'); % was [xi yi opt.dim(3)], now corrected for zoom opt.handlescross = [hch1(:)';hch2(:)';hch3(:)']; opt.handlesmarker = []; else % update the existing crosshairs, don't change the handles crosshair([xi yi-yloadj zi], 'handle', opt.handlescross(1, :)); crosshair([xi+xhiadj yi zi], 'handle', opt.handlescross(2, :)); crosshair([xi yi zi], 'handle', opt.handlescross(3, :)); end if opt.showcrosshair set(opt.handlescross,'Visible','on'); else set(opt.handlescross,'Visible','off'); end delete(opt.handlesmarker(opt.handlesmarker(:)>0)); opt.handlesmarker = []; % draw markers idx = find(~cellfun(@isempty,opt.markerlab)); % non-empty markers if ~isempty(idx) for i=1:numel(idx) markerlab{i,1} = opt.markerlab{idx(i),1}; markerpos(i,:) = opt.markerpos{idx(i),1}; end opt.vox2 = round(ft_warp_apply(inv(mri.transform), markerpos)); % head to vox tmp1 = opt.vox2(:,1); tmp2 = opt.vox2(:,2); tmp3 = opt.vox2(:,3); subplot(h1); if ~opt.global % filter markers distant to the current slice (N units and further) posj_idx = find( abs(tmp2 - repmat(yi,size(tmp2))) < opt.markerdist); posi = tmp1(posj_idx); posj = tmp2(posj_idx); posk = tmp3(posj_idx); else % plot all markers on the current slice posj_idx = 1:numel(tmp1); posi = tmp1; posj = tmp2; posk = tmp3; end if ~isempty(posi) hold on opt.handlesmarker(:,1) = plot3(posi, repmat(yi-yloadj,size(posj)), posk, 'marker', '+', 'linestyle', 'none', 'color', 'r'); % [xi yi-yloadj zi] if opt.showlabels for i=1:numel(posj_idx) opt.handlesmarker(i,4) = text(posi(i), yi-yloadj, posk(i), markerlab{posj_idx(i),1}, 'color', 'b'); end end hold off end subplot(h2); if ~opt.global % filter markers distant to the current slice (N units and further) posi_idx = find( abs(tmp1 - repmat(xi,size(tmp1))) < opt.markerdist); posi = tmp1(posi_idx); posj = tmp2(posi_idx); posk = tmp3(posi_idx); else % plot all markers on the current slice posi_idx = 1:numel(tmp1); posi = tmp1; posj = tmp2; posk = tmp3; end if ~isempty(posj) hold on opt.handlesmarker(:,2) = plot3(repmat(xi+xhiadj,size(posi)), posj, posk, 'marker', '+', 'linestyle', 'none', 'color', 'r'); % [xi+xhiadj yi zi] if opt.showlabels for i=1:numel(posi_idx) opt.handlesmarker(i,5) = text(posi(i)+xhiadj, posj(i), posk(i), markerlab{posi_idx(i),1}, 'color', 'b'); end end hold off end subplot(h3); if ~opt.global % filter markers distant to the current slice (N units and further) posk_idx = find( abs(tmp3 - repmat(zi,size(tmp3))) < opt.markerdist); posi = tmp1(posk_idx); posj = tmp2(posk_idx); posk = tmp3(posk_idx); else % plot all markers on the current slice posk_idx = 1:numel(tmp1); posi = tmp1; posj = tmp2; posk = tmp3; end if ~isempty(posk) hold on opt.handlesmarker(:,3) = plot3(posi, posj, repmat(zi,size(posk)), 'marker', '+', 'linestyle', 'none', 'color', 'r'); % [xi yi zi] if opt.showlabels for i=1:numel(posk_idx) opt.handlesmarker(i,6) = text(posi(i), posj(i), zi, markerlab{posk_idx(i),1}, 'color', 'b'); end end hold off end end % for all markers if isfield(opt, 'scatterfig') cb_scatterredraw(h); % also update the appendix figure(h); % FIXME: ugly as it switches forth and back to mainfig end % do not initialize on the next call opt.init = false; setappdata(h, 'opt', opt); set(h, 'currentaxes', curr_ax); toc %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_scatterredraw(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); if opt.scatter % radiobutton on if ~isfield(opt, 'scatterfig') % if the figure does not yet exist, initiate opt.scatterfig = figure(... 'Name', [mfilename ' appendix'],... 'Units', 'normalized', ... 'Color', [1 1 1], ... 'Visible', 'on'); set(opt.scatterfig, 'CloseRequestFcn', @cb_scattercleanup); opt.scatterfig_h1 = axes('position',[0.06 0.06 0.74 0.88]); set(opt.scatterfig_h1, 'DataAspectRatio', get(opt.handlesaxes(1), 'DataAspectRatio')); axis image; xlabel('x'); ylabel('y'); zlabel('z'); % scatter range sliders opt.scatterfig_h23text = uicontrol('Style', 'text',... 'String','Treshold',... 'Units', 'normalized', ... 'Position',[.85+0.03 .26 .1 0.04],... 'BackgroundColor', [1 1 1], ... 'HandleVisibility','on'); opt.scatterfig_h2 = uicontrol('Style', 'slider', ... 'Parent', opt.scatterfig, ... 'Min', 0, 'Max', 1, ... 'Value', opt.slim(1), ... 'Units', 'normalized', ... 'Position', [.85+.02 .06 .05 .2], ... 'Callback', @cb_scatterminslider); opt.scatterfig_h3 = uicontrol('Style', 'slider', ... 'Parent', opt.scatterfig, ... 'Min', 0, 'Max', 1, ... 'Value', opt.slim(2), ... 'Units', 'normalized', ... 'Position', [.85+.07 .06 .05 .2], ... 'Callback', @cb_scattermaxslider); msize = round(2500/opt.mri.dim(3)); % headsize (25 cm) / z slices inc = abs(opt.slim(2)-opt.slim(1))/4; % color increments for r = 1:4 % 4 color layers to encode peaks lim1 = opt.slim(1) + r*inc - inc; lim2 = opt.slim(1) + r*inc; voxind = find(opt.ana>lim1 & opt.ana<lim2); [x,y,z] = ind2sub(opt.mri.dim, voxind); hold on; scatter3(x,y,z,msize,'Marker','s','MarkerEdgeColor','none','MarkerFaceColor',[.8-(r*.2) .8-(r*.2) .8-(r*.2)]); end % draw the crosshair for the first time opt.handlescross2 = crosshair([opt.ijk], 'parent', opt.scatterfig_h1, 'color', 'blue'); end figure(opt.scatterfig); % update the existing crosshairs, don't change the handles crosshair([opt.ijk], 'handle', opt.handlescross2); if opt.showcrosshair set(opt.handlescross,'Visible','on'); else set(opt.handlescross,'Visible','off'); end % plot the markers if isfield(opt, 'vox2') delete(findobj(opt.scatterfig,'Type','line','Marker','+')); % remove previous markers plot3(opt.vox2(:,1),opt.vox2(:,2),opt.vox2(:,3), 'marker', '+', 'linestyle', 'none', 'color', 'r'); end end setappdata(h, 'opt', opt); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_keyboard(h, eventdata) if isempty(eventdata) % determine the key that corresponds to the uicontrol element that was activated key = get(h, 'userdata'); else % determine the key that was pressed on the keyboard key = parseKeyboardEvent(eventdata); end % get focus back to figure if ~strcmp(get(h, 'type'), 'figure') set(h, 'enable', 'off'); drawnow; set(h, 'enable', 'on'); end h = getparent(h); opt = getappdata(h, 'opt'); curr_ax = get(h, 'currentaxes'); tag = get(curr_ax, 'tag'); if isempty(key) % this happens if you press the apple key key = ''; end % the following code is largely shared with FT_SOURCEPLOT switch key case {'' 'shift+shift' 'alt-alt' 'control+control' 'command-0'} % do nothing case '1' subplot(opt.handlesaxes(1)); case '2' subplot(opt.handlesaxes(2)); case '3' subplot(opt.handlesaxes(3)); case 'q' setappdata(h, 'opt', opt); cb_cleanup(h); case 'g' % global/local elec view (h9) toggle if isequal(opt.global, 0) opt.global = 1; set(opt.handlesaxes(9), 'Value', 1); elseif isequal(opt.global, 1) opt.global = 0; set(opt.handlesaxes(9), 'Value', 0); end setappdata(h, 'opt', opt); cb_redraw(h); case 'l' % elec label view (h8) toggle if isequal(opt.showlabels, 0) opt.showlabels = 1; set(opt.handlesaxes(8), 'Value', 1); elseif isequal(opt.showlabels, 1) opt.showlabels = 0; set(opt.handlesaxes(8), 'Value', 0); end setappdata(h, 'opt', opt); cb_redraw(h); case 'm' % magnet (h7) toggle if isequal(opt.magnet, 0) opt.magnet = 1; set(opt.handlesaxes(7), 'Value', 1); elseif isequal(opt.magnet, 1) opt.magnet = 0; set(opt.handlesaxes(7), 'Value', 0); end setappdata(h, 'opt', opt); case {28 29 30 31 'leftarrow' 'rightarrow' 'uparrow' 'downarrow'} % update the view to a new position if strcmp(tag,'ik') && (strcmp(key,'i') || strcmp(key,'uparrow') || isequal(key, 30)), opt.ijk(3) = opt.ijk(3)+1; opt.update = [0 0 1]; elseif strcmp(tag,'ik') && (strcmp(key,'j') || strcmp(key,'leftarrow') || isequal(key, 28)), opt.ijk(1) = opt.ijk(1)-1; opt.update = [0 1 0]; elseif strcmp(tag,'ik') && (strcmp(key,'k') || strcmp(key,'rightarrow') || isequal(key, 29)), opt.ijk(1) = opt.ijk(1)+1; opt.update = [0 1 0]; elseif strcmp(tag,'ik') && (strcmp(key,'m') || strcmp(key,'downarrow') || isequal(key, 31)), opt.ijk(3) = opt.ijk(3)-1; opt.update = [0 0 1]; elseif strcmp(tag,'ij') && (strcmp(key,'i') || strcmp(key,'uparrow') || isequal(key, 30)), opt.ijk(2) = opt.ijk(2)+1; opt.update = [1 0 0]; elseif strcmp(tag,'ij') && (strcmp(key,'j') || strcmp(key,'leftarrow') || isequal(key, 28)), opt.ijk(1) = opt.ijk(1)-1; opt.update = [0 1 0]; elseif strcmp(tag,'ij') && (strcmp(key,'k') || strcmp(key,'rightarrow') || isequal(key, 29)), opt.ijk(1) = opt.ijk(1)+1; opt.update = [0 1 0]; elseif strcmp(tag,'ij') && (strcmp(key,'m') || strcmp(key,'downarrow') || isequal(key, 31)), opt.ijk(2) = opt.ijk(2)-1; opt.update = [1 0 0]; elseif strcmp(tag,'jk') && (strcmp(key,'i') || strcmp(key,'uparrow') || isequal(key, 30)), opt.ijk(3) = opt.ijk(3)+1; opt.update = [0 0 1]; elseif strcmp(tag,'jk') && (strcmp(key,'j') || strcmp(key,'leftarrow') || isequal(key, 28)), opt.ijk(2) = opt.ijk(2)-1; opt.update = [1 0 0]; elseif strcmp(tag,'jk') && (strcmp(key,'k') || strcmp(key,'rightarrow') || isequal(key, 29)), opt.ijk(2) = opt.ijk(2)+1; opt.update = [1 0 0]; elseif strcmp(tag,'jk') && (strcmp(key,'m') || strcmp(key,'downarrow') || isequal(key, 31)), opt.ijk(3) = opt.ijk(3)-1; opt.update = [0 0 1]; else % do nothing end; setappdata(h, 'opt', opt); cb_redraw(h); % contrast scaling case {43 'shift+equal'} % numpad + if isempty(opt.clim) opt.clim = [min(opt.ana(:)) max(opt.ana(:))]; end % reduce color scale range by 10% cscalefactor = (opt.clim(2)-opt.clim(1))/10; %opt.clim(1) = opt.clim(1)+cscalefactor; opt.clim(2) = opt.clim(2)-cscalefactor; setappdata(h, 'opt', opt); cb_redraw(h); case {45 'shift+hyphen'} % numpad - if isempty(opt.clim) opt.clim = [min(opt.ana(:)) max(opt.ana(:))]; end % increase color scale range by 10% cscalefactor = (opt.clim(2)-opt.clim(1))/10; %opt.clim(1) = opt.clim(1)-cscalefactor; opt.clim(2) = opt.clim(2)+cscalefactor; setappdata(h, 'opt', opt); cb_redraw(h); case 99 % 'c' opt.showcrosshair = ~opt.showcrosshair; setappdata(h, 'opt', opt); cb_redraw(h); case 102 % 'f' opt.showmarkers = ~opt.showmarkers; setappdata(h, 'opt', opt); cb_redraw(h); case 3 % right mouse click % add point to a list l1 = get(get(gca, 'xlabel'), 'string'); l2 = get(get(gca, 'ylabel'), 'string'); switch l1, case 'i' xc = d1; case 'j' yc = d1; case 'k' zc = d1; end switch l2, case 'i' xc = d2; case 'j' yc = d2; case 'k' zc = d2; end pnt = [pnt; xc yc zc]; case 2 % middle mouse click l1 = get(get(gca, 'xlabel'), 'string'); l2 = get(get(gca, 'ylabel'), 'string'); % remove the previous point if size(pnt,1)>0 pnt(end,:) = []; end if l1=='i' && l2=='j' updatepanel = [1 2 3]; elseif l1=='i' && l2=='k' updatepanel = [2 3 1]; elseif l1=='j' && l2=='k' updatepanel = [3 1 2]; end otherwise % do nothing end % switch key %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_buttonpress(h, eventdata) h = getparent(h); cb_getposition(h); switch get(h, 'selectiontype') case 'normal' % just update to new position, nothing else to be done here cb_redraw(h); case 'alt' set(h, 'windowbuttonmotionfcn', @cb_tracemouse); cb_redraw(h); otherwise end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_buttonrelease(h, eventdata) set(h, 'windowbuttonmotionfcn', ''); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_tracemouse(h, eventdata) h = getparent(h); cb_getposition(h); cb_redraw(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_getposition(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); curr_ax = get(h, 'currentaxes'); pos = mean(get(curr_ax, 'currentpoint')); tag = get(curr_ax, 'tag'); if ~isempty(tag) && ~opt.init if strcmp(tag, 'ik') opt.ijk([1 3]) = round(pos([1 3])); opt.update = [1 1 1]; elseif strcmp(tag, 'ij') opt.ijk([1 2]) = round(pos([1 2])); opt.update = [1 1 1]; elseif strcmp(tag, 'jk') opt.ijk([2 3]) = round(pos([2 3])); opt.update = [1 1 1]; end end opt.ijk = min(opt.ijk(:)', opt.dim); opt.ijk = max(opt.ijk(:)', [1 1 1]); if opt.magnet % magnetize try center = opt.ijk; radius = opt.magradius; % FIXME here it would be possible to adjust the selection at the edges of the volume xsel = center(1)+(-radius:radius); ysel = center(2)+(-radius:radius); zsel = center(3)+(-radius:radius); cubic = opt.ana(xsel, ysel, zsel); if strcmp(opt.magtype, 'peak') % find the peak intensity voxel within the cube [val, idx] = max(cubic(:)); [ix, iy, iz] = ind2sub(size(cubic), idx); elseif strcmp(opt.magtype, 'trough') % find the trough intensity voxel within the cube [val, idx] = min(cubic(:)); [ix, iy, iz] = ind2sub(size(cubic), idx); elseif strcmp(opt.magtype, 'weighted') % find the weighted center of mass in the cube dim = size(cubic); [X, Y, Z] = ndgrid(1:dim(1), 1:dim(2), 1:dim(3)); cubic = cubic./sum(cubic(:)); ix = round(X(:)' * cubic(:)); iy = round(Y(:)' * cubic(:)); iz = round(Z(:)' * cubic(:)); end % adjust the indices for the selection opt.ijk = [ix, iy, iz] + center - radius - 1; fprintf('==================================================================================\n'); fprintf(' clicked at [%d %d %d], %s magnetized adjustment [%d %d %d]\n', center, opt.magtype, opt.ijk-center); catch % this fails if the selection is at the edge of the volume warning('cannot magnetize at the edge of the volume'); end end % if magnetize setappdata(h, 'opt', opt); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_cleanup(h, eventdata) opt = getappdata(h, 'opt'); if isfield(opt, 'scatterfig') cb_scattercleanup(opt.scatterfig); end opt.quit = true; setappdata(h, 'opt', opt); uiresume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = getparent(h) p = h; while p~=0 h = p; p = get(h, 'parent'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key = parseKeyboardEvent(eventdata) key = eventdata.Key; % handle possible numpad events (different for Windows and UNIX systems) % NOTE: shift+numpad number does not work on UNIX, since the shift % modifier is always sent for numpad events if isunix() shiftInd = match_str(eventdata.Modifier, 'shift'); if ~isnan(str2double(eventdata.Character)) && ~isempty(shiftInd) % now we now it was a numpad keystroke (numeric character sent AND % shift modifier present) key = eventdata.Character; eventdata.Modifier(shiftInd) = []; % strip the shift modifier end elseif ispc() if strfind(eventdata.Key, 'numpad') key = eventdata.Character;d end end if ~isempty(eventdata.Modifier) key = [eventdata.Modifier{1} '+' key]; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_minslider(h4, eventdata) newlim = get(h4, 'value'); h = getparent(h4); opt = getappdata(h, 'opt'); opt.clim(1) = newlim; fprintf('contrast limits updated to [%.03f %.03f]\n', opt.clim); setappdata(h, 'opt', opt); cb_redraw(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_maxslider(h5, eventdata) newlim = get(h5, 'value'); h = getparent(h5); opt = getappdata(h, 'opt'); opt.clim(2) = newlim; fprintf('contrast limits updated to [%.03f %.03f]\n', opt.clim); setappdata(h, 'opt', opt); cb_redraw(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_intensityslider(h4, eventdata) % java intensity range slider - not fully functional loval = get(h4, 'value'); hival = get(h4, 'highvalue'); h = getparent(h4); % this fails: The name 'parent' is not an accessible property for an instance of class 'com.jidesoft.swing.RangeSlider'. opt = getappdata(h, 'opt'); opt.clim = [loval hival]; setappdata(h, 'opt', opt); cb_redraw(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_eleclistbox(h6, eventdata) elecidx = get(h6, 'Value'); % chosen elec listtopidx = get(h6, 'ListboxTop'); % ensure listbox does not move upon label selec if ~isempty(elecidx) if numel(elecidx)>1 fprintf('too many labels selected\n'); return end eleclis = cellstr(get(h6, 'String')); % all labels eleclab = eleclis{elecidx}; % this elec's label h = getparent(h6); opt = getappdata(h, 'opt'); % toggle electrode status and assign markers if strfind(eleclab, 'silver') % not yet, check fprintf('assigning marker %s\n', opt.label{elecidx,1}); eleclab = regexprep(eleclab, '"silver"','"black"'); % replace font color opt.markerlab{elecidx,1} = opt.label(elecidx,1); % assign marker label opt.markerpos{elecidx,1} = opt.pos; % assign marker position elseif strfind(eleclab, 'black') % already chosen before, move cusor to marker or uncheck if strcmp(get(h,'SelectionType'),'normal') % single click to move cursor to fprintf('moving cursor to marker %s\n', opt.label{elecidx,1}); opt.ijk = ft_warp_apply(inv(opt.mri.transform), opt.markerpos{elecidx,1}); % move cursor to marker position elseif strcmp(get(h,'SelectionType'),'open') % double click to uncheck fprintf('removing marker %s\n', opt.label{elecidx,1}); eleclab = regexprep(eleclab, '"black"','"silver"'); % replace font color opt.markerlab{elecidx,1} = {}; % assign marker label opt.markerpos{elecidx,1} = zeros(0,3); % assign marker position end end % update plot eleclis{elecidx} = eleclab; set(h6, 'String', eleclis); set(h6, 'ListboxTop', listtopidx); % ensure listbox does not move upon label selec setappdata(h, 'opt', opt); cb_redraw(h); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_magnetbutton(h7, eventdata) h = getparent(h7); opt = getappdata(h, 'opt'); opt.magnet = get(h7, 'value'); setappdata(h, 'opt', opt); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_labelsbutton(h8, eventdata) h = getparent(h8); opt = getappdata(h, 'opt'); opt.showlabels = get(h8, 'value'); setappdata(h, 'opt', opt); cb_redraw(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_globalbutton(h9, eventdata) h = getparent(h9); opt = getappdata(h, 'opt'); opt.global = get(h9, 'value'); setappdata(h, 'opt', opt); cb_redraw(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_zoomslider(h10, eventdata) h = getparent(h10); opt = getappdata(h, 'opt'); opt.zoom = round(get(h10, 'value')*10)/10; setappdata(h, 'opt', opt); cb_redraw(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_scatterbutton(hscatter, eventdata) h = getparent(hscatter); opt = getappdata(h, 'opt'); opt.scatter = get(hscatter, 'value'); % update value setappdata(h, 'opt', opt); if isfield(opt, 'scatterfig') && ~opt.scatter % if already open but shouldn't, close it cb_scattercleanup(opt.scatterfig); end if opt.scatter cb_scatterredraw(h); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_scattercleanup(hObject, eventdata) h = findobj('type','figure','name',mfilename); opt = getappdata(h, 'opt'); opt.scatter = 0; set(opt.handlesaxes(11), 'Value', 0); opt = rmfield(opt, 'scatterfig'); setappdata(h, 'opt', opt); delete(hObject); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_scatterminslider(h2, eventdata) h = findobj('type','figure','name',mfilename); opt = getappdata(h, 'opt'); opt.slim(1) = get(h2, 'value'); fprintf('scatter limits updated to [%.03f %.03f]\n', opt.slim); setappdata(h, 'opt', opt); delete(findobj('type','scatter')); % remove previous scatters msize = round(2500/opt.mri.dim(3)); % headsize (25 cm) / z slices inc = abs(opt.slim(2)-opt.slim(1))/4; % color increments for r = 1:4 % 4 color layers to encode peaks lim1 = opt.slim(1) + r*inc - inc; lim2 = opt.slim(1) + r*inc; voxind = find(opt.ana>lim1 & opt.ana<lim2); [x,y,z] = ind2sub(opt.mri.dim, voxind); hold on; scatter3(x,y,z,msize,'Marker','s','MarkerEdgeColor','none','MarkerFaceColor',[.8-(r*.2) .8-(r*.2) .8-(r*.2)]); end cb_scatterredraw(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_scattermaxslider(h3, eventdata) h = findobj('type','figure','name',mfilename); opt = getappdata(h, 'opt'); opt.slim(2) = get(h3, 'value'); fprintf('scatter limits updated to [%.03f %.03f]\n', opt.slim); setappdata(h, 'opt', opt); delete(findobj('type','scatter')); % remove previous scatters msize = round(2500/opt.mri.dim(3)); % headsize (25 cm) / z slices inc = abs(opt.slim(2)-opt.slim(1))/4; % color increments for r = 1:4 % 4 color layers to encode peaks lim1 = opt.slim(1) + r*inc - inc; lim2 = opt.slim(1) + r*inc; voxind = find(opt.ana>lim1 & opt.ana<lim2); [x,y,z] = ind2sub(opt.mri.dim, voxind); hold on; scatter3(x,y,z,msize,'Marker','s','MarkerEdgeColor','none','MarkerFaceColor',[.8-(r*.2) .8-(r*.2) .8-(r*.2)]); end cb_scatterredraw(h);
github
lcnbeapp/beapp-master
ft_sourceplot.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_sourceplot.m
66,934
utf_8
ac9cf37d2c1a5f847260b28941afca09
function ft_sourceplot(cfg, functional, anatomical) % FT_SOURCEPLOT plots functional source reconstruction data on slices or on a % surface, optionally as an overlay on anatomical MRI data, where statistical data % can be used to determine the opacity of the mask. Input data comes from % FT_SOURCEANALYSIS, FT_SOURCEGRANDAVERAGE or statistical values from % FT_SOURCESTATISTICS. % % Use as % ft_sourceplot(cfg, data) % where the input data can contain an anatomical MRI, functional source % reconstruction results and/or statistical data. If both anatomical and % functional/statistical data is provided as input, they should be represented or % interpolated on the same same 3-D grid, e.g. using FT_SOURCEINTERPOLATE. % % The slice and ortho visualization plot the data in the input data voxel % arrangement, i.e. the three ortho views are the 1st, 2nd and 3rd dimension of % the 3-D data matrix, not of the head coordinate system. The specification of the % coordinate for slice intersection is specified in head coordinates, i.e. % relative to the fiducials and in mm or cm. If you want the visualisation to be % consistent with the head coordinate system, you can reslice the data using % FT_VOLUMERESLICE. % % The configuration should contain: % cfg.method = 'slice', plots the data on a number of slices in the same plane % 'ortho', plots the data on three orthogonal slices % 'surface', plots the data on a 3D brain surface % 'glassbrain', plots a max-projection through the brain % 'vertex', plots the grid points or vertices scaled according to the functional value % % cfg.anaparameter = string, field in data with the anatomical data (default = 'anatomy' if present in data) % cfg.funparameter = string, field in data with the functional parameter of interest (default = []) % cfg.maskparameter = string, field in the data to be used for opacity masking of fun data (default = []) % If values are between 0 and 1, zero is fully transparant and one is fully opaque. % If values in the field are not between 0 and 1 they will be scaled depending on the values % of cfg.opacitymap and cfg.opacitylim (see below) % You can use masking in several ways, f.i. % - use outcome of statistics to show only the significant values and mask the insignificant % NB see also cfg.opacitymap and cfg.opacitylim below % - use the functional data itself as mask, the highest value (and/or lowest when negative) % will be opaque and the value closest to zero transparent % - Make your own field in the data with values between 0 and 1 to control opacity directly % % The following parameters can be used in all methods: % cfg.downsample = downsampling for resolution reduction, integer value (default = 1) (orig: from surface) % cfg.atlas = string, filename of atlas to use (default = []) see FT_READ_ATLAS % for ROI masking (see "masking" below) or in "ortho-plotting" mode (see "ortho-plotting" below) % % The following parameters can be used for the functional data: % cfg.funcolormap = colormap for functional data, see COLORMAP (default = 'auto') % 'auto', depends structure funparameter, or on funcolorlim % - funparameter: only positive values, or funcolorlim:'zeromax' -> 'hot' % - funparameter: only negative values, or funcolorlim:'minzero' -> 'cool' % - funparameter: both pos and neg values, or funcolorlim:'maxabs' -> 'default' % - funcolorlim: [min max] if min & max pos-> 'hot', neg-> 'cool', both-> 'default' % cfg.funcolorlim = color range of the functional data (default = 'auto') % [min max] % 'maxabs', from -max(abs(funparameter)) to +max(abs(funparameter)) % 'zeromax', from 0 to max(funparameter) % 'minzero', from min(funparameter) to 0 % 'auto', if funparameter values are all positive: 'zeromax', % all negative: 'minzero', both possitive and negative: 'maxabs' % cfg.colorbar = 'yes' or 'no' (default = 'yes') % % The following parameters can be used for the masking data: % cfg.opacitymap = opacitymap for mask data, see ALPHAMAP (default = 'auto') % 'auto', depends structure maskparameter, or on opacitylim % - maskparameter: only positive values, or opacitylim:'zeromax' -> 'rampup' % - maskparameter: only negative values, or opacitylim:'minzero' -> 'rampdown' % - maskparameter: both pos and neg values, or opacitylim:'maxabs' -> 'vdown' % - opacitylim: [min max] if min & max pos-> 'rampup', neg-> 'rampdown', both-> 'vdown' % - NB. to use p-values use 'rampdown' to get lowest p-values opaque and highest transparent % cfg.opacitylim = range of mask values to which opacitymap is scaled (default = 'auto') % [min max] % 'maxabs', from -max(abs(maskparameter)) to +max(abs(maskparameter)) % 'zeromax', from 0 to max(abs(maskparameter)) % 'minzero', from min(abs(maskparameter)) to 0 % 'auto', if maskparameter values are all positive: 'zeromax', % all negative: 'minzero', both possitive and negative: 'maxabs' % cfg.roi = string or cell of strings, region(s) of interest from anatomical atlas (see cfg.atlas above) % everything is masked except for ROI % % The following parameters apply for ortho-plotting % cfg.location = location of cut, (default = 'auto') % 'auto', 'center' if only anatomy, 'max' if functional data % 'min' and 'max' position of min/max funparameter % 'center' of the brain % [x y z], coordinates in voxels or head, see cfg.locationcoordinates % cfg.locationcoordinates = coordinate system used in cfg.location, 'head' or 'voxel' (default = 'head') % 'head', headcoordinates as mm or cm % 'voxel', voxelcoordinates as indices % cfg.crosshair = 'yes' or 'no' (default = 'yes') % cfg.axis = 'on' or 'off' (default = 'on') % cfg.queryrange = number, in atlas voxels (default 3) % % % The following parameters apply for slice-plotting % cfg.nslices = number of slices, (default = 20) % cfg.slicerange = range of slices in data, (default = 'auto') % 'auto', full range of data % [min max], coordinates of first and last slice in voxels % cfg.slicedim = dimension to slice 1 (x-axis) 2(y-axis) 3(z-axis) (default = 3) % cfg.title = string, title of the figure window % % When cfg.method = 'surface', the functional data will be rendered onto a cortical % mesh (can be an inflated mesh). If the input source data contains a tri-field (i.e. % a description of a mesh), no interpolation is needed. If the input source data does % not contain a tri-field, an interpolation is performed onto a specified surface. % Note that the coordinate system in which the surface is defined should be the same % as the coordinate system that is represented in source.pos. % % The following parameters apply to surface-plotting when an interpolation % is required % cfg.surffile = string, file that contains the surface (default = 'surface_white_both.mat') % 'surface_white_both.mat' contains a triangulation that corresponds with the % SPM anatomical template in MNI coordinates % cfg.surfinflated = string, file that contains the inflated surface (default = []) % may require specifying a point-matching (uninflated) surffile % cfg.surfdownsample = number (default = 1, i.e. no downsampling) % cfg.projmethod = projection method, how functional volume data is projected onto surface % 'nearest', 'project', 'sphere_avg', 'sphere_weighteddistance' % cfg.projvec = vector (in mm) to allow different projections that % are combined with the method specified in cfg.projcomb % cfg.projcomb = 'mean', 'max', method to combine the different projections % cfg.projweight = vector of weights for the different projections (default = 1) % cfg.projthresh = implements thresholding on the surface level % for example, 0.7 means 70% of maximum % cfg.sphereradius = maximum distance from each voxel to the surface to be % included in the sphere projection methods, expressed in mm % cfg.distmat = precomputed distance matrix (default = []) % % The following parameters apply to surface-plotting independent of whether % an interpolation is required % cfg.camlight = 'yes' or 'no' (default = 'yes') % cfg.renderer = 'painters', 'zbuffer', ' opengl' or 'none' (default = 'opengl') % note that when using opacity the OpenGL renderer is required. % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % If you specify this option the input data will be read from a *.mat file on % disk. This mat files should contain only a single variable corresponding to the % input structure. % % See also FT_SOURCEMOVIE, FT_SOURCEANALYSIS, FT_SOURCEGRANDAVERAGE, % FT_SOURCESTATISTICS, FT_VOLUMELOOKUP, FT_READ_ATLAS, FT_READ_MRI % TODO have to be built in: % cfg.marker = [Nx3] array defining N marker positions to display (orig: from sliceinterp) % cfg.markersize = radius of markers (default = 5) % cfg.markercolor = [1x3] marker color in RGB (default = [1 1 1], i.e. white) (orig: from sliceinterp) % white background option % undocumented TODO % slice in all directions % surface also optimal when inside present % come up with a good glass brain projection % Copyright (C) 2007-2016, Robert Oostenveld, Ingrid Nieuwenhuis % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar functional anatomical ft_preamble provenance functional anatomical ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % this is not supported any more as of 26/10/2011 if ischar(functional) error('please use cfg.inputfile instead of specifying the input variable as a sting'); end % ensure that old and unsupported options are not being relied on by the end-user's script cfg = ft_checkconfig(cfg, 'renamedval', {'funparameter', 'avg.pow', 'pow'}); cfg = ft_checkconfig(cfg, 'renamedval', {'funparameter', 'avg.coh', 'coh'}); cfg = ft_checkconfig(cfg, 'renamedval', {'funparameter', 'avg.mom', 'mom'}); cfg = ft_checkconfig(cfg, 'renamedval', {'maskparameter', 'avg.pow', 'pow'}); cfg = ft_checkconfig(cfg, 'renamedval', {'maskparameter', 'avg.coh', 'coh'}); cfg = ft_checkconfig(cfg, 'renamedval', {'maskparameter', 'avg.mom', 'mom'}); cfg = ft_checkconfig(cfg, 'renamedval', {'location', 'interactive', 'auto'}); % instead of specifying cfg.coordsys, the user should specify the coordsys in the functional data cfg = ft_checkconfig(cfg, 'forbidden', {'units', 'inputcoordsys', 'coordinates'}); cfg = ft_checkconfig(cfg, 'deprecated', 'coordsys'); % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=2837 cfg = ft_checkconfig(cfg, 'renamed', {'viewdim', 'axisratio'}); if isfield(cfg, 'atlas') && ~isempty(cfg.atlas) % the atlas lookup requires the specification of the coordsys functional = ft_checkdata(functional, 'datatype', {'volume', 'source'}, 'feedback', 'yes', 'hasunit', 'yes', 'hascoordsys', 'yes'); else % check if the input functional is valid for this function, a coordsys is not directly needed functional = ft_checkdata(functional, 'datatype', {'volume', 'source'}, 'feedback', 'yes', 'hasunit', 'yes'); end % set the defaults for all methods cfg.method = ft_getopt(cfg, 'method', 'ortho'); cfg.funparameter = ft_getopt(cfg, 'funparameter', []); cfg.maskparameter = ft_getopt(cfg, 'maskparameter', []); cfg.downsample = ft_getopt(cfg, 'downsample', 1); cfg.title = ft_getopt(cfg, 'title', ''); cfg.atlas = ft_getopt(cfg, 'atlas', []); cfg.marker = ft_getopt(cfg, 'marker', []); cfg.markersize = ft_getopt(cfg, 'markersize', 5); cfg.markercolor = ft_getopt(cfg, 'markercolor', [1 1 1]); cfg.renderer = ft_getopt(cfg, 'renderer', 'opengl'); cfg.colorbar = ft_getopt(cfg, 'colorbar', 'yes'); cfg.voxelratio = ft_getopt(cfg, 'voxelratio', 'data'); % display size of the voxel, 'data' or 'square' cfg.axisratio = ft_getopt(cfg, 'axisratio', 'data'); % size of the axes of the three orthoplots, 'square', 'voxel', or 'data' if ~isfield(cfg, 'anaparameter') if isfield(functional, 'anatomy') cfg.anaparameter = 'anatomy'; else cfg.anaparameter = []; end end % set the common defaults for the functional data cfg.funcolormap = ft_getopt(cfg, 'funcolormap', 'auto'); cfg.funcolorlim = ft_getopt(cfg, 'funcolorlim', 'auto'); % set the common defaults for the statistical data cfg.opacitymap = ft_getopt(cfg, 'opacitymap', 'auto'); cfg.opacitylim = ft_getopt(cfg, 'opacitylim', 'auto'); cfg.roi = ft_getopt(cfg, 'roi', []); if isfield(cfg, 'TTlookup'), error('TTlookup is old; now specify cfg.atlas, see help!'); end % select the functional and the mask parameter cfg.funparameter = parameterselection(cfg.funparameter, functional); cfg.maskparameter = parameterselection(cfg.maskparameter, functional); % only a single parameter should be selected try, cfg.funparameter = cfg.funparameter{1}; end try, cfg.maskparameter = cfg.maskparameter{1}; end % the data can be passed as input argument or can be read from disk hasanatomical = exist('anatomical', 'var'); if hasanatomical % interpolate on the fly, this also does the downsampling if requested tmpcfg = keepfields(cfg, {'downsample', 'interpmethod'}); tmpcfg.parameter = cfg.funparameter; functional = ft_sourceinterpolate(tmpcfg, functional, anatomical); [cfg, functional] = rollback_provenance(cfg, functional); elseif ~hasanatomical && cfg.downsample~=1 % optionally downsample the functional volume tmpcfg = keepfields(cfg, {'downsample'}); tmpcfg.parameter = {cfg.funparameter, cfg.maskparameter, cfg.anaparameter}; functional = ft_volumedownsample(tmpcfg, functional); [cfg, functional] = rollback_provenance(cfg, functional); end if isfield(functional, 'dim') && isfield(functional, 'transform') % this is a regular 3D functional volume isUnstructuredFun = false; elseif isfield(functional, 'dim') && isfield(functional, 'pos') % these are positions that can be mapped onto a 3D regular grid isUnstructuredFun = false; % contstruct the transformation matrix from the positions functional.transform = pos2transform(functional.pos, functional.dim); else % this is functional data on irregular positions, such as a cortical sheet isUnstructuredFun = true; end % this only relates to the dimensions of the geometry, which is npos*1 or nx*ny*nz if isUnstructuredFun dim = [size(functional.pos,1) 1]; else dim = functional.dim; end %% get the elements that will be plotted hasatlas = ~isempty(cfg.atlas); if hasatlas if ischar(cfg.atlas) % initialize the atlas [p, f, x] = fileparts(cfg.atlas); fprintf(['reading ', f, ' atlas coordinates and labels\n']); atlas = ft_read_atlas(cfg.atlas); else atlas = cfg.atlas; end end hasroi = ~isempty(cfg.roi); if hasroi if ~hasatlas error('specify cfg.atlas which specifies cfg.roi') else % get the mask tmpcfg = []; tmpcfg.roi = cfg.roi; tmpcfg.atlas = cfg.atlas; tmpcfg.inputcoord = functional.coordsys; roi = ft_volumelookup(tmpcfg,functional); end end hasana = isfield(functional, cfg.anaparameter); if hasana ana = getsubfield(functional, cfg.anaparameter); if isa(ana, 'uint8') || isa(ana, 'uint16') || isa(ana, 'int8') || isa(ana, 'int16') ana = double(ana); end fprintf('scaling anatomy to [0 1]\n'); dmin = min(ana(:)); dmax = max(ana(:)); ana = (ana-dmin)./(dmax-dmin); ana = reshape(ana, dim); end %%% funparameter hasfun = isfield(functional, cfg.funparameter); if hasfun fun = getsubfield(functional, cfg.funparameter); dimord = getdimord(functional, cfg.funparameter); dimtok = tokenize(dimord, '_'); % replace the cell-array functional with a normal array if strcmp(dimtok{1}, '{pos}') tmpdim = getdimsiz(functional, cfg.funparameter); tmpfun = nan(tmpdim); insideindx = find(functional.inside); for i=insideindx(:)' tmpfun(i,:) = fun{i}; end fun = tmpfun; clear tmpfun dimtok{1} = 'pos'; % update the description of the dimensions dimord([1 5]) = []; % remove the { and } end % ensure that the functional data is real if ~isreal(fun) warning('functional data is complex, taking absolute value'); fun = abs(fun); end if strcmp(dimord, 'pos_rgb') % treat functional data as rgb values if any(fun(:)>1 | fun(:)<0) % scale tmpdim = size(fun); nvox = prod(tmpdim(1:end-1)); tmpfun = reshape(fun,[nvox tmpdim(end)]); m1 = max(tmpfun,[],1); m2 = min(tmpfun,[],1); tmpfun = (tmpfun-m2(ones(nvox,1),:))./(m1(ones(nvox,1),:)-m2(ones(nvox,1),:)); fun = reshape(tmpfun, tmpdim); clear tmpfun end qi = 1; hasfreq = 0; hastime = 0; doimage = 1; fcolmin = 0; fcolmax = 1; else % determine scaling min and max (fcolmin fcolmax) and funcolormap if ~isa(fun, 'logical') funmin = min(fun(:)); funmax = max(fun(:)); else funmin = 0; funmax = 1; end % smart automatic limits if isequal(cfg.funcolorlim, 'auto') if sign(funmin)>-1 && sign(funmax)>-1 cfg.funcolorlim = 'zeromax'; elseif sign(funmin)<1 && sign(funmax)<1 cfg.funcolorlim = 'minzero'; else cfg.funcolorlim = 'maxabs'; end end if ischar(cfg.funcolorlim) % limits are given as string if isequal(cfg.funcolorlim, 'maxabs') fcolmin = -max(abs([funmin,funmax])); fcolmax = max(abs([funmin,funmax])); if isequal(cfg.funcolormap, 'auto'); cfg.funcolormap = 'default'; end; elseif isequal(cfg.funcolorlim, 'zeromax') fcolmin = 0; fcolmax = funmax; if isequal(cfg.funcolormap, 'auto'); cfg.funcolormap = 'hot'; end; elseif isequal(cfg.funcolorlim, 'minzero') fcolmin = funmin; fcolmax = 0; if isequal(cfg.funcolormap, 'auto'); cfg.funcolormap = 'cool'; end; else error('do not understand cfg.funcolorlim'); end else % limits are numeric fcolmin = cfg.funcolorlim(1); fcolmax = cfg.funcolorlim(2); % smart colormap if isequal(cfg.funcolormap, 'auto') if sign(fcolmin) == -1 && sign(fcolmax) == 1 cfg.funcolormap = 'default'; else if fcolmin < 0 cfg.funcolormap = 'cool'; else cfg.funcolormap = 'hot'; end end end end % if ischar clear funmin funmax % what if fun is 4D? if ndims(fun)>3 || prod(dim)==size(fun,1) if strcmp(dimord, 'pos_freq_time') % functional contains time-frequency representation qi = [1 1]; hasfreq = numel(functional.freq)>1; hastime = numel(functional.time)>1; fun = reshape(fun, [dim numel(functional.freq) numel(functional.time)]); elseif strcmp(dimord, 'pos_time') % functional contains evoked field qi = 1; hasfreq = 0; hastime = numel(functional.time)>1; fun = reshape(fun, [dim numel(functional.time)]); elseif strcmp(dimord, 'pos_freq') % functional contains frequency spectra qi = 1; hasfreq = numel(functional.freq)>1; hastime = 0; fun = reshape(fun, [dim numel(functional.freq)]); else qi = 1; hasfreq = 0; hastime = 0; fun = reshape(fun, dim); end else % do nothing qi = 1; hasfreq = 0; hastime = 0; end doimage = 0; end % if dimord has rgb or something else else % there is no functional data qi = 1; hasfreq = 0; hastime = 0; doimage = 0; fcolmin = 0; % needs to be defined for callback fcolmax = 1; end hasmsk = issubfield(functional, cfg.maskparameter); if hasmsk if ~hasfun error('you can not have a mask without functional data') else msk = getsubfield(functional, cfg.maskparameter); if islogical(msk) % otherwise sign() not posible msk = double(msk); end end % reshape to match fun if strcmp(dimord, 'pos_freq_time') % functional contains timefrequency representation msk = reshape(msk, [dim numel(functional.freq) numel(functional.time)]); elseif strcmp(dimord, 'pos_time') % functional contains evoked field msk = reshape(msk, [dim numel(functional.time)]); elseif strcmp(dimord, 'pos_freq') % functional contains frequency spectra msk = reshape(msk, [dim numel(functional.freq)]); else msk = reshape(msk, dim); end % determine scaling and opacitymap mskmin = min(msk(:)); mskmax = max(msk(:)); % determine the opacity limits and the opacity map % smart limits: make from auto other string, or equal to funcolorlim if funparameter == maskparameter if isequal(cfg.opacitylim, 'auto') if isequal(cfg.funparameter,cfg.maskparameter) cfg.opacitylim = cfg.funcolorlim; else if sign(mskmin)>-1 && sign(mskmax)>-1 cfg.opacitylim = 'zeromax'; elseif sign(mskmin)<1 && sign(mskmax)<1 cfg.opacitylim = 'minzero'; else cfg.opacitylim = 'maxabs'; end end end if ischar(cfg.opacitylim) % limits are given as string switch cfg.opacitylim case 'zeromax' opacmin = 0; opacmax = mskmax; if isequal(cfg.opacitymap, 'auto'), cfg.opacitymap = 'rampup'; end; case 'minzero' opacmin = mskmin; opacmax = 0; if isequal(cfg.opacitymap, 'auto'), cfg.opacitymap = 'rampdown'; end; case 'maxabs' opacmin = -max(abs([mskmin, mskmax])); opacmax = max(abs([mskmin, mskmax])); if isequal(cfg.opacitymap, 'auto'), cfg.opacitymap = 'vdown'; end; otherwise error('incorrect specification of cfg.opacitylim'); end % switch opacitylim else % limits are numeric opacmin = cfg.opacitylim(1); opacmax = cfg.opacitylim(2); if isequal(cfg.opacitymap, 'auto') if sign(opacmin)>-1 && sign(opacmax)>-1 cfg.opacitymap = 'rampup'; elseif sign(opacmin)<1 && sign(opacmax)<1 cfg.opacitymap = 'rampdown'; else cfg.opacitymap = 'vdown'; end end end % handling opacitylim and opacitymap clear mskmin mskmax else opacmin = []; opacmax = []; end % prevent outside fun from being plotted if hasfun && ~hasmsk && isfield(functional, 'inside') hasmsk = 1; msk = zeros(dim); cfg.opacitymap = 'rampup'; opacmin = 0; opacmax = 1; % make intelligent mask if isequal(cfg.method, 'surface') msk(functional.inside) = 1; else if hasana msk(functional.inside) = 0.5; % so anatomy is visible else msk(functional.inside) = 1; end end end % if region of interest is specified, mask everything besides roi if hasfun && hasroi && ~hasmsk hasmsk = 1; msk = roi; cfg.opacitymap = 'rampup'; opacmin = 0; opacmax = 1; elseif hasfun && hasroi && hasmsk msk = roi .* msk; opacmin = []; opacmax = []; % has to be defined elseif hasroi error('you can not have a roi without functional data') end %% give some feedback if ~hasfun && ~hasana % this seems to be a problem that people often have due to incorrect specification of the cfg error('no anatomy is present and no functional data is selected, please check your cfg.funparameter'); end if ~hasana fprintf('not plotting anatomy\n'); end if ~hasfun fprintf('not plotting functional data\n'); end if ~hasmsk fprintf('not applying a mask on the functional data\n'); end if ~hasatlas fprintf('not using an atlas\n'); end if ~hasroi fprintf('not using a region-of-interest\n'); end %% start building the figure h = figure; set(h, 'color', [1 1 1]); set(h, 'visible', 'on'); set(h, 'renderer', cfg.renderer); if ~isempty(cfg.title) title(cfg.title); end %%% set color and opacity mapping for this figure if hasfun colormap(cfg.funcolormap); cfg.funcolormap = colormap; end if hasmsk cfg.opacitymap = alphamap(cfg.opacitymap); alphamap(cfg.opacitymap); if ndims(fun)>3 && ndims(msk)==3 siz = size(fun); msk = repmat(msk, [1 1 1 siz(4:end)]); end end switch cfg.method case 'slice' % set the defaults for method=slice cfg.nslices = ft_getopt(cfg, 'nslices', 20); cfg.slicedim = ft_getopt(cfg, 'slicedim', 3); cfg.slicerange = ft_getopt(cfg, 'slicerange', 'auto'); % white BG => mskana % TODO: HERE THE FUNCTION THAT MAKES TO SLICE DIMENSION ALWAYS THE THIRD DIMENSION, AND ALSO KEEP TRANSFORMATION MATRIX UP TO DATE % zoiets % if hasana; ana = shiftdim(ana,cfg.slicedim-1); end; % if hasfun; fun = shiftdim(fun,cfg.slicedim-1); end; % if hasmsk; msk = shiftdim(msk,cfg.slicedim-1); end; % ADDED BY JM: allow for slicedim different than 3 switch cfg.slicedim case 1 dim = dim([2 3 1]); if hasana, ana = permute(ana,[2 3 1]); end if hasfun, fun = permute(fun,[2 3 1]); end if hasmsk, msk = permute(msk,[2 3 1]); end cfg.slicedim=3; case 2 dim = dim([3 1 2]); if hasana, ana = permute(ana,[3 1 2]); end if hasfun, fun = permute(fun,[3 1 2]); end if hasmsk, msk = permute(msk,[3 1 2]); end cfg.slicedim=3; otherwise % nothing needed end %%%%% select slices if ~ischar(cfg.slicerange) ind_fslice = cfg.slicerange(1); ind_lslice = cfg.slicerange(2); elseif isequal(cfg.slicerange, 'auto') if hasfun % default if isfield(functional, 'inside') insideMask = false(size(fun)); insideMask(functional.inside) = true; ind_fslice = min(find(max(max(insideMask,[],1),[],2))); ind_lslice = max(find(max(max(insideMask,[],1),[],2))); else ind_fslice = min(find(~isnan(max(max(fun,[],1),[],2)))); ind_lslice = max(find(~isnan(max(max(fun,[],1),[],2)))); end elseif hasana % if only ana, no fun ind_fslice = min(find(max(max(ana,[],1),[],2))); ind_lslice = max(find(max(max(ana,[],1),[],2))); else error('no functional parameter and no anatomical parameter, can not plot'); end else error('do not understand cfg.slicerange'); end ind_allslice = linspace(ind_fslice,ind_lslice,cfg.nslices); ind_allslice = round(ind_allslice); % make new ana, fun, msk, mskana with only the slices that will be plotted (slice dim is always third dimension) if hasana; new_ana = ana(:,:,ind_allslice); clear ana; ana=new_ana; clear new_ana; end; if hasfun; new_fun = fun(:,:,ind_allslice); clear fun; fun=new_fun; clear new_fun; end; if hasmsk; new_msk = msk(:,:,ind_allslice); clear msk; msk=new_msk; clear new_msk; end; % if hasmskana; new_mskana = mskana(:,:,ind_allslice); clear mskana; mskana=new_mskana; clear new_mskana; end; % update the dimensions of the volume if hasana; dim=size(ana); else dim=size(fun); end; %%%%% make a "quilt", that contain all slices on 2D patched sheet % Number of patches along sides of Quilt (M and N) % Size (in voxels) of side of patches of Quilt (m and n) % take care of a potential singleton 3rd dimension if numel(dim)<3 dim(end+1:3) = 1; end %if cfg.slicedim~=3 % error('only supported for slicedim=3'); %end m = dim(1); n = dim(2); M = ceil(sqrt(dim(3))); N = ceil(sqrt(dim(3))); num_patch = N*M; num_slice = (dim(cfg.slicedim)); num_empt = num_patch-num_slice; % put empty slides on ana, fun, msk, mskana to fill Quilt up if hasana; ana(:,:,end+1:num_patch)=0; end; if hasfun; fun(:,:,end+1:num_patch)=0; end; if hasmsk; msk(:,:,end+1:num_patch)=0; end; % if hasmskana; mskana(:,:,end:num_patch)=0; end; % put the slices in the quilt for iSlice = 1:num_slice xbeg = floor((iSlice-1)./M); ybeg = mod(iSlice-1, M); if hasana quilt_ana(ybeg*m+1:(ybeg+1)*m, xbeg*n+1:(xbeg+1)*n)=ana(:,:,iSlice); end if hasfun quilt_fun(ybeg*m+1:(ybeg+1)*m, xbeg*n+1:(xbeg+1)*n)=fun(:,:,iSlice); end if hasmsk quilt_msk(ybeg.*m+1:(ybeg+1)*m, xbeg*n+1:(xbeg+1)*n)=msk(:,:,iSlice); end % if hasmskana % quilt_mskana(ybeg.*m+1:(ybeg+1).*m, xbeg.*n+1:(xbeg+1).*n)=mskana(:,:,iSlice); % end end % make vols and scales, containes volumes to be plotted (fun, ana, msk), added by ingnie if hasana; vols2D{1} = quilt_ana; scales{1} = []; end; % needed when only plotting ana if hasfun; vols2D{2} = quilt_fun; scales{2} = [fcolmin fcolmax]; end; if hasmsk; vols2D{3} = quilt_msk; scales{3} = [opacmin opacmax]; end; % the transpose is needed for displaying the matrix using the MATLAB image() function if hasana; ana = vols2D{1}'; end; if hasfun && ~doimage; fun = vols2D{2}'; end; if hasfun && doimage; fun = permute(vols2D{2},[2 1 3]); end; if hasmsk; msk = vols2D{3}'; end; if hasana % scale anatomy between 0 and 1 fprintf('scaling anatomy\n'); amin = min(ana(:)); amax = max(ana(:)); ana = (ana-amin)./(amax-amin); clear amin amax; % convert anatomy into RGB values ana = cat(3, ana, ana, ana); ha = imagesc(ana); end hold on if hasfun if doimage hf = image(fun); else hf = imagesc(fun); try caxis(scales{2}); end % apply the opacity mask to the functional data if hasmsk % set the opacity set(hf, 'AlphaData', msk) set(hf, 'AlphaDataMapping', 'scaled') try alim(scales{3}); end elseif hasana set(hf, 'AlphaData', 0.5) end end end axis equal axis tight axis xy axis off if istrue(cfg.colorbar) if hasfun % use a normal MATLAB coorbar hc = colorbar; set(hc, 'YLim', [fcolmin fcolmax]); else warning('no colorbar possible without functional data') end end case 'ortho' % set the defaults for method=ortho cfg.location = ft_getopt(cfg, 'location', 'auto'); cfg.locationcoordinates = ft_getopt(cfg, 'locationcoordinates', 'head'); cfg.crosshair = ft_getopt(cfg, 'crosshair', 'yes'); cfg.axis = ft_getopt(cfg, 'axis', 'on'); cfg.queryrange = ft_getopt(cfg, 'queryrange', 3); if ~ischar(cfg.location) if strcmp(cfg.locationcoordinates, 'head') % convert the headcoordinates location into voxel coordinates loc = inv(functional.transform) * [cfg.location(:); 1]; loc = round(loc(1:3)); elseif strcmp(cfg.locationcoordinates, 'voxel') % the location is already in voxel coordinates loc = round(cfg.location(1:3)); else error('you should specify cfg.locationcoordinates'); end else if isequal(cfg.location, 'auto') if hasfun if isequal(cfg.funcolorlim, 'maxabs'); loc = 'max'; elseif isequal(cfg.funcolorlim, 'zeromax'); loc = 'max'; elseif isequal(cfg.funcolorlim, 'minzero'); loc = 'min'; else % if numerical loc = 'max'; end else loc = 'center'; end; else loc = cfg.location; end end % determine the initial intersection of the cursor (xi yi zi) if ischar(loc) && strcmp(loc, 'min') if isempty(cfg.funparameter) error('cfg.location is min, but no functional parameter specified'); end [dummy, minindx] = min(fun(:)); [xi, yi, zi] = ind2sub(dim, minindx); elseif ischar(loc) && strcmp(loc, 'max') if isempty(cfg.funparameter) error('cfg.location is max, but no functional parameter specified'); end [dummy, maxindx] = max(fun(:)); [xi, yi, zi] = ind2sub(dim, maxindx); elseif ischar(loc) && strcmp(loc, 'center') xi = round(dim(1)/2); yi = round(dim(2)/2); zi = round(dim(3)/2); elseif ~ischar(loc) % using nearest instead of round ensures that the position remains within the volume xi = nearest(1:dim(1), loc(1)); yi = nearest(1:dim(2), loc(2)); zi = nearest(1:dim(3), loc(3)); end xi = round(xi); xi = max(xi, 1); xi = min(xi, dim(1)); yi = round(yi); yi = max(yi, 1); yi = min(yi, dim(2)); zi = round(zi); zi = max(zi, 1); zi = min(zi, dim(3)); % axes settings if strcmp(cfg.axisratio, 'voxel') % determine the number of voxels to be plotted along each axis axlen1 = dim(1); axlen2 = dim(2); axlen3 = dim(3); elseif strcmp(cfg.axisratio, 'data') % determine the length of the edges along each axis [cp_voxel, cp_head] = cornerpoints(dim, functional.transform); axlen1 = norm(cp_head(2,:)-cp_head(1,:)); axlen2 = norm(cp_head(4,:)-cp_head(1,:)); axlen3 = norm(cp_head(5,:)-cp_head(1,:)); elseif strcmp(cfg.axisratio, 'square') % the length of the axes should be equal axlen1 = 1; axlen2 = 1; axlen3 = 1; end % this is the size reserved for subplot h1, h2 and h3 h1size(1) = 0.82*axlen1/(axlen1 + axlen2); h1size(2) = 0.82*axlen3/(axlen2 + axlen3); h2size(1) = 0.82*axlen2/(axlen1 + axlen2); h2size(2) = 0.82*axlen3/(axlen2 + axlen3); h3size(1) = 0.82*axlen1/(axlen1 + axlen2); h3size(2) = 0.82*axlen2/(axlen2 + axlen3); if strcmp(cfg.voxelratio, 'square') voxlen1 = 1; voxlen2 = 1; voxlen3 = 1; elseif strcmp(cfg.voxelratio, 'data') % the size of the voxel is scaled with the data [cp_voxel, cp_head] = cornerpoints(dim, functional.transform); voxlen1 = norm(cp_head(2,:)-cp_head(1,:))/norm(cp_voxel(2,:)-cp_voxel(1,:)); voxlen2 = norm(cp_head(4,:)-cp_head(1,:))/norm(cp_voxel(4,:)-cp_voxel(1,:)); voxlen3 = norm(cp_head(5,:)-cp_head(1,:))/norm(cp_voxel(5,:)-cp_voxel(1,:)); end %% the figure is interactive, add callbacks set(h, 'windowbuttondownfcn', @cb_buttonpress); set(h, 'windowbuttonupfcn', @cb_buttonrelease); set(h, 'windowkeypressfcn', @cb_keyboard); set(h, 'CloseRequestFcn', @cb_cleanup); % ensure that this is done in interactive mode set(h, 'renderer', cfg.renderer); %% create figure handles % axis handles will hold the anatomical functional if present, along with labels etc. h1 = axes('position',[0.06 0.06+0.06+h3size(2) h1size(1) h1size(2)]); h2 = axes('position',[0.06+0.06+h1size(1) 0.06+0.06+h3size(2) h2size(1) h2size(2)]); h3 = axes('position',[0.06 0.06 h3size(1) h3size(2)]); set(h1, 'Tag', 'ik', 'Visible', cfg.axis, 'XAxisLocation', 'top'); set(h2, 'Tag', 'jk', 'Visible', cfg.axis, 'YAxisLocation', 'right'); % after rotating in ft_plot_ortho this becomes top set(h3, 'Tag', 'ij', 'Visible', cfg.axis); set(h1, 'DataAspectRatio',1./[voxlen1 voxlen2 voxlen3]); set(h2, 'DataAspectRatio',1./[voxlen1 voxlen2 voxlen3]); set(h3, 'DataAspectRatio',1./[voxlen1 voxlen2 voxlen3]); % create structure to be passed to gui opt = []; opt.dim = dim; opt.ijk = [xi yi zi]; opt.h1size = h1size; opt.h2size = h2size; opt.h3size = h3size; opt.handlesaxes = [h1 h2 h3]; opt.handlesfigure = h; opt.axis = cfg.axis; if hasatlas opt.atlas = atlas; end if hasana opt.ana = ana; end if hasfun opt.fun = fun; end if hasmsk opt.msk = msk; end opt.update = [1 1 1]; opt.init = true; opt.usedim = (isUnstructuredFun==false); opt.usepos = (isUnstructuredFun==true); opt.hasatlas = hasatlas; opt.hasfreq = hasfreq; opt.hastime = hastime; opt.hasmsk = hasmsk; opt.hasfun = hasfun; opt.hasana = hasana; opt.qi = qi; opt.tag = 'ik'; opt.functional = functional; opt.fcolmin = fcolmin; opt.fcolmax = fcolmax; opt.opacmin = opacmin; opt.opacmax = opacmax; opt.clim = []; % contrast limits for the anatomy, see ft_volumenormalise opt.colorbar = cfg.colorbar; opt.queryrange = cfg.queryrange; opt.funcolormap = cfg.funcolormap; opt.crosshair = istrue(cfg.crosshair); %% do the actual plotting setappdata(h, 'opt', opt); cb_redraw(h); fprintf('\n'); fprintf('click left mouse button to reposition the cursor\n'); fprintf('click and hold right mouse button to update the position while moving the mouse\n'); fprintf('use the arrowkeys to navigate in the current axis\n'); case 'surface' % set the defaults for method=surface cfg.downsample = ft_getopt(cfg, 'downsample', 1); cfg.surfdownsample = ft_getopt(cfg, 'surfdownsample', 1); cfg.surffile = ft_getopt(cfg, 'surffile', 'surface_white_both.mat'); % use a triangulation that corresponds with the collin27 anatomical template in MNI coordinates cfg.surfinflated = ft_getopt(cfg, 'surfinflated', []); cfg.sphereradius = ft_getopt(cfg, 'sphereradius', []); cfg.projvec = ft_getopt(cfg, 'projvec', 1); cfg.projweight = ft_getopt(cfg, 'projweight', ones(size(cfg.projvec))); cfg.projcomb = ft_getopt(cfg, 'projcomb', 'mean'); % or max cfg.projthresh = ft_getopt(cfg, 'projthresh', []); cfg.projmethod = ft_getopt(cfg, 'projmethod', 'nearest'); cfg.distmat = ft_getopt(cfg, 'distmat', []); cfg.camlight = ft_getopt(cfg, 'camlight', 'yes'); % determine whether the source functional already contains a triangulation interpolate2surf = 0; if ~isUnstructuredFun % no triangulation present: interpolation should be performed fprintf('The source functional is defined on a 3D grid, interpolation to a surface mesh will be performed\n'); interpolate2surf = 1; elseif isUnstructuredFun && isfield(functional, 'tri') fprintf('The source functional is defined on a triangulated surface, using the surface mesh description in the functional\n'); elseif isUnstructuredFun % add a transform field to the functional fprintf('The source functional does not contain a triangulated surface, we may need to interpolate to a surface mesh\n'); functional.transform = pos2transform(functional.pos); interpolate2surf = 1; end if interpolate2surf, % deal with the interpolation % FIXME this should be dealt with by ft_sourceinterpolate % read the triangulated cortical surface from file surf = ft_read_headshape(cfg.surffile); if isfield(surf, 'transform'), % compute the surface vertices in head coordinates surf.pos = ft_warp_apply(surf.transform, surf.pos); end % downsample the cortical surface if cfg.surfdownsample > 1 if ~isempty(cfg.surfinflated) error('downsampling the surface is not possible in combination with an inflated surface'); end fprintf('downsampling surface from %d vertices\n', size(surf.pos,1)); [temp.tri, temp.pos] = reducepatch(surf.tri, surf.pos, 1/cfg.surfdownsample); % find indices of retained patch faces [dummy, idx] = ismember(temp.pos, surf.pos, 'rows'); idx(idx==0) = []; surf.tri = temp.tri; surf.pos = temp.pos; clear temp % downsample other fields if isfield(surf, 'curv'), surf.curv = surf.curv(idx); end if isfield(surf, 'sulc'), surf.sulc = surf.sulc(idx); end if isfield(surf, 'hemisphere'), surf.hemisphere = surf.hemisphere(idx); end end % these are required if ~isfield(functional, 'inside') functional.inside = true(dim); end fprintf('%d voxels in functional data\n', prod(dim)); fprintf('%d vertices in cortical surface\n', size(surf.pos,1)); tmpcfg = []; tmpcfg.parameter = {cfg.funparameter}; if ~isempty(cfg.maskparameter) tmpcfg.parameter = [tmpcfg.parameter {cfg.maskparameter}]; maskparameter = cfg.maskparameter; else tmpcfg.parameter = [tmpcfg.parameter {'mask'}]; functional.mask = msk; maskparameter = 'mask'; % temporary variable end tmpcfg.interpmethod = cfg.projmethod; tmpcfg.distmat = cfg.distmat; tmpcfg.sphereradius = cfg.sphereradius; tmpcfg.projvec = cfg.projvec; tmpcfg.projcomb = cfg.projcomb; tmpcfg.projweight = cfg.projweight; tmpcfg.projthresh = cfg.projthresh; tmpdata = ft_sourceinterpolate(tmpcfg, functional, surf); if hasfun, val = getsubfield(tmpdata, cfg.funparameter); val = val(:); end if hasmsk, maskval = getsubfield(tmpdata, maskparameter); maskval = maskval(:); end if ~isempty(cfg.projthresh), maskval(abs(val) < cfg.projthresh*max(abs(val(:)))) = 0; end else surf = []; surf.pos = functional.pos; surf.tri = functional.tri; % if hasfun, val = fun(functional.inside(:)); end % if hasmsk, maskval = msk(functional.inside(:)); end if hasfun, val = fun(:); end if hasmsk, maskval = msk(:); end end if ~isempty(cfg.surfinflated) if ~isstruct(cfg.surfinflated) % read the inflated triangulated cortical surface from file surf = ft_read_headshape(cfg.surfinflated); else surf = cfg.surfinflated; if isfield(surf, 'transform'), % compute the surface vertices in head coordinates surf.pos = ft_warp_apply(surf.transform, surf.pos); end end end %------do the plotting cortex_light = [0.781 0.762 0.664]; cortex_dark = [0.781 0.762 0.664]/2; if isfield(surf, 'curv') % the curvature determines the color of gyri and sulci color = surf.curv(:) * cortex_dark + (1-surf.curv(:)) * cortex_light; else color = repmat(cortex_light, size(surf.pos,1), 1); end h1 = patch('Vertices', surf.pos, 'Faces', surf.tri, 'FaceVertexCData', color, 'FaceColor', 'interp'); set(h1, 'EdgeColor', 'none'); axis off; axis vis3d; axis equal; if hasfun h2 = patch('Vertices', surf.pos, 'Faces', surf.tri, 'FaceVertexCData', val, 'FaceColor', 'interp'); set(h2, 'EdgeColor', 'none'); try caxis(gca,[fcolmin fcolmax]); end colormap(cfg.funcolormap); if hasmsk set(h2, 'FaceVertexAlphaData', maskval); set(h2, 'FaceAlpha', 'interp'); set(h2, 'AlphaDataMapping', 'scaled'); try alim(gca, [opacmin opacmax]); end alphamap(cfg.opacitymap); end end lighting gouraud if istrue(cfg.camlight) camlight end if istrue(cfg.colorbar) if hasfun % use a normal MATLAB colorbar hc = colorbar; set(hc, 'YLim', [fcolmin fcolmax]); else warning('no colorbar possible without functional data') end end case 'glassbrain' % This is implemented using a recursive call with an updated functional data % structure. The functional volume is replaced by a volume in which the maxima % are projected to the "edge" of the volume. tmpcfg = keepfields(cfg, {'funparameter', 'funcolorlim', 'funcolormap', 'opacitylim', 'axis', 'renderer'}); tmpcfg.method = 'ortho'; tmpcfg.location = [1 1 1]; tmpcfg.locationcoordinates = 'voxel'; tmpcfg.maskparameter = 'inside'; if hasfun, fun = getsubfield(functional, cfg.funparameter); fun = reshape(fun, dim); fun(1,:,:) = max(fun, [], 1); % get the projection along the 1st dimension fun(:,1,:) = max(fun, [], 2); % get the projection along the 2nd dimension fun(:,:,1) = max(fun, [], 3); % get the projection along the 3rd dimension functional = setsubfield(functional, cfg.funparameter, fun); end if hasana, ana = getsubfield(functional, cfg.anaparameter); % this remains as it is functional = setsubfield(functional, cfg.anaparameter, ana); end if hasmsk, msk = getsubfield(functional, 'inside'); msk = reshape(msk, dim); if hasana msk(1,:,:) = fun(1,:,:)>0 & imfill(abs(ana(1,:,:)-1))>0; msk(:,1,:) = fun(:,1,:)>0 & imfill(abs(ana(:,1,:)-1))>0; msk(:,:,1) = fun(:,:,1)>0 & imfill(abs(ana(:,:,1)-1))>0; else msk(1,:,:) = fun(1,:,:)>0; msk(:,1,:) = fun(:,1,:)>0; msk(:,:,1) = fun(:,:,1)>0; end functional = setsubfield(functional, 'inside', msk); end ft_sourceplot(tmpcfg, functional); case 'vertex' if isUnstructuredFun pos = functional.pos; else [X, Y, Z] = ndgrid(1:dim(1), 1:dim(2), 1:dim(3)); pos = ft_warp_apply(functional.transform, [X(:) Y(:) Z(:)]); end if isfield(functional, 'inside') pos = pos(functional.inside,:); if hasfun fun = fun(functional.inside); end end % scale the functional data between -30 and 30 fun = 30*fun/max(abs(fun(:))); if any(fun<=0) warning('using red for positive and blue for negative functional values') col = zeros(numel(fun), 3); % RGB col(fun>0,1) = 1; % red col(fun<0,3) = 1; % blue fun(fun==0) = eps; % these will be black ft_plot_mesh(pos, 'vertexsize', abs(fun), 'vertexcolor', col); else ft_plot_mesh(pos, 'vertexsize', fun, 'vertexcolor', 'k'); end % ensure that the axes don't change if you rotate axis vis3d otherwise error('unsupported method "%s"', cfg.method); end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous functional ft_postamble provenance % add a menu to the figure % also, delete any possibly existing previous menu, this is safe because delete([]) does nothing ftmenu = uimenu(gcf, 'Label', 'FieldTrip'); uimenu(ftmenu, 'Label', 'Show pipeline', 'Callback', {@menu_pipeline, cfg}); uimenu(ftmenu, 'Label', 'About', 'Callback', @menu_about); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_redraw(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); curr_ax = get(h, 'currentaxes'); tag = get(curr_ax, 'tag'); functional = opt.functional; h1 = opt.handlesaxes(1); h2 = opt.handlesaxes(2); h3 = opt.handlesaxes(3); xi = opt.ijk(1); yi = opt.ijk(2); zi = opt.ijk(3); qi = opt.qi; if any([xi yi zi] > functional.dim) || any([xi yi zi] <= 0) return; end opt.ijk = [xi yi zi 1]'; if opt.usedim xyz = functional.transform * opt.ijk; elseif opt.usepos ix = sub2ind(opt.dim,xi,yi,zi); xyz = functional.pos(ix,:); end opt.ijk = opt.ijk(1:3); % construct a string with user feedback str1 = sprintf('voxel %d, indices [%d %d %d]', sub2ind(functional.dim(1:3), xi, yi, zi), opt.ijk); if isfield(functional, 'coordsys') && isfield(functional, 'unit') str2 = sprintf('%s coordinates [%.1f %.1f %.1f] %s', functional.coordsys, xyz(1:3), functional.unit); elseif ~isfield(functional, 'coordsys') && isfield(functional, 'unit') str2 = sprintf('location [%.1f %.1f %.1f] %s', xyz(1:3), functional.unit); elseif isfield(functional, 'coordsys') && ~isfield(functional, 'unit') str2 = sprintf('%s coordinates [%.1f %.1f %.1f]', functional.coordsys, xyz(1:3)); elseif ~isfield(functional, 'coordsys') && ~isfield(functional, 'unit') str2 = sprintf('location [%.1f %.1f %.1f]', xyz(1:3)); else str2 = ''; end if opt.hasfreq && opt.hastime, str3 = sprintf('%.1f s, %.1f Hz', functional.time(opt.qi(2)), functional.freq(opt.qi(1))); elseif ~opt.hasfreq && opt.hastime, str3 = sprintf('%.1f s', functional.time(opt.qi(1))); elseif opt.hasfreq && ~opt.hastime, str3 = sprintf('%.1f Hz', functional.freq(opt.qi(1))); else str3 = ''; end if opt.hasfun if ~opt.hasfreq && ~opt.hastime val = opt.fun(xi, yi, zi); elseif ~opt.hasfreq && opt.hastime val = opt.fun(xi, yi, zi, opt.qi); elseif opt.hasfreq && ~opt.hastime val = opt.fun(xi, yi, zi, opt.qi); elseif opt.hasfreq && opt.hastime val = opt.fun(xi, yi, zi, opt.qi(1), opt.qi(2)); end str4 = sprintf('value %f', val); else str4 = ''; end %fprintf('%s %s %s %s\n', str1, str2, str3, str4); if opt.hasatlas %tmp = [opt.ijk(:)' 1] * opt.atlas.transform; % atlas and functional might have different transformation matrices, so xyz cannot be used here anymore % determine the anatomical label of the current position lab = atlas_lookup(opt.atlas, (xyz(1:3)), 'inputcoord', functional.coordsys, 'queryrange', opt.queryrange); if isempty(lab) lab = 'NA'; %fprintf('atlas labels: not found\n'); else tmp = sprintf('%s', strrep(lab{1}, '_', ' ')); for i=2:length(lab) tmp = [tmp sprintf(', %s', strrep(lab{i}, '_', ' '))]; end lab = tmp; end else lab = 'NA'; end if opt.hasana if opt.init tmph = [h1 h2 h3]; ft_plot_ortho(opt.ana, 'transform', eye(4), 'location', opt.ijk, 'style', 'subplot', 'parents', tmph, 'update', opt.update, 'doscale', false, 'clim', opt.clim); opt.anahandles = findobj(opt.handlesfigure, 'type', 'surface')'; for i=1:length(opt.anahandles) opt.parenttag{i} = get(get(opt.anahandles(i), 'parent'), 'tag'); end [i1,i2,i3] = intersect(opt.parenttag, {'ik' 'jk' 'ij'}); opt.anahandles = opt.anahandles(i3(i2)); % seems like swapping the order opt.anahandles = opt.anahandles(:)'; set(opt.anahandles, 'tag', 'ana'); else ft_plot_ortho(opt.ana, 'transform', eye(4), 'location', opt.ijk, 'style', 'subplot', 'surfhandle', opt.anahandles, 'update', opt.update, 'doscale', false, 'clim', opt.clim); end end if opt.hasfun if opt.init if opt.hasmsk tmpqi = [opt.qi 1]; tmph = [h1 h2 h3]; ft_plot_ortho(opt.fun(:,:,:,tmpqi(1),tmpqi(2)), 'datmask', opt.msk(:,:,:,tmpqi(1),tmpqi(2)), 'transform', eye(4), 'location', opt.ijk, ... 'style', 'subplot', 'parents', tmph, 'update', opt.update, ... 'colormap', opt.funcolormap, 'clim', [opt.fcolmin opt.fcolmax], ... 'opacitylim', [opt.opacmin opt.opacmax]); else tmpqi = [opt.qi 1]; tmph = [h1 h2 h3]; ft_plot_ortho(opt.fun(:,:,:,tmpqi(1),tmpqi(2)), 'transform', eye(4), 'location', opt.ijk, ... 'style', 'subplot', 'parents', tmph, 'update', opt.update, ... 'colormap', opt.funcolormap, 'clim', [opt.fcolmin opt.fcolmax]); end % after the first call, the handles to the functional surfaces % exist. create a variable containing this, and sort according to % the parents opt.funhandles = findobj(opt.handlesfigure, 'type', 'surface'); opt.funtag = get(opt.funhandles, 'tag'); opt.funhandles = opt.funhandles(~strcmp('ana', opt.funtag)); for i=1:length(opt.funhandles) opt.parenttag{i} = get(get(opt.funhandles(i), 'parent'), 'tag'); end [i1,i2,i3] = intersect(opt.parenttag, {'ik' 'jk' 'ij'}); opt.funhandles = opt.funhandles(i3(i2)); % seems like swapping the order opt.funhandles = opt.funhandles(:)'; set(opt.funhandles, 'tag', 'fun'); if ~opt.hasmsk && opt.hasfun && opt.hasana set(opt.funhandles(1), 'facealpha',0.5); set(opt.funhandles(2), 'facealpha',0.5); set(opt.funhandles(3), 'facealpha',0.5); end else if opt.hasmsk tmpqi = [opt.qi 1]; tmph = opt.funhandles; ft_plot_ortho(opt.fun(:,:,:,tmpqi(1),tmpqi(2)), 'datmask', opt.msk(:,:,:,tmpqi(1),tmpqi(2)), 'transform', eye(4), 'location', opt.ijk, ... 'style', 'subplot', 'surfhandle', tmph, 'update', opt.update, ... 'colormap', opt.funcolormap, 'clim', [opt.fcolmin opt.fcolmax], ... 'opacitylim', [opt.opacmin opt.opacmax]); else tmpqi = [opt.qi 1]; tmph = opt.funhandles; ft_plot_ortho(opt.fun(:,:,:,tmpqi(1),tmpqi(2)), 'transform', eye(4), 'location', opt.ijk, ... 'style', 'subplot', 'surfhandle', tmph, 'update', opt.update, ... 'colormap', opt.funcolormap, 'clim', [opt.fcolmin opt.fcolmax]); end end end set(opt.handlesaxes(1), 'Visible',opt.axis); set(opt.handlesaxes(2), 'Visible',opt.axis); set(opt.handlesaxes(3), 'Visible',opt.axis); if opt.hasfreq && opt.hastime && opt.hasfun, h4 = subplot(2,2,4); tmpdat = double(shiftdim(opt.fun(xi,yi,zi,:,:),3)); uimagesc(double(functional.time), double(functional.freq), tmpdat); axis xy; xlabel('time'); ylabel('freq'); set(h4, 'tag', 'TF1'); caxis([opt.fcolmin opt.fcolmax]); elseif opt.hasfreq && opt.hasfun, h4 = subplot(2,2,4); plot(functional.freq, shiftdim(opt.fun(xi,yi,zi,:),3)); xlabel('freq'); axis([functional.freq(1) functional.freq(end) opt.fcolmin opt.fcolmax]); set(h4, 'tag', 'TF2'); elseif opt.hastime && opt.hasfun, h4 = subplot(2,2,4); plot(functional.time, shiftdim(opt.fun(xi,yi,zi,:),3)); xlabel('time'); set(h4, 'tag', 'TF3', 'xlim',functional.time([1 end]), 'ylim',[opt.fcolmin opt.fcolmax], 'layer', 'top'); elseif strcmp(opt.colorbar, 'yes') && ~isfield(opt, 'hc'), if opt.hasfun % vectorcolorbar = linspace(fscolmin, fcolmax,length(cfg.funcolormap)); % imagesc(vectorcolorbar,1,vectorcolorbar);colormap(cfg.funcolormap); % use a normal MATLAB colorbar, attach it to the invisible 4th subplot try caxis([opt.fcolmin opt.fcolmax]); end opt.hc = colorbar; set(opt.hc, 'location', 'southoutside'); set(opt.hc, 'position',[0.06+0.06+opt.h1size(1) 0.06-0.06+opt.h3size(2) opt.h2size(1) 0.06]); try set(opt.hc, 'XLim', [opt.fcolmin opt.fcolmax]); end else ft_warning('no colorbar possible without functional data'); end end if ~((opt.hasfreq && numel(functional.freq)>1) || opt.hastime) if opt.init ht = subplot('position',[0.06+0.06+opt.h1size(1) 0.06 opt.h2size(1) opt.h3size(2)]); set(ht, 'visible', 'off'); opt.ht1=text(0,0.6,str1); opt.ht2=text(0,0.5,str2); opt.ht3=text(0,0.4,str4); opt.ht4=text(0,0.3,str3); opt.ht5=text(0,0.2,['atlas label: ' lab]); else set(opt.ht1, 'string',str1); set(opt.ht2, 'string',str2); set(opt.ht3, 'string',str4); set(opt.ht4, 'string',str3); set(opt.ht5, 'string',['atlas label: ' lab]); end end % make the last current axes current again sel = findobj('type', 'axes', 'tag',tag); if ~isempty(sel) set(opt.handlesfigure, 'currentaxes', sel(1)); end if opt.crosshair if opt.init hch1 = crosshair([xi 1 zi], 'parent', opt.handlesaxes(1)); hch3 = crosshair([xi yi opt.dim(3)], 'parent', opt.handlesaxes(3)); hch2 = crosshair([opt.dim(1) yi zi], 'parent', opt.handlesaxes(2)); opt.handlescross = [hch1(:)';hch2(:)';hch3(:)']; else crosshair([xi 1 zi], 'handle', opt.handlescross(1, :)); crosshair([opt.dim(1) yi zi], 'handle', opt.handlescross(2, :)); crosshair([xi yi opt.dim(3)], 'handle', opt.handlescross(3, :)); end end if opt.init opt.init = false; setappdata(h, 'opt', opt); end set(h, 'currentaxes', curr_ax); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_keyboard(h, eventdata) if isempty(eventdata) % determine the key that corresponds to the uicontrol element that was activated key = get(h, 'userdata'); else % determine the key that was pressed on the keyboard key = parseKeyboardEvent(eventdata); end % get focus back to figure if ~strcmp(get(h, 'type'), 'figure') set(h, 'enable', 'off'); drawnow; set(h, 'enable', 'on'); end h = getparent(h); opt = getappdata(h, 'opt'); curr_ax = get(h, 'currentaxes'); tag = get(curr_ax, 'tag'); if isempty(key) % this happens if you press the apple key key = ''; end % the following code is largely shared with FT_VOLUMEREALIGN switch key case {'' 'shift+shift' 'alt-alt' 'control+control' 'command-0'} % do nothing case '1' subplot(opt.handlesaxes(1)); case '2' subplot(opt.handlesaxes(2)); case '3' subplot(opt.handlesaxes(3)); case 'q' setappdata(h, 'opt', opt); cb_cleanup(h); case {'i' 'j' 'k' 'm' 28 29 30 31 'leftarrow' 'rightarrow' 'uparrow' 'downarrow'} % TODO FIXME use leftarrow rightarrow uparrow downarrow % update the view to a new position if strcmp(tag, 'ik') && (strcmp(key, 'i') || strcmp(key, 'uparrow') || isequal(key, 30)), opt.ijk(3) = opt.ijk(3)+1; opt.update = [0 0 1]; elseif strcmp(tag, 'ik') && (strcmp(key, 'j') || strcmp(key, 'leftarrow') || isequal(key, 28)), opt.ijk(1) = opt.ijk(1)-1; opt.update = [0 1 0]; elseif strcmp(tag, 'ik') && (strcmp(key, 'k') || strcmp(key, 'rightarrow') || isequal(key, 29)), opt.ijk(1) = opt.ijk(1)+1; opt.update = [0 1 0]; elseif strcmp(tag, 'ik') && (strcmp(key, 'm') || strcmp(key, 'downarrow') || isequal(key, 31)), opt.ijk(3) = opt.ijk(3)-1; opt.update = [0 0 1]; elseif strcmp(tag, 'ij') && (strcmp(key, 'i') || strcmp(key, 'uparrow') || isequal(key, 30)), opt.ijk(2) = opt.ijk(2)+1; opt.update = [1 0 0]; elseif strcmp(tag, 'ij') && (strcmp(key, 'j') || strcmp(key, 'leftarrow') || isequal(key, 28)), opt.ijk(1) = opt.ijk(1)-1; opt.update = [0 1 0]; elseif strcmp(tag, 'ij') && (strcmp(key, 'k') || strcmp(key, 'rightarrow') || isequal(key, 29)), opt.ijk(1) = opt.ijk(1)+1; opt.update = [0 1 0]; elseif strcmp(tag, 'ij') && (strcmp(key, 'm') || strcmp(key, 'downarrow') || isequal(key, 31)), opt.ijk(2) = opt.ijk(2)-1; opt.update = [1 0 0]; elseif strcmp(tag, 'jk') && (strcmp(key, 'i') || strcmp(key, 'uparrow') || isequal(key, 30)), opt.ijk(3) = opt.ijk(3)+1; opt.update = [0 0 1]; elseif strcmp(tag, 'jk') && (strcmp(key, 'j') || strcmp(key, 'leftarrow') || isequal(key, 28)), opt.ijk(2) = opt.ijk(2)-1; opt.update = [1 0 0]; elseif strcmp(tag, 'jk') && (strcmp(key, 'k') || strcmp(key, 'rightarrow') || isequal(key, 29)), opt.ijk(2) = opt.ijk(2)+1; opt.update = [1 0 0]; elseif strcmp(tag, 'jk') && (strcmp(key, 'm') || strcmp(key, 'downarrow') || isequal(key, 31)), opt.ijk(3) = opt.ijk(3)-1; opt.update = [0 0 1]; else % do nothing end; setappdata(h, 'opt', opt); cb_redraw(h); % contrast scaling case {43 'shift+equal'} % numpad + if isempty(opt.clim) opt.clim = [min(opt.ana(:)) max(opt.ana(:))]; end % reduce color scale range by 5% cscalefactor = (opt.clim(2)-opt.clim(1))/10; %opt.clim(1) = opt.clim(1)+cscalefactor; opt.clim(2) = opt.clim(2)-cscalefactor; setappdata(h, 'opt', opt); cb_redraw(h); case {45 'shift+hyphen'} % numpad - if isempty(opt.clim) opt.clim = [min(opt.ana(:)) max(opt.ana(:))]; end % increase color scale range by 5% cscalefactor = (opt.clim(2)-opt.clim(1))/10; %opt.clim(1) = opt.clim(1)-cscalefactor; opt.clim(2) = opt.clim(2)+cscalefactor; setappdata(h, 'opt', opt); cb_redraw(h); otherwise end % switch key %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_buttonpress(h, eventdata) h = getparent(h); cb_getposition(h); switch get(h, 'selectiontype') case 'normal' % just update to new position, nothing else to be done here cb_redraw(h); case 'alt' set(h, 'windowbuttonmotionfcn', @cb_tracemouse); cb_redraw(h); otherwise end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_buttonrelease(h, eventdata) set(h, 'windowbuttonmotionfcn', ''); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_tracemouse(h, eventdata) h = getparent(h); cb_getposition(h); cb_redraw(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_getposition(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); curr_ax = get(h, 'currentaxes'); pos = mean(get(curr_ax, 'currentpoint')); tag = get(curr_ax, 'tag'); if ~isempty(tag) && ~opt.init if strcmp(tag, 'ik') opt.ijk([1 3]) = round(pos([1 3])); opt.update = [1 1 1]; elseif strcmp(tag, 'ij') opt.ijk([1 2]) = round(pos([1 2])); opt.update = [1 1 1]; elseif strcmp(tag, 'jk') opt.ijk([2 3]) = round(pos([2 3])); opt.update = [1 1 1]; elseif strcmp(tag, 'TF1') % timefreq opt.qi(2) = nearest(opt.functional.time, pos(1)); opt.qi(1) = nearest(opt.functional.freq, pos(2)); opt.update = [1 1 1]; elseif strcmp(tag, 'TF2') % freq only opt.qi = nearest(opt.functional.freq, pos(1)); opt.update = [1 1 1]; elseif strcmp(tag, 'TF3') % time only opt.qi = nearest(opt.functional.time, pos(1)); opt.update = [1 1 1]; end end opt.ijk = min(opt.ijk(:)', opt.dim); opt.ijk = max(opt.ijk(:)', [1 1 1]); setappdata(h, 'opt', opt); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_cleanup(h, eventdata) % opt = getappdata(h, 'opt'); % opt.quit = true; % setappdata(h, 'opt', opt); % uiresume delete(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = getparent(h) p = h; while p~=0 h = p; p = get(h, 'parent'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key = parseKeyboardEvent(eventdata) key = eventdata.Key; % handle possible numpad events (different for Windows and UNIX systems) % NOTE: shift+numpad number does not work on UNIX, since the shift % modifier is always sent for numpad events if isunix() shiftInd = match_str(eventdata.Modifier, 'shift'); if ~isnan(str2double(eventdata.Character)) && ~isempty(shiftInd) % now we now it was a numpad keystroke (numeric character sent AND % shift modifier present) key = eventdata.Character; eventdata.Modifier(shiftInd) = []; % strip the shift modifier end elseif ispc() if strfind(eventdata.Key, 'numpad') key = eventdata.Character; end end if ~isempty(eventdata.Modifier) key = [eventdata.Modifier{1} '+' key]; end
github
lcnbeapp/beapp-master
ft_statistics_stats.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_statistics_stats.m
12,353
utf_8
d5721c810b45a74a5c1ef735d4711acc
function [stat, cfg] = ft_statistics_stats(cfg, dat, design) % FT_STATISTICS_STATS performs a massive univariate statistical test using the % MATLAB statistics toolbox. This function should not be called directly, % instead you should call the function that is associated with the type of data % on which you want to perform the test. % % Use as % stat = ft_timelockstatistics(cfg, data1, data2, data3, ...) % stat = ft_freqstatistics (cfg, data1, data2, data3, ...) % stat = ft_sourcestatistics (cfg, data1, data2, data3, ...) % % Where the data is obtained from FT_TIMELOCKANALYSIS, FT_FREQANALYSIS % or FT_SOURCEANALYSIS respectively, or from FT_TIMELOCKGRANDAVERAGE, % FT_FREQGRANDAVERAGE or FT_SOURCEGRANDAVERAGE respectively and with % cfg.method = 'montecarlo' % % This function uses the MATLAB statistics toolbox to perform various % statistical tests on timelock, frequency or source data. Supported % configuration options are % cfg.alpha = number, critical value for rejecting the null-hypothesis (default = 0.05) % cfg.tail = number, -1, 1 or 0 (default = 0) % cfg.feedback = string, 'gui', 'text', 'textbar' or 'no' (default = 'textbar') % cfg.method = 'stats' % cfg.statistic = 'ttest' test against a mean of zero % 'ttest2' compare the mean in two conditions % 'paired-ttest' % 'anova1' % 'kruskalwallis' % 'signtest' % 'signrank' % % See also TTEST, TTEST2, KRUSKALWALLIS, SIGNTEST, SIGNRANK % Undocumented local options: % cfg.avgovertime % cfg.constantvalue % Copyright (C) 2005, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % test for the presence of the statistics toolbox ft_hastoolbox('stats', 1); % set the defaults that are common to all methods if ~isfield(cfg, 'feedback'), cfg.feedback = 'textbar'; end switch cfg.statistic %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case {'ttest', 'ttest_samples_vs_const'} % set the defaults if ~isfield(cfg, 'alpha'), cfg.alpha = 0.05; end if ~isfield(cfg, 'constantvalue'), cfg.constantvalue = 0; end if ~isfield(cfg, 'tail'), cfg.tail = 0; end if ~any(size(design)==1) error('design matrix should only contain one factor (i.e. one row)'); end Ncond = length(unique(design)); if Ncond>1 error(sprintf('%s method is only supported for one condition at a time', cfg.statistic)); end Nobs = size(dat, 1); Nrepl = size(dat, 2); % over all conditions h = zeros(Nobs, 1); p = zeros(Nobs, 1); s = zeros(Nobs, 1); ci = zeros(Nobs, 2); fprintf('number of observations %d\n', Nobs); fprintf('number of replications %d\n', Nrepl); ft_progress('init', cfg.feedback); for chan = 1:Nobs ft_progress(chan/Nobs, 'Processing observation %d/%d\n', chan, Nobs); [h(chan), p(chan), ci(chan, :), stats] = ttest_wrapper(dat(chan, :), cfg.constantvalue, cfg.alpha, cfg.tail); s(chan) = stats.tstat; end ft_progress('close'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case {'ttest2', 'ttest_2samples_by_timepoint'} % set the defaults if ~isfield(cfg, 'alpha'), cfg.alpha = 0.05; end if ~isfield(cfg, 'tail'), cfg.tail = 0; end if size(design,1)~=1 error('design matrix should only contain one factor (i.e. one row)'); end Ncond = length(unique(design)); if Ncond~=2 error(sprintf('%s method is only supported for two condition', cfg.statistic)); end Nobs = size(dat, 1); selA = find(design==design(1)); selB = find(design~=design(1)); Nrepl = [length(selA), length(selB)]; h = zeros(Nobs, 1); p = zeros(Nobs, 1); s = zeros(Nobs, 1); ci = zeros(Nobs, 2); fprintf('number of observations %d\n', Nobs); fprintf('number of replications %d and %d\n', Nrepl(1), Nrepl(2)); ft_progress('init', cfg.feedback); for chan = 1:Nobs ft_progress(chan/Nobs, 'Processing observation %d/%d\n', chan, Nobs); [h(chan), p(chan), ci(chan, :), stats] = ttest2_wrapper(dat(chan, selA), dat(chan, selB), cfg.alpha, cfg.tail); s(chan) = stats.tstat; end ft_progress('close'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case {'paired-ttest'} % set the defaults if ~isfield(cfg, 'alpha'), cfg.alpha = 0.05; end if ~isfield(cfg, 'tail'), cfg.tail = 0; end if ~any(size(design)==1) error('design matrix should only contain one factor (i.e. one row)'); end Ncond = length(unique(design)); if Ncond~=2 error(sprintf('%s method is only supported for two condition', cfg.statistic)); end Nobs = size(dat, 1); selA = find(design==design(1)); selB = find(design~=design(1)); Nrepl = [length(selA), length(selB)]; if Nrepl(1)~=Nrepl(2) error('number of replications per condition should be the same'); end h = zeros(Nobs, 1); p = zeros(Nobs, 1); s = zeros(Nobs, 1); ci = zeros(Nobs, 2); fprintf('number of observations %d\n', Nobs); fprintf('number of replications %d and %d\n', Nrepl(1), Nrepl(2)); ft_progress('init', cfg.feedback); for chan = 1:Nobs ft_progress(chan/Nobs, 'Processing observation %d/%d\n', chan, Nobs); [h(chan), p(chan), ci(chan, :), stats] = ttest_wrapper(dat(chan, selA)-dat(chan, selB), 0, cfg.alpha, cfg.tail); s(chan) = stats.tstat; end ft_progress('close'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case {'anova1'} if ~any(size(design)==1) error('design matrix should only contain one factor (i.e. one row)'); end Ncond = length(unique(design)); Nobs = size(dat, 1); Nrepl = size(dat, 2); % over all conditions h = zeros(Nobs, 1); p = zeros(Nobs, 1); fprintf('number of observations %d\n', Nobs); fprintf('number of replications %d\n', Nrepl); fprintf('number of levels %d\n', Ncond); ft_progress('init', cfg.feedback); for chan = 1:Nobs ft_progress(chan/Nobs, 'Processing observation %d/%d\n', chan, Nobs); p(chan) = anova1(dat(chan, :), design(:), 'off'); end ft_progress('close'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case {'kruskalwallis'} if ~any(size(design)==1) error('design matrix should only contain one factor (i.e. one row)'); end Ncond = length(unique(design)); Nobs = size(dat, 1); Nrepl = size(dat, 2); % over all conditions h = zeros(Nobs, 1); p = zeros(Nobs, 1); fprintf('number of observations %d\n', Nobs); fprintf('number of replications %d\n', Nrepl); fprintf('number of levels %d\n', Ncond); ft_progress('init', cfg.feedback); for chan = 1:Nobs ft_progress(chan/Nobs, 'Processing observation %d/%d\n', chan, Nobs); p(chan) = kruskalwallis(dat(chan, :), design(:), 'off'); end ft_progress('close'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % case {'anovan'} % % Nfact = size(design,1); % Nobs = size(dat, 1); % Nrepl = size(dat, 2); % over all conditions % % h = zeros(Nobs, 1); % p = zeros(Nobs, 1); % ci = zeros(Nobs, 2); % fprintf('number of observations %d\n', Nobs); % fprintf('number of replications %d\n', Nrepl); % fprintf('number of factors %d\n', Nfact); % % % reformat the design matrix into the grouping variable cell-array % for i=1:Nfact % group{i} = design(i,:); % end % % ft_progress('init', cfg.feedback); % for chan = 1:Nobs % ft_progress(chan/Nobs, 'Processing observation %d/%d\n', chan, Nobs); % % FIXME, the probability is returned for each factor separately % p = anovan(dat(chan, :), group, 'display', 'off'); % end % ft_progress('close'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'ttest_window_avg_vs_const' % this used to be a feature of the timelockanalysis as it was % originally implemented by Jens Schwartzbach, but it has been % superseded by the use of ft_selectdata for data selection error(sprintf('%s is not supported any more, use cfg.avgovertime=''yes'' instead', cfg.statistic)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case {'signtest'} % set the defaults if ~isfield(cfg, 'alpha'), cfg.alpha = 0.05; end if ~isfield(cfg, 'tail'), cfg.tail = 0; end switch cfg.tail case 0 cfg.tail = 'both'; case -1 cfg.tail = 'left'; case 1 cfg.tail = 'right'; end; if size(design,1)~=1 error('design matrix should only contain one factor (i.e. one row)'); end Ncond = length(unique(design)); if Ncond~=2 error(sprintf('%s method is only supported for two condition', cfg.statistic)); end Nobs = size(dat, 1); selA = find(design==design(1)); selB = find(design~=design(1)); Nrepl = [length(selA), length(selB)]; h = zeros(Nobs, 1); p = zeros(Nobs, 1); s = zeros(Nobs, 1); fprintf('number of observations %d\n', Nobs); fprintf('number of replications %d and %d\n', Nrepl(1), Nrepl(2)); ft_progress('init', cfg.feedback); for chan = 1:Nobs ft_progress(chan/Nobs, 'Processing observation %d/%d\n', chan, Nobs); [p(chan), h(chan), stats] = signtest(dat(chan, selA), dat(chan, selB),'alpha', cfg.alpha,'tail', cfg.tail); s(chan) = stats.sign; end ft_progress('close'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case {'signrank'} % set the defaults if ~isfield(cfg, 'alpha'), cfg.alpha = 0.05; end if ~isfield(cfg, 'tail'), cfg.tail = 0; end switch cfg.tail case 0 cfg.tail = 'both'; case -1 cfg.tail = 'left'; case 1 cfg.tail = 'right'; end; if size(design,1)~=1 error('design matrix should only contain one factor (i.e. one row)'); end Ncond = length(unique(design)); if Ncond~=2 error(sprintf('%s method is only supported for two condition', cfg.statistic)); end Nobs = size(dat, 1); selA = find(design==design(1)); selB = find(design~=design(1)); Nrepl = [length(selA), length(selB)]; h = zeros(Nobs, 1); p = zeros(Nobs, 1); s = zeros(Nobs, 1); fprintf('number of observations %d\n', Nobs); fprintf('number of replications %d and %d\n', Nrepl(1), Nrepl(2)); ft_progress('init', cfg.feedback); for chan = 1:Nobs ft_progress(chan/Nobs, 'Processing observation %d/%d\n', chan, Nobs); [p(chan), h(chan), stats] = signrank(dat(chan, selA), dat(chan, selB),'alpha', cfg.alpha,'tail', cfg.tail); s(chan) = stats.signedrank; end ft_progress('close'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% otherwise error(sprintf('Statistical method ''%s'' is not implemented', cfg.statistic)); end % assign the output variable stat = []; try, stat.mask = h; end try, stat.prob = p; end try, stat.stat = s; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions for ttest and ttest2 % - old Matlab, with syntax: ttest(x,y,alpha,tail,dim) % - new Matlab and GNU Octave, with syntax: ttest(x,y,'alpha',alpha,...) function [h,p,ci,stats]=ttest_wrapper(x,y,alpha,tail) [h,p,ci,stats]=general_ttestX_wrapper(@ttest,x,y,alpha,tail); function [h,p,ci,stats]=ttest2_wrapper(x,y,alpha,tail) [h,p,ci,stats]=general_ttestX_wrapper(@ttest2,x,y,alpha,tail); function [h,p,ci,stats]=general_ttestX_wrapper(ttest_func,x,y,alpha,tail) if nargin(ttest_func)>0 % old Matlab [h,p,ci,stats]=ttest_func(x,y,alpha,tail); else % GNU Octave and new Matlab [h,p,ci,stats]=ttest_func(x,y,'alpha',alpha,'tail',tail); end
github
lcnbeapp/beapp-master
ft_megrealign.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_megrealign.m
18,741
utf_8
70c06177fc1b0bc68db90decccf0589b
function [data] = ft_megrealign(cfg, data) % FT_MEGREALIGN interpolates MEG data towards standard gradiometer locations by % projecting the individual timelocked data towards a coarse source reconstructed % representation and computing the magnetic field on the standard gradiometer % locations. % % Use as % [interp] = ft_megrealign(cfg, data) % % Required configuration options: % cfg.template % cfg.inwardshift % % The new gradiometer definition is obtained from a template dataset, % or can be constructed by averaging the gradiometer positions over % multiple datasets. % cfg.template = single dataset that serves as template % cfg.template(1..N) = datasets that are averaged into the standard % % The realignment is done by computing a minumum norm estimate using a % large number of dipoles that are placed in the upper layer of the brain % surface, followed by a forward computation towards the template % gradiometer array. This requires the specification of a volume conduction % model of the head and of a source model. % % A volume conduction model of the head should be specified with % cfg.headmodel = structure, see FT_PREPARE_HEADMODEL % % A source model (i.e. a superficial layer with distributed sources) can be % constructed from a headshape file, or from the volume conduction model % cfg.spheremesh = number of dipoles in the source layer (default = 642) % cfg.inwardshift = depth of the source layer relative to the headshape % surface or volume conduction model (no default % supplied, see below) % cfg.headshape = a filename containing headshape, a structure containing a % single triangulated boundary, or a Nx3 matrix with surface % points % % If you specify a headshape and it describes the skin surface, you should specify an % inward shift of 2.5 cm. % % For a single-sphere or a local-spheres volume conduction model based on the skin % surface, an inward shift of 2.5 cm is reasonable. % % For a single-sphere or a local-spheres volume conduction model based on the brain % surface, you should probably use an inward shift of about 1 cm. % % For a realistic single-shell volume conduction model based on the brain surface, you % should probably use an inward shift of about 1 cm. % % Other options are % cfg.pruneratio = for singular values, default is 1e-3 % cfg.verify = 'yes' or 'no', show the percentage difference (default = 'yes') % cfg.feedback = 'yes' or 'no' (default = 'no') % cfg.channel = Nx1 cell-array with selection of channels (default = 'MEG'), % see FT_CHANNELSELECTION for details % cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') % % This implements the method described by T.R. Knosche, Transformation % of whole-head MEG recordings between different sensor positions. % Biomed Tech (Berl). 2002 Mar;47(3):59-62. For more information and % related methods, see Stolk et al., Online and offline tools for head % movement compensation in MEG. NeuroImage, 2012. % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % cfg.outputfile = ... % If you specify one of these (or both) the input data will be read from a *.mat % file on disk and/or the output data will be written to a *.mat file. These mat % files should contain only a single variable, corresponding with the % input/output structure. % % See also FT_PREPARE_LOCALSPHERES, FT_PREPARE_SINGLESHELL % Copyright (C) 2004-2014, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar data ft_preamble provenance data ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'renamed', {'plot3d', 'feedback'}); cfg = ft_checkconfig(cfg, 'renamedval', {'headshape', 'headmodel', []}); cfg = ft_checkconfig(cfg, 'required', {'inwardshift', 'template'}); cfg = ft_checkconfig(cfg, 'renamed', {'hdmfile', 'headmodel'}); cfg = ft_checkconfig(cfg, 'renamed', {'vol', 'headmodel'}); % set the default configuration cfg.headshape = ft_getopt(cfg, 'headshape', []); cfg.pruneratio = ft_getopt(cfg, 'pruneratio', 1e-3); cfg.spheremesh = ft_getopt(cfg, 'spheremesh', 642); cfg.verify = ft_getopt(cfg, 'verify', 'yes'); cfg.feedback = ft_getopt(cfg, 'feedback', 'yes'); cfg.trials = ft_getopt(cfg, 'trials', 'all', 1); cfg.channel = ft_getopt(cfg, 'channel', 'MEG'); cfg.topoparam = ft_getopt(cfg, 'topoparam', 'rms'); % store original datatype dtype = ft_datatype(data); % check if the input data is valid for this function data = ft_checkdata(data, 'datatype', 'raw', 'feedback', 'yes', 'hassampleinfo', 'yes', 'ismeg', 'yes'); % do realignment per trial pertrial = all(ismember({'nasX';'nasY';'nasZ';'lpaX';'lpaY';'lpaZ';'rpaX';'rpaY';'rpaZ'}, data.label)); % put the low-level options pertaining to the dipole grid in their own field cfg = ft_checkconfig(cfg, 'renamed', {'tightgrid', 'tight'}); % this is moved to cfg.grid.tight by the subsequent createsubcfg cfg = ft_checkconfig(cfg, 'renamed', {'sourceunits', 'unit'}); % this is moved to cfg.grid.unit by the subsequent createsubcfg cfg = ft_checkconfig(cfg, 'createsubcfg', {'grid'}); if isstruct(cfg.template) % this should be a cell-array cfg.template = {cfg.template}; end % retain only the MEG channels in the data and temporarily store % the rest, these will be added back to the transformed data later. % select trials and channels of interest tmpcfg = []; tmpcfg.trials = cfg.trials; tmpcfg.channel = setdiff(data.label, ft_channelselection(cfg.channel, data.label)); rest = ft_selectdata(tmpcfg, data); tmpcfg.channel = ft_channelselection(cfg.channel, data.label); data = ft_selectdata(tmpcfg, data); % restore the provenance information [cfg, data] = rollback_provenance(cfg, data); Ntrials = length(data.trial); % cfg.channel = ft_channelselection(cfg.channel, data.label); % dataindx = match_str(data.label, cfg.channel); % restindx = setdiff(1:length(data.label),dataindx); % if ~isempty(restindx) % fprintf('removing %d non-MEG channels from the data\n', length(restindx)); % rest.label = data.label(restindx); % first remember the rest % data.label = data.label(dataindx); % then reduce the data % for i=1:Ntrials % rest.trial{i} = data.trial{i}(restindx,:); % first remember the rest % data.trial{i} = data.trial{i}(dataindx,:); % then reduce the data % end % else % rest.label = {}; % rest.trial = {}; % end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % construct the average template gradiometer array %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% template = struct([]); % initialize as empty structure for i=1:length(cfg.template) if ischar(cfg.template{i}), fprintf('reading template sensor position from %s\n', cfg.template{i}); tmp = ft_read_sens(cfg.template{i}); elseif isstruct(cfg.template{i}) && isfield(cfg.template{i}, 'coilpos') && isfield(cfg.template{i}, 'coilori') && isfield(cfg.template{i}, 'tra'), tmp = cfg.template{i}; elseif isstruct(cfg.template{i}) && isfield(cfg.template{i}, 'pnt') && isfield(cfg.template{i}, 'ori') && isfield(cfg.template{i}, 'tra'), % it seems to be a pre-2011v1 type gradiometer structure, update it tmp = ft_datatype_sens(cfg.template{i}); else error('unrecognized template input'); end % prevent "Subscripted assignment between dissimilar structures" error template = appendstruct(template, tmp); clear tmp end grad = ft_average_sens(template); % construct the final template gradiometer definition template = []; template.grad = grad; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % FT_PREPARE_VOL_SENS will match the data labels, the gradiometer labels and the % volume model labels (in case of a localspheres model) and result in a gradiometer % definition that only contains the gradiometers that are present in the data. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% volcfg = []; volcfg.headmodel = cfg.headmodel; volcfg.grad = data.grad; volcfg.channel = data.label; % this might be a subset of the MEG channels gradorig = data.grad; % this is needed later on for plotting. As of % yet the next step is not entirely correct, because it does not keep track % of the balancing of the gradiometer array. FIXME this may require some % thought because the leadfields are computed with low level functions and % do not easily accommodate for matching the correct channels with each % other (in order to compute the projection matrix). [volold, data.grad] = prepare_headmodel(volcfg); % note that it is neccessary to keep the two volume conduction models % seperate, since the single-shell Nolte model contains gradiometer specific % precomputed parameters. Note that this is not guaranteed to result in a % good projection for local sphere models. volcfg.grad = template.grad; volcfg.channel = 'MEG'; % include all MEG channels [volnew, template.grad] = prepare_headmodel(volcfg); if strcmp(ft_senstype(data.grad), ft_senstype(template.grad)) [id, it] = match_str(data.grad.label, template.grad.label); fprintf('mean distance towards template gradiometers is %.2f %s\n', mean(sum((data.grad.chanpos(id,:)-template.grad.chanpos(it,:)).^2, 2).^0.5), template.grad.unit); else % the projection is from one MEG system to another MEG system, which makes a comparison of the data difficult cfg.feedback = 'no'; cfg.verify = 'no'; end % copy all options that are potentially used in ft_prepare_sourcemodel tmpcfg = keepfields(cfg, {'grid' 'mri' 'headshape' 'symmetry' 'smooth' 'threshold' 'spheremesh' 'inwardshift'}); tmpcfg.headmodel = volold; tmpcfg.grad = data.grad; % create the dipole grid on which the data will be projected grid = ft_prepare_sourcemodel(tmpcfg); pos = grid.pos; % sometimes some of the dipole positions are nan, due to problems with the headsurface triangulation % remove them to prevent problems with the forward computation sel = find(any(isnan(pos(:,1)),2)); pos(sel,:) = []; % compute the forward model for the new gradiometer positions fprintf('computing forward model for %d dipoles\n', size(pos,1)); lfnew = ft_compute_leadfield(pos, template.grad, volnew); if ~pertrial, %this needs to be done only once lfold = ft_compute_leadfield(pos, data.grad, volold); [realign, noalign, bkalign] = computeprojection(lfold, lfnew, cfg.pruneratio, cfg.verify); else %the forward model and realignment matrices have to be computed for each trial %this also goes for the singleshell volume conductor model %x = which('rigidbodyJM'); %this function is needed %if isempty(x), % error('you are trying out experimental code for which you need some extra functionality which is currently not in the release version of fieldtrip. if you are interested in trying it out, contact jan-mathijs'); %end end % interpolate the data towards the template gradiometers for i=1:Ntrials fprintf('realigning trial %d\n', i); if pertrial, %warp the gradiometer array according to the motiontracking data sel = match_str(rest.label, {'nasX';'nasY';'nasZ';'lpaX';'lpaY';'lpaZ';'rpaX';'rpaY';'rpaZ'}); hmdat = rest.trial{i}(sel,:); if ~all(hmdat==repmat(hmdat(:,1),[1 size(hmdat,2)])) error('only one position per trial is at present allowed'); else %M = rigidbodyJM(hmdat(:,1)) M = ft_headcoordinates(hmdat(1:3,1),hmdat(4:6,1),hmdat(7:9,1)); grad = ft_transform_sens(M, data.grad); end volcfg.grad = grad; %compute volume conductor [volold, grad] = prepare_headmodel(volcfg); %compute forward model lfold = ft_compute_leadfield(pos, grad, volold); %compute projection matrix [realign, noalign, bkalign] = computeprojection(lfold, lfnew, cfg.pruneratio, cfg.verify); end data.realign{i} = realign * data.trial{i}; if strcmp(cfg.verify, 'yes') % also compute the residual variance when interpolating [id,it] = match_str(data.grad.label, template.grad.label); rvrealign = rv(data.trial{i}(id,:), data.realign{i}(it,:)); fprintf('original -> template RV %.2f %%\n', 100 * mean(rvrealign)); datnoalign = noalign * data.trial{i}; datbkalign = bkalign * data.trial{i}; rvnoalign = rv(data.trial{i}, datnoalign); rvbkalign = rv(data.trial{i}, datbkalign); fprintf('original -> original RV %.2f %%\n', 100 * mean(rvnoalign)); fprintf('original -> template -> original RV %.2f %%\n', 100 * mean(rvbkalign)); end end % plot the topography before and after the realignment if strcmp(cfg.feedback, 'yes') warning('showing MEG topography (RMS value over time) in the first trial only'); Nchan = length(data.grad.label); [id,it] = match_str(data.grad.label, template.grad.label); pos1 = data.grad.chanpos(id,:); pos2 = template.grad.chanpos(it,:); prj1 = elproj(pos1); tri1 = delaunay(prj1(:,1), prj1(:,2)); prj2 = elproj(pos2); tri2 = delaunay(prj2(:,1), prj2(:,2)); switch cfg.topoparam case 'rms' p1 = sqrt(mean(data.trial{1}(id,:).^2, 2)); p2 = sqrt(mean(data.realign{1}(it,:).^2, 2)); case 'svd' [u, s, v] = svd(data.trial{1}(id,:)); p1 = u(:,1); [u, s, v] = svd(data.realign{1}(it,:)); p2 = u(:,1); otherwise error('unsupported cfg.topoparam'); end X = [pos1(:,1) pos2(:,1)]'; Y = [pos1(:,2) pos2(:,2)]'; Z = [pos1(:,3) pos2(:,3)]'; % show figure with old an new helmets, volume model and dipole grid figure hold on ft_plot_vol(volold); plot3(grid.pos(:,1),grid.pos(:,2),grid.pos(:,3),'b.'); plot3(pos1(:,1), pos1(:,2), pos1(:,3), 'r.') % original positions plot3(pos2(:,1), pos2(:,2), pos2(:,3), 'g.') % template positions line(X,Y,Z, 'color', 'black'); view(-90, 90); % show figure with data on old helmet location figure hold on plot3(pos1(:,1), pos1(:,2), pos1(:,3), 'r.') % original positions plot3(pos2(:,1), pos2(:,2), pos2(:,3), 'g.') % template positions line(X,Y,Z, 'color', 'black'); axis equal; axis vis3d bnd1 = []; bnd1.pos = pos1; bnd1.tri = tri1; ft_plot_mesh(bnd1,'vertexcolor',p1,'edgecolor','none') title('RMS, before realignment') view(-90, 90) % show figure with data on new helmet location figure hold on plot3(pos1(:,1), pos1(:,2), pos1(:,3), 'r.') % original positions plot3(pos2(:,1), pos2(:,2), pos2(:,3), 'g.') % template positions line(X,Y,Z, 'color', 'black'); axis equal; axis vis3d bnd2 = []; bnd2.pos = pos2; bnd2.tri = tri2; ft_plot_mesh(bnd2,'vertexcolor',p2,'edgecolor','none') title('RMS, after realignment') view(-90, 90) end % store the realigned data in a new structure interp.label = template.grad.label; interp.grad = template.grad; % replace with the template gradiometer array interp.trial = data.realign; % remember the processed data interp.fsample = data.fsample; interp.time = data.time; % add the rest channels back to the data, these were not interpolated if ~isempty(rest.label) fprintf('adding %d non-MEG channels back to the data (', length(rest.label)); fprintf('%s, ', rest.label{1:end-1}); fprintf('%s)\n', rest.label{end}); for trial=1:length(rest.trial) interp.trial{trial} = [interp.trial{trial}; rest.trial{trial}]; end interp.label = [interp.label; rest.label]; end % copy the trial specific information into the output if isfield(data, 'trialinfo') interp.trialinfo = data.trialinfo; end % copy the sampleinfo field as well if isfield(data, 'sampleinfo') interp.sampleinfo = data.sampleinfo; end % convert back to input type if necessary switch dtype case 'timelock' interp = ft_checkdata(interp, 'datatype', 'timelock'); otherwise % keep the output as it is end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous data % rename the output variable to accomodate the savevar postamble data = interp; ft_postamble provenance data ft_postamble history data ft_postamble savevar data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % subfunction that computes the projection matrix(ces) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [realign, noalign, bkalign] = computeprojection(lfold, lfnew, pruneratio, verify) % compute this inverse only once, although it is used twice tmp = prunedinv(lfold, pruneratio); % compute the three interpolation matrices fprintf('computing interpolation matrix #1\n'); realign = lfnew * tmp; if strcmp(verify, 'yes') fprintf('computing interpolation matrix #2\n'); noalign = lfold * tmp; fprintf('computing interpolation matrix #3\n'); bkalign = lfold * prunedinv(lfnew, pruneratio) * realign; else noalign = []; bkalign = []; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % subfunction that computes the inverse using a pruned SVD %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [lfi] = prunedinv(lf, r) [u, s, v] = svd(lf); if r<1, % treat r as a ratio p = find(s<(s(1,1)*r) & s~=0); else % treat r as the number of spatial components to keep diagels = 1:(min(size(s))+1):(min(size(s)).^2); p = diagels((r+1):end); end fprintf('pruning %d from %d, i.e. removing the %d smallest spatial components\n', length(p), min(size(s)), length(p)); s(p) = 0; s(find(s~=0)) = 1./s(find(s~=0)); lfi = v * s' * u';
github
lcnbeapp/beapp-master
ft_volumelookup.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_volumelookup.m
14,555
utf_8
85db9e3295336353532219bebdf32b95
function [output] = ft_volumelookup(cfg, volume) % FT_VOLUMELOOKUP can be used in to combine an anatomical or functional % atlas with source reconstruction. You can use it for forward and reverse % lookup. % % Given the anatomical or functional label, it looks up the locations and % creates a mask (as a binary volume) based on the label, or creates a % sphere or box around a point of interest. In this case the function is to % be used as: % mask = ft_volumelookup(cfg, volume) % % Given a binary volume that indicates a region of interest, it looks up % the corresponding anatomical or functional labels from a given atlas. In % this case the function is to be used as follows: % labels = ft_volumelookup(cfg, volume) % % In both cases the input volume can be: % mri is the output of FT_READ_MRI % source is the output of FT_SOURCEANALYSIS % stat is the output of FT_SOURCESTATISTICS % % The configuration options for a mask according to an atlas: % cfg.inputcoord = 'mni' or 'tal', coordinate system of the mri/source/stat % cfg.atlas = string, filename of atlas to use, either the AFNI % brik file that is available from http://afni.nimh.nih.gov/afni/doc/misc/ttatlas_tlrc, % or the WFU atlasses available from http://fmri.wfubmc.edu. see FT_READ_ATLAS % cfg.roi = string or cell of strings, region(s) of interest from anatomical atlas % % The configuration options for a spherical/box mask around a point of interest: % cfg.roi = Nx3 vector, coordinates of the points of interest % cfg.sphere = radius of each sphere in cm/mm dep on unit of input % cfg.box = Nx3 vector, size of each box in cm/mm dep on unit of input % cfg.round2nearestvoxel = 'yes' or 'no' (default = 'no'), voxel closest to point of interest is calculated % and box/sphere is centered around coordinates of that voxel % % The configuration options for labels from a mask: % cfg.inputcoord = 'mni' or 'tal', coordinate system of the mri/source/stat % cfg.atlas = string, filename of atlas to use, either the AFNI % brik file that is available from http://afni.nimh.nih.gov/afni/doc/misc/afni_ttatlas/, % or the WFU atlasses available from http://fmri.wfubmc.edu. see FT_READ_ATLAS % cfg.maskparameter = string, field in volume to be lookedup, data in field should be logical % cfg.maxqueryrange = number, should be 1, 3, 5 (default = 1) % % The label output has a field "names", a field "count" and a field "usedqueryrange" % To get a list of areas of the given mask you can do for instance: % [tmp ind] = sort(labels.count,1,'descend'); % sel = find(tmp); % for j = 1:length(sel) % found_areas{j,1} = [num2str(labels.count(ind(j))) ': ' labels.name{ind(j)}]; % end % in found_areas you can then see how many times which labels are found % NB in the AFNI brick one location can have 2 labels! % % Dependent on the input coordinates and the coordinates of the atlas, the % input MRI is transformed betweem MNI and Talairach-Tournoux coordinates % See http://www.mrc-cbu.cam.ac.uk/Imaging/Common/mnispace.shtml for more details. % % See also FT_READ_ATLAS, FT_SOURCEPLOT % Copyright (C) 2008-2013, Robert Oostenveld, Ingrid Nieuwenhuis % Copyright (C) 2013, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar volume ft_preamble provenance volume ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % the handling of the default cfg options is done further down % the checking of the input data is done further down cfg.maxqueryrange = ft_getopt(cfg,'maxqueryrange', 1); roi2mask = 0; mask2label = 0; if isfield(cfg, 'roi'); roi2mask = 1; elseif isfield(cfg, 'maskparameter') mask2label = 1; else error('either specify cfg.roi, or cfg.maskparameter') end if roi2mask % only for volume data volume = ft_checkdata(volume, 'datatype', 'volume'); cfg.round2nearestvoxel = ft_getopt(cfg, 'round2nearestvoxel', 'no'); isatlas = iscell(cfg.roi) || ischar(cfg.roi); ispoi = isnumeric(cfg.roi); if isatlas+ispoi ~= 1 error('do not understand cfg.roi') end if isatlas ft_checkconfig(cfg, 'forbidden', {'sphere' 'box'}, ... 'required', {'atlas' 'inputcoord'}); elseif ispoi ft_checkconfig(cfg, 'forbidden', {'atlas' 'inputcoord'}); if isempty(ft_getopt(cfg, 'sphere')) && isempty(ft_getopt(cfg, 'box')) % either needs to be there error('either specify cfg.sphere or cfg.box') end end elseif mask2label % convert to source representation (easier to work with) volume = ft_checkdata(volume, 'datatype', 'source'); ft_checkconfig(cfg, 'required', {'atlas' 'inputcoord'}); if isempty(intersect(cfg.maxqueryrange, [1 3 5])) error('incorrect query range, should be one of [1 3 5]'); end end if roi2mask % determine location of each anatomical voxel in its own voxel coordinates dim = volume.dim; i = 1:dim(1); j = 1:dim(2); k = 1:dim(3); [I, J, K] = ndgrid(i, j, k); ijk = [I(:) J(:) K(:) ones(prod(dim),1)]'; % determine location of each anatomical voxel in head coordinates xyz = volume.transform * ijk; % note that this is 4xN if isatlas if ischar(cfg.atlas), % assume it to represent a filename atlas = ft_read_atlas(cfg.atlas); else % assume cfg.atlas to be a struct, but it may have been converted % into a config object atlas = struct(cfg.atlas); end % determine which field(s) to use to look up the labels, % and whether these are boolean or indexed fn = fieldnames(atlas); isboolean = false(numel(fn),1); isindexed = false(numel(fn),1); for i=1:length(fn) if islogical(atlas.(fn{i})) && isequal(size(atlas.(fn{i})), atlas.dim) isboolean(i) = true; elseif isnumeric(atlas.(fn{i})) && isequal(size(atlas.(fn{i})), atlas.dim) isindexed(i) = true; end end if any(isindexed) % let the indexed prevail fn = fn(isindexed); isindexed = 1; elseif any(isboolean) % use the boolean fn = fn(isboolean); isindexed = 0; end if ischar(cfg.roi) cfg.roi = {cfg.roi}; end if isindexed, sel = zeros(0,2); for m = 1:length(fn) for i = 1:length(cfg.roi) tmp = find(strcmp(cfg.roi{i}, atlas.([fn{m},'label']))); sel = [sel; tmp m*ones(numel(tmp),1)]; end end fprintf('found %d matching anatomical labels\n', size(sel,1)); % this is to accommodate for multiple parcellations: % the brick refers to the parcellationname % the value refers to the value within the given parcellation brick = sel(:,2); value = sel(:,1); % convert between MNI head coordinates and TAL head coordinates % coordinates should be expressed compatible with the atlas if strcmp(cfg.inputcoord, 'mni') && strcmp(atlas.coordsys, 'tal') xyz(1:3,:) = mni2tal(xyz(1:3,:)); elseif strcmp(cfg.inputcoord, 'mni') && strcmp(atlas.coordsys, 'mni') % nothing to do elseif strcmp(cfg.inputcoord, 'tal') && strcmp(atlas.coordsys, 'tal') % nothing to do elseif strcmp(cfg.inputcoord, 'tal') && strcmp(atlas.coordsys, 'mni') xyz(1:3,:) = tal2mni(xyz(1:3,:)); elseif ~strcmp(cfg.inputcoord, atlas.coordsys) error('there is a mismatch between the coordinate system in the atlas and the coordinate system in the data, which cannot be resolved'); end % determine location of each anatomical voxel in atlas voxel coordinates ijk = atlas.transform \ xyz; ijk = round(ijk(1:3,:))'; inside_vol = ijk(:,1)>=1 & ijk(:,1)<=atlas.dim(1) & ... ijk(:,2)>=1 & ijk(:,2)<=atlas.dim(2) & ... ijk(:,3)>=1 & ijk(:,3)<=atlas.dim(3); inside_vol = find(inside_vol); % convert the selection inside the atlas volume into linear indices ind = sub2ind(atlas.dim, ijk(inside_vol,1), ijk(inside_vol,2), ijk(inside_vol,3)); brick_val = cell(1,numel(brick)); % search the bricks for the value of each voxel for i=1:numel(brick_val) brick_val{i} = zeros(prod(dim),1); brick_val{i}(inside_vol) = atlas.(fn{brick(i)})(ind); end mask = zeros(prod(dim),1); for i=1:numel(brick_val) %fprintf('constructing mask for %s\n', atlas.descr.name{sel(i)}); mask = mask | (brick_val{i}==value(i)); end else error('support for atlases that have a probabilistic segmentationstyle is not supported yet'); % NOTE: this may be very straightforward indeed: the mask is just the % logical or of the specified rois. end elseif ispoi if istrue(cfg.round2nearestvoxel) for i=1:size(cfg.roi,1) cfg.roi(i,:) = poi2voi(cfg.roi(i,:), xyz); end end % sphere(s) if isfield(cfg, 'sphere') mask = zeros(1,prod(dim)); for i=1:size(cfg.roi,1) dist = sqrt( (xyz(1,:) - cfg.roi(i,1)).^2 + (xyz(2,:) - cfg.roi(i,2)).^2 + (xyz(3,:) - cfg.roi(i,3)).^2 ); mask = mask | (dist <= cfg.sphere(i)); end % box(es) elseif isfield(cfg, 'box') mask = zeros(1, prod(dim)); for i=1:size(cfg.roi,1) mask = mask | ... (xyz(1,:) <= (cfg.roi(i,1) + cfg.box(i,1)./2) & xyz(1,:) >= (cfg.roi(i,1) - cfg.box(i,1)./2)) & ... (xyz(2,:) <= (cfg.roi(i,2) + cfg.box(i,2)./2) & xyz(2,:) >= (cfg.roi(i,2) - cfg.box(i,2)./2)) & ... (xyz(3,:) <= (cfg.roi(i,3) + cfg.box(i,3)./2) & xyz(3,:) >= (cfg.roi(i,3) - cfg.box(i,3)./2)); end end end mask = reshape(mask, dim); fprintf('%i voxels in mask, which is %.3f %% of total volume\n', sum(mask(:)), 100*mean(mask(:))); output = mask; elseif mask2label if ischar(cfg.atlas), % assume it to represent a filename atlas = ft_read_atlas(cfg.atlas); else % assume cfg.atlas to be a struct, but it may have been converted % into a config object atlas = struct(cfg.atlas); end % determine which field(s) to use to look up the labels, % and whether these are boolean or indexed fn = fieldnames(atlas); isboolean = false(numel(fn),1); isindexed = false(numel(fn),1); for i=1:length(fn) if islogical(atlas.(fn{i})) && isequal(size(atlas.(fn{i})), atlas.dim) isboolean(i) = true; elseif isnumeric(atlas.(fn{i})) && isequal(size(atlas.(fn{i})), atlas.dim) isindexed(i) = true; end end if any(isindexed) % let the indexed prevail fn = fn(isindexed); isindexed = 1; elseif any(isboolean) % use the boolean fn = fn(isboolean); isindexed = 0; end sel = find(volume.(cfg.maskparameter)(:)); labels.name = cell(0,1); for k = 1:numel(fn) % ensure that they are concatenated as column tmp = atlas.([fn{k},'label']); labels.name = cat(1, labels.name(:), tmp(:)); end labels.name{end+1} = 'no_label_found'; labels.count = zeros(length(labels.name),1); for iLab = 1:length(labels.name) labels.usedqueryrange{iLab} = []; end for iVox = 1:length(sel) usedQR = 1; label = atlas_lookup(atlas, [volume.pos(sel(iVox),1) volume.pos(sel(iVox),2) volume.pos(sel(iVox),3)], 'inputcoord', cfg.inputcoord, 'queryrange', 1); if isempty(label) && cfg.maxqueryrange > 1 label = atlas_lookup(atlas, [volume.pos(sel(iVox),1) volume.pos(sel(iVox),2) volume.pos(sel(iVox),3)], 'inputcoord', cfg.inputcoord, 'queryrange', 3); usedQR = 3; end if isempty(label) && cfg.maxqueryrange > 3 label = atlas_lookup(atlas, [volume.pos(sel(iVox),1) volume.pos(sel(iVox),2) volume.pos(sel(iVox),3)], 'inputcoord', cfg.inputcoord, 'queryrange', 5); usedQR = 5; end if isempty(label) label = {'no_label_found'}; elseif length(label) == 1 label = {label}; end ind_lab = []; for iLab = 1:length(label) ind_lab = [ind_lab find(strcmp(label{iLab}, labels.name))]; end labels.count(ind_lab) = labels.count(ind_lab) + (1/length(ind_lab)); for iFoundLab = 1:length(ind_lab) if isempty(labels.usedqueryrange{ind_lab(iFoundLab)}) labels.usedqueryrange{ind_lab(iFoundLab)} = usedQR; else labels.usedqueryrange{ind_lab(iFoundLab)} = [labels.usedqueryrange{ind_lab(iFoundLab)} usedQR]; end end end %iVox output = labels; end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble provenance %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION point of interest to voxel of interest %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function voi = poi2voi(poi, xyz) xmin = min(abs(xyz(1,:) - poi(1))); xcl = round(abs(xyz(1,:) - poi(1))) == round(xmin); ymin = min(abs(xyz(2,:) - poi(2))); ycl = round(abs(xyz(2,:) - poi(2))) == round(ymin); zmin = min(abs(xyz(3,:) - poi(3))); zcl = round(abs(xyz(3,:) - poi(3))) == round(zmin); xyzcls = xcl + ycl + zcl; ind_voi = xyzcls == 3; if sum(ind_voi) > 1; fprintf('%i voxels at same distance of poi, taking first voxel\n', sum(ind_voi)) ind_voi_temp = find(ind_voi); ind_voi_temp = ind_voi_temp(1); ind_voi = zeros(size(ind_voi)); ind_voi(ind_voi_temp) = 1; ind_voi = logical(ind_voi); end voi = xyz(1:3,ind_voi); fprintf('coordinates of voi: %.1f %.1f %.1f\n', voi(1), voi(2), voi(3));
github
lcnbeapp/beapp-master
ft_multiplotTFR.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_multiplotTFR.m
30,950
utf_8
785cbcd905ef5ff77519037ef9da1a2d
function [cfg] = ft_multiplotTFR(cfg, data) % FT_MULTIPLOTTFR plots the time-frequency representations of power or coherence % in a topographical layout. The plots of the indivual sensors are arranged % according to their location specified in the layout. % % Use as % ft_multiplotTFR(cfg, data) % % The data can be a time-frequency representation of power or coherence % that was computed using the FT_FREQANALYSIS or FT_FREQDESCRIPTIVES % functions. % % The configuration can have the following parameters: % cfg.parameter = field to be represented as color (default depends on data.dimord) % 'powspctrm' or 'cohspctrm' % cfg.maskparameter = field in the data to be used for opacity masking of data % cfg.maskstyle = style used to masking, 'opacity', 'saturation' or 'outline' (default = 'opacity') % use 'saturation' or 'outline' when saving to vector-format (like *.eps) to avoid all % sorts of image-problems (currently only possible with a white backgroud) % cfg.maskalpha = alpha value between 0 (transparant) and 1 (opaque) used for masking areas dictated by cfg.maskparameter (default = 1) % cfg.masknans = 'yes' or 'no' (default = 'yes') % cfg.xlim = 'maxmin' or [xmin xmax] (default = 'maxmin') % cfg.ylim = 'maxmin' or [ymin ymax] (default = 'maxmin') % cfg.zlim = plotting limits for color dimension, 'maxmin', 'maxabs', 'zeromax', 'minzero', or [zmin zmax] (default = 'maxmin') % cfg.gradscale = number, scaling to apply to the MEG gradiometer channels prior to display % cfg.magscale = number, scaling to apply to the MEG magnetometer channels prior to display % cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details % cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui' % cfg.baseline = 'yes', 'no' or [time1 time2] (default = 'no'), see FT_FREQBASELINE % cfg.baselinetype = 'absolute', 'relative', 'relchange' or 'db' (default = 'absolute') % cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') % cfg.box = 'yes', 'no' (default = 'no' if maskparameter given default = 'yes') % Draw a box around each graph % cfg.hotkeys = enables hotkeys (up/down arrows) for dynamic colorbar adjustment % cfg.colorbar = 'yes', 'no' (default = 'no') % cfg.colormap = any sized colormap, see COLORMAP % cfg.comment = string of text (default = date + zlimits) % Add 'comment' to graph (according to COMNT in the layout) % cfg.showlabels = 'yes', 'no' (default = 'no') % cfg.showoutline = 'yes', 'no' (default = 'no') % cfg.fontsize = font size of comment and labels (if present) (default = 8) % cfg.interactive = Interactive plot 'yes' or 'no' (default = 'yes') % In a interactive plot you can select areas and produce a new % interactive plot when a selected area is clicked. Multiple areas % can be selected by holding down the SHIFT key. % cfg.renderer = 'painters', 'zbuffer', ' opengl' or 'none' (default = []) % cfg.directionality = '', 'inflow' or 'outflow' specifies for % connectivity measures whether the inflow into a % node, or the outflow from a node is plotted. The % (default) behavior of this option depends on the dimor % of the input data (see below). % cfg.layout = specify the channel layout for plotting using one of % the supported ways (see below). % % For the plotting of directional connectivity data the cfg.directionality % option determines what is plotted. The default value and the supported % functionality depend on the dimord of the input data. If the input data % is of dimord 'chan_chan_XXX', the value of directionality determines % whether, given the reference channel(s), the columns (inflow), or rows % (outflow) are selected for plotting. In this situation the default is % 'inflow'. Note that for undirected measures, inflow and outflow should % give the same output. If the input data is of dimord 'chancmb_XXX', the % value of directionality determines whether the rows in data.labelcmb are % selected. With 'inflow' the rows are selected if the refchannel(s) occur in % the right column, with 'outflow' the rows are selected if the % refchannel(s) occur in the left column of the labelcmb-field. Default in % this case is '', which means that all rows are selected in which the % refchannel(s) occur. This is to robustly support linearly indexed % undirected connectivity metrics. In the situation where undirected % connectivity measures are linearly indexed, specifying 'inflow' or % 'outflow' can result in unexpected behavior. % % The layout defines how the channels are arranged and what the size of each % subplot is. You can specify the layout in a variety of ways: % - you can provide a pre-computed layout structure (see ft_prepare_layout) % - you can give the name of an ascii layout file with extension *.lay % - you can give the name of an electrode file % - you can give an electrode definition, i.e. "elec" structure % - you can give a gradiometer definition, i.e. "grad" structure % If you do not specify any of these and the data structure contains an % electrode or gradiometer structure (common for MEG data, since the header % of the MEG datafile contains the gradiometer information), that will be % used for creating a layout. If you want to have more fine-grained control % over the layout of the subplots, you should create your own layout file. % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % If you specify this option the input data will be read from a *.mat % file on disk. This mat files should contain only a single variable named 'data', % corresponding to the input structure. For this particular function, the % data should be provided as a cell array. % % See also: % FT_MULTIPLOTER, FT_SINGLEPLOTER, FT_SINGLEPLOTTFR, FT_TOPOPLOTER, FT_TOPOPLOTTFR, % FT_PREPARE_LAYOUT % Undocumented local options: % cfg.channel % cfg.layoutname % cfg.orient = landscape/portrait % Copyright (C) 2003-2006, Ole Jensen % Copyright (C) 2007-2011, Roemer van der Meij & Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar data ft_preamble provenance data ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input data is valid for this function data = ft_checkdata(data, 'datatype', 'freq'); % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'unused', {'cohtargetchannel'}); cfg = ft_checkconfig(cfg, 'renamed', {'matrixside', 'directionality'}); cfg = ft_checkconfig(cfg, 'renamed', {'cohrefchannel', 'refchannel'}); cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'parameter'}); cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'}); cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedforward', 'outflow'}); cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedback', 'inflow'}); cfg = ft_checkconfig(cfg, 'deprecated', {'xparam', 'yparam'}); % set the defaults cfg.baseline = ft_getopt(cfg, 'baseline', 'no'); cfg.baselinetype = ft_getopt(cfg, 'baselinetype', 'absolute'); cfg.trials = ft_getopt(cfg, 'trials', 'all', 1); cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin'); cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin'); cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin'); cfg.magscale = ft_getopt(cfg, 'magscale', 1); cfg.gradscale = ft_getopt(cfg, 'gradscale', 1); cfg.colorbar = ft_getopt(cfg, 'colorbar', 'no'); cfg.comment = ft_getopt(cfg, 'comment', date); cfg.showlabels = ft_getopt(cfg, 'showlabels', 'no'); cfg.showoutline = ft_getopt(cfg, 'showoutline', 'no'); cfg.channel = ft_getopt(cfg, 'channel', 'all'); cfg.fontsize = ft_getopt(cfg, 'fontsize', 8); cfg.interactive = ft_getopt(cfg, 'interactive', 'yes'); cfg.hotkeys = ft_getopt(cfg, 'hotkeys', 'no'); cfg.renderer = ft_getopt(cfg, 'renderer'); % let MATLAB decide on default cfg.orient = ft_getopt(cfg, 'orient', 'landscape'); cfg.maskalpha = ft_getopt(cfg, 'maskalpha', 1); cfg.masknans = ft_getopt(cfg, 'masknans', 'yes'); cfg.maskparameter = ft_getopt(cfg, 'maskparameter'); cfg.maskstyle = ft_getopt(cfg, 'maskstyle', 'opacity'); cfg.directionality = ft_getopt(cfg, 'directionality', ''); cfg.figurename = ft_getopt(cfg, 'figurename'); if ~isfield(cfg, 'box') if ~isempty(cfg.maskparameter) cfg.box = 'yes'; else cfg.box = 'no'; end end if numel(findobj(gcf, 'type', 'axes', '-not', 'tag', 'ft-colorbar')) > 1 && strcmp(cfg.interactive, 'yes') warning('using cfg.interactive = ''yes'' in subplots is not supported, setting cfg.interactive = ''no''') cfg.interactive = 'no'; end dimord = data.dimord; dimtok = tokenize(dimord, '_'); % Set x/y/parameter defaults if ~any(ismember(dimtok, 'time')) error('input data needs a time dimension'); else xparam = 'time'; yparam = 'freq'; cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm'); end if isfield(cfg, 'channel') && isfield(data, 'label') cfg.channel = ft_channelselection(cfg.channel, data.label); elseif isfield(cfg, 'channel') && isfield(data, 'labelcmb') cfg.channel = ft_channelselection(cfg.channel, unique(data.labelcmb(:))); end % perform channel selection but only allow this when cfg.interactive = 'no' if isfield(data, 'label') && strcmp(cfg.interactive, 'no') selchannel = ft_channelselection(cfg.channel, data.label); elseif isfield(data, 'labelcmb') && strcmp(cfg.interactive, 'no') selchannel = ft_channelselection(cfg.channel, unique(data.labelcmb(:))); end % check whether rpt/subj is present and remove if necessary and whether hasrpt = any(ismember(dimtok, {'rpt' 'subj'})); if hasrpt, % this also deals with fourier-spectra in the input % or with multiple subjects in a frequency domain stat-structure % on the fly computation of coherence spectrum is not supported if isfield(data, 'crsspctrm'), data = rmfield(data, 'crsspctrm'); end % keep mask-parameter if it is set if ~isempty(cfg.maskparameter) tempmask = data.(cfg.maskparameter); end tmpcfg = []; tmpcfg.trials = cfg.trials; tmpcfg.jackknife = 'no'; if isfield(cfg, 'parameter') && ~strcmp(cfg.parameter, 'powspctrm') % freqdesctiptives will only work on the powspctrm field % hence a temporary copy of the data is needed tempdata.dimord = data.dimord; tempdata.freq = data.freq; tempdata.label = data.label; tempdata.powspctrm = data.(cfg.parameter); if isfield(data, 'cfg') tempdata.cfg = data.cfg; end tempdata = ft_freqdescriptives(tmpcfg, tempdata); data.(cfg.parameter) = tempdata.powspctrm; clear tempdata else data = ft_freqdescriptives(tmpcfg, data); end % put mask-parameter back if it is set if ~isempty(cfg.maskparameter) data.(cfg.maskparameter) = tempmask; end dimord = data.dimord; dimtok = tokenize(dimord, '_'); end % if hasrpt % Read or create the layout that will be used for plotting: cla; hold on lay = ft_prepare_layout(cfg, data); cfg.layout = lay; % Apply baseline correction: if ~strcmp(cfg.baseline, 'no') % keep mask-parameter if it is set if ~isempty(cfg.maskparameter) tempmask = data.(cfg.maskparameter); end data = ft_freqbaseline(cfg, data); % put mask-parameter back if it is set if ~isempty(cfg.maskparameter) data.(cfg.maskparameter) = tempmask; end end % Handle the bivariate case % Check for bivariate metric with 'chan_chan' in the dimord selchan = strmatch('chan', dimtok); isfull = length(selchan)>1; % Check for bivariate metric with a labelcmb haslabelcmb = isfield(data, 'labelcmb'); if (isfull || haslabelcmb) && (isfield(data, cfg.parameter) && ~strcmp(cfg.parameter, 'powspctrm')) % A reference channel is required: if ~isfield(cfg, 'refchannel') error('no reference channel is specified'); end % check for refchannel being part of selection if ~strcmp(cfg.refchannel, 'gui') if haslabelcmb cfg.refchannel = ft_channelselection(cfg.refchannel, unique(data.labelcmb(:))); else cfg.refchannel = ft_channelselection(cfg.refchannel, data.label); end if (isfull && ~any(ismember(data.label, cfg.refchannel))) || ... (haslabelcmb && ~any(ismember(data.labelcmb(:), cfg.refchannel))) error('cfg.refchannel is a not present in the (selected) channels)') end end % Interactively select the reference channel if strcmp(cfg.refchannel, 'gui') % Open a single figure with the channel layout, the user can click on a reference channel h = clf; ft_plot_lay(lay, 'box', false); title('Select the reference channel by dragging a selection window, more than 1 channel can be selected...'); % add the channel information to the figure info = guidata(gcf); info.x = lay.pos(:, 1); info.y = lay.pos(:, 2); info.label = lay.label; info.dataname = ''; guidata(h, info); %set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'callback', {@select_topoplotER, cfg, data}}); set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonUpFcn'}); set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonDownFcn'}); set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonMotionFcn'}); return end if ~isfull, % Convert 2-dimensional channel matrix to a single dimension: if isempty(cfg.directionality) sel1 = find(strcmp(cfg.refchannel, data.labelcmb(:, 2))); sel2 = find(strcmp(cfg.refchannel, data.labelcmb(:, 1))); elseif strcmp(cfg.directionality, 'outflow') sel1 = []; sel2 = find(strcmp(cfg.refchannel, data.labelcmb(:, 1))); elseif strcmp(cfg.directionality, 'inflow') sel1 = find(strcmp(cfg.refchannel, data.labelcmb(:, 2))); sel2 = []; end fprintf('selected %d channels for %s\n', length(sel1)+length(sel2), cfg.parameter); if length(sel1)+length(sel2)==0 error('there are no channels selected for plotting: you may need to look at the specification of cfg.directionality'); end data.(cfg.parameter) = data.(cfg.parameter)([sel1;sel2], :, :); data.label = [data.labelcmb(sel1, 1);data.labelcmb(sel2, 2)]; data.labelcmb = data.labelcmb([sel1;sel2], :); %data = rmfield(data, 'labelcmb'); else % General case sel = match_str(data.label, cfg.refchannel); siz = [size(data.(cfg.parameter)) 1]; if strcmp(cfg.directionality, 'inflow') || isempty(cfg.directionality) %the interpretation of 'inflow' and 'outflow' depend on %the definition in the bivariate representation of the data %in FieldTrip the row index 'causes' the column index channel %data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(:, sel, :), 2), [siz(1) 1 siz(3:end)]); sel1 = 1:siz(1); sel2 = sel; meandir = 2; elseif strcmp(cfg.directionality, 'outflow') %data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(sel, :, :), 1), [siz(1) 1 siz(3:end)]); sel1 = sel; sel2 = 1:siz(1); meandir = 1; elseif strcmp(cfg.directionality, 'ff-fd') error('cfg.directionality = ''ff-fd'' is not supported anymore, you have to manually subtract the two before the call to ft_multiplotTFR'); elseif strcmp(cfg.directionality, 'fd-ff') error('cfg.directionality = ''fd-ff'' is not supported anymore, you have to manually subtract the two before the call to ft_multiplotTFR'); end %if directionality end %if ~isfull end %handle the bivariate data % Get physical x-axis range: if strcmp(cfg.xlim, 'maxmin') xmin = min(data.(xparam)); xmax = max(data.(xparam)); else xmin = cfg.xlim(1); xmax = cfg.xlim(2); end % Replace value with the index of the nearest bin if ~isempty(xparam) xmin = nearest(data.(xparam), xmin); xmax = nearest(data.(xparam), xmax); end % Get physical y-axis range: if strcmp(cfg.ylim, 'maxmin') ymin = min(data.(yparam)); ymax = max(data.(yparam)); else ymin = cfg.ylim(1); ymax = cfg.ylim(2); end % Replace value with the index of the nearest bin if ~isempty(yparam) ymin = nearest(data.(yparam), ymin); ymax = nearest(data.(yparam), ymax); end % test if X and Y are linearly spaced (to within 10^-12): % FROM UIMAGE x = data.(xparam)(xmin:xmax); y = data.(yparam)(ymin:ymax); dx = min(diff(x)); % smallest interval for X dy = min(diff(y)); % smallest interval for Y evenx = all(abs(diff(x)/dx-1)<1e-12); % true if X is linearly spaced eveny = all(abs(diff(y)/dy-1)<1e-12); % true if Y is linearly spaced if ~evenx || ~eveny warning('(one of the) axis is/are not evenly spaced, but plots are made as if axis are linear') end % Take subselection of channels, this only works % in the interactive mode if exist('selchannel', 'var') sellab = match_str(data.label, selchannel); label = data.label(sellab); else sellab = 1:numel(data.label); label = data.label; end dat = data.(cfg.parameter); % get dimord dimensions dims = textscan(data.dimord, '%s', 'Delimiter', '_'); dims = dims{1}; ydim = find(strcmp(yparam, dims)); xdim = find(strcmp(xparam, dims)); zdim = setdiff(1:ndims(dat), [ydim xdim]); % and permute dat = permute(dat, [zdim(:)' ydim xdim]); if isfull dat = dat(sel1, sel2, ymin:ymax, xmin:xmax); dat = nanmean(dat, meandir); siz = size(dat); dat = reshape(dat, [max(siz(1:2)) siz(3) siz(4)]); dat = dat(sellab, :, :); % this makes no sense, so COMMENTED OUT AS OF FEBURARY 22 2012 % elseif haslabelcmb % dat = dat(sellab, ymin:ymax, xmin:xmax); else dat = dat(sellab, ymin:ymax, xmin:xmax); end if ~isempty(cfg.maskparameter) mask = data.(cfg.maskparameter); mask = permute(mask, [zdim(:)' ydim xdim]); if isfull && cfg.maskalpha == 1 mask = mask(sel1, sel2, ymin:ymax, xmin:xmax); mask = nanmean(nanmean(nanmean(mask, meandir), 4), 3); elseif haslabelcmb && cfg.maskalpha == 1 mask = mask(sellab, ymin:ymax, xmin:xmax); %mask = nanmean(nanmean(mask, 3), 2); elseif cfg.maskalpha == 1 mask = mask(sellab, ymin:ymax, xmin:xmax); %mask = nanmean(nanmean(mask, 3), 2); elseif isfull && cfg.maskalpha ~= 1 maskl = mask(sel1, sel2, ymin:ymax, xmin:xmax); %% check this for full representation mask = zeros(size(maskl)); mask(maskl) = 1; mask(~maskl) = cfg.maskalpha; elseif haslabelcmb && cfg.maskalpha ~= 1 maskl = mask(sellab, ymin:ymax, xmin:xmax); mask = zeros(size(maskl)); mask(maskl) = 1; mask(~maskl) = cfg.maskalpha; elseif cfg.maskalpha ~= 1 maskl = mask(sellab, ymin:ymax, xmin:xmax); mask = zeros(size(maskl)); mask(maskl) = 1; mask(~maskl) = cfg.maskalpha; end end % Select the channels in the data that match with the layout: [chanseldat, chansellay] = match_str(label, lay.label); if isempty(chanseldat) error('labels in data and labels in layout do not match'); end % if magnetometer/gradiometer scaling is requested, get indices for % channels if (cfg.magscale ~= 1) magInd = match_str(label, ft_channelselection('MEGMAG', label)); end if (cfg.gradscale ~= 1) gradInd = match_str(label, ft_channelselection('MEGGRAD', label)); end datsel = dat(chanseldat, :, :); if ~isempty(cfg.maskparameter) maskdat = mask(chanseldat, :, :); end % Select x and y coordinates and labels of the channels in the data chanX = lay.pos(chansellay, 1); chanY = lay.pos(chansellay, 2); chanWidth = lay.width(chansellay); chanHeight = lay.height(chansellay); % Get physical z-axis range (color axis): if strcmp(cfg.zlim, 'maxmin') zmin = min(datsel(:)); zmax = max(datsel(:)); elseif strcmp(cfg.zlim, 'maxabs') zmin = -max(abs(datsel(:))); zmax = max(abs(datsel(:))); elseif strcmp(cfg.zlim, 'zeromax') zmin = 0; zmax = max(datsel(:)); elseif strcmp(cfg.zlim, 'minzero') zmin = min(datsel(:)); zmax = 0; else zmin = cfg.zlim(1); zmax = cfg.zlim(2); end % set colormap if isfield(cfg, 'colormap') if size(cfg.colormap, 2)~=3, error('multiplotTFR(): Colormap must be a n x 3 matrix'); end set(gcf, 'colormap', cfg.colormap); end % Plot channels: for k=1:length(chanseldat) % Get cdata: cdata = shiftdim(datsel(k, :, :)); if ~isempty(cfg.maskparameter) mdata = shiftdim(maskdat(k, :, :)); end % scale if needed if (cfg.magscale ~= 1 && any(magInd == chanseldat(k))) cdata = cdata .* cfg.magscale; end if (cfg.gradscale ~= 1 && any(gradInd == chanseldat(k))) cdata = cdata .* cfg.gradscale; end % Draw plot (and mask Nan's with maskfield if requested) if isequal(cfg.masknans, 'yes') && isempty(cfg.maskparameter) nans_mask = ~isnan(cdata); mask = double(nans_mask); ft_plot_matrix(cdata, 'clim', [zmin zmax], 'tag', 'cip', 'highlightstyle', cfg.maskstyle, 'highlight', mask, 'hpos', chanX(k), 'vpos', chanY(k), 'width', chanWidth(k), 'height', chanHeight(k)) elseif isequal(cfg.masknans, 'yes') && ~isempty(cfg.maskparameter) nans_mask = ~isnan(cdata); mask = nans_mask .* mdata; mask = double(mask); ft_plot_matrix(cdata, 'clim', [zmin zmax], 'tag', 'cip', 'highlightstyle', cfg.maskstyle, 'highlight', mask, 'hpos', chanX(k), 'vpos', chanY(k), 'width', chanWidth(k), 'height', chanHeight(k)) elseif isequal(cfg.masknans, 'no') && ~isempty(cfg.maskparameter) mask = mdata; mask = double(mask); ft_plot_matrix(cdata, 'clim', [zmin zmax], 'tag', 'cip', 'highlightstyle', cfg.maskstyle, 'highlight', mask, 'hpos', chanX(k), 'vpos', chanY(k), 'width', chanWidth(k), 'height', chanHeight(k)) else ft_plot_matrix(cdata, 'clim', [zmin zmax], 'tag', 'cip', 'hpos', chanX(k), 'vpos', chanY(k), 'width', chanWidth(k), 'height', chanHeight(k)) end % Currently the handle isn't being used below, this is here for possible use in the future h = findobj('tag', 'cip'); end % for chanseldat % write comment: k = cellstrmatch('COMNT', lay.label); if ~isempty(k) comment = cfg.comment; comment = sprintf('%0s\nxlim=[%.3g %.3g]', comment, data.(xparam)(xmin), data.(xparam)(xmax)); comment = sprintf('%0s\nylim=[%.3g %.3g]', comment, data.(yparam)(ymin), data.(yparam)(ymax)); comment = sprintf('%0s\nzlim=[%.3g %.3g]', comment, zmin, zmax); ft_plot_text(lay.pos(k, 1), lay.pos(k, 2), sprintf(comment), 'Fontsize', cfg.fontsize); end % plot scale: k = cellstrmatch('SCALE', lay.label); if ~isempty(k) % Get average cdata across channels: cdata = shiftdim(mean(datsel, 1)); % Draw plot (and mask Nan's with maskfield if requested) if isequal(cfg.masknans, 'yes') && isempty(cfg.maskparameter) mask = ~isnan(cdata); mask = double(mask); ft_plot_matrix(cdata, 'clim', [zmin zmax], 'tag', 'cip', 'highlightstyle', cfg.maskstyle, 'highlight', mask, 'hpos', lay.pos(k, 1), 'vpos', lay.pos(k, 2), 'width', lay.width(k, 1), 'height', lay.height(k, 1)) elseif isequal(cfg.masknans, 'yes') && ~isempty(cfg.maskparameter) mask = ~isnan(cdata); mask = mask .* mdata; mask = double(mask); ft_plot_matrix(cdata, 'clim', [zmin zmax], 'tag', 'cip', 'highlightstyle', cfg.maskstyle, 'highlight', mask, 'hpos', lay.pos(k, 1), 'vpos', lay.pos(k, 2), 'width', lay.width(k, 1), 'height', lay.height(k, 1)) elseif isequal(cfg.masknans, 'no') && ~isempty(cfg.maskparameter) mask = mdata; mask = double(mask); ft_plot_matrix(cdata, 'clim', [zmin zmax], 'tag', 'cip', 'highlightstyle', cfg.maskstyle, 'highlight', mask, 'hpos', lay.pos(k, 1), 'vpos', lay.pos(k, 2), 'width', lay.width(k, 1), 'height', lay.height(k, 1)) else ft_plot_matrix(cdata, 'clim', [zmin zmax], 'tag', 'cip', 'hpos', lay.pos(k, 1), 'vpos', lay.pos(k, 2), 'width', lay.width(k, 1), 'height', lay.height(k, 1)) end % Currently the handle isn't being used below, this is here for possible use in the future h = findobj('tag', 'cip'); end % plot layout boxflg = istrue(cfg.box); labelflg = istrue(cfg.showlabels); outlineflg = istrue(cfg.showoutline); ft_plot_lay(lay, 'box', boxflg, 'label', labelflg, 'outline', outlineflg, 'point', 'no', 'mask', 'no'); % plot colorbar: if isfield(cfg, 'colorbar') && (strcmp(cfg.colorbar, 'yes')) colorbar; end % Set colour axis caxis([zmin zmax]); if strcmp('yes', cfg.hotkeys) % Attach data and cfg to figure and attach a key listener to the figure set(gcf, 'KeyPressFcn', {@key_sub, zmin, zmax}) end % set the figure window title if isempty(get(gcf, 'Name')) if isfield(cfg, 'funcname') funcname = cfg.funcname; else funcname = mfilename; end if isfield(cfg, 'dataname') dataname = cfg.dataname; elseif nargin > 1 dataname = inputname(2); else % data provided through cfg.inputfile dataname = cfg.inputfile; end if isempty(cfg.figurename) set(gcf, 'Name', sprintf('%d: %s: %s', double(gcf), funcname, dataname)); set(gcf, 'NumberTitle', 'off'); else set(gcf, 'name', cfg.figurename); set(gcf, 'NumberTitle', 'off'); end else funcname = ''; dataname = ''; end % Make the figure interactive: if strcmp(cfg.interactive, 'yes') % add the channel information to the figure info = guidata(gcf); info.x = lay.pos(:, 1); info.y = lay.pos(:, 2); info.label = lay.label; info.dataname = dataname; guidata(gcf, info); set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg, data}, 'event', 'WindowButtonUpFcn'}); set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg, data}, 'event', 'WindowButtonDownFcn'}); set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg, data}, 'event', 'WindowButtonMotionFcn'}); end axis tight axis off hold off % Set orientation for printing if specified if ~isempty(cfg.orient) orient(gcf, cfg.orient); end % Set renderer if specified if ~isempty(cfg.renderer) set(gcf, 'renderer', cfg.renderer) end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous data ft_postamble provenance % add a menu to the figure % also, delete any possibly existing previous menu, this is safe because delete([]) does nothing delete(findobj(gcf, 'type', 'uimenu', 'label', 'FieldTrip')); ftmenu = uimenu(gcf, 'Label', 'FieldTrip'); uimenu(ftmenu, 'Label', 'Show pipeline', 'Callback', {@menu_pipeline, cfg}); uimenu(ftmenu, 'Label', 'About', 'Callback', @menu_about); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function l = cellstrmatch(str, strlist) l = []; for k=1:length(strlist) if strcmp(char(str), char(strlist(k))) l = [l k]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION which is called by ft_select_channel in case cfg.refchannel='gui' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function select_multiplotTFR(label, cfg, varargin) if isfield(cfg, 'inputfile') % the reading has already been done and varargin contains the data cfg = rmfield(cfg, 'inputfile'); end % put data name in here, this cannot be resolved by other means info = guidata(gcf); cfg.dataname = info.dataname; cfg.refchannel = label; fprintf('selected cfg.refchannel = ''%s''\n', join_str(', ', cfg.refchannel)); p = get(gcf, 'Position'); f = figure; set(f, 'Position', p); ft_multiplotTFR(cfg, varargin{:}); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION which is called after selecting channels in case of cfg.interactive='yes' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function select_singleplotTFR(label, cfg, varargin) if ~isempty(label) if isfield(cfg, 'inputfile') % the reading has already been done and varargin contains the data cfg = rmfield(cfg, 'inputfile'); end cfg.channel = label; % make sure ft_singleplotTFR does not apply a baseline correction again cfg.baseline = 'no'; % put data name in here, this cannot be resolved by other means info = guidata(gcf); cfg.dataname = info.dataname; fprintf('selected cfg.channel = {'); for i=1:(length(cfg.channel)-1) fprintf('''%s'', ', cfg.channel{i}); end fprintf('''%s''}\n', cfg.channel{end}); p = get(gcf, 'Position'); f = figure; set(f, 'Position', p); ft_singleplotTFR(cfg, varargin{:}); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION which handles hot keys in the current plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key_sub(handle, eventdata, varargin) incr = (max(caxis)-min(caxis)) /10; % symmetrically scale color bar down by 10 percent if strcmp(eventdata.Key, 'uparrow') caxis([min(caxis)-incr max(caxis)+incr]); % symmetrically scale color bar up by 10 percent elseif strcmp(eventdata.Key, 'downarrow') caxis([min(caxis)+incr max(caxis)-incr]); % resort to minmax of data for colorbar elseif strcmp(eventdata.Key, 'm') caxis([varargin{1} varargin{2}]); end
github
lcnbeapp/beapp-master
ft_connectivityanalysis.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_connectivityanalysis.m
41,951
utf_8
0d5870627ccd8b4bbcef93cede262474
function [stat] = ft_connectivityanalysis(cfg, data) % FT_CONNECTIVITYANALYSIS computes various measures of connectivity between % MEG/EEG channels or between source-level signals. % % Use as % stat = ft_connectivityanalysis(cfg, data) % stat = ft_connectivityanalysis(cfg, timelock) % stat = ft_connectivityanalysis(cfg, freq) % stat = ft_connectivityanalysis(cfg, source) % where the first input argument is a configuration structure (see below) % and the second argument is the output of FT_PREPROCESSING, % FT_TIMELOCKANLAYSIS, FT_FREQANALYSIS, FT_MVARANALYSIS or FT_SOURCEANALYSIS. % % The different connectivity metrics are supported only for specific % datatypes (see below). % % The configuration structure has to contain % cfg.method = string, can be % 'amplcorr', amplitude correlation, support for freq and source data % 'coh', coherence, support for freq, freqmvar and source data. % For partial coherence also specify cfg.partchannel, see below. % For imaginary part of coherency or coherency also specify % cfg.complex, see below. % 'csd', cross-spectral density matrix, can also calculate partial % csds - if cfg.partchannel is specified, support for freq % and freqmvar data % 'dtf', directed transfer function, support for freq and % freqmvar data % 'granger', granger causality, support for freq and freqmvar data % 'pdc', partial directed coherence, support for freq and % freqmvar data % 'plv', phase-locking value, support for freq and freqmvar data % 'powcorr', power correlation, support for freq and source data % 'powcorr_ortho', power correlation with single trial % orthogonalisation, support for source data % 'ppc' pairwise phase consistency % 'psi', phaseslope index, support for freq and freqmvar data % 'wpli', weighted phase lag index (signed one, % still have to take absolute value to get indication of % strength of interaction. Note: measure has positive % bias. Use wpli_debiased to avoid this. % 'wpli_debiased' debiased weighted phase lag index % (estimates squared wpli) % 'wppc' weighted pairwise phase consistency % 'corr' Pearson correlation, support for timelock or raw data % % Additional configuration options are % cfg.channel = Nx1 cell-array containing a list of channels which are % used for the subsequent computations. This only has an effect when % the input data is univariate. See FT_CHANNELSELECTION % cfg.channelcmb = Nx2 cell-array containing the channel combinations on % which to compute the connectivity. This only has an effect when the % input data is univariate. See FT_CHANNELCOMBINATION % cfg.trials = Nx1 vector specifying which trials to include for the % computation. This only has an effect when the input data contains % repetitions. % cfg.feedback = string, specifying the feedback presented to the user. % Default is 'none'. See FT_PROGRESS % % For specific methods the cfg can also contain % cfg.partchannel = cell-array containing a list of channels that need to % be partialized out, support for method 'coh', 'csd', 'plv' % cfg.complex = 'abs' (default), 'angle', 'complex', 'imag', 'real', % '-logabs', support for method 'coh', 'csd', 'plv' % cfg.removemean = 'yes' (default), or 'no', support for method % 'powcorr' and 'amplcorr'. % cfg.bandwidth = scalar, (default = Rayleigh frequency), needed for % 'psi', half-bandwidth of the integration across frequencies (in Hz) % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % cfg.outputfile = ... % If you specify one of these (or both) the input data will be read from a *.mat % file on disk and/or the output data will be written to a *.mat file. These mat % files should contain only a single variable, corresponding with the % input/output structure. % % See also FT_PREPROCESSING, FT_TIMELOCKANALYSIS, FT_FREQANALYSIS, % FT_MVARANALYSIS, FT_SOURCEANALYSIS, FT_NETWORKANALYSIS. % % For the implemented methods, see also FT_CONNECTIVITY_CORR, % FT_CONNECTIVITY_GRANGER, FT_CONNECTIVITY_PPC, FT_CONNECTIVITY_WPLI, % FT_CONNECTIVITY_PDC, FT_CONNECTIVITY_DTF, FT_CONNECTIVITY_PSI % Undocumented options: % cfg.refindx = % cfg.jackknife = % cfg.method = 'mi'; % cfg.granger.block = % cfg.granger.conditional = % % Methods to be implemented % 'xcorr', cross correlation function % 'di', directionality index % 'spearman' spearman's rank correlation % Copyright (C) 2009, Jan-Mathijs Schoffelen, Andre Bastos, Martin Vinck, Robert Oostenveld % Copyright (C) 2010-2011, Jan-Mathijs Schoffelen, Martin Vinck % Copyright (C) 2012-2013, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar data ft_preamble provenance data ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % FIXME it should be checked carefully whether the following works % check if the input data is valid for this function % data = ft_checkdata(data, 'datatype', {'raw', 'timelock', 'freq', 'source'}); % set the defaults cfg.feedback = ft_getopt(cfg, 'feedback', 'none'); cfg.channel = ft_getopt(cfg, 'channel', 'all'); cfg.channelcmb = ft_getopt(cfg, 'channelcmb', {'all' 'all'}); cfg.refindx = ft_getopt(cfg, 'refindx', 'all'); cfg.trials = ft_getopt(cfg, 'trials', 'all', 1); cfg.complex = ft_getopt(cfg, 'complex', 'abs'); cfg.jackknife = ft_getopt(cfg, 'jackknife', 'no'); cfg.removemean = ft_getopt(cfg, 'removemean', 'yes'); cfg.partchannel = ft_getopt(cfg, 'partchannel', ''); cfg.parameter = ft_getopt(cfg, 'parameter', []); hasjack = (isfield(data, 'method') && strcmp(data.method, 'jackknife')) || (isfield(data, 'dimord') && strcmp(data.dimord(1:6), 'rptjck')); hasrpt = (isfield(data, 'dimord') && ~isempty(strfind(data.dimord, 'rpt'))) || (isfield(data, 'avg') && isfield(data.avg, 'mom')) || (isfield(data, 'trial') && isfield(data.trial, 'mom')); % FIXME old-fashioned pcc data dojack = strcmp(cfg.jackknife, 'yes'); normrpt = 0; % default, has to be overruled e.g. in plv, because of single replicate normalisation normpow = 1; % default, has to be overruled e.g. in csd, % select trials of interest if ~strcmp(cfg.trials, 'all') tmpcfg = []; tmpcfg.trials = cfg.trials; data = ft_selectdata(tmpcfg, data); [cfg, data] = rollback_provenance(cfg, data); end % select channels/channelcombination of interest and set the cfg-options accordingly if isfield(data, 'label'), selchan = cell(0, 1); if ~isempty(cfg.channelcmb) && ~isequal(cfg.channelcmb, {'all' 'all'}), tmpcmb = ft_channelcombination(cfg.channelcmb, data.label); tmpchan = unique(tmpcmb(:)); cfg.channelcmb = ft_channelcombination(cfg.channelcmb, tmpchan, 1); selchan = [selchan;unique(cfg.channelcmb(:))]; end cfg.channel = ft_channelselection(cfg.channel, data.label); selchan = [selchan;cfg.channel]; if ~isempty(cfg.partchannel) cfg.partchannel = ft_channelselection(cfg.partchannel, data.label); selchan = [selchan; cfg.partchannel]; end tmpcfg = []; tmpcfg.channel = unique(selchan); data = ft_selectdata(tmpcfg, data); elseif isfield(data, 'labelcmb') cfg.channel = ft_channelselection(cfg.channel, unique(data.labelcmb(:))); if ~isempty(cfg.partchannel) error('partialisation is only possible without linearly indexed bivariate data'); end if ~isempty(cfg.channelcmb), % FIXME do something extra here end % FIXME call selectdata end % FIXME check which methods require hasrpt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % data bookkeeping - ensure that the input data is appropriate for the method %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% needrpt = 1; % logical flag to specify whether (pseudo)-repetitions are required in the lower level connectivity function (can be singleton) switch cfg.method case {'coh' 'csd'} if ~isempty(cfg.partchannel) if hasrpt && ~hasjack, warning('partialisation on single trial observations is not supported, removing trial dimension'); try data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'}, 'cmbrepresentation', 'fullfast'); inparam = 'crsspctrm'; hasrpt = 0; catch error('partial coherence/csd is only supported for input allowing for a all-to-all csd representation'); end else try data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'}, 'cmbrepresentation', 'full'); inparam = 'crsspctrm'; catch error('partial coherence/csd is only supported for input allowing for a all-to-all csd representation'); end end else data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq' 'source'}); inparam = 'crsspctrm'; end if strcmp(cfg.method, 'csd'), normpow = 0; outparam = 'crsspctrm'; elseif strcmp(cfg.method, 'coh'), outparam = 'cohspctrm'; end dtype = ft_datatype(data); switch dtype case 'source' if isempty(cfg.refindx), error('indices of reference voxels need to be specified'); end % if numel(cfg.refindx)>1, error('more than one reference voxel is not yet supported'); end otherwise end % FIXME think of accommodating partial coherence for source data with only a few references case {'wpli'} data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'}); inparam = 'crsspctrm'; outparam = 'wplispctrm'; debiaswpli = 0; if hasjack, error('to compute wpli, data should be in rpt format'); end case {'wpli_debiased'} data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'}); inparam = 'crsspctrm'; outparam = 'wpli_debiasedspctrm'; debiaswpli = 1; if hasjack, error('to compute wpli, data should be in rpt format'); end case {'ppc'} data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'}); inparam = 'crsspctrm'; outparam = 'ppcspctrm'; weightppc = 0; if hasjack, error('to compute ppc, data should be in rpt format'); end case {'wppc'} data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'}); inparam = 'crsspctrm'; outparam = 'wppcspctrm'; weightppc = 1; if hasjack, error('to compute wppc, data should be in rpt format'); end case {'plv'} data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq' 'source'}); inparam = 'crsspctrm'; outparam = 'plvspctrm'; normrpt = 1; case {'corr'} data = ft_checkdata(data, 'datatype', {'raw' 'timelock'}); if isfield(data, 'cov') % it looks like a timelock with a cov, which is perfectly valid as input data = ft_checkdata(data, 'datatype', 'timelock'); else % it does not have a cov, the covariance will be computed on the fly further down data = ft_checkdata(data, 'datatype', 'raw'); end inparam = 'cov'; outparam = cfg.method; case {'amplcorr' 'powcorr'} data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq' 'source'}); dtype = ft_datatype(data); switch dtype case {'freq' 'freqmvar'} inparam = 'powcovspctrm'; case 'source' inparam = 'powcov'; if isempty(cfg.refindx), error('indices of reference voxels need to be specified'); end % if numel(cfg.refindx)>1, error('more than one reference voxel is not yet supported'); end otherwise end outparam = [cfg.method, 'spctrm']; case {'granger' 'instantaneous_causality' 'total_interdependence'} % create subcfg for the spectral factorization if ~isfield(cfg, 'granger') cfg.granger = []; end cfg.granger.conditional = ft_getopt(cfg.granger, 'conditional', 'no'); cfg.granger.block = ft_getopt(cfg.granger, 'block', []); if isfield(cfg, 'channelcmb'), cfg.granger.channelcmb = cfg.channelcmb; cfg = rmfield(cfg, 'channelcmb'); end data = ft_checkdata(data, 'datatype', {'mvar' 'freqmvar' 'freq'}); inparam = {'transfer', 'noisecov', 'crsspctrm'}; if strcmp(cfg.method, 'granger'), outparam = 'grangerspctrm'; end if strcmp(cfg.method, 'instantaneous_causality'), outparam = 'instantspctrm'; end if strcmp(cfg.method, 'total_interdependence'), outparam = 'totispctrm'; end % check whether the frequency bins are more or less equidistant dfreq = diff(data.freq)./mean(diff(data.freq)); assert(all(dfreq>0.999) && all(dfreq<1.001), ['non equidistant frequency bins are not supported for method ',cfg.method]); case {'dtf' 'pdc'} data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'}); inparam = 'transfer'; outparam = [cfg.method, 'spctrm']; case {'psi'} cfg.bandwidth = ft_getopt(cfg, 'bandwidth', []); cfg.normalize = ft_getopt(cfg, 'normalize', 'no'); assert(~isempty(cfg.bandwidth), 'you need to supply cfg.bandwidth with ''psi'' as method'); data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'}); inparam = 'crsspctrm'; outparam = 'psispctrm'; % check whether the frequency bins are more or less equidistant dfreq = diff(data.freq)./mean(diff(data.freq)); assert(all(dfreq>0.999) && all(dfreq<1.001), 'non equidistant frequency bins are not supported for method ''psi'''); case {'powcorr_ortho'} data = ft_checkdata(data, 'datatype', {'source', 'freq'}); % inparam = 'avg.mom'; inparam = 'mom'; outparam = 'powcorrspctrm'; case {'mi'} % create the subcfg for the mutual information if ~isfield(cfg, 'mi'), cfg.mi = []; end cfg.mi.numbin = ft_getopt(cfg.mi, 'numbin', 10); cfg.mi.lags = ft_getopt(cfg.mi, 'lags', 0); % what are the input requirements? data = ft_checkdata(data, 'datatype', {'raw' 'timelock' 'freq' 'source'}); dtype = ft_datatype(data); if strcmp(dtype, 'timelock') if ~isfield(data, 'trial') inparam = 'avg'; else inparam = 'trial'; end hasrpt = (isfield(data, 'dimord') && ~isempty(strfind(data.dimord, 'rpt'))); elseif strcmp(dtype, 'raw') inparam = 'trial'; hasrpt = 1; elseif strcmp(dtype, 'freq') inparam = 'something'; else inparam = 'something else'; end outparam = 'mi'; needrpt = 1; case {'di'} % wat eigenlijk? otherwise error('unknown method % s', cfg.method); end dtype = ft_datatype(data); % FIXME throw an error if cfg.complex~='abs', and dojack==1 % FIXME throw an error if no replicates and cfg.method='plv' % FIXME trial selection has to be implemented still %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % data bookkeeping - check whether the required inparam is present in the data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(~isfield(data, inparam)) || (isfield(data, 'crsspctrm') && (ischar(inparam) && strcmp(inparam, 'crsspctrm'))), if iscell(inparam) % in the case of multiple inparams, use the first one to check the % input data (e.g. checking for 'transfer' for requested granger) inparam = inparam{1}; end switch dtype case {'freq' 'freqmvar'} if strcmp(inparam, 'crsspctrm') if isfield(data, 'fourierspctrm') [data, powindx, hasrpt] = univariate2bivariate(data, 'fourierspctrm', 'crsspctrm', dtype, 'cmb', cfg.channelcmb, 'keeprpt', normrpt); elseif strcmp(inparam, 'crsspctrm') && isfield(data, 'powspctrm') % if input data is old-fashioned, i.e. contains powandcsd [data, powindx, hasrpt] = univariate2bivariate(data, 'powandcsd', 'crsspctrm', dtype, 'cmb', cfg.channelcmb, 'keeprpt', normrpt); elseif isfield(data, 'labelcmb') powindx = labelcmb2indx(data.labelcmb); else powindx = []; end elseif strcmp(inparam, 'powcovspctrm') if isfield(data, 'powspctrm'), [data, powindx] = univariate2bivariate(data, 'powspctrm', 'powcovspctrm', dtype, 'demeanflag', strcmp(cfg.removemean, 'yes'), 'cmb', cfg.channelcmb, 'sqrtflag', strcmp(cfg.method, 'amplcorr')); elseif isfield(data, 'fourierspctrm'), [data, powindx] = univariate2bivariate(data, 'fourierspctrm', 'powcovspctrm', dtype, 'demeanflag', strcmp(cfg.removemean, 'yes'), 'cmb', cfg.channelcmb, 'sqrtflag', strcmp(cfg.method, 'amplcorr')); end elseif strcmp(inparam, 'transfer') if isfield(data, 'fourierspctrm') % FIXME this is fast but throws away the trial dimension, consider % a way to keep trial information if needed, but use the fast way % if possible data = ft_checkdata(data, 'cmbrepresentation', 'fullfast'); hasrpt = 0; elseif isfield(data, 'powspctrm') data = ft_checkdata(data, 'cmbrepresentation', 'full'); end % convert the inparam back to cell array in the case of granger if strcmp(cfg.method, 'granger') || strcmp(cfg.method, 'instantaneous_causality') || strcmp(cfg.method, 'total_interdependence') inparam = {'transfer' 'noisecov' 'crsspctrm'}; tmpcfg = ft_checkconfig(cfg, 'createsubcfg', {'granger'}); optarg = ft_cfg2keyval(tmpcfg.granger); else tmpcfg = ft_checkconfig(cfg, 'createsubcfg', {cfg.method}); optarg = ft_cfg2keyval(tmpcfg.(cfg.method)); end % compute the transfer matrix data = ft_connectivity_csd2transfer(data, optarg{:}); end case 'source' if ischar(cfg.refindx) && strcmp(cfg.refindx, 'all') cfg.refindx = 1:size(data.pos,1); elseif ischar(cfg.refindx) error('cfg.refindx should be a 1xN vector, or ''all'''); end if strcmp(inparam, 'crsspctrm') [data, powindx, hasrpt] = univariate2bivariate(data, 'mom', 'crsspctrm', dtype, 'cmb', cfg.refindx, 'keeprpt', 0); % [data, powindx, hasrpt] = univariate2bivariate(data, 'fourierspctrm', 'crsspctrm', dtype, 0, cfg.refindx, [], 1); elseif strcmp(inparam, 'powcov') if isfield(data, 'pow') [data, powindx, hasrpt] = univariate2bivariate(data, 'pow', 'powcov', dtype, 'demeanflag', strcmp(cfg.removemean, 'yes'), 'cmb', cfg.refindx, 'sqrtflag', strcmp(cfg.method, 'amplcorr'), 'keeprpt', 0); elseif isfield(data, 'mom') [data, powindx, hasrpt] = univariate2bivariate(data, 'mom', 'powcov', dtype, 'demeanflag', strcmp(cfg.removemean, 'yes'), 'cmb', cfg.refindx, 'sqrtflag', strcmp(cfg.method, 'amplcorr'), 'keeprpt', 0); end end case 'comp' [data, powindx, hasrpt] = univariate2bivariate(data, 'trial', 'cov', dtype, 'demeanflag', strcmp(cfg.removemean, 'yes'), 'cmb', cfg.channelcmb, 'sqrtflag', false, 'keeprpt', 1); end % switch dtype elseif (isfield(data, 'crsspctrm') && (ischar(inparam) && strcmp(inparam, 'crsspctrm'))) % this means that there is a sparse crsspctrm in the data else powindx = []; end % ensure that the bivariate measure exists % do some additional work if single trial normalisation is required % for example when plv needs to be computed if normrpt && hasrpt, if strcmp(inparam, 'crsspctrm'), tmp = data.(inparam); nrpt = size(tmp, 1); ft_progress('init', cfg.feedback, 'normalising...'); for k = 1:nrpt ft_progress(k/nrpt, 'normalising amplitude of replicate % d from % d to 1\n', k, nrpt); tmp(k, :, :, :, :) = tmp(k, :, :, :, :)./abs(tmp(k, :, :, :, :)); end ft_progress('close'); data.(inparam) = tmp; end end % convert the labels for the partialisation channels into indices % do the same for the labels of the channels that should be kept % convert the labels in the output to reflect the partialisation if ~isempty(cfg.partchannel) allchannel = ft_channelselection(cfg.channel, data.label); pchanindx = match_str(allchannel, cfg.partchannel); kchanindx = setdiff(1:numel(allchannel), pchanindx); keepchn = allchannel(kchanindx); cfg.pchanindx = pchanindx; cfg.allchanindx = kchanindx; partstr = ''; for k = 1:numel(cfg.partchannel) partstr = [partstr, '-', cfg.partchannel{k}]; end for k = 1:numel(keepchn) keepchn{k} = [keepchn{k}, '\', partstr(2:end)]; end data.label = keepchn; % update labels to remove the partialed channels % FIXME consider keeping track of which channels have been partialised else cfg.pchanindx = []; cfg.allchanindx = []; end % check if jackknife is required if hasrpt && dojack && hasjack, % do nothing elseif hasrpt && dojack && ~(exist('debiaswpli', 'var') || exist('weightppc', 'var')), % compute leave-one-outs % assume the inparam(s) are well-behaved, i.e. they have the 'rpt' % dimension as the first dimension if iscell(inparam) for k = 1:numel(inparam) nrpt = size(data.(inparam{k}),1); sumdat = sum(data.(inparam{k}),1); data.(inparam{k}) = (sumdat(ones(nrpt,1),:,:,:,:,:) - data.(inparam{k}))./(nrpt-1); clear sumdat; end else nrpt = size(data.(inparam),1); sumdat = sum(data.(inparam),1); data.(inparam) = (sumdat(ones(nrpt,1),:,:,:,:,:) - data.(inparam))./(nrpt-1); clear sumdat; end hasjack = 1; elseif hasrpt && ~(exist('debiaswpli', 'var') || exist('weightppc', 'var') || strcmp(cfg.method, 'powcorr_ortho'))% || needrpt) % create dof variable if isfield(data, 'dof') dof = data.dof; elseif isfield(data, 'cumtapcnt') dof = sum(data.cumtapcnt); end tmpcfg = []; tmpcfg.avgoverrpt = 'yes'; data = ft_selectdata(tmpcfg, data); hasrpt = 0; else % nothing required end % ensure that the first dimension is singleton if ~hasrpt if ~hasrpt && needrpt if ischar(inparam) data.(inparam) = reshape(data.(inparam), [1 size(data.(inparam))]); else for k = 1:numel(inparam) data.(inparam{k}) = reshape(data.(inparam{k}), [1 size(data.(inparam{k}))]); end end if isfield(data, 'dimord') data.dimord = ['rpt_', data.dimord]; elseif ~strcmp(dtype, 'raw') data.([inparam, 'dimord']) = ['rpt_', data.([inparam, 'dimord'])]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute the desired connectivity metric by calling the appropriate ft_connectivity_XXX function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch cfg.method case 'coh' % coherence (unsquared), if cfg.complex = 'imag' imaginary part of coherency optarg = {'complex', cfg.complex, 'dimord', data.dimord, 'feedback', cfg.feedback, 'pownorm', normpow, 'hasjack', hasjack}; if ~isempty(cfg.pchanindx), optarg = cat(2, optarg, {'pchanindx', cfg.pchanindx, 'allchanindx', cfg.allchanindx}); end if exist('powindx', 'var'), optarg = cat(2, optarg, {'powindx', powindx}); end [datout, varout, nrpt] = ft_connectivity_corr(data.(inparam), optarg{:}); case 'csd' % cross-spectral density (e.g. useful if partialisation is required) optarg = {'complex', cfg.complex, 'dimord', data.dimord, 'feedback', cfg.feedback, 'pownorm', normpow, 'hasjack', hasjack}; if ~isempty(cfg.pchanindx), optarg = cat(2, optarg, {'pchanindx', cfg.pchanindx, 'allchanindx', cfg.allchanindx}); end if exist('powindx', 'var'), optarg = cat(2, optarg, {'powindx', powindx}); end [datout, varout, nrpt] = ft_connectivity_corr(data.(inparam), optarg{:}); case {'wpli' 'wpli_debiased'} % weighted pli or debiased weighted phase lag index. optarg = {'feedback', cfg.feedback, 'dojack', dojack, 'debias', debiaswpli}; [datout, varout, nrpt] = ft_connectivity_wpli(data.(inparam), optarg{:}); case {'wppc' 'ppc'} % weighted pairwise phase consistency or pairwise phase consistency optarg = {'feedback', cfg.feedback, 'dojack', dojack, 'weighted', weightppc}; [datout, varout, nrpt] = ft_connectivity_ppc(data.(inparam), optarg{:}); case 'plv' % phase locking value optarg = {'complex', cfg.complex, 'dimord', data.dimord, 'feedback', cfg.feedback, 'pownorm', normpow, 'hasjack', hasjack}; if ~isempty(cfg.pchanindx), optarg = cat(2, optarg, {'pchanindx', cfg.pchanindx, 'allchanindx', cfg.allchanindx}); end if exist('powindx', 'var'), optarg = cat(2, optarg, {'powindx', powindx}); end [datout, varout, nrpt] = ft_connectivity_corr(data.(inparam), optarg{:}); case 'amplcorr' % amplitude correlation if isfield(data, 'dimord'), dimord = data.dimord; else dimord = data.([inparam, 'dimord']); end optarg = {'feedback', cfg.feedback, 'dimord', dimord, 'complex', 'real', 'pownorm', 1, 'pchanindx', [], 'hasjack', hasjack}; if exist('powindx', 'var'), optarg = cat(2, optarg, {'powindx', powindx}); end [datout, varout, nrpt] = ft_connectivity_corr(data.(inparam), optarg{:}); case 'powcorr' % power correlation if isfield(data, 'dimord'), dimord = data.dimord; else dimord = data.([inparam, 'dimord']); end optarg = {'feedback', cfg.feedback, 'dimord', dimord, 'complex', 'real', 'pownorm', 1, 'pchanindx', [], 'hasjack', hasjack}; if exist('powindx', 'var'), optarg = cat(2, optarg, {'powindx', powindx}); end [datout, varout, nrpt] = ft_connectivity_corr(data.(inparam), optarg{:}); case {'granger' 'instantaneous_causality' 'total_interdependence'} % granger causality if ft_datatype(data, 'freq') || ft_datatype(data, 'freqmvar'), if isfield(data, 'labelcmb') && ~istrue(cfg.granger.conditional), % multiple pairwise non-parametric transfer functions % linearly indexed % The following is very slow, one may make assumptions regarding % the order of the channels -> csd2transfer gives combinations in % quadruplets, where the first and fourth are auto-combinations, % and the second and third are cross-combinations % powindx = labelcmb2indx(data.labelcmb); % % The following is not needed anymore, because ft_connectivity_granger % relies on some hard-coded assumptions for the channel-pair ordering. % Otherwise it becomes just too slow. % powindx = zeros(size(data.labelcmb)); % for k = 1:size(powindx, 1)/4 % ix = ((k-1)*4+1):k*4; % powindx(ix, :) = [1 1;4 1;1 4;4 4] + (k-1)*4; % end powindx = []; if isfield(data, 'label'), % this field should be removed data = rmfield(data, 'label'); end elseif isfield(data, 'labelcmb') && istrue(cfg.granger.conditional), % conditional (blockwise) needs linearly represented cross-spectra, % that have been produced by ft_connectivity_csd2transfer % % each row in Nx2 cell-array tmp refers to a comparison % tmp{k, 1} represents the ordered blocks % for the full trivariate model: the second element drives the % first element, while the rest is partialed out. % tmp{k, 2} represents the ordered blocks where the driving block % is left out blocks = unique(data.blockindx); nblocks = numel(blocks); cnt = 0; for k = 1:nblocks for m = (k+1):nblocks cnt = cnt+1; rest = setdiff(reshape(blocks,[1 numel(blocks)]), [k m]); % make sure to reshape blocks into 1xn vector tmp{cnt, 1} = [k m rest]; tmp{cnt, 2} = [k rest]; newlabelcmb{cnt, 1} = data.block(m).name; % note the index swap: convention is driver in left column newlabelcmb{cnt, 2} = data.block(k).name; cnt = cnt+1; tmp{cnt, 1} = [m k rest]; tmp{cnt, 2} = [m rest]; newlabelcmb{cnt, 1} = data.block(k).name; newlabelcmb{cnt, 2} = data.block(m).name; end end [cmbindx, n] = blockindx2cmbindx(data.labelcmb, {data.label data.blockindx}, tmp); powindx.cmbindx = cmbindx; powindx.n = n; data.labelcmb = newlabelcmb; if isfield(data, 'label') % this field should be removed data = rmfield(data, 'label'); end elseif isfield(cfg.granger, 'block') && ~isempty(cfg.granger.block) % blockwise granger for k = 1:numel(cfg.granger.block) %newlabel{k, 1} = cat(2, cfg.granger.block(k).label{:}); newlabel{k,1} = cfg.granger.block(k).name; powindx{k,1} = match_str(data.label, cfg.granger.block(k).label); end data.label = newlabel; else powindx = []; end % fs = cfg.fsample; % FIXME do we really need this, or is this related to how noisecov is defined and normalised? if ~exist('powindx', 'var'), powindx = []; end if strcmp(cfg.method, 'granger'), methodstr = 'granger'; end if strcmp(cfg.method, 'instantaneous_causality'), methodstr = 'instantaneous'; end if strcmp(cfg.method, 'total_interdependence'), methodstr = 'total'; end optarg = {'hasjack', hasjack, 'method', methodstr, 'powindx', powindx, 'dimord', data.dimord}; [datout, varout, nrpt] = ft_connectivity_granger(data.transfer, data.noisecov, data.crsspctrm, optarg{:}); else error('granger for time domain data is not yet implemented'); end case 'dtf' % directed transfer function if isfield(data, 'labelcmb'), powindx = labelcmb2indx(data.labelcmb); else powindx = []; end optarg = {'feedback', cfg.feedback, 'powindx', powindx, 'hasjack', hasjack}; hasrpt = ~isempty(strfind(data.dimord, 'rpt')); if hasrpt, nrpt = size(data.(inparam), 1); datin = data.(inparam); else nrpt = 1; datin = reshape(data.(inparam), [1 size(data.(inparam))]); end [datout, varout, nrpt] = ft_connectivity_dtf(datin, optarg{:}); case 'pdc' % partial directed coherence if isfield(data, 'labelcmb'), powindx = labelcmb2indx(data.labelcmb); else powindx = []; end optarg = {'feedback', cfg.feedback, 'powindx', powindx, 'hasjack', hasjack}; hasrpt = ~isempty(strfind(data.dimord, 'rpt')); if hasrpt, nrpt = size(data.(inparam), 1); datin = data.(inparam); else nrpt = 1; datin = reshape(data.(inparam), [1 size(data.(inparam))]); end [datout, varout, nrpt] = ft_connectivity_pdc(datin, optarg{:}); case 'psi' % phase slope index nbin = nearest(data.freq, data.freq(1)+cfg.bandwidth)-1; optarg = {'feedback', cfg.feedback, 'dimord', data.dimord, 'nbin', nbin, 'normalize', cfg.normalize, 'hasrpt', hasrpt, 'hasjack', hasjack}; if exist('powindx', 'var'), optarg = cat(2, optarg, {'powindx', powindx}); end [datout, varout, nrpt] = ft_connectivity_psi(data.(inparam), optarg{:}); case 'powcorr_ortho' % Joerg Hipp's power correlation method optarg = {'refindx', cfg.refindx, 'tapvec', data.cumtapcnt}; if isfield(data, 'mom') % this is expected to be a single frequency %dat = cat(2, data.mom{data.inside}).'; % HACK dimord = getdimord(data, 'mom'); dimtok = tokenize(dimord, '_'); posdim = find(strcmp(dimtok,'{pos}')); posdim = 4; % we concatenate across positions... rptdim = find(~cellfun('isempty',strfind(dimtok,'rpt'))); rptdim = rptdim-1; % the posdim has to be taken into account... dat = cat(4, data.mom{data.inside}); dat = permute(dat,[posdim rptdim setdiff(1:ndims(dat),[posdim rptdim])]); datout = ft_connectivity_powcorr_ortho(dat, optarg{:}); elseif strcmp(data.dimord, 'rpttap_chan_freq') % loop over all frequencies [nrpttap, nchan, nfreq] = size(data.fourierspctrm); datout = cell(1, nfreq); for i=1:length(data.freq) dat = reshape(data.fourierspctrm(:,:,i)', nrpttap, nchan).'; datout{i} = ft_connectivity_powcorr_ortho(dat, optarg{:}); end datout = cat(3, datout{:}); % HACK otherwise I don't know how to inform the code further down about the dimord data.dimord = 'rpttap_chan_chan_freq'; else error('unsupported data representation'); end varout = []; nrpt = numel(data.cumtapcnt); case 'mi' % mutual information using the information breakdown toolbox % presence of the toolbox is checked in the low-level function if ~strcmp(dtype, 'raw') && (numel(cfg.mi.lags)>1 || cfg.mi.lags~=0), error('computation of lagged mutual information is only possible with ''raw'' data in the input'); end switch dtype case 'raw' % ensure the lags to be in samples, not in seconds. cfg.mi.lags = round(cfg.mi.lags.*data.fsample); dat = catnan(data.trial, max(abs(cfg.mi.lags))); if ischar(cfg.refindx) && strcmp(cfg.refindx, 'all') outdimord = 'chan_chan'; elseif numel(cfg.refindx)==1, outdimord = 'chan'; else error('at present cfg.refindx should be either ''all'', or scalar'); end if numel(cfg.mi.lags)>1 data.time = cfg.mi.lags./data.fsample; outdimord = [outdimord,'_time']; else data = rmfield(data, 'time'); end case 'timelock' dat = data.(inparam); dat = reshape(permute(dat, [2 3 1]), [size(dat, 2) size(dat, 1)*size(dat, 3)]); data = rmfield(data, 'time'); if ischar(cfg.refindx) && strcmp(cfg.refindx, 'all') outdimord = 'chan_chan'; elseif numel(cfg.refindx)==1, outdimord = 'chan'; else error('at present cfg.refindx should be either ''all'', or scalar'); end %data.dimord = 'chan_chan'; case 'freq' error('not yet implemented'); case 'source' % for the time being work with mom % dat = cat(2, data.mom{data.inside}).'; dat = cat(1, data.mom{data.inside}); % dat = abs(dat); end optarg = {'numbin', cfg.mi.numbin, 'lags', cfg.mi.lags, 'refindx', cfg.refindx}; [datout] = ft_connectivity_mutualinformation(dat, optarg{:}); varout = []; nrpt = []; case 'corr' % pearson's correlation coefficient optarg = {'dimord', getdimord(data, inparam), 'feedback', cfg.feedback, 'hasjack', hasjack}; if ~isempty(cfg.pchanindx), optarg = cat(2, optarg, {'pchanindx', cfg.pchanindx, 'allchanindx', cfg.allchanindx}); end [datout, varout, nrpt] = ft_connectivity_corr(data.(inparam), optarg{:}); case 'xcorr' % cross-correlation function error('method %s is not yet implemented', cfg.method); case 'spearman' % spearman's rank correlation error('method %s is not yet implemented', cfg.method); case 'di' % directionality index error('method %s is not yet implemented', cfg.method); otherwise error('unknown method %s', cfg.method); end % switch method % remove the auto combinations if necessary -> FIXME this is granger specific and thus could move to ft_connectivity_granger if (strcmp(cfg.method, 'granger') || strcmp(cfg.method, 'instantaneous_causality') || strcmp(cfg.method, 'total_interdependence')) && isfield(cfg, 'granger') && isfield(cfg.granger, 'sfmethod') && strcmp(cfg.granger.sfmethod, 'bivariate'), % remove the auto-combinations based on the order in the data switch dtype case {'freq' 'freqmvar'} keepchn = 1:size(datout, 1); keepchn = mod(keepchn, 4)==2 | mod(keepchn, 4)==3; datout = datout(keepchn, :, :, :, :); if ~isempty(varout), varout = varout(keepchn, :, :, :, :); end data.labelcmb = data.labelcmb(keepchn, :); case 'source' % not yet implemented end end if exist('powindx', 'var') && ~isempty(powindx), % based on powindx switch dtype case {'freq' 'freqmvar'} if isfield(data, 'labelcmb') && ~isstruct(powindx), keepchn = powindx(:, 1) ~= powindx(:, 2); datout = datout(keepchn, :, :, :, :); if ~isempty(varout), if all(size(varout)==size(nrpt)) nrpt = nrpt(keepchn, :, :, :, :); end varout = varout(keepchn, :, :, :, :); end data.labelcmb = data.labelcmb(keepchn, :); end case 'source' nvox = size(unique(data.pos(:, 1:3), 'rows'), 1); ncmb = size(data.pos, 1)/nvox-1; remove = (powindx(:, 1) == powindx(:, 2)) & ((1:size(powindx, 1))' > nvox*ncmb); keepchn = ~remove; datout = datout(keepchn, :, :, :, :); if ~isempty(varout), varout = varout(keepchn, :, :, :, :); end inside = false(zeros(1, size(data.pos, 1))); inside(data.inside) = true; inside = inside(keepchn); data.inside = find(inside)'; data.outside = find(inside==0)'; data.pos = data.pos(keepchn, :); end % switch dtype end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % create the output structure %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch dtype case {'freq' 'freqmvar'}, stat = []; if isfield(data, 'label'), stat.label = data.label; end if isfield(data, 'labelcmb'), stat.labelcmb = data.labelcmb; % ensure the correct dimord in case the input was 'powandcsd' data.dimord = strrep(data.dimord, 'chan_', 'chancmb_'); end tok = tokenize(data.dimord, '_'); dimord = ''; for k = 1:numel(tok) if isempty(strfind(tok{k}, 'rpt')) dimord = [dimord, '_', tok{k}]; end end stat.dimord = dimord(2:end); stat.(outparam) = datout; if ~isempty(varout), stat.([outparam, 'sem']) = (varout./nrpt).^0.5; end case 'timelock' stat = []; if isfield(data, 'label'), stat.label = data.label; end if isfield(data, 'labelcmb'), stat.labelcmb = data.labelcmb; end % deal with the dimord if exist('outdimord', 'var'), stat.dimord = outdimord; else % guess tok = tokenize(getdimord(data, inparam), '_'); dimord = ''; for k = 1:numel(tok) if isempty(strfind(tok{k}, 'rpt')) dimord = [dimord, '_', tok{k}]; end end stat.dimord = dimord(2:end); end stat.(outparam) = datout; if ~isempty(varout), stat.([outparam, 'sem']) = (varout./nrpt).^0.5; end case 'source' stat = keepfields(data, {'pos', 'dim', 'transform', 'inside', 'outside'}); stat.(outparam) = datout; if ~isempty(varout), stat.([outparam, 'sem']) = (varout/nrpt).^0.5; end case 'raw' stat = []; stat.label = data.label; stat.(outparam) = datout; if ~isempty(varout), stat.([outparam, 'sem']) = (varout/nrpt).^0.5; end if exist('outdimord', 'var'), stat.dimord = outdimord; end end % switch dtype if isfield(stat, 'dimord') dimtok = tokenize(stat.dimord, '_'); % these dimensions in the output data must come from the input data if any(strcmp(dimtok, 'time')), stat.time = data.time; end if any(strcmp(dimtok, 'freq')), stat.freq = data.freq; end else % just copy them over, alhtough we don't know for sure whether they are needed in the output if isfield(data, 'freq'), stat.freq = data.freq; end if isfield(data, 'time'), stat.time = data.time; end end if isfield(data, 'grad'), stat.grad = data.grad; end if isfield(data, 'elec'), stat.elec = data.elec; end if exist('dof', 'var'), stat.dof = dof; end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous data ft_postamble provenance stat ft_postamble history stat ft_postamble savevar stat %------------------------------------------------------------------------------- %subfunction to concatenate data with nans in between, needed for %time-shifted mi function [datamatrix] = catnan(datacells, nnans) nchan = size(datacells{1}, 1); nsmp = cellfun('size',datacells,2); nrpt = numel(datacells); %---initialize datamatrix = nan(nchan, sum(nsmp) + nnans*(nrpt+1)); %---fill the matrix for k = 1:nrpt if k==1, begsmp = 1+nnans; endsmp = nsmp(1)+nnans; else begsmp = k*nnans + sum(nsmp(1:(k-1))) + 1; endsmp = k*nnans + sum(nsmp(1:k)); end datamatrix(:,begsmp:endsmp) = datacells{k}; end
github
lcnbeapp/beapp-master
ft_defaults.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_defaults.m
13,356
utf_8
0fc0a3d3c7e67d69d12f3fb15f856bc1
function ft_defaults % FT_DEFAULTS (ending with "s") sets some general settings in the global variable % ft_default (without the "s") and takes care of the required path settings. This % function is called at the begin of all FieldTrip functions. % % The configuration defaults are stored in the global "ft_default" structure. % The ft_checkconfig function that is called by many FieldTrip functions will % merge this global ft_default structure with the cfg ctructure that you pass to % the FieldTrip function that you are calling. % % The global options and their default values are % ft_default.trackdatainfo = string, can be 'yes' or 'no' (default = 'no') % ft_default.trackconfig = string, can be 'cleanup', 'report', 'off' (default = 'off') % ft_default.showcallinfo = string, can be 'yes' or 'no' (default = 'yes') % ft_default.checkconfig = string, can be 'pedantic', 'loose', 'silent' (default = 'loose') % ft_default.checksize = number in bytes, can be inf (default = 1e5) % ft_default.outputfilepresent = string, can be 'keep', 'overwrite', 'error' (default = 'overwrite') % ft_default.debug = string, can be 'display', 'displayonerror', 'displayonsuccess', 'save', 'saveonerror', saveonsuccess' or 'no' (default = 'no') % ft_default.trackusage = false, or string with salt for one-way encryption of identifying information (by default this is enabled and an automatic salt is created) % % See also FT_HASTOOLBOX, FT_CHECKCONFIG % undocumented options % ft_default.siunits = 'yes' or 'no' % Copyright (C) 2009-2016, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ global ft_default persistent initialized if isempty(initialized) initialized = false; end % locate the file that contains the persistent FieldTrip preferences fieldtripprefs = fullfile(prefdir, 'fieldtripprefs.mat'); if exist(fieldtripprefs, 'file') prefs = load(fieldtripprefs); % the file contains multiple fields ft_default = mergeconfig(ft_default, prefs); end % Set the defaults in a global variable, ft_checkconfig will copy these over into the local configuration. % NOTE ft_getopt might not be available on the path at this moment and can therefore not yet be used. % NOTE all options here should be explicitly listed as allowed in ft_checkconfig if ~isfield(ft_default, 'trackconfig'), ft_default.trackconfig = 'off'; end % cleanup, report, off if ~isfield(ft_default, 'checkconfig'), ft_default.checkconfig = 'loose'; end % pedantic, loose, silent if ~isfield(ft_default, 'checksize'), ft_default.checksize = 1e5; end % number in bytes, can be inf if ~isfield(ft_default, 'showcallinfo'), ft_default.showcallinfo = 'yes'; end % yes or no, this is used in ft_pre/postamble_provenance if ~isfield(ft_default, 'debug'), ft_default.debug = 'no'; end % no, save, saveonerror, display, displayonerror, this is used in ft_pre/postamble_debug if ~isfield(ft_default, 'outputfilepresent'), ft_default.outputfilepresent = 'overwrite'; end % can be keep, overwrite, error % these options allow to disable parts of the provenance if ~isfield(ft_default, 'trackcallinfo'), ft_default.trackcallinfo = 'yes'; end % yes or no if ~isfield(ft_default, 'trackdatainfo'), ft_default.trackdatainfo = 'no'; end % yes or no % Check whether this ft_defaults function has already been executed. Note that we % should not use ft_default itself directly, because the user might have set stuff % in that struct already prior to ft_defaults being called for the first time. if initialized && exist('ft_hastoolbox', 'file') return; end % Ensure that the path containing ft_defaults is on the path. % This allows people to do "cd path_to_fieldtrip; ft_defaults" ftPath = fileparts(mfilename('fullpath')); % get the full path to this function, strip away 'ft_defaults' ftPath = strrep(ftPath, '\', '\\'); if isempty(regexp(path, [ftPath pathsep '|' ftPath '$'], 'once')) warning('FieldTrip is not yet on your MATLAB path, adding %s', strrep(ftPath, '\\', '\')); addpath(ftPath); end if ~isdeployed if isempty(which('ft_hastoolbox')) % the fieldtrip/utilities directory contains the ft_hastoolbox and ft_warning % functions, which are required for the remainder of this script addpath(fullfile(fileparts(which('ft_defaults')), 'utilities')); end % Some people mess up their path settings and then have % different versions of certain toolboxes on the path. % The following will issue a warning checkMultipleToolbox('FieldTrip', 'ft_defaults.m'); checkMultipleToolbox('spm', 'spm.m'); checkMultipleToolbox('mne', 'fiff_copy_tree.m'); checkMultipleToolbox('eeglab', 'eeglab2fieldtrip.m'); checkMultipleToolbox('dipoli', 'write_tri.m'); checkMultipleToolbox('eeprobe', 'read_eep_avr.mexa64'); checkMultipleToolbox('yokogawa', 'GetMeg160ChannelInfoM.p'); checkMultipleToolbox('simbio', 'sb_compile_vista.m'); checkMultipleToolbox('fns', 'fns_region_read.m'); checkMultipleToolbox('bemcp', 'bem_Cii_cst.mexa64'); checkMultipleToolbox('bci2000', 'load_bcidat.m'); checkMultipleToolbox('openmeeg', 'openmeeg_helper.m'); checkMultipleToolbox('freesurfer', 'vox2ras_ksolve.m'); checkMultipleToolbox('fastica', 'fastica.m'); checkMultipleToolbox('besa', 'readBESAmul.m'); checkMultipleToolbox('neuroshare', 'ns_GetAnalogData.m'); checkMultipleToolbox('ctf', 'setCTFDataBalance.m'); checkMultipleToolbox('afni', 'WriteBrikHEAD.m'); checkMultipleToolbox('gifti', '@gifti/display.m'); checkMultipleToolbox('sqdproject', 'sqdread.m'); checkMultipleToolbox('xml4mat', 'xml2mat.m'); checkMultipleToolbox('cca', 'ccabss.m'); checkMultipleToolbox('bsmart', 'armorf.m'); checkMultipleToolbox('iso2mesh', 'iso2meshver.m'); checkMultipleToolbox('bct', 'degrees_und.m'); checkMultipleToolbox('yokogawa_meg_reader', 'getYkgwHdrEvent.p'); checkMultipleToolbox('biosig', 'sopen.m'); checkMultipleToolbox('icasso', 'icassoEst.m'); try % external/signal contains alternative implementations of some signal processing functions addpath(fullfile(fileparts(which('ft_defaults')), 'external', 'signal')); end try % some alternative implementations of statistics functions if ~ft_platform_supports('stats') addpath(fullfile(fileparts(which('ft_defaults')), 'external', 'stats')); end end try % external/images contains alternative implementations of some image processing functions addpath(fullfile(fileparts(which('ft_defaults')), 'external', 'images')); end try % this directory contains various functions that were obtained from elsewere, e.g. MATLAB file exchange ft_hastoolbox('fileexchange', 3, 1); % not required end try % this directory contains the backward compatibility wrappers for the ft_xxx function name change ft_hastoolbox('compat', 3, 1); % not required end try % these directories deal with compatibility with older MATLAB versions if ft_platform_supports('matlabversion', -inf, '2008a'), ft_hastoolbox('compat/matlablt2008b', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2008b'), ft_hastoolbox('compat/matlablt2009a', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2009a'), ft_hastoolbox('compat/matlablt2009b', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2009b'), ft_hastoolbox('compat/matlablt2010a', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2010a'), ft_hastoolbox('compat/matlablt2010b', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2010b'), ft_hastoolbox('compat/matlablt2011a', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2011a'), ft_hastoolbox('compat/matlablt2011b', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2011b'), ft_hastoolbox('compat/matlablt2012a', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2012a'), ft_hastoolbox('compat/matlablt2012b', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2012b'), ft_hastoolbox('compat/matlablt2013a', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2013a'), ft_hastoolbox('compat/matlablt2013b', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2013b'), ft_hastoolbox('compat/matlablt2014a', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2014a'), ft_hastoolbox('compat/matlablt2014b', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2014d'), ft_hastoolbox('compat/matlablt2015a', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2015a'), ft_hastoolbox('compat/matlablt2015b', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2015b'), ft_hastoolbox('compat/matlablt2016a', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2016a'), ft_hastoolbox('compat/matlablt2016b', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2016b'), ft_hastoolbox('compat/matlablt2017a', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2017a'), ft_hastoolbox('compat/matlablt2017b', 3, 1); end if ft_platform_supports('matlabversion', -inf, '2017b'), ft_hastoolbox('compat/matlablt2018a', 3, 1); end end try % these contains template layouts, neighbour structures, MRIs and cortical meshes ft_hastoolbox('template/layout', 1, 1); ft_hastoolbox('template/anatomy', 1, 1); ft_hastoolbox('template/headmodel', 1, 1); ft_hastoolbox('template/electrode', 1, 1); ft_hastoolbox('template/neighbours', 1, 1); ft_hastoolbox('template/sourcemodel', 1, 1); end try % this is used in ft_statistics ft_hastoolbox('statfun', 1, 1); end try % this is used in ft_definetrial ft_hastoolbox('trialfun', 1, 1); end try % this contains the low-level reading functions ft_hastoolbox('fileio', 1, 1); end try % this is for filtering etc. on time-series data ft_hastoolbox('preproc', 1, 1); end try % this contains forward models for the EEG and MEG volume conductor ft_hastoolbox('forward', 1, 1); end try % this contains inverse source estimation methods ft_hastoolbox('inverse', 1, 1); end try % this contains intermediate-level plotting functions, e.g. multiplots and 3-d objects ft_hastoolbox('plotting', 1, 1); end try % this contains intermediate-level functions for spectral analysis ft_hastoolbox('specest', 1, 1); end try % this contains the functions to compute connectivity metrics ft_hastoolbox('connectivity', 1, 1); end try % this contains the functions for spike and spike-field analysis ft_hastoolbox('spike', 1, 1); end try % this contains user contributed functions ft_hastoolbox('contrib/misc', 1, 1); end try % this contains specific code and examples for realtime processing ft_hastoolbox('realtime/example', 3, 1); % not required ft_hastoolbox('realtime/online_mri', 3, 1); % not required ft_hastoolbox('realtime/online_meg', 3, 1); % not required ft_hastoolbox('realtime/online_eeg', 3, 1); % not required end end % track the usage of this function, this only happens once at startup ft_trackusage('startup'); % remember that the function has executed in a persistent variable initialized = true; end % function ft_default %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function checkMultipleToolbox(toolbox, keyfile) if ~ft_platform_supports('which-all') return; end list = which(keyfile, '-all'); if length(list)>1 [ws, warned] = ft_warning(sprintf('Multiple versions of %s on your path will confuse FieldTrip', toolbox)); if warned % only throw the warning once for i=1:length(list) warning('one version of %s is found here: %s', toolbox, list{i}); end end ft_warning('You probably used addpath(genpath(''path_to_fieldtrip'')), this can lead to unexpected behaviour. See http://www.fieldtriptoolbox.org/faq/should_i_add_fieldtrip_with_all_subdirectories_to_my_matlab_path'); end end % function checkMultipleToolbox
github
lcnbeapp/beapp-master
ft_prepare_neighbours.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_prepare_neighbours.m
13,251
utf_8
07eb375aeb41eb43bd565f6470060f88
function [neighbours, cfg] = ft_prepare_neighbours(cfg, data) % FT_PREPARE_NEIGHBOURS finds the neighbours of the channels based on three % different methods. Using the 'distance'-method, prepare_neighbours is % based on a minimum neighbourhood distance (in cfg.neighbourdist). The % 'triangulation'-method calculates a triangulation based on a % two-dimenstional projection of the sensor position. The 'template'-method % loads a default template for the given data type. prepare_neighbours % should be verified using cfg.feedback ='yes' or by calling % ft_neighbourplot % % The positions of the channel are specified in a gradiometer or electrode configuration or % from a layout. The sensor configuration can be passed into this function in three ways: % (1) in a configuration field, % (2) in a file whose name is passed in a configuration field, and that can be imported using FT_READ_SENS, or % (3) in a data field. % % Use as % neighbours = ft_prepare_neighbours(cfg, data) % % The configuration can contain % cfg.method = 'distance', 'triangulation' or 'template' % cfg.neighbourdist = number, maximum distance between neighbouring sensors (only for 'distance') % cfg.template = name of the template file, e.g. CTF275_neighb.mat % cfg.layout = filename of the layout, see FT_PREPARE_LAYOUT % cfg.channel = channels for which neighbours should be found % cfg.feedback = 'yes' or 'no' (default = 'no') % % The EEG or MEG sensor positions can be present in the data or can be specified as % cfg.elec = structure with electrode positions, see FT_DATATYPE_SENS % cfg.grad = structure with gradiometer definition, see FT_DATATYPE_SENS % cfg.elecfile = name of file containing the electrode positions, see FT_READ_SENS % cfg.gradfile = name of file containing the gradiometer definition, see FT_READ_SENS % % The output is an array of structures with the "neighbours" which is % structured like this: % neighbours(1).label = 'Fz'; % neighbours(1).neighblabel = {'Cz', 'F3', 'F3A', 'FzA', 'F4A', 'F4'}; % neighbours(2).label = 'Cz'; % neighbours(2).neighblabel = {'Fz', 'F4', 'RT', 'RTP', 'P4', 'Pz', 'P3', 'LTP', 'LT', 'F3'}; % neighbours(3).label = 'Pz'; % neighbours(3).neighblabel = {'Cz', 'P4', 'P4P', 'Oz', 'P3P', 'P3'}; % etc. % Note that a channel is not considered to be a neighbour of itself. % % See also FT_NEIGHBOURPLOT % Copyright (C) 2006-2011, Eric Maris, Jorn M. Horschig, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar data ft_preamble provenance data ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'required', {'method'}); % set the defaults cfg.feedback = ft_getopt(cfg, 'feedback', 'no'); cfg.channel = ft_getopt(cfg, 'channel', 'all'); % the data can be passed as input arguments or can be read from disk hasdata = exist('data', 'var'); if hasdata % check if the input data is valid for this function data = ft_checkdata(data); end if strcmp(cfg.method, 'template') neighbours = []; fprintf('Trying to load sensor neighbours from a template\n'); % determine from where to load the neighbour template if ~isfield(cfg, 'template') % if data has been put in, try to estimate the sensor type if hasdata fprintf('Estimating sensor type of data to determine the layout filename\n'); senstype = ft_senstype(data.label); fprintf('Data is of sensor type ''%s''\n', senstype); if ~exist([senstype '_neighb.mat'], 'file') if exist([senstype '.lay'], 'file') cfg.layout = [senstype '.lay']; else fprintf('Name of sensor type does not match name of layout- and template-file\n'); end else cfg.template = [senstype '_neighb.mat']; end end end % if that failed if ~isfield(cfg, 'template') % check whether a layout can be used if ~isfield(cfg, 'layout') % error if that fails as well error('You need to define a template or layout or give data as an input argument when ft_prepare_neighbours is called with cfg.method=''template'''); end fprintf('Using the 2-D layout filename to determine the template filename\n'); cfg.template = [strtok(cfg.layout, '.') '_neighb.mat']; end % adjust filename if ~exist(cfg.template, 'file') cfg.template = lower(cfg.template); end % add necessary extensions if numel(cfg.template) < 4 || ~isequal(cfg.template(end-3:end), '.mat') if numel(cfg.template) < 7 || ~isequal(cfg.template(end-6:end), '_neighb') cfg.template = [cfg.template, '_neighb']; end cfg.template = [cfg.template, '.mat']; end % check for existence if ~exist(cfg.template, 'file') error('Template file could not be found - please check spelling or see http://www.fieldtriptoolbox.org/faq/how_can_i_define_my_own_neighbourhood_template (please consider sharing it with others via the FT mailing list)'); end load(cfg.template); fprintf('Successfully loaded neighbour structure from %s\n', cfg.template); else % get the the grad or elec if not present in the data if hasdata sens = ft_fetch_sens(cfg, data); else sens = ft_fetch_sens(cfg); end if strcmp(ft_senstype(sens), 'neuromag306') warning('Neuromag306 system detected - be aware of different sensor types, see http://www.fieldtriptoolbox.org/faq/why_are_there_multiple_neighbour_templates_for_the_neuromag306_system'); end chanpos = sens.chanpos; label = sens.label; if nargin > 1 % remove channels that are not in data [dataidx, sensidx] = match_str(data.label, label); chanpos = chanpos(sensidx, :); label = label(sensidx); end if ~strcmp(cfg.channel, 'all') desired = ft_channelselection(cfg.channel, label); [sensidx] = match_str(label, desired); chanpos = chanpos(sensidx, :); label = label(sensidx); end switch lower(cfg.method) case 'distance' % use a smart default for the distance if ~isfield(cfg, 'neighbourdist') sens = ft_checkdata(sens, 'hasunit', 'yes'); if isfield(sens, 'unit') && strcmp(sens.unit, 'm') cfg.neighbourdist = 0.04; elseif isfield(sens, 'unit') && strcmp(sens.unit, 'dm') cfg.neighbourdist = 0.4; elseif isfield(sens, 'unit') && strcmp(sens.unit, 'cm') cfg.neighbourdist = 4; elseif isfield(sens, 'unit') && strcmp(sens.unit, 'mm') cfg.neighbourdist = 40; else % don't provide a default in case the dimensions of the sensor array are unknown error('Sensor distance is measured in an unknown unit type'); end fprintf('using a distance threshold of %g\n', cfg.neighbourdist); end neighbours = compneighbstructfromgradelec(chanpos, label, cfg.neighbourdist); case {'triangulation', 'tri'} % the latter for reasons of simplicity if size(chanpos, 2)==2 || all(chanpos(:,3)==0) % the sensor positions are already on a 2D plane prj = chanpos(:,1:2); else % project sensor on a 2D plane prj = elproj(chanpos); end % make a 2d delaunay triangulation of the projected points tri = delaunay(prj(:,1), prj(:,2)); tri_x = delaunay(prj(:,1)./2, prj(:,2)); tri_y = delaunay(prj(:,1), prj(:,2)./2); tri = [tri; tri_x; tri_y]; neighbours = compneighbstructfromtri(chanpos, label, tri); otherwise error('Method ''%s'' not known', cfg.method); end end % removed as from Nov 09 2011 - hope there are no problems with this % if iscell(neighbours) % warning('Neighbourstructure is in old format - converting to structure array'); % neighbours = fixneighbours(neighbours); % end % only select those channels that are in the data neighb_chans = {neighbours(:).label}; if isfield(cfg, 'channel') && ~isempty(cfg.channel) if hasdata desired = ft_channelselection(cfg.channel, data.label); else desired = ft_channelselection(cfg.channel, neighb_chans); end elseif (hasdata) desired = data.label; else desired = neighb_chans; end % in any case remove SCALE and COMNT desired = ft_channelselection({'all', '-SCALE', '-COMNT'}, desired); neighb_idx = ismember(neighb_chans, desired); neighbours = neighbours(neighb_idx); k = 0; for i=1:length(neighbours) if isempty(neighbours(i).neighblabel) warning('FIELDTRIP:NoNeighboursFound', 'no neighbours found for %s\n', neighbours(i).label); % JMH: I removed this in Feb 2013 - this is handled above now % note however that in case of using a template, this function behaves % differently now (neighbourschans can still be channels not in % cfg.channel) %else % only selected desired channels % neighbours(i).neighblabel = neighbours(i).neighblabel(ismember(neighbours(i).neighblabel, desired)); end k = k + length(neighbours(i).neighblabel); end if k==0 error('No neighbours were found!'); end fprintf('there are on average %.1f neighbours per channel\n', k/length(neighbours)); if strcmp(cfg.feedback, 'yes') % give some graphical feedback cfg.neighbours = neighbours; if hasdata ft_neighbourplot(cfg, data); else ft_neighbourplot(cfg); end end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous data ft_postamble provenance neighbours ft_postamble history neighbours %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that compute the neighbourhood geometry from the % gradiometer/electrode positions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [neighbours] = compneighbstructfromgradelec(chanpos, label, neighbourdist) nsensors = length(label); % compute the distance between all sensors dist = zeros(nsensors,nsensors); for i=1:nsensors dist(i,:) = sqrt(sum((chanpos(1:nsensors,:) - repmat(chanpos(i,:), nsensors, 1)).^2,2))'; end; % find the neighbouring electrodes based on distance % later we have to restrict the neighbouring electrodes to those actually selected in the dataset channeighbstructmat = (dist<neighbourdist); % electrode istelf is not a neighbour channeighbstructmat = (channeighbstructmat .* ~eye(nsensors)); % construct a structured cell array with all neighbours neighbours=struct; for i=1:nsensors neighbours(i).label = label{i}; neighbours(i).neighblabel = label(find(channeighbstructmat(i,:))); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that computes the neighbourhood geometry from the % triangulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [neighbours] = compneighbstructfromtri(chanpos, label, tri) nsensors = length(label); channeighbstructmat = zeros(nsensors,nsensors); % mark neighbours according to triangulation for i=1:size(tri, 1) channeighbstructmat(tri(i, 1), tri(i, 2)) = 1; channeighbstructmat(tri(i, 1), tri(i, 3)) = 1; channeighbstructmat(tri(i, 2), tri(i, 1)) = 1; channeighbstructmat(tri(i, 3), tri(i, 1)) = 1; channeighbstructmat(tri(i, 2), tri(i, 3)) = 1; channeighbstructmat(tri(i, 3), tri(i, 2)) = 1; end % construct a structured cell array with all neighbours neighbours = struct; alldist = []; for i=1:nsensors neighbours(i).label = label{i}; neighbidx = find(channeighbstructmat(i,:)); neighbours(i).dist = sqrt(sum((repmat(chanpos(i, :), numel(neighbidx), 1) - chanpos(neighbidx, :)).^2, 2)); alldist = [alldist; neighbours(i).dist]; neighbours(i).neighblabel = label(neighbidx); end % remove neighbouring channels that are too far away (imporntant e.g. in % case of missing sensors) neighbdist = mean(alldist)+3*std(alldist); for i=1:nsensors idx = neighbours(i).dist > neighbdist; neighbours(i).dist(idx) = []; neighbours(i).neighblabel(idx) = []; end neighbours = rmfield(neighbours, 'dist');
github
lcnbeapp/beapp-master
ft_crossfrequencyanalysis.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_crossfrequencyanalysis.m
9,389
utf_8
64b924a3625f4df0dcd5baaae904a6cf
function crossfreq = ft_crossfrequencyanalysis(cfg,freqlow,freqhigh) % FT_CROSSFREQUENCYANALYSIS performs cross-frequency analysis using various algorithms % % Use as % crossfreq = ft_crossfrequencyanalysis(cfg, freqlo, freqhi) % where freq is frequency decomposed data structure as obtained from FT_FREQANALYSIS % and cfg is a configuration structure that should contain % % cfg.freqlow scalar or vector, selection of frequencies for the low frequency data % cfg.freqhigh scalar or vector, selection of frequencies for the high frequency data % cfg.chanlow selection of channels for the low frequency, see FT_CHANNELSELECTION % cfg.chanhigh selection of channels for the high frequency, see FT_CHANNELSELECTION % cfg.method 'plv' - phase locking value % 'mvl' - mean vector length % 'mi' - modulation index % cfg.keeptrials string, can be 'yes' or 'no' % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % cfg.outputfile = ... % If you specify one of these (or both) the input data will be read from a *.mat % file on disk and/or the output data will be written to a *.mat file. These mat % files should contain only a single variable, corresponding with the % input/output structure. % % See also FT_FREQANALYSIS % Copyright (C) 2014, Donders Centre for Cognitive Neuroimaging % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar freqlow freqhigh ft_preamble provenance freqlow freqhi ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort % do not continue function execution in case the outputfile is present and the user indicated to keep it return end % ensure that the input data is valid for this function, this will also do % backward-compatibility conversions of old data that for example was % read from an old *.mat file freqlow = ft_checkdata(freqlow, 'datatype', 'freq', 'feedback', 'yes'); freqhigh = ft_checkdata(freqhigh, 'datatype', 'freq', 'feedback', 'yes'); cfg.chanlow = ft_getopt(cfg, 'chanlow', 'all'); cfg.chanhigh = ft_getopt(cfg, 'chanhigh', 'all'); cfg.freqlow = ft_getopt(cfg, 'freqlow'); cfg.freqhigh = ft_getopt(cfg, 'freqhigh'); cfg.keeptrials = ft_getopt(cfg, 'keeptrials'); % make selection of frequencies and channels tmpcfg = []; tmpcfg.channel = cfg.chanlow; tmpcfg.frequency = cfg.freqlow; freqlow = ft_selectdata(tmpcfg, freqlow); [tmpcfg, freqlow] = rollback_provenance(cfg, freqlow); try, cfg.chanlow = tmpcfg.channel; end try, cfg.freqlow = tmpcfg.frequency; end tmpcfg = []; tmpcfg.channel = cfg.chanhigh; tmpcfg.foi = cfg.freqhigh; freqhigh = ft_selectdata(tmpcfg, freqhigh); [tmpcfg, freqhigh] = rollback_provenance(cfg, freqhigh); try, cfg.chanhigh = tmpcfg.channel; end try, cfg.freqhigh = tmpcfg.frequency; end LF = freqlow.freq; HF = freqhigh.freq; ntrial = size(freqlow.fourierspctrm,1); % FIXME the dimord might be different nchan = size(freqlow.fourierspctrm,2); % FIXME the dimord might be different %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % prepare the data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch cfg.method case 'plv' % phase locking value plvdatas = zeros(ntrial,nchan,numel(LF),numel(HF)) ; for i =1:nchan chandataLF = freqlow.fourierspctrm(:,i,:,:); chandataHF = freqhigh.fourierspctrm(:,i,:,:); for j = 1:ntrial plvdatas(j,i,:,:) = data2plv(squeeze(chandataLF(j,:,:,:)),squeeze(chandataHF(j,:,:,:))); end end cfcdata = plvdatas; case 'mvl' % mean vector length mvldatas = zeros(ntrial,nchan,numel(LF),numel(HF)); for i =1:nchan chandataLF = freqlow.fourierspctrm(:,i,:,:); chandataHF = freqhigh.fourierspctrm(:,i,:,:); for j = 1:ntrial mvldatas(j,i,:,:) = data2mvl(squeeze(chandataLF(j,:,:,:)),squeeze(chandataHF(j,:,:,:))); end end cfcdata = mvldatas; case 'mi' % modulation index nbin = 20; % number of phase bin pacdatas = zeros(ntrial,nchan,numel(LF),numel(HF),nbin) ; for i =1:nchan chandataLF = freqlow.fourierspctrm(:,i,:,:); chandataHF = freqhigh.fourierspctrm(:,i,:,:); for j = 1:ntrial pacdatas(j,i,:,:,:) = data2pac(squeeze(chandataLF(j,:,:,:)),squeeze(chandataHF(j,:,:,:)),nbin); end end cfcdata = pacdatas; end % switch method for data preparation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % do the actual computation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch cfg.method case 'plv' if strcmp(cfg.keeptrials,'no') crsspctrm = squeeze(abs(mean(cfcdata,1))); dimord = 'chan_freqlow_freqhigh' ; else crsspctrm = abs(cfcdata); dimord = 'rpt_chan_freqlow_freqhigh' ; end case 'mvl' if strcmp(cfg.keeptrials,'no') crsspctrm = squeeze(abs(mean(cfcdata,1))); dimord = 'chan_freqlow_freqhigh' ; else crsspctrm = abs(cfcdata); dimord = 'rpt_chan_freqlow_freqhigh' ; end case 'mi' [ntrial,nchan,nlf,nhf,nbin] = size(cfcdata); if strcmp(cfg.keeptrials,'yes') dimord = 'rpt_chan_freqlow_freqhigh' ; crsspctrm = zeros(ntrial,nchan,nlf,nhf); for k =1:ntrial for n=1:nchan pac = squeeze(cfcdata(k,n,:,:,:)); Q =ones(nbin,1)/nbin; % uniform distribution mi = zeros(nlf,nhf); for i=1:nlf for j=1:nhf P = squeeze(pac(i,j,:))/ nansum(pac(i,j,:)); % normalized distribution % KL distance mi(i,j) = nansum(P.* (log2(P)-log2(Q)))/log2(pha); end end crsspctrm(k,n,:,:) = mi; end end else dimord = 'chan_freqlow_freqhigh' ; crsspctrm = zeros(nchan,nlf,nhf); cfcdatamean = squeeze(mean(cfcdata,1)); for k =1:nchan pac = squeeze(cfcdatamean(k,:,:,:)); Q =ones(nbin,1)/nbin; % uniform distribution mi = zeros(nlf,nhf); for i=1:nlf for j=1:nhf P = squeeze(pac(i,j,:))/ nansum(pac(i,j,:)); % normalized distribution % KL distance mi(i,j) = nansum(P.* (log2(P)-log2(Q)))/log2(nbin); end end crsspctrm(k,:,:) = mi; end end % if keeptrials end % switch method for actual computation crossfreq.crsspctrm = crsspctrm; crossfreq.dimord = dimord; crossfreq.freqlow = LF; crossfreq.freqhigh = HF; ft_postamble debug ft_postamble trackconfig ft_postamble previous freqlow freqhigh ft_postamble provenance crossfreq ft_postamble history crossfreq ft_postamble savevar crossfreq end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [plvdata] =data2plv(LFsigtemp,HFsigtemp) LFphas = angle(LFsigtemp); HFamp = abs(HFsigtemp); HFamp(isnan(HFamp(:))) = 0; % replace nan with 0 HFphas = angle(hilbert(HFamp'))'; plvdata = zeros(size(LFsigtemp,1),size(HFsigtemp,1)); % phase lokcing value for i = 1:size(LFsigtemp) for j = 1:size(HFsigtemp) plvdata(i,j) = nanmean(exp(1i*(LFphas(i,:)-HFphas(j,:)))); end end end % function function [mvldata] =data2mvl(LFsigtemp,HFsigtemp) % calculate mean vector length (complex value) per trial % mvldata dim: LF*HF LFphas = angle(LFsigtemp); HFamp = abs(HFsigtemp); mvldata = zeros(size(LFsigtemp,1),size(HFsigtemp,1)); % mean vector length for i = 1:size(LFsigtemp) for j = 1:size(HFsigtemp) mvldata(i,j) = nanmean(HFamp(j,:).*exp(1i*LFphas(i,:))); end end end % function function pacdata =data2pac(LFsigtemp,HFsigtemp,nbin) % calculate phase amplitude distribution per trial % pacdata dim: LF*HF*Phasebin pacdata = zeros(size(LFsigtemp,1),size(HFsigtemp,1),nbin); Ang = angle(LFsigtemp); Amp = abs(HFsigtemp); [~,bin] = histc(Ang, linspace(-pi,pi,nbin)); % binned low frequency phase binamp = zeros (size(HFsigtemp,1),nbin); % binned amplitude for i= 1:size(Ang,1) for k =1:nbin idx = bin(i,:)==k; binamp(:,k) = mean(Amp(:,idx),2); end pacdata(i,:,:) = binamp; end end % function
github
lcnbeapp/beapp-master
ft_conjunctionanalysis.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_conjunctionanalysis.m
8,875
utf_8
106b6a2753353fed3cf27ea9b1fb1da7
function [conjunction] = ft_conjunctionanalysis(cfg, varargin) % FT_CONJUNCTIONANALYSIS finds the minimum statistic common across two or % more contrasts, i.e. data following ft_xxxstatistics. Furthermore, it % finds the overlap of sensors/voxels that show statistically significant % results (a logical AND on the mask fields). % % Alternatively, it finds minimalistic mean power values in the % input datasets. Here, a type 'relative change' baselinecorrection % prior to conjunction is advised. % % Use as % [stat] = ft_conjunctionanalysis(cfg, stat1, stat2, .., statN) % % where the input data is the result from either FT_TIMELOCKSTATISTICS, % FT_FREQSTATISTICS, or FT_SOURCESTATISTICS % % No configuration options are yet implemented. % % See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS, FT_SOURCESTATISTICS % Copyright (C) 2010-2014, Arjen Stolk % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar varargin ft_preamble provenance varargin ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % input check ndatasets = length(varargin); if ndatasets<2 error('not enough input arguments; there should be at least two'); end % check if the input data is valid for this function for i = 1:ndatasets varargin{i} = ft_checkdata(varargin{i}, 'datatype', {'timelock', 'freq', 'source'}, 'feedback', 'yes'); end fprintf('performing conjunction analysis on %d input datasets \n', ndatasets); conjunction = []; % determine datatype isfreq = ft_datatype(varargin{1}, 'freq'); istimelock = ft_datatype(varargin{1}, 'timelock'); issource = ft_datatype(varargin{1}, 'source'); % conjunction loop, in case ndatasets > 2 for i = 1:ndatasets-1 % align input arguments for conjunction if isempty(conjunction) data1 = varargin{i}; data2 = varargin{i+1}; else data1 = conjunction; % use already conjunct output data2 = varargin{i+1}; end %% SOURCE DATA if issource if isfield(data1, 'stat') fprintf('minimum statistics on source level data \n'); % equal size input check if ~isequal(size(data1.stat), size(data2.stat)) error('the input arguments have different sizes'); end % prepare the output data structure conjunction = data1; if isfield(data1, 'posclusters') % remove cluster details fprintf('removing information about positive clusters\n'); conjunction = rmfield(conjunction, 'posclusters'); conjunction = rmfield(conjunction, 'posclusterslabelmat'); end if isfield(data1, 'negclusters') % remove cluster details fprintf('removing information about negative clusters\n'); conjunction = rmfield(conjunction, 'negclusters'); conjunction = rmfield(conjunction, 'negclusterslabelmat'); end fprintf('minimum statistics on stat fields \n'); conjunction.stat = minimumstatistics(data1.stat, data2.stat); if isfield(data1, 'prob') && isfield(data2, 'prob') % conjunction on probabilities fprintf('minimum statistics on prob fields \n'); conjunction.prob = maximumprobabilities(data1.prob, data2.prob); end if isfield(data1, 'mask') && isfield(data2, 'mask') % conjunction on mask parameters fprintf('logical AND on mask fields \n'); conjunction.mask = logicalAND(data1.mask, data2.mask); end elseif isfield(data1, 'avg') && isfield(data2, 'avg') % conjunction on mean power values fprintf('minimum statistics on mean voxel power \n'); % equal size input check if ~isequal(size(data1.avg.pow), size(data2.avg.pow)) error('the input arguments have different sizes'); end conjunction = data1; conjunction.avg.pow = minimumstatistics(data1.avg.pow, data2.avg.pow); elseif isfield(data1, 'trial') fprintf('please first compute the averages with ft_sourcedescriptives \n'); else fprintf('this source level data does not fit conjunction analysis \n'); end end % end of source level conjunction %% SENSOR DATA if isfreq || istimelock if isfield(data1, 'stat') % conjunction on t-values fprintf('minimum statistics on sensor level data \n'); % equal size input check if ~isequal(size(data1.stat), size(data2.stat)) error('the input arguments have different sizes'); end % prepare the output data structure conjunction = data1; if isfield(data1, 'posclusters') % remove cluster details fprintf('removing information about positive clusters\n'); conjunction = rmfield(conjunction, 'posclusters'); conjunction = rmfield(conjunction, 'posclusterslabelmat'); end if isfield(data1, 'negclusters') % remove cluster details fprintf('removing information about negative clusters\n'); conjunction = rmfield(conjunction, 'negclusters'); conjunction = rmfield(conjunction, 'negclusterslabelmat'); end fprintf('minimum statistics on stat fields \n'); conjunction.stat = minimumstatistics(data1.stat, data2.stat); if isfield(data1, 'prob') && isfield(data2, 'prob') % conjunction on probabilities fprintf('minimum statistics on prob fields \n'); conjunction.prob = maximumprobabilities(data1.prob, data2.prob); end if isfield(data1, 'mask') && isfield(data2, 'mask') % conjunction on mask parameters fprintf('logical AND on mask fields \n'); conjunction.mask = logicalAND(data1.mask, data2.mask); end elseif isfield(data1, 'powspctrm') && isfield(data2, 'powspctrm') % conjunction on mean power values fprintf('minimum statistics on mean sensor power \n'); % equal size input check if ~isequal(size(data1.powspctrm), size(data2.powspctrm)) error('the input arguments have different sizes'); end conjunction = data1; conjunction.powspctrm = minimumstatistics(data1.powspctrm, data2.powspctrm); elseif isfield(data1, 'avg') && isfield(data2, 'avg') % conjunction on mean signal amplitudes fprintf('minimum statistics on mean sensor amplitudes \n'); % equal size input check if ~isequal(size(data1.avg), size(data2.avg)) error('the input arguments have different sizes'); end conjunction = data1; conjunction.avg = minimumstatistics(data1.avg, data2.avg); elseif isfield(data1, 'trial') fprintf('please first compute the averages with ft_timelockdescriptives/ft_freqdescriptives \n'); else fprintf('this sensor level data does not fit conjunction analysis \n'); end end % end of sensor level conjunction clear data1; clear data2; end % end of conjunction loop %% UNIDENTIFIED DATA if istimelock == 0 && isfreq == 0 && issource == 0 fprintf('this data is not appropriate for conjunction analysis\n'); conjunction = []; end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous varargin ft_postamble provenance conjunction ft_postamble history conjunction ft_postamble savevar conjunction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [minstat] = minimumstatistics(variable1, variable2) minAbsT = min(abs(variable1), abs(variable2)); % minimum of the absolute values equalSign = (sign(variable1) == sign(variable2)); % 1 is signs are equal, 0 otherwise origSign = sign(variable1); % sign(varagin2) gives same result minstat = minAbsT.*equalSign.*origSign; function [maxprob] = maximumprobabilities(variable1, variable2) maxprob = max(variable1, variable2); % maximum of the probabilities function [logic] = logicalAND(variable1, variable2) logic = (variable1 & variable2); % compute logical AND
github
lcnbeapp/beapp-master
ft_sliceinterp.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_sliceinterp.m
18,635
utf_8
f2c5c3de8b6b941ac0dda303889261a2
function [outim] = ft_sliceinterp(cfg, ininterp) % FT_SLICEINTERP plots a 2D-montage of source reconstruction and anatomical MRI % after these have been interpolated onto the same grid. % % Use as % ft_sliceinterp(cfg, interp) % or % [rgbimage] = ft_sliceinterp(cfg, interp), rgbimage is the monatage image % % where interp is the output of sourceinterpolate and cfg is a structure % with any of the following fields: % % cfg.funparameter string with the functional parameter of interest (default = 'source') % cfg.maskparameter parameter used as opacity mask (default = 'none') % cfg.clipmin value or 'auto' (clipping of source data) % cfg.clipmax value or 'auto' (clipping of source data) % cfg.clipsym 'yes' or 'no' (default) symmetrical clipping % cfg.colormap colormap for source overlay (default is jet(128)) % cfg.colmin source value mapped to the lowest color (default = 'auto') % cfg.colmax source value mapped to the highest color (default = 'auto') % cfg.maskclipmin value or 'auto' (clipping of mask data) % cfg.maskclipmax value or 'auto' (clipping of mask data) % cfg.maskclipsym 'yes' or 'no' (default) symmetrical clipping % cfg.maskmap opacitymap for source overlay % (default is linspace(0,1,128)) % cfg.maskcolmin mask value mapped to the lowest opacity, i.e. % completely transparent (default ='auto') % cfg.maskcolmin mask value mapped to the highest opacity, i.e. % non-transparent (default = 'auto') % cfg.alpha value between 0 and 1 or 'adaptive' (default) % cfg.nslices integer value, default is 20 % cfg.dim integer value, default is 3 (dimension to slice) % cfg.spacemin 'auto' (default) or integer (first slice position) % cfg.spacemax 'auto' (default) or integer (last slice position) % cfg.resample integer value, default is 1 (for resolution reduction) % cfg.rotate number of ccw 90 deg slice rotations (default = 0) % cfg.title optional title (default is '') % cfg.whitebg 'yes' or 'no' (default = 'yes') % cfg.flipdim flip data along the sliced dimension, 'yes' or 'no' % (default = 'no') % cfg.marker [Nx3] array defining N marker positions to display % cfg.markersize radius of markers (default = 5); % cfg.markercolor [1x3] marker color in RGB (default = [1 1 1], i.e. white) % cfg.interactive 'yes' or 'no' (default), interactive coordinates % and source values % % if cfg.alpha is set to 'adaptive' the opacity of the source overlay % linearly follows the source value: maxima are opaque and minima are % transparent. % % if cfg.spacemin and/or cfg.spacemax are set to 'auto' the sliced % space is automatically restricted to the evaluated source-space % % if cfg.colmin and/or cfg.colmax are set to 'auto' the colormap is mapped % to source values the following way: if source values are either all % positive or all negative the colormap is mapped to from % min(source) to max(source). If source values are negative and positive % the colormap is symmetrical mapped around 0 from -max(abs(source)) to % +max(abs(source)). % % If cfg.maskparameter specifies a parameter to be used as an opacity mask % cfg.alpha is not used. Instead the mask values are maped to an opacitymap % that can be specified using cfg.maskmap. The mapping onto that % opacitymap is controlled as for the functional data using the % corresponding clipping and min/max options. % % if cfg.whitebg is set to 'yes' the function estimates the head volume and % displays a white background outside the head, which can save a lot of black % printer toner. % % if cfg.interactive is set to 'yes' a button will be displayed for % interactive data evaluation and coordinate reading. After clicking the % button named 'coords' you can click on any position in the slice montage. % After clicking these coordinates and their source value are displayed in % a text box below the button. The coordinates correspond to indeces in the % input data array: % % f = interp.source(coord_1,coord_2,coord_3) % % The coordinates are not affected by any transformations used for displaying % the data such as cfg.dim, cfg.rotate,cfg.flipdim or cfg.resample. % % See also FT_SOURCEANALYSIS, FT_VOLUMERESLICE % Copyright (C) 2004, Markus Siegel, [email protected] % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar ininterp ft_preamble provenance ininterp ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input data is valid for this function ininterp = ft_checkdata(ininterp, 'datatype', 'volume', 'feedback', 'yes'); % set the defaults if ~isfield(cfg, 'clipmin'); cfg.clipmin = 'auto'; end if ~isfield(cfg, 'clipmax'); cfg.clipmax = 'auto'; end if ~isfield(cfg, 'clipsym'); cfg.clipsym = 'no'; end if ~isfield(cfg, 'alpha'); cfg.alpha = 'adaptive'; end if ~isfield(cfg, 'nslices'); cfg.nslices = 20; end if ~isfield(cfg, 'dim'); cfg.dim = 3; end if ~isfield(cfg, 'colormap'); cfg.colormap = jet(128); end if ~isfield(cfg, 'spacemin'); cfg.spacemin = 'auto'; end if ~isfield(cfg, 'spacemax'); cfg.spacemax = 'auto'; end if ~isfield(cfg, 'colmin'); cfg.colmin = 'auto'; end if ~isfield(cfg, 'colmax'); cfg.colmax = 'auto'; end if ~isfield(cfg, 'resample'); cfg.resample = 1; end if ~isfield(cfg, 'rotate'); cfg.rotate = 0; end if ~isfield(cfg, 'title'); cfg.title = ''; end if ~isfield(cfg, 'whitebg'); cfg.whitebg = 'no'; end if ~isfield(cfg, 'flipdim'); cfg.flipdim = 'no'; end if ~isfield(cfg, 'marker'); cfg.marker = []; end if ~isfield(cfg, 'markersize'); cfg.markersize = 5; end if ~isfield(cfg, 'markercolor'); cfg.markercolor = [1,1,1]; end if ~isfield(cfg, 'interactive'); cfg.interactive = 'no'; end if ~isfield(cfg, 'maskclipmin'); cfg.maskclipmin = 'auto'; end if ~isfield(cfg, 'maskclipmax'); cfg.maskclipmax = 'auto'; end if ~isfield(cfg, 'maskclipsym'); cfg.maskclipsym = 'no'; end if ~isfield(cfg, 'maskmap'); cfg.maskmap = linspace(0,1,128); end if ~isfield(cfg, 'maskcolmin'); cfg.maskcolmin = 'auto'; end if ~isfield(cfg, 'maskcolmax'); cfg.maskcolmax = 'auto'; end if ~isfield(cfg, 'maskparameter');cfg.maskparameter = []; end % perform some checks on the configuration for backward compatibility if ~isfield(cfg, 'funparameter') && isfield(ininterp, 'source') % if present, the default behavior should be to use this field for plotting cfg.funparameter = 'source'; end % make the selection of functional and mask data consistent with the data cfg.funparameter = parameterselection(cfg.funparameter, ininterp); cfg.maskparameter = parameterselection(cfg.maskparameter, ininterp); % only a single parameter should be selected try, cfg.funparameter = cfg.funparameter{1}; end try, cfg.maskparameter = cfg.maskparameter{1}; end % check anatomical data if isfield(ininterp,'anatomy'); interp.anatomy = reshape(ininterp.anatomy, ininterp.dim); else error('no anatomical data supplied'); end % check functional data if ~isempty(cfg.funparameter) interp.source = double(reshape(getsubfield(ininterp, cfg.funparameter), ininterp.dim)); else error('no functional data supplied'); end % check mask data if ~isempty(cfg.maskparameter) interp.mask = double(reshape(getsubfield(ininterp,cfg.maskparameter), ininterp.dim)); maskdat = 1; else fprintf('no opacity mask data supplied\n'); interp.mask = []; maskdat = 0; end % only work with the copy of the relevant parameters in "interp" clear ininterp; % convert anatomy data type and optimize contrast if isa(interp.anatomy, 'uint8') || isa(interp.anatomy, 'uint16') fprintf('converting anatomy to floating point values...'); interp.anatomy = double(interp.anatomy); fprintf('done\n'); end fprintf('optimizing contrast of anatomical data ...'); minana = min(interp.anatomy(:)); maxana = max(interp.anatomy(:)); interp.anatomy = (interp.anatomy-minana)./(maxana-minana); fprintf('done\n'); % store original data if 'interactive' mode if strcmp(cfg.interactive,'yes') data.source = interp.source; end % place markers marker = zeros(size(interp.anatomy)); if ~isempty(cfg.marker) fprintf('placing markers ...'); [x,y,z] = ndgrid([1:size(interp.anatomy,1)],[1:size(interp.anatomy,2)],[1:size(interp.anatomy,3)]); for imarker = 1:size(cfg.marker,1) marker(find(sqrt((x-cfg.marker(iarker,1)).^2 + (y-cfg.marker(imarker,2)).^2 + (z-cfg.marker(imarker,3)).^2)<=cfg.markersize)) = 1; end fprintf('done\n'); end % shift dimensions fprintf('sorting dimensions...'); interp.anatomy = shiftdim(interp.anatomy,cfg.dim-1); interp.source = shiftdim(interp.source,cfg.dim-1); interp.mask = shiftdim(interp.mask,cfg.dim-1); marker = shiftdim(marker,cfg.dim-1); fprintf('done\n'); % flip dimensions if strcmp(cfg.flipdim,'yes') fprintf('flipping dimensions...'); interp.anatomy = flipdim(interp.anatomy,1); interp.source = flipdim(interp.source,1); interp.mask = flipdim(interp.mask,1); marker = flipdim(marker,1); fprintf('done\n'); end % set slice space if ischar(cfg.spacemin) fprintf('setting first slice position...'); spacemin = min(find(~isnan(max(max(interp.source,[],3),[],2)))); fprintf('%d...done\n',spacemin); else spacemin = cfg.spacemin; end if ischar(cfg.spacemax) fprintf('setting last slice position...'); spacemax = max(find(~isnan(max(max(interp.source,[],3),[],2)))); fprintf('%d...done\n',spacemax); else spacemax = cfg.spacemax; end % clip funtional data if ~ischar(cfg.clipmin) fprintf('clipping functional minimum...'); switch cfg.clipsym case 'no' interp.source(find(interp.source<cfg.clipmin)) = nan; case 'yes' interp.source(find(abs(interp.source)<cfg.clipmin)) = nan; end fprintf('done\n'); end if ~ischar(cfg.clipmax) fprintf('clipping functional maximum...'); switch cfg.clipsym case 'no' interp.source(find(interp.source>cfg.clipmax)) = nan; case 'yes' interp.source(find(abs(interp.source)>cfg.clipmax)) = nan; end fprintf('done\n'); end % clip mask data if maskdat if ~ischar(cfg.maskclipmin) fprintf('clipping mask minimum...'); switch cfg.maskclipsym case 'no' interp.mask(find(interp.mask<cfg.maskclipmin)) = nan; case 'yes' interp.mask(find(abs(interp.mask)<cfg.maskclipmin)) = nan; end fprintf('done\n'); end if ~ischar(cfg.maskclipmax) fprintf('clipping mask maximum...'); switch cfg.maskclipsym case 'no' interp.mask(find(interp.mask>cfg.maskclipmax)) = nan; case 'yes' interp.mask(find(abs(interp.mask)>cfg.maskclipmax)) = nan; end fprintf('done\n'); end end % scale functional data fprintf('scaling functional data...'); fmin = min(interp.source(:)); fmax = max(interp.source(:)); if ~ischar(cfg.colmin) fcolmin = cfg.colmin; else if sign(fmin)==sign(fmax) fcolmin = fmin; else fcolmin = -max(abs([fmin,fmax])); end end if ~ischar(cfg.colmax) fcolmax = cfg.colmax; else if sign(fmin)==sign(fmax) fcolmax = fmax; else fcolmax = max(abs([fmin,fmax])); end end interp.source = (interp.source-fcolmin)./(fcolmax-fcolmin); if ~ischar(cfg.colmax) interp.source(find(interp.source>1)) = 1; end if ~ischar(cfg.colmin) interp.source(find(interp.source<0)) = 0; end fprintf('done\n'); % scale mask data if maskdat fprintf('scaling mask data...'); fmin = min(interp.mask(:)); fmax = max(interp.mask(:)); if ~ischar(cfg.maskcolmin) mcolmin = cfg.maskcolmin; else if sign(fmin)==sign(fmax) mcolmin = fmin; else mcolmin = -max(abs([fmin,fmax])); end end if ~ischar(cfg.maskcolmax) mcolmax = cfg.maskcolmax; else if sign(fmin)==sign(fmax) mcolmax = fmax; else mcolmax = max(abs([fmin,fmax])); end end interp.mask = (interp.mask-mcolmin)./(mcolmax-mcolmin); if ~ischar(cfg.maskcolmax) interp.mask(find(interp.mask>1)) = 1; end if ~ischar(cfg.maskcolmin) interp.mask(find(interp.mask<0)) = 0; end fprintf('done\n'); end % merge anatomy, functional data and mask fprintf('constructing overlay...'); if ischar(cfg.colormap) % replace string by colormap using standard MATLAB function cfg.colormap = colormap(cfg.colormap); end cmap = cfg.colormap; cmaplength = size(cmap,1); maskmap = cfg.maskmap(:); maskmaplength = size(maskmap,1); indslice = round(linspace(spacemin,spacemax,cfg.nslices)); nvox1 = length(1:cfg.resample:size(interp.anatomy,2)); nvox2 = length(1:cfg.resample:size(interp.anatomy,3)); if mod(cfg.rotate,2) dummy = nvox1; nvox1 = nvox2; nvox2 = dummy; end out = zeros(nvox1,nvox2,3,cfg.nslices); for islice = 1:cfg.nslices sel1 = 1:cfg.resample:size(interp.anatomy,2); sel2 = 1:cfg.resample:size(interp.anatomy,3); dummy1 = reshape(interp.anatomy(indslice(islice),sel1,sel2), [numel(sel1) numel(sel2)]); dummy2 = reshape(interp.source(indslice(islice),sel1,sel2), [numel(sel1) numel(sel2)]); indmarker = find(reshape(marker(indslice(islice),sel1,sel2), [numel(sel1) numel(sel2)])); indsource = find(~isnan(dummy2)); if maskdat dummymask = reshape(interp.mask(indslice(islice),sel1,sel2), [numel(sel1) numel(sel2)]); indsource = find(~isnan(dummy2) & ~isnan(dummymask)); end for icol = 1:3 dummy3 = dummy1; if not(maskdat) if ~ischar(cfg.alpha) try dummy3(indsource) = ... (1-cfg.alpha) * dummy3(indsource) + ... cfg.alpha * cmap(round(dummy2(indsource)*(cmaplength-1))+1,icol); end else try dummy3(indsource) = ... (1-dummy2(indsource)) .* dummy3(indsource) + ... dummy2(indsource) .* cmap(round(dummy2(indsource)*(cmaplength-1))+1,icol); end end else dummy3(indsource) = ... (1-maskmap(round(dummymask(indsource)*(maskmaplength-1))+1)).* ... dummy3(indsource) + ... maskmap(round(dummymask(indsource)*(maskmaplength-1))+1) .* ... cmap(round(dummy2(indsource)*(cmaplength-1))+1,icol); end dummy3(indmarker) = cfg.markercolor(icol); out(:,:,icol,islice) = rot90(dummy3,cfg.rotate); end if strcmp(cfg.whitebg,'yes') bgmask = zeros(nvox1,nvox2); bgmask(find(conv2(mean(out(:,:,:,islice),3),ones(round((nvox1+nvox2)/8))/(round((nvox1+nvox2)/8).^2),'same')<0.1)) = 1; for icol = 1:3 out(:,:,icol,islice) = bgmask.*ones(nvox1,nvox2) + (1-bgmask).* out(:,:,icol,islice); end end end fprintf('done\n'); clf; fprintf('plotting...'); axes('position',[0.9 0.3 0.02 0.4]); image(permute(cmap,[1 3 2])); set(gca,'YAxisLocation','right'); set(gca,'XTick',[]); set(gca,'YDir','normal'); set(gca,'YTick',linspace(1,cmaplength,5)); set(gca,'YTickLabel',linspace(fcolmin,fcolmax,5)); set(gca,'Box','on'); axes('position',[0.01 0.01 0.88 0.90]); [h,nrows,ncols]=slicemon(out); xlim=get(gca,'XLim'); ylim=get(gca,'YLim'); text(diff(xlim)/2,-diff(ylim)/100,cfg.title,'HorizontalAlignment','center','Interpreter','none'); drawnow; fprintf('done\n'); if nargout > 0 outim=get(h,'CData'); end if strcmp(cfg.interactive,'yes') data.sin = size(interp.source); data.nrows = nrows; data.ncols = ncols; data.out = out; data.indslice = indslice; data.cfg = cfg; data.hfig = gcf; uicontrol('Units','norm', 'Position', [0.9 0.2 0.08 0.05], 'Style','pushbutton', 'String','coords',... 'Callback',@getcoords,'FontSize',7); data.hcoords = uicontrol('Units','norm', 'Position', [0.9 0.05 0.08 0.13], 'Style','text', 'String','','HorizontalAlign','left','FontSize',7); guidata(data.hfig,data); end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble history ininterp ft_postamble provenance % ---------------- subfunctions ---------------- function getcoords(h,eventdata,handles,varargin) data = guidata(gcf); [xi,yi] = ginput(1); co(2,1) = round(mod(yi,size(data.out,1))); co(3,1) = round(mod(xi,size(data.out,2))); switch mod(data.cfg.rotate,4) case 1, t1 = co(2); co(2) = co(3); co(3) = data.sin(3)-t1; case 2, co(2) = data.sin(2)-co(2); co(3) = data.sin(3)-co(3); case 3, t1 = co(3); co(3) = co(2); co(2) = data.sin(2)-t1; end try co(1) = data.indslice(fix(xi/size(data.out,2)) + fix(yi/size(data.out,1))*data.ncols + 1); catch co(1) = NaN; end if strcmp(data.cfg.flipdim, 'yes') co(1) = data.sin(1) - co(1) + 1; end co = co(:); co(2:3) = round(co(2:3)*data.cfg.resample); for ishift = 1:data.cfg.dim-1 co = [co(3);co(1);co(2)]; end set(data.hcoords,'String',sprintf('1: %d\n2: %d\n3: %d\nf: %0.4f',co(1),co(2),co(3),data.source(co(1),co(2),co(3)))); function [h,nrows,ncols] = slicemon(a) % display the montage w/o image_toolbox siz = [size(a,1) size(a,2) size(a,4)]; nn = sqrt(prod(siz))/siz(2); mm = siz(3)/nn; if (ceil(nn)-nn) < (ceil(mm)-mm), nn = ceil(nn); mm = ceil(siz(3)/nn); else mm = ceil(mm); nn = ceil(siz(3)/mm); end b = a(1,1); b(1,1) = 0; b = repmat(b, [mm*siz(1), nn*siz(2), size(a,3), 1]); rows = 1:siz(1); cols = 1:siz(2); for i=0:mm-1, for j=0:nn-1, k = j+i*nn+1; if k<=siz(3), b(rows+i*siz(1),cols+j*siz(2),:) = a(:,:,:,k); end end end hh = image(b); axis image; box off; set(gca,'XTick',[],'YTick',[],'Visible','off'); if nargout > 0 h = hh; nrows = mm; ncols = nn; end
github
lcnbeapp/beapp-master
ft_clusterplot.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_clusterplot.m
18,675
utf_8
5b3eefd9bad8ee441352bfaa996bfcdc
function [cfg] = ft_clusterplot(cfg, stat) % FT_CLUSTERPLOT plots a series of topographies with highlighted clusters. % % Use as % ft_clusterplot(cfg, stat) % where the input data is obtained from FT_TIMELOCKSTATISTICS or FT_FREQSTATISTICS % and the configuration options can be % cfg.alpha = number, highest cluster p-value to be plotted max 0.3 (default = 0.05) % cfg.highlightseries = 1x5 cell-array, highlight option series with 'on','labels' or 'numbers' (default {'on','on','on','on','on'} for p < [0.01 0.05 0.1 0.2 0.3] % cfg.highlightsymbolseries = 1x5 vector, highlight marker symbol series (default ['*','x','+','o','.'] for p < [0.01 0.05 0.1 0.2 0.3] % cfg.highlightsizeseries = 1x5 vector, highlight marker size series (default [6 6 6 6 6] for p < [0.01 0.05 0.1 0.2 0.3]) % cfg.highlightcolorpos = color of highlight marker for positive clusters (default = [0 0 0]) % cfg.highlightcolorneg = color of highlight marker for negative clusters (default = [0 0 0]) % cfg.subplotsize = layout of subplots ([h w], default [3 5]) % cfg.saveaspng = string, filename of the output figures (default = 'no') % % You can also specify cfg options that apply to FT_TOPOPLOTTFR, except for % cfg.xlim, any of the FT_TOPOPLOTTFR highlight options, cfg.comment and % cfg.commentpos. % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % If you specify this option the input data will be read from a *.mat % file on disk. This mat files should contain only a single variable named 'data', % corresponding to the input structure. % % See also: % FT_TOPOPLOTTFR, FT_TOPOPLOTER, FT_SINGLEPLOTER % Copyright (C) 2007, Ingrid Nieuwenhuis, F.C. Donders Centre % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar stat ft_preamble provenance stat ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input data is valid for this function stat = ft_checkdata(stat, 'datatype', {'timelock', 'freq'}, 'feedback', 'yes'); % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'renamed', {'hlmarkerseries', 'highlightsymbolseries'}); cfg = ft_checkconfig(cfg, 'renamed', {'hlmarkersizeseries', 'highlightsizeseries'}); cfg = ft_checkconfig(cfg, 'renamed', {'hlcolorpos', 'highlightcolorpos'}); cfg = ft_checkconfig(cfg, 'renamed', {'hlcolorneg', 'highlightcolorneg'}); cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'parameter'}); cfg = ft_checkconfig(cfg, 'deprecated', {'hllinewidthseries'}); cfg = ft_checkconfig(cfg, 'deprecated', {'xparam', 'yparam'}); % added several forbidden options cfg = ft_checkconfig(cfg, 'forbidden', {'highlight', ... 'highlightchannel', ... 'highlightsymbol', ... 'highlightcolor', ... 'highlightsize', ... 'highlightfontsize', ... 'xlim', ... 'comment', ... 'commentpos'}); % set the defaults cfg.marker = ft_getopt(cfg, 'marker', 'off'); cfg.alpha = ft_getopt(cfg, 'alpha', 0.05); cfg.highlightseries = ft_getopt(cfg, 'highlightseries', {'on','on','on','on','on'}); cfg.highlightsymbolseries = ft_getopt(cfg, 'highlightsymbolseries', ['*','x','+','o','.']); cfg.highlightsizeseries = ft_getopt(cfg, 'highlightsizeseries', [6 6 6 6 6]); cfg.hllinewidthseries = ft_getopt(cfg, 'hllinewidthseries', [1 1 1 1 1]); cfg.highlightcolorpos = ft_getopt(cfg, 'highlightcolorpos', [0 0 0]); cfg.highlightcolorneg = ft_getopt(cfg, 'highlightcolorneg', [0 0 0]); cfg.parameter = ft_getopt(cfg, 'parameter', 'stat'); cfg.saveaspng = ft_getopt(cfg, 'saveaspng', 'no'); cfg.subplotsize = ft_getopt(cfg, 'subplotsize', [3 5]); cfg.feedback = ft_getopt(cfg, 'feedback', 'text'); % error if cfg.highlightseries is not a cell, for possible confusion with cfg-options if ~iscell(cfg.highlightseries) error('cfg.highlightseries should be a cell-array of strings') end % get the options that are specific for topoplotting cfgtopo = keepfields(cfg, {'parameter', 'marker', 'markersymbol', 'markercolor', 'markersize', 'markerfontsize', 'style', 'gridscale', 'interplimits', 'interpolation', 'contournum', 'colorbar', 'shading', 'zlim'}); % prepare the layout, this only has to be done once cfgtopo.layout = ft_prepare_layout(cfg, stat); cfgtopo.showcallinfo = 'no'; cfgtopo.feedback = 'no'; % handle with the data, it should be 1D or 2D dimord = getdimord(stat, cfg.parameter); dimtok = tokenize(dimord, '_'); dimsiz = getdimsiz(stat, cfg.parameter); dimsiz(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions switch dimord case 'chan' is2D = false; case 'chan_time' is2D = true; case 'chan_freq' is2D = true; case 'chan_freq_time' % no more than two dimensions are supported, we can ignore singleton dimensions is2D = true; if dimsiz(2)==1 stat = rmfield(stat, 'freq'); stat.dimord = 'chan_time'; % remove the singleton dimension in the middle stat.(cfg.parameter) = reshape(stat.(cfg.parameter),dimsiz([1 3])); if isfield(stat, 'posclusterslabelmat') stat.posclusterslabelmat = reshape(stat.posclusterslabelmat, dimsiz([1 3])); end if isfield(stat, 'negclusterslabelmat') stat.negclusterslabelmat = reshape(stat.negclusterslabelmat, dimsiz([1 3])); end elseif dimsiz(3)==1 stat = rmfield(stat, 'time'); stat.dimord = 'chan_freq'; % no need to remove the singleton dimension at the end else error('this only works if either frequency or time is a singleton dimension'); end otherwise error('unsupported dimord %s', dimord); end % switch dimord % these are not valid any more clear dimord dimsiz % this determines the labels in the figure hastime = isfield(stat, 'time'); hasfreq = isfield(stat, 'freq'); % use the vector time, even though the 2nd dimension might be freq if hastime time = stat.time; elseif hasfreq time = stat.freq; end if issubfield(stat, 'cfg.correcttail') && ((strcmp(stat.cfg.correcttail,'alpha') || strcmp(stat.cfg.correcttail,'prob')) && (stat.cfg.tail == 0)); if ~(cfg.alpha >= stat.cfg.alpha); warning(['the pvalue you plot: cfg.alpha = ' num2str(cfg.alpha) ' is higher than the correcttail option you tested: stat.cfg.alpha = ' num2str(stat.cfg.alpha)]); end end % find significant clusters sigpos = []; signeg = []; haspos = isfield(stat,'posclusters'); hasneg = isfield(stat,'negclusters'); if haspos == 0 && hasneg == 0 fprintf('%s\n','no significant clusters in data; nothing to plot') else if haspos for iPos = 1:length(stat.posclusters) sigpos(iPos) = stat.posclusters(iPos).prob < cfg.alpha; end end if hasneg for iNeg = 1:length(stat.negclusters) signeg(iNeg) = stat.negclusters(iNeg).prob < cfg.alpha; end end sigpos = find(sigpos == 1); signeg = find(signeg == 1); Nsigpos = length(sigpos); Nsigneg = length(signeg); Nsigall = Nsigpos + Nsigneg; if Nsigall == 0 error('no clusters present with a p-value lower than the specified alpha, nothing to plot') end % make clusterslabel matrix per significant cluster if haspos posCLM = stat.posclusterslabelmat; sigposCLM = zeros(size(posCLM)); probpos = []; for iPos = 1:length(sigpos) sigposCLM(:,:,iPos) = (posCLM == sigpos(iPos)); probpos(iPos) = stat.posclusters(iPos).prob; hlsignpos(iPos) = prob2hlsign(probpos(iPos), cfg.highlightsymbolseries); end else posCLM = []; sigposCLM = []; probpos = []; end if hasneg negCLM = stat.negclusterslabelmat; signegCLM = zeros(size(negCLM)); probneg = []; for iNeg = 1:length(signeg) signegCLM(:,:,iNeg) = (negCLM == signeg(iNeg)); probneg(iNeg) = stat.negclusters(iNeg).prob; hlsignneg(iNeg) = prob2hlsign(probneg(iNeg), cfg.highlightsymbolseries); end else % no negative clusters negCLM = []; signegCLM = []; probneg = []; end fprintf('%s%i%s%g%s\n','There are ',Nsigall,' clusters smaller than alpha (',cfg.alpha,')') if is2D % define time or freq window per cluster for iPos = 1:length(sigpos) possum_perclus = sum(sigposCLM(:,:,iPos),1); %sum over chans for each time- or freq-point ind_min = min(find(possum_perclus~=0)); ind_max = max(find(possum_perclus~=0)); time_perclus = [time(ind_min) time(ind_max)]; if hastime fprintf('%s%s%s%s%s%s%s%s%s%s%s\n','Positive cluster: ',num2str(sigpos(iPos)),', pvalue: ',num2str(probpos(iPos)),' (',hlsignpos(iPos),')',', t = ',num2str(time_perclus(1)),' to ',num2str(time_perclus(2))) elseif hasfreq fprintf('%s%s%s%s%s%s%s%s%s%s%s\n','Positive cluster: ',num2str(sigpos(iPos)),', pvalue: ',num2str(probpos(iPos)),' (',hlsignpos(iPos),')',', f = ',num2str(time_perclus(1)),' to ',num2str(time_perclus(2))) end end for iNeg = 1:length(signeg) negsum_perclus = sum(signegCLM(:,:,iNeg),1); ind_min = min(find(negsum_perclus~=0)); ind_max = max(find(negsum_perclus~=0)); time_perclus = [time(ind_min) time(ind_max)]; if hastime time_perclus = [time(ind_min) time(ind_max)]; fprintf('%s%s%s%s%s%s%s%s%s%s%s\n','Negative cluster: ',num2str(signeg(iNeg)),', pvalue: ',num2str(probneg(iNeg)),' (',hlsignneg(iNeg),')',', t = ',num2str(time_perclus(1)),' to ',num2str(time_perclus(2))) elseif hasfreq fprintf('%s%s%s%s%s%s%s%s%s%s%s\n','Negative cluster: ',num2str(signeg(iNeg)),', pvalue: ',num2str(probneg(iNeg)),' (',hlsignneg(iNeg),')',', f = ',num2str(time_perclus(1)),' to ',num2str(time_perclus(2))) end end % define time- or freq-window containing all significant clusters possum = sum(sigposCLM,3); %sum over Chans for timevector possum = sum(possum,1); negsum = sum(signegCLM,3); negsum = sum(negsum,1); if haspos && hasneg allsum = possum + negsum; elseif haspos allsum = possum; else allsum = negsum; end ind_timewin_min = min(find(allsum~=0)); ind_timewin_max = max(find(allsum~=0)); timewin = time(ind_timewin_min:ind_timewin_max); else for iPos = 1:length(sigpos) fprintf('%s%s%s%s%s%s%s\n','Positive cluster: ',num2str(sigpos(iPos)),', pvalue: ',num2str(probpos(iPos)),' (',hlsignpos(iPos),')') end for iNeg = 1:length(signeg) fprintf('%s%s%s%s%s%s%s\n','Negative cluster: ',num2str(signeg(iNeg)),', pvalue: ',num2str(probneg(iNeg)),' (',hlsignneg(iNeg),')') end end % setup highlight options for all clusters and make comment for 1D data compos = []; comneg = []; for iPos = 1:length(sigpos) if stat.posclusters(sigpos(iPos)).prob < 0.01 cfgtopo.highlight{iPos} = cfg.highlightseries{1}; cfgtopo.highlightsymbol{iPos} = cfg.highlightsymbolseries(1); cfgtopo.highlightsize{iPos} = cfg.highlightsizeseries(1); elseif stat.posclusters(sigpos(iPos)).prob < 0.05 cfgtopo.highlight{iPos} = cfg.highlightseries{2}; cfgtopo.highlightsymbol{iPos} = cfg.highlightsymbolseries(2); cfgtopo.highlightsize{iPos} = cfg.highlightsizeseries(2); elseif stat.posclusters(sigpos(iPos)).prob < 0.1 cfgtopo.highlight{iPos} = cfg.highlightseries{3}; cfgtopo.highlightsymbol{iPos} = cfg.highlightsymbolseries(3); cfgtopo.highlightsize{iPos} = cfg.highlightsizeseries(3); elseif stat.posclusters(sigpos(iPos)).prob < 0.2 cfgtopo.highlight{iPos} = cfg.highlightseries{4}; cfgtopo.highlightsymbol{iPos} = cfg.highlightsymbolseries(4); cfgtopo.highlightsize{iPos} = cfg.highlightsizeseries(4); elseif stat.posclusters(sigpos(iPos)).prob < 0.3 cfgtopo.highlight{iPos} = cfg.highlightseries{5}; cfgtopo.highlightsymbol{iPos} = cfg.highlightsymbolseries(5); cfgtopo.highlightsize{iPos} = cfg.highlightsizeseries(5); end cfgtopo.highlightcolor{iPos} = cfg.highlightcolorpos; compos = strcat(compos,cfgtopo.highlightsymbol{iPos}, 'p=',num2str(probpos(iPos)),' '); % make comment, only used for 1D data end for iNeg = 1:length(signeg) if stat.negclusters(signeg(iNeg)).prob < 0.01 cfgtopo.highlight{length(sigpos)+iNeg} = cfg.highlightseries{1}; cfgtopo.highlightsymbol{length(sigpos)+iNeg} = cfg.highlightsymbolseries(1); cfgtopo.highlightsize{length(sigpos)+iNeg} = cfg.highlightsizeseries(1); elseif stat.negclusters(signeg(iNeg)).prob < 0.05 cfgtopo.highlight{length(sigpos)+iNeg} = cfg.highlightseries{2}; cfgtopo.highlightsymbol{length(sigpos)+iNeg} = cfg.highlightsymbolseries(2); cfgtopo.highlightsize{length(sigpos)+iNeg} = cfg.highlightsizeseries(2); elseif stat.negclusters(signeg(iNeg)).prob < 0.1 cfgtopo.highlight{length(sigpos)+iNeg} = cfg.highlightseries{3}; cfgtopo.highlightsymbol{length(sigpos)+iNeg} = cfg.highlightsymbolseries(3); cfgtopo.highlightsize{length(sigpos)+iNeg} = cfg.highlightsizeseries(3); elseif stat.negclusters(signeg(iNeg)).prob < 0.2 cfgtopo.highlight{length(sigpos)+iNeg} = cfg.highlightseries{4}; cfgtopo.highlightsymbol{length(sigpos)+iNeg} = cfg.highlightsymbolseries(4); cfgtopo.highlightsize{length(sigpos)+iNeg} = cfg.highlightsizeseries(4); elseif stat.negclusters(signeg(iNeg)).prob < 0.3 cfgtopo.highlight{length(sigpos)+iNeg} = cfg.highlightseries{5}; cfgtopo.highlightsymbol{length(sigpos)+iNeg} = cfg.highlightsymbolseries(5); cfgtopo.highlightsize{length(sigpos)+iNeg} = cfg.highlightsizeseries(5); end cfgtopo.highlightcolor{length(sigpos)+iNeg} = cfg.highlightcolorneg; comneg = strcat(comneg,cfgtopo.highlightsymbol{length(sigpos)+iNeg}, 'p=',num2str(probneg(iNeg)),' '); % make comment, only used for 1D data end if is2D Npl = length(timewin); else Npl = 1; end numSubplots = prod(cfg.subplotsize); Nfig = ceil(Npl/numSubplots); % put channel indexes in list if is2D for iPl = 1:Npl for iPos = 1:length(sigpos) list{iPl}{iPos} = find(sigposCLM(:,ind_timewin_min+iPl-1,iPos) == 1); end for iNeg = 1:length(signeg) list{iPl}{length(sigpos)+iNeg} = find(signegCLM(:,ind_timewin_min+iPl-1,iNeg) == 1); end end else for iPl = 1:Npl for iPos = 1:length(sigpos) list{iPl}{iPos} = find(sigposCLM(:,iPos) == 1); end for iNeg = 1:length(signeg) list{iPl}{length(sigpos)+iNeg} = find(signegCLM(:,iNeg) == 1); end end end % this does not work, because the progress tracker is also used inside ft_topoplotTFR % ft_progress('init', cfg.feedback, 'making subplots...'); % ft_progress(count/Npl, 'making subplot %d from %d', count, Npl); % ft_progress('close'); count = 0; % make plots for iPl = 1:Nfig figure; if is2D if iPl < Nfig for iT = 1:numSubplots PlN = (iPl-1)*numSubplots + iT; %plotnumber cfgtopo.xlim = [time(ind_timewin_min+PlN-1) time(ind_timewin_min+PlN-1)]; cfgtopo.highlightchannel = list{PlN}; if hastime cfgtopo.comment = strcat('time: ',num2str(time(ind_timewin_min+PlN-1)), ' s'); elseif hasfreq cfgtopo.comment = strcat('freq: ',num2str(time(ind_timewin_min+PlN-1)), ' Hz'); end cfgtopo.commentpos = 'title'; subplot(cfg.subplotsize(1), cfg.subplotsize(2), iT); count = count+1; fprintf('making subplot %d from %d\n', count, Npl); ft_topoplotTFR(cfgtopo, stat); end elseif iPl == Nfig for iT = 1:Npl-(numSubplots*(Nfig-1)) PlN = (iPl-1)*numSubplots + iT; %plotnumber cfgtopo.xlim = [time(ind_timewin_min+PlN-1) time(ind_timewin_min+PlN-1)]; cfgtopo.highlightchannel = list{PlN}; if hastime cfgtopo.comment = strcat('time: ',num2str(time(ind_timewin_min+PlN-1)), ' s'); elseif hasfreq cfgtopo.comment = strcat('freq: ',num2str(time(ind_timewin_min+PlN-1)), ' Hz'); end cfgtopo.commentpos = 'title'; subplot(cfg.subplotsize(1), cfg.subplotsize(2), iT); count = count+1; fprintf('making subplot %d from %d\n', count, Npl); ft_topoplotTFR(cfgtopo, stat); end end else cfgtopo.highlightchannel = list{1}; cfgtopo.comment = strcat(compos,comneg); cfgtopo.commentpos = 'title'; count = count+1; fprintf('making subplot %d from %d\n', count, Npl); ft_topoplotTFR(cfgtopo, stat); end % save figure if isequal(cfg.saveaspng,'no'); else filename = strcat(cfg.saveaspng, '_fig', num2str(iPl)); print(gcf,'-dpng',filename); end end end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous stat ft_postamble provenance %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sign = prob2hlsign(prob, hlsign) if prob < 0.01 sign = hlsign(1); elseif prob < 0.05 sign = hlsign(2); elseif prob < 0.1 sign = hlsign(3); elseif prob < 0.2 sign = hlsign(4); elseif prob < 0.3 sign = hlsign(5); end
github
lcnbeapp/beapp-master
ft_sourcemovie.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_sourcemovie.m
27,386
utf_8
e4209fc342ee8d918587cffc2dfc2d6e
function [cfg, M] = ft_sourcemovie(cfg, source, source2) % FT_SOURCEMOVIE displays the source reconstruction on a cortical mesh % and allows the user to scroll through time with a movie % % Use as % ft_sourcemovie(cfg, source) % where the input source data is obtained from FT_SOURCEANALYSIS and cfg is % a configuratioun structure that should contain % % cfg.funparameter = string, functional parameter that is color coded (default = 'pow') % cfg.maskparameter = string, functional parameter that is used for opacity (default = []) % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % If you specify this option the input data will be read from a *.mat % file on disk. This mat files should contain only a single variable named 'data', % corresponding to the input structure. % % See also FT_SOURCEPLOT, FT_SOURCEINTERPOLATE % Undocumented options: % cfg.parcellation % Copyright (C) 2011-2015, Robert Oostenveld % Copyright (C) 2012-2014, Jorn Horschig % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the initial part deals with parsing the input options and data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar source ft_preamble provenance source ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % the data can be passed as input argument or can be read from disk hassource2 = exist('source2', 'var'); % check if the input data is valid for this function source = ft_checkdata(source, 'datatype', 'source', 'feedback', 'yes'); % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'cfg.funparameter'}); cfg = ft_checkconfig(cfg, 'renamed', {'parameter', 'cfg.funparameter'}); cfg = ft_checkconfig(cfg, 'renamed', {'mask', 'maskparameter'}); % these are not needed any more, once the source structure has a proper dimord % cfg = ft_checkconfig(cfg, 'deprecated', 'xparam'); % cfg = ft_checkconfig(cfg, 'deprecated', 'yparam'); % get the options xlim = ft_getopt(cfg, 'xlim'); ylim = ft_getopt(cfg, 'ylim'); zlim = ft_getopt(cfg, 'zlim'); olim = ft_getopt(cfg, 'alim'); % don't use alim as variable name cfg.xparam = ft_getopt(cfg, 'xparam'); % default is dealt with below cfg.yparam = ft_getopt(cfg, 'yparam'); % default is dealt with below cfg.funparameter = ft_getopt(cfg, 'funparameter'); cfg.maskparameter = ft_getopt(cfg, 'maskparameter'); cfg.renderer = ft_getopt(cfg, 'renderer', 'opengl'); cfg.title = ft_getopt(cfg, 'title', ''); cfg.parcellation = ft_getopt(cfg, 'parcellation'); % select the functional and the mask parameter cfg.funparameter = parameterselection(cfg.funparameter, source); cfg.maskparameter = parameterselection(cfg.maskparameter, source); % only a single parameter should be selected try, cfg.funparameter = cfg.funparameter{1}; end try, cfg.maskparameter = cfg.maskparameter{1}; end dimord = getdimord(source, cfg.funparameter); dimtok = tokenize(dimord, '_'); if isempty(cfg.xparam) && numel(dimtok)>1 cfg.xparam = dimtok{2}; end if isempty(cfg.xparam) && numel(dimtok)>2 cfg.yparam = dimtok{3}; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the actual computation is done in the middle part %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~hassource2 fun = getsubfield(source, cfg.funparameter); elseif hassource2 && isfield(source2, 'pos'), fun = getsubfield(source, cfg.funparameter); fun2 = getsubfield(source2, cfg.funparameter); elseif hassource2 % assume the first data argument to be a parcellation, and the second a parcellated structure tmp = getsubfield(source2, cfg.funparameter); siz = [size(tmp) 1]; fun = zeros([size(source.pos, 1), siz(2:end)]); parcels = source.(cfg.parcellation); parcelslabel = source.([cfg.parcellation,'label']); for k = 1:numel(source2.label) sel = match_str(source.([cfg.parcellation,'label']), source2.label{k}); if ~isempty(sel) sel = source.(cfg.parcellation)==sel; fun(sel,:,:) = repmat(tmp(k,:,:), [sum(sel) 1]); end end source.(cfg.xparam) = source2.(cfg.xparam); if ~isempty(cfg.yparam) source.(cfg.yparam) = source2.(cfg.yparam); end end if size(source.pos)~=size(fun,1) error('inconsistent number of vertices in the cortical mesh'); end if ~isfield(source, 'tri') error('source.tri missing, this function requires a triangulated cortical sheet as source model'); end if ~isempty(cfg.maskparameter) && ischar(cfg.maskparameter) mask = double(getsubfield(source, cfg.maskparameter)); else mask = 0.5*ones(size(fun)); end xparam = source.(cfg.xparam); if length(xparam)~=size(fun,2) error('inconsistent size of "%s" compared to "%s"', cfg.funparameter, cfg.xparam); end if ~isempty(cfg.yparam) yparam = source.(cfg.yparam); if length(yparam)~=size(fun,3) error('inconsistent size of "%s" compared to "%s"', cfg.funparameter, cfg.yparam); end else yparam = []; end if isempty(xlim) xlim(1) = min(xparam); xlim(2) = max(xparam); end xbeg = nearest(xparam, xlim(1)); xend = nearest(xparam, xlim(2)); % update the configuration cfg.xlim = xparam([xbeg xend]); if ~isempty(yparam) if isempty(ylim) ylim(1) = min(yparam); ylim(2) = max(yparam); end ybeg = nearest(yparam, ylim(1)); yend = nearest(yparam, ylim(2)); % update the configuration cfg.ylim = xparam([xbeg xend]); hasyparam = true; else % this allows us not to worry about the yparam any more yparam = nan; ybeg = 1; yend = 1; cfg.ylim = []; hasyparam = false; end % make a subselection of the data xparam = xparam(xbeg:xend); yparam = yparam(ybeg:yend); fun = fun(:,xbeg:xend,ybeg:yend); if hassource2 && isfield(source2, 'pos'), fun2 = fun2(:,xbeg:xend,ybeg:yend); end mask = mask(:,xbeg:xend,ybeg:yend); clear xbeg xend ybeg yend if isempty(zlim) zlim(1) = min(fun(:)); zlim(2) = max(fun(:)); % update the configuration cfg.zlim = zlim; end if isempty(olim) olim(1) = min(mask(:)); olim(2) = max(mask(:)); if olim(1)==olim(2) olim(1) = 0; olim(2) = 1; end % update the configuration %cfg.alim = olim; end % collect the data and the options to be used in the figure opt.cfg = cfg; opt.xparam = xparam; opt.yparam = yparam; opt.xval = 0; opt.yval = 0; opt.dat = fun; opt.mask = abs(mask); opt.pos = source.pos; opt.tri = source.tri; if isfield(source, 'inside') opt.vindx = source.inside(:); else opt.vindx = 1:size(opt.pos,1); end opt.speed = 1; opt.record = 0; opt.threshold = 0; opt.frame = 0; opt.cleanup = false; if exist('parcels', 'var'), opt.parcellation = parcels; end if exist('parcelslabel', 'var'), opt.parcellationlabel = parcelslabel; end % add functional data of optional third input to the opt structure % FIXME here we should first check whether the meshes correspond! if hassource2 && isfield(source2, 'pos') opt.dat2 = fun2; opt.dat1 = opt.dat; end %% start building the figure h = figure; set(h, 'color', [1 1 1]); set(h, 'visible', 'on'); set(h, 'renderer', cfg.renderer); set(h, 'toolbar', 'figure'); set(h, 'CloseRequestFcn', @cb_quitbutton); set(h, 'position', [100 200 700 500]); set(h, 'windowbuttondownfcn', @cb_getposition); if ~isempty(cfg.title) title(cfg.title); end % get timer object t = timer; set(t, 'timerfcn', {@cb_timer, h}, 'period', 0.1, 'executionmode', 'fixedSpacing'); % make the user interface elements cambutton = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'light', 'userdata', 'C'); playbutton = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'play', 'userdata', 'p'); recordbutton = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'record', 'userdata', 'r'); quitbutton = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'quit', 'userdata', 'q'); if isfield(opt, 'dat2'), displaybutton = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'display: var1', 'userdata', 'f'); end thrmin = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'downarrow'); thr = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'threshold', 'userdata', 't'); thrplus = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'uparrow'); spdmin = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'shift+downarrow'); spd = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'speed','userdata', 's'); spdplus = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'shift+uparrow'); clim = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'colorlim', 'userdata', 'z'); climminmin = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '-', 'userdata', 'leftarrow'); climmaxmin = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '+', 'userdata', 'shift+leftarrow'); climminplus = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '-', 'userdata', 'rightarrow'); climmaxplus = uicontrol('parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '+', 'userdata', 'shift+rightarrow'); sliderx = uicontrol('parent', h, 'units', 'normalized', 'style', 'slider', 'string', sprintf('%s = ', cfg.xparam)); stringx = uicontrol('parent', h, 'units', 'normalized', 'style', 'text'); slidery = uicontrol('parent', h, 'units', 'normalized', 'style', 'slider', 'string', sprintf('%s = ', cfg.yparam)); stringy = uicontrol('parent', h, 'units', 'normalized', 'style', 'text'); stringz = uicontrol('parent', h, 'units', 'normalized', 'style', 'text'); stringp = uicontrol('parent', h, 'units', 'normalized', 'style', 'text'); if isfield(opt,'dat2') set(displaybutton, 'position', [0.005 0.34 0.18 0.05], 'callback', @cb_keyboard); end set(cambutton, 'position', [0.095 0.28 0.09 0.05], 'callback', @cb_keyboard); set(quitbutton, 'position', [0.005 0.28 0.09 0.05], 'callback', @cb_keyboard); set(playbutton, 'position', [0.005 0.22 0.09 0.05], 'callback', @cb_keyboard); set(recordbutton, 'position', [0.095 0.22 0.09 0.05], 'callback', @cb_keyboard); set(thrmin, 'position', [0.005 0.16 0.03 0.05], 'callback', @cb_keyboard); set(thr, 'position', [0.035 0.16 0.12 0.05], 'callback', @cb_keyboard); set(thrplus, 'position', [0.155 0.16 0.03 0.05], 'callback', @cb_keyboard); set(climminmin, 'position', [0.005 0.10 0.03 0.025], 'callback', @cb_keyboard); set(climmaxmin, 'position', [0.005 0.125 0.03 0.025], 'callback', @cb_keyboard); set(clim, 'position', [0.035 0.10 0.12 0.05], 'callback', @cb_keyboard); set(climminplus, 'position', [0.155 0.10 0.03 0.025], 'callback', @cb_keyboard); set(climmaxplus, 'position', [0.155 0.125 0.03 0.025], 'callback', @cb_keyboard); set(spdmin, 'position', [0.005 0.04 0.03 0.05], 'callback', @cb_keyboard); set(spd, 'position', [0.035 0.04 0.12 0.05], 'callback', @cb_keyboard); set(spdplus, 'position', [0.155 0.04 0.03 0.05], 'callback', @cb_keyboard); set(sliderx, 'position', [0.02 0.4 0.3 0.03], 'callback', @cb_slider);%[0.200 0.04 0.78 0.03], 'callback', @cb_slider); set(slidery, 'position', [0.350 0.5 0.03 0.35], 'callback', @cb_slider); set(stringx, 'position', [0.800 0.93 0.18 0.03]); set(stringy, 'position', [0.800 0.90 0.18 0.03]); set(stringz, 'position', [0.650 0.96 0.33 0.03]); set(stringp, 'position', [0.650 0.87 0.33 0.03]); set(stringx, 'string', sprintf('%s = ', cfg.xparam)); set(stringy, 'string', sprintf('%s = ', cfg.yparam)); set(stringz, 'string', sprintf('position = ')); set(stringp, 'string', sprintf('parcel = ')); set(stringx, 'horizontalalignment', 'right', 'backgroundcolor', [1 1 1]); set(stringy, 'horizontalalignment', 'right', 'backgroundcolor', [1 1 1]); set(stringz, 'horizontalalignment', 'right', 'backgroundcolor', [1 1 1]); set(stringp, 'horizontalalignment', 'right', 'backgroundcolor', [1 1 1]); % create axes object to contain the mesh hx = axes; set(hx, 'position', [0.4 0.08 0.6 0.8]); set(hx, 'tag', 'mesh'); if isfield(source, 'sulc') vdat = source.sulc; vdat = vdat-min(vdat); vdat = vdat./max(vdat); vdat = 0.1+0.3.*repmat(round(1-vdat),[1 3]); hs1 = ft_plot_mesh(source, 'edgecolor', 'none', 'vertexcolor', vdat); else hs1 = ft_plot_mesh(source, 'edgecolor', 'none', 'facecolor', [0.5 0.5 0.5]); end lighting gouraud siz = [size(opt.dat) 1]; hs = ft_plot_mesh(source, 'edgecolor', 'none', 'vertexcolor', 0*opt.dat(:,ceil(siz(2)/2),ceil(siz(3)/2)));%, 'facealpha', 0*opt.mask(:,1,1)); lighting gouraud cam1 = camlight('left'); cam2 = camlight('right'); caxis(cfg.zlim); %alim(cfg.alim); % create axis object to contain a time course hy = axes; set(hy, 'position', [0.02 0.5 0.3 0.35]); set(hy, 'yaxislocation', 'right'); if ~hasyparam tline = plot(opt.xparam, mean(opt.dat(opt.vindx,:))); hold on; abc = axis; axis([opt.xparam(1) opt.xparam(end) abc(3:4)]); vline = plot(opt.xparam(1)*[1 1], abc(3:4), 'r'); if hassource2 && isfield(source2, 'pos') tline2 = plot(opt.xparam, mean(opt.dat2(opt.vindx,:)), 'r'); hold on; end else tline = imagesc(opt.xparam, opt.yparam, shiftdim(mean(opt.dat(opt.vindx,:,:)),1)'); axis xy; hold on; abc = [opt.xparam([1 end]) opt.yparam([1 end])]; vline = plot(opt.xparam(ceil(siz(2)/2)).*[1 1], abc(3:4)); hline = plot(abc(1:2), opt.yparam(ceil(siz(3)/2)).*[1 1]); %error('not yet implemented'); end set(hy, 'tag', 'timecourse'); % remember the various handles opt.h = h; % handle to the figure opt.hs = hs; % handle to the mesh opt.hx = hx; % handle to the axes containing the mesh opt.hy = hy; % handle to the axes containing the timecourse opt.cam = [cam1 cam2]; % handles to the light objects opt.vline = vline; % handle to the line in the ERF plot opt.tline = tline; % handle to the ERF if exist('hline', 'var') opt.hline = hline; end if hassource2 && isfield(source2, 'pos'), opt.tline2 = tline2; end opt.playbutton = playbutton; % handle to the playbutton opt.recordbutton = recordbutton; % handle to the recordbutton opt.quitbutton = quitbutton; % handle to the quitbutton try, opt.displaybutton = displaybutton; end %opt.p = p; opt.t = t; %opt.hx = hx; %opt.hy = hy; opt.sliderx = sliderx; opt.slidery = slidery; opt.stringx = stringx; opt.stringy = stringy; opt.stringz = stringz; opt.stringp = stringp; if ~hasyparam set(opt.slidery, 'visible', 'off'); set(opt.stringy, 'visible', 'off'); end if ~exist('parcels', 'var') set(opt.stringp, 'visible', 'off'); end setappdata(h, 'opt', opt); while opt.cleanup==0 uiwait(h); opt = getappdata(h, 'opt'); end stop(opt.t); if nargout M = opt.movie; end delete(h); % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous source ft_postamble provenance %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_slider(h, eventdata) persistent previous_valx previous_valy previous_vindx if isempty(previous_valx) previous_valx = 0; end if isempty(previous_valy) previous_valy = 0; end h = getparent(h); opt = getappdata(h, 'opt'); valx = get(opt.sliderx, 'value'); valx = round(valx*(size(opt.dat,2)-1))+1; valx = min(valx, size(opt.dat,2)); valx = max(valx, 1); valy = get(opt.slidery, 'value'); valy = round(valy*(size(opt.dat,3)-1))+1; valy = min(valy, size(opt.dat,3)); valy = max(valy, 1); mask = opt.mask(:,valx,valy); mask(opt.dat(:,valx,valy)<opt.threshold) = 0; % update stuff if previous_valx~=valx || previous_valy~=valy % update strings set(opt.stringx, 'string', sprintf('%s = %3.3f\n', opt.cfg.xparam, opt.xparam(valx))); set(opt.stringy, 'string', sprintf('%s = %3.3f\n', opt.cfg.yparam, opt.yparam(valy))); % update data in mesh set(opt.hs, 'FaceVertexCData', opt.dat(:,valx,valy)); set(opt.hs, 'FaceVertexAlphaData', mask); set(opt.vline, 'xdata', [1 1]*opt.xparam(valx)); if isfield(opt, 'hline') set(opt.hline, 'ydata', [1 1]*opt.yparam(valy)); end end % update ERF-plot if ~isfield(opt, 'hline') set(opt.hy, 'ylim', opt.cfg.zlim); set(opt.vline, 'ydata', opt.cfg.zlim); else set(opt.hy, 'clim', opt.cfg.zlim); end if ~(numel(previous_vindx)==numel(opt.vindx) && all(previous_vindx==opt.vindx)) if ~isfield(opt, 'hline') tmp = mean(opt.dat(opt.vindx,:,valy),1); set(opt.tline, 'ydata', tmp); else tmp = shiftdim(mean(opt.dat(opt.vindx,:,:),1))'; set(opt.tline, 'cdata', tmp); end %set(opt.hy, 'ylim', [min(tmp(:)) max(tmp(:))]); %set(opt.vline, 'ydata', [min(tmp(:)) max(tmp(:))]); if isfield(opt, 'dat2') tmp = mean(opt.dat1(opt.vindx,:,valy),1); set(opt.tline, 'ydata', tmp); tmp = mean(opt.dat2(opt.vindx,:,valy),1); set(opt.tline2, 'ydata', tmp); end set(opt.hy, 'yaxislocation', 'right'); set(opt.stringz, 'string', sprintf('position = [%2.1f, %2.1f, %2.1f]', opt.pos(opt.vindx,:))); if isfield(opt, 'parcellation'), set(opt.stringp, 'string', sprintf('parcel = %s', opt.parcellationlabel{opt.parcellation(opt.vindx)})); end end if opt.record tmp = get(opt.h, 'position'); opt.frame = opt.frame + 1; opt.movie(opt.frame) = getframe(opt.h,[1 1 tmp(3:4)-1]); end setappdata(h, 'opt', opt); previous_valx = valx; previous_valy = valy; previous_vindx = opt.vindx; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_playbutton(h, eventdata) opt = getappdata(h, 'opt'); if strcmp(get(opt.playbutton, 'string'), 'pause') stop(opt.t); set(opt.playbutton, 'string', 'play'); else start(opt.t); set(opt.playbutton, 'string', 'pause'); end setappdata(h, 'opt', opt); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_quitbutton(h, eventdata) opt = getappdata(h, 'opt'); opt.cleanup = 1; setappdata(h, 'opt', opt); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_recordbutton(h, eventdata) opt = getappdata(h, 'opt'); if strcmp(get(opt.recordbutton, 'string'), 'stop') opt.record = 0; set(opt.recordbutton, 'string', 'record'); else opt.record = 1; set(opt.recordbutton, 'string', 'stop'); end setappdata(h, 'opt', opt); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_timer(obj, info, h) opt = getappdata(h, 'opt'); delta = opt.speed/size(opt.dat,2); val = get(opt.sliderx, 'value'); val = val + delta; if val>1 val = val-1; end set(opt.sliderx, 'value', val); setappdata(h, 'opt', opt); cb_slider(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_alim(h, eventdata) if ~ishandle(h) return end opt = guidata(h); switch get(h, 'String') case '+' alim(alim*sqrt(2)); case '-' alim(alim/sqrt(2)); end % switch guidata(h, opt); uiresume; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_getposition(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); if strcmp(get(get(h, 'currentaxes'), 'tag'), 'timecourse') % get the current point pos = get(opt.hy, 'currentpoint'); set(opt.sliderx, 'value', nearest(opt.xparam, pos(1,1))./numel(opt.xparam)); if isfield(opt, 'hline') set(opt.slidery, 'value', nearest(opt.yparam, pos(1,2))./numel(opt.yparam)); end elseif strcmp(get(get(h, 'currentaxes'), 'tag'), 'mesh') % get the current point, which is defined as the intersection through the % axis-box (in 3D) pos = get(opt.hx, 'currentpoint'); % get the intersection with the mesh [ipos, d] = intersect_line(opt.pos, opt.tri, pos(1,:), pos(2,:)); [md, ix] = min(abs(d)); dpos = opt.pos - ipos(ix*ones(size(opt.pos,1),1),:); opt.vindx = nearest(sum(dpos.^2,2),0); end setappdata(h, 'opt', opt); cb_slider(h); uiresume; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_keyboard(h, eventdata) if isempty(eventdata) % determine the key that corresponds to the uicontrol element that was activated key = get(h, 'userdata'); else % determine the key that was pressed on the keyboard key = parseKeyboardEvent(eventdata); end % get focus back to figure if ~strcmp(get(h, 'type'), 'figure') set(h, 'enable', 'off'); drawnow; set(h, 'enable', 'on'); end h = getparent(h); opt = getappdata(h, 'opt'); switch key case 'leftarrow' % change colorlim opt.cfg.zlim(1) = opt.cfg.zlim(1)-0.1*abs(opt.cfg.zlim(1)); setappdata(h, 'opt', opt); caxis(opt.cfg.zlim); set(opt.hx, 'Clim', opt.cfg.zlim); case 'shift+leftarrow' % change colorlim opt.cfg.zlim(1) = opt.cfg.zlim(1)+0.1*abs(opt.cfg.zlim(1)); setappdata(h, 'opt', opt); caxis(opt.cfg.zlim); set(opt.hx, 'Clim', opt.cfg.zlim); case 'rightarrow' opt.cfg.zlim(2) = opt.cfg.zlim(2)-0.1*abs(opt.cfg.zlim(2)); setappdata(h, 'opt', opt); caxis(opt.cfg.zlim); set(opt.hx, 'Clim', opt.cfg.zlim); case 'shift+rightarrow' opt.cfg.zlim(2) = opt.cfg.zlim(2)+0.1*abs(opt.cfg.zlim(2)); setappdata(h, 'opt', opt); caxis(opt.cfg.zlim); set(opt.hx, 'Clim', opt.cfg.zlim); case 'uparrow' % enhance threshold opt.threshold = opt.threshold+0.01.*max(opt.dat(:)); setappdata(h, 'opt', opt); case 'downarrow' % lower threshold opt.threshold = opt.threshold-0.01.*max(opt.dat(:)); setappdata(h, 'opt', opt); case 'shift+uparrow' % change speed opt.speed = opt.speed*sqrt(2); setappdata(h, 'opt', opt); case 'shift+downarrow' opt.speed = opt.speed/sqrt(2); opt.speed = max(opt.speed, 1); % should not be smaller than 1 setappdata(h, 'opt', opt); case 'ctrl+uparrow' % change channel case 'C' % update camera position camlight(opt.cam(1), 'left'); camlight(opt.cam(2), 'right'); case 'p' cb_playbutton(h); case 'q' cb_quitbutton(h); case 'r' cb_recordbutton(h); case 's' % select the speed response = inputdlg('speed', 'specify', 1, {num2str(opt.speed)}); if ~isempty(response) opt.speed = str2double(response); setappdata(h, 'opt', opt); end case 't' % select the threshold response = inputdlg('threshold', 'specify', 1, {num2str(opt.threshold)}); if ~isempty(response) opt.threshold = str2double(response); setappdata(h, 'opt', opt); end case 'z' % select the colorlim response = inputdlg('colorlim', 'specify', 1, {[num2str(opt.cfg.zlim(1)),' ',num2str(opt.cfg.zlim(2))]}); if ~isempty(response) [tok1, tok2] = strtok(response, ' '); opt.cfg.zlim(1) = str2double(deblank(tok1)); opt.cfg.zlim(2) = str2double(deblank(tok2)); set(opt.hx, 'Clim', opt.cfg.zlim); setappdata(h, 'opt', opt); end case 'f' if isfield(opt, 'dat2') if isequalwithequalnans(opt.dat,opt.dat2), opt.dat = opt.dat1; set(opt.displaybutton, 'string', 'display: var1'); end if isequalwithequalnans(opt.dat,opt.dat1), opt.dat = opt.dat2; set(opt.displaybutton, 'string', 'display: var2'); end end setappdata(h, 'opt', opt); cb_slider(h); case 'control+control' % do nothing case 'shift+shift' % do nothing case 'alt+alt' % do nothing otherwise setappdata(h, 'opt', opt); cb_help(h); end cb_slider(h); uiresume(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = getparent(h) p = h; while p~=0 h = p; p = get(h, 'parent'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key = parseKeyboardEvent(eventdata) key = eventdata.Key; % handle possible numpad events (different for Windows and UNIX systems) % NOTE: shift+numpad number does not work on UNIX, since the shift % modifier is always sent for numpad events if isunix() shiftInd = match_str(eventdata.Modifier, 'shift'); if ~isnan(str2double(eventdata.Character)) && ~isempty(shiftInd) % now we now it was a numpad keystroke (numeric character sent AND % shift modifier present) key = eventdata.Character; eventdata.Modifier(shiftInd) = []; % strip the shift modifier end elseif ispc() if strfind(eventdata.Key, 'numpad') key = eventdata.Character; end end if ~isempty(eventdata.Modifier) key = [eventdata.Modifier{1} '+' key]; end
github
lcnbeapp/beapp-master
ft_sourcedescriptives.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_sourcedescriptives.m
50,287
utf_8
6f54ea734332fd49fc0a7a16e886c4e3
function [source] = ft_sourcedescriptives(cfg, source) % FT_SOURCEDESCRIPTIVES computes descriptive parameters of the source % analysis results. % % Use as % [source] = ft_sourcedescriptives(cfg, source) % % where cfg is a structure with the configuration details and source is the % result from a beamformer source estimation. The configuration can contain % cfg.cohmethod = 'regular', 'lambda1', 'canonical' % cfg.powmethod = 'regular', 'lambda1', 'trace', 'none' % cfg.supmethod = 'chan_dip', 'chan', 'dip', 'none' (default) % cfg.projectmom = 'yes' or 'no' (default = 'no') % cfg.eta = 'yes' or 'no' (default = 'no') % cfg.kurtosis = 'yes' or 'no' (default = 'no') % cfg.keeptrials = 'yes' or 'no' (default = 'no') % cfg.keepcsd = 'yes' or 'no' (default = 'no') % cfg.keepnoisecsd = 'yes' or 'no' (default = 'no') % cfg.keepmom = 'yes' or 'no' (default = 'yes') % cfg.keepnoisemom = 'yes' or 'no' (default = 'yes') % cfg.resolutionmatrix = 'yes' or 'no' (default = 'no') % cfg.feedback = 'no', 'text' (default), 'textbar', 'gui' % % The following option only applies to LCMV single-trial timecourses. % cfg.fixedori = 'within_trials' or 'over_trials' (default = 'over_trials') % % If repeated trials are present that have undergone some sort of % resampling (i.e. jackknife, bootstrap, singletrial or rawtrial), the mean, % variance and standard error of mean will be computed for all source % parameters. This is done after applying the optional transformation % on the power and projected noise. % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % cfg.outputfile = ... % If you specify one of these (or both) the input data will be read from a *.mat % file on disk and/or the output data will be written to a *.mat file. These mat % files should contain only a single variable, corresponding with the % input/output structure. % % See also FT_SOURCEANALYSIS, FT_SOURCESTATISTICS, FT_MATH % Copyright (C) 2004-2015, Robert Oostenveld & Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar source ft_preamble provenance source ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input data is valid for this function % source = ft_checkdata(source, 'datatype', 'source', 'feedback', 'yes'); cfg = ft_checkconfig(cfg, 'forbidden', {'trials'}); % trial selection is not implented here, you may want to consider ft_selectdata % DEPRECATED by roboos on 13 June 2013 % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=2199 for more details % support for this functionality can be removed at the end of 2013 cfg = ft_checkconfig(cfg, 'deprecated', {'transform'}); % please use ft_math instead % set the defaults cfg.transform = ft_getopt(cfg, 'transform', []); cfg.projectmom = ft_getopt(cfg, 'projectmom', 'no');% if yes -> svdfft cfg.numcomp = ft_getopt(cfg, 'numcomp', 1); cfg.powmethod = ft_getopt(cfg, 'powmethod', []);% see below cfg.cohmethod = ft_getopt(cfg, 'cohmethod', []);% see below cfg.feedback = ft_getopt(cfg, 'feedback', 'textbar'); cfg.supmethod = ft_getopt(cfg, 'supmethod', 'none'); cfg.resolutionmatrix = ft_getopt(cfg, 'resolutionmatrix', 'no'); cfg.eta = ft_getopt(cfg, 'eta', 'no'); cfg.fa = ft_getopt(cfg, 'fa', 'no'); cfg.kurtosis = ft_getopt(cfg, 'kurtosis', 'no'); cfg.keeptrials = ft_getopt(cfg, 'keeptrials', 'no'); cfg.keepcsd = ft_getopt(cfg, 'keepcsd', 'no'); cfg.keepmom = ft_getopt(cfg, 'keepmom', 'yes'); cfg.keepnoisecsd = ft_getopt(cfg, 'keepnoisecsd', 'no'); cfg.keepnoisemom = ft_getopt(cfg, 'keepnoisemom', 'yes'); cfg.fwhm = ft_getopt(cfg, 'fwhm', 'no'); cfg.fwhmremovecenter = ft_getopt(cfg, 'fwhmremovecenter', 0); cfg.fwhmmethod = ft_getopt(cfg, 'fwhmmethod', 'barnes'); cfg.fwhmmaxdist = ft_getopt(cfg, 'fwhmmaxdist', []); cfg.fixedori = ft_getopt(cfg, 'fixedori', 'over_trials'); % only works for minimumnormestimate cfg.demean = ft_getopt(cfg, 'demean', 'yes'); cfg.baselinewindow = ft_getopt(cfg, 'baselinewindow', [-inf 0]); cfg.zscore = ft_getopt(cfg, 'zscore', 'yes'); zscore = strcmp(cfg.zscore, 'yes'); demean = strcmp(cfg.demean, 'yes'); % get desired method from source structure source.method = ft_getopt(source,'method',[]); % this is required for backward compatibility with the old sourceanalysis if isfield(source, 'method') && strcmp(source.method, 'randomized') source.method = 'randomization'; elseif isfield(source, 'method') && strcmp(source.method, 'permuted') source.method = 'permutation'; elseif isfield(source, 'method') && strcmp(source.method, 'jacknife') source.method = 'jackknife'; end % determine the type of data, this is only relevant for a few specific types ispccdata = isfield(source, 'avg') && isfield(source.avg, 'csdlabel'); islcmvavg = isfield(source, 'avg') && isfield(source, 'time') && isfield(source.avg, 'mom') && any(size(source.avg.pow)==1); islcmvtrl = isfield(source, 'trial') && isfield(source, 'time') && isfield(source.trial, 'mom'); ismneavg = isfield(source, 'avg') && isfield(source, 'time') && isfield(source.avg, 'mom') && size(source.avg.pow, 2)==numel(source.time); % check the consistency of the defaults if strcmp(cfg.projectmom, 'yes') if isempty(cfg.powmethod) cfg.powmethod = 'regular'; % set the default elseif ~strcmp(cfg.powmethod, 'regular') error('unsupported powmethod in combination with projectmom'); end if isempty(cfg.cohmethod) cfg.cohmethod = 'regular';% set the default elseif ~strcmp(cfg.cohmethod, 'regular') error('unsupported cohmethod in combination with projectmom'); end else if isempty(cfg.powmethod) cfg.powmethod = 'lambda1'; % set the default end if isempty(cfg.cohmethod) cfg.cohmethod = 'lambda1'; % set the default end end % this is required for backward compatibility with an old version of sourcedescriptives if isfield(cfg, 'singletrial'), cfg.keeptrials = cfg.singletrial; end % do a validity check on the input data and specified options if strcmp(cfg.resolutionmatrix, 'yes') if ~isfield(source.avg, 'filter') error('The computation of the resolution matrix requires keepfilter=''yes'' in sourceanalysis.'); elseif ~isfield(source, 'leadfield') error('The computation of the resolution matrix requires keepleadfield=''yes'' in sourceanalysis.'); end end if strcmp(cfg.fwhm, 'yes') if ~isfield(source.avg, 'filter') error('The computation of the fwhm requires keepfilter=''yes'' in sourceanalysis.'); end end if strcmp(cfg.eta, 'yes') && strcmp(cfg.cohmethod, 'svdfft'), error('eta cannot be computed in combination with the application of svdfft'); end if strcmp(cfg.keeptrials, 'yes') && ~strcmp(cfg.supmethod, 'none'), error('you cannot keep trials when you want to partialize something'); end % set some flags for convenience isnoise = isfield(source, 'avg') && isfield(source.avg, 'noisecsd'); keeptrials = strcmp(cfg.keeptrials, 'yes'); projectmom = strcmp(cfg.projectmom, 'yes'); % determine the subfunction used for computing power switch cfg.powmethod case 'regular' powmethodfun = @powmethod_regular; case 'lambda1' powmethodfun = @powmethod_lambda1; case 'trace' powmethodfun = @powmethod_trace; case 'none' powmethodfun = []; otherwise error('unsupported powmethod'); end % represent the selection of sources in the brain as a row-vector with indices insideindx = find(source.inside(:)'); if ispccdata % the source reconstruction was computed using the pcc beamformer Ndipole = size(source.pos,1); if ischar(source.avg.csdlabel{1}), source.avg.csdlabel = {source.avg.csdlabel}; end if numel(source.avg.csdlabel)==1, source.avg.csdlabel = repmat(source.avg.csdlabel, [Ndipole 1]); end dipsel = find(strcmp(source.avg.csdlabel{1}, 'scandip')); refchansel = find(strcmp(source.avg.csdlabel{1}, 'refchan')); refdipsel = find(strcmp(source.avg.csdlabel{1}, 'refdip')); supchansel = find(strcmp(source.avg.csdlabel{1}, 'supchan')); supdipsel = find(strcmp(source.avg.csdlabel{1}, 'supdip')); % cannot handle reference channels and reference dipoles simultaneously if numel(refchansel)>0 && numel(refdipsel)>0 error('cannot simultaneously handle reference channels and reference dipole'); end % these are only used to count the number of reference/suppression dipoles and channels refsel = [refdipsel refchansel]; supsel = [supdipsel supchansel]; % first do the projection of the moment, if requested if projectmom source.avg.ori = cell(1, Ndipole); ft_progress('init', cfg.feedback, 'projecting dipole moment'); for i=insideindx ft_progress(i/length(insideindx), 'projecting dipole moment %d/%d\n', i, length(insideindx)); if numel(source.avg.csdlabel)>1, dipsel = find(strcmp(source.avg.csdlabel{i}, 'scandip')); refchansel = find(strcmp(source.avg.csdlabel{i}, 'refchan')); refdipsel = find(strcmp(source.avg.csdlabel{i}, 'refdip')); supchansel = find(strcmp(source.avg.csdlabel{i}, 'supchan')); supdipsel = find(strcmp(source.avg.csdlabel{i}, 'supdip')); % these are only used to count the number of reference/suppression dipoles and channels refsel = [refdipsel refchansel]; supsel = [supdipsel supchansel]; end mom = source.avg.mom{i}(dipsel, :); ref = source.avg.mom{i}(refdipsel, :); sup = source.avg.mom{i}(supdipsel, :); refchan = source.avg.mom{i}(refchansel, :); supchan = source.avg.mom{i}(supchansel, :); % compute the projection of the scanning dipole along the direction of the dominant amplitude if length(dipsel)>1, [mom, rmom] = svdfft(mom, cfg.numcomp, source.cumtapcnt); else rmom = []; end source.avg.ori{i} = rmom; % compute the projection of the reference dipole along the direction of the dominant amplitude if length(refdipsel)>1, [ref, rref] = svdfft(ref, 1, source.cumtapcnt); else rref = []; end % compute the projection of the supression dipole along the direction of the dominant amplitude if length(supdipsel)>1, [sup, rsup] = svdfft(sup, 1, source.cumtapcnt); else rsup = []; end % compute voxel-level fourier-matrix source.avg.mom{i} = cat(1, mom, ref, sup, refchan, supchan); % create rotation-matrix rotmat = zeros(0, length(source.avg.csdlabel{i})); if ~isempty(rmom), rotmat = [rotmat; rmom zeros(numel(refsel)+numel(supsel),1)]; end if ~isempty(rref), rotmat = [rotmat; zeros(1, numel(dipsel)), rref, zeros(1,numel(refchansel)+numel(supsel))]; end if ~isempty(rsup), rotmat = [rotmat; zeros(1, numel(dipsel)+numel(refdipsel)), rsup, zeros(1,numel(refchansel)+numel(supchansel))]; end for j=1:length(supchansel) rotmat(end+1,:) = 0; rotmat(end,numel(dipsel)+numel(refdipsel)+numel(supdipsel)+j) = 1; end for j=1:length(refchansel) rotmat(end+1,:) = 0; rotmat(end,numel(dipsel)+numel(refdipsel)+numel(supdipsel)+numel(supchansel)+j) = 1; end % compute voxel-level csd-matrix if isfield(source.avg, 'csd'), source.avg.csd{i} = rotmat * source.avg.csd{i} * rotmat'; end % compute voxel-level noisecsd-matrix if isfield(source.avg, 'noisecsd'), source.avg.noisecsd{i} = rotmat * source.avg.noisecsd{i} * rotmat'; end % compute rotated filter if isfield(source.avg, 'filter'), source.avg.filter{i} = rotmat * source.avg.filter{i}; end if isfield(source.avg, 'csdlabel'), % remember what the interpretation is of all CSD output components scandiplabel = repmat({'scandip'}, 1, cfg.numcomp); % only one dipole orientation remains refdiplabel = repmat({'refdip'}, 1, length(refdipsel)>0); % for svdfft at max. only one dipole orientation remains supdiplabel = repmat({'supdip'}, 1, length(supdipsel)>0); % for svdfft at max. only one dipole orientation remains refchanlabel = repmat({'refchan'}, 1, length(refchansel)); supchanlabel = repmat({'supchan'}, 1, length(supchansel)); % concatenate all the labels source.avg.csdlabel{i} = cat(2, scandiplabel, refdiplabel, supdiplabel, refchanlabel, supchanlabel); end % compute rotated leadfield % FIXME in the presence of a refdip and/or supdip, this does not work; leadfield is Nx3 if isfield(source, 'leadfield'), %FIXME this is a proposed dirty fix n1 = size(source.leadfield{i},2); %n2 = size(rotmat,2) - n1; n2 = size(rotmat,2) - n1 +1; %added 1 JM source.leadfield{i} = source.leadfield{i} * rotmat(1:n2, 1:n1)'; end end % for i=insideindx ft_progress('close'); % update the indices dipsel = find(strcmp(source.avg.csdlabel, 'scandip')); refchansel = find(strcmp(source.avg.csdlabel, 'refchan')); refdipsel = find(strcmp(source.avg.csdlabel, 'refdip')); supchansel = find(strcmp(source.avg.csdlabel, 'supchan')); supdipsel = find(strcmp(source.avg.csdlabel, 'supdip')); refsel = [refdipsel refchansel]; supsel = [supdipsel supchansel]; end % if projectmom if keeptrials cumtapcnt = source.cumtapcnt(:); sumtapcnt = cumsum([0;cumtapcnt]); Ntrial = length(cumtapcnt); ft_progress('init', cfg.feedback, 'computing singletrial voxel-level cross-spectral densities'); for triallop = 1:Ntrial source.trial(triallop).csd = cell(Ndipole, 1); % allocate memory for this trial source.trial(triallop).mom = cell(Ndipole, 1); % allocate memory for this trial ft_progress(triallop/Ntrial, 'computing singletrial voxel-level cross-spectral densities %d%d\n', triallop, Ntrial); for i=insideindx dat = source.avg.mom{i}; tmpmom = dat(:, sumtapcnt(triallop)+1:sumtapcnt(triallop+1)); tmpcsd = (tmpmom * tmpmom') ./cumtapcnt(triallop); source.trial(triallop).mom{i} = tmpmom; source.trial(triallop).csd{i} = tmpcsd; end % for i=insideindx end % for triallop ft_progress('close'); % remove the average, continue with separate trials, but keep track of % the csdlabel csdlabel = source.avg.csdlabel; source = rmfield(source, 'avg'); else fprintf('using average voxel-level cross-spectral densities\n'); csdlabel = source.avg.csdlabel; end % if keeptrials % process the csdlabel for each of the dipoles hasrefdip = true; hasrefchan = true; hassupdip = true; hassupchan = true; dipselcell = cell(Ndipole,1); refdipselcell = cell(Ndipole,1); refchanselcell = cell(Ndipole,1); supdipselcell = cell(Ndipole,1); supchanselcell = cell(Ndipole,1); for i = insideindx dipsel = find(strcmp(csdlabel{i}, 'scandip')); refchansel = find(strcmp(csdlabel{i}, 'refchan')); refdipsel = find(strcmp(csdlabel{i}, 'refdip')); supchansel = find(strcmp(csdlabel{i}, 'supchan')); supdipsel = find(strcmp(csdlabel{i}, 'supdip')); hasrefdip = ~isempty(refdipsel) && hasrefdip; %NOTE: it has to be true for all dipoles! hasrefchan = ~isempty(refchansel) && hasrefchan; hassupdip = ~isempty(supdipsel) && hassupdip; hassupchan = ~isempty(supchansel) && hassupchan; dipselcell{i} = dipsel; refdipselcell{i} = refdipsel; refchanselcell{i} = refchansel; supdipselcell{i} = supdipsel; supchanselcell{i} = supchansel; end if keeptrials % do the processing of the CSD matrices for each trial if ~strcmp(cfg.supmethod, 'none') error('suppression is only supported for average CSD'); end %dipselcell = mat2cell(repmat(dipsel(:)', [Ndipole 1]), ones(Ndipole,1), length(dipsel)); %if hasrefdip, refdipselcell = mat2cell(repmat(refdipsel(:)', [Ndipole 1]), ones(Ndipole,1), length(refdipsel)); end %if hasrefchan, refchanselcell = mat2cell(repmat(refchansel(:)', [Ndipole 1]), ones(Ndipole,1), length(refchansel)); end %if hassupdip, supdipselcell = mat2cell(repmat(supdipsel(:)', [Ndipole 1]), ones(Ndipole,1), length(supdipsel)); end %if hassupchan, supchanselcell = mat2cell(repmat(supchansel(:)', [Ndipole 1]), ones(Ndipole,1), length(supchansel)); end ft_progress('init', cfg.feedback, 'computing singletrial voxel-level power'); for triallop = 1:Ntrial %initialize the variables source.trial(triallop).pow = zeros(Ndipole, 1); if hasrefdip, source.trial(triallop).refdippow = zeros(Ndipole, 1); end if hasrefchan, source.trial(triallop).refchanpow = zeros(Ndipole, 1); end if hassupdip, source.trial(triallop).supdippow = zeros(Ndipole, 1); end if hassupchan, source.trial(triallop).supchanpow = zeros(Ndipole, 1); end ft_progress(triallop/Ntrial, 'computing singletrial voxel-level power %d%d\n', triallop, Ntrial); source.trial(triallop).pow(source.inside) = cellfun(powmethodfun, source.trial(triallop).csd(source.inside), dipselcell(source.inside)); if hasrefdip, source.trial(triallop).refdippow(source.inside) = cellfun(powmethodfun,source.trial(triallop).csd(source.inside), refdipselcell(source.inside)); end if hassupdip, source.trial(triallop).supdippow(source.inside) = cellfun(powmethodfun,source.trial(triallop).csd(source.inside), supdipselcell(source.inside)); end if hasrefchan, source.trial(triallop).refchanpow(source.inside) = cellfun(powmethodfun,source.trial(triallop).csd(source.inside), refchanselcell(source.inside)); end if hassupchan, source.trial(triallop).supchanpow(source.inside) = cellfun(powmethodfun,source.trial(triallop).csd(source.inside), supchanselcell(source.inside)); end %FIXME kan volgens mij niet if isnoise && isfield(source.trial(triallop), 'noisecsd'), % compute the power of the noise projected on each source component source.trial(triallop).noise = cellfun(powmethodfun,source.trial(triallop).csd, dipselcell); if hasrefdip, source.trial(triallop).refdipnoise = cellfun(powmethodfun,source.trial(triallop).noisecsd, refdipselcell); end if hassupdip, source.trial(triallop).supdipnoise = cellfun(powmethodfun,source.trial(triallop).noisecsd, supdipselcell); end if hasrefchan, source.trial(triallop).refchannoise = cellfun(powmethodfun,source.trial(triallop).noisecsd, refchanselcell); end if hassupchan, source.trial(triallop).supchannoise = cellfun(powmethodfun,source.trial(triallop).noisecsd, supchanselcell); end end % if isnoise end % for triallop ft_progress('close'); if strcmp(cfg.keepcsd, 'no') source.trial = rmfield(source.trial, 'csd'); end else % do the processing of the average CSD matrix for i=insideindx switch cfg.supmethod case 'chan_dip' supindx = [supdipsel supchansel]; if i==insideindx(1), refsel = refsel - length(supdipsel); end % adjust index only once case 'chan' supindx = supchansel; case 'dip' supindx = supdipsel; if i==insideindx(1), refsel = refsel - length(supdipsel); end case 'none' % do nothing supindx = []; end tmpcsd = source.avg.csd{i}; scnindx = setdiff(1:size(tmpcsd,1), supindx); tmpcsd = tmpcsd(scnindx, scnindx) - tmpcsd(scnindx, supindx)*pinv(tmpcsd(supindx, supindx))*tmpcsd(supindx, scnindx); source.avg.csd{i} = tmpcsd; end % for i=insideindx % source.avg.csdlabel = source.avg.csdlabel(scnindx); if isnoise && ~strcmp(cfg.supmethod, 'none') source.avg = rmfield(source.avg, 'noisecsd'); end % initialize the variables source.avg.pow = nan(Ndipole, 1); if hasrefdip, source.avg.refdippow = nan(Ndipole, 1); end if hasrefchan, source.avg.refchanpow = nan(Ndipole, 1); end if hassupdip, source.avg.supdippow = nan(Ndipole, 1); end if hassupchan, source.avg.supchanpow = nan(Ndipole, 1); end if isnoise source.avg.noise = nan(Ndipole, 1); if hasrefdip, source.avg.refdipnoise = nan(Ndipole, 1); end if hasrefchan, source.avg.refchannoise = nan(Ndipole, 1); end if hassupdip, source.avg.supdipnoise = nan(Ndipole, 1); end if hassupchan, source.avg.supchannoise = nan(Ndipole, 1); end end % if isnoise if hasrefdip||hasrefchan, source.avg.coh = nan(Ndipole, 1); end if strcmp(cfg.eta, 'yes'), source.avg.eta = nan(Ndipole, 1); source.avg.ori = cell(1, Ndipole); end if strcmp(cfg.eta, 'yes') && ~isempty(refsel), source.avg.etacsd = nan(Ndipole, 1); source.avg.ucsd = cell(1, Ndipole); end if strcmp(cfg.fa, 'yes'), source.avg.fa = nan(Ndipole, 1); end for i=insideindx dipsel = dipselcell{i}; refsel = [refchanselcell{i} refdipselcell{i}]; % compute the power of each source component if strcmp(cfg.projectmom, 'yes') && cfg.numcomp>1, source.avg.pow(i) = powmethodfun(source.avg.csd{i}(dipselcell{i},dipselcell{i}), 1); else source.avg.pow(i) = powmethodfun(source.avg.csd{i}(dipselcell{i},dipselcell{i})); end if hasrefdip, source.avg.refdippow(i) = powmethodfun(source.avg.csd{i}(refdipsel,refdipsel)); end if hassupdip, source.avg.supdippow(i) = powmethodfun(source.avg.csd{i}(supdipsel,supdipsel)); end if hasrefchan, source.avg.refchanpow(i) = powmethodfun(source.avg.csd{i}(refchansel,refchansel)); end if hassupchan, source.avg.supchanpow(i) = powmethodfun(source.avg.csd{i}(supchansel,supchansel)); end if isnoise % compute the power of the noise projected on each source component if strcmp(cfg.projectmom, 'yes') && cfg.numcomp>1, source.avg.noise(i) = powmethodfun(source.avg.noisecsd{i}(dipselcell{i},dipselcell{i}), 1); else source.avg.noise(i) = powmethodfun(source.avg.noisecsd{i}(dipselcell{i},dipselcell{i})); end if hasrefdip, source.avg.refdipnoise(i) = powmethodfun(source.avg.noisecsd{i}(refdipsel,refdipsel)); end if hassupdip, source.avg.supdipnoise(i) = powmethodfun(source.avg.noisecsd{i}(supdipsel,supdipsel)); end if hasrefchan, source.avg.refchannoise(i) = powmethodfun(source.avg.noisecsd{i}(refchansel,refchansel)); end if hassupchan, source.avg.supchannoise(i) = powmethodfun(source.avg.noisecsd{i}(supchansel,supchansel)); end end % if isnoise if ~isempty(refsel) % compute coherence csd = source.avg.csd{i}; switch cfg.cohmethod case 'regular' % assume that all dipoles have been projected along the direction of maximum power Pd = abs(csd(dipsel, dipsel)); Pr = abs(csd(refsel, refsel)); Cdr = csd(dipsel, refsel); source.avg.coh(i) = (Cdr.^2) ./ (Pd*Pr); case 'lambda1' %compute coherence on Joachim Gross' way Pd = lambda1(csd(dipsel, dipsel)); Pr = lambda1(csd(refsel, refsel)); Cdr = lambda1(csd(dipsel, refsel)); source.avg.coh(i) = abs(Cdr).^2 ./ (Pd*Pr); case 'canonical' [ccoh, c2, v1, v2] = cancorr(csd, dipsel, refsel); [cmax, indmax] = max(ccoh); source.avg.coh(i) = ccoh(indmax); otherwise error('unsupported cohmethod'); end % cohmethod end % compute eta if strcmp(cfg.eta, 'yes') [source.avg.eta(i), source.avg.ori{i}] = csd2eta(source.avg.csd{i}(dipselcell{i},dipselcell{i})); if ~isempty(refsel), %FIXME this only makes sense when only a reference signal OR a dipole is selected [source.avg.etacsd(i), source.avg.ucsd{i}] = csd2eta(source.avg.csd{i}(dipsel,refsel)); end end %compute fa if strcmp(cfg.fa, 'yes') source.avg.fa(i) = csd2fa(source.avg.csd{i}(dipsel,dipsel)); end end % for diplop if strcmp(cfg.keepcsd, 'no') source.avg = rmfield(source.avg, 'csd'); end if strcmp(cfg.keepnoisecsd, 'no') && isnoise source.avg = rmfield(source.avg, 'noisecsd'); end end elseif ismneavg %the source reconstruction was computed using the minimumnormestimate and contains an average timecourse if demean begsmp = nearest(source.time, cfg.baselinewindow(1)); endsmp = nearest(source.time, cfg.baselinewindow(2)); ft_progress('init', cfg.feedback, 'baseline correcting dipole moments'); for diplop=1:length(insideindx) ft_progress(diplop/length(insideindx), 'baseline correcting dipole moments %d/%d\n', diplop, length(insideindx)); mom = source.avg.mom{insideindx(diplop)}; mom = ft_preproc_baselinecorrect(mom, begsmp, endsmp); source.avg.mom{insideindx(diplop)} = mom; end ft_progress('close'); end if projectmom if isfield(source, 'tri') nrm = normals(source.pos, source.tri, 'vertex'); source.avg.phi = zeros(size(source.pos,1),1); end ft_progress('init', cfg.feedback, 'projecting dipole moment'); for diplop=1:length(insideindx) ft_progress(diplop/length(insideindx), 'projecting dipole moment %d/%d\n', diplop, length(insideindx)); mom = source.avg.mom{insideindx(diplop)}; [mom, rmom] = svdfft(mom, 1); source.avg.mom{insideindx(diplop)} = mom; source.avg.ori{insideindx(diplop)} = rmom; end if isfield(source, 'tri') for diplop=insideindx source.avg.phi(diplop) = source.avg.ori{diplop}*nrm(diplop,:)'; end end if isfield(source.avg, 'noisecov') source.avg.noise = nan+zeros(size(source.pos,1),1); for diplop=insideindx rmom = source.avg.ori{diplop}; source.avg.noise(diplop) = rmom*source.avg.noisecov{diplop}*rmom'; end end ft_progress('close'); end if zscore begsmp = nearest(source.time, cfg.baselinewindow(1)); endsmp = nearest(source.time, cfg.baselinewindow(2)); % zscore using baselinewindow for power ft_progress('init', cfg.feedback, 'computing power'); %source.avg.absmom = source.avg.pow; for diplop=1:length(insideindx) ft_progress(diplop/length(insideindx), 'computing power %d/%d\n', diplop, length(insideindx)); mom = source.avg.mom{insideindx(diplop)}; mmom = mean(mom(:,begsmp:endsmp),2); smom = std(mom(:,begsmp:endsmp),[],2); pow = sum(((mom-mmom(:,ones(size(mom,2),1)))./smom(:,ones(size(mom,2),1))).^2,1); source.avg.pow(insideindx(diplop),:) = pow; %source.avg.absmom(source.inside(diplop),:) = sum((mom-mmom)./smom,1); end ft_progress('close'); else % just square for power ft_progress('init', cfg.feedback, 'computing power'); %source.avg.absmom = source.avg.pow; for diplop=1:length(insideindx) ft_progress(diplop/length(insideindx), 'computing power %d/%d\n', diplop, length(insideindx)); mom = source.avg.mom{insideindx(diplop)}; pow = sum(mom.^2,1); source.avg.pow(insideindx(diplop),:) = pow; %source.avg.absmom(insideindx(diplop),:) = sum(mom,1); end ft_progress('close'); end if strcmp(cfg.kurtosis, 'yes') fprintf('computing kurtosis based on dipole timecourse\n'); source.avg.k2 = nan(size(source.pos,1),1); for diplop=1:length(insideindx) mom = source.avg.mom{insideindx(diplop)}; if length(mom)~=prod(size(mom)) error('kurtosis can only be computed for projected dipole moment'); end source.avg.k2(insideindx(diplop)) = kurtosis(mom); end end elseif islcmvavg % the source reconstruction was computed using the lcmv beamformer and contains an average timecourse if projectmom ft_progress('init', cfg.feedback, 'projecting dipole moment'); for diplop=1:length(insideindx) ft_progress(diplop/length(insideindx), 'projecting dipole moment %d/%d\n', diplop, length(insideindx)); mom = source.avg.mom{insideindx(diplop)}; [mom, rmom] = svdfft(mom, 1); source.avg.mom{insideindx(diplop)} = mom; source.avg.ori{insideindx(diplop)} = rmom; end ft_progress('close'); end if ~strcmp(cfg.powmethod, 'none') fprintf('recomputing power based on dipole timecourse\n') source.avg.pow = nan(size(source.pos,1),1); for diplop=1:length(insideindx) mom = source.avg.mom{insideindx(diplop)}; cov = mom * mom'; source.avg.pow(insideindx(diplop)) = powmethodfun(cov); end end if strcmp(cfg.kurtosis, 'yes') fprintf('computing kurtosis based on dipole timecourse\n'); source.avg.k2 = nan(size(source.pos,1),1); for diplop=1:length(insideindx) mom = source.avg.mom{insideindx(diplop)}; if length(mom)~=prod(size(mom)) error('kurtosis can only be computed for projected dipole moment'); end source.avg.k2(insideindx(diplop)) = kurtosis(mom); end end elseif islcmvtrl % the source reconstruction was computed using the lcmv beamformer and contains a single-trial timecourse ntrial = length(source.trial); if projectmom && strcmp(cfg.fixedori, 'within_trials') % the dipole orientation is re-determined for each trial ft_progress('init', cfg.feedback, 'projecting dipole moment'); for trllop=1:ntrial ft_progress(trllop/ntrial, 'projecting dipole moment %d/%d\n', trllop, ntrial); for diplop=1:length(insideindx) mom = source.trial(trllop).mom{insideindx(diplop)}; [mom, rmom] = svdfft(mom, 1); source.trial(trllop).mom{insideindx(diplop)} = mom; source.trial(trllop).ori{insideindx(diplop)} = rmom; % remember the orientation end end ft_progress('close'); elseif projectmom && strcmp(cfg.fixedori, 'over_trials') ft_progress('init', cfg.feedback, 'projecting dipole moment'); % compute average covariance over all trials for trllop=1:ntrial for diplop=1:length(insideindx) mom = source.trial(trllop).mom{insideindx(diplop)}; if trllop==1 cov{diplop} = mom*mom'./size(mom,2); else cov{diplop} = mom*mom'./size(mom,2) + cov{diplop}; end end end % compute source orientation over all trials for diplop=1:length(insideindx) [dum, ori{diplop}] = svdfft(cov{diplop}, 1); end % project the data in each trial for trllop=1:ntrial ft_progress(trllop/ntrial, 'projecting dipole moment %d/%d\n', trllop, ntrial); for diplop=1:length(insideindx) mom = source.trial(trllop).mom{insideindx(diplop)}; mom = ori{diplop}*mom; source.trial(trllop).mom{insideindx(diplop)} = mom; source.trial(trllop).ori{insideindx(diplop)} = ori{diplop}; end end ft_progress('close'); end if ~strcmp(cfg.powmethod, 'none') fprintf('recomputing power based on dipole timecourse\n') for trllop=1:ntrial for diplop=1:length(insideindx) mom = source.trial(trllop).mom{insideindx(diplop)}; cov = mom * mom'; source.trial(trllop).pow(insideindx(diplop)) = powmethodfun(cov); end end end if strcmp(cfg.kurtosis, 'yes') fprintf('computing kurtosis based on dipole timecourse\n'); for trllop=1:ntrial source.trial(trllop).k2 = nan(size(source.pos,1),1); for diplop=1:length(insideindx) mom = source.trial(trllop).mom{insideindx(diplop)}; if length(mom)~=numel(mom) error('kurtosis can only be computed for projected dipole moment'); end source.trial(trllop).k2(insideindx(diplop)) = kurtosis(mom); end end end end % dealing with pcc or lcmv input if isfield(source, 'avg') && isfield(source.avg, 'pow') && isfield(source.avg, 'noise') && ~ismneavg % compute the neural activity index for the average source.avg.nai = source.avg.pow(:) ./ source.avg.noise(:); end if isfield(source, 'trial') && isfield(source.trial, 'pow') && isfield(source.trial, 'noise') % compute the neural activity index for the trials ntrials = length(source.trial); for trlop=1:ntrials source.trial(trlop).nai = source.trial(trlop).pow ./ source.trial(trlop).noise; end end if strcmp(source.method, 'randomization') || strcmp(source.method, 'permutation') % compute the neural activity index for the two randomized conditions source.avgA.nai = source.avgA.pow ./ source.avgA.noise; source.avgB.nai = source.avgB.pow ./ source.avgB.noise; for trlop=1:length(source.trialA) source.trialA(trlop).nai = source.trialA(trlop).pow ./ source.trialA(trlop).noise; end for trlop=1:length(source.trialB) source.trialB(trlop).nai = source.trialB(trlop).pow ./ source.trialB(trlop).noise; end end if ~isempty(cfg.transform) fprintf('applying %s transformation on the power and projected noise\n', cfg.transform); % apply the specified transformation on the power if isfield(source, 'avg' ) && isfield(source.avg , 'pow'), source.avg .pow = feval(cfg.transform, source.avg .pow); end if isfield(source, 'avgA' ) && isfield(source.avgA , 'pow'), source.avgA.pow = feval(cfg.transform, source.avgA.pow); end if isfield(source, 'avgB' ) && isfield(source.avgB , 'pow'), source.avgB.pow = feval(cfg.transform, source.avgB.pow); end if isfield(source, 'trial' ) && isfield(source.trial , 'pow'), for i=1:length(source.trial ), source.trial (i).pow = feval(cfg.transform, source.trial (i).pow); end; end if isfield(source, 'trialA') && isfield(source.trialA, 'pow'), for i=1:length(source.trialA), source.trialA(i).pow = feval(cfg.transform, source.trialA(i).pow); end; end if isfield(source, 'trialB') && isfield(source.trialB, 'pow'), for i=1:length(source.trialB), source.trialB(i).pow = feval(cfg.transform, source.trialB(i).pow); end; end % apply the specified transformation on the projected noise if isfield(source, 'avg' ) && isfield(source.avg , 'noise'), source.avg .noise = feval(cfg.transform, source.avg .noise); end if isfield(source, 'avgA' ) && isfield(source.avgA , 'noise'), source.avgA.noise = feval(cfg.transform, source.avgA.noise); end if isfield(source, 'avgB' ) && isfield(source.avgB , 'noise'), source.avgB.noise = feval(cfg.transform, source.avgB.noise); end if isfield(source, 'trial' ) && isfield(source.trial , 'noise'), for i=1:length(source.trial ), source.trial (i).noise = feval(cfg.transform, source.trial (i).noise); end; end if isfield(source, 'trialA') && isfield(source.trialA, 'noise'), for i=1:length(source.trialA), source.trialA(i).noise = feval(cfg.transform, source.trialA(i).noise); end; end if isfield(source, 'trialB') && isfield(source.trialB, 'noise'), for i=1:length(source.trialB), source.trialB(i).noise = feval(cfg.transform, source.trialB(i).noise); end; end end if strcmp(source.method, 'pseudovalue') % compute the pseudovalues for the beamformer output avg = source.trial(1); % the first is the complete average Ntrials = length(source.trial)-1; % the remaining are the leave-one-out averages pseudoval = []; if isfield(source.trial, 'pow') allavg = getfield(avg, 'pow'); for i=1:Ntrials thisavg = getfield(source.trial(i+1), 'pow'); thisval = Ntrials*allavg - (Ntrials-1)*thisavg; pseudoval(i).pow = thisval; end end if isfield(source.trial, 'coh') allavg = getfield(avg, 'coh'); for i=1:Ntrials thisavg = getfield(source.trial(i+1), 'coh'); thisval = Ntrials*allavg - (Ntrials-1)*thisavg; pseudoval(i).coh = thisval; end end if isfield(source.trial, 'nai') allavg = getfield(avg, 'nai'); for i=1:Ntrials thisavg = getfield(source.trial(i+1), 'nai'); thisval = Ntrials*allavg - (Ntrials-1)*thisavg; pseudoval(i).nai = thisval; end end if isfield(source.trial, 'noise') allavg = getfield(avg, 'noise'); for i=1:Ntrials thisavg = getfield(source.trial(i+1), 'noise'); thisval = Ntrials*allavg - (Ntrials-1)*thisavg; pseudoval(i).noise = thisval; end end % store the pseudovalues instead of the original values source.trial = pseudoval; end if strcmp(source.method, 'jackknife') || strcmp(source.method, 'bootstrap') || strcmp(source.method, 'pseudovalue') || strcmp(source.method, 'singletrial') || strcmp(source.method, 'rawtrial') % compute descriptive statistics (mean, var, sem) for multiple trial data % compute these for as many source parameters as possible % for convenience copy the trials out of the source structure dip = source.trial; % determine the (original) number of trials in the data if strcmp(source.method, 'bootstrap') %VERANDERD ER ZAT GEEN .RESAMPLE IN SOURCE Ntrials = size(source.trial,2);% WAS size(source.resample, 2); else Ntrials = length(source.trial); end fprintf('original data contained %d trials\n', Ntrials); % allocate memory for all elements in the dipole structure sumdip = []; if isfield(dip(1), 'var'), sumdip.var = zeros(size(dip(1).var )); sumdip.var(~source.inside) = nan; end if isfield(dip(1), 'pow'), sumdip.pow = zeros(size(dip(1).pow )); sumdip.pow(~source.inside) = nan; end if isfield(dip(1), 'coh'), sumdip.coh = zeros(size(dip(1).coh )); sumdip.coh(~source.inside) = nan; end if isfield(dip(1), 'rv'), sumdip.rv = zeros(size(dip(1).rv )); sumdip.rv(~source.inside) = nan; end if isfield(dip(1), 'noise'), sumdip.noise = zeros(size(dip(1).noise)); sumdip.noise(~source.inside) = nan; end if isfield(dip(1), 'nai'), sumdip.nai = zeros(size(dip(1).nai )); sumdip.nai(~source.inside) = nan; end sqrdip = []; if isfield(dip(1), 'var'), sqrdip.var = zeros(size(dip(1).var )); sqrdip.var(~source.inside) = nan; end if isfield(dip(1), 'pow'), sqrdip.pow = zeros(size(dip(1).pow )); sqrdip.pow(~source.inside) = nan; end if isfield(dip(1), 'coh'), sqrdip.coh = zeros(size(dip(1).coh )); sqrdip.coh(~source.inside) = nan; end if isfield(dip(1), 'rv'), sqrdip.rv = zeros(size(dip(1).rv )); sqrdip.rv(~source.inside) = nan; end if isfield(dip(1), 'noise'), sqrdip.noise = zeros(size(dip(1).noise)); sqrdip.noise(~source.inside) = nan; end if isfield(dip(1), 'nai'), sqrdip.nai = zeros(size(dip(1).nai )); sqrdip.nai(~source.inside) = nan; end if isfield(dip(1), 'mom') sumdip.mom = cell(size(dip(1).mom)); sqrdip.mom = cell(size(dip(1).mom)); for i=1:length(dip(1).mom) sumdip.mom{i} = zeros(size(dip(1).mom{i})); sqrdip.mom{i} = zeros(size(dip(1).mom{i})); end end if isfield(dip(1), 'csd') sumdip.csd = cell(size(dip(1).csd)); sqrdip.csd = cell(size(dip(1).csd)); for i=1:length(dip(1).csd) sumdip.csd{i} = zeros(size(dip(1).csd{i})); sqrdip.csd{i} = zeros(size(dip(1).csd{i})); end end for trial=1:length(dip) % compute the sum of all values if isfield(dip(trial), 'var'), sumdip.var = sumdip.var + dip(trial).var; end if isfield(dip(trial), 'pow'), sumdip.pow = sumdip.pow + dip(trial).pow; end if isfield(dip(trial), 'coh'), sumdip.coh = sumdip.coh + dip(trial).coh; end if isfield(dip(trial), 'rv'), sumdip.rv = sumdip.rv + dip(trial).rv; end if isfield(dip(trial), 'noise'), sumdip.noise = sumdip.noise + dip(trial).noise; end if isfield(dip(trial), 'nai'), sumdip.nai = sumdip.nai + dip(trial).nai; end % compute the sum of squared values if isfield(dip(trial), 'var'), sqrdip.var = sqrdip.var + (dip(trial).var ).^2; end if isfield(dip(trial), 'pow'), sqrdip.pow = sqrdip.pow + (dip(trial).pow ).^2; end if isfield(dip(trial), 'coh'), sqrdip.coh = sqrdip.coh + (dip(trial).coh ).^2; end if isfield(dip(trial), 'rv'), sqrdip.rv = sqrdip.rv + (dip(trial).rv ).^2; end if isfield(dip(trial), 'noise'), sqrdip.noise = sqrdip.noise + (dip(trial).noise).^2; end if isfield(dip(trial), 'nai'), sqrdip.nai = sqrdip.nai + (dip(trial).nai ).^2; end % do the same for the cell array with mom if isfield(dip(trial), 'mom') for i=1:length(dip(1).mom) sumdip.mom{i} = sumdip.mom{i} + dip(trial).mom{i}; sqrdip.mom{i} = sqrdip.mom{i} + (dip(trial).mom{i}).^2; end end % do the same for the cell array with csd if isfield(dip(trial), 'csd') for i=1:length(dip(1).csd) sumdip.csd{i} = sumdip.csd{i} + dip(trial).csd{i}; sqrdip.csd{i} = sqrdip.csd{i} + (dip(trial).csd{i}).^2; end end end % compute the mean over all repetitions if isfield(sumdip, 'var'), dipmean.var = sumdip.var / length(dip); end if isfield(sumdip, 'pow'), dipmean.pow = sumdip.pow / length(dip); end if isfield(sumdip, 'coh'), dipmean.coh = sumdip.coh / length(dip); end if isfield(sumdip, 'rv'), dipmean.rv = sumdip.rv / length(dip); end if isfield(sumdip, 'noise'), dipmean.noise = sumdip.noise / length(dip); end if isfield(sumdip, 'nai'), dipmean.nai = sumdip.nai / length(dip); end % for the cell array with mom, this is done further below % for the cell array with csd, this is done further below % the estimates for variance and SEM are biased if we are working with the jackknife/bootstrap % determine the proper variance scaling that corrects for this bias % note that Ntrials is not always the same as the length of dip, especially in case of the bootstrap if strcmp(source.method, 'singletrial') bias = 1; elseif strcmp(source.method, 'rawtrial') bias = 1; elseif strcmp(source.method, 'jackknife') % Effron gives SEM estimate for the jackknife method in equation 11.5 (paragraph 11.2) % to get the variance instead of SEM, we also have to multiply with the number of trials bias = (Ntrials - 1)^2; elseif strcmp(source.method, 'bootstrap') % Effron gives SEM estimate for the bootstrap method in algorithm 6.1 (equation 6.6) % to get the variance instead of SEM, we also have to multiply with the number of trials bias = Ntrials; elseif strcmp(source.method, 'pseudovalue') % note that I have not put any thought in this aspect yet warning('don''t know how to compute bias for pseudovalue resampling'); bias = 1; end % compute the variance over all repetitions if isfield(sumdip, 'var'), dipvar.var = bias*(sqrdip.var - (sumdip.var .^2)/length(dip))/(length(dip)-1); end if isfield(sumdip, 'pow'), dipvar.pow = bias*(sqrdip.pow - (sumdip.pow .^2)/length(dip))/(length(dip)-1); end if isfield(sumdip, 'coh'), dipvar.coh = bias*(sqrdip.coh - (sumdip.coh .^2)/length(dip))/(length(dip)-1); end if isfield(sumdip, 'rv' ), dipvar.rv = bias*(sqrdip.rv - (sumdip.rv .^2)/length(dip))/(length(dip)-1); end if isfield(sumdip, 'noise' ), dipvar.noise = bias*(sqrdip.noise - (sumdip.noise .^2)/length(dip))/(length(dip)-1); end if isfield(sumdip, 'nai' ), dipvar.nai = bias*(sqrdip.nai - (sumdip.nai .^2)/length(dip))/(length(dip)-1); end % compute the SEM over all repetitions if isfield(sumdip, 'var'), dipsem.var = (dipvar.var /Ntrials).^0.5; end if isfield(sumdip, 'pow'), dipsem.pow = (dipvar.pow /Ntrials).^0.5; end if isfield(sumdip, 'coh'), dipsem.coh = (dipvar.coh /Ntrials).^0.5; end if isfield(sumdip, 'rv' ), dipsem.rv = (dipvar.rv /Ntrials).^0.5; end if isfield(sumdip, 'noise' ), dipsem.noise = (dipvar.noise /Ntrials).^0.5; end if isfield(sumdip, 'nai' ), dipsem.nai = (dipvar.nai /Ntrials).^0.5; end % compute the mean and SEM over all repetitions for the cell array with mom if isfield(dip(trial), 'mom') for i=1:length(dip(1).mom) dipmean.mom{i} = sumdip.mom{i}/length(dip); dipvar.mom{i} = bias*(sqrdip.mom{i} - (sumdip.mom{i}.^2)/length(dip))/(length(dip)-1); dipsem.mom{i} = (dipvar.mom{i}/Ntrials).^0.5; end end % compute the mean and SEM over all repetitions for the cell array with csd if isfield(dip(trial), 'csd') for i=1:length(dip(1).csd) dipmean.csd{i} = sumdip.csd{i}/length(dip); dipvar.csd{i} = bias*(sqrdip.csd{i} - (sumdip.csd{i}.^2)/length(dip))/(length(dip)-1); dipsem.csd{i} = (dipvar.csd{i}/Ntrials).^0.5; end end if strcmp(source.method, 'pseudovalue') % keep the trials, since they have been converted to pseudovalues % and hence the trials contain the interesting data elseif keeptrials % keep the trials upon request else % remove the original trials source = rmfield(source, 'trial'); % assign the descriptive statistics to the output source structure source.avg = dipmean; source.var = dipvar; source.sem = dipsem; end end if strcmp(cfg.resolutionmatrix, 'yes') % this is only implemented for pcc and no refdips/chans at the moment Nchan = size(source.leadfield{insideindx(1)}, 1); Ninside = length(insideindx); allfilter = zeros(Ninside,Nchan); allleadfield = zeros(Nchan,Ninside); dipsel = match_str(source.avg.csdlabel, 'scandip'); ft_progress('init', cfg.feedback, 'computing resolution matrix'); for diplop=1:length(insideindx) ft_progress(diplop/length(insideindx), 'computing resolution matrix %d/%d\n', diplop, length(insideindx)); % concatenate all filters allfilter(diplop,:) = source.avg.filter{insideindx(diplop)}(dipsel,:); % concatenate all leadfields allleadfield(:,diplop) = source.leadfield{insideindx(diplop)}; end ft_progress('close'); % multiply the filters and leadfields to obtain the resolution matrix % see equation 1 and 2 in De Peralta-Menendez RG, Gonzalez-Andino SL: A critical analysis of linear inverse solutions to the neuroelectromagnetic inverse problem. IEEE Transactions on Biomedical Engineering 45: 440-448, 1998. source.resolution = nan(Ndipole, Ndipole); source.resolution(insideindx, insideindx) = allfilter*allleadfield; end % compute fwhm if strcmp(cfg.fwhm, 'yes') switch cfg.fwhmmethod case 'barnes' if ~isfield(source, 'dim') error('computation of fwhm is not possible with method ''barnes'' is not possible when the dipoles are not defined on a regular 3D grid'); end fprintf('computing fwhm of spatial filters using method ''barnes''\n'); source = estimate_fwhm1(source, cfg.fwhmremovecenter); case 'gaussfit' fprintf('computing fwhm of spatial filters using method ''gaussfit''\n'); source = estimate_fwhm2(source, cfg.fwhmmaxdist); otherwise error('unknown method for fwhm estimation'); end end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous source ft_postamble provenance source ft_postamble history source ft_postamble savevar source %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function to compute eta from a csd-matrix %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [eta, u] = csd2eta(csd) [u,s,v] = svd(real(csd)); eta = s(2,2)./s(1,1); u = u'; %orientation is defined in the rows %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function to compute fa from a csd-matrix %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fa] = csd2fa(csd) s = svd(real(csd)); ns = rank(real(csd)); s = s(1:ns); ms = mean(s); fa = sqrt( (ns./(ns-1)) .* (sum((s-ms).^2))./(sum(s.^2)) ); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function to compute power %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function p = powmethod_lambda1(x, ind) if nargin==1, ind = 1:size(x,1); end s = svd(x(ind,ind)); p = s(1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function to compute power %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function p = powmethod_trace(x, ind) if nargin==1, ind = 1:size(x,1); end p = trace(x(ind,ind)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function to compute power %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function p = powmethod_regular(x, ind) if nargin==1, ind = 1:size(x,1); end p = abs(x(ind,ind)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function to obtain the largest singular value or trace of the % source CSD matrices resulting from DICS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function s = lambda1(x) s = svd(x); s = s(1);
github
lcnbeapp/beapp-master
ft_defacevolume.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_defacevolume.m
16,914
utf_8
5f4be3aba9099ccccbf2f1a745004df0
function mri = ft_defacevolume(cfg, mri) % FT_DEFACEVOLUME allows you to de-identify an anatomical MRI by erasing specific regions, such as the face and ears. The graphical % user interface allows you to position a box over the anatomical data inside which % all anatomical voxel values will be replaced by zero. You might have to call this % function multiple times when both face and ears need to be removed. Following % defacing, you should check the result with FT_SOURCEPLOT. % % Use as % mri = ft_defacevolume(cfg, mri) % % The configuration can contain the following options % cfg.translate = initial position of the center of the box (default = [0 0 0]) % cfg.scale = initial size of the box along each dimension (default is automatic) % cfg.translate = initial rotation of the box (default = [0 0 0]) % cfg.selection = which voxels to keep, can be 'inside' or 'outside' (default = 'outside') % cfg.smooth = 'no' or the FWHM of the gaussian kernel in voxels (default = 'no') % cfg.keepbrain = 'no' or 'yes', segment and retain the brain (default = 'no') % cfg.feedback = 'no' or 'yes', whether to provide graphical feedback (default = 'no') % % If you specify no smoothing, the selected area will be zero-masked. If you % specify a certain amount of smoothing (in voxels FWHM), the selected area will % be replaced by a smoothed version of the data. % % See also FT_ANONIMIZEDATA, FT_DEFACEMESH, FT_ANALYSISPIPELINE, FT_SOURCEPLOT % Copyright (C) 2015-2016, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar mri ft_preamble provenance mri ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % set the defaults cfg.rotate = ft_getopt(cfg, 'rotate', [0 0 0]); cfg.scale = ft_getopt(cfg, 'scale'); % the automatic default is determined further down cfg.translate = ft_getopt(cfg, 'translate', [0 0 0]); cfg.selection = ft_getopt(cfg, 'selection', 'outside'); cfg.smooth = ft_getopt(cfg, 'smooth', 'no'); cfg.keepbrain = ft_getopt(cfg, 'keepbrain', 'no'); cfg.feedback = ft_getopt(cfg, 'feedback', 'no'); ismri = ft_datatype(mri, 'volume') && isfield(mri, 'anatomy'); ismesh = isfield(mri, 'pos'); % triangles are optional if ismri % check if the input data is valid for this function mri = ft_checkdata(mri, 'datatype', 'volume', 'feedback', 'yes'); end % determine the size of the "unit" sphere in the origin and the length of the axes switch mri.unit case 'mm' axmax = 150; rbol = 5; case 'cm' axmax = 15; rbol = 0.5; case 'm' axmax = 0.15; rbol = 0.005; otherwise error('unknown units (%s)', unit); end figHandle = figure; set(figHandle, 'CloseRequestFcn', @cb_close); % clear persistent variables to ensure fresh figure clear ft_plot_slice if ismri % the volumetric data needs to be interpolated onto three orthogonal planes % determine a resolution that is close to, or identical to the original resolution [corner_vox, corner_head] = cornerpoints(mri.dim, mri.transform); diagonal_head = norm(range(corner_head)); diagonal_vox = norm(range(corner_vox)); resolution = diagonal_head/diagonal_vox; % this is in units of "mri.unit" % create a contrast enhanced version of the anatomy mri.anatomy = double(mri.anatomy); dum = unique(mri.anatomy(:)); clim(1) = dum(round(0.05*numel(dum))); clim(2) = dum(round(0.95*numel(dum))); anatomy = (mri.anatomy-clim(1))/(clim(2)-clim(1)); ft_plot_ortho(anatomy, 'transform', mri.transform, 'unit', mri.unit, 'resolution', resolution, 'style', 'intersect'); elseif ismesh ft_plot_mesh(mri); end axis vis3d view([110 36]); % shift the axes to the left ax = get(gca, 'position'); ax(1) = 0; set(gca, 'position', ax); % get the xyz-axes xdat = [-axmax 0 0; axmax 0 0]; ydat = [0 -axmax 0; 0 axmax 0]; zdat = [0 0 -axmax; 0 0 axmax]; % get the xyz-axes dotted xdatdot = (-axmax:(axmax/15):axmax); xdatdot = xdatdot(1:floor(numel(xdatdot)/2)*2); xdatdot = reshape(xdatdot, [2 numel(xdatdot)/2]); n = size(xdatdot,2); ydatdot = [zeros(2,n) xdatdot zeros(2,n)]; zdatdot = [zeros(2,2*n) xdatdot]; xdatdot = [xdatdot zeros(2,2*n)]; % plot axes hl = line(xdat, ydat, zdat); set(hl(1), 'linewidth', 1, 'color', 'r'); set(hl(2), 'linewidth', 1, 'color', 'g'); set(hl(3), 'linewidth', 1, 'color', 'b'); hld = line(xdatdot, ydatdot, zdatdot); for k = 1:n set(hld(k ), 'linewidth', 3, 'color', 'r'); set(hld(k+n*1), 'linewidth', 3, 'color', 'g'); set(hld(k+n*2), 'linewidth', 3, 'color', 'b'); end if isempty(cfg.scale) cfg.scale = [axmax axmax axmax]/2; end guidata(figHandle, cfg); % add the GUI elements cb_creategui(gca); cb_redraw(gca); uiwait(figHandle); cfg = guidata(figHandle); delete(figHandle); drawnow fprintf('keeping all voxels from MRI that are %s the box\n', cfg.selection) % the order of application is scale, rotate, translate S = cfg.S; R = cfg.R; T = cfg.T; if ismri % it is possible to convert the box to headcoordinates, but it is more efficient the other way around [X, Y, Z] = ndgrid(1:mri.dim(1), 1:mri.dim(2), 1:mri.dim(3)); voxpos = ft_warp_apply(mri.transform, [X(:) Y(:) Z(:)]); % voxel positions in head coordinates voxpos = ft_warp_apply(inv(T*R*S), voxpos); % voxel positions in box coordinates remove = ... voxpos(:,1) > -0.5 & ... voxpos(:,1) < +0.5 & ... voxpos(:,2) > -0.5 & ... voxpos(:,2) < +0.5 & ... voxpos(:,3) > -0.5 & ... voxpos(:,3) < +0.5; elseif ismesh || issource meshpos = ft_warp_apply(inv(T*R*S), mri.pos); % mesh vertex positions in box coordinates remove = ... meshpos(:,1) > -0.5 & ... meshpos(:,1) < +0.5 & ... meshpos(:,2) > -0.5 & ... meshpos(:,2) < +0.5 & ... meshpos(:,3) > -0.5 & ... meshpos(:,3) < +0.5; end if strcmp(cfg.selection, 'inside') % invert the selection, i.e. keep the voxels inside the box remove = ~remove; end if ismri if istrue(cfg.keepbrain) tmpcfg = []; tmpcfg.output = {'brain'}; seg = ft_volumesegment(tmpcfg, mri); fprintf('keeping voxels in brain segmentation\n'); % keep the tissue of the brain remove(seg.brain) = 0; clear seg end if istrue(cfg.feedback) tmpmri = keepfields(mri, {'anatomy', 'transform', 'coordsys', 'units', 'dim'}); tmpmri.remove = remove; tmpcfg = []; tmpcfg.funparameter = 'remove'; ft_sourceplot(tmpcfg, tmpmri); end if isequal(cfg.smooth, 'no') fprintf('zero-filling %.0f%% of the volume\n', 100*mean(remove)); mri.anatomy(remove) = 0; else tmp = mri.anatomy; tmp = (1 + 0.5.*randn(size(tmp))).*tmp; % add 50% noise to each voxel tmp = volumesmooth(tmp, cfg.smooth, 'anatomy'); fprintf('smoothing %.0f%% of the volume\n', 100*mean(remove)); mri.anatomy(remove) = tmp(remove); end elseif ismesh % determine all fields that might need to be defaced fn = setdiff(fieldnames(mri), ignorefields('deface')); dimord = cell(size(fn)); for i=1:numel(fn) dimord{i} = getdimord(mri, fn{i}); end % this applies to headshapes and meshes in general fprintf('keeping %d and removing %d vertices in the mesh\n', sum(remove==0), sum(remove==1)); if isfield(mri, 'tri') [mri.pos, mri.tri] = remove_vertices(mri.pos, mri.tri, remove); elseif isfield(mri, 'tet') [mri.pos, mri.tet] = remove_vertices(mri.pos, mri.tet, remove); elseif isfield(mri, 'hex') [mri.pos, mri.hex] = remove_vertices(mri.pos, mri.hex, remove); else mri.pos = mri.pos(~remove,1:3); end for i=1:numel(fn) dimtok = tokenize(dimord{i}, '_'); % do some sanity checks if any(strcmp(dimtok, '{pos}')) error('not supported'); end if numel(dimtok)>5 error('too many dimensions'); end % remove the same positions from each matching dimension if numel(dimtok)>0 && strcmp(dimtok{1}, 'pos') mri.(fn{i}) = mri.(fn{i})(~remove,:,:,:,:); end if numel(dimtok)>1 && strcmp(dimtok{2}, 'pos') mri.(fn{i}) = mri.(fn{i})(:,~remove,:,:,:); end if numel(dimtok)>2 && strcmp(dimtok{3}, 'pos') mri.(fn{i}) = mri.(fn{i})(:,:,~remove,:,:); end if numel(dimtok)>3 && strcmp(dimtok{4}, 'pos') mri.(fn{i}) = mri.(fn{i})(:,:,:,~remove,:); end if numel(dimtok)>4 && strcmp(dimtok{5}, 'pos') mri.(fn{i}) = mri.(fn{i})(:,:,:,:,~remove); end end % for fn mri = removefields(mri, {'dim', 'transform'}); % these fields don't apply any more end % ismesh % remove the temporary fields from the configuration, keep the rest for provenance cfg = removefields(cfg, {'R', 'S', 'T'}); % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous mri ft_postamble provenance mri ft_postamble history mri ft_postamble savevar mri %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_redraw(figHandle, varargin) persistent p % define the position of each GUI element figHandle = get(figHandle, 'parent'); cfg = guidata(figHandle); rx = str2double(get(findobj(figHandle, 'tag', 'rx'), 'string')); ry = str2double(get(findobj(figHandle, 'tag', 'ry'), 'string')); rz = str2double(get(findobj(figHandle, 'tag', 'rz'), 'string')); tx = str2double(get(findobj(figHandle, 'tag', 'tx'), 'string')); ty = str2double(get(findobj(figHandle, 'tag', 'ty'), 'string')); tz = str2double(get(findobj(figHandle, 'tag', 'tz'), 'string')); sx = str2double(get(findobj(figHandle, 'tag', 'sx'), 'string')); sy = str2double(get(findobj(figHandle, 'tag', 'sy'), 'string')); sz = str2double(get(findobj(figHandle, 'tag', 'sz'), 'string')); % remember the user specified transformation cfg.rotate = [rx ry rz]; cfg.translate = [tx ty tz]; cfg.scale = [sx sy sz]; R = rotate (cfg.rotate); T = translate(cfg.translate); S = scale (cfg.scale); % remember the transformation matrices cfg.R = R; cfg.T = T; cfg.S = S; % start with a cube of unit dimensions x1 = -0.5; y1 = -0.5; z1 = -0.5; x2 = +0.5; y2 = +0.5; z2 = +0.5; plane1 = [ x1 y1 z1 x2 y1 z1 x2 y2 z1 x1 y2 z1]; plane2 = [ x1 y1 z2 x2 y1 z2 x2 y2 z2 x1 y2 z2]; plane3 = [ x1 y1 z1 x1 y2 z1 x1 y2 z2 x1 y1 z2]; plane4 = [ x2 y1 z1 x2 y2 z1 x2 y2 z2 x2 y1 z2]; plane5 = [ x1 y1 z1 x2 y1 z1 x2 y1 z2 x1 y1 z2]; plane6 = [ x1 y2 z1 x2 y2 z1 x2 y2 z2 x1 y2 z2]; plane1 = ft_warp_apply(T*R*S, plane1); plane2 = ft_warp_apply(T*R*S, plane2); plane3 = ft_warp_apply(T*R*S, plane3); plane4 = ft_warp_apply(T*R*S, plane4); plane5 = ft_warp_apply(T*R*S, plane5); plane6 = ft_warp_apply(T*R*S, plane6); if all(ishandle(p)) delete(p); end p(1) = patch(plane1(:,1), plane1(:,2), plane1(:,3), 'y'); p(2) = patch(plane2(:,1), plane2(:,2), plane2(:,3), 'y'); p(3) = patch(plane3(:,1), plane3(:,2), plane3(:,3), 'y'); p(4) = patch(plane4(:,1), plane4(:,2), plane4(:,3), 'y'); p(5) = patch(plane5(:,1), plane5(:,2), plane5(:,3), 'y'); p(6) = patch(plane6(:,1), plane6(:,2), plane6(:,3), 'y'); set(p, 'FaceAlpha', 0.3); guidata(figHandle, cfg); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_creategui(figHandle, varargin) % define the position of each GUI element figHandle = get(figHandle, 'parent'); cfg = guidata(figHandle); % constants CONTROL_WIDTH = 0.05; CONTROL_HEIGHT = 0.08; CONTROL_HOFFSET = 0.68; CONTROL_VOFFSET = 0.20; % rotateui uicontrol('tag', 'rotateui', 'parent', figHandle, 'units', 'normalized', 'style', 'text', 'string', 'rotate', 'callback', []) uicontrol('tag', 'rx', 'parent', figHandle, 'units', 'normalized', 'style', 'edit', 'string', num2str(cfg.rotate(1)), 'callback', @cb_redraw) uicontrol('tag', 'ry', 'parent', figHandle, 'units', 'normalized', 'style', 'edit', 'string', num2str(cfg.rotate(2)), 'callback', @cb_redraw) uicontrol('tag', 'rz', 'parent', figHandle, 'units', 'normalized', 'style', 'edit', 'string', num2str(cfg.rotate(3)), 'callback', @cb_redraw) ft_uilayout(figHandle, 'tag', 'rotateui', 'BackgroundColor', [0.8 0.8 0.8], 'width', 2*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET, 'vpos', CONTROL_VOFFSET); ft_uilayout(figHandle, 'tag', 'rx', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+3*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET); ft_uilayout(figHandle, 'tag', 'ry', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+4*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET); ft_uilayout(figHandle, 'tag', 'rz', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+5*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET); % scaleui uicontrol('tag', 'scaleui', 'parent', figHandle, 'units', 'normalized', 'style', 'text', 'string', 'scale', 'callback', []) uicontrol('tag', 'sx', 'parent', figHandle, 'units', 'normalized', 'style', 'edit', 'string', num2str(cfg.scale(1)), 'callback', @cb_redraw) uicontrol('tag', 'sy', 'parent', figHandle, 'units', 'normalized', 'style', 'edit', 'string', num2str(cfg.scale(2)), 'callback', @cb_redraw) uicontrol('tag', 'sz', 'parent', figHandle, 'units', 'normalized', 'style', 'edit', 'string', num2str(cfg.scale(3)), 'callback', @cb_redraw) ft_uilayout(figHandle, 'tag', 'scaleui', 'BackgroundColor', [0.8 0.8 0.8], 'width', 2*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET, 'vpos', CONTROL_VOFFSET-CONTROL_HEIGHT); ft_uilayout(figHandle, 'tag', 'sx', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+3*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-CONTROL_HEIGHT); ft_uilayout(figHandle, 'tag', 'sy', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+4*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-CONTROL_HEIGHT); ft_uilayout(figHandle, 'tag', 'sz', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+5*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-CONTROL_HEIGHT); % translateui uicontrol('tag', 'translateui', 'parent', figHandle, 'units', 'normalized', 'style', 'text', 'string', 'translate', 'callback', []) uicontrol('tag', 'tx', 'parent', figHandle, 'units', 'normalized', 'style', 'edit', 'string', num2str(cfg.translate(1)), 'callback', @cb_redraw) uicontrol('tag', 'ty', 'parent', figHandle, 'units', 'normalized', 'style', 'edit', 'string', num2str(cfg.translate(2)), 'callback', @cb_redraw) uicontrol('tag', 'tz', 'parent', figHandle, 'units', 'normalized', 'style', 'edit', 'string', num2str(cfg.translate(3)), 'callback', @cb_redraw) ft_uilayout(figHandle, 'tag', 'translateui', 'BackgroundColor', [0.8 0.8 0.8], 'width', 2*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET, 'vpos', CONTROL_VOFFSET-2*CONTROL_HEIGHT); ft_uilayout(figHandle, 'tag', 'tx', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+3*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-2*CONTROL_HEIGHT); ft_uilayout(figHandle, 'tag', 'ty', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+4*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-2*CONTROL_HEIGHT); ft_uilayout(figHandle, 'tag', 'tz', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+5*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-2*CONTROL_HEIGHT); % somehow the toolbar gets lost in 2012b set(figHandle, 'toolbar', 'figure'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_close(figHandle, varargin) % the figure will be closed in the main function after collecting the guidata uiresume;
github
lcnbeapp/beapp-master
ft_freqanalysis_mvar.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_freqanalysis_mvar.m
8,209
utf_8
455f4261f748338ec12c74948fbda55b
function [freq] = ft_freqanalysis_mvar(cfg, data) % FT_FREQANALYSIS_MVAR performs frequency analysis on % mvar data, by fourier transformation of the coefficients. The output % contains cross-spectral density, spectral transfer matrix, and the % covariance of the innovation noise. The dimord = 'chan_chan(_freq)(_time) % % The function is stand-alone, but is typically called through % FT_FREQANALYSIS, specifying cfg.method = 'mvar'. % % Use as % [freq] = ft_freqanalysis(cfg, data), with cfg.method = 'mvar' % % or % % [freq] = ft_freqanalysis_mvar(cfg, data) % % The input data structure should be a data structure created by % FT_MVARANALYSIS, i.e. a data-structure of type 'mvar'. % % The configuration can contain: % cfg.foi = vector with the frequencies at which the spectral quantities % are estimated (in Hz). Default: 0:1:Nyquist % cfg.feedback = 'none', or any of the methods supported by FT_PROGRESS, % for providing feedback to the user in the command % window. % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % cfg.outputfile = ... % If you specify one of these (or both) the input data will be read from a *.mat % file on disk and/or the output data will be written to a *.mat file. These mat % files should contain only a single variable, corresponding with the % input/output structure. % % See also FT_MVARANALYSIS, FT_DATATYPE_MVAR, FT_PROGRESS % Copyright (C) 2009, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar data ft_preamble provenance data ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end cfg.foi = ft_getopt(cfg, 'foi', 'all'); cfg.feedback = ft_getopt(cfg, 'feedback', 'none'); %cfg.channel = ft_getopt(cfg, 'channel', 'all'); %cfg.keeptrials = ft_getopt(cfg, 'keeptrials', 'no'); %cfg.jackknife = ft_getopt(cfg, 'jackknife', 'no'); %cfg.keeptapers = ft_getopt(cfg, 'keeptapers', 'yes'); if strcmp(cfg.foi, 'all'), cfg.foi = (0:1:data.fsampleorig/2); end dimtok = tokenize(data.dimord, '_'); isfull = isfield(data, 'label') && sum(strcmp(dimtok,'chan'))==2; isuvar = isfield(data, 'label') && sum(strcmp(dimtok,'chan'))==1; isbvar = isfield(data, 'labelcmb'); if (isfull||isuvar) && isbvar error('data representaion is ambiguous'); end if ~isfull && ~isbvar && ~isuvar error('data representation is unsupported'); end %keeprpt = strcmp(cfg.keeptrials, 'yes'); %keeptap = strcmp(cfg.keeptapers, 'yes'); %dojack = strcmp(cfg.jackknife, 'yes'); %dozscore = strcmp(cfg.zscore, 'yes'); %if ~keeptap, error('not keeping tapers is not possible yet'); end %if dojack && keeprpt, error('you cannot simultaneously keep trials and do jackknifing'); end nfoi = length(cfg.foi); if isfield(data, 'time') ntoi = numel(data.time); else ntoi = 1; end if isfull || isuvar cfg.channel = ft_channelselection('all', data.label); %cfg.channel = ft_channelselection(cfg.channel, data.label); chanindx = match_str(data.label, cfg.channel); nchan = length(chanindx); label = data.label(chanindx); nlag = size(data.coeffs,3); %change in due course %---allocate memory h = complex(zeros(nchan, nchan, nfoi, ntoi), zeros(nchan, nchan, nfoi, ntoi)); a = complex(zeros(nchan, nchan, nfoi, ntoi), zeros(nchan, nchan, nfoi, ntoi)); crsspctrm = complex(zeros(nchan, nchan, nfoi, ntoi), zeros(nchan, nchan, nfoi, ntoi)); elseif isbvar ncmb = size(data.labelcmb,1)./4; nlag = size(data.coeffs,2); %---allocate memory h = complex(zeros(ncmb*4, nfoi, ntoi), zeros(ncmb*4, nfoi, ntoi)); a = complex(zeros(ncmb*4, nfoi, ntoi), zeros(ncmb*4, nfoi, ntoi)); crsspctrm = complex(zeros(ncmb*4, nfoi, ntoi), zeros(ncmb*4, nfoi, ntoi)); end %FIXME build in repetitions %---loop over the tois ft_progress('init', cfg.feedback, 'computing MAR-model based TFR'); for j = 1:ntoi ft_progress(j/ntoi, 'processing timewindow %d from %d\n', j, ntoi); if isfull %---compute transfer function ar = reshape(data.coeffs(:,:,:,j), [nchan nchan*nlag]); [h(:,:,:,j), a(:,:,:,j)] = ar2h(ar, cfg.foi, data.fsampleorig); %---compute cross-spectra nc = data.noisecov(:,:,j); for k = 1:nfoi tmph = h(:,:,k,j); crsspctrm(:,:,k,j) = tmph*nc*tmph'; end elseif isuvar %---compute transfer function for m = 1:nchan ar = reshape(data.coeffs(m,:,j), [1 nlag]); [h(m,m,:,j), a(m,m,:,j)] = ar2h(ar, cfg.foi, data.fsampleorig); %---compute cross-spectra nc = data.noisecov(m,j); for k = 1:nfoi tmph = h(m,m,k,j); crsspctrm(m,m,k,j) = tmph*nc*tmph'; end end elseif isbvar for kk = 1:ncmb %---compute transfer function ar = reshape(data.coeffs((kk-1)*4+(1:4),:,:,j), [2 2*nlag]); [tmph,tmpa] = ar2h(ar, cfg.foi, data.fsampleorig); h((kk-1)*4+(1:4),:,:) = reshape(tmph, [4 nfoi ntoi]); a((kk-1)*4+(1:4),:,:) = reshape(tmpa, [4 nfoi ntoi]); %---compute cross-spectra nc = reshape(data.noisecov((kk-1)*4+(1:4),j), [2 2]); for k = 1:nfoi crsspctrm((kk-1)*4+(1:4),k,j) = reshape(tmph(:,:,k)*nc*tmph(:,:,k)', [4 1]); end end end end ft_progress('close'); %---create output-structure freq = []; freq.freq = cfg.foi; %freq.cumtapcnt= ones(ntrl, 1)*ntap; freq.transfer = h; %freq.itransfer = a; freq.noisecov = data.noisecov; freq.crsspctrm = crsspctrm; if isfield(data, 'dof'), freq.dof = data.dof; end if isfull freq.label = label; if ntoi>1 freq.time = data.time; freq.dimord = 'chan_chan_freq_time'; else freq.dimord = 'chan_chan_freq'; end elseif isbvar freq.labelcmb = data.labelcmb; if ntoi>1 freq.time = data.time; freq.dimord = 'chancmb_freq_time'; else freq.dimord = 'chancmb_freq'; end end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous data ft_postamble provenance freq ft_postamble history freq ft_postamble savevar freq %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to compute transfer-function from ar-parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [h, zar] = ar2h(ar, foi, fsample) nchan = size(ar,1); ncmb = nchan*nchan; nfoi = length(foi); %---z-transform frequency axis zfoi = exp(-2.*pi.*1i.*(foi./fsample)); %---reorganize the ar-parameters ar = reshape(ar, [ncmb size(ar,2)./nchan]); ar = fliplr([reshape(eye(nchan), [ncmb 1]) -ar]); zar = complex(zeros(ncmb, nfoi), zeros(ncmb, nfoi)); for k = 1:ncmb zar(k,:) = polyval(ar(k,:),zfoi); end zar = reshape(zar, [nchan nchan nfoi]); h = zeros(size(zar)); for k = 1:nfoi h(:,:,k) = inv(zar(:,:,k)); end h = sqrt(2).*h; %account for the negative frequencies, normalization necessary for %comparison with non-parametric (fft based) results in fieldtrip %FIXME probably the normalization for the zero Hz bin is incorrect zar = zar./sqrt(2);
github
lcnbeapp/beapp-master
ft_math.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_math.m
17,813
utf_8
c90f403d7bc6a7bb69ba1a6fb9b5b61f
function data = ft_math(cfg, varargin) % FT_MATH performs mathematical operations on FieldTrip data structures, % such as addition, subtraction, division, etc. % % Use as % data = ft_math(cfg, data1, data2, ...) % with one or multiple FieldTrip data structures as the input and the configuration % structure cfg in which you specify the mathematical operation that is to be % executed on the desired parameter from the data % cfg.parameter = string, field from the input data on which the operation is % performed, e.g. 'pow' or 'avg' % cfg.operation = string, for example '(x1-x2)/(x1+x2)' or 'x1/6' % % In the specification of the mathematical operation, x1 is the parameter obtained % from the first input data structure, x2 from the second, etc. % % Rather than specifying the operation as a string that is evaluated, you can also % specify it as a single operation. The advantage is that it is computed faster. % cfg.operation = string, can be 'add', 'subtract', 'divide', 'multiply', 'log10', 'abs' % If you specify only a single input data structure and the operation is 'add', % 'subtract', 'divide' or 'multiply', the configuration should also contain: % cfg.scalar = scalar value to be used in the operation % % The operation 'add' is implemented as follows % y = x1 + x2 + .... % if you specify multiple input arguments, or as % y = x1 + s % if you specify one input argument and a scalar value. % % The operation 'subtract' is implemented as follows % y = x1 - x2 - .... % if you specify multiple input arguments, or as % y = x1 - s % if you specify one input argument and a scalar value. % % The operation 'divide' is implemented as follows % y = x1 ./ x2 % if you specify two input arguments, or as % y = x1 / s % if you specify one input argument and a scalar value. % % The operation 'multiply' is implemented as follows % y = x1 .* x2 % if you specify two input arguments, or as % y = x1 * s % if you specify one input argument and a scalar value. % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % cfg.outputfile = ... % If you specify one of these (or both) the input data will be read from a *.mat % file on disk and/or the output data will be written to a *.mat file. These mat % files should contain only a single variable, corresponding with the % input/output structure. % % See also FT_DATATYPE % Undocumented options: % cfg.matrix = rather than using a scalar, a matrix can be specified. In % this case, the dimensionality of cfg.matrix should be equal % to the dimensionality of data.(cfg.parameter). If used in % combination with cfg.operation, the operation should % involve element-wise combination of the data and the % matrix. % Copyright (C) 2012-2015, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the initial part deals with parsing the input options and data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do teh general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar varargin ft_preamble provenance varargin ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end type = ft_datatype(varargin{1}); for i=1:length(varargin) % check if the input data is valid for this function, that all data types are equal and update old data structures varargin{i} = ft_checkdata(varargin{i}, 'datatype', type); end % ensure that the required options are present cfg = ft_checkconfig(cfg, 'required', {'operation', 'parameter'}); cfg = ft_checkconfig(cfg, 'renamed', {'value', 'scalar'}); cfg = ft_checkconfig(cfg, 'renamedval', {'funparameter', 'avg.pow', 'pow'}); cfg = ft_checkconfig(cfg, 'renamedval', {'funparameter', 'avg.coh', 'coh'}); cfg = ft_checkconfig(cfg, 'renamedval', {'funparameter', 'avg.mom', 'mom'}); if ~iscell(cfg.parameter) cfg.parameter = {cfg.parameter}; end % this function only works for the upcoming (not yet standard) source representation without sub-structures if ft_datatype(varargin{1}, 'source') % update the old-style beamformer source reconstruction for i=1:length(varargin) varargin{i} = ft_datatype_source(varargin{i}, 'version', 'upcoming'); end for p = 1:length(cfg.parameter) if strncmp(cfg.parameter{p}, 'avg.', 4) cfg.parameter{p} = cfg.parameter{p}(5:end); % remove the 'avg.' part end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the actual computation is done in the middle part %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for p=1:length(cfg.parameter) if ~issubfield(varargin{1}, cfg.parameter{p}) error('the requested parameter is not present in the data'); end end % ensure that the data in all inputs has the same channels, time-axis, etc. tmpcfg = []; tmpcfg.parameter = cfg.parameter; [varargin{:}] = ft_selectdata(tmpcfg, varargin{:}); % restore the provenance information [cfg, varargin{:}] = rollback_provenance(cfg, varargin{:}); % restore the user-specified parameter option cfg.parameter = tmpcfg.parameter; for p = 1:length(cfg.parameter) dimordtmp{p} = getdimord(varargin{1}, cfg.parameter{p}); if p>1 && ~strcmp(dimordtmp{1}, dimordtmp{p}) error('the dimord of multiple parameters must be the same'); end end dimord = dimordtmp{1}; clear dimordtmp dimtok = tokenize(dimord, '_'); % this determines which descriptive fields will get copied over haschan = any(strcmp(dimtok, 'chan')); haschancmb = any(strcmp(dimtok, 'chancmb')); hasfreq = any(strcmp(dimtok, 'freq')); hastime = any(strcmp(dimtok, 'time')); haspos = any(strcmp(dimtok, 'pos')); % construct the output data structure data = []; if haschan data.label = varargin{1}.label; end if haschancmb data.labelcmb = varargin{1}.labelcmb; end if hasfreq data.freq = varargin{1}.freq; end if hastime data.time = varargin{1}.time; end if haspos if isfield(varargin{1}, 'pos') data.pos = varargin{1}.pos; end if isfield(varargin{1}, 'dim') data.dim = varargin{1}.dim; end if isfield(varargin{1}, 'transform') data.transform = varargin{1}.transform; end end % use an anonymous function assign = @(var, val) assignin('caller', var, val); for p = 1:length(cfg.parameter) fprintf('selecting %s from the first input argument\n', cfg.parameter{p}); % create the local variables x1, x2, ... for i=1:length(varargin) assign(sprintf('x%i', i), getsubfield(varargin{i}, cfg.parameter{p})); end % create the local variables s and m s = ft_getopt(cfg, 'scalar'); m = ft_getopt(cfg, 'matrix'); % check the dimensionality of m against the input data if ~isempty(m), for i=1:length(varargin) ok = isequal(size(getsubfield(varargin{i}, cfg.parameter{p})),size(m)); if ~ok, break; end end if ~ok, error('the dimensions of cfg.matrix do not allow for element-wise operations'); end end % only one of these can be defined at the moment (i.e. not allowing for % operations such as (x1+m)^s for now if ~isempty(m) && ~isempty(s), error('you can either specify a cfg.matrix or a cfg.scalar, not both'); end % touch it to keep track of it in the output cfg if ~isempty(s), cfg.scalar; end if ~isempty(m), cfg.matrix; end % replace s with m, so that the code below is more transparent if ~isempty(m), s = m; clear m; end if length(varargin)==1 switch cfg.operation case 'add' if isscalar(s), fprintf('adding %f to the %s\n', s, cfg.parameter{p}); else fprintf('adding the contents of cfg.matrix to the %s\n', cfg.parameter{p}); end if iscell(x1) y = cellplus(x1, s); else y = x1 + s; end case 'subtract' if isscalar(s), fprintf('subtracting %f from the %s\n', s, cfg.parameter{p}); else fprintf('subtracting the contents of cfg.matrix from the %s\n', cfg.parameter{p}); end if iscell(x1) y = cellminus(x1, s); else y = x1 - s; end case 'multiply' if isscalar(s), fprintf('multiplying %s with %f\n', cfg.parameter{p}, s); else fprintf('multiplying %s with the content of cfg.matrix\n', cfg.parameter{p}); end fprintf('multiplying %s with %f\n', cfg.parameter{p}, s); if iscell(x1) y = celltimes(x1, s); else y = x1 .* s; end case 'divide' if isscalar(s), fprintf('dividing %s by %f\n', cfg.parameter{p}, s); else fprintf('dividing %s by the content of cfg.matrix\n', cfg.parameter{p}); end if iscell(x1) y = cellrdivide(x1, s); else y = x1 ./ s; end case 'log10' fprintf('taking the log10 of %s\n', cfg.parameter{p}); if iscell(x1) y = celllog10(x1); else y = log10(x1); end case 'abs' fprintf('taking the abs of %s\n', cfg.parameter{p}); if iscell(x1) y = cellabs(x1); else y = abs(x1); end otherwise % assume that the operation is descibed as a string, e.g. x1^s % where x1 is the first argument and s is obtained from cfg.scalar arginstr = sprintf('x%i,', 1:length(varargin)); arginstr = arginstr(1:end-1); % remove the trailing ',' eval(sprintf('operation = @(%s) %s;', arginstr, cfg.operation)); if ~iscell(varargin{1}.(cfg.parameter{p})) % gather x1, x2, ... into a cell-array arginval = eval(sprintf('{%s}', arginstr)); eval(sprintf('operation = @(%s) %s;', arginstr, cfg.operation)); if numel(s)<=1 y = arrayfun(operation, arginval{:}); elseif size(s)==size(arginval{1}) y = feval(operation, arginval{:}); end else y = cell(size(x1)); % do the same thing, but now for each element of the cell array for i=1:numel(y) for j=1:length(varargin) % rather than working with x1 and x2, we need to work on its elements % xx1 is one element of the x1 cell-array assign(sprintf('xx%d', j), eval(sprintf('x%d{%d}', j, i))) end % gather xx1, xx2, ... into a cell-array arginstr = sprintf('xx%i,', 1:length(varargin)); arginstr = arginstr(1:end-1); % remove the trailing ',' arginval = eval(sprintf('{%s}', arginstr)); if numel(s)<=1 y{i} = arrayfun(operation, arginval{:}); else y{i} = feval(operation, arginval{:}); end end % for each element end % iscell or not end % switch else switch cfg.operation case 'add' for i=2:length(varargin) fprintf('adding the %s input argument\n', nth(i)); if iscell(x1) y = cellplus(x1, varargin{i}.(cfg.parameter{p})); else y = x1 + varargin{i}.(cfg.parameter{p}); end end case 'multiply' for i=2:length(varargin) fprintf('multiplying with the %s input argument\n', nth(i)); if iscell(x1) y = celltimes(x1, varargin{i}.(cfg.parameter{p})); else y = x1 .* varargin{i}.(cfg.parameter{p}); end end case 'subtract' if length(varargin)>2 error('the operation "%s" requires exactly 2 input arguments', cfg.operation); end fprintf('subtracting the 2nd input argument from the 1st\n'); if iscell(x1) y = cellminus(x1, varargin{2}.(cfg.parameter{p})); else y = x1 - varargin{2}.(cfg.parameter{p}); end case 'divide' if length(varargin)>2 error('the operation "%s" requires exactly 2 input arguments', cfg.operation); end fprintf('dividing the 1st input argument by the 2nd\n'); if iscell(x1) y = cellrdivide(x1, varargin{2}.(cfg.parameter{p})); else y = x1 ./ varargin{2}.(cfg.parameter{p}); end case 'log10' if length(varargin)>2 error('the operation "%s" requires exactly 2 input arguments', cfg.operation); end fprintf('taking the log difference between the 2nd input argument and the 1st\n'); y = log10(x1 ./ varargin{2}.(cfg.parameter{p})); otherwise % assume that the operation is descibed as a string, e.g. (x1-x2)/(x1+x2) % ensure that all input arguments are being used for i=1:length(varargin) assert(~isempty(regexp(cfg.operation, sprintf('x%i', i), 'once')), 'not all input arguments are assigned in the operation') end arginstr = sprintf('x%i,', 1:length(varargin)); arginstr = arginstr(1:end-1); % remove the trailing ',' eval(sprintf('operation = @(%s) %s;', arginstr, cfg.operation)); if ~iscell(varargin{1}.(cfg.parameter{p})) % gather x1, x2, ... into a cell-array arginval = eval(sprintf('{%s}', arginstr)); eval(sprintf('operation = @(%s) %s;', arginstr, cfg.operation)); if numel(s)<=1 y = arrayfun(operation, arginval{:}); else y = feval(operation, arginval{:}); end else y = cell(size(x1)); % do the same thing, but now for each element of the cell array for i=1:numel(y) for j=1:length(varargin) % rather than working with x1 and x2, we need to work on its elements % xx1 is one element of the x1 cell-array assign(sprintf('xx%d', j), eval(sprintf('x%d{%d}', j, i))) end % gather xx1, xx2, ... into a cell-array arginstr = sprintf('xx%i,', 1:length(varargin)); arginstr = arginstr(1:end-1); % remove the trailing ',' arginval = eval(sprintf('{%s}', arginstr)); if numel(s)<=1 y{i} = arrayfun(operation, arginval{:}); else y{i} = feval(operation, arginval{:}); end end % for each element end % iscell or not end % switch end % one or multiple input data structures % store the result of the operation in the output structure data = setsubfield(data, cfg.parameter{p}, y); end % p over length(cfg.parameter) data.dimord = dimord; % certain fields should remain in the output, but only if they are identical in all inputs keepfield = {'grad', 'elec', 'inside', 'trialinfo', 'sampleinfo'}; for j=1:numel(keepfield) if isfield(varargin{1}, keepfield{j}) tmp = varargin{i}.(keepfield{j}); keep = true; else keep = false; end for i=1:numel(varargin) if ~isfield(varargin{i}, keepfield{j}) || ~isequal(varargin{i}.(keepfield{j}), tmp) keep = false; break end end if keep data.(keepfield{j}) = tmp; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % deal with the output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ft_postamble debug ft_postamble trackconfig ft_postamble previous varargin ft_postamble provenance data ft_postamble history data ft_postamble savevar data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function s = nth(n) if rem(n,10)==1 && rem(n,100)~=11 s = sprintf('%dst', n); elseif rem(n,10)==2 && rem(n,100)~=12 s = sprintf('%dnd', n); elseif rem(n,10)==3 && rem(n,100)~=13 s = sprintf('%drd', n); else s = sprintf('%dth', n); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTIONS for doing math on each element of a cell-array %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function z = cellplus(x, y) if ~iscell(y) y = repmat({y}, size(x)); end z = cellfun(@plus, x, y, 'UniformOutput', false); function z = cellminus(x, y) if ~iscell(y) y = repmat({y}, size(x)); end z = cellfun(@minus, x, y, 'UniformOutput', false); function z = celltimes(x, y) if ~iscell(y) y = repmat({y}, size(x)); end z = cellfun(@times, x, y, 'UniformOutput', false); function z = cellrdivide(x, y) if ~iscell(y) y = repmat({y}, size(x)); end z = cellfun(@rdivide, x, y, 'UniformOutput', false); function z = celllog10(x) z = cellfun(@log10, x, 'UniformOutput', false); function z = cellabs(x) z = cellfun(@abs, x, 'UniformOutput', false);
github
lcnbeapp/beapp-master
ft_removetmsartifact.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_removetmsartifact.m
11,406
utf_8
422128cb8363b94785f8e75e0e5abce4
function data = ft_removetmsartifact(cfg, data) % FT_REMOVETMSARTIFACT removes TMS artifacts from EEG data % % %% % NOTE: Please be aware that this function is deprecated. Please follow the % TMS-EEG tutorial instead at http://www.fieldtriptoolbox.org/tutorial/tms-eeg % %% % % Use as % data = ft_removetmsartifact(cfg, data) % where the input data is a raw data, for example obtained from FT_PREPROCESSING, and % cfg is a configuratioun structure that should contain % cfg.method = string, can be 'twopassfilter', 'interpolatepulse' % cfg.pulseonset = value or vector, time in seconds of the TMS pulse in seconds % % The following options pertain to the 'replace' method % cfg.pulsewidth = value, pulse pulsewidth to be removed in seconds % cfg.offset = value, offset with respect to pulse onset to start % replacing, in seconds. % % The following options pertain to the 'twopassfilter' method % cfg.lpfreq = number in Hz % cfg.lpfiltord = lowpass filter order % cfg.lpfilttype = digital filter type, 'but' or 'fir' or 'firls' (default = 'but') % cfg.pulsewidth = value, pulse pulsewidth to be removed in seconds. If % set to 0, entire trial will be filtered. % cfg.offset = value, offset with respect to pulse onset to start % filtering, in seconds. % % See also FT_REJECTARTIFACT, FT_REJECTCOMPONENT % Copyrights (C) 2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % DEPRECATED by jimher on 19 September 2013 % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=1791 for more details warning('FT_REMOVETMSARTIFACT is deprecated, please follow TMS-EEG tutorial instead (http://www.fieldtriptoolbox.org/tutorial/tms-eeg).') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the initial part deals with parsing the input options and data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar datain ft_preamble provenance datain ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input data is valid for this function data = ft_checkdata(data, 'datatype', {'raw'}, 'feedback', 'yes'); % ensure that the required options are present cfg = ft_checkconfig(cfg, 'required', {'method'}); % get the options cfg.method = ft_getopt(cfg, 'method'); % there is no default cfg.pulseonset = ft_getopt(cfg, 'pulseonset'); cfg.pulsewidth = ft_getopt(cfg, 'pulsewidth'); cfg.lpfiltord = ft_getopt(cfg, 'lpfiltord', 2); cfg.lpfilttype = ft_getopt(cfg, 'lpfilttype', 'but'); cfg.lpfreq = ft_getopt(cfg, 'lpfreq', 30); cfg.offset = ft_getopt(cfg, 'offset', 0); cfg.fillmethod = ft_getopt(cfg, 'fillmethod'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the actual computation is done in the middle part %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% numtrl = length(data.trial); temp_pulse = []; if ~isfield(data, 'fsample') fsample = 1/mean(diff(data.time{1})); else fsample = data.fsample; end if isnumeric(cfg.pulsewidth) && numel(cfg.pulsewidth)==1; temp_pulse = cfg.pulsewidth; end; % copy for all trials if isnumeric(cfg.pulseonset) && numel(cfg.pulseonset)==1; cfg.pulseonset = repmat(cfg.pulseonset, numtrl, 1); end if isnumeric(cfg.pulsewidth) && numel(cfg.pulsewidth)==1; cfg.pulsewidth = repmat(cfg.pulsewidth, numtrl, 1); end % check wether fields are cell where necessary if ~iscell(cfg.pulseonset); cfg.pulseonset = num2cell(cfg.pulseonset); end; if ~iscell(cfg.pulsewidth); cfg.pulsewidth = num2cell(cfg.pulsewidth); end; if isempty(cfg.pulseonset) || isempty(cfg.pulsewidth) for i=1:numtrl [onset, width] = pulsedetect(data.trial{i}); % these should be expressed in seconds cfg.pulseonset{i} = data.time{i}(onset); if ~isempty(temp_pulse) cfg.pulsewidth{i} = repmat(temp_pulse, 1, length(onset)); else cfg.pulsewidth{i} = width; end; fprintf('detected %d pulses in trial %d\n', length(onset), i); end end % estimate pulse onset and width switch cfg.method case 'twopassfilter' for i=1:numtrl for j=1:length(cfg.pulseonset{i}) %tmssample = nearest(data.time{i}, cfg.pulseonset{i}(j)); pulseonset = cfg.pulseonset{i}(j); pulsewidth = cfg.pulsewidth{i}(j); offset = cfg.offset; % express it in samples, pulseonset = nearest(data.time{i}, pulseonset); pulsewidth = round(pulsewidth*fsample); offset = round(offset*fsample); % get the part of the data that is left and right of the TMS pulse artifact dat1 = data.trial{i}(:,1:pulseonset); dat2 = data.trial{i}(:,(pulseonset+1:end)); % filter the two pieces, prevent filter artifacts [filt1] = ft_preproc_lowpassfilter(dat1,fsample,cfg.lpfreq,cfg.lpfiltord,cfg.lpfilttype,'onepass'); [filt2] = ft_preproc_lowpassfilter(dat2,fsample,cfg.lpfreq,cfg.lpfiltord,cfg.lpfilttype,'onepass-reverse'); % stitch the left and right parts of the data back together %data.trial{i} = [filt1 filt2]; fill = [filt1 filt2]; % determine a short window around the tms pulse begsample = pulseonset + offset; endsample = pulseonset + pulsewidth + offset - 1; % replace data in the pulse window with a filtered version if pulsewidth == 0 data.trial{i} = fill; else data.trial{i}(:,begsample:endsample) = fill(:,begsample:endsample); end; end % for pulses end % for trials case 'interpolatepulse' for i=1:numtrl for j=1:length(cfg.pulseonset{i}) pulseonset = cfg.pulseonset{i}(j); pulsewidth = cfg.pulsewidth{i}(j); offset = cfg.offset; % express it in samples, pulseonset = nearest(data.time{i}, pulseonset); pulsewidth = round(pulsewidth*fsample); offset = round(offset*fsample); begsample = pulseonset + offset; endsample = pulseonset + pulsewidth + offset - 1; % determine a short window before the TMS pulse begsample1 = begsample - pulsewidth; endsample1 = begsample - 1; % determine a short window after the TMS pulse begsample2 = endsample + 1; endsample2 = endsample + pulsewidth; dat1 = data.trial{i}(:,begsample1:endsample1); dat2 = data.trial{i}(:,begsample2:endsample2); %fill = dat1(:,randperm(size(dat1,2))); % randomly shuffle the data points %fill = mean(dat1,2) + cumsum(std(dat1,[],2).*randn(size(dat1,1),size(dat1,2))); % fill = linspace(mean(dat1,2),mean(dat2,2),endsample1-begsample1+1); % fill = fill + cumsum(std(dat1,[],2).*randn(size(dat1,1),size(dat1,2))); % fill = cumsum(std(dat1,[],2).*randn(size(dat1,1),size(dat1,2))); switch cfg.fillmethod case 'fft' fft_dat1 = fft(dat1); fft_dat2 = fft(dat2); fill = real(ifft(mean([fft_dat1; fft_dat2]))); % fill = std(dat1,[],2).*randn(size(dat1,1),size(dat1,2)); % fill = fill .* repmat(hann(size(fill,2))',size(fill,1),1); % %fill = fill - linspace(fill(:,1),fill(:,end),endsample1-begsample1+1); % % fill = fill + linspace(mean(dat1,2),mean(dat2,2),endsample1-begsample1+1); % fill = fill + linspace(dat1(:,end),dat2(:,1),endsample1-begsample1+1); case 'zeros' fill = zeros(size(dat1,1),size(dat1,2)); case 'randperm' fill = dat1(:,randperm(size(dat1,2))); % randomly shuffle the data points case 'brown' fill = linspace(mean(dat1,2),mean(dat2,2),endsample1-begsample1+1); fill = fill + cumsum(std(dat1,[],2).*randn(size(dat1,1),size(dat1,2))); case 'linear' fill = interp1([1:size(dat1,2) 2*size(dat1,2)+1:3*size(dat1,2)], [dat1 dat2]', size(dat1,2)+1:2*size(dat1,2),'linear')'; case 'linear+noise' fill = interp1([1:size(dat1,2) 2*size(dat1,2)+1:3*size(dat1,2)], [dat1 dat2]', size(dat1,2)+1:2*size(dat1,2),'linear')'; fill = fill(2:end-1) + std(dat1,[],2).*randn(size(dat1,1),size(dat1,2)); case 'spline' fill = interp1([1:size(dat1,2) 2*size(dat1,2)+1:3*size(dat1,2)], [dat1 dat2]', size(dat1,2)+1:2*size(dat1,2),'spline')'; case 'cubic' fill = interp1([1:size(dat1,2) 2*size(dat1,2)+1:3*size(dat1,2)], [dat1 dat2]', size(dat1,2)+1:2*size(dat1,2),'cubic')'; case 'cubic+noise' fill = interp1([1:size(dat1,2) 2*size(dat1,2)+1:3*size(dat1,2)], [dat1 dat2]', size(dat1,2)+1:2*length(dat1),'cubic')'; fill = fill + std(dat1,[],2).*randn(size(dat1,1),size(dat1,2)); end; % FIXME an alternative would be to replace it with an interpolated version of the signal just around it % FIXME an alternative would be to replace it with nan % FIXME an alternative would be to replace it with random noise % replace the data in the pulse window with a random shuffled version of the data just around it data.trial{i}(:,begsample:endsample) = fill; end % for pulses end % for trials otherwise error('unsupported method'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % deal with the output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ft_postamble debug ft_postamble trackconfig ft_postamble previous data ft_postamble provenance data ft_postamble history data ft_postamble savevar data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that detects the onset and pulsewidth of one or multiple TMS pulses % that are present as artifact in a segment of multi-channel EEG data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [onset, pulsewidth] = pulsedetect(dat) [nchan, ntime] = size(dat); for i=1:nchan dat(i,:) = dat(i,:) - median(dat(i,:)); end dat = sum(abs(dat),1); threshold = 0.5 * max(dat); dat = dat>threshold; dat = [0 diff(dat) 0]; onset = find(dat== 1); offset = find(dat==-1) - 1; pulsewidth = offset - onset; % make the pulse a bit wider offset = offset - 2*pulsewidth; pulsewidth = pulsewidth*5;
github
lcnbeapp/beapp-master
ft_interactiverealign.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_interactiverealign.m
22,918
utf_8
5ef189d255cecff5ebfcdd4c7b876b59
function cfg = ft_interactiverealign(cfg) % FT_INTERACTIVEREALIGN interactively rotates, scales and translates % electrode positions to template electrode positions or towards % the head surface. % % Use as % [cfg] = ft_interactiverealign(cfg) % % The configuration structure should contain the individuals geometrical % objects that have to be realigned as % cfg.individual.elec = structure % cfg.individual.grad = structure % cfg.individual.headmodel = structure, see FT_PREPARE_HEADMODEL % cfg.individual.headmodelstyle = 'edge', 'surface' or 'both' (default = 'edge') % cfg.individual.headshape = structure, see FT_READ_HEADSHAPE % cfg.individual.headshapestyle = 'vertex', 'surface' or 'both' (default = 'vertex') % % The configuration structure should also contain the geometrical % objects of a template that serves as target % cfg.template.elec = structure % cfg.template.grad = structure % cfg.template.headmodel = structure, see FT_PREPARE_HEADMODEL % cfg.template.headmodelstyle = 'edge', 'surface' or 'both' (default = 'edge') % cfg.template.headshape = structure, see FT_READ_HEADSHAPE % cfg.template.headshapestyle = 'vertex', 'surface' or 'both' (default = 'vertex') % % See also FT_VOLUMEREALIGN, FT_ELECTRODEREALIGN, FT_READ_SENS, FT_READ_VOL, FT_READ_HEADSHAPE % Copyright (C) 2008, Vladimir Litvak % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble provenance ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'required', {'individual', 'template'}); cfg.individual = ft_checkconfig(cfg.individual, 'renamed', {'vol', 'headmodel'}); cfg.individual = ft_checkconfig(cfg.individual, 'renamed', {'volstyle', 'headmodelstyle'}); cfg.template = ft_checkconfig(cfg.template, 'renamed', {'vol', 'headmodel'}); cfg.template = ft_checkconfig(cfg.template, 'renamed', {'volstyle', 'headmodelstyle'}); cfg.individual.elec = ft_getopt(cfg.individual, 'elec', []); cfg.individual.grad = ft_getopt(cfg.individual, 'grad', []); cfg.individual.headshape = ft_getopt(cfg.individual, 'headshape', []); cfg.individual.headshapestyle = ft_getopt(cfg.individual, 'headshapestyle', 'vertex'); cfg.individual.headmodel = ft_getopt(cfg.individual, 'headmodel', []); cfg.individual.headmodelstyle = ft_getopt(cfg.individual, 'headmodelstyle', 'edge'); cfg.individual.mri = ft_getopt(cfg.individual, 'mri', []); cfg.individual.mristyle = ft_getopt(cfg.individual, 'mristyle', 'intersect'); cfg.template.elec = ft_getopt(cfg.template, 'elec', []); cfg.template.grad = ft_getopt(cfg.template, 'grad', []); cfg.template.headshape = ft_getopt(cfg.template, 'headshape', []); cfg.template.headshapestyle = ft_getopt(cfg.template, 'headshapestyle', 'vertex'); cfg.template.headmodel = ft_getopt(cfg.template, 'headmodel', []); cfg.template.headmodelstyle = ft_getopt(cfg.template, 'headmodelstyle', 'edge'); cfg.template.mri = ft_getopt(cfg.template, 'mri', []); cfg.template.mristyle = ft_getopt(cfg.template, 'mristyle', 'intersect'); template = struct(cfg.template); individual = struct(cfg.individual); % ensure that they are consistent with the latest FieldTrip version if ~isempty(template.elec) template.elec = ft_datatype_sens(template.elec); end if ~isempty(individual.elec) individual.elec = ft_datatype_sens(individual.elec); end if ~isempty(template.headshape) template.headshape = fixpos(template.headshape); end if ~isempty(individual.headshape) individual.headshape = fixpos(individual.headshape); end % convert the coordinates of all geometrical objects into mm fn = {'elec', 'grad', 'headshape', 'headmodel', 'mri'}; for i=1:length(fn) if ~isempty(individual.(fn{i})) individual.(fn{i}) = ft_convert_units(individual.(fn{i}), 'mm'); end end for i=1:length(fn) if ~isempty(template.(fn{i})) template.(fn{i}) = ft_convert_units(template.(fn{i}), 'mm'); end end if ~isempty(template.headshape) if ~isfield(template.headshape, 'tri') || isempty(template.headshape.tri) template.headshape.tri = projecttri(template.headshape.pos); end end if ~isempty(individual.headshape) if ~isfield(individual.headshape, 'tri') || isempty(individual.headshape.tri) individual.headshape.tri = projecttri(individual.headshape.pos); end end % open a figure fig = figure; set(gca, 'position', [0.05 0.15 0.75 0.75]); axis([-150 150 -150 150 -150 150]); % add the data to the figure set(fig, 'CloseRequestFcn', @cb_quit); setappdata(fig, 'individual', individual); setappdata(fig, 'template', template); setappdata(fig, 'transform', eye(4)); setappdata(fig, 'cleanup', false); setappdata(fig, 'toggle_axes', 1); setappdata(fig, 'toggle_grid', 1); % add the GUI elements cb_creategui(gca); cb_redraw(gca); rotate3d on cleanup = false; while ~cleanup uiwait(fig); cfg.m = getappdata(fig, 'transform'); cleanup = getappdata(fig, 'cleanup'); end % remember the transform and touch it cfg.m = getappdata(fig, 'transform'); cfg.m; delete(fig); % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble provenance %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_creategui(h, eventdata, handles) % define the position of each GUI element fig = getparent(h); % constants CONTROL_WIDTH = 0.04; CONTROL_HEIGHT = 0.05; CONTROL_HOFFSET = 0.75; CONTROL_VOFFSET = 0.5; % rotateui uicontrol('tag', 'rotateui', 'parent', fig, 'units', 'normalized', 'style', 'text', 'string', 'rotate', 'callback', []) uicontrol('tag', 'rx', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) uicontrol('tag', 'ry', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) uicontrol('tag', 'rz', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) ft_uilayout(fig, 'tag', 'rotateui', 'BackgroundColor', [0.8 0.8 0.8], 'width', 2*CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET, 'vpos', CONTROL_VOFFSET+CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'rx', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+3*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET+CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'ry', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+4*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET+CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'rz', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+5*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET+CONTROL_HEIGHT); % scaleui uicontrol('tag', 'scaleui', 'parent', fig, 'units', 'normalized', 'style', 'text', 'string', 'scale', 'callback', []) uicontrol('tag', 'sx', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '1', 'callback', @cb_redraw) uicontrol('tag', 'sy', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '1', 'callback', @cb_redraw) uicontrol('tag', 'sz', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '1', 'callback', @cb_redraw) ft_uilayout(fig, 'tag', 'scaleui', 'BackgroundColor', [0.8 0.8 0.8], 'width', 2*CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET, 'vpos', CONTROL_VOFFSET-0*CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'sx', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+3*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-0*CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'sy', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+4*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-0*CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'sz', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+5*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-0*CONTROL_HEIGHT); % translateui uicontrol('tag', 'translateui', 'parent', fig, 'units', 'normalized', 'style', 'text', 'string', 'translate', 'callback', []) uicontrol('tag', 'tx', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) uicontrol('tag', 'ty', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) uicontrol('tag', 'tz', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) ft_uilayout(fig, 'tag', 'translateui', 'BackgroundColor', [0.8 0.8 0.8], 'width', 2*CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET, 'vpos', CONTROL_VOFFSET-1*CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'tx', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+3*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-1*CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'ty', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+4*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-1*CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'tz', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+5*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-1*CONTROL_HEIGHT); % control buttons uicontrol('tag', 'viewbtn', 'parent', fig, 'units', 'normalized', 'style', 'popup', 'string', 'top|bottom|left|right|front|back', 'value', 1, 'callback', @cb_view); uicontrol('tag', 'redisplaybtn', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'redisplay', 'value', [], 'callback', @cb_redraw); uicontrol('tag', 'applybtn', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'apply', 'value', [], 'callback', @cb_apply); uicontrol('tag', 'toggle labels', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'toggle label', 'value', 0, 'callback', @cb_redraw); uicontrol('tag', 'toggle axes', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'toggle axes', 'value', getappdata(fig, 'toggle_axes'), 'callback', @cb_redraw); uicontrol('tag', 'toggle grid', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'toggle grid', 'value', getappdata(fig, 'toggle_grid'), 'callback', @cb_redraw); uicontrol('tag', 'quitbtn', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'quit', 'value', 1, 'callback', @cb_quit); ft_uilayout(fig, 'tag', 'viewbtn', 'BackgroundColor', [0.8 0.8 0.8], 'width', 6*CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'vpos', CONTROL_VOFFSET-2*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); ft_uilayout(fig, 'tag', 'redisplaybtn', 'BackgroundColor', [0.8 0.8 0.8], 'width', 6*CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'vpos', CONTROL_VOFFSET-4*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); ft_uilayout(fig, 'tag', 'applybtn', 'BackgroundColor', [0.8 0.8 0.8], 'width', 6*CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'vpos', CONTROL_VOFFSET-5*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); ft_uilayout(fig, 'tag', 'toggle labels', 'BackgroundColor', [0.8 0.8 0.8], 'width', 6*CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'vpos', CONTROL_VOFFSET-6*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); ft_uilayout(fig, 'tag', 'toggle axes', 'BackgroundColor', [0.8 0.8 0.8], 'width', 6*CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'vpos', CONTROL_VOFFSET-7*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); ft_uilayout(fig, 'tag', 'toggle grid', 'BackgroundColor', [0.8 0.8 0.8], 'width', 6*CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'vpos', CONTROL_VOFFSET-8*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); ft_uilayout(fig, 'tag', 'quitbtn', 'BackgroundColor', [0.8 0.8 0.8], 'width', 6*CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'vpos', CONTROL_VOFFSET-9*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); % alpha ui (somehow not implemented, facealpha is fixed at 0.7 uicontrol('tag', 'alphaui', 'parent', fig, 'units', 'normalized', 'style', 'text', 'string', 'alpha', 'value', [], 'callback', []); uicontrol('tag', 'alpha', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0.6', 'value', [], 'callback', @cb_redraw); ft_uilayout(fig, 'tag', 'alphaui', 'BackgroundColor', [0.8 0.8 0.8], 'width', 3*CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'vpos', CONTROL_VOFFSET-3*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); ft_uilayout(fig, 'tag', 'alpha', 'BackgroundColor', [0.8 0.8 0.8], 'width', 3*CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'vpos', CONTROL_VOFFSET-3*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+3*CONTROL_WIDTH); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_redraw(h, eventdata, handles) fig = getparent(h); individual = getappdata(fig, 'individual'); template = getappdata(fig, 'template'); transform = getappdata(fig, 'transform'); % get the transformation details rx = str2double(get(findobj(fig, 'tag', 'rx'), 'string')); ry = str2double(get(findobj(fig, 'tag', 'ry'), 'string')); rz = str2double(get(findobj(fig, 'tag', 'rz'), 'string')); tx = str2double(get(findobj(fig, 'tag', 'tx'), 'string')); ty = str2double(get(findobj(fig, 'tag', 'ty'), 'string')); tz = str2double(get(findobj(fig, 'tag', 'tz'), 'string')); sx = str2double(get(findobj(fig, 'tag', 'sx'), 'string')); sy = str2double(get(findobj(fig, 'tag', 'sy'), 'string')); sz = str2double(get(findobj(fig, 'tag', 'sz'), 'string')); R = rotate ([rx ry rz]); T = translate([tx ty tz]); S = scale ([sx sy sz]); H = S * T * R; % combine the present transform according to the GUI with the one that has been previously applied transform = H * transform; axis vis3d; cla xlabel('x') ylabel('y') zlabel('z') hold on % the "individual" struct is a local copy, so it is safe to change it here if ~isempty(individual.headmodel) individual.headmodel = ft_transform_vol(transform, individual.headmodel); end if ~isempty(individual.elec) individual.elec = ft_transform_sens(transform, individual.elec); end if ~isempty(individual.grad) individual.grad = ft_transform_sens(transform, individual.grad); end if ~isempty(individual.headshape) individual.headshape = ft_transform_headshape(transform, individual.headshape); end if ~isempty(individual.mri) individual.mri.transform = transform * individual.mri.transform; end if ~isempty(template.mri) if strcmp(template.mristyle, 'intersect') ft_plot_ortho(template.mri.anatomy, 'transform', template.mri.transform, 'style', 'intersect', 'intersectmesh', individual.headshape); elseif strcmp(template.mristyle, 'montage') ft_plot_montage(template.mri.anatomy, 'transform', template.mri.transform, 'style', 'intersect', 'intersectmesh', individual.headshape); end end if ~isempty(individual.mri) if strcmp(individual.mristyle, 'intersect') ft_plot_ortho(individual.mri.anatomy, 'transform', individual.mri.transform, 'style', 'intersect', 'intersectmesh', template.headshape); elseif strcmp(individual.mristyle, 'montage') ft_plot_montage(individual.mri.anatomy, 'transform', individual.mri.transform, 'style', 'intersect', 'intersectmesh', template.headshape); end end if ~isempty(template.elec) % FIXME use ft_plot_sens if isfield(template.elec, 'line') tmpbnd = []; tmpbnd.pos = template.elec.chanpos; tmpbnd.tri = template.elec.line; ft_plot_mesh(tmpbnd,'vertexcolor', 'b', 'facecolor', 'none', 'edgecolor', 'b', 'vertexsize',10) else ft_plot_mesh(template.elec.chanpos,'vertexcolor', 'b', 'vertexsize',10); end end if ~isempty(individual.elec) % FIXME use ft_plot_sens if isfield(individual.elec, 'line') tmpbnd = []; tmpbnd.pos = individual.elec.chanpos; tmpbnd.tri = individual.elec.line; ft_plot_mesh(tmpbnd,'vertexcolor', 'r', 'facecolor', 'none', 'edgecolor', 'r', 'vertexsize',10) else ft_plot_mesh(individual.elec.chanpos,'vertexcolor', 'r', 'vertexsize',10); end end if ~isempty(template.grad) % FIXME use ft_plot_sens ft_plot_mesh(template.grad.chanpos,'vertexcolor', 'b', 'vertexsize',10); % FIXME also plot lines? end if ~isempty(individual.grad) % FIXME use ft_plot_sens ft_plot_mesh(individual.grad.chanpos,'vertexcolor', 'r', 'vertexsize',10); % FIXME also plot lines? end if ~isempty(template.headmodel) % FIXME this only works for boundary element models if strcmp(template.headmodelstyle, 'edge') vertexcolor = 'none'; edgecolor = 'k'; facecolor = 'none'; elseif strcmp(template.headmodelstyle, 'surface') vertexcolor = 'none'; edgecolor = 'none'; facecolor = 'skin'; elseif strcmp(template.headmodelstyle, 'both') vertexcolor = 'none'; edgecolor = 'k'; facecolor = 'skin'; end for i = 1:numel(template.headmodel.bnd) ft_plot_mesh(template.headmodel.bnd(i), 'facecolor', facecolor, 'vertexcolor', vertexcolor, 'edgecolor', edgecolor) end end if ~isempty(individual.headmodel) % FIXME this only works for boundary element models if strcmp(individual.headmodelstyle, 'edge') vertexcolor = 'none'; edgecolor = 'k'; facecolor = 'none'; elseif strcmp(individual.headmodelstyle, 'surface') vertexcolor = 'none'; edgecolor = 'none'; facecolor = 'skin'; elseif strcmp(individual.headmodelstyle, 'both') vertexcolor = 'none'; edgecolor = 'k'; facecolor = 'skin'; end for i = 1:numel(individual.headmodel.bnd) ft_plot_mesh(individual.headmodel.bnd(i), 'facecolor', facecolor, 'vertexcolor', vertexcolor, 'edgecolor', edgecolor) end end if ~isempty(template.headshape) if isfield(template.headshape, 'pos') && ~isempty(template.headshape.pos) if strcmp(template.headshapestyle, 'edge') vertexcolor = 'none'; edgecolor = 'k'; facecolor = 'none'; elseif strcmp(template.headshapestyle, 'surface') vertexcolor = 'none'; edgecolor = 'none'; facecolor = 'skin'; elseif strcmp(template.headshapestyle, 'both') vertexcolor = 'none'; edgecolor = 'k'; facecolor = 'skin'; end ft_plot_headshape(template.headshape, 'facecolor', facecolor, 'vertexcolor', vertexcolor, 'edgecolor', edgecolor) end end if ~isempty(individual.headshape) if isfield(individual.headshape, 'pos') && ~isempty(individual.headshape.pos) if strcmp(individual.headshapestyle, 'edge') vertexcolor = 'none'; edgecolor = 'k'; facecolor = 'none'; elseif strcmp(individual.headshapestyle, 'surface') vertexcolor = 'none'; edgecolor = 'none'; facecolor = 'skin'; elseif strcmp(individual.headshapestyle, 'both') vertexcolor = 'none'; edgecolor = 'k'; facecolor = 'skin'; end ft_plot_headshape(individual.headshape, 'facecolor', facecolor, 'vertexcolor', vertexcolor, 'edgecolor', edgecolor) end end alpha(str2double(get(findobj(fig, 'tag', 'alpha'), 'string'))); lighting gouraud material shiny camlight if strcmp(get(h, 'tag'), 'toggle axes') setappdata(fig, 'toggle_axes', ~getappdata(fig, 'toggle_axes')) end if getappdata(fig, 'toggle_axes') axis on else axis off end if strcmp(get(h, 'tag'), 'toggle grid') setappdata(fig, 'toggle_grid', ~getappdata(fig, 'toggle_grid')) end if getappdata(fig, 'toggle_grid') grid on else grid off end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_apply(h, eventdata, handles) fig = getparent(h); transform = getappdata(fig, 'transform'); % get the transformation details rx = str2double(get(findobj(fig, 'tag', 'rx'), 'string')); ry = str2double(get(findobj(fig, 'tag', 'ry'), 'string')); rz = str2double(get(findobj(fig, 'tag', 'rz'), 'string')); tx = str2double(get(findobj(fig, 'tag', 'tx'), 'string')); ty = str2double(get(findobj(fig, 'tag', 'ty'), 'string')); tz = str2double(get(findobj(fig, 'tag', 'tz'), 'string')); sx = str2double(get(findobj(fig, 'tag', 'sx'), 'string')); sy = str2double(get(findobj(fig, 'tag', 'sy'), 'string')); sz = str2double(get(findobj(fig, 'tag', 'sz'), 'string')); % create the transformation matrix; R = rotate ([rx ry rz]); T = translate([tx ty tz]); S = scale ([sx sy sz]); H = S * T * R; transform = H * transform; set(findobj(fig, 'tag', 'rx'), 'string', 0); set(findobj(fig, 'tag', 'ry'), 'string', 0); set(findobj(fig, 'tag', 'rz'), 'string', 0); set(findobj(fig, 'tag', 'tx'), 'string', 0); set(findobj(fig, 'tag', 'ty'), 'string', 0); set(findobj(fig, 'tag', 'tz'), 'string', 0); set(findobj(fig, 'tag', 'sx'), 'string', 1); set(findobj(fig, 'tag', 'sy'), 'string', 1); set(findobj(fig, 'tag', 'sz'), 'string', 1); setappdata(fig, 'transform', transform); if ~getappdata(fig, 'cleanup') cb_redraw(h); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_view(h, eventdata) % FIXME this is hardcoded for a particular (probably MNI/SPM) coordinate system val = get(h, 'value'); switch val case 1 view([90 90]); case 2 view([90 -90]); case 3 view([-90 0]); case 4 view([90 0]); case 5 view([-180 0]); case 6 view([0 0]); otherwise end uiresume; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_quit(h, eventdata) fig = getparent(h); setappdata(fig, 'cleanup', true); % ensure to apply the current transformation cb_apply(h); uiresume; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = getparent(h) p = h; while p~=0 h = p; p = get(h, 'parent'); end
github
lcnbeapp/beapp-master
ft_neighbourplot.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_neighbourplot.m
14,397
utf_8
775e543981ae4a5e32195c20d0bbdde8
function [cfg] = ft_neighbourplot(cfg, data) % FT_NEIGHBOURPLOT visualizes neighbouring channels in a particular channel % configuration. The positions of the channel are specified in a % gradiometer or electrode configuration or from a layout. % % Use as % ft_neighbourplot(cfg) % or as % ft_neighbourplot(cfg, data) % % where the configuration can contain % cfg.verbose = 'yes' or 'no', if 'yes' then the plot callback will include text output % cfg.neighbours = neighbourhood structure, see FT_PREPARE_NEIGHBOURS (optional) % cfg.enableedit = 'yes' or 'no' (default). allows the user to % flexibly add or remove edges between vertices % or one of the following options % cfg.layout = filename of the layout, see FT_PREPARE_LAYOUT % cfg.elec = structure with electrode definition % cfg.grad = structure with gradiometer definition % cfg.elecfile = filename containing electrode definition % cfg.gradfile = filename containing gradiometer definition % % If cfg.neighbours is not defined, this function will call % FT_PREPARE_NEIGHBOURS to determine the channel neighbours. The % following data fields may also be used by FT_PREPARE_NEIGHBOURS % data.elec = structure with EEG electrode positions % data.grad = structure with MEG gradiometer positions % If cfg.neighbours is empty, no neighbouring sensors are assumed. % % Use cfg.enableedit to create or extend your own neighbourtemplate % % See also FT_PREPARE_NEIGHBOURS, FT_PREPARE_LAYOUT % Copyright (C) 2011, J?rn M. Horschig, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar data ft_preamble provenance data ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % the data can be passed as input arguments or can be read from disk hasdata = exist('data', 'var'); if hasdata % check if the input data is valid for this function data = ft_checkdata(data); end cfg.enableedit = ft_getopt(cfg, 'enableedit', 'no'); if isfield(cfg, 'neighbours') cfg.neighbours = cfg.neighbours; elseif hasdata cfg.neighbours = ft_prepare_neighbours(cfg, data); else cfg.neighbours = ft_prepare_neighbours(cfg); end if ~isfield(cfg, 'verbose') cfg.verbose = 'no'; elseif strcmp(cfg.verbose, 'yes') cfg.verbose = true; end % get the the grad or elec if hasdata sens = ft_fetch_sens(cfg, data); else sens = ft_fetch_sens(cfg); end % insert sensors that are not in neighbourhood structure if isempty(cfg.neighbours) nsel = 1:numel(sens.label); else nsel = find(~ismember(sens.label, {cfg.neighbours.label})); end for i=1:numel(nsel) cfg.neighbours(end+1).label = sens.label{nsel(i)}; cfg.neighbours(end).neighblabel = {}; end [tmp, sel] = match_str(sens.label, {cfg.neighbours.label}); cfg.neighbours = cfg.neighbours(sel); % give some graphical feedback if all(sens.chanpos(:,3)==0) % the sensor positions are already projected on a 2D plane proj = sens.chanpos(:,1:2); else % use 3-dimensional data for plotting proj = sens.chanpos; end hf = figure; axis equal axis vis3d axis off hold on; hl = []; for i=1:length(cfg.neighbours) this = cfg.neighbours(i); sel1 = match_str(sens.label, this.label); sel2 = match_str(sens.label, this.neighblabel); % account for missing sensors this.neighblabel = sens.label(sel2); for j=1:length(this.neighblabel) x1 = proj(sel1,1); y1 = proj(sel1,2); x2 = proj(sel2(j),1); y2 = proj(sel2(j),2); X = [x1 x2]; Y = [y1 y2]; if size(proj, 2) == 2 hl(sel1, sel2(j)) = line(X, Y, 'color', 'r'); elseif size(proj, 2) == 3 z1 = proj(sel1,3); z2 = proj(sel2(j),3); Z = [z1 z2]; hl(sel1, sel2(j)) = line(X, Y, Z, 'color', 'r'); end end end % this is for putting the channels on top of the connections hs = []; for i=1:length(cfg.neighbours) this = cfg.neighbours(i); sel1 = match_str(sens.label, this.label); sel2 = match_str(sens.label, this.neighblabel); % account for missing sensors this.neighblabel = sens.label(sel2); if isempty(sel1) continue; end if size(proj, 2) == 2 hs(i) = line(proj(sel1, 1), proj(sel1, 2), ... 'MarkerEdgeColor', 'k', ... 'MarkerFaceColor', 'k', ... 'Marker', 'o', ... 'MarkerSize', .125*(2+numel(cfg.neighbours(i).neighblabel))^2, ... 'UserData', i, ... 'ButtonDownFcn', @showLabelInTitle); elseif size(proj, 2) == 3 hs(i) = line(proj(sel1, 1), proj(sel1, 2), proj(sel1, 3), ... 'MarkerEdgeColor', 'k', ... 'MarkerFaceColor', 'k', ... 'Marker', 'o', ... 'MarkerSize', .125*(2+numel(cfg.neighbours(i).neighblabel))^2, ... 'UserData', i, ... 'ButtonDownFcn', @showLabelInTitle); else error('Channel coordinates are too high dimensional'); end end hold off; title('[Click on a sensor to see its label]'); % store what is needed in UserData of figure userdata.lastSensId = []; userdata.cfg = cfg; userdata.sens = sens; userdata.hs = hs; userdata.hl = hl; userdata.quit = false; hf = getparent(hf); set(hf, 'UserData', userdata); if istrue(cfg.enableedit) set(hf, 'CloseRequestFcn', @cleanup_cb); while ~userdata.quit uiwait(hf); userdata = get(hf, 'UserData'); end cfg = userdata.cfg; hf = getparent(hf); delete(hf); end % in any case remove SCALE and COMNT desired = ft_channelselection({'all', '-SCALE', '-COMNT'}, {cfg.neighbours.label}); neighb_idx = ismember({cfg.neighbours.label}, desired); cfg.neighbours = cfg.neighbours(neighb_idx); % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous data ft_postamble provenance end % main function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function showLabelInTitle(gcbo, EventData, handles) userdata = get(gcf, 'UserData'); lastSensId = userdata.lastSensId; cfg = userdata.cfg; hs = userdata.hs; curSensId = get(gcbo, 'UserData'); if lastSensId == curSensId title('[Click on a sensor to see its label]'); set(hs(curSensId), 'MarkerFaceColor', 'k'); userdata.lastSensId = []; elseif isempty(lastSensId) || ~istrue(cfg.enableedit) userdata.lastSensId = curSensId; if istrue(cfg.enableedit) title(['Selected channel: ' cfg.neighbours(curSensId).label ' click on another to (dis-)connect']); else title(['Selected channel: ' cfg.neighbours(curSensId).label]); end if cfg.verbose str = sprintf('%s, ', cfg.neighbours(curSensId).neighblabel{:}); if length(str)>2 % remove the last comma and space str = str(1:end-2); end fprintf('Selected channel %s, which has %d neighbours: %s\n', ... cfg.neighbours(curSensId).label, ... length(cfg.neighbours(curSensId).neighblabel), ... str); end set(hs(curSensId), 'MarkerFaceColor', 'g'); set(hs(lastSensId), 'MarkerFaceColor', 'k'); elseif istrue(cfg.enableedit) hl = userdata.hl; sens = userdata.sens; if all(sens.chanpos(:,3)==0) % the sensor positions are already projected on a 2D plane proj = sens.chanpos(:,1:2); else % use 3-dimensional data for plotting proj = sens.chanpos; end % find out whether they are connected connected1 = ismember(cfg.neighbours(curSensId).neighblabel, cfg.neighbours(lastSensId).label); connected2 = ismember(cfg.neighbours(lastSensId).neighblabel, cfg.neighbours(curSensId).label); if any(connected1) % then disconnect cfg.neighbours(curSensId).neighblabel(connected1) = []; cfg.neighbours(lastSensId).neighblabel(connected2) = []; title(['Disconnected channels ' cfg.neighbours(curSensId).label ' and ' cfg.neighbours(lastSensId).label]); delete(hl(curSensId, lastSensId)); hl(curSensId, lastSensId) = 0; delete(hl(lastSensId, curSensId)); hl(lastSensId, curSensId) = 0; else % then connect cfg.neighbours(curSensId).neighblabel{end+1} = cfg.neighbours(lastSensId).label; cfg.neighbours(lastSensId).neighblabel{end+1} = cfg.neighbours(curSensId).label; title(['Connected channels ' cfg.neighbours(curSensId).label ' and ' cfg.neighbours(lastSensId).label]); % draw new edge x1 = proj(curSensId,1); y1 = proj(curSensId,2); x2 = proj(lastSensId,1); y2 = proj(lastSensId,2); X = [x1 x2]; Y = [y1 y2]; if size(proj, 2) == 2 hl(curSensId, lastSensId) = line(X, Y, 'color', 'r'); hl(lastSensId, curSensId) = line(X, Y, 'color', 'r'); elseif size(proj, 2) == 3 z1 = proj(curSensId,3); z2 = proj(lastSensId,3); Z =[z1 z2]; hl(curSensId, lastSensId) = line(X, Y, Z, 'color', 'r'); hl(lastSensId, curSensId) = line(X, Y, Z, 'color', 'r'); end end % draw nodes on top again delete(hs(curSensId)); delete(hs(lastSensId)); if size(proj, 2) == 2 hs(curSensId) = line(proj(curSensId, 1), proj(curSensId, 2), ... 'MarkerEdgeColor', 'k', ... 'MarkerFaceColor', 'k', ... 'Marker', 'o', ... 'MarkerSize', .125*(2+numel(cfg.neighbours(curSensId).neighblabel))^2, ... 'UserData', curSensId, ... 'ButtonDownFcn', @showLabelInTitle); hs(lastSensId) = line(proj(lastSensId, 1), proj(lastSensId, 2), ... 'MarkerEdgeColor', 'k', ... 'MarkerFaceColor', 'k', ... 'Marker', 'o', ... 'MarkerSize', .125*(2+numel(cfg.neighbours(lastSensId).neighblabel))^2, ... 'UserData', lastSensId, ... 'ButtonDownFcn', @showLabelInTitle); elseif size(proj, 2) == 3 hs(curSensId) = line(proj(curSensId, 1), proj(curSensId, 2), proj(curSensId, 3), ... 'MarkerEdgeColor', 'k', ... 'MarkerFaceColor', 'k', ... 'Marker', 'o', ... 'MarkerSize', .125*(2+numel(cfg.neighbours(curSensId).neighblabel))^2, ... 'UserData', curSensId, ... 'ButtonDownFcn', @showLabelInTitle); hs(lastSensId) = line(proj(lastSensId, 1), proj(lastSensId, 2), proj(lastSensId, 3), ... 'MarkerEdgeColor', 'k', ... 'MarkerFaceColor', 'k', ... 'Marker', 'o', ... 'MarkerSize', .125*(2+numel(cfg.neighbours(lastSensId).neighblabel))^2, ... 'UserData', lastSensId, ... 'ButtonDownFcn', @showLabelInTitle); else error('Channel coordinates are too high dimensional'); end if cfg.verbose str = sprintf('%s, ', cfg.neighbours(curSensId).neighblabel{:}); if length(str)>2 % remove the last comma and space str = str(1:end-2); end fprintf('Selected channel %s, which has %d neighbours: %s\n', ... cfg.neighbours(curSensId).label, ... length(cfg.neighbours(curSensId).neighblabel), ... str); end set(hs(curSensId), 'MarkerFaceColor', 'g'); set(hs(lastSensId), 'MarkerFaceColor', 'k'); userdata.lastSensId = curSensId; userdata.hl = hl; userdata.hs = hs; userdata.cfg = cfg; set(gcf, 'UserData', userdata); return; else % can never happen, so do nothing end set(gcf, 'UserData', userdata); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cleanup_cb(h, eventdata) userdata = get(h, 'UserData'); h = getparent(h); userdata.quit = true; set(h, 'UserData', userdata); uiresume end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = getparent(h) p = h; while p~=0 h = p; p = get(h, 'parent'); end end
github
lcnbeapp/beapp-master
ft_appendfreq.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_appendfreq.m
14,982
utf_8
cb5cb36f0468f54d1ad2e83c9b40ee46
function [freq] = ft_appendfreq(cfg, varargin) % FT_APPENDFREQ concatenates multiple frequency or time-frequency data % structures that have been processed separately. If the input data % structures contain different channels, it will be concatenated along the % channel direction. If the channels are identical in the input data % structures, the data will be concatenated along the repetition dimension. % % Use as % combined = ft_appendfreq(cfg, freq1, freq2, ...) % % cfg.parameter = String. Specifies the name of the field to concatenate. % For example, to concatenate freq1.powspctrm, % freq2.powspctrm etc, use cft.parameter = 'powspctrm'. % % The configuration can optionally contain % cfg.appenddim = String. The dimension to concatenate over (default is 'auto'). % cfg.tolerance = Double. Tolerance determines how different the units of % frequency structures are allowed to be to be considered % compatible (default: 1e-5). % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % cfg.outputfile = ... % If you specify one of these (or both) the input data will be read from a % *.mat file on disk and/or the output data will be written to a *.mat file. % These mat files should contain only a single variable, corresponding with % the input/output structure. % % See also FT_FREQANALYSIS, FT_APPENDDATA, FT_APPENDTIMELOCK, FT_APPENDSOURCE % Copyright (C) 2011, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar varargin ft_preamble provenance varargin ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input data is valid for this function for i=1:length(varargin) varargin{i} = ft_checkdata(varargin{i}, 'datatype', 'freq'); end % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'required', 'parameter'); % set the defaults cfg.channel = ft_getopt(cfg, 'channel', 'all'); cfg.appenddim = ft_getopt(cfg, 'appenddim', 'auto'); cfg.tolerance = ft_getopt(cfg, 'tolerance', 1e-5); % do a basic check to see whether the dimords match Ndata = length(varargin); dimord = cell(1,Ndata); for i=1:Ndata dimord{i} = varargin{i}.dimord; end dimordmatch = all(strcmp(dimord{1}, dimord)); if ~dimordmatch error('the dimords of the input data structures are not equal'); end % create the output structure from scratch freq = []; tol = cfg.tolerance; dimtok = tokenize(dimord{1}, '_'); switch cfg.appenddim case 'auto' % only allow to append across observations if these are present in the data if any(strcmp(dimtok, 'rpt')) cfg.appenddim = 'rpt'; elseif any(strcmp(dimtok, 'rpttap')) cfg.appenddim = 'rpttap'; elseif any(strcmp(dimtok, 'subj')) cfg.appenddim = 'subj'; else % we need to check whether the other dimensions are the same. % if not, consider some tolerance. boolval1 = checkchan(varargin{:}, 'identical'); boolval2 = checkfreq(varargin{:}, 'identical', tol); if isfield(varargin{1}, 'time'), boolval3 = checktime(varargin{:}, 'identical', tol); if boolval1 && boolval2 && boolval3 % each of the input datasets contains a single repetition (perhaps an average), these can be concatenated cfg.appenddim = 'rpt'; elseif ~boolval1 && boolval2 && boolval3 cfg.appenddim = 'chan'; elseif boolval1 && ~boolval2 && boolval3 cfg.appenddim = 'freq'; elseif boolval1 && boolval2 && ~boolval3 cfg.appenddim = 'time'; else error('the input datasets have multiple non-identical dimensions, this function only appends one dimension at a time'); end else if boolval1 && boolval2 % each of the input datasets contains a single repetition (perhaps an average), these can be concatenated cfg.appenddim = 'rpt'; elseif ~boolval1 && boolval2 cfg.appenddim = 'chan'; elseif boolval1 && ~boolval2 cfg.appenddim = 'freq'; end end end % determine the dimension for appending end switch cfg.appenddim case {'rpt' 'rpttap' 'subj'} catdim = find(ismember(dimtok, {'rpt' 'rpttap' 'subj'})); if numel(catdim)==0 catdim = 0; elseif numel(catdim)==1 % this is OK elseif numel(catdim)>1 error('ambiguous dimord for concatenation'); end % if any of these are present, concatenate % if not prepend the dimord with rpt (and thus shift the dimensions) % here we need to check whether the other dimensions are the same. if % not, consider some tolerance. boolval1 = checkchan(varargin{:}, 'identical'); boolval2 = checkfreq(varargin{:}, 'identical', tol); if isfield(varargin{1}, 'time'), boolval3 = checktime(varargin{:}, 'identical', tol); else boolval3 = true; end if any([boolval2 boolval3]==false) error('appending across observations is not possible, because the frequency and/or temporal dimensions are incompatible'); end % select and reorder the channels that are in every dataset tmpcfg = []; tmpcfg.channel = cfg.channel; tmpcfg.tolerance = cfg.tolerance; [varargin{:}] = ft_selectdata(tmpcfg, varargin{:}); for i=1:Ndata [cfg_rolledback, varargin{i}] = rollback_provenance(cfg, varargin{i}); end cfg = cfg_rolledback; % update the dimord if catdim==0 freq.dimord = ['rpt_',varargin{1}.dimord]; % FIXME append dof else freq.dimord = varargin{1}.dimord; % FIXME append dof % before append cumtapcnt cumsumcnt trialinfo check if there's a % subfield in each dataset. Append fields of different dataset might % lead in empty and/or non-existing fields in a particular dataset hascumsumcnt = []; hascumtapcnt = []; hastrialinfo = []; for i=1:Ndata if isfield(varargin{i},'cumsumcnt'); hascumsumcnt(end+1) = 1; else hascumsumcnt(end+1) = 0; end if isfield(varargin{i},'cumtapcnt'); hascumtapcnt(end+1) = 1; else hascumtapcnt(end+1) = 0; end if isfield(varargin{i},'trialinfo'); hastrialinfo(end+1) = 1; else hastrialinfo(end+1) = 0; end end % screen concatenable fields if ~checkfreq(varargin{:}, 'identical', tol) error('the freq fields of the input data structures are not equal'); else freq.freq=varargin{1}.freq; end if ~sum(hascumsumcnt)==0 && ~(sum(hascumsumcnt)==Ndata); error('the cumsumcnt fields of the input data structures are not equal'); else iscumsumcnt=unique(hascumsumcnt); end if ~sum(hascumtapcnt)==0 && ~(sum(hascumtapcnt)==Ndata); error('the cumtapcnt fields of the input data structures are not equal'); else iscumtapcnt=unique(hascumtapcnt); end if ~sum(hastrialinfo)==0 && ~(sum(hastrialinfo)==Ndata); error('the trialinfo fields of the input data structures are not equal'); else istrialinfo=unique(hastrialinfo); end % concatenating fields for i=1:Ndata; if iscumsumcnt; cumsumcnt{i}=varargin{i}.cumsumcnt; end if iscumtapcnt; cumtapcnt{i}=varargin{i}.cumtapcnt; end if istrialinfo; trialinfo{i}=varargin{i}.trialinfo; end end % fill in the rest of the descriptive fields if iscumsumcnt; freq.cumsumcnt = cat(catdim,cumsumcnt{:}); clear cumsumcnt; end if iscumtapcnt; freq.cumtapcnt = cat(catdim,cumtapcnt{:}); clear cumtapcnt; end if istrialinfo; freq.trialinfo = cat(catdim,trialinfo{:}); clear trialinfo; end end freq.label = varargin{1}.label; freq.freq = varargin{1}.freq; if isfield(varargin{1}, 'time'), freq.time = varargin{1}.time; end case 'chan' catdim = find(strcmp('chan', dimtok)); if isempty(catdim) % try chancmb catdim = find(strcmp('chancmb', dimtok)); elseif numel(catdim)>1 error('ambiguous dimord for concatenation'); end % check whether all channels are unique and throw an error if not [boolval, list] = checkchan(varargin{:}, 'unique'); if ~boolval error('the input data structures have non-unique channels, concatenation across channel is not possible'); end if isfield(varargin{1}, 'time') if ~checktime(varargin{:}, 'identical', tol) error('the input data structures have non-identical time bins, concatenation across channels not possible'); end end if ~checkfreq(varargin{:}, 'identical', tol) error('the input data structures have non-identical frequency bins, concatenation across channels not possible'); end % update the channel description freq.label = list; % fill in the rest of the descriptive fields freq.freq = varargin{1}.freq; if isfield(varargin{1}, 'time'), freq.time = varargin{1}.time; end freq.dimord = varargin{1}.dimord; case 'freq' catdim = find(strcmp('freq', dimtok)); % check whether all frequencies are unique and throw an error if not [boolval, list] = checkfreq(varargin{:}, 'unique', tol); if ~boolval error('the input data structures have non-unique frequency bins, concatenation across frequency is not possible'); end if ~checkchan(varargin{:}, 'identical') error('the input data structures have non-identical channels, concatenation across frequency not possible'); end if isfield(varargin{1}, 'time') if ~checktime(varargin{:}, 'identical', tol) error('the input data structures have non-identical time bins, concatenation across channels not possible'); end end % update the frequency description freq.freq = list(:)'; % fill in the rest of the descriptive fields freq.label = varargin{1}.label; freq.dimord = varargin{1}.dimord; if isfield(varargin{1}, 'time'), freq.time = varargin{1}.time; end case 'time' catdim = find(strcmp('time', dimtok)); % check whether all time points are unique and throw an error if not [boolval, list] = checktime(varargin{:}, 'unique', tol); if ~boolval error('the input data structures have non-unique time bins, concatenation across time is not possible'); end if ~checkchan(varargin{:}, 'identical') error('the input data structures have non-identical channels, concatenation across time not possible'); end if ~checkfreq(varargin{:}, 'identical', tol) error('the input data structures have non-identical frequency bins, concatenation across time not possible'); end % update the time description freq.time = list(:)'; % fill in the rest of the descriptive fields freq.label = varargin{1}.label; freq.freq = varargin{1}.freq; freq.dimord = varargin{1}.dimord; otherwise error('it is not allowed to concatenate across dimension %s',cfg.appenddim); end param = cfg.parameter; if ~iscell(param), param = {param}; end % are we appending along the channel dimension? catchan = strcmp(cfg.appenddim, 'chan'); chandim = find(strcmp('chan', dimtok)); % concatenate the numeric data for k = 1:numel(param) tmp = cell(1,Ndata); % get the numeric data 'param{k}' if present for m = 1:Ndata if ~isfield(varargin{m}, param{k}) error('parameter %s is not present in all data sets', param{k}); end tmp{m} = varargin{m}.(param{k}); % if we are not appending along the channel dimension, make sure we % reorder the channel dimension across the different data sets. At this % point we can be sure that all data sets have identical channels. if ~catchan && m > 1 [a,b] = match_str(varargin{1}.label, varargin{m}.label); if ~all(a==b) tmp{m} = reorderdim(tmp{m}, chandim, b); end end end if catdim==0, ndim = length(size(tmp{1})); freq.(param{k}) = permute(cat(ndim+1,tmp{:}),[ndim+1 1:ndim]); else freq.(param{k}) = cat(catdim,tmp{:}); end end % for k = 1:numel(param) % deal with the sensor information, if present if isfield(varargin{1}, 'grad') || isfield(varargin{1}, 'elec') keepsensinfo = true; if isfield(varargin{1}, 'grad'), sensfield = 'grad'; end if isfield(varargin{1}, 'elec'), sensfield = 'elec'; end for k = 2:Ndata keepsensinfo = keepsensinfo && isequaln(varargin{1}.(sensfield), varargin{k}.(sensfield)); end if keepsensinfo, freq.(sensfield) = varargin{1}.(sensfield); end end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous varargin ft_postamble provenance freq ft_postamble history freq ft_postamble savevar freq %--------------------------------------------- % subfunction to check uniqueness of freq bins function [boolval, faxis] = checkfreq(varargin) % last input is always the required string tol = varargin{end}; required = varargin{end-1}; varargin = varargin(1:end-2); Ndata = numel(varargin); Nfreq = zeros(1,Ndata); faxis = zeros(1,0); for i=1:Ndata Nfreq(i) = numel(varargin{i}.freq); faxis = [faxis;varargin{i}.freq(:)]; end if strcmp(required, 'unique') boolval = numel(unique(faxis))==numel(faxis) && ~all(isnan(faxis)); % the second condition is included when the freq is set to dummy nan elseif strcmp(required, 'identical') % the number of frequency bins needs at least to be the same across % inputs boolval = all(Nfreq==Nfreq(1)); if boolval % then check whether the axes are equal faxis = reshape(faxis, Nfreq(1), []); boolval = all(all(abs(faxis - repmat(faxis(:,1), 1, Ndata))<tol)==1); faxis = faxis(:,1); end end
github
lcnbeapp/beapp-master
ft_electroderealign.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_electroderealign.m
38,512
utf_8
66eebcaea5b14ce2be2ddce9abd44d98
function [elec_realigned] = ft_electroderealign(cfg, elec_original) % FT_ELECTRODEREALING rotates, translates, scales and warps electrode positions. The % default is to only rotate and translate, i.e. to do a rigid body transformation in % which only the coordinate system is changed. With the right settings if can apply % additional deformations to the input sensors (e.g. scale them to better fit the % skin surface). The different methods are described in detail below. % % INTERACTIVE - You can display the skin surface together with the % electrode or gradiometer positions, and manually (using the graphical % user interface) adjust the rotation, translation and scaling parameters, % so that the electrodes correspond with the skin. % % FIDUCIAL - You can apply a rigid body realignment based on three fiducial % locations. After realigning, the fiducials in the input electrode set % (typically nose, left and right ear) are along the same axes as the % fiducials in the template electrode set. % % TEMPLATE - You can apply a spatial transformation/deformation that % automatically minimizes the distance between the electrodes or % gradiometers and a template or sensor array. The warping methods use a % non-linear search to minimize the distance between the input sensor % positions and the corresponding template sensors. % % HEADSHAPE - You can apply a spatial transformation/deformation that % automatically minimizes the distance between the electrodes and the head % surface. The warping methods use a non-linear search to minimize the % distance between the input sensor positions and the projection of the % electrodes on the head surface. % % PROJECT - This projects all electrodes to the nearest point on the % head surface mesh. % % Use as % [elec_realigned] = ft_sensorrealign(cfg) % with the electrode or gradiometer details in the configuration, or as % [elec_realigned] = ft_sensorrealign(cfg, elec_orig) % with the electrode or gradiometer definition as 2nd input argument. % % The configuration can contain the following options % cfg.method = string representing the method for aligning or placing the electrodes % 'interactive' realign manually using a graphical user interface % 'fiducial' realign using three fiducials (e.g. NAS, LPA and RPA) % 'template' realign the electrodes to match a template set % 'headshape' realign the electrodes to fit the head surface % 'project' projects electrodes onto the head surface % cfg.warp = string describing the spatial transformation for the template and headshape methods % 'rigidbody' apply a rigid-body warp (default) % 'globalrescale' apply a rigid-body warp with global rescaling % 'traditional' apply a rigid-body warp with individual axes rescaling % 'nonlin1' apply a 1st order non-linear warp % 'nonlin2' apply a 2nd order non-linear warp % 'nonlin3' apply a 3rd order non-linear warp % 'nonlin4' apply a 4th order non-linear warp % 'nonlin5' apply a 5th order non-linear warp % 'dykstra2012' non-linear wrap only for headshape % method useful for projecting ECoG onto % cortex hull. % cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), % see FT_CHANNELSELECTION for details % cfg.fiducial = cell-array with the name of three fiducials used for % realigning (default = {'nasion', 'lpa', 'rpa'}) % cfg.casesensitive = 'yes' or 'no', determines whether string comparisons % between electrode labels are case sensitive (default = 'yes') % cfg.feedback = 'yes' or 'no' (default = 'no') % % The electrode positions can be present in the 2nd input argument or can be specified as % cfg.elec = structure with electrode positions, see FT_DATATYPE_SENS % cfg.elecfile = name of file containing the electrode positions, see FT_READ_SENS % % If you want to realign the EEG electrodes using anatomical fiducials, the template % has to contain the three fiducials, e.g. % cfg.target.pos(1,:) = [110 0 0] % location of the nose % cfg.target.pos(2,:) = [0 90 0] % location of the left ear % cfg.target.pos(3,:) = [0 -90 0] % location of the right ear % cfg.target.label = {'NAS', 'LPA', 'RPA'} % % If you want to align EEG electrodes to a single or multiple template electrode sets % (which will be averaged), you should specify the template electrode sets either as % electrode structures (i.e. when they are already read in memory) or their file % names using % cfg.target = single electrode set that serves as standard % or % cfg.target{1..N} = list of electrode sets that will be averaged % % If you want to align EEG electrodes to the head surface, you should specify the head surface as % cfg.headshape = a filename containing headshape, a structure containing a % single triangulated boundary, or a Nx3 matrix with surface % points % % If you want to align ECoG electrodes to the pial surface, you first need to % compute the cortex hull with FT_PREPARE_MESH. dykstra2012 uses algorithm % described in Dykstra et al. (2012, Neuroimage) in which electrodes are % projected onto pial surface while minimizing the displacement of the % electrodes from original location and maintaining the grid shape. It relies % on the optimization toolbox. % cfg.method = 'headshape' % cfg.warp = 'dykstra2012' % cfg.headshape = a filename containing headshape, a structure containing a % single triangulated boundary, or a Nx3 matrix with surface % points % cfg.feedback = 'yes' or 'no' (feedback includes the output of the iteration % procedure. % % See also FT_READ_SENS, FT_VOLUMEREALIGN, FT_INTERACTIVEREALIGN, FT_PREPARE_MESH % Copyright (C) 2005-2015, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % the interactive method uses a global variable to get the data from the figure when it is closed global norm % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar elec_original ft_preamble provenance elec_original ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'renamed', {'template', 'target'}); cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'realignfiducials', 'fiducial'}); cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'realignfiducial', 'fiducial'}); cfg = ft_checkconfig(cfg, 'renamedval', {'warp', 'homogenous', 'rigidbody'}); cfg = ft_checkconfig(cfg, 'renamedval', {'warp', 'homogeneous', 'rigidbody'}); cfg = ft_checkconfig(cfg, 'forbidden', 'outline'); % set the defaults cfg.warp = ft_getopt(cfg, 'warp', 'rigidbody'); cfg.channel = ft_getopt(cfg, 'channel', 'all'); cfg.feedback = ft_getopt(cfg, 'feedback', 'no'); cfg.casesensitive = ft_getopt(cfg, 'casesensitive', 'no'); cfg.headshape = ft_getopt(cfg, 'headshape', []); % for triangulated head surface, without labels cfg.target = ft_getopt(cfg, 'target', []); % for electrodes or fiducials, always with labels cfg.coordsys = ft_getopt(cfg, 'coordsys'); % this allows for automatic template fiducial placement if ~isempty(cfg.coordsys) && isempty(cfg.target) % set the template fiducial locations according to the coordinate system switch lower(cfg.coordsys) case 'ctf' cfg.target = []; cfg.target.coordsys = 'ctf'; cfg.target.pos(1,:) = [100 0 0]; cfg.target.pos(2,:) = [0 80 0]; cfg.target.pos(3,:) = [0 -80 0]; cfg.target.label{1} = 'NAS'; cfg.target.label{2} = 'LPA'; cfg.target.label{3} = 'RPA'; otherwise error('the %s coordinate system is not automatically supported, please specify fiducial details in cfg.target') end end % ensure that the right cfg options have been set corresponding to the method switch cfg.method case 'template' % realign the sensors to match a template set cfg = ft_checkconfig(cfg, 'required', 'target', 'forbidden', 'headshape'); case 'headshape' % realign the sensors to fit the head surface cfg = ft_checkconfig(cfg, 'required', 'headshape', 'forbidden', 'target'); case 'fiducial' % realign using the NAS, LPA and RPA fiducials cfg = ft_checkconfig(cfg, 'required', 'target', 'forbidden', 'headshape'); end % switch cfg.method if strcmp(cfg.method, 'fiducial') && isfield(cfg, 'warp') && ~isequal(cfg.warp, 'rigidbody') warning('The method ''fiducial'' implies a rigid body tramsformation. See also http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=1722'); cfg.warp = 'rigidbody'; end if strcmp(cfg.method, 'fiducial') && isfield(cfg, 'warp') && ~isequal(cfg.warp, 'rigidbody') warning('The method ''interactive'' implies a rigid body tramsformation. See also http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=1722'); cfg.warp = 'rigidbody'; end if isfield(cfg, 'headshape') && isa(cfg.headshape, 'config') % convert the nested config-object back into a normal structure cfg.headshape = struct(cfg.headshape); end if isfield(cfg, 'target') && isa(cfg.target, 'config') % convert the nested config-object back into a normal structure cfg.target = struct(cfg.target); end % the data can be passed as input arguments or can be read from disk hasdata = exist('data', 'var'); % get the electrode definition that should be warped if ~hasdata elec_original = ft_fetch_sens(cfg); else % the input electrodes were specified as second input argument % or read from cfg.inputfile end % ensure that the units are specified elec_original = ft_convert_units(elec_original); % ensure up-to-date sensor description (Oct 2011) elec_original = ft_datatype_sens(elec_original); % ensure that channel and electrode positions are the same assert(isequaln(elec_original.elecpos, elec_original.chanpos), 'this function requires same electrode and channel positions.'); % remember the original electrode locations and labels and do all the work with a % temporary copy, this involves channel selection and changing to lower case elec = elec_original; % instead of working with all sensors, only work with the fiducials % this is useful for gradiometer structures if strcmp(cfg.method, 'fiducial') && isfield(elec, 'fid') fprintf('using the fiducials instead of the sensor positions\n'); elec.fid.unit = elec.unit; elec = elec.fid; end usetarget = isfield(cfg, 'target') && ~isempty(cfg.target); useheadshape = isfield(cfg, 'headshape') && ~isempty(cfg.headshape); if usetarget % get the template electrode definitions if ~iscell(cfg.target) cfg.target = {cfg.target}; end Ntemplate = length(cfg.target); for i=1:Ntemplate if isstruct(cfg.target{i}) target(i) = cfg.target{i}; else target(i) = ft_read_sens(cfg.target{i}); end end clear tmp for i=1:Ntemplate % ensure up-to-date sensor description % ensure that the units are consistent with the electrodes tmp(i) = ft_convert_units(ft_datatype_sens(target(i)), elec.unit); end target = tmp; end if useheadshape % get the surface describing the head shape if isstruct(cfg.headshape) && isfield(cfg.headshape, 'hex') cfg.headshape = fixpos(cfg.headshape); fprintf('extracting surface from hexahedral mesh\n'); headshape = mesh2edge(cfg.headshape); headshape = poly2tri(headshape); elseif isstruct(cfg.headshape) && isfield(cfg.headshape, 'tet') cfg.headshape = fixpos(cfg.headshape); fprintf('extracting surface from tetrahedral mesh\n'); headshape = mesh2edge(cfg.headshape); elseif isstruct(cfg.headshape) && isfield(cfg.headshape, 'tri') cfg.headshape = fixpos(cfg.headshape); headshape = cfg.headshape; elseif isnumeric(cfg.headshape) && size(cfg.headshape,2)==3 % use the headshape points specified in the configuration headshape.pos = cfg.headshape; elseif ischar(cfg.headshape) % read the headshape from file headshape = ft_read_headshape(cfg.headshape); else error('cfg.headshape is not specified correctly') end if ~isfield(headshape, 'tri') && ~isfield(headshape, 'poly') % generate a closed triangulation from the surface points headshape.pos = unique(headshape.pos, 'rows'); headshape.tri = projecttri(headshape.pos); end headshape = ft_convert_units(headshape, elec.unit); % ensure that the units are consistent with the electrodes end % convert all labels to lower case for string comparisons % this has to be done AFTER keeping the original labels and positions if strcmp(cfg.casesensitive, 'no') for i=1:length(elec.label) elec.label{i} = lower(elec.label{i}); end if usetarget for j=1:length(target) for i=1:length(target(j).label) target(j).label{i} = lower(target(j).label{i}); end end end end % start with an empty structure, this will be returned at the end norm = []; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(cfg.method, 'template') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % determine electrode selection and overlapping subset for warping cfg.channel = ft_channelselection(cfg.channel, elec.label); for i=1:Ntemplate cfg.channel = ft_channelselection(cfg.channel, target(i).label); end % make consistent subselection of electrodes [cfgsel, datsel] = match_str(cfg.channel, elec.label); elec.label = elec.label(datsel); elec.elecpos = elec.elecpos(datsel,:); for i=1:Ntemplate [cfgsel, datsel] = match_str(cfg.channel, target(i).label); target(i).label = target(i).label(datsel); target(i).elecpos = target(i).elecpos(datsel,:); end % compute the average of the target electrode positions average = ft_average_sens(target); fprintf('warping electrodes to average template... '); % the newline comes later [norm.elecpos, norm.m] = ft_warp_optim(elec.elecpos, average.elecpos, cfg.warp); norm.label = elec.label; dpre = mean(sqrt(sum((average.elecpos - elec.elecpos).^2, 2))); dpost = mean(sqrt(sum((average.elecpos - norm.elecpos).^2, 2))); fprintf('mean distance prior to warping %f, after warping %f\n', dpre, dpost); if strcmp(cfg.feedback, 'yes') % create an empty figure, continued below... figure axis equal axis vis3d hold on xlabel('x') ylabel('y') zlabel('z') % plot all electrodes before warping ft_plot_sens(elec, 'r*'); % plot all electrodes after warping ft_plot_sens(norm, 'm.', 'label', 'label'); % plot the template electrode locations ft_plot_sens(average, 'b.'); % plot lines connecting the input and the realigned electrode locations with the template locations my_line3(elec.elecpos, average.elecpos, 'color', 'r'); my_line3(norm.elecpos, average.elecpos, 'color', 'm'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(cfg.method, 'headshape') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % determine electrode selection and overlapping subset for warping cfg.channel = ft_channelselection(cfg.channel, elec.label); % make subselection of electrodes [cfgsel, datsel] = match_str(cfg.channel, elec.label); elec.label = elec.label(datsel); elec.elecpos = elec.elecpos(datsel,:); norm.label = elec.label; if strcmp(lower(cfg.warp), 'dykstra2012') norm.elecpos = ft_warp_dykstra2012(elec.elecpos, headshape, cfg.feedback); else fprintf('warping electrodes to skin surface... '); % the newline comes later [norm.elecpos, norm.m] = ft_warp_optim(elec.elecpos, headshape, cfg.warp); dpre = ft_warp_error([], elec.elecpos, headshape, cfg.warp); dpost = ft_warp_error(norm.m, elec.elecpos, headshape, cfg.warp); fprintf('mean distance prior to warping %f, after warping %f\n', dpre, dpost); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(cfg.method, 'fiducial') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the fiducials have to be present in the electrodes and in the template set label = intersect(lower(elec.label), lower(target.label)); if ~isfield(cfg, 'fiducial') || isempty(cfg.fiducial) % try to determine the names of the fiducials automatically option1 = {'nasion' 'left' 'right'}; option2 = {'nasion' 'lpa' 'rpa'}; option3 = {'nz' 'left' 'right'}; option4 = {'nz' 'lpa' 'rpa'}; option5 = {'nas' 'left' 'right'}; option6 = {'nas' 'lpa' 'rpa'}; if length(match_str(label, option1))==3 cfg.fiducial = option1; elseif length(match_str(label, option2))==3 cfg.fiducial = option2; elseif length(match_str(label, option3))==3 cfg.fiducial = option3; elseif length(match_str(label, option4))==3 cfg.fiducial = option4; elseif length(match_str(label, option5))==3 cfg.fiducial = option5; elseif length(match_str(label, option6))==3 cfg.fiducial = option6; else error('could not determine consistent fiducials in the input and the target, please specify cfg.fiducial or cfg.coordsys') end end fprintf('matching fiducials {''%s'', ''%s'', ''%s''}\n', cfg.fiducial{1}, cfg.fiducial{2}, cfg.fiducial{3}); % determine electrode selection cfg.channel = ft_channelselection(cfg.channel, elec.label); [cfgsel, datsel] = match_str(cfg.channel, elec.label); elec.label = elec.label(datsel); elec.elecpos = elec.elecpos(datsel,:); if length(cfg.fiducial)~=3 error('you must specify exaclty three fiducials'); end % do case-insensitive search for fiducial locations nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1})); lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2})); rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3})); if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1 error('not all fiducials were found in the electrode set'); end elec_nas = elec.elecpos(nas_indx,:); elec_lpa = elec.elecpos(lpa_indx,:); elec_rpa = elec.elecpos(rpa_indx,:); % FIXME change the flow in the remainder % if one or more template electrode sets are specified, then align to the average of those % if no template is specified, then align so that the fiducials are along the axis % find the matching fiducials in the template and average them tmpl_nas = nan(Ntemplate,3); tmpl_lpa = nan(Ntemplate,3); tmpl_rpa = nan(Ntemplate,3); for i=1:Ntemplate nas_indx = match_str(lower(target(i).label), lower(cfg.fiducial{1})); lpa_indx = match_str(lower(target(i).label), lower(cfg.fiducial{2})); rpa_indx = match_str(lower(target(i).label), lower(cfg.fiducial{3})); if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1 error(sprintf('not all fiducials were found in template %d', i)); end tmpl_nas(i,:) = target(i).elecpos(nas_indx,:); tmpl_lpa(i,:) = target(i).elecpos(lpa_indx,:); tmpl_rpa(i,:) = target(i).elecpos(rpa_indx,:); end tmpl_nas = mean(tmpl_nas,1); tmpl_lpa = mean(tmpl_lpa,1); tmpl_rpa = mean(tmpl_rpa,1); % realign both to a common coordinate system elec2common = ft_headcoordinates(elec_nas, elec_lpa, elec_rpa); templ2common = ft_headcoordinates(tmpl_nas, tmpl_lpa, tmpl_rpa); % compute the combined transform norm = []; norm.m = templ2common \ elec2common; % apply the transformation to the fiducials as sanity check norm.elecpos(1,:) = ft_warp_apply(norm.m, elec_nas, 'homogeneous'); norm.elecpos(2,:) = ft_warp_apply(norm.m, elec_lpa, 'homogeneous'); norm.elecpos(3,:) = ft_warp_apply(norm.m, elec_rpa, 'homogeneous'); norm.label = cfg.fiducial; nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1})); lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2})); rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3})); dpre = mean(sqrt(sum((elec.elecpos([nas_indx lpa_indx rpa_indx],:) - [tmpl_nas; tmpl_lpa; tmpl_rpa]).^2, 2))); nas_indx = match_str(lower(norm.label), lower(cfg.fiducial{1})); lpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{2})); rpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{3})); dpost = mean(sqrt(sum((norm.elecpos([nas_indx lpa_indx rpa_indx],:) - [tmpl_nas; tmpl_lpa; tmpl_rpa]).^2, 2))); fprintf('mean distance between fiducials prior to realignment %f, after realignment %f\n', dpre, dpost); if strcmp(cfg.feedback, 'yes') % create an empty figure, continued below... figure axis equal axis vis3d hold on xlabel('x') ylabel('y') zlabel('z') % plot the first three electrodes before transformation my_plot3(elec.elecpos(1,:), 'r*'); my_plot3(elec.elecpos(2,:), 'r*'); my_plot3(elec.elecpos(3,:), 'r*'); my_text3(elec.elecpos(1,:), elec.label{1}, 'color', 'r'); my_text3(elec.elecpos(2,:), elec.label{2}, 'color', 'r'); my_text3(elec.elecpos(3,:), elec.label{3}, 'color', 'r'); % plot the template fiducials my_plot3(tmpl_nas, 'b*'); my_plot3(tmpl_lpa, 'b*'); my_plot3(tmpl_rpa, 'b*'); my_text3(tmpl_nas, ' nas', 'color', 'b'); my_text3(tmpl_lpa, ' lpa', 'color', 'b'); my_text3(tmpl_rpa, ' rpa', 'color', 'b'); % plot all electrodes after transformation my_plot3(norm.elecpos, 'm.'); my_plot3(norm.elecpos(1,:), 'm*'); my_plot3(norm.elecpos(2,:), 'm*'); my_plot3(norm.elecpos(3,:), 'm*'); my_text3(norm.elecpos(1,:), norm.label{1}, 'color', 'm'); my_text3(norm.elecpos(2,:), norm.label{2}, 'color', 'm'); my_text3(norm.elecpos(3,:), norm.label{3}, 'color', 'm'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(cfg.method, 'interactive') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % give the user instructions disp('Use the mouse to rotate the head and the electrodes around, and click "redisplay"'); disp('Close the figure when you are done'); % open a figure fig = figure; % add the data to the figure set(fig, 'CloseRequestFcn', @cb_close); setappdata(fig, 'elec', elec); setappdata(fig, 'transform', eye(4)); if useheadshape setappdata(fig, 'headshape', headshape); end if usetarget % FIXME interactive realigning to template electrodes is not yet supported % this requires a consistent handling of channel selection etc. setappdata(fig, 'target', target); end % add the GUI elements cb_creategui(gca); cb_redraw(gca); rotate3d on waitfor(fig); % get the data from the figure that was left behind as global variable tmp = norm; clear global norm norm = tmp; clear tmp %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(cfg.method, 'project') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% [dum, prj] = project_elec(elec.elecpos, headshape.pos, headshape.tri); % replace the electrodes with the projected version elec.elecpos = prj; else error('unknown method'); end % if method % apply the spatial transformation to all electrodes, and replace the % electrode labels by their case-sensitive original values switch cfg.method case {'template', 'headshape'} if strcmp(lower(cfg.warp), 'dykstra2012') elec_realigned = norm; elec_realigned.unit = elec_original.unit; else % the transformation is a linear or non-linear warp, i.e. a vector try % convert the vector with fitted parameters into a 4x4 homogenous transformation % apply the transformation to the original complete set of sensors elec_realigned = ft_transform_sens(feval(cfg.warp, norm.m), elec_original); catch % the previous section will fail for nonlinear transformations elec_realigned.label = elec_original.label; try, elec_realigned.elecpos = ft_warp_apply(norm.m, elec_original.elecpos, cfg.warp); end end % remember the transformation elec_realigned.(cfg.warp) = norm.m; end case {'fiducial' 'interactive'} % the transformation is a 4x4 homogenous matrix % apply the transformation to the original complete set of sensors elec_realigned = ft_transform_sens(norm.m, elec_original); % remember the transformation elec_realigned.homogeneous = norm.m; case 'project' % nothing to be done elec_realigned = elec; otherwise error('unknown method'); end % the coordinate system is in general not defined after transformation if isfield(elec_realigned, 'coordsys') elec_realigned = rmfield(elec_realigned, 'coordsys'); end % in some cases the coordinate system matches that of the input target or headshape switch cfg.method case 'template' if isfield(target, 'coordsys') elec_realigned.coordsys = target.coordsys; end case 'headshape' if isfield(headshape, 'coordsys') elec_realigned.coordsys = headshape.coordsys; end case 'fiducial' if isfield(target, 'coordsys') elec_realigned.coordsys = target.coordsys; end case 'interactive' % the coordinate system is not known case 'project' % the coordinate system remains the same if isfield(elec_original, 'coordsys') elec_realigned.coordsys = elec_original.coordsys; end otherwise error('unknown method'); end % channel positions are identical to the electrode positions (this was checked at the start) elec_realigned.chanpos = elec_realigned.elecpos; % update it to the latest version elec_realigned = ft_datatype_sens(elec_realigned); % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous elec_original ft_postamble provenance elec_realigned ft_postamble history elec_realigned %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % some simple SUBFUNCTIONs that facilitate 3D plotting %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = my_plot3(xyz, varargin) h = plot3(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:}); function h = my_text3(xyz, varargin) h = text(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:}); function my_line3(xyzB, xyzE, varargin) for i=1:size(xyzB,1) line([xyzB(i,1) xyzE(i,1)], [xyzB(i,2) xyzE(i,2)], [xyzB(i,3) xyzE(i,3)], varargin{:}) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_creategui(hObject, eventdata, handles) % % define the position of each GUI element fig = get(hObject, 'parent'); % constants CONTROL_WIDTH = 0.05; CONTROL_HEIGHT = 0.06; CONTROL_HOFFSET = 0.7; CONTROL_VOFFSET = 0.5; % rotateui uicontrol('tag', 'rotateui', 'parent', fig, 'units', 'normalized', 'style', 'text', 'string', 'rotate', 'callback', []) uicontrol('tag', 'rx', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) uicontrol('tag', 'ry', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) uicontrol('tag', 'rz', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) ft_uilayout(fig, 'tag', 'rotateui', 'BackgroundColor', [0.8 0.8 0.8], 'width', 2*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET, 'vpos', CONTROL_VOFFSET); ft_uilayout(fig, 'tag', 'rx', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+3*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET); ft_uilayout(fig, 'tag', 'ry', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+4*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET); ft_uilayout(fig, 'tag', 'rz', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+5*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET); % scaleui uicontrol('tag', 'scaleui', 'parent', fig, 'units', 'normalized', 'style', 'text', 'string', 'scale', 'callback', []) uicontrol('tag', 'sx', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '1', 'callback', @cb_redraw) uicontrol('tag', 'sy', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '1', 'callback', @cb_redraw) uicontrol('tag', 'sz', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '1', 'callback', @cb_redraw) ft_uilayout(fig, 'tag', 'scaleui', 'BackgroundColor', [0.8 0.8 0.8], 'width', 2*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET, 'vpos', CONTROL_VOFFSET-CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'sx', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+3*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'sy', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+4*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'sz', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+5*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-CONTROL_HEIGHT); % translateui uicontrol('tag', 'translateui', 'parent', fig, 'units', 'normalized', 'style', 'text', 'string', 'translate', 'callback', []) uicontrol('tag', 'tx', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) uicontrol('tag', 'ty', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) uicontrol('tag', 'tz', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0', 'callback', @cb_redraw) ft_uilayout(fig, 'tag', 'translateui', 'BackgroundColor', [0.8 0.8 0.8], 'width', 2*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET, 'vpos', CONTROL_VOFFSET-2*CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'tx', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+3*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-2*CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'ty', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+4*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-2*CONTROL_HEIGHT); ft_uilayout(fig, 'tag', 'tz', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'hpos', CONTROL_HOFFSET+5*CONTROL_WIDTH, 'vpos', CONTROL_VOFFSET-2*CONTROL_HEIGHT); % control buttons uicontrol('tag', 'redisplaybtn', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'redisplay', 'value', [], 'callback', @cb_redraw); uicontrol('tag', 'applybtn', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'apply', 'value', [], 'callback', @cb_apply); uicontrol('tag', 'toggle labels', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'toggle label', 'value', 0, 'callback', @cb_redraw); uicontrol('tag', 'toggle axes', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'toggle axes', 'value', 0, 'callback', @cb_redraw); ft_uilayout(fig, 'tag', 'redisplaybtn', 'BackgroundColor', [0.8 0.8 0.8], 'width', 6*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-3*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); ft_uilayout(fig, 'tag', 'applybtn', 'BackgroundColor', [0.8 0.8 0.8], 'width', 6*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-4*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); ft_uilayout(fig, 'tag', 'toggle labels', 'BackgroundColor', [0.8 0.8 0.8], 'width', 6*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-5*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); ft_uilayout(fig, 'tag', 'toggle axes', 'BackgroundColor', [0.8 0.8 0.8], 'width', 6*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-6*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); % alpha ui (somehow not implemented, facealpha is fixed at 0.7 uicontrol('tag', 'alphaui', 'parent', fig, 'units', 'normalized', 'style', 'text', 'string', 'alpha', 'value', [], 'callback', []); uicontrol('tag', 'alpha', 'parent', fig, 'units', 'normalized', 'style', 'edit', 'string', '0.7', 'value', [], 'callback', @cb_redraw); ft_uilayout(fig, 'tag', 'alphaui', 'BackgroundColor', [0.8 0.8 0.8], 'width', 3*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-7*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); ft_uilayout(fig, 'tag', 'alpha', 'BackgroundColor', [0.8 0.8 0.8], 'width', 3*CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-7*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+3*CONTROL_WIDTH); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_redraw(hObject, eventdata, handles) fig = get(hObject, 'parent'); headshape = getappdata(fig, 'headshape'); elec = getappdata(fig, 'elec'); target = getappdata(fig, 'target'); % get the transformation details rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string')); ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string')); rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string')); tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string')); ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string')); tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string')); sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string')); sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string')); sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string')); R = rotate ([rx ry rz]); T = translate([tx ty tz]); S = scale ([sx sy sz]); H = S * T * R; elec = ft_transform_sens(H, elec); axis vis3d; cla xlabel('x') ylabel('y') zlabel('z') if ~isempty(target) disp('Plotting the target electrodes in blue'); if size(target.elecpos, 2)==2 hs = plot(target.elecpos(:,1), target.elecpos(:,2), 'b.', 'MarkerSize', 20); else hs = plot3(target.elecpos(:,1), target.elecpos(:,2), target.elecpos(:,3), 'b.', 'MarkerSize', 20); end end if ~isempty(headshape) % plot the faces of the 2D or 3D triangulation skin = [255 213 119]/255; ft_plot_mesh(headshape,'facecolor', skin,'EdgeColor','none','facealpha',0.7); lighting gouraud material shiny camlight end if isfield(elec, 'fid') && ~isempty(elec.fid.pos) disp('Plotting the fiducials in red'); ft_plot_sens(elec.fid,'style', 'r*'); end if get(findobj(fig, 'tag', 'toggle axes'), 'value') axis on grid on else axis off grid on end hold on if get(findobj(fig, 'tag', 'toggle labels'), 'value') ft_plot_sens(elec,'label', 'on'); else ft_plot_sens(elec,'label', 'off'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_apply(hObject, eventdata, handles) fig = get(hObject, 'parent'); elec = getappdata(fig, 'elec'); transform = getappdata(fig, 'transform'); % get the transformation details rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string')); ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string')); rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string')); tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string')); ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string')); tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string')); sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string')); sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string')); sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string')); R = rotate ([rx ry rz]); T = translate([tx ty tz]); S = scale ([sx sy sz]); H = S * T * R; elec = ft_transform_headshape(H, elec); transform = H * transform; set(findobj(fig, 'tag', 'rx'), 'string', 0); set(findobj(fig, 'tag', 'ry'), 'string', 0); set(findobj(fig, 'tag', 'rz'), 'string', 0); set(findobj(fig, 'tag', 'tx'), 'string', 0); set(findobj(fig, 'tag', 'ty'), 'string', 0); set(findobj(fig, 'tag', 'tz'), 'string', 0); set(findobj(fig, 'tag', 'sx'), 'string', 1); set(findobj(fig, 'tag', 'sy'), 'string', 1); set(findobj(fig, 'tag', 'sz'), 'string', 1); setappdata(fig, 'elec', elec); setappdata(fig, 'transform', transform); cb_redraw(hObject); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_close(hObject, eventdata, handles) % make the current transformation permanent and subsequently allow deleting the figure cb_apply(gca); % get the updated electrode from the figure fig = hObject; % hmmm, this is ugly global norm norm = getappdata(fig, 'elec'); norm.m = getappdata(fig, 'transform'); set(fig, 'CloseRequestFcn', @delete); delete(fig);
github
lcnbeapp/beapp-master
ft_singleplotTFR.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_singleplotTFR.m
25,551
utf_8
c1e10cb941401df2b09074cf6edb3bf3
function [cfg] = ft_singleplotTFR(cfg, data) % FT_SINGLEPLOTTFR plots the time-frequency representation of power of a % single channel or the average over multiple channels. % % Use as % ft_singleplotTFR(cfg,data) % % The input freq structure should be a a time-frequency representation of % power or coherence that was computed using the FT_FREQANALYSIS function. % % The configuration can have the following parameters: % cfg.parameter = field to be plotted on z-axis, e.g. 'powspcrtrm' (default depends on data.dimord) % cfg.maskparameter = field in the data to be used for masking of data % (not possible for mean over multiple channels, or when input contains multiple subjects % or trials) % cfg.maskstyle = style used to masking, 'opacity', 'saturation' or 'outline' (default = 'opacity') % use 'saturation' or 'outline' when saving to vector-format (like *.eps) to avoid all sorts of image-problems % cfg.maskalpha = alpha value between 0 (transparant) and 1 (opaque) used for masking areas dictated by cfg.maskparameter (default = 1) % cfg.masknans = 'yes' or 'no' (default = 'yes') % cfg.xlim = 'maxmin' or [xmin xmax] (default = 'maxmin') % cfg.ylim = 'maxmin' or [ymin ymax] (default = 'maxmin') % cfg.zlim = plotting limits for color dimension, 'maxmin', 'maxabs', 'zeromax', 'minzero', or [zmin zmax] (default = 'maxmin') % cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see FT_FREQBASELINE % cfg.baselinetype = 'absolute', 'relative', 'relchange' or 'db' (default = 'absolute') % cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') % cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), % see FT_CHANNELSELECTION for details % cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui' % cfg.fontsize = font size of title (default = 8) % cfg.hotkeys = enables hotkeys (up/down arrows) for dynamic colorbar adjustment % cfg.colormap = any sized colormap, see COLORMAP % cfg.colorbar = 'yes', 'no' (default = 'yes') % cfg.interactive = Interactive plot 'yes' or 'no' (default = 'yes') % In a interactive plot you can select areas and produce a new % interactive plot when a selected area is clicked. Multiple areas % can be selected by holding down the SHIFT key. % cfg.renderer = 'painters', 'zbuffer',' opengl' or 'none' (default = []) % cfg.directionality = '', 'inflow' or 'outflow' specifies for % connectivity measures whether the inflow into a % node, or the outflow from a node is plotted. The % (default) behavior of this option depends on the dimor % of the input data (see below). % % For the plotting of directional connectivity data the cfg.directionality % option determines what is plotted. The default value and the supported % functionality depend on the dimord of the input data. If the input data % is of dimord 'chan_chan_XXX', the value of directionality determines % whether, given the reference channel(s), the columns (inflow), or rows % (outflow) are selected for plotting. In this situation the default is % 'inflow'. Note that for undirected measures, inflow and outflow should % give the same output. If the input data is of dimord 'chancmb_XXX', the % value of directionality determines whether the rows in data.labelcmb are % selected. With 'inflow' the rows are selected if the refchannel(s) occur in % the right column, with 'outflow' the rows are selected if the % refchannel(s) occur in the left column of the labelcmb-field. Default in % this case is '', which means that all rows are selected in which the % refchannel(s) occur. This is to robustly support linearly indexed % undirected connectivity metrics. In the situation where undirected % connectivity measures are linearly indexed, specifying 'inflow' or % 'outflow' can result in unexpected behavior. % % See also FT_SINGLEPLOTER, FT_MULTIPLOTER, FT_MULTIPLOTTFR, FT_TOPOPLOTER, FT_TOPOPLOTTFR % Copyright (C) 2005-2006, F.C. Donders Centre % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble provenance ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input data is valid for this function data = ft_checkdata(data, 'datatype', 'freq'); % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'unused', {'cohtargetchannel'}); cfg = ft_checkconfig(cfg, 'renamed', {'matrixside', 'directionality'}); cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'}); cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedforward', 'outflow'}); cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedback', 'inflow'}); cfg = ft_checkconfig(cfg, 'renamed', {'channelindex', 'channel'}); cfg = ft_checkconfig(cfg, 'renamed', {'channelname', 'channel'}); cfg = ft_checkconfig(cfg, 'renamed', {'cohrefchannel', 'refchannel'}); cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'parameter'}); cfg = ft_checkconfig(cfg, 'deprecated', {'xparam', 'yparam'}); % Set the defaults: cfg.baseline = ft_getopt(cfg, 'baseline', 'no'); cfg.baselinetype = ft_getopt(cfg, 'baselinetype', 'absolute'); cfg.trials = ft_getopt(cfg, 'trials', 'all', 1); cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin'); cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin'); cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin'); cfg.fontsize = ft_getopt(cfg, 'fontsize', 8); cfg.colorbar = ft_getopt(cfg, 'colorbar', 'yes'); cfg.interactive = ft_getopt(cfg, 'interactive', 'yes'); cfg.hotkeys = ft_getopt(cfg, 'hotkeys', 'no'); cfg.renderer = ft_getopt(cfg, 'renderer', []); cfg.maskalpha = ft_getopt(cfg, 'maskalpha', 1); cfg.maskparameter = ft_getopt(cfg, 'maskparameter', []); cfg.maskstyle = ft_getopt(cfg, 'maskstyle', 'opacity'); cfg.channel = ft_getopt(cfg, 'channel', 'all'); cfg.masknans = ft_getopt(cfg, 'masknans', 'yes'); cfg.directionality = ft_getopt(cfg, 'directionality',[]); cfg.figurename = ft_getopt(cfg, 'figurename', []); cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm'); dimord = getdimord(data, cfg.parameter); dimtok = tokenize(dimord, '_'); % Set x/y/parameter defaults if ~any(ismember(dimtok, 'time')) error('input data needs a time dimension'); else xparam = 'time'; yparam = 'freq'; end if isfield(cfg, 'channel') && isfield(data, 'label') cfg.channel = ft_channelselection(cfg.channel, data.label); elseif isfield(cfg, 'channel') && isfield(data, 'labelcmb') cfg.channel = ft_channelselection(cfg.channel, unique(data.labelcmb(:))); end if isempty(cfg.channel) error('no channels selected'); end if ~isfield(data, cfg.parameter) error('data has no field ''%s''', cfg.parameter); end % check whether rpt/subj is present and remove if necessary and whether hasrpt = any(ismember(dimtok, {'rpt' 'subj'})); if hasrpt, % this also deals with fourier-spectra in the input % or with multiple subjects in a frequency domain stat-structure % on the fly computation of coherence spectrum is not supported if isfield(data, 'crsspctrm'), data = rmfield(data, 'crsspctrm'); end tmpcfg = []; tmpcfg.trials = cfg.trials; tmpcfg.jackknife = 'no'; % keep mask-parameter if it is set if ~isempty(cfg.maskparameter) tempmask = data.(cfg.maskparameter); end if isfield(cfg, 'parameter') && ~strcmp(cfg.parameter,'powspctrm') % freqdesctiptives will only work on the powspctrm field % hence a temporary copy of the data is needed tempdata.dimord = data.dimord; tempdata.freq = data.freq; tempdata.label = data.label; tempdata.time = data.time; tempdata.powspctrm = data.(cfg.parameter); if isfield(data, 'cfg') tempdata.cfg = data.cfg; end tempdata = ft_freqdescriptives(tmpcfg, tempdata); data.(cfg.parameter) = tempdata.powspctrm; clear tempdata else data = ft_freqdescriptives(tmpcfg, data); end % put mask-parameter back if it is set if ~isempty(cfg.maskparameter) data.(cfg.maskparameter) = tempmask; end dimord = data.dimord; dimtok = tokenize(dimord, '_'); end % if hasrpt % Handle the bivariate case % Check for bivariate metric with 'chan_chan' in the dimord selchan = strmatch('chan', dimtok); isfull = length(selchan)>1; % Check for bivariate metric with a labelcmb haslabelcmb = isfield(data, 'labelcmb'); % check whether the bivariate metric is the one requested to plot %shouldPlotCmb = (haslabelcmb && ... % size(data.(cfg.parameter),selchan(1)) == size(data.labelcmb,1)) ... % || isfull; % this should work because if dimord has multiple chans (so isfull=1) % % then we can never plot anything without reference channel % % this is different when haslabelcmb=1; then the parameter % % requested to plot might well be a simple powspctrm %if (isfull || haslabelcmb) && shouldPlotCmb if (isfull || haslabelcmb) && (isfield(data, cfg.parameter) && ~strcmp(cfg.parameter, 'powspctrm')) % A reference channel is required: if ~isfield(cfg, 'refchannel') error('no reference channel is specified'); end % check for refchannel being part of selection if ~strcmp(cfg.refchannel,'gui') if haslabelcmb cfg.refchannel = ft_channelselection(cfg.refchannel, unique(data.labelcmb(:))); else cfg.refchannel = ft_channelselection(cfg.refchannel, data.label); end if (isfull && ~any(ismember(data.label, cfg.refchannel))) || ... (haslabelcmb && ~any(ismember(data.labelcmb(:), cfg.refchannel))) error('cfg.refchannel is a not present in the (selected) channels)') end end % Interactively select the reference channel if strcmp(cfg.refchannel, 'gui') error('coh.refchannel = ''gui'' is not supported at the moment for ft_singleplotTFR'); % % % Open a single figure with the channel layout, the user can click on a reference channel % h = clf; % ft_plot_lay(lay, 'box', false); % title('Select the reference channel by dragging a selection window, more than 1 channel can be selected...'); % % add the channel information to the figure % info = guidata(gcf); % info.x = lay.pos(:,1); % info.y = lay.pos(:,2); % info.label = lay.label; % guidata(h, info); % %set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'callback', {@select_topoplotER, cfg, data}}); % set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonUpFcn'}); % set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonDownFcn'}); % set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonMotionFcn'}); % return end if ~isfull, % Convert 2-dimensional channel matrix to a single dimension: if isempty(cfg.directionality) sel1 = find(strcmp(cfg.refchannel, data.labelcmb(:,2))); sel2 = find(strcmp(cfg.refchannel, data.labelcmb(:,1))); elseif strcmp(cfg.directionality, 'outflow') sel1 = []; sel2 = find(strcmp(cfg.refchannel, data.labelcmb(:,1))); elseif strcmp(cfg.directionality, 'inflow') sel1 = find(strcmp(cfg.refchannel, data.labelcmb(:,2))); sel2 = []; end fprintf('selected %d channels for %s\n', length(sel1)+length(sel2), cfg.parameter); if length(sel1)+length(sel2)==0 error('there are no channels selected for plotting: you may need to look at the specification of cfg.directionality'); end data.(cfg.parameter) = data.(cfg.parameter)([sel1;sel2],:,:); data.label = [data.labelcmb(sel1,1);data.labelcmb(sel2,2)]; data.labelcmb = data.labelcmb([sel1;sel2],:); data = rmfield(data, 'labelcmb'); else % General case sel = match_str(data.label, cfg.refchannel); siz = [size(data.(cfg.parameter)) 1]; if strcmp(cfg.directionality, 'inflow') || isempty(cfg.directionality) %the interpretation of 'inflow' and 'outflow' depend on %the definition in the bivariate representation of the data %data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(:,sel,:),2),[siz(1) 1 siz(3:end)]); sel1 = 1:siz(1); sel2 = sel; meandir = 2; elseif strcmp(cfg.directionality, 'outflow') %data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(sel,:,:),1),[siz(1) 1 siz(3:end)]); sel1 = sel; sel2 = 1:siz(1); meandir = 1; elseif strcmp(cfg.directionality, 'ff-fd') error('cfg.directionality = ''ff-fd'' is not supported anymore, you have to manually subtract the two before the call to ft_singleplotTFR'); elseif strcmp(cfg.directionality, 'fd-ff') error('cfg.directionality = ''fd-ff'' is not supported anymore, you have to manually subtract the two before the call to ft_singleplotTFR'); end %if directionality end %if ~isfull end %handle the bivariate data % Apply baseline correction: if ~strcmp(cfg.baseline, 'no') % keep mask-parameter if it is set if ~isempty(cfg.maskparameter) tempmask = data.(cfg.maskparameter); end data = ft_freqbaseline(cfg, data); % put mask-parameter back if it is set if ~isempty(cfg.maskparameter) data.(cfg.maskparameter) = tempmask; end end % Get physical x-axis range: if strcmp(cfg.xlim,'maxmin') xmin = min(data.(xparam)); xmax = max(data.(xparam)); else xmin = cfg.xlim(1); xmax = cfg.xlim(2); end % Replace value with the index of the nearest bin if ~isempty(xparam) xmin = nearest(data.(xparam), xmin); xmax = nearest(data.(xparam), xmax); end % Get physical y-axis range: if strcmp(cfg.ylim,'maxmin') ymin = min(data.(yparam)); ymax = max(data.(yparam)); else ymin = cfg.ylim(1); ymax = cfg.ylim(2); end % Replace value with the index of the nearest bin if ~isempty(yparam) ymin = nearest(data.(yparam), ymin); ymax = nearest(data.(yparam), ymax); end % % test if X and Y are linearly spaced (to within 10^-12): % FROM UIMAGE % x = data.(xparam)(xmin:xmax); % y = data.(yparam)(ymin:ymax); % dx = min(diff(x)); % smallest interval for X % dy = min(diff(y)); % smallest interval for Y % evenx = all(abs(diff(x)/dx-1)<1e-12); % true if X is linearly spaced % eveny = all(abs(diff(y)/dy-1)<1e-12); % true if Y is linearly spaced % % % masking only possible for evenly spaced axis % if strcmp(cfg.masknans, 'yes') && (~evenx || ~eveny) % warning('(one of the) axis are not evenly spaced -> nans cannot be masked out -> cfg.masknans is set to ''no'';') % cfg.masknans = 'no'; % end % % if ~isempty(cfg.maskparameter) && (~evenx || ~eveny) % warning('(one of the) axis are not evenly spaced -> no masking possible -> cfg.maskparameter cleared') % cfg.maskparameter = []; % end % perform channel selection selchannel = ft_channelselection(cfg.channel, data.label); sellab = match_str(data.label, selchannel); % cfg.maskparameter only possible for single channel if length(sellab) > 1 && ~isempty(cfg.maskparameter) warning('no masking possible for average over multiple channels -> cfg.maskparameter cleared') cfg.maskparameter = []; end % get dimord dimensions ydim = find(strcmp(yparam, dimtok)); xdim = find(strcmp(xparam, dimtok)); zdim = setdiff(1:length(dimtok), [ydim xdim]); % all other dimensions % and permute dat = data.(cfg.parameter); dat = permute(dat, [zdim(:)' ydim xdim]); if isfull dat = dat(sel1, sel2, ymin:ymax, xmin:xmax); dat = nanmean(dat, meandir); siz = size(dat); dat = reshape(dat, [max(siz(1:2)) siz(3) siz(4)]); dat = dat(sellab, :, :); elseif haslabelcmb dat = dat(sellab, ymin:ymax, xmin:xmax); else dat = dat(sellab, ymin:ymax, xmin:xmax); end if ~isempty(cfg.maskparameter) mask = data.(cfg.maskparameter); if isfull && cfg.maskalpha == 1 mask = mask(sel1, sel2, ymin:ymax, xmin:xmax); mask = nanmean(mask, meandir); siz = size(mask); mask = reshape(mask, [max(siz(1:2)) siz(3) siz(4)]); mask = reshape(mask(sellab, :, :), [siz(3) siz(4)]); elseif haslabelcmb && cfg.maskalpha == 1 mask = squeeze(mask(sellab, ymin:ymax, xmin:xmax)); elseif cfg.maskalpha == 1 mask = squeeze(mask(sellab, ymin:ymax, xmin:xmax)); elseif isfull && cfg.maskalpha ~= 1 %% check me maskl = mask(sel1, sel2, ymin:ymax, xmin:xmax); maskl = nanmean(maskl, meandir); siz = size(maskl); maskl = reshape(maskl, [max(siz(1:2)) siz(3) siz(4)]); maskl = squeeze(reshape(maskl(sellab, :, :), [siz(3) siz(4)])); mask = zeros(size(maskl)); mask(maskl) = 1; mask(~maskl) = cfg.maskalpha; elseif haslabelcmb && cfg.maskalpha ~= 1 maskl = squeeze(mask(sellab, ymin:ymax, xmin:xmax)); mask = zeros(size(maskl)); mask(maskl) = 1; mask(~maskl) = cfg.maskalpha; elseif cfg.maskalpha ~= 1 maskl = squeeze(mask(sellab, ymin:ymax, xmin:xmax)); mask = zeros(size(maskl)); mask(maskl) = 1; mask(~maskl) = cfg.maskalpha; end end siz = size(dat); datamatrix = reshape(mean(dat, 1), [siz(2:end) 1]); xvector = data.(xparam)(xmin:xmax); yvector = data.(yparam)(ymin:ymax); % Get physical z-axis range (color axis): if strcmp(cfg.zlim,'maxmin') zmin = min(datamatrix(:)); zmax = max(datamatrix(:)); elseif strcmp(cfg.zlim,'maxabs') zmin = -max(abs(datamatrix(:))); zmax = max(abs(datamatrix(:))); elseif strcmp(cfg.zlim,'zeromax') zmin = 0; zmax = max(datamatrix(:)); elseif strcmp(cfg.zlim,'minzero') zmin = min(datamatrix(:)); zmax = 0; else zmin = cfg.zlim(1); zmax = cfg.zlim(2); end % set colormap if isfield(cfg,'colormap') if size(cfg.colormap,2)~=3, error('singleplotTFR(): Colormap must be a n x 3 matrix'); end set(gcf,'colormap',cfg.colormap); end % Draw plot (and mask NaN's if requested): cla if isequal(cfg.masknans,'yes') && isempty(cfg.maskparameter) nans_mask = ~isnan(datamatrix); mask = double(nans_mask); ft_plot_matrix(xvector, yvector, datamatrix, 'clim',[zmin,zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask) elseif isequal(cfg.masknans,'yes') && ~isempty(cfg.maskparameter) nans_mask = ~isnan(datamatrix); mask = mask .* nans_mask; mask = double(mask); ft_plot_matrix(xvector, yvector, datamatrix, 'clim',[zmin,zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask) elseif isequal(cfg.masknans,'no') && ~isempty(cfg.maskparameter) mask = double(mask); ft_plot_matrix(xvector, yvector, datamatrix, 'clim',[zmin,zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask) else ft_plot_matrix(xvector, yvector, datamatrix, 'clim',[zmin,zmax],'tag','cip') end hold on axis xy; % set(gca,'Color','k') if isequal(cfg.colorbar,'yes') % tag the colorbar so we know which axes are colorbars colorbar('tag', 'ft-colorbar'); end % Set adjust color axis if strcmp('yes',cfg.hotkeys) % Attach data and cfg to figure and attach a key listener to the figure set(gcf, 'KeyPressFcn', {@key_sub, zmin, zmax}) end % Make the figure interactive: if strcmp(cfg.interactive, 'yes') % first, attach data to the figure with the current axis handle as a name dataname = fixname(num2str(double(gca))); setappdata(gcf,dataname,data); set(gcf, 'WindowButtonUpFcn', {@ft_select_range, 'multiple', false, 'callback', {@select_topoplotTFR, cfg}, 'event', 'WindowButtonUpFcn'}); set(gcf, 'WindowButtonDownFcn', {@ft_select_range, 'multiple', false, 'callback', {@select_topoplotTFR, cfg}, 'event', 'WindowButtonDownFcn'}); set(gcf, 'WindowButtonMotionFcn', {@ft_select_range, 'multiple', false, 'callback', {@select_topoplotTFR, cfg}, 'event', 'WindowButtonMotionFcn'}); % set(gcf, 'WindowButtonUpFcn', {@ft_select_range, 'multiple', false, 'callback', {@select_topoplotTFR, cfg, data}, 'event', 'WindowButtonUpFcn'}); % set(gcf, 'WindowButtonDownFcn', {@ft_select_range, 'multiple', false, 'callback', {@select_topoplotTFR, cfg, data}, 'event', 'WindowButtonDownFcn'}); % set(gcf, 'WindowButtonMotionFcn', {@ft_select_range, 'multiple', false, 'callback', {@select_topoplotTFR, cfg, data}, 'event', 'WindowButtonMotionFcn'}); end % Create title text containing channel name(s) and channel number(s): if length(sellab) == 1 t = [char(cfg.channel) ' / ' num2str(sellab) ]; else t = sprintf('mean(%0s)', join_str(',', cfg.channel)); end h = title(t,'fontsize', cfg.fontsize); % set the figure window title, add channel labels if number is small if isempty(get(gcf, 'Name')) if length(sellab) < 5 chans = join_str(',', cfg.channel); else chans = '<multiple channels>'; end if isfield(cfg,'dataname') if iscell(cfg.dataname) dataname = cfg.dataname{1}; else dataname = cfg.dataname; end elseif nargin > 1 dataname = inputname(2); else % data provided through cfg.inputfile dataname = cfg.inputfile; end if isempty(cfg.figurename) set(gcf, 'Name', sprintf('%d: %s: %s (%s)', double(gcf), mfilename, dataname, chans)); set(gcf, 'NumberTitle', 'off'); else set(gcf, 'name', cfg.figurename); set(gcf, 'NumberTitle', 'off'); end end axis tight; hold off; % Set renderer if specified if ~isempty(cfg.renderer) set(gcf, 'renderer', cfg.renderer) end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous data ft_postamble provenance % add a menu to the figure, but only if the current figure does not have subplots % also, delete any possibly existing previous menu, this is safe because delete([]) does nothing delete(findobj(gcf, 'type', 'uimenu', 'label', 'FieldTrip')); if numel(findobj(gcf, 'type', 'axes', '-not', 'tag', 'ft-colorbar')) <= 1 ftmenu = uimenu(gcf, 'Label', 'FieldTrip'); uimenu(ftmenu, 'Label', 'Show pipeline', 'Callback', {@menu_pipeline, cfg}); uimenu(ftmenu, 'Label', 'About', 'Callback', @menu_about); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION which is called after selecting a time range %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function select_topoplotTFR(cfg, varargin) % first to last callback-input of ft_select_range is range % last callback-input of ft_select_range is contextmenu label, if used range = varargin{end-1}; varargin = varargin(1:end-2); % remove range and last % get appdata belonging to current axis dataname = fixname(num2str(double(gca))); data = getappdata(gcf, dataname); if isfield(cfg, 'inputfile') % the reading has already been done and varargin contains the data cfg = rmfield(cfg, 'inputfile'); end % make sure the topo displays all channels, not just the ones in this % singleplot cfg.channel = 'all'; cfg.comment = 'auto'; cfg.xlim = range(1:2); cfg.ylim = range(3:4); % compatibility fix for new ft_topoplotER/TFR cfg options if isfield(cfg,'showlabels') && strcmp(cfg.showlabels,'yes') cfg = rmfield(cfg,'showlabels'); cfg.marker = 'labels'; elseif isfield(cfg,'showlabels') && strcmp(cfg.showlabels,'no') cfg = rmfield(cfg,'showlabels'); cfg.marker = 'on'; end fprintf('selected cfg.xlim = [%f %f]\n', cfg.xlim(1), cfg.xlim(2)); fprintf('selected cfg.ylim = [%f %f]\n', cfg.ylim(1), cfg.ylim(2)); p = get(gcf, 'Position'); f = figure; set(f, 'Position', p); ft_topoplotTFR(cfg, data); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION which handles hot keys in the current plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key_sub(handle, eventdata, varargin) incr = (max(caxis)-min(caxis)) /10; % symmetrically scale color bar down by 10 percent if strcmp(eventdata.Key,'uparrow') caxis([min(caxis)-incr max(caxis)+incr]); % symmetrically scale color bar up by 10 percent elseif strcmp(eventdata.Key,'downarrow') caxis([min(caxis)+incr max(caxis)-incr]); % resort to minmax of data for colorbar elseif strcmp(eventdata.Key,'m') caxis([varargin{1} varargin{2}]); end
github
lcnbeapp/beapp-master
ft_prepare_sourcemodel.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_prepare_sourcemodel.m
34,786
utf_8
2a141b62a7f6242462a4682d7abf426b
function [grid, cfg] = ft_prepare_sourcemodel(cfg, headmodel, sens) % FT_PREPARE_SOURCEMODEL constructs a source model, for example a 3-D grid or a % cortical sheet. The source model that can be used for source reconstruction, % beamformer scanning, linear estimation and MEG interpolation. % % Use as % grid = ft_prepare_sourcemodel(cfg) % % where the configuration structure contains the details on how the source % model should be constructed. % % A source model can be constructed based on % - regular 3D grid with explicit specification % - regular 3D grid with specification of the resolution % - regular 3D grid, based on segmented MRI, restricted to gray matter % - regular 3D grid, based on a warped template grid, based on the MNI brain % - surface grid based on the brain surface from the volume conduction model % - surface grid based on the head surface from an external file % - cortical sheet that was created in MNE or Freesurfer % - using user-supplied grid positions, which can be regular or irregular % The approach that will be used depends on the configuration options that % you specify. % % Configuration options for generating a regular 3-D grid % cfg.grid.xgrid = vector (e.g. -20:1:20) or 'auto' (default = 'auto') % cfg.grid.ygrid = vector (e.g. -20:1:20) or 'auto' (default = 'auto') % cfg.grid.zgrid = vector (e.g. 0:1:20) or 'auto' (default = 'auto') % cfg.grid.resolution = number (e.g. 1 cm) for automatic grid generation % % Configuration options for a predefined grid % cfg.grid.pos = N*3 matrix with position of each source % cfg.grid.inside = N*1 vector with boolean value whether grid point is inside brain (optional) % cfg.grid.dim = [Nx Ny Nz] vector with dimensions in case of 3-D grid (optional) % % The following fields are not used in this function, but will be copied along to the output % cfg.grid.leadfield % cfg.grid.filter or alternatively cfg.grid.avg.filter % cfg.grid.subspace % cfg.grid.lbex % % Configuration options for a warped MNI grid % cfg.mri = can be filename or MRI structure, containing the individual anatomy % cfg.grid.warpmni = 'yes' % cfg.grid.resolution = number (e.g. 6) of the resolution of the % template MNI grid, defined in mm % cfg.grid.template = specification of a template grid (grid structure), or a % filename of a template grid (defined in MNI space), % either cfg.grid.resolution or cfg.grid.template needs % to be defined. If both are defined cfg.grid.template % prevails % cfg.grid.nonlinear = 'no' (or 'yes'), use non-linear normalization % % Configuration options for cortex segmentation, i.e. for placing dipoles in grey matter % cfg.mri = can be filename, MRI structure or segmented MRI structure % cfg.threshold = 0.1, relative to the maximum value in the segmentation % cfg.smooth = 5, smoothing in voxels % % Configuration options for reading a cortical sheet from file % cfg.headshape = string, should be a *.fif file % % The EEG or MEG sensor positions can be present in the data or can be specified as % cfg.elec = structure with electrode positions, see FT_DATATYPE_SENS % cfg.grad = structure with gradiometer definition, see FT_DATATYPE_SENS % or alternatively % cfg.elecfile = name of file containing the electrode positions, see FT_READ_SENS % cfg.gradfile = name of file containing the gradiometer definition, see FT_READ_SENS % % The headmodel or volume conduction model can be specified as % cfg.headmodel = structure with volume conduction model, see FT_PREPARE_HEADMODEL % % Other configuration options % cfg.grid.unit = string, can be 'mm', 'cm', 'm' (default is automatic) % cfg.grid.tight = 'yes' or 'no' (default is automatic) % cfg.inwardshift = number, how much should the innermost surface be moved inward to constrain % sources to be considered inside the source compartment (default = 0) % cfg.moveinward = number, move dipoles inward to ensure a certain distance to the innermost % surface of the source compartment (default = 0) % cfg.spherify = 'yes' or 'no', scale the source model so that it fits inside a sperical % volume conduction model (default = 'no') % cfg.symmetry = 'x', 'y' or 'z' symmetry for two dipoles, can be empty (default = []) % cfg.headshape = a filename for the headshape, a structure containing a single surface, % or a Nx3 matrix with headshape surface points (default = []) % % See also FT_PREPARE_LEADFIELD, FT_PREPARE_HEADMODEL, FT_SOURCEANALYSIS, % FT_DIPOLEFITTING, FT_MEGREALIGN % Copyright (C) 2004-2013, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble provenance ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'deprecated', 'mriunits'); cfg = ft_checkconfig(cfg, 'renamed', {'hdmfile', 'headmodel'}); cfg = ft_checkconfig(cfg, 'renamed', {'vol', 'headmodel'}); % put the low-level options pertaining to the dipole grid in their own field cfg = ft_checkconfig(cfg, 'renamed', {'tightgrid', 'tight'}); % this is moved to cfg.grid.tight by the subsequent createsubcfg cfg = ft_checkconfig(cfg, 'renamed', {'sourceunits', 'unit'}); % this is moved to cfg.grid.unit by the subsequent createsubcfg cfg = ft_checkconfig(cfg, 'createsubcfg', {'grid'}); % set the defaults cfg.moveinward = ft_getopt(cfg, 'moveinward', []); % the default is automatic and depends on a triangulation being present cfg.spherify = ft_getopt(cfg, 'spherify', 'no'); cfg.headshape = ft_getopt(cfg, 'headshape', []); cfg.symmetry = ft_getopt(cfg, 'symmetry', []); cfg.grid = ft_getopt(cfg, 'grid', []); cfg.spmversion = ft_getopt(cfg, 'spmversion', 'spm8'); cfg.grid.unit = ft_getopt(cfg.grid, 'unit', 'auto'); % this code expects the inside to be represented as a logical array if isfield(cfg, 'grid') cfg.grid = ft_checkconfig(cfg.grid, 'renamed', {'pnt' 'pos'}); if isfield(cfg.grid, 'template') cfg.grid.template = ft_checkconfig(cfg.grid.template, 'renamed', {'pnt' 'pos'}); end end cfg = ft_checkconfig(cfg, 'index2logical', 'yes'); if ~isfield(cfg, 'headmodel') && nargin>1 % put it in the configuration structure % this is for backward compatibility, 13 Januari 2011 cfg.headmodel = headmodel; end if ~isfield(cfg, 'grad') && ~isfield(cfg, 'elec') && nargin>2 % put it in the configuration structure % this is for backward compatibility, 13 Januari 2011 cfg.grad = sens; end if isfield(cfg.grid, 'resolution') && isfield(cfg.grid, 'xgrid') && ~ischar(cfg.grid.xgrid) error('You cannot specify cfg.grid.resolution and an explicit cfg.grid.xgrid simultaneously'); end if isfield(cfg.grid, 'resolution') && isfield(cfg.grid, 'ygrid') && ~ischar(cfg.grid.ygrid) error('You cannot specify cfg.grid.resolution and an explicit cfg.grid.ygrid simultaneously'); end if isfield(cfg.grid, 'resolution') && isfield(cfg.grid, 'zgrid') && ~ischar(cfg.grid.zgrid) error('You cannot specify cfg.grid.resolution and an explicit cfg.grid.zgrid simultaneously'); end % the source model can be constructed in a number of ways basedongrid = isfield(cfg.grid, 'xgrid') && ~ischar(cfg.grid.xgrid); % regular 3D grid with explicit specification basedonpos = isfield(cfg.grid, 'pos'); % using user-supplied grid positions, which can be regular or irregular basedonshape = ~isempty(cfg.headshape); % surface grid based on inward shifted head surface from external file basedonmri = isfield(cfg, 'mri') && ~(isfield(cfg.grid, 'warpmni') && istrue(cfg.grid.warpmni)); % regular 3D grid, based on segmented MRI, restricted to gray matter basedonmni = isfield(cfg, 'mri') && (isfield(cfg.grid, 'warpmni') && istrue(cfg.grid.warpmni)); % regular 3D grid, based on warped MNI template basedonvol = false; % surface grid based on inward shifted brain surface from volume conductor basedoncortex = isfield(cfg, 'headshape') && (iscell(cfg.headshape) || any(ft_filetype(cfg.headshape, {'neuromag_fif', 'freesurfer_triangle_binary', 'caret_surf', 'gifti'}))); % cortical sheet from external software such as Caret or FreeSurfer, can also be two separate hemispheres basedonresolution = isfield(cfg.grid, 'resolution') && ~basedonmri && ~basedonmni; % regular 3D grid with specification of the resolution if basedonshape && basedoncortex % treating it as cortical sheet has preference basedonshape = false; end if basedongrid && basedonpos % fall back to default behaviour, in which the pos overrides the grid basedongrid = false; end if ~any([basedonresolution basedongrid basedonpos basedonshape basedonmri basedoncortex basedonmni]) && ~isempty(cfg.headmodel) % fall back to default behaviour, which is to create a surface grid (e.g. used in MEGREALIGN) basedonvol = 1; end % these are mutually exclusive, but printing all requested methods here % facilitates debugging of weird configs. Also specify the defaults here to % keep the overview if basedonresolution fprintf('creating dipole grid based on automatic 3D grid with specified resolution\n'); cfg.grid.xgrid = ft_getopt(cfg.grid, 'xgrid', 'auto'); cfg.grid.ygrid = ft_getopt(cfg.grid, 'ygrid', 'auto'); cfg.grid.zgrid = ft_getopt(cfg.grid, 'zgrid', 'auto'); cfg.inwardshift = ft_getopt(cfg, 'inwardshift', 0); %in this case for inside detection, FIXME move to cfg.grid cfg.grid.tight = ft_getopt(cfg.grid, 'tight', 'yes'); end if basedongrid fprintf('creating dipole grid based on user specified 3D grid\n'); cfg.inwardshift = ft_getopt(cfg, 'inwardshift', 0); %in this case for inside detection, FIXME move to cfg.grid cfg.grid.tight = ft_getopt(cfg.grid, 'tight', 'yes'); end if basedonpos fprintf('creating dipole grid based on user specified dipole positions\n'); cfg.inwardshift = ft_getopt(cfg, 'inwardshift', 0); %in this case for inside detection, FIXME move to cfg.grid cfg.grid.tight = ft_getopt(cfg.grid, 'tight', 'no'); end if basedonshape fprintf('creating dipole grid based on inward-shifted head shape\n'); cfg.inwardshift = ft_getopt(cfg, 'inwardshift', 0); %in this case for inside detection, FIXME move to cfg.grid cfg.spheremesh = ft_getopt(cfg, 'spheremesh', 642); % FIXME move spheremesh to cfg.grid cfg.grid.tight = ft_getopt(cfg.grid, 'tight', 'yes'); end if basedoncortex cfg.grid.tight = ft_getopt(cfg.grid, 'tight', 'yes'); end if basedonmri fprintf('creating dipole grid based on an anatomical volume\n'); cfg.threshold = ft_getopt(cfg, 'threshold', 0.1); % relative cfg.smooth = ft_getopt(cfg, 'smooth', 5); % in voxels cfg.grid.tight = ft_getopt(cfg.grid, 'tight', 'yes'); end if basedonvol fprintf('creating dipole grid based on inward-shifted brain surface from volume conductor model\n'); cfg.inwardshift = ft_getopt(cfg, 'inwardshift', 0); %in this case for inside detection, FIXME move to cfg.grid cfg.spheremesh = ft_getopt(cfg, 'spheremesh', 642); % FIXME move spheremesh to cfg.grid cfg.grid.tight = ft_getopt(cfg.grid, 'tight', 'no'); end if basedonmni cfg.grid.tight = ft_getopt(cfg.grid, 'tight', 'no'); cfg.grid.nonlinear = ft_getopt(cfg.grid, 'nonlinear', 'no'); end % these are mutually exclusive if sum([basedonresolution basedongrid basedonpos basedonshape basedonmri basedonvol basedoncortex basedonmni])~=1 error('incorrect cfg specification for constructing a dipole grid'); end if (isfield(cfg, 'smooth') && ~strcmp(cfg.smooth, 'no')) || basedonmni % check that SPM is on the path, try to add the preferred version if strcmpi(cfg.spmversion, 'spm2'), ft_hastoolbox('SPM2', 1); elseif strcmpi(cfg.spmversion, 'spm8'), ft_hastoolbox('SPM8', 1); elseif strcmpi(cfg.spmversion, 'spm12'), ft_hastoolbox('SPM12', 1); end end % start with an empty grid grid = []; % get the volume conduction model try headmodel = ft_fetch_vol(cfg); catch headmodel = []; end % get the gradiometer or electrode definition try sens = ft_fetch_sens(cfg); catch sens = []; end if strcmp(cfg.grid.unit, 'auto') if isfield(cfg.grid, 'pos') && size(cfg.grid.pos,1)>10 % estimate the units based on the existing source positions cfg.grid = rmfield(cfg.grid, 'unit'); % remove 'auto' and have ft_convert_units determine it properly cfg.grid = ft_convert_units(cfg.grid); elseif ~isempty(sens) % copy the units from the sensor array cfg.grid.unit = sens.unit; elseif ~isempty(headmodel) % copy the units from the volume conduction model cfg.grid.unit = headmodel.unit; else warning('assuming "cm" as default source units'); cfg.grid.unit = 'cm'; end end % convert the sensor array to the desired units for the source model if ~isempty(sens) sens = ft_convert_units(sens, cfg.grid.unit); end % convert the head model to the desired units for the source model if ~isempty(headmodel) headmodel = ft_convert_units(headmodel, cfg.grid.unit); end if basedonresolution %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % construct a regular 3D grid that spans a box encompassing all electrode % or gradiometer coils, this will typically also cover the complete brain %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(sens) minpos = min(sens.chanpos,[],1); maxpos = max(sens.chanpos,[],1); elseif ~isempty(headmodel) minpos = [inf inf inf]; maxpos = [-inf -inf -inf]; for k = 1:numel(headmodel.bnd) tmpbnd = headmodel.bnd(k); if ~isfield(tmpbnd, 'pnt') && isfield(tmpbnd, 'pos') pos = tmpbnd.pos; elseif isfield(tmpbnd, 'pnt') && ~isfield(tmpbnd, 'pos') pos = tmpbnd.pnt; end minpos = min(minpos, min(pos,[],1)); maxpos = max(maxpos, max(pos,[],1)); end % add a few % on either side minpos(minpos<0) = minpos(minpos<0).*1.08; maxpos(maxpos>0) = maxpos(maxpos>0).*1.08; minpos(minpos>0) = minpos(minpos>0).*0.92; maxpos(maxpos<0) = maxpos(maxpos<0).*0.92; else error('creating a 3D-grid sourcemodel this way requires either sensor position information or a headmodel to estimate the extent of the brain'); end fprintf('creating dipole grid with %g %s resolution\n', cfg.grid.resolution, cfg.grid.unit); % round the bounding box limits to the nearest cm switch cfg.grid.unit case 'm' minpos = floor(minpos*100)/100; maxpos = ceil(maxpos*100)/100; case 'cm' minpos = floor(minpos); maxpos = ceil(maxpos); case 'mm' minpos = floor(minpos/10)*10; maxpos = ceil(maxpos/10)*10; end if ischar(cfg.grid.xgrid) && strcmp(cfg.grid.xgrid, 'auto') grid.xgrid = minpos(1):cfg.grid.resolution:maxpos(1); end if ischar(cfg.grid.ygrid) && strcmp(cfg.grid.ygrid, 'auto') grid.ygrid = minpos(2):cfg.grid.resolution:maxpos(2); end if ischar(cfg.grid.zgrid) && strcmp(cfg.grid.zgrid, 'auto') grid.zgrid = minpos(3):cfg.grid.resolution:maxpos(3); end grid.dim = [length(grid.xgrid) length(grid.ygrid) length(grid.zgrid)]; [X, Y, Z] = ndgrid(grid.xgrid, grid.ygrid, grid.zgrid); grid.pos = [X(:) Y(:) Z(:)]; grid.unit = cfg.grid.unit; end if basedongrid %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % a detailed xgrid/ygrid/zgrid has been specified, the other details % still need to be determined %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% grid.xgrid = cfg.grid.xgrid; grid.ygrid = cfg.grid.ygrid; grid.zgrid = cfg.grid.zgrid; grid.dim = [length(grid.xgrid) length(grid.ygrid) length(grid.zgrid)]; [X, Y, Z] = ndgrid(grid.xgrid, grid.ygrid, grid.zgrid); grid.pos = [X(:) Y(:) Z(:)]; grid.unit = cfg.grid.unit; end if basedonpos %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % a grid is already specified in the configuration, reuse as much of the % prespecified grid as possible (but only known objects) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% grid = keepfields(cfg.grid, {'pos', 'unit', 'xgrid', 'ygrid', 'zgrid', 'mom', 'tri', 'dim', 'transform', 'inside', 'lbex', 'subspace', 'leadfield', 'filter', 'label', 'leadfielddimord'}); end if basedonmri %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % construct a grid based on the segmented MRI that is provided in the % configuration, only voxels in gray matter will be used %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ischar(cfg.mri) mri = ft_read_mri(cfg.mri); else mri = cfg.mri; end % ensure the mri to have units if ~isfield(mri, 'unit') mri = ft_convert_units(mri); end if ~isfield(cfg.grid, 'resolution') switch cfg.grid.unit case 'mm' cfg.grid.resolution = 10; case 'cm' cfg.grid.resolution = 1; case 'dm' cfg.grid.resolution = 0.1; case 'm' cfg.grid.resolution = 0.01; end end issegmentation = false; if isfield(mri, 'gray') % this is not a boolean segmentation, but based on tissue probability % maps, being the original implementation here. dat = double(mri.gray); % apply a smoothing of a certain amount of voxels if ~strcmp(cfg.smooth, 'no'); dat = volumesmooth(dat, cfg.smooth, 'MRI gray matter'); end elseif isfield(mri, 'anatomy') % this could be a tpm stored on disk, i.e. the result of % ft_volumesegment. Reading it in always leads to the field 'anatomy'. % Note this could be any anatomical mask dat = double(mri.anatomy); % apply a smoothing of a certain amount of voxels if ~strcmp(cfg.smooth, 'no'); dat = volumesmooth(dat, cfg.smooth, 'anatomy'); end elseif ft_datatype(mri, 'segmentation') % this is a proper segmentation, where a set of boolean masks is in the % input, or and indexed volume, along with labels. FIXME for now still % only works for boolean volumes. issegmentation = true; fn = booleanfields(mri); if isempty(fn) % convert indexed segmentation into probabilistic mri = ft_datatype_segmentation(mri, 'segmentationstyle', 'probabilistic'); fn = booleanfields(mri); end dat = false(mri.dim); for i=1:numel(fn) if ~strcmp(cfg.smooth, 'no') mri.(fn{i}) = volumesmooth(double(mri.(fn{i})), cfg.smooth, fn{i}) > cfg.threshold; end dat = dat | mri.(fn{i}); end dat = double(dat); else error('cannot determine the format of the segmentation in cfg.mri'); end % determine for each voxel whether it belongs to the grey matter fprintf('thresholding MRI data at a relative value of %f\n', cfg.threshold); head = dat./max(dat(:)) > cfg.threshold; % convert the source/functional data into the same units as the anatomical MRI scale = ft_scalingfactor(cfg.grid.unit, mri.unit); ind = find(head(:)); fprintf('%d from %d voxels in the segmentation are marked as ''inside'' (%.0f%%)\n', length(ind), numel(head), 100*length(ind)/numel(head)); [X,Y,Z] = ndgrid(1:mri.dim(1), 1:mri.dim(2), 1:mri.dim(3)); % create the grid in MRI-coordinates posmri = [X(ind) Y(ind) Z(ind)]; % take only the inside voxels poshead = ft_warp_apply(mri.transform, posmri); % transform to head coordinates resolution = cfg.grid.resolution*scale; % source and mri can be expressed in different units (e.g. cm and mm) xgrid = floor(min(poshead(:,1))):resolution:ceil(max(poshead(:,1))); % create the grid in head-coordinates ygrid = floor(min(poshead(:,2))):resolution:ceil(max(poshead(:,2))); % with 'consistent' x,y,z definitions zgrid = floor(min(poshead(:,3))):resolution:ceil(max(poshead(:,3))); [X,Y,Z] = ndgrid(xgrid,ygrid,zgrid); pos2head = [X(:) Y(:) Z(:)]; pos2mri = ft_warp_apply(inv(mri.transform), pos2head); % transform to MRI voxel coordinates pos2mri = round(pos2mri); inside = getinside(pos2mri, head); % use helper subfunction grid.pos = pos2head/scale; % convert to source units grid.xgrid = xgrid/scale; % convert to source units grid.ygrid = ygrid/scale; % convert to source units grid.zgrid = zgrid/scale; % convert to source units grid.dim = [length(grid.xgrid) length(grid.ygrid) length(grid.zgrid)]; grid.inside = inside(:); grid.unit = cfg.grid.unit; if issegmentation % pass on the segmentation information on the grid points, the % individual masks have been smoothed above fn = booleanfields(mri); for i=1:numel(fn) grid.(fn{i}) = getinside(pos2mri, mri.(fn{i})); end % convert back is not in general possible because the masks can be % overlapping due to smoothing % grid = ft_datatype_segmentation(grid, 'segmentationstyle', segstyle); end fprintf('the full grid contains %d grid points\n', numel(grid.inside)); fprintf('%d grid points are mared as inside the brain\n', sum(grid.inside)); end if basedoncortex %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read it from a *.fif file that was created using Freesurfer and MNE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if iscell(cfg.headshape) % FIXME loop over all files, this should be two hemispheres keyboard else shape = ft_read_headshape(cfg.headshape); end % ensure that the headshape is in the same units as the source shape = ft_convert_units(shape, cfg.grid.unit); % return both the vertices and triangles from the cortical sheet grid.pos = shape.pos; grid.tri = shape.tri; grid.unit = shape.unit; end if basedonshape %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % use the headshape to make a superficial dipole layer (e.g. % for megrealign). Assume that all points are inside the volume. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % get the surface describing the head shape if isstruct(cfg.headshape) && isfield(cfg.headshape, 'pos') % use the headshape surface specified in the configuration headshape = cfg.headshape; elseif isnumeric(cfg.headshape) && size(cfg.headshape,2)==3 % use the headshape points specified in the configuration headshape.pos = cfg.headshape; elseif ischar(cfg.headshape) % read the headshape from file headshape = ft_read_headshape(cfg.headshape); else error('cfg.headshape is not specified correctly') end % ensure that the headshape is in the same units as the source headshape = ft_convert_units(headshape, cfg.grid.unit); if ~isfield(headshape, 'tri') % generate a closed triangulation from the surface points headshape.pos = unique(headshape.pos, 'rows'); headshape.tri = projecttri(headshape.pos); end % please note that cfg.inwardshift should be expressed in the units consistent with cfg.grid.unit grid.pos = headsurface([], [], 'headshape', headshape, 'inwardshift', cfg.inwardshift, 'npnt', cfg.spheremesh); grid.tri = headshape.tri; grid.unit = headshape.unit; grid.inside = true(size(grid.pos,1),1); end if basedonvol %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % use the volume conduction model to make a superficial dipole layer (e.g. % for megrealign). Assume that all points are inside the volume. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % please note that cfg.inwardshift should be expressed in the units consistent with cfg.grid.unit grid.pos = headsurface(headmodel, sens, 'inwardshift', cfg.inwardshift, 'npnt', cfg.spheremesh); grid.unit = cfg.grid.unit; grid.inside = true(size(grid.pos,1),1); end if basedonmni if ~isfield(cfg.grid, 'template') && ~isfield(cfg.grid, 'resolution') error('you either need to specify the filename of a template grid in cfg.grid.template, or a resolution in cfg.grid.resolution'); elseif isfield(cfg.grid, 'template') % let the template filename prevail fname = cfg.grid.template; elseif isfield(cfg.grid, 'resolution') && cfg.grid.resolution==round(cfg.grid.resolution) % use one of the templates that are in Fieldtrip, this requires a % resolution fname = ['standard_sourcemodel3d',num2str(cfg.grid.resolution),'mm.mat']; elseif isfield(cfg.grid, 'resolution') && cfg.grid.resolution~=round(cfg.grid.resolution) fname = ['standard_sourcemodel3d',num2str(floor(cfg.grid.resolution)),'point',num2str(10*(cfg.grid.resolution-floor(cfg.grid.resolution))),'mm.mat']; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check whether the mni template grid exists for the specified resolution % if not create it: FIXME (this needs to be done still) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % get the mri if ischar(cfg.mri) if ~exist(fname, 'file') error('the MNI template grid based on the specified resolution does not exist'); end mri = ft_read_mri(cfg.mri); else mri = cfg.mri; end % get the template grid if ischar(fname) mnigrid = load(fname, 'sourcemodel'); mnigrid = mnigrid.sourcemodel; else mnigrid = cfg.grid.template; end % ensure these to have units in mm, the conversion of the source model is done further down mri = ft_convert_units(mri, 'mm'); mnigrid = ft_convert_units(mnigrid, 'mm'); % ensure that it is specified with logical inside mnigrid = fixinside(mnigrid); % spatial normalisation of mri and construction of subject specific dipole grid positions tmpcfg = []; tmpcfg.nonlinear = cfg.grid.nonlinear; if isfield(cfg.grid, 'templatemri') tmpcfg.template = cfg.grid.templatemri; end normalise = ft_volumenormalise(tmpcfg, mri); if ~isfield(normalise, 'params') && ~isfield(normalise, 'initial') fprintf('applying an inverse warp based on a linear transformation only\n'); grid.pos = ft_warp_apply(inv(normalise.cfg.final), mnigrid.pos); else grid.pos = ft_warp_apply(inv(normalise.initial), ft_warp_apply(normalise.params, mnigrid.pos, 'sn2individual')); end if isfield(mnigrid, 'dim') grid.dim = mnigrid.dim; end if isfield(mnigrid, 'tri') grid.tri = mnigrid.tri; end grid.unit = mnigrid.unit; grid.inside = mnigrid.inside; grid.params = normalise.params; grid.initial = normalise.initial; if ft_datatype(mnigrid, 'parcellation') % copy the boolean fields over grid = copyfields(mnigrid, grid, booleanfields(mnigrid)); end end % in most cases the source model will already be in the desired units, but e.g. for "basedonmni" it will be in 'mm' % convert to the requested units grid = ft_convert_units(grid, cfg.grid.unit); if strcmp(cfg.spherify, 'yes') if ~ft_voltype(headmodel, 'singlesphere') && ~ft_voltype(headmodel, 'concentricspheres') error('this only works for spherical volume conduction models'); end % deform the cortex so that it fits in a unit sphere pos = mesh_spherify(grid.pos, [], 'shift', 'range'); % scale it to the radius of the innermost sphere, make it a tiny bit smaller to % ensure that the support point with the exact radius 1 is still inside the sphere pos = pos*min(headmodel.r)*0.999; pos(:,1) = pos(:,1) + headmodel.o(1); pos(:,2) = pos(:,2) + headmodel.o(2); pos(:,3) = pos(:,3) + headmodel.o(3); grid.pos = pos; end if ~isempty(cfg.moveinward) % construct a triangulated boundary of the source compartment [pos1, tri1] = headsurface(headmodel, [], 'inwardshift', cfg.moveinward, 'surface', 'brain'); inside = bounding_mesh(grid.pos, pos1, tri1); if ~all(inside) pos2 = grid.pos(~inside,:); [dum, pos3] = project_elec(pos2, pos1, tri1); grid.pos(~inside,:) = pos3; end if cfg.moveinward>cfg.inwardshift grid.inside = true(size(grid.pos,1),1); end end % determine the dipole locations that are inside the source compartment of the % volume conduction model, i.e. inside the brain if ~isfield(grid, 'inside') grid.inside = ft_inside_vol(grid.pos, headmodel, 'grad', sens, 'headshape', cfg.headshape, 'inwardshift', cfg.inwardshift); % this returns a boolean vector end if strcmp(cfg.grid.tight, 'yes') fprintf('%d dipoles inside, %d dipoles outside brain\n', sum(grid.inside), sum(~grid.inside)); fprintf('making tight grid\n'); xmin = min(grid.pos(grid.inside,1)); ymin = min(grid.pos(grid.inside,2)); zmin = min(grid.pos(grid.inside,3)); xmax = max(grid.pos(grid.inside,1)); ymax = max(grid.pos(grid.inside,2)); zmax = max(grid.pos(grid.inside,3)); xmin_indx = find(grid.xgrid==xmin); ymin_indx = find(grid.ygrid==ymin); zmin_indx = find(grid.zgrid==zmin); xmax_indx = find(grid.xgrid==xmax); ymax_indx = find(grid.ygrid==ymax); zmax_indx = find(grid.zgrid==zmax); sel = (grid.pos(:,1)>=xmin & grid.pos(:,1)<=xmax); % select all grid positions inside the tight box sel = sel & (grid.pos(:,2)>=ymin & grid.pos(:,2)<=ymax); % select all grid positions inside the tight box sel = sel & (grid.pos(:,3)>=zmin & grid.pos(:,3)<=zmax); % select all grid positions inside the tight box % update the grid locations that are marked as inside the brain grid.pos = grid.pos(sel,:); % update the boolean fields, this requires the original dim fn = booleanfields(grid); for i=1:numel(fn) grid.(fn{i}) = grid.(fn{i})(sel); end grid.xgrid = grid.xgrid(xmin_indx:xmax_indx); grid.ygrid = grid.ygrid(ymin_indx:ymax_indx); grid.zgrid = grid.zgrid(zmin_indx:zmax_indx); grid.dim = [length(grid.xgrid) length(grid.ygrid) length(grid.zgrid)]; end fprintf('%d dipoles inside, %d dipoles outside brain\n', sum(grid.inside), sum(~grid.inside)); % apply the symmetry constraint, i.e. add a symmetric dipole for each location that was defined sofar if ~isempty(cfg.symmetry) if size(grid.pos,2)>3 % sanity check, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3119 warning('the construction of a symmetric dipole model requires to start with a Nx3 description of the dipole positions, discarding subsequent columns'); grid.pos = grid.pos(:,1:3); end if strcmp(cfg.symmetry, 'x') reduce = [1 2 3]; % select the parameters [x1 y1 z1] expand = [1 2 3 1 2 3]; % repeat them as [x1 y1 z1 x1 y1 z1] mirror = [1 1 1 -1 1 1]; % multiply each of them with 1 or -1, resulting in [x1 y1 z1 -x1 y elseif strcmp(cfg.symmetry, 'y') reduce = [1 2 3]; % select the parameters [x1 y1 z1] expand = [1 2 3 1 2 3]; % repeat them as [x1 y1 z1 x1 y1 z1] mirror = [1 1 1 1 -1 1]; % multiply each of them with 1 or -1, resulting in [x1 y1 z1 x1 -y elseif strcmp(cfg.symmetry, 'z') reduce = [1 2 3]; % select the parameters [x1 y1 z1] expand = [1 2 3 1 2 3]; % repeat them as [x1 y1 z1 x1 y1 z1] mirror = [1 1 1 1 1 -1]; % multiply each of them with 1 or -1, resulting in [x1 y1 z1 x1 y1 else error('unrecognized symmetry constraint'); end fprintf('each source describes two dipoles with symmetry along %s axis\n', cfg.symmetry); % expand the number of parameters from one (3) to two dipoles (6) grid.pos = grid.pos(:,expand) .* repmat(mirror, size(grid.pos,1), 1); end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble provenance grid ft_postamble history grid %-------------------------------------------------------------- % helper function for basedonmri method to determine the inside % returns a boolean vector function inside = getinside(pos, mask) % it might be that the box with the points does not completely fit into the % mask dim = size(mask); sel = find(pos(:,1)<1 | pos(:,1)>dim(1) | ... pos(:,2)<1 | pos(:,2)>dim(2) | ... pos(:,3)<1 | pos(:,3)>dim(3)); if isempty(sel) % use the efficient implementation inside = mask(sub2ind(dim, pos(:,1), pos(:,2), pos(:,3))); else % only loop over the points that can be dealt with inside = zeros(size(pos,1), 1); for i=setdiff(1:size(pos,1), sel(:)') inside(i) = mask(pos(i,1), pos(i,2), pos(i,3)); end end %-------------------------------------------------------------------------- % helper function to return the fieldnames of the boolean fields in a % segmentation, should work both for volumetric and for source function fn = booleanfields(mri) fn = fieldnames(mri); isboolean = false(1,numel(fn)); for i=1:numel(fn) if islogical(mri.(fn{i})) && isequal(numel(mri.(fn{i})),prod(mri.dim)) isboolean(i) = true; end end fn = fn(isboolean);
github
lcnbeapp/beapp-master
ft_multiplotER.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_multiplotER.m
35,324
utf_8
39694d442a64d6dd2c92402f20d2f942
function [cfg] = ft_multiplotER(cfg, varargin) % FT_MULTIPLOTER plots the event-related potentials, event-related fields % or oscillatory activity (power or coherence) versus frequency. Multiple % datasets can be overlayed. The plots are arranged according to their % location specified in the layout. % % Use as % ft_multiplotER(cfg, data) % or % ft_multiplotER(cfg, data, data2, ..., dataN) % % The data can be an ERP/ERF produced by FT_TIMELOCKANALYSIS, a powerspectrum % produced by FT_FREQANALYSIS or a coherencespectrum produced by FT_FREQDESCRIPTIVES. % If you specify multiple datasets they must contain the same channels, etc. % % The configuration can have the following parameters: % cfg.parameter = field to be plotted on y-axis (default depends on data.dimord) % 'avg', 'powspctrm' or 'cohspctrm' % cfg.maskparameter = field in the first dataset to be used for marking significant data % cfg.maskstyle = style used for masking of data, 'box', 'thickness' or 'saturation' (default = 'box') % cfg.xlim = 'maxmin' or [xmin xmax] (default = 'maxmin') % cfg.ylim = 'maxmin', 'maxabs', 'zeromax', 'minzero', or [ymin ymax] (default = 'maxmin') % cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details % cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui' % cfg.baseline = 'yes', 'no' or [time1 time2] (default = 'no'), see FT_TIMELOCKBASELINE or FT_FREQBASELINE % cfg.baselinetype = 'absolute' or 'relative' (default = 'absolute') % cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') % cfg.axes = 'yes', 'no' (default = 'yes') % Draw x- and y-axes for each graph % cfg.box = 'yes', 'no' (default = 'no') % Draw a box around each graph % cfg.comment = string of text (default = date + colors) % Add 'comment' to graph (according to COMNT in the layout) % cfg.showlabels = 'yes', 'no' (default = 'no') % cfg.showoutline = 'yes', 'no' (default = 'no') % cfg.fontsize = font size of comment and labels (if present) (default = 8) % cfg.interactive = Interactive plot 'yes' or 'no' (default = 'yes') % In a interactive plot you can select areas and produce a new % interactive plot when a selected area is clicked. Multiple areas % can be selected by holding down the SHIFT key. % cfg.renderer = 'painters', 'zbuffer', ' opengl' or 'none' (default = []) % cfg.linestyle = linestyle/marker type, see options of the PLOT function (default = '-') % can be a single style for all datasets, or a cell-array containing one style for each dataset % cfg.linewidth = linewidth in points (default = 0.5) % cfg.graphcolor = color(s) used for plotting the dataset(s) (default = 'brgkywrgbkywrgbkywrgbkyw') % alternatively, colors can be specified as Nx3 matrix of RGB values % cfg.directionality = '', 'inflow' or 'outflow' specifies for % connectivity measures whether the inflow into a % node, or the outflow from a node is plotted. The % (default) behavior of this option depends on the dimor % of the input data (see below). % cfg.layout = specify the channel layout for plotting using one of % the supported ways (see below). % % For the plotting of directional connectivity data the cfg.directionality % option determines what is plotted. The default value and the supported % functionality depend on the dimord of the input data. If the input data % is of dimord 'chan_chan_XXX', the value of directionality determines % whether, given the reference channel(s), the columns (inflow), or rows % (outflow) are selected for plotting. In this situation the default is % 'inflow'. Note that for undirected measures, inflow and outflow should % give the same output. If the input data is of dimord 'chancmb_XXX', the % value of directionality determines whether the rows in data.labelcmb are % selected. With 'inflow' the rows are selected if the refchannel(s) occur in % the right column, with 'outflow' the rows are selected if the % refchannel(s) occur in the left column of the labelcmb-field. Default in % this case is '', which means that all rows are selected in which the % refchannel(s) occur. This is to robustly support linearly indexed % undirected connectivity metrics. In the situation where undirected % connectivity measures are linearly indexed, specifying 'inflow' or % 'outflow' can result in unexpected behavior. % % The layout defines how the channels are arranged and what the size of each % subplot is. You can specify the layout in a variety of ways: % - you can provide a pre-computed layout structure (see prepare_layout) % - you can give the name of an ascii layout file with extension *.lay % - you can give the name of an electrode file % - you can give an electrode definition, i.e. "elec" structure % - you can give a gradiometer definition, i.e. "grad" structure % If you do not specify any of these and the data structure contains an % electrode or gradiometer structure, that will be used for creating a % layout. If you want to have more fine-grained control over the layout % of the subplots, you should create your own layout file. % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % If you specify this option the input data will be read from a *.mat % file on disk. This mat files should contain only a single variable named 'data', % corresponding to the input structure. For this particular function, the % data should be provided as a cell array. % % See also FT_MULTIPLOTTFR, FT_SINGLEPLOTER, FT_SINGLEPLOTTFR, FT_TOPOPLOTER, % FT_TOPOPLOTTFR, FT_PREPARE_LAYOUT % Undocumented local options: % cfg.layoutname % cfg.preproc % cfg.orient = landscape/portrait % Copyright (C) 2003-2006, Ole Jensen % Copyright (C) 2007-2011, Roemer van der Meij & Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar varargin ft_preamble provenance varargin ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end for i=1:length(varargin) % check if the input data is valid for this function varargin{i} = ft_checkdata(varargin{i}, 'datatype', {'timelock', 'freq'}); end % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'}); cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedforward', 'outflow'}); cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedback', 'inflow'}); cfg = ft_checkconfig(cfg, 'renamed', {'matrixside', 'directionality'}); cfg = ft_checkconfig(cfg, 'renamed', {'cohrefchannel', 'refchannel'}); cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'parameter'}); cfg = ft_checkconfig(cfg, 'renamed', {'hlim', 'xlim'}); cfg = ft_checkconfig(cfg, 'renamed', {'vlim', 'ylim'}); cfg = ft_checkconfig(cfg, 'deprecated', {'xparam'}); cfg = ft_checkconfig(cfg, 'unused', {'cohtargetchannel'}); % set the defaults cfg.baseline = ft_getopt(cfg, 'baseline', 'no'); cfg.trials = ft_getopt(cfg, 'trials', 'all', 1); cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin'); cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin'); cfg.comment = ft_getopt(cfg, 'comment', strcat([date '\n'])); cfg.axes = ft_getopt(cfg, 'axes', 'yes'); cfg.showlabels = ft_getopt(cfg, 'showlabels', 'no'); cfg.showoutline = ft_getopt(cfg, 'showoutline', 'no'); cfg.box = ft_getopt(cfg, 'box', 'no'); cfg.fontsize = ft_getopt(cfg, 'fontsize', 8); cfg.graphcolor = ft_getopt(cfg, 'graphcolor', 'brgkywrgbkywrgbkywrgbkyw'); cfg.interactive = ft_getopt(cfg, 'interactive', 'yes'); cfg.renderer = ft_getopt(cfg, 'renderer'); % let MATLAB decide on default cfg.orient = ft_getopt(cfg, 'orient', 'landscape'); cfg.maskparameter = ft_getopt(cfg, 'maskparameter'); cfg.linestyle = ft_getopt(cfg, 'linestyle', '-'); cfg.linewidth = ft_getopt(cfg, 'linewidth', 0.5); cfg.maskstyle = ft_getopt(cfg, 'maskstyle', 'box'); cfg.channel = ft_getopt(cfg, 'channel', 'all'); cfg.directionality = ft_getopt(cfg, 'directionality', ''); cfg.figurename = ft_getopt(cfg, 'figurename'); cfg.preproc = ft_getopt(cfg, 'preproc'); cfg.tolerance = ft_getopt(cfg, 'tolerance', 1e-5); cfg.frequency = ft_getopt(cfg, 'frequency', 'all'); % needed for frequency selection with TFR data cfg.latency = ft_getopt(cfg, 'latency', 'all'); % needed for latency selection with TFR data, FIXME, probably not used if numel(findobj(gcf, 'type', 'axes', '-not', 'tag', 'ft-colorbar')) > 1 && strcmp(cfg.interactive, 'yes') warning('using cfg.interactive = ''yes'' in subplots is not supported, setting cfg.interactive = ''no''') cfg.interactive = 'no'; end Ndata = length(varargin); for i=1:Ndata dtype{i} = ft_datatype(varargin{i}); hastime(i) = ~isempty(strfind(varargin{i}.dimord, 'time')); hasfreq(i) = ~isempty(strfind(varargin{i}.dimord, 'freq')); end % check if the input has consistent datatypes if ~all(strcmp(dtype, dtype{1})) || ~all(hastime==hastime(1)) || ~all(hasfreq==hasfreq(1)) error('different datatypes are not allowed as input'); end dtype = dtype{1}; hastime = hastime(1); hasfreq = hasfreq(1); % ensure that all inputs are sufficiently consistent if hastime && ~checktime(varargin{:}, 'identical', cfg.tolerance); error('this function requires identical time axes for all input structures'); end if hasfreq && ~checkfreq(varargin{:}, 'identical', cfg.tolerance); error('this function requires identical frequency axes for all input structures'); end %FIXME rename directionality and refchannel in more meaningful options if ischar(cfg.graphcolor) GRAPHCOLOR = ['k' cfg.graphcolor]; elseif isnumeric(cfg.graphcolor) GRAPHCOLOR = [0 0 0; cfg.graphcolor]; end % check for linestyle being a cell-array, check it's length, and lengthen it if does not have enough styles in it if ischar(cfg.linestyle) cfg.linestyle = {cfg.linestyle}; end if Ndata>1 if (length(cfg.linestyle) < Ndata ) && (length(cfg.linestyle) > 1) error('either specify cfg.linestyle as a cell-array with one cell for each dataset, or only specify one linestyle') elseif (length(cfg.linestyle) < Ndata ) && (length(cfg.linestyle) == 1) tmpstyle = cfg.linestyle{1}; cfg.linestyle = cell(Ndata , 1); for idataset = 1:Ndata cfg.linestyle{idataset} = tmpstyle; end end end % % interactive plotting is not allowed with more than 1 input % if numel(varargin)>1 && strcmp(cfg.interactive, 'yes') % error('interactive plotting is not supported with more than 1 input data set'); % end dimord = varargin{1}.dimord; dimtok = tokenize(dimord, '_'); % ensure that the preproc specific options are located in the cfg.preproc % substructure, but also ensure that the field 'refchannel' is present at the % highest level in the structure. This is a little hack by JM because the field % refchannel can also refer to the plotting of a connectivity metric. Also, % the freq2raw conversion does not work at all in the call to ft_preprocessing. % Therefore, for now, the preprocessing will not be done when there is freq % data in the input. A more generic solution should be considered. if isfield(cfg, 'refchannel'), refchannelincfg = cfg.refchannel; end if ~any(strcmp({'freq', 'freqmvar'}, dtype)), cfg = ft_checkconfig(cfg, 'createsubcfg', {'preproc'}); end if exist('refchannelincfg', 'var'), cfg.refchannel = refchannelincfg; end if ~isempty(cfg.preproc) % preprocess the data, i.e. apply filtering, baselinecorrection, etc. fprintf('applying preprocessing options\n'); if ~isfield(cfg.preproc, 'feedback') cfg.preproc.feedback = cfg.interactive; end for i=1:Ndata varargin{i} = ft_preprocessing(cfg.preproc, varargin{i}); end end for i=1:Ndata % this is needed for correct treatment of GRAPHCOLOR later on if nargin>1, if ~isempty(inputname(i+1)) iname{i+1} = inputname(i+1); else iname{i+1} = ['input', num2str(i, '%02d')]; end else iname{i+1} = cfg.inputfile{i}; end end % Set x/y/parameter defaults according to datatype and dimord switch dtype case 'timelock' xparam = 'time'; yparam = ''; cfg.parameter = ft_getopt(cfg, 'parameter', 'avg'); case 'freq' if any(ismember(dimtok, 'time')) xparam = 'time'; yparam = 'freq'; cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm'); else xparam = 'freq'; yparam = ''; cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm'); end case 'comp' % not supported otherwise % not supported end % user specified own fields, but no yparam (which is not asked in help) if exist('xparam', 'var') && isfield(cfg, 'parameter') && ~exist('yparam', 'var') yparam = ''; end if isfield(cfg, 'channel') && isfield(varargin{1}, 'label') cfg.channel = ft_channelselection(cfg.channel, varargin{1}.label); elseif isfield(cfg, 'channel') && isfield(varargin{1}, 'labelcmb') cfg.channel = ft_channelselection(cfg.channel, unique(varargin{1}.labelcmb(:))); end % perform channel selection, unless in the other plotting functions this % can always be done because ft_multiplotER is the entry point into the % interactive stream, but will not be revisited if isfield(varargin{1}, 'label') % only do the channel selection when it can actually be done, % i.e. when the data are bivariate ft_selectdata will crash, moreover % the bivariate case is handled below tmpcfg = keepfields(cfg, 'channel'); tmpvar = varargin{1}; [varargin{:}] = ft_selectdata(tmpcfg, varargin{:}); % restore the provenance information [cfg, varargin{:}] = rollback_provenance(cfg, varargin{:}); if isfield(tmpvar, cfg.maskparameter) && ~isfield(varargin{1}, cfg.maskparameter) % the mask parameter is not present after ft_selectdata, because it is % not included in all input arguments. Make the same selection and copy % it over tmpvar = ft_selectdata(tmpcfg, tmpvar); varargin{1}.(cfg.maskparameter) = tmpvar.(cfg.maskparameter); end clear tmpvar tmpcfg end if isfield(varargin{1}, 'label') % && strcmp(cfg.interactive, 'no') selchannel = ft_channelselection(cfg.channel, varargin{1}.label); elseif isfield(varargin{1}, 'labelcmb') % && strcmp(cfg.interactive, 'no') selchannel = ft_channelselection(cfg.channel, unique(varargin{1}.labelcmb(:))); end % check whether rpt/subj is present and remove if necessary % FIXME this should be implemented with avgoverpt in ft_selectdata hasrpt = sum(ismember(dimtok, {'rpt' 'subj'})); if strcmp(dtype, 'timelock') && hasrpt, tmpcfg = []; % disable hashing of input data (speeds up things) tmpcfg.trackcallinfo = 'no'; tmpcfg.trials = cfg.trials; for i=1:Ndata % save mask (timelockanalysis will remove it) if ~isempty(cfg.maskparameter) tmpmask = varargin{i}.(cfg.maskparameter); end varargin{i} = ft_timelockanalysis(tmpcfg, varargin{i}); if ~strcmp(cfg.parameter, 'avg') % rename avg back into its original parameter name varargin{i}.(cfg.parameter) = varargin{i}.avg; varargin{i} = rmfield(varargin{i}, 'avg'); end % put back mask if ~isempty(cfg.maskparameter) varargin{i}.(cfg.maskparameter) = tmpmask; end end dimord = varargin{1}.dimord; dimtok = tokenize(dimord, '_'); elseif strcmp(dtype, 'freq') && hasrpt, % this also deals with fourier-spectra in the input % or with multiple subjects in a frequency domain stat-structure % on the fly computation of coherence spectrum is not supported for i=1:Ndata if isfield(varargin{i}, 'crsspctrm'), varargin{i} = rmfield(varargin{i}, 'crsspctrm'); end end tmpcfg = []; tmpcfg.trials = cfg.trials; tmpcfg.jackknife = 'no'; for i=1:Ndata if isfield(cfg, 'parameter') && ~strcmp(cfg.parameter, 'powspctrm') % freqdesctiptives will only work on the powspctrm field % hence a temporary copy of the data is needed tempdata.dimord = varargin{i}.dimord; tempdata.freq = varargin{i}.freq; tempdata.label = varargin{i}.label; tempdata.powspctrm = varargin{i}.(cfg.parameter); if isfield(varargin{i}, 'cfg') tempdata.cfg = varargin{i}.cfg; end tempdata = ft_freqdescriptives(tmpcfg, tempdata); varargin{i}.(cfg.parameter) = tempdata.powspctrm; clear tempdata else varargin{i} = ft_freqdescriptives(tmpcfg, varargin{i}); end end dimord = varargin{1}.dimord; dimtok = tokenize(dimord, '_'); end % % Read or create the layout that will be used for plotting cla lay = ft_prepare_layout(cfg, varargin{1}); cfg.layout = lay; % plot layout boxflg = istrue(cfg.box); labelflg = false; % channel labels are plotted further down using ft_plot_vector outlineflg = istrue(cfg.showoutline); ft_plot_lay(lay, 'box', boxflg, 'label', labelflg, 'outline', outlineflg, 'point', 'no', 'mask', 'no'); % Apply baseline correction if ~strcmp(cfg.baseline, 'no') for i=1:Ndata if strcmp(dtype, 'timelock') && strcmp(xparam, 'time') varargin{i} = ft_timelockbaseline(cfg, varargin{i}); elseif strcmp(dtype, 'freq') && strcmp(xparam, 'time') varargin{i} = ft_freqbaseline(cfg, varargin{i}); elseif strcmp(dtype, 'freq') && strcmp(xparam, 'freq') error('Baseline correction is not supported for spectra without a time dimension'); else warning('Baseline correction not applied, please set xparam'); end end end % Handle the bivariate case % Check for bivariate metric with 'chan_chan' in the dimord selchan = strmatch('chan', dimtok); isfull = length(selchan)>1; % Check for bivariate metric with a labelcmb haslabelcmb = isfield(varargin{1}, 'labelcmb'); if (isfull || haslabelcmb) && (isfield(varargin{1}, cfg.parameter) && ~strcmp(cfg.parameter, 'powspctrm')) % A reference channel is required: if ~isfield(cfg, 'refchannel') error('no reference channel is specified'); end % check for refchannel being part of selection if ~strcmp(cfg.refchannel, 'gui') if haslabelcmb cfg.refchannel = ft_channelselection(cfg.refchannel, unique(varargin{1}.labelcmb(:))); else cfg.refchannel = ft_channelselection(cfg.refchannel, varargin{1}.label); end if (isfull && ~any(ismember(varargin{1}.label, cfg.refchannel))) || ... (haslabelcmb && ~any(ismember(varargin{1}.labelcmb(:), cfg.refchannel))) error('cfg.refchannel is a not present in the (selected) channels)') end end % Interactively select the reference channel if strcmp(cfg.refchannel, 'gui') % Open a single figure with the channel layout, the user can click on a reference channel h = clf; ft_plot_lay(lay, 'box', false); title('Select the reference channel by dragging a selection window, more than 1 channel can be selected...'); % add the channel information to the figure info = guidata(gcf); info.x = lay.pos(:, 1); info.y = lay.pos(:, 2); info.label = lay.label; guidata(h, info); %set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'callback', {@select_topoplotER, cfg, data}}); set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotER, cfg, varargin{1}}, 'event', 'WindowButtonUpFcn'}); set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotER, cfg, varargin{1}}, 'event', 'WindowButtonDownFcn'}); set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotER, cfg, varargin{1}}, 'event', 'WindowButtonMotionFcn'}); return end for i=1:Ndata if ~isfull, % Convert 2-dimensional channel matrix to a single dimension: if isempty(cfg.directionality) sel1 = find(strcmp(cfg.refchannel, varargin{i}.labelcmb(:, 2))); sel2 = find(strcmp(cfg.refchannel, varargin{i}.labelcmb(:, 1))); elseif strcmp(cfg.directionality, 'outflow') sel1 = []; sel2 = find(strcmp(cfg.refchannel, varargin{i}.labelcmb(:, 1))); elseif strcmp(cfg.directionality, 'inflow') sel1 = find(strcmp(cfg.refchannel, varargin{i}.labelcmb(:, 2))); sel2 = []; end fprintf('selected %d channels for %s\n', length(sel1)+length(sel2), cfg.parameter); if length(sel1)+length(sel2)==0 error('there are no channels selected for plotting: you may need to look at the specification of cfg.directionality'); end varargin{i}.(cfg.parameter) = varargin{i}.(cfg.parameter)([sel1;sel2], :, :); varargin{i}.label = [varargin{i}.labelcmb(sel1, 1);varargin{i}.labelcmb(sel2, 2)]; varargin{i}.labelcmb = varargin{i}.labelcmb([sel1;sel2], :); %varargin{i} = rmfield(varargin{i}, 'labelcmb'); else % General case sel = match_str(varargin{i}.label, cfg.refchannel); siz = [size(varargin{i}.(cfg.parameter)) 1]; if strcmp(cfg.directionality, 'inflow') || isempty(cfg.directionality) %the interpretation of 'inflow' and 'outflow' depend on %the definition in the bivariate representation of the data %in FieldTrip the row index 'causes' the column index channel %data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(:, sel, :), 2), [siz(1) 1 siz(3:end)]); sel1 = 1:siz(1); sel2 = sel; meandir = 2; elseif strcmp(cfg.directionality, 'outflow') %data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(sel, :, :), 1), [siz(1) 1 siz(3:end)]); sel1 = sel; sel2 = 1:siz(1); meandir = 1; elseif strcmp(cfg.directionality, 'ff-fd') error('cfg.directionality = ''ff-fd'' is not supported anymore, you have to manually subtract the two before the call to ft_multiplotER'); elseif strcmp(cfg.directionality, 'fd-ff') error('cfg.directionality = ''fd-ff'' is not supported anymore, you have to manually subtract the two before the call to ft_multiplotER'); end %if directionality end %if ~isfull end %for i end %handle the bivariate data % Get physical min/max range of x if strcmp(cfg.xlim, 'maxmin') % Find maxmin throughout all varargins: xmin = []; xmax = []; for i=1:length(varargin) xmin = min([xmin varargin{i}.(xparam)]); xmax = max([xmax varargin{i}.(xparam)]); end else xmin = cfg.xlim(1); xmax = cfg.xlim(2); end % Get the index of the nearest bin for i=1:Ndata xidmin(i, 1) = nearest(varargin{i}.(xparam), xmin); xidmax(i, 1) = nearest(varargin{i}.(xparam), xmax); end if strcmp('freq',yparam) && strcmp('freq',dtype) tmpcfg = keepfields(cfg, {'parameter'}); tmpcfg.avgoverfreq = 'yes'; tmpcfg.frequency = cfg.frequency; [varargin{:}] = ft_selectdata(tmpcfg, varargin{:}); % restore the provenance information [cfg, varargin{:}] = rollback_provenance(cfg, varargin{:}); elseif strcmp('time',yparam) && strcmp('freq',dtype) tmpcfg = keepfields(cfg, {'parameter'}); tmpcfg.avgovertime = 'yes'; tmpcfg.latency = cfg.latency; [varargin{:}] = ft_selectdata(tmpcfg, varargin{:}); % restore the provenance information [cfg, varargin{:}] = rollback_provenance(cfg, varargin{:}); end % Get physical y-axis range (ylim / parameter): if strcmp(cfg.ylim, 'maxmin') || strcmp(cfg.ylim, 'maxabs') % Find maxmin throughout all varargins: ymin = []; ymax = []; for i=1:length(varargin) % Select the channels in the data that match with the layout and that % are selected for plotting: dat = []; dat = varargin{i}.(cfg.parameter); seldat1 = match_str(varargin{i}.label, lay.label); % indexes labels corresponding in input and layout seldat2 = match_str(varargin{i}.label, cfg.channel); % indexes labels corresponding in input and plot-selection if isempty(seldat1) error('labels in data and labels in layout do not match'); end data = dat(intersect(seldat1, seldat2), :); ymin = min([ymin min(min(min(data)))]); ymax = max([ymax max(max(max(data)))]); end if strcmp(cfg.ylim, 'maxabs') % handle maxabs, make y-axis center on 0 ymax = max([abs(ymax) abs(ymin)]); ymin = -ymax; elseif strcmp(cfg.ylim, 'zeromax') ymin = 0; elseif strcmp(cfg.ylim, 'minzero') ymax = 0; end else ymin = cfg.ylim(1); ymax = cfg.ylim(2); end % convert the layout to Ole's style of variable names X = lay.pos(:, 1); Y = lay.pos(:, 2); width = lay.width; height = lay.height; Lbl = lay.label; % Create empty channel coordinates and labels arrays: chanX(1:length(Lbl)) = NaN; chanY(1:length(Lbl)) = NaN; chanLabels = cell(1, length(Lbl)); hold on; colorLabels = []; % Plot each data set: for i=1:Ndata % Make vector dat with one value for each channel dat = varargin{i}.(cfg.parameter); % get dimord dimensions dims = textscan(varargin{i}.dimord, '%s', 'Delimiter', '_'); dims = dims{1}; ydim = find(strcmp(yparam, dims)); xdim = find(strcmp(xparam, dims)); zdim = setdiff(1:ndims(dat), [ydim xdim]); % and permute dat = permute(dat, [zdim(:)' ydim xdim]); xval = varargin{i}.(xparam); % Take subselection of channels, this only works % in the non-interactive mode if exist('selchannel', 'var') sellab = match_str(varargin{i}.label, selchannel); label = varargin{i}.label(sellab); else sellab = 1:numel(varargin{i}.label); label = varargin{i}.label; end if isfull dat = dat(sel1, sel2, xidmin(i):xidmax(i)); dat = nanmean(dat, meandir); elseif haslabelcmb dat = dat(sellab, xidmin(i):xidmax(i)); else dat = dat(sellab, xidmin(i):xidmax(i)); end xval = xval(xidmin(i):xidmax(i)); % Select the channels in the data that match with the layout: [seldat, sellay] = match_str(label, cfg.layout.label); if isempty(seldat) error('labels in data and labels in layout do not match'); end % gather the data of multiple input arguments datamatrix{i} = dat(seldat, :); % Select x and y coordinates and labels of the channels in the data layX = cfg.layout.pos(sellay, 1); layY = cfg.layout.pos(sellay, 2); layLabels = cfg.layout.label(sellay); if ~isempty(cfg.maskparameter) % one value for each channel, or one value for each channel-time point maskmatrix = varargin{1}.(cfg.maskparameter)(seldat, :); maskmatrix = maskmatrix(:, xidmin:xidmax); else % create an Nx0 matrix maskmatrix = zeros(length(seldat), 0); end if Ndata > 1 if ischar(GRAPHCOLOR); colorLabels = [colorLabels iname{i+1} '=' GRAPHCOLOR(i+1) '\n']; elseif isnumeric(GRAPHCOLOR); colorLabels = [colorLabels iname{i+1} '=' num2str(GRAPHCOLOR(i+1, :)) '\n']; end end end % for number of input data for m=1:length(layLabels) % Plot ER if ischar(GRAPHCOLOR); color = GRAPHCOLOR(2:end); elseif isnumeric(GRAPHCOLOR); color = GRAPHCOLOR(2:end, :); end mask = maskmatrix(m, :); for i=1:Ndata yval(i, :) = datamatrix{i}(m, :); end % Clip out of bounds y values: yval(yval > ymax) = ymax; yval(yval < ymin) = ymin; if strcmp(cfg.showlabels, 'yes') label = layLabels(m); else % don't show labels label = []; end ft_plot_vector(xval, yval, 'width', width(m), 'height', height(m), 'hpos', layX(m), 'vpos', layY(m), 'hlim', [xmin xmax], 'vlim', [ymin ymax], 'color', color, 'style', cfg.linestyle{i}, 'linewidth', cfg.linewidth, 'axis', cfg.axes, 'highlight', mask, 'highlightstyle', cfg.maskstyle, 'label', label, 'box', cfg.box, 'fontsize', cfg.fontsize); if i==1, % Keep ER plot coordinates (at centre of ER plot), and channel labels (will be stored in the figure's UserData struct): chanX(m) = X(m) + 0.5 * width(m); chanY(m) = Y(m) + 0.5 * height(m); chanLabels{m} = Lbl{m}; end end % for number of channels % Add the colors of the different datasets to the comment: cfg.comment = [cfg.comment colorLabels]; % Write comment text: l = cellstrmatch('COMNT', Lbl); if ~isempty(l) ft_plot_text(X(l), Y(l), sprintf(cfg.comment), 'Fontsize', cfg.fontsize, 'interpreter', 'none'); end % Plot scales: l = cellstrmatch('SCALE', Lbl); if ~isempty(l) plotScales([xmin xmax], [ymin ymax], X(l), Y(l), width(1), height(1), cfg) end % set the figure window title if isempty(get(gcf, 'Name')) if nargin > 1 dataname = {inputname(2)}; for k = 2:Ndata dataname{end+1} = inputname(k+1); end else % data provided through cfg.inputfile dataname = cfg.inputfile; end if isempty(cfg.figurename) set(gcf, 'Name', sprintf('%d: %s: %s', double(gcf), mfilename, join_str(', ', dataname))); set(gcf, 'NumberTitle', 'off'); else set(gcf, 'name', cfg.figurename); set(gcf, 'NumberTitle', 'off'); end else dataname = {}; end % Make the figure interactive: if strcmp(cfg.interactive, 'yes') % add the dataname and channel information to the figure % this is used in the callbacks info = guidata(gcf); info.x = lay.pos(:, 1); info.y = lay.pos(:, 2); info.label = lay.label; info.dataname = dataname; guidata(gcf, info); set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg, varargin{:}}, 'event', 'WindowButtonUpFcn'}); set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg, varargin{:}}, 'event', 'WindowButtonDownFcn'}); set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg, varargin{:}}, 'event', 'WindowButtonMotionFcn'}); end axis tight axis off if strcmp(cfg.box, 'yes') abc = axis; axis(abc + [-1 +1 -1 +1]*mean(abs(abc))/10) end hold off % Set orientation for printing if specified if ~isempty(cfg.orient) orient(gcf, cfg.orient); end % Set renderer if specified if ~isempty(cfg.renderer) set(gcf, 'renderer', cfg.renderer) end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous varargin ft_postamble provenance % add a menu to the figure, but only if the current figure does not have subplots % also, delete any possibly existing previous menu, this is safe because delete([]) does nothing delete(findobj(gcf, 'type', 'uimenu', 'label', 'FieldTrip')); if numel(findobj(gcf, 'type', 'axes')) <= 1 ftmenu = uimenu(gcf, 'Label', 'FieldTrip'); uimenu(ftmenu, 'Label', 'Show pipeline', 'Callback', {@menu_pipeline, cfg}); uimenu(ftmenu, 'Label', 'About', 'Callback', @menu_about); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plotScales(hlim, vlim, hpos, vpos, width, height, cfg) % the placement of all elements is identical placement = {'hpos', hpos, 'vpos', vpos, 'width', width, 'height', height, 'hlim', hlim, 'vlim', vlim}; ft_plot_box([hlim vlim], placement{:}, 'edgecolor', 'k'); if hlim(1)<=0 && hlim(2)>=0 ft_plot_vector([0 0], vlim, placement{:}, 'color', 'b'); end if vlim(1)<=0 && vlim(2)>=0 ft_plot_vector(hlim, [0 0], placement{:}, 'color', 'b'); end ft_plot_text(hlim(1), vlim(1), [num2str(hlim(1), 3) ' '], placement{:}, 'rotation', 90, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'top', 'Fontsize', cfg.fontsize); ft_plot_text(hlim(2), vlim(1), [num2str(hlim(2), 3) ' '], placement{:}, 'rotation', 90, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'top', 'Fontsize', cfg.fontsize); ft_plot_text(hlim(1), vlim(1), [num2str(vlim(1), 3) ' '], placement{:}, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'bottom', 'Fontsize', cfg.fontsize); ft_plot_text(hlim(1), vlim(2), [num2str(vlim(2), 3) ' '], placement{:}, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'bottom', 'Fontsize', cfg.fontsize); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function l = cellstrmatch(str, strlist) l = []; for k=1:length(strlist) if strcmp(char(str), char(strlist(k))) l = [l k]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION which is called after selecting channels in case of cfg.refchannel='gui' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function select_multiplotER(label, cfg, varargin) if ~isempty(label) if isfield(cfg, 'inputfile') % the reading has already been done and varargin contains the data cfg = rmfield(cfg, 'inputfile'); end % put data name in here, this cannot be resolved by other means info = guidata(gcf); cfg.dataname = info.dataname; if iscell(label) label = label{1}; end cfg.refchannel = label; % FIXME this only works with label being a string fprintf('selected cfg.refchannel = ''%s''\n', cfg.refchannel); p = get(gcf, 'Position'); f = figure; set(f, 'Position', p); ft_multiplotER(cfg, varargin{:}); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION which is called after selecting channels in case of cfg.interactive='yes' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function select_singleplotER(label, cfg, varargin) if ~isempty(label) if isfield(cfg, 'inputfile') % the reading has already been done and varargin contains the data cfg = rmfield(cfg, 'inputfile'); end cfg.channel = label; % put data name in here, this cannot be resolved by other means info = guidata(gcf); cfg.dataname = info.dataname; fprintf('selected cfg.channel = {'); for i=1:(length(cfg.channel)-1) fprintf('''%s'', ', cfg.channel{i}); end fprintf('''%s''}\n', cfg.channel{end}); p = get(gcf, 'Position'); f = figure; set(f, 'Position', p); ft_singleplotER(cfg, varargin{:}); end
github
lcnbeapp/beapp-master
ft_prepare_mesh.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_prepare_mesh.m
9,219
utf_8
ee790b2287e954598ed510afb471183a
function [bnd, cfg] = ft_prepare_mesh(cfg, mri) % FT_PREPARE_MESH creates a triangulated surface mesh for the volume % conduction model. The mesh can either be selected manually from raw % mri data or can be generated starting from a segmented volume % information stored in the mri structure. FT_PREPARE_MESH can be used % to create a cortex hull, i.e. the smoothed envelope around the pial % surface created by freesurfer. The result is a bnd structure which % contains the information about all segmented surfaces related to mri % sand are expressed in world coordinates. % % Use as % bnd = ft_prepare_mesh(cfg, mri) % bnd = ft_prepare_mesh(cfg, seg) % bnd = ft_prepare_mesh(cfg) # for cortexhull % % Configuration options: % cfg.method = string, can be 'interactive', 'projectmesh', 'iso2mesh', 'isosurface', % 'headshape', 'hexahedral', 'tetrahedral', 'cortexhull' % cfg.tissue = cell-array with tissue types or numeric vector with integer values % cfg.numvertices = numeric vector, should have same number of elements as cfg.tissue % cfg.downsample = integer number (default = 1, i.e. no downsampling), see FT_VOLUMEDOWNSAMPLE % cfg.headshape = (optional) a filename containing headshape, a Nx3 matrix with surface % points, or a structure with a single or multiple boundaries % % Method 'cortexhull' has its own specific configuration options: % cfg.headshape = a filename containing the pial surface computed by % freesurfer recon-all ('/path/to/surf/lh.pial') % cfg. % % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % cfg.outputfile = ... % If you specify one of these (or both) the input data will be read from a *.mat % file on disk and/or the output data will be written to a *.mat file. These mat % files should contain only a single variable, corresponding with the % input/output structure. % % Example % mri = ft_read_mri('Subject01.mri'); % % cfg = []; % cfg.output = {'scalp', 'skull', 'brain'}; % segmentation = ft_volumesegment(cfg, mri); % % cfg = []; % cfg.tissue = {'scalp', 'skull', 'brain'}; % cfg.numvertices = [800, 1600, 2400]; % bnd = ft_prepare_mesh(cfg, segmentation); % % cfg = []; % cfg.method = 'cortexhull'; % cfg.headshape = '/path/to/surf/lh.pial'; % cortex_hull = ft_prepare_mesh(cfg); % % See also FT_VOLUMESEGMENT, FT_PREPARE_HEADMODEL, FT_PLOT_MESH % Undocumented functionality: at this moment it allows for either % bnd = ft_prepare_mesh(cfg) or % bnd = ft_prepare_mesh(cfg, headmodel) % but more consistent would be to specify a volume conduction model with % cfg.headmodel = structure with volume conduction model, see FT_PREPARE_HEADMODEL % cfg.headshape = name of file containing the volume conduction model, see FT_READ_VOL % % Undocumented options, I have no clue why they exist % cfg.method = {'singlesphere' 'concentricspheres' 'localspheres'} % Copyrights (C) 2009-2012, Robert Oostenveld & Cristiano Micheli % Copyrights (C) 2012-2013, Robert Oostenveld & Lilla Magyari % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar mri ft_preamble provenance mri ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % we cannot use nargin, because the data might have been loaded from cfg.inputfile hasdata = exist('mri', 'var'); % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'forbidden', {'numcompartments', 'outputfile', 'sourceunits', 'mriunits'}); % get the options cfg.downsample = ft_getopt(cfg, 'downsample', 1); % default is no downsampling cfg.numvertices = ft_getopt(cfg, 'numvertices'); % no default % This was changed on 3 December 2013, this backward compatibility can be removed in 6 months from now. if isfield(cfg, 'interactive') if strcmp(cfg.interactive, 'yes') warning('please specify cfg.method=''interactive'' instead of cfg.interactive=''yes'''); cfg.method = 'interactive'; end cfg = rmfield(cfg, 'interactive'); end % This was changed on 3 December 2013, it makes sense to keep it like this on the % long term (previously there was no explicit use of cfg.method, now there is). % Translate the input options in the appropriate cfg.method. if ~isfield(cfg, 'method') if isfield(cfg, 'headshape') && ~isempty(cfg.headshape) warning('please specify cfg.method=''headshape'''); cfg.method = 'headshape'; elseif hasdata && ~strcmp(ft_voltype(mri), 'unknown') % the input is a spherical volume conduction model cfg.method = ft_voltype(mri); elseif hasdata warning('please specify cfg.method=''projectmesh'', ''iso2mesh'' or ''isosurface'''); warning('using ''projectmesh'' as default'); cfg.method = 'projectmesh'; end end if hasdata && cfg.downsample~=1 % optionally downsample the anatomical volume and/or tissue segmentations tmpcfg = keepfields(cfg, {'downsample'}); mri = ft_volumedownsample(tmpcfg, mri); % restore the provenance information [cfg, mri] = rollback_provenance(cfg, mri); end switch cfg.method case 'interactive' % this makes sense with a non-segmented MRI as input % call the corresponding helper function bnd = prepare_mesh_manual(cfg, mri); case {'projectmesh', 'iso2mesh', 'isosurface'} % this makes sense with a segmented MRI as input % call the corresponding helper function bnd = prepare_mesh_segmentation(cfg, mri); case 'headshape' % call the corresponding helper function bnd = prepare_mesh_headshape(cfg); case 'hexahedral' % the MRI is assumed to contain a segmentation % call the corresponding helper function bnd = prepare_mesh_hexahedral(cfg, mri); case 'tetrahedral' % the MRI is assumed to contain a segmentation % call the corresponding helper function bnd = prepare_mesh_tetrahedral(cfg, mri); case {'singlesphere' 'concentricspheres' 'localspheres'} % FIXME for localspheres it should be replaced by an outline of the head, see private/headsurface fprintf('triangulating the sphere in the volume conductor\n'); [pos, tri] = makesphere(cfg.numvertices); bnd = []; mri = ft_convert_units(mri); % ensure that it has units headmodel = ft_datatype_headmodel(mri); % rename it and ensure that it is consistent and up-to-date for i=1:length(headmodel.r) bnd(i).pos(:,1) = pos(:,1)*headmodel.r(i) + headmodel.o(1); bnd(i).pos(:,2) = pos(:,2)*headmodel.r(i) + headmodel.o(2); bnd(i).pos(:,3) = pos(:,3)*headmodel.r(i) + headmodel.o(3); bnd(i).tri = tri; end case 'cortexhull' bnd = prepare_cortexhull(cfg); otherwise error('unsupported cfg.method') end % copy the geometrical units from the input to the output if ~isfield(bnd, 'unit') && hasdata && isfield(mri, 'unit') for i=1:numel(bnd) bnd(i).unit = mri.unit; end elseif ~isfield(bnd, 'unit') bnd = ft_convert_units(bnd); end % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous mri ft_postamble provenance bnd ft_postamble history bnd %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % HELPER FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [pos, tri] = makesphere(numvertices) if isempty(numvertices) [pos,tri] = icosahedron162; fprintf('using the mesh specified by icosaedron162\n'); elseif numvertices==42 [pos,tri] = icosahedron42; fprintf('using the mesh specified by icosaedron%d\n',size(pos,1)); elseif numvertices==162 [pos,tri] = icosahedron162; fprintf('using the mesh specified by icosaedron%d\n',size(pos,1)); elseif numvertices==642 [pos,tri] = icosahedron642; fprintf('using the mesh specified by icosaedron%d\n',size(pos,1)); elseif numvertices==2562 [pos,tri] = icosahedron2562; fprintf('using the mesh specified by icosaedron%d\n',size(pos,1)); else [pos, tri] = msphere(numvertices); fprintf('using the mesh specified by msphere with %d vertices\n',size(pos,1)); end
github
lcnbeapp/beapp-master
fieldtrip2fiff.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fieldtrip2fiff.m
10,130
utf_8
bce65d78216fd8c34de7e249b66f54d4
function fieldtrip2fiff(filename, data) % FIELDTRIP2FIFF saves a FieldTrip raw data structure as a fiff-file, allowing it % to be further analyzed by the Elekta/Neuromag software, or in the MNE suite % software. % % Use as % fieldtrip2fiff(filename, data) % where filename is the name of the output file, and data is a raw data structure % as obtained from FT_PREPROCESSING, or a timelock structure obtained from % FT_TIMELOCKANALYSIS. % % If the data comes from preprocessing and has only one trial, then it writes the % data into raw continuous format. If present in the data, the original header % from neuromag is reused (also removing the non-used channels). Otherwise, the % function tries to create a correct header, which might or might not contain the % correct scaling and channel location. If the data contains events in the cfg % structure, it writes the events in the MNE format (three columns) into a file % based on "filename", ending with "-eve.fif" % % See also FT_DATATYPE_RAW, FT_DATATYPE_TIMELOCK % Copyright (C) 2012-2013, Jan-Mathijs Schoffelen, Gio Piantoni % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % this ensures that the path is correct and that the ft_defaults global variable is available ft_defaults % ensure that the filename has the correct extension [pathstr, name, ext] = fileparts(filename); if ~strcmp(ext, '.fif') error('if the filename is specified with extension, this should read .fif'); end fifffile = [pathstr filesep name '.fif']; eventfile = [pathstr filesep name '-eve.fif']; % ensure the mne-toolbox to be on the path ft_hastoolbox('mne', 1); % check if the input data is valid for this function data = ft_checkdata(data, 'datatype', {'raw', 'timelock'}, 'feedback', 'yes'); istlck = ft_datatype(data, 'timelock'); isepch = ft_datatype(data, 'raw'); israw = false; if isepch && numel(data.trial) == 1 isepch = false; israw = true; end % Create a fiff-header, or take it from the original header if possible if ft_senstype(data, 'neuromag') && isfield(data, 'hdr') fprintf('Using the original FIFF header, but channel locations are read \nfrom .grad and .elec in the data, if they exist\n') info = data.hdr.orig; else info.meas_id.version = NaN; info.meas_id.machid = [NaN;NaN]; info.meas_id.secs = NaN; info.meas_id.usecs = NaN; info.meas_date = [NaN;NaN]; info.acq_pars = []; % needed by raw info.acq_stim = []; % needed by raw info.highpass = NaN; info.lowpass = NaN; % no strictly necessary, but the inverse functions in MNE works better if % this matrix is present info.dev_head_t.from = 1; info.dev_head_t.to = 4; info.dev_head_t.trans = eye(4); info.ctf_head_t = []; info.dig = []; info.projs = struct('kind', {}, 'active', {}, 'desc', {}, 'data', {}); info.comps = struct('ctfkind', {}, 'kind', {}, 'save_calibrated', {}, ... 'rowcals', {}, 'colcals', {}, 'data', {}); info.bads = []; if isepch info.sfreq = 1./mean(diff(data.time{1})); info.isaverage = 0; info.isepoched = 1; info.iscontinuous = 0; elseif istlck info.sfreq = 1./mean(diff(data.time)); info.isaverage = 1; info.isepoched = 0; info.iscontinuous = 0; end end if israw info.sfreq = data.fsample; elseif isepch info.sfreq = 1 ./ mean(diff(data.time{1})); elseif istlck info.sfreq = 1 ./ mean(diff(data.time)); end info.ch_names = data.label(:)'; info.chs = sens2fiff(data); info.nchan = numel(data.label); if israw [outfid, cals] = fiff_start_writing_raw(fifffile, info); fiff_write_raw_buffer(outfid, data.trial{1}, cals); fiff_finish_writing_raw(outfid); % write events, if they exists if isfield(data, 'cfg') event = ft_findcfg(data.cfg, 'event'); else event = []; end if ~isempty(event) eve = convertevent(event); mne_write_events(eventfile, eve); fprintf('Writing events to %s\n', eventfile) end elseif isepch error('fieldtrip2fiff:NotImplementedError', 'Function to write epochs to MNE not implemented yet') for j = 1:length(data.trial) evoked(j).aspect_kind = 100; evoked(j).is_smsh = 0; % FIXME: How could we tell? evoked(j).nave = 1; % FIXME: Use the real value evoked(j).first = round(data.time{j}(1)*info.sfreq); evoked(j).last = round(data.time{j}(end)*info.sfreq); evoked(j).times = data.time{j}; evoked(j).comment = sprintf('FieldTrip data, category/trial %d', j); evoked(j).epochs = data.trial{j}; end % fiffdata.info = info; % fiffdata.evoked = evoked; % fiff_write_XXX(fifffile, fiffdata); elseif istlck evoked.aspect_kind = 100; evoked.is_smsh = 0; evoked.nave = max(data.dof(:)); evoked.first = round(data.time(1)*info.sfreq); evoked.last = round(data.time(end)*info.sfreq); evoked.times = data.time; evoked.comment = sprintf('FieldTrip data averaged'); evoked.epochs = data.avg; fiffdata.info = info; fiffdata.evoked = evoked; fiff_write_evoked(fifffile, fiffdata); end %------------------- % subfunction function [chs] = sens2fiff(data) % use orig information if available if isfield(data, 'hdr') && isfield(data.hdr, 'orig') && ... isfield(data.hdr.orig, 'chs') [dummy, i_label, i_chs] = intersect(data.label, {data.hdr.orig.chs.ch_name}); chs(i_label) = data.hdr.orig.chs(i_chs); return end % otherwise reconstruct it fprintf('Reconstructing channel locations, it might be inaccurate\n') FIFF = fiff_define_constants; % some constants are not defined in the MATLAB function if isfield(data, 'grad') hasgrad = true; else hasgrad = false; end if isfield(data, 'elec') haselec = true; elec = ft_convert_units(data.elec, 'cm'); % that MNE uses cm else haselec = false; end cnt_grad = 0; cnt_elec = 0; cnt_else = 0; for k = 1:numel(data.label) % create a struct for each channel chs(1,k).scanno = k; chs(1,k).ch_name = data.label{k}; chs(1,k).range = 1; chs(1,k).cal = 1; i_grad = false; i_elec = false; if hasgrad i_grad = strcmp(data.grad.label, data.label{k}); elseif haselec i_elec = strcmp(elec.label, data.label{k}); end if any(i_grad) chs(1,k).kind = FIFF.FIFFV_MEG_CH; cnt_grad = cnt_grad + 1; chs(1,k).logno = cnt_grad; switch data.grad.chantype{i_grad} case 'megmag' chs(1,k).coil_type = 3024; chs(1,k).unit = FIFF.FIFF_UNIT_T; case 'megplanar' chs(1,k).coil_type = 3012; chs(1,k).unit = FIFF.FIFF_UNIT_T_M; case 'meggrad' chs(1,k).coil_type = 3022; chs(1,k).unit = FIFF.FIFF_UNIT_T; otherwise fprintf('Unknown channel type %s, assigned to meggrad', data.grad.chantype{i_grad}) chs(1,k).coil_type = 3022; chs(1,k).unit = FIFF.FIFF_UNIT_T; end chs(1,k).coil_trans = eye(4); chs(1,k).unit_mul = 0; chs(1,k).coord_frame = FIFF.FIFFV_COORD_HEAD; chs(1,k).eeg_loc = []; chs(1,k).loc = [data.grad.chanpos(i_grad,:)'; reshape(eye(3),[9 1])]; elseif any(i_elec) chs(1,k).kind = FIFF.FIFFV_EEG_CH; cnt_elec = cnt_elec + 1; chs(1,k).logno = cnt_elec; chs(1,k).coil_type = NaN; chs(1,k).coil_trans = []; chs(1,k).unit = 107; % volts FIFF.FIFF_UNIT_V chs(1,k).unit_mul = -6; % micro FIFF.FIFF_UNITM_MU chs(1,k).coord_frame = FIFF.FIFFV_COORD_DEVICE; chs(1,k).eeg_loc = [elec.chanpos(i_elec,:)' zeros(3,1)] / 100; chs(1,k).loc = [chs(1,k).eeg_loc(:); 0; 1; 0; 0; 0; 1]; else chs(1,k).kind = NaN; cnt_else = cnt_else + 1; chs(1,k).logno = cnt_else; chs(1,k).coil_type = NaN; chs(1,k).coil_trans = []; chs(1,k).unit = NaN; chs(1,k).unit_mul = 0; chs(1,k).coord_frame = NaN; chs(1,k).eeg_loc = []; chs(1,k).loc = zeros(12,1); end end function eve = convertevent(event) % tentative code, with lots of assumption %CTF should use backpanel trigger backpanel = strcmp({event.type}, 'backpanel trigger'); if any(backpanel) fprintf('Writing the value of the backpanel trigger into the event file\n') trigger = [event(backpanel).value]; eve = zeros(numel(trigger), 3); eve(:,1) = [event(backpanel).sample]; eve(:,3) = [event(backpanel).value]; return end % use ev_type and ev_value ev_type = unique({event.type}); % convert to cell of strings if any(cellfun(@isnumeric, {event.value})) event_value = cellfun(@num2str, {event.value}, 'uni', false); else event_value = {event.value}; end ev_value = unique(event_value); eve = zeros(numel(event), 3); for i1 = 1:numel(ev_type) for i2 = 1:numel(ev_value) i_type = strcmp({event.type}, ev_type{i1}); i_value = strcmp(event_value, ev_value{i2}); marker = i1 * 10 + i2; if any(i_type & i_value) eve(i_type & i_value, 1) = [event(i_type & i_value).sample]; eve(i_type & i_value, 2) = marker; end end end % report event coding newev = unique(eve(:,2)); fprintf('EVENTS have been coded as:\n') for i = 1:numel(newev) i_type = floor(newev(i)/10); i_value = mod(newev(i), 10); fprintf('type: %s, value %s -> % 3d\n', ev_type{i_type}, ev_value{i_value}, newev(i)) end
github
lcnbeapp/beapp-master
ft_artifact_zvalue.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_artifact_zvalue.m
48,529
utf_8
d7f68586d26f9a1b0725e1f63f4b08ad
function [cfg, artifact] = ft_artifact_zvalue(cfg, data) % FT_ARTIFACT_ZVALUE reads the interesting segments of data from file and % identifies artifacts by means of thresholding the z-transformed value % of the preprocessed raw data. Depending on the preprocessing options, % this method will be sensitive to EOG, muscle or jump artifacts. % This procedure only works on continuously recorded data. % % Use as % [cfg, artifact] = ft_artifact_zvalue(cfg) % or % [cfg, artifact] = ft_artifact_zvalue(cfg, data) % % The output argument "artifact" is a Nx2 matrix comparable to the % "trl" matrix of FT_DEFINETRIAL. The first column of which specifying the % beginsamples of an artifact period, the second column contains the % endsamples of the artifactperiods. % % If you are calling FT_ARTIFACT_ZVALUE with only the configuration as first % input argument and the data still has to be read from file, you should % specify % cfg.dataset = string with the filename % or % cfg.headerfile = string with the filename % cfg.datafile = string with the filename % and optionally % cfg.headerformat % cfg.dataformat % % If you are calling FT_ARTIFACT_ZVALUE with also the second input argument % "data", then that should contain data that was already read from file % a call to FT_PREPROCESSING. % % If you encounter difficulties with memory usage, you can use % cfg.memory = 'low' or 'high', whether to be memory or computationally efficient, respectively (default = 'high') % % The required configuration settings are: % cfg.trl % cfg.continuous % cfg.artfctdef.zvalue.channel % cfg.artfctdef.zvalue.cutoff % cfg.artfctdef.zvalue.trlpadding % cfg.artfctdef.zvalue.fltpadding % cfg.artfctdef.zvalue.artpadding % % The optional configuration settings (see below) are: % cfg.artfctdef.zvalue.artfctpeak = 'yes' or 'no' % cfg.artfctdef.zvalue.interactive = 'yes' or 'no' % % If you specify artfctpeak='yes', the maximum value of the artifact within its range % will be found and saved into cfg.artfctdef.zvalue.peaks. % % If you specify interactive='yes', a GUI will be started and you can manually % accept/reject detected artifacts, and/or change the threshold. To control the % graphical interface via keyboard, use the following keys: % % q : Stop % % comma : Step to the previous artifact trial % a : Specify artifact trial to display % period : Step to the next artifact trial % % x : Step 10 trials back % leftarrow : Step to the previous trial % t : Specify trial to display % rightarrow : Step to the next trial % c : Step 10 trials forward % % k : Keep trial % space : Mark complete trial as artifact % r : Mark part of trial as artifact % % downarrow : Shift the z-threshold down % z : Specify the z-threshold % uparrow : Shift the z-threshold down % % Use also, e.g. as input to DSS option of ft_componentanalysis % cfg.artfctdef.zvalue.artfctpeakrange=[-0.25 0.25], for example to indicate range % around peak to include, saved into cfg.artfctdef.zvalue.dssartifact. The default is % [0 0]. Range will respect trial boundaries (i.e. be shorter if peak is near % beginning or end of trial). Samples between trials will be removed; thus this won't % match .sampleinfo of the data structure. % % Configuration settings related to the preprocessing of the data are % cfg.artfctdef.zvalue.lpfilter = 'no' or 'yes' lowpass filter % cfg.artfctdef.zvalue.hpfilter = 'no' or 'yes' highpass filter % cfg.artfctdef.zvalue.bpfilter = 'no' or 'yes' bandpass filter % cfg.artfctdef.zvalue.bsfilter = 'no' or 'yes' bandstop filter for line noise removal % cfg.artfctdef.zvalue.dftfilter = 'no' or 'yes' line noise removal using discrete fourier transform % cfg.artfctdef.zvalue.medianfilter = 'no' or 'yes' jump preserving median filter % cfg.artfctdef.zvalue.lpfreq = lowpass frequency in Hz % cfg.artfctdef.zvalue.hpfreq = highpass frequency in Hz % cfg.artfctdef.zvalue.bpfreq = bandpass frequency range, specified as [low high] in Hz % cfg.artfctdef.zvalue.bsfreq = bandstop frequency range, specified as [low high] in Hz % cfg.artfctdef.zvalue.lpfiltord = lowpass filter order % cfg.artfctdef.zvalue.hpfiltord = highpass filter order % cfg.artfctdef.zvalue.bpfiltord = bandpass filter order % cfg.artfctdef.zvalue.bsfiltord = bandstop filter order % cfg.artfctdef.zvalue.medianfiltord = length of median filter % cfg.artfctdef.zvalue.lpfilttype = digital filter type, 'but' (default) or 'firws' or 'fir' or 'firls' % cfg.artfctdef.zvalue.hpfilttype = digital filter type, 'but' (default) or 'firws' or 'fir' or 'firls' % cfg.artfctdef.zvalue.bpfilttype = digital filter type, 'but' (default) or 'firws' or 'fir' or 'firls' % cfg.artfctdef.zvalue.bsfilttype = digital filter type, 'but' (default) or 'firws' or 'fir' or 'firls' % cfg.artfctdef.zvalue.detrend = 'no' or 'yes' % cfg.artfctdef.zvalue.demean = 'no' or 'yes' % cfg.artfctdef.zvalue.baselinewindow = [begin end] in seconds, the default is the complete trial % cfg.artfctdef.zvalue.hilbert = 'no' or 'yes' % cfg.artfctdef.zvalue.rectify = 'no' or 'yes' % % See also FT_REJECTARTIFACT, FT_ARTIFACT_CLIP, FT_ARTIFACT_ECG, FT_ARTIFACT_EOG, % FT_ARTIFACT_JUMP, FT_ARTIFACT_MUSCLE, FT_ARTIFACT_THRESHOLD, FT_ARTIFACT_ZVALUE % Copyright (C) 2003-2011, Jan-Mathijs Schoffelen & Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble provenance ft_preamble loadvar data % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % set default rejection parameters cfg.headerformat = ft_getopt(cfg, 'headerformat', []); cfg.dataformat = ft_getopt(cfg, 'dataformat', []); cfg.memory = ft_getopt(cfg, 'memory', 'high'); cfg.artfctdef = ft_getopt(cfg, 'artfctdef', []); cfg.artfctdef.zvalue = ft_getopt(cfg.artfctdef, 'zvalue', []); cfg.artfctdef.zvalue.method = ft_getopt(cfg.artfctdef.zvalue, 'method', 'all'); cfg.artfctdef.zvalue.ntrial = ft_getopt(cfg.artfctdef.zvalue, 'ntrial', 10); cfg.artfctdef.zvalue.channel = ft_getopt(cfg.artfctdef.zvalue, 'channel', {}); cfg.artfctdef.zvalue.trlpadding = ft_getopt(cfg.artfctdef.zvalue, 'trlpadding', 0); cfg.artfctdef.zvalue.fltpadding = ft_getopt(cfg.artfctdef.zvalue, 'fltpadding', 0); cfg.artfctdef.zvalue.artpadding = ft_getopt(cfg.artfctdef.zvalue, 'artpadding', 0); cfg.artfctdef.zvalue.interactive = ft_getopt(cfg.artfctdef.zvalue, 'interactive', 'no'); cfg.artfctdef.zvalue.cumulative = ft_getopt(cfg.artfctdef.zvalue, 'cumulative', 'yes'); cfg.artfctdef.zvalue.artfctpeak = ft_getopt(cfg.artfctdef.zvalue, 'artfctpeak', 'no'); cfg.artfctdef.zvalue.artfctpeakrange = ft_getopt(cfg.artfctdef.zvalue, 'artfctpeakrange',[0 0]); % for backward compatibility cfg.artfctdef = ft_checkconfig(cfg.artfctdef, 'renamed', {'blc', 'demean'}); cfg.artfctdef = ft_checkconfig(cfg.artfctdef, 'renamed', {'blcwindow' 'baselinewindow'}); cfg.artfctdef.zvalue = ft_checkconfig(cfg.artfctdef.zvalue, 'renamed', {'sgn', 'channel'}); cfg.artfctdef.zvalue = ft_checkconfig(cfg.artfctdef.zvalue, 'renamed', {'feedback', 'interactive'}); if isfield(cfg.artfctdef.zvalue, 'artifact') fprintf('zvalue artifact detection has already been done, retaining artifacts\n'); artifact = cfg.artfctdef.zvalue.artifact; return end % set feedback cfg.feedback = ft_getopt(cfg, 'feedback', 'text'); % clear old warnings from this stack ft_warning('-clear') % flag whether to compute z-value per trial or not, rationale being that if % there are fluctuations in the variance across trials (e.g. due to % position differences in MEG measurements) which don't have to do with the artifact per se, % the detection is compromised (although the data quality is questionable % when there is a lot of movement to begin with). pertrial = strcmp(cfg.artfctdef.zvalue.method, 'trial'); demeantrial = strcmp(cfg.artfctdef.zvalue.method, 'trialdemean'); if pertrial if isfield(cfg.artfctdef.zvalue, 'ntrial') && cfg.artfctdef.zvalue.ntrial>0 pertrial = cfg.artfctdef.zvalue.ntrial; else error('you should specify cfg.artfctdef.zvalue.ntrial, and it should be > 0'); end end % the data can be passed as input arguments or can be read from disk hasdata = exist('data', 'var'); if ~hasdata % only cfg given, read data from disk cfg = ft_checkconfig(cfg, 'dataset2files', 'yes'); hdr = ft_read_header(cfg.headerfile, 'headerformat', cfg.headerformat); trl = cfg.trl; else % check whether the value for trlpadding makes sense if cfg.artfctdef.zvalue.trlpadding > 0 % negative trlpadding is allowed with in-memory data error('you cannot use positive trlpadding with in-memory data'); end % check if the input data is valid for this function data = ft_checkdata(data, 'datatype', 'raw', 'hassampleinfo', 'yes'); cfg = ft_checkconfig(cfg, 'forbidden', {'dataset', 'headerfile', 'datafile'}); hdr = ft_fetch_header(data); trl = data.sampleinfo; end % set default cfg.continuous if ~isfield(cfg, 'continuous') if hdr.nTrials==1 cfg.continuous = 'yes'; else cfg.continuous = 'no'; end end trlpadding = round(cfg.artfctdef.zvalue.trlpadding*hdr.Fs); fltpadding = round(cfg.artfctdef.zvalue.fltpadding*hdr.Fs); artpadding = round(cfg.artfctdef.zvalue.artpadding*hdr.Fs); trl(:,1) = trl(:,1) - trlpadding; % pad the trial with some samples, in order to detect trl(:,2) = trl(:,2) + trlpadding; % artifacts at the edges of the relevant trials. if size(trl, 2) >= 3 trl(:,3) = trl(:,3) - trlpadding; % the offset can ofcourse be adjusted as well elseif hasdata % reconstruct offset for tr=1:size(trl, 1) % account for 0 might not be in data.time t0 = interp1(data.time{tr}, 1:numel(data.time{tr}), 0, 'linear', 'extrap'); trl(tr, 3) = -t0+1 - trlpadding; end else % assuming that the trial starts at t=0s trl(:, 3) = trl(:, 1); end trllength = trl(:,2) - trl(:,1) + 1; % length of each trial numtrl = size(trl,1); cfg.artfctdef.zvalue.trl = trl; % remember where we are going to look for artifacts cfg.artfctdef.zvalue.channel = ft_channelselection(cfg.artfctdef.zvalue.channel, hdr.label); sgnind = match_str(hdr.label, cfg.artfctdef.zvalue.channel); numsgn = length(sgnind); thresholdsum = strcmp(cfg.artfctdef.zvalue.cumulative, 'yes'); if numsgn<1 error('no channels selected'); end % read the data and apply preprocessing options sumval = zeros(numsgn, 1); sumsqr = zeros(numsgn, 1); numsmp = zeros(numsgn, 1); ft_progress('init', cfg.feedback, ['searching for artifacts in ' num2str(numsgn) ' channels']); for trlop = 1:numtrl ft_progress(trlop/numtrl, 'searching in trial %d from %d\n', trlop, numtrl); if strcmp(cfg.memory, 'low') % store nothing in memory if hasdata dat = ft_fetch_data(data, 'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no'), 'skipcheckdata', 1); else dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no'), 'dataformat', cfg.dataformat); end dat = preproc(dat, cfg.artfctdef.zvalue.channel, offset2time(0, hdr.Fs, size(dat,2)), cfg.artfctdef.zvalue, fltpadding, fltpadding); if trlop==1 && ~pertrial sumval = zeros(size(dat,1), 1); sumsqr = zeros(size(dat,1), 1); numsmp = zeros(size(dat,1), 1); numsgn = size(dat,1); elseif trlop==1 && pertrial sumval = zeros(size(dat,1), numtrl); sumsqr = zeros(size(dat,1), numtrl); numsmp = zeros(size(dat,1), numtrl); numsgn = size(dat,1); end if ~pertrial % accumulate the sum and the sum-of-squares sumval = sumval + sum(dat,2); sumsqr = sumsqr + sum(dat.^2,2); numsmp = numsmp + size(dat,2); else % store per trial the sum and the sum-of-squares sumval(:,trlop) = sum(dat,2); sumsqr(:,trlop) = sum(dat.^2,2); numsmp(:,trlop) = size(dat,2); end else % store all data in memory, saves computation time if hasdata dat{trlop} = ft_fetch_data(data, 'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no'), 'skipcheckdata', 1); else dat{trlop} = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no'), 'dataformat', cfg.dataformat); end dat{trlop} = preproc(dat{trlop}, cfg.artfctdef.zvalue.channel, offset2time(0, hdr.Fs, size(dat{trlop},2)), cfg.artfctdef.zvalue, fltpadding, fltpadding); if trlop==1 && ~pertrial sumval = zeros(size(dat{1},1), 1); sumsqr = zeros(size(dat{1},1), 1); numsmp = zeros(size(dat{1},1), 1); numsgn = size(dat{1},1); elseif trlop==1 && pertrial sumval = zeros(size(dat{1},1), numtrl); sumsqr = zeros(size(dat{1},1), numtrl); numsmp = zeros(size(dat{1},1), numtrl); numsgn = size(dat{1},1); end if ~pertrial % accumulate the sum and the sum-of-squares sumval = sumval + sum(dat{trlop},2); sumsqr = sumsqr + sum(dat{trlop}.^2,2); numsmp = numsmp + size(dat{trlop},2); else % store per trial the sum and the sum-of-squares sumval(:,trlop) = sum(dat{trlop},2); sumsqr(:,trlop) = sum(dat{trlop}.^2,2); numsmp(:,trlop) = size(dat{trlop},2); end end end % for trlop ft_progress('close'); if pertrial>1 sumval = ft_preproc_smooth(sumval, pertrial)*pertrial; sumsqr = ft_preproc_smooth(sumsqr, pertrial)*pertrial; numsmp = ft_preproc_smooth(numsmp, pertrial)*pertrial; end % compute the average and the standard deviation datavg = sumval./numsmp; datstd = sqrt(sumsqr./numsmp - (sumval./numsmp).^2); if strcmp(cfg.memory, 'low') fprintf('\n'); end zmax = cell(1, numtrl); zsum = cell(1, numtrl); zindx = cell(1, numtrl); % create a vector that indexes the trials, or is all 1, in order % to a per trial z-scoring, or use a static std and mean (used in lines 317 % and 328) if pertrial indvec = 1:numtrl; else indvec = ones(1,numtrl); end for trlop = 1:numtrl if strcmp(cfg.memory, 'low') % store nothing in memory (note that we need to preproc AGAIN... *yawn* fprintf('.'); if hasdata dat = ft_fetch_data(data, 'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no')); else dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no'), 'dataformat', cfg.dataformat); end dat = preproc(dat, cfg.artfctdef.zvalue.channel, offset2time(0, hdr.Fs, size(dat,2)), cfg.artfctdef.zvalue, fltpadding, fltpadding); zmax{trlop} = -inf + zeros(1,size(dat,2)); zsum{trlop} = zeros(1,size(dat,2)); zindx{trlop} = zeros(1,size(dat,2)); nsmp = size(dat,2); zdata = (dat - datavg(:,indvec(trlop)*ones(1,nsmp)))./datstd(:,indvec(trlop)*ones(1,nsmp)); % convert the filtered data to z-values zsum{trlop} = nansum(zdata,1); % accumulate the z-values over channels [zmax{trlop},ind] = max(zdata,[],1); % find the maximum z-value and remember it zindx{trlop} = sgnind(ind); % also remember the channel number that has the largest z-value else % initialize some matrices zmax{trlop} = -inf + zeros(1,size(dat{trlop},2)); zsum{trlop} = zeros(1,size(dat{trlop},2)); zindx{trlop} = zeros(1,size(dat{trlop},2)); nsmp = size(dat{trlop},2); zdata = (dat{trlop} - datavg(:,indvec(trlop)*ones(1,nsmp)))./datstd(:,indvec(trlop)*ones(1,nsmp)); % convert the filtered data to z-values zsum{trlop} = nansum(zdata,1); % accumulate the z-values over channels [zmax{trlop},ind] = max(zdata,[],1); % find the maximum z-value and remember it zindx{trlop} = sgnind(ind); % also remember the channel number that has the largest z-value end % This alternative code does the same, but it is much slower % for i=1:size(zmax{trlop},2) % if zdata{trlop}(i)>zmax{trlop}(i) % % update the maximum value and channel index % zmax{trlop}(i) = zdata{trlop}(i); % zindx{trlop}(i) = sgnind(sgnlop); % end % end end % for trlop if demeantrial for trlop = 1:numtrl zmax{trlop} = zmax{trlop}-mean(zmax{trlop},2); zsum{trlop} = zsum{trlop}-mean(zsum{trlop},2); end end %for sgnlop=1:numsgn % % read the data and apply preprocessing options % sumval = 0; % sumsqr = 0; % numsmp = 0; % fprintf('searching channel %s ', cfg.artfctdef.zvalue.channel{sgnlop}); % for trlop = 1:numtrl % fprintf('.'); % if hasdata % dat{trlop} = ft_fetch_data(data, 'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', sgnind(sgnlop), 'checkboundary', strcmp(cfg.continuous,'no')); % else % dat{trlop} = read_data(cfg.datafile, 'header', hdr, 'begsample', trl(trlop,1)-fltpadding, 'endsample', trl(trlop,2)+fltpadding, 'chanindx', sgnind(sgnlop), 'checkboundary', strcmp(cfg.continuous,'no')); % end % dat{trlop} = preproc(dat{trlop}, cfg.artfctdef.zvalue.channel(sgnlop), hdr.Fs, cfg.artfctdef.zvalue, [], fltpadding, fltpadding); % % accumulate the sum and the sum-of-squares % sumval = sumval + sum(dat{trlop},2); % sumsqr = sumsqr + sum(dat{trlop}.^2,2); % numsmp = numsmp + size(dat{trlop},2); % end % for trlop % % % compute the average and the standard deviation % datavg = sumval./numsmp; % datstd = sqrt(sumsqr./numsmp - (sumval./numsmp).^2); % % for trlop = 1:numtrl % if sgnlop==1 % % initialize some matrices % zdata{trlop} = zeros(size(dat{trlop})); % zmax{trlop} = -inf + zeros(size(dat{trlop})); % zsum{trlop} = zeros(size(dat{trlop})); % zindx{trlop} = zeros(size(dat{trlop})); % end % zdata{trlop} = (dat{trlop} - datavg)./datstd; % convert the filtered data to z-values % zsum{trlop} = zsum{trlop} + zdata{trlop}; % accumulate the z-values over channels % zmax{trlop} = max(zmax{trlop}, zdata{trlop}); % find the maximum z-value and remember it % zindx{trlop}(zmax{trlop}==zdata{trlop}) = sgnind(sgnlop); % also remember the channel number that has the largest z-value % % % This alternative code does the same, but it is much slower % % for i=1:size(zmax{trlop},2) % % if zdata{trlop}(i)>zmax{trlop}(i) % % % update the maximum value and channel index % % zmax{trlop}(i) = zdata{trlop}(i); % % zindx{trlop}(i) = sgnind(sgnlop); % % end % % end % end % fprintf('\n'); %end % for sgnlop for trlop = 1:numtrl zsum{trlop} = zsum{trlop} ./ sqrt(numsgn); end % always create figure % keypress to enable keyboard uicontrol h = figure('KeyPressFcn', @keyboard_cb); set(h, 'visible', 'off'); opt.artcfg = cfg.artfctdef.zvalue; opt.artval = {}; opt.artpadding = artpadding; opt.cfg = cfg; opt.channel = 'artifact'; opt.hdr = hdr; opt.numtrl = size(trl,1); opt.quit = 0; opt.threshold = cfg.artfctdef.zvalue.cutoff; opt.thresholdsum = thresholdsum; opt.trialok = true(1,opt.numtrl); % OK by means of objective criterion opt.keep = zeros(1,opt.numtrl); % OK overruled by user +1 to keep, -1 to reject, start all zeros for callback to work opt.trl = trl; opt.trlop = 1; opt.updatethreshold = true; opt.zmax = zmax; opt.zsum = zsum; if ~thresholdsum opt.zval = zmax; else opt.zval = zsum; end opt.zindx = zindx; if ~hasdata opt.data = {}; else opt.data = data; end if strcmp(cfg.artfctdef.zvalue.interactive, 'yes') set(h, 'visible', 'on'); set(h, 'CloseRequestFcn', @cleanup_cb); % give graphical feedback and allow the user to modify the threshold set(h, 'position', [100 200 900 400]); h1 = axes('position', [0.05 0.15 0.4 0.8]); h2 = axes('position', [0.5 0.57 0.45 0.38]); h3 = axes('position', [0.5 0.15 0.45 0.32]); opt.h1 = h1; opt.h2 = h2; opt.h3 = h3; setappdata(h, 'opt', opt); artval_cb(h); redraw_cb(h); % make the user interface elements for the data view, the order of the elements % here is from left to right and should match the order in the documentation uicontrol('tag', 'width1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'stop', 'userdata', 'q'); uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'comma'); uicontrol('tag', 'width1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'artifact', 'userdata', 'a'); uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'period'); uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<<', 'userdata', 'x'); uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'leftarrow'); uicontrol('tag', 'width1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'trial', 'userdata', 't'); uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'rightarrow'); uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>>', 'userdata', 'c'); uicontrol('tag', 'width3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'keep trial', 'userdata', 'k'); uicontrol('tag', 'width3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'reject full', 'userdata', 'space'); uicontrol('tag', 'width3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'reject part', 'userdata', 'r'); uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'downarrow'); uicontrol('tag', 'width3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'threshold', 'userdata', 'z'); uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'uparrow'); %uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'control+uparrow') %uicontrol('tag', 'width1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'channel', 'userdata', 'c') %uicontrol('tag', 'width2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'control+downarrow') ft_uilayout(h, 'tag', 'width1', 'width', 0.10, 'height', 0.05); ft_uilayout(h, 'tag', 'width2', 'width', 0.05, 'height', 0.05); ft_uilayout(h, 'tag', 'width3', 'width', 0.12, 'height', 0.05); ft_uilayout(h, 'tag', 'width1', 'style', 'pushbutton', 'callback', @keyboard_cb); ft_uilayout(h, 'tag', 'width2', 'style', 'pushbutton', 'callback', @keyboard_cb); ft_uilayout(h, 'tag', 'width3', 'style', 'pushbutton', 'callback', @keyboard_cb); ft_uilayout(h, 'tag', 'width1', 'retag', 'viewui'); ft_uilayout(h, 'tag', 'width2', 'retag', 'viewui'); ft_uilayout(h, 'tag', 'width3', 'retag', 'viewui'); ft_uilayout(h, 'tag', 'viewui', 'BackgroundColor', [0.8 0.8 0.8], 'hpos', 'auto', 'vpos', 0.005); while opt.quit==0 uiwait(h); opt = getappdata(h, 'opt'); end else % compute the artifacts given the settings in the cfg setappdata(h, 'opt', opt); artval_cb(h); end h = getparent(h); opt = getappdata(h, 'opt'); % convert to one long vector dum = zeros(1,max(opt.trl(:,2))); for trlop=1:opt.numtrl dum(opt.trl(trlop,1):opt.trl(trlop,2)) = opt.artval{trlop}; end artval = dum; % find the padded artifacts and put them in a Nx2 trl-like matrix artbeg = find(diff([0 artval])== 1); artend = find(diff([artval 0])==-1); artifact = [artbeg(:) artend(:)]; if strcmp(cfg.artfctdef.zvalue.artfctpeak,'yes') cnt=1; shift=opt.trl(1,1)-1; for tt=1:opt.numtrl if tt==1 tind{tt}=find(artifact(:,2)<opt.trl(tt,2)); else tind{tt}=intersect(find(artifact(:,2)<opt.trl(tt,2)),find(artifact(:,2)>opt.trl(tt-1,2))); end artbegend=[(artifact(tind{tt},1)-opt.trl(tt,1)+1) (artifact(tind{tt},2)-opt.trl(tt,1)+1)]; for rr=1:size(artbegend,1) [mx,mxnd]=max(opt.zval{tt}(artbegend(rr,1):artbegend(rr,2))); peaks(cnt)=artifact(tind{tt}(rr),1)+mxnd-1; dssartifact(cnt,1)=max(peaks(cnt)+cfg.artfctdef.zvalue.artfctpeakrange(1)*hdr.Fs,opt.trl(tt,1)); dssartifact(cnt,2)=min(peaks(cnt)+cfg.artfctdef.zvalue.artfctpeakrange(2)*hdr.Fs,opt.trl(tt,2)); peaks(cnt)=peaks(cnt)-shift; dssartifact(cnt,:)=dssartifact(cnt,:)-shift; cnt=cnt+1; end if tt<opt.numtrl shift=shift+opt.trl(tt+1,1)-opt.trl(tt,2)-1; end clear artbegend end cfg.artfctdef.zvalue.peaks=peaks'; cfg.artfctdef.zvalue.dssartifact=dssartifact; end % remember the artifacts that were found cfg.artfctdef.zvalue.artifact = artifact; % also update the threshold cfg.artfctdef.zvalue.cutoff = opt.threshold; fprintf('detected %d artifacts\n', size(artifact,1)); delete(h); % do the general cleanup and bookkeeping at the end of the function ft_postamble provenance ft_postamble previous data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function artval_cb(h, eventdata) opt = getappdata(h, 'opt'); artval = cell(1,opt.numtrl); for trlop=1:opt.numtrl if opt.thresholdsum, % threshold the accumulated z-values artval{trlop} = opt.zsum{trlop}>opt.threshold; else % threshold the max z-values artval{trlop} = opt.zmax{trlop}>opt.threshold; end % pad the artifacts artbeg = find(diff([0 artval{trlop}])== 1); artend = find(diff([artval{trlop} 0])==-1); artbeg = artbeg - opt.artpadding; artend = artend + opt.artpadding; artbeg(artbeg<1) = 1; artend(artend>length(artval{trlop})) = length(artval{trlop}); for artlop=1:length(artbeg) artval{trlop}(artbeg(artlop):artend(artlop)) = 1; end opt.trialok(trlop) = isempty(artbeg); end for trlop = find(opt.keep==1 & opt.trialok==0) % overrule the objective criterion, i.e. keep the trial when the user % wants to keep it artval{trlop}(:) = 0; end for trlop = find(opt.keep<0 & opt.trialok==1) % if the user specifies that the trial is not OK % reject the whole trial if there is no extra-threshold data, % otherwise use the artifact as found by the thresholding if opt.thresholdsum && opt.keep(trlop)==-1, % threshold the accumulated z-values artval{trlop} = opt.zsum{trlop}>opt.threshold; elseif opt.keep(trlop)==-1 % threshold the max z-values artval{trlop} = opt.zmax{trlop}>opt.threshold; elseif opt.keep(trlop)==-2 artval{trlop}(:) = 1; end % pad the artifacts artbeg = find(diff([0 artval{trlop}])== 1); artend = find(diff([artval{trlop} 0])==-1); artbeg = artbeg - opt.artpadding; artend = artend + opt.artpadding; artbeg(artbeg<1) = 1; artend(artend>length(artval{trlop})) = length(artval{trlop}); if ~isempty(artbeg) for artlop=1:length(artbeg) artval{trlop}(artbeg(artlop):artend(artlop)) = 1; end else artval{trlop}(:) = 1; end end for trlop = find(opt.keep==-2 & opt.trialok==0) % if the user specifies the whole trial to be rejected define the whole % segment to be bad artval{trlop}(:) = 1; % pad the artifacts artbeg = find(diff([0 artval{trlop}])== 1); artend = find(diff([artval{trlop} 0])==-1); artbeg = artbeg - opt.artpadding; artend = artend + opt.artpadding; artbeg(artbeg<1) = 1; artend(artend>length(artval{trlop})) = length(artval{trlop}); if ~isempty(artbeg) for artlop=1:length(artbeg) artval{trlop}(artbeg(artlop):artend(artlop)) = 1; end else artval{trlop}(:) = 1; end end opt.artval = artval; setappdata(h, 'opt', opt); uiresume; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function keyboard_cb(h, eventdata) % If a mouseclick was made, use that value. If not, determine the key that % corresponds to the uicontrol element that was activated. if isa(eventdata,'matlab.ui.eventdata.ActionData') % only the case when clicked with mouse curKey = get(h, 'userdata'); elseif isa(eventdata, 'matlab.ui.eventdata.KeyData') % only when key was pressed if isempty(eventdata.Character) && any(strcmp(eventdata.Key, {'control', 'shift', 'alt', '0'})) % only a modifier key was pressed return end if isempty(eventdata.Modifier) curKey = eventdata.Key; else curKey = [sprintf('%s+', eventdata.Modifier{:}) eventdata.Key]; end elseif isfield(eventdata, 'Key') % only when key was pressed curKey = eventdata.Key; elseif isempty(eventdata) % matlab2012b returns an empty double upon a mouse click curKey = get(h, 'userdata'); else error('cannot process user input, please report this on http://bugzilla.fieldtriptoolbox.org including your MATLAB version'); end h = getparent(h); % otherwise h is empty if isa [...].ActionData opt = getappdata(h, 'opt'); disp(strcat('Key = ', curKey)) switch strtrim(curKey) case 'leftarrow' % change trials opt.trlop = max(opt.trlop - 1, 1); % should not be smaller than 1 setappdata(h, 'opt', opt); redraw_cb(h, eventdata); case 'x' opt.trlop = max(opt.trlop - 10, 1); % should not be smaller than 1 setappdata(h, 'opt', opt); redraw_cb(h, eventdata); case 'rightarrow' opt.trlop = min(opt.trlop + 1, opt.numtrl); % should not be larger than the number of trials setappdata(h, 'opt', opt); redraw_cb(h, eventdata); case 'c' opt.trlop = min(opt.trlop + 10, opt.numtrl); % should not be larger than the number of trials setappdata(h, 'opt', opt); redraw_cb(h, eventdata); case 'uparrow' % change threshold opt.threshold = opt.threshold+0.5; opt.updatethreshold = true; setappdata(h, 'opt', opt); artval_cb(h, eventdata); redraw_cb(h, eventdata); opt = getappdata(h, 'opt'); % grab the opt-structure from the handle because it has been adjusted in the callbacks opt.updatethreshold = false; setappdata(h, 'opt', opt); case 'downarrow' opt.threshold = opt.threshold-0.5; opt.updatethreshold = true; setappdata(h, 'opt', opt); artval_cb(h, eventdata); redraw_cb(h, eventdata); opt = getappdata(h, 'opt'); % grab the opt-structure from the handle because it has been adjusted in the callbacks opt.updatethreshold = false; setappdata(h, 'opt', opt); case 'period' % change artifact artfctindx = find(opt.trialok == 0); sel = find(artfctindx>opt.trlop); if ~isempty(sel) opt.trlop = artfctindx(sel(1)); end setappdata(h, 'opt', opt); redraw_cb(h, eventdata); case 'comma' artfctindx = find(opt.trialok == 0); sel = find(artfctindx<opt.trlop); if ~isempty(sel) opt.trlop = artfctindx(sel(end)); end setappdata(h, 'opt', opt); redraw_cb(h, eventdata); % case 'control+uparrow' % change channel % if strcmp(opt.channel, 'artifact') % [dum, indx] = max(opt.zval); % sgnind = opt.zindx(indx); % else % if ~isempty(opt.data) % sgnind = match_str(opt.channel, opt.data.label); % selchan = match_str(opt.artcfg.channel, opt.channel); % else % sgnind = match_str(opt.channel, opt.hdr.label); % selchan = match_str(opt.artcfg.channel, opt.channel); % end % end % numchan = numel(opt.artcfg.channel); % chansel = min(selchan+1, numchan); % % convert numeric array into cell-array with channel labels % opt.channel = tmpchan(chansel); % setappdata(h, 'opt', opt); % redraw_cb(h, eventdata); % case 'c' % select channel % select = match_str([opt.artcfg.channel;{'artifact'}], opt.channel); % opt.channel = select_channel_list([opt.artcfg.channel;{'artifact'}], select); % setappdata(h, 'opt', opt); % redraw_cb(h, eventdata); % case 'control+downarrow' % tmpchan = [opt.artcfg.channel;{'artifact'}]; % append the 'artifact' channel % chansel = match_str(tmpchan, opt.channel); % chansel = max(chansel-1, 1); % % convert numeric array into cell-array with channel labels % opt.channel = tmpchan(chansel); % setappdata(h, 'opt', opt); % redraw_cb(h, eventdata); case 'a' % select the artifact to display response = inputdlg(sprintf('artifact trial to display'), 'specify', 1, {num2str(opt.trlop)}); if ~isempty(response) artfctindx = find(opt.trialok == 0); sel = str2double(response); sel = min(numel(artfctindx), sel); sel = max(1, sel); opt.trlop = artfctindx(sel); setappdata(h, 'opt', opt); redraw_cb(h, eventdata); end case 'q' setappdata(h, 'opt', opt); cleanup_cb(h); case 't' % select the trial to display response = inputdlg(sprintf('trial to display'), 'specify', 1, {num2str(opt.trlop)}); if ~isempty(response) opt.trlop = str2double(response); opt.trlop = min(opt.trlop, opt.numtrl); % should not be larger than the number of trials opt.trlop = max(opt.trlop, 1); % should not be smaller than 1 setappdata(h, 'opt', opt); redraw_cb(h, eventdata); end case 'z' % select the threshold response = inputdlg('z-threshold', 'specify', 1, {num2str(opt.threshold)}); if ~isempty(response) opt.threshold = str2double(response); opt.updatethreshold = true; setappdata(h, 'opt', opt); artval_cb(h, eventdata); redraw_cb(h, eventdata); opt = getappdata(h, 'opt'); % grab the opt-structure from the handle because it has been adjusted in the callbacks opt.updatethreshold = false; setappdata(h, 'opt', opt); end case 'k' opt.keep(opt.trlop) = 1; setappdata(h, 'opt', opt); artval_cb(h); redraw_cb(h); case 'r' % only of the trial contains a partial artifact if opt.trialok(opt.trlop) == 0 opt.keep(opt.trlop) = -1; end setappdata(h, 'opt', opt); artval_cb(h); redraw_cb(h); case 'space' opt.keep(opt.trlop) = -2; setappdata(h, 'opt', opt); artval_cb(h); redraw_cb(h); case 'control+control' % do nothing case 'shift+shift' % do nothing case 'alt+alt' % do nothing otherwise setappdata(h, 'opt', opt); % this should be consistent with the help of the function fprintf('----------------------------------------------------------------------\n'); fprintf(' q : Stop\n'); fprintf('\n'); fprintf(' comma : Step to the previous artifact trial\n'); fprintf(' a : Specify artifact trial to display\n'); fprintf(' period : Step to the next artifact trial\n'); fprintf('\n'); fprintf(' x : Step 10 trials back\n'); fprintf(' leftarrow : Step to the previous trial\n'); fprintf(' t : Specify trial to display\n'); fprintf(' rightarrow : Step to the next trial\n'); fprintf(' c : Step 10 trials forward\n'); fprintf('\n'); fprintf(' k : Keep trial\n'); fprintf(' space : Mark complete trial as artifact\n'); fprintf(' r : Mark part of trial as artifact\n'); fprintf('\n'); fprintf(' downarrow : Shift the z-threshold down\n'); fprintf(' z : Specify the z-threshold\n'); fprintf(' uparrow : Shift the z-threshold down\n'); fprintf('----------------------------------------------------------------------\n'); end clear curKey; uiresume(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function redraw_cb(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); % make a local copy of the relevant variables trlop = opt.trlop; artval = opt.artval{trlop}; zindx = opt.zindx{trlop}; zval = opt.zval{trlop}; cfg = opt.cfg; artcfg = opt.artcfg; hdr = opt.hdr; trl = opt.trl; trlpadsmp = round(artcfg.trlpadding*hdr.Fs); channel = opt.channel; % determine the channel with the highest z-value to be displayed % this is default behaviour but can be overruled in the gui if strcmp(channel, 'artifact') [dum, indx] = max(zval); sgnind = zindx(indx); else if ~isempty(opt.data) sgnind = match_str(channel, opt.data.label); else sgnind = match_str(channel, hdr.label); end end if ~isempty(opt.data) data = ft_fetch_data(opt.data, 'header', hdr, 'begsample', trl(trlop,1), 'endsample', trl(trlop,2), 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no')); else data = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', trl(trlop,1), 'endsample', trl(trlop,2), 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no')); end %data = preproc(data, '', hdr.Fs, artcfg, [], artcfg.fltpadding, artcfg.fltpadding); str = sprintf('trial %3d, channel %s', opt.trlop, hdr.label{sgnind}); fprintf('showing %s\n', str); %----------------------------- % plot summary in left subplot subplot(opt.h1);hold on; % plot as a blue line only once if isempty(get(opt.h1, 'children')) for k = 1:opt.numtrl xval = opt.trl(k,1):opt.trl(k,2); if opt.thresholdsum, yval = opt.zsum{k}; else yval = opt.zmax{k}; end plot(opt.h1, xval, yval, 'linestyle', '-', 'color', 'b', 'displayname', 'data'); xlabel('samples'); ylabel('z-value'); end end h1children = get(opt.h1, 'children'); % plot trial box boxhandle = findall(h1children, 'displayname', 'highlight'); if isempty(boxhandle) % draw it xval = trl(opt.trlop,1):trl(opt.trlop,2); if opt.thresholdsum, yval = opt.zsum{opt.trlop}; else yval = opt.zmax{opt.trlop}; end plot(opt.h1, xval, yval, 'linestyle', '-', 'color', 'm', 'linewidth', 2, 'displayname', 'highlight'); else % update it xval = trl(opt.trlop,1):trl(opt.trlop,2); if opt.thresholdsum, yval = opt.zsum{opt.trlop}; else yval = opt.zmax{opt.trlop}; end set(boxhandle, 'XData', xval); set(boxhandle, 'YData', yval); end % plot as red lines the suprathreshold data points thrhandle = findall(h1children, 'displayname', 'reddata'); if isempty(thrhandle) % they have to be drawn for k = 1:opt.numtrl xval = trl(k,1):trl(k,2); if opt.thresholdsum, yval = opt.zsum{k}; else yval = opt.zmax{k}; end dum = yval<=opt.threshold; yval(dum) = nan; plot(opt.h1, xval, yval, 'linestyle', '-', 'color', [1 0 0], 'displayname', 'reddata'); end hline(opt.threshold, 'color', 'r', 'linestyle', ':', 'displayname', 'threshline'); elseif ~isempty(thrhandle) && opt.updatethreshold % they can be updated for k = 1:opt.numtrl xval = trl(k,1):trl(k,2); if opt.thresholdsum, yval = opt.zsum{k}; else yval = opt.zmax{k}; end dum = yval<=opt.threshold; yval(dum) = nan; set(thrhandle(k), 'XData', xval); set(thrhandle(k), 'YData', yval); end set(findall(h1children, 'displayname', 'threshline'), 'YData', [1 1].*opt.threshold); end %-------------------------------------------------- % get trial specific x-axis values and padding info xval = ((trl(opt.trlop,1):trl(opt.trlop,2))-trl(opt.trlop,1)+trl(opt.trlop,3))./opt.hdr.Fs; if trlpadsmp>0 sel = trlpadsmp:(size(data,2)-trlpadsmp); selpad = 1:size(data,2); else sel = 1:size(data,2); selpad = sel; end % plot data of most aberrant channel in upper subplot subplot(opt.h2); hold on if isempty(get(opt.h2, 'children')) % do the plotting plot(xval(selpad), data(selpad), 'color', [0.5 0.5 1], 'displayname', 'line1'); plot(xval(sel), data(sel), 'color', [0 0 1], 'displayname', 'line2'); vline(xval( 1)+(trlpadsmp-1/opt.hdr.Fs), 'color', [0 0 0], 'displayname', 'vline1'); vline(xval(end)-(trlpadsmp/opt.hdr.Fs), 'color', [0 0 0], 'displayname', 'vline2'); data(~artval) = nan; plot(xval, data, 'r-', 'displayname', 'line3'); xlabel('time(s)'); ylabel('uV or Tesla'); xlim([xval(1) xval(end)]); title(str); else % update in the existing handles h2children = get(opt.h2, 'children'); set(findall(h2children, 'displayname', 'vline1'), 'visible', 'off'); set(findall(h2children, 'displayname', 'vline2'), 'visible', 'off'); set(findall(h2children, 'displayname', 'line1'), 'XData', xval(selpad)); set(findall(h2children, 'displayname', 'line1'), 'YData', data(selpad)); set(findall(h2children, 'displayname', 'line2'), 'XData', xval(sel)); set(findall(h2children, 'displayname', 'line2'), 'YData', data(sel)); data(~artval) = nan; set(findall(h2children, 'displayname', 'line3'), 'XData', xval); set(findall(h2children, 'displayname', 'line3'), 'YData', data); abc2 = axis(opt.h2); set(findall(h2children, 'displayname', 'vline1'), 'XData', [1 1]*xval( 1)+(trlpadsmp-1/opt.hdr.Fs)); set(findall(h2children, 'displayname', 'vline1'), 'YData', abc2(3:4)); set(findall(h2children, 'displayname', 'vline2'), 'XData', [1 1]*xval(end)-(trlpadsmp/opt.hdr.Fs)); set(findall(h2children, 'displayname', 'vline2'), 'YData', abc2(3:4)); set(findall(h2children, 'displayname', 'vline1'), 'visible', 'on'); set(findall(h2children, 'displayname', 'vline2'), 'visible', 'on'); str = sprintf('trial %3d, channel %s', opt.trlop, hdr.label{sgnind}); title(str); xlim([xval(1) xval(end)]); end % plot z-values in lower subplot subplot(opt.h3); hold on; if isempty(get(opt.h3, 'children')) % do the plotting plot(xval(selpad), zval(selpad), 'color', [0.5 0.5 1], 'displayname', 'line1b'); plot(xval(sel), zval(sel), 'color', [0 0 1], 'displayname', 'line2b'); hline(opt.threshold, 'color', 'r', 'linestyle', ':', 'displayname', 'threshline'); vline(xval( 1)+(trlpadsmp-1/opt.hdr.Fs), 'color', [0 0 0], 'displayname', 'vline1b'); vline(xval(end)-(trlpadsmp/opt.hdr.Fs), 'color', [0 0 0], 'displayname', 'vline2b'); zval(~artval) = nan; plot(xval, zval, 'r-', 'displayname', 'line3b'); xlabel('time(s)'); ylabel('z-value'); xlim([xval(1) xval(end)]); else % update in the existing handles h3children = get(opt.h3, 'children'); set(findall(h3children, 'displayname', 'vline1b'), 'visible', 'off'); set(findall(h3children, 'displayname', 'vline2b'), 'visible', 'off'); set(findall(h3children, 'displayname', 'line1b'), 'XData', xval(selpad)); set(findall(h3children, 'displayname', 'line1b'), 'YData', zval(selpad)); set(findall(h3children, 'displayname', 'line2b'), 'XData', xval(sel)); set(findall(h3children, 'displayname', 'line2b'), 'YData', zval(sel)); zval(~artval) = nan; set(findall(h3children, 'displayname', 'line3b'), 'XData', xval); set(findall(h3children, 'displayname', 'line3b'), 'YData', zval); set(findall(h3children, 'displayname', 'threshline'), 'YData', [1 1].*opt.threshold); set(findall(h3children, 'displayname', 'threshline'), 'XData', xval([1 end])); abc = axis(opt.h3); set(findall(h3children, 'displayname', 'vline1b'), 'XData', [1 1]*xval( 1)+(trlpadsmp-1/opt.hdr.Fs)); set(findall(h3children, 'displayname', 'vline1b'), 'YData', abc(3:4)); set(findall(h3children, 'displayname', 'vline2b'), 'XData', [1 1]*xval(end)-(trlpadsmp/opt.hdr.Fs)); set(findall(h3children, 'displayname', 'vline2b'), 'YData', abc(3:4)); set(findall(h3children, 'displayname', 'vline1b'), 'visible', 'on'); set(findall(h3children, 'displayname', 'vline2b'), 'visible', 'on'); xlim([xval(1) xval(end)]); end setappdata(h, 'opt', opt); uiresume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cleanup_cb(h, eventdata) opt = getappdata(h, 'opt'); opt.quit = true; setappdata(h, 'opt', opt); uiresume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = getparent(h) p = h; while p~=0 h = p; p = get(h, 'parent'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key = parseKeyboardEvent(eventdata) key = eventdata.Key; % handle possible numpad events (different for Windows and UNIX systems) % NOTE: shift+numpad number does not work on UNIX, since the shift % modifier is always sent for numpad events if isunix() shiftInd = match_str(eventdata.Modifier, 'shift'); if ~isnan(str2double(eventdata.Character)) && ~isempty(shiftInd) % now we now it was a numpad keystroke (numeric character sent AND % shift modifier present) key = eventdata.Character; eventdata.Modifier(shiftInd) = []; % strip the shift modifier end elseif ispc() if strfind(eventdata.Key, 'numpad') key = eventdata.Character; end end if ~isempty(eventdata.Modifier) key = [eventdata.Modifier{1} '+' key]; end
github
lcnbeapp/beapp-master
ft_sourceparcellate.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_sourceparcellate.m
17,075
utf_8
a75c59fcd439e6245d86f4a5ad81ccb6
function parcel = ft_sourceparcellate(cfg, source, parcellation) % FT_SOURCEPARCELLATE combines the source-reconstruction parameters over the parcels. % % Use as % output = ft_sourceparcellate(cfg, source, parcellation) % where the input source is a 2D surface-based or 3-D voxel-based source grid that was for % example obtained from FT_SOURCEANALYSIS or FT_COMPUTE_LEADFIELD. The input parcellation is % described in detail in FT_DATATYPE_PARCELLATION (2-D) or FT_DATATYPE_SEGMENTATION (3-D) and % can be obtained from FT_READ_ATLAS or from a custom parcellation/segmentation for your % individual subject. The output is a channel-based representation with the combined (e.g. % averaged) representation of the source parameters per parcel. % % The configuration "cfg" is a structure that can contain the following % fields % cfg.method = string, method to combine the values, see below (default = 'mean') % cfg.parcellation = string, fieldname that contains the desired parcellation % cfg.parameter = cell-array with strings, fields that should be parcellated (default = 'all') % % The values within a parcel or parcel-combination can be combined using % the following methods: % 'mean' compute the mean % 'median' compute the median (unsupported for fields that are represented in a cell-array) % 'eig' compute the largest eigenvector % 'min' take the minimal value % 'max' take the maximal value % 'maxabs' take the signed maxabs value % % See also FT_SOURCEANALYSIS, FT_DATATYPE_PARCELLATION, FT_DATATYPE_SEGMENTATION % Copyright (C) 2012-2013, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar source parcellation ft_preamble provenance source parcellation ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % get the defaults cfg.parcellation = ft_getopt(cfg, 'parcellation'); cfg.parameter = ft_getopt(cfg, 'parameter', 'all'); cfg.method = ft_getopt(cfg, 'method', 'mean'); % can be mean, min, max, svd cfg.feedback = ft_getopt(cfg, 'feedback', 'text'); % the data can be passed as input argument or can be read from disk hasparcellation = exist('parcellation', 'var'); if ischar(cfg.parameter) cfg.parameter = {cfg.parameter}; end if hasparcellation % the parcellation is specified as separate structure else % the parcellation is represented in the source structure itself parcellation = source; end % keep the transformation matrix if isfield(parcellation, 'transform') transform = parcellation.transform; else transform = []; end % ensure it is a parcellation, not a segmentation parcellation = ft_checkdata(parcellation, 'datatype', 'parcellation', 'parcellationstyle', 'indexed'); % keep the transformation matrix if ~isempty(transform) parcellation.transform = transform; end % ensure it is a source, not a volume source = ft_checkdata(source, 'datatype', 'source', 'inside', 'logical'); % ensure that the source and the parcellation are anatomically consistent if ~isequalwithequalnans(source.pos, parcellation.pos) error('the source positions are not consistent with the parcellation, please use FT_SOURCEINTERPOLATE'); end if isempty(cfg.parcellation) % determine the first field that can be used for the parcellation fn = fieldnames(parcellation); for i=1:numel(fn) if isfield(parcellation, [fn{i} 'label']) warning('using "%s" for the parcellation', fn{i}); cfg.parcellation = fn{i}; break end end end if isempty(cfg.parcellation) error('you should specify the field containing the parcellation'); end % determine the fields and corresponding dimords to work on fn = fieldnames(source); fn = setdiff(fn, {'pos', 'tri', 'inside', 'outside', 'time', 'freq', 'dim', 'transform', 'unit', 'coordsys', 'cfg', 'hdr'}); % remove fields that do not represent the data fn = fn(cellfun(@isempty, regexp(fn, 'dimord'))); % remove dimord fields fn = fn(cellfun(@isempty, regexp(fn, 'label'))); % remove label fields dimord = cell(size(fn)); for i=1:numel(fn) dimord{i} = getdimord(source, fn{i}); end if any(strcmp(cfg.parameter, 'all')) cfg.parameter = fn; else [inside, i1, i2] = intersect(cfg.parameter, fn); [outside ] = setdiff(cfg.parameter, fn); if ~isempty(outside) warning('\nparameter "%s" cannot be parcellated', outside{:}); end cfg.parameter = fn(i2); fn = fn(i2); dimord = dimord(i2); end % although it is technically feasible, don't parcellate the parcellation itself sel = ~strcmp(cfg.parcellation, fn); fn = fn(sel); dimord = dimord(sel); if numel(fn)==0 error('there are no source parameters that can be parcellated'); end % get the parcellation and the labels that go with it seg = parcellation.(cfg.parcellation); seglabel = parcellation.([cfg.parcellation 'label']); nseg = length(seglabel); if isfield(source, 'inside') % determine the conjunction of the parcellation and the inside source points n0 = numel(source.inside); n1 = sum(source.inside(:)); n2 = sum(seg(:)~=0); fprintf('there are in total %d positions, %d positions are inside the brain, %d positions have a label\n', n0, n1, n2); fprintf('%d of the positions inside the brain have a label\n', sum(seg(source.inside)~=0)); fprintf('%d of the labeled positions are inside the brain\n', sum(source.inside(seg(:)~=0))); fprintf('%d of the positions inside the brain do not have a label\n', sum(seg(source.inside)==0)); % discard the positions outside the brain and the positions in the brain that do not have a label seg(~source.inside) = 0; end % start preparing the output data structure parcel = []; parcel.label = seglabel; if isfield(source, 'time') parcel.time = source.time; end if isfield(source, 'freq') parcel.freq = source.freq; end for i=1:numel(fn) % parcellate each of the desired parameters dat = source.(fn{i}); if strncmp('{pos_pos}', dimord{i}, 9) fprintf('creating %d*%d parcel combinations for parameter %s by taking the %s\n', numel(seglabel), numel(seglabel), fn{i}, cfg.method); tmp = cell(nseg, nseg); ft_progress('init', cfg.feedback, 'computing parcellation'); k = 0; K = numel(seglabel)^2; for j1=1:numel(seglabel) for j2=1:numel(seglabel) k = k + 1; ft_progress(k/K, 'computing parcellation for %s combined with %s', seglabel{j1}, seglabel{j2}); switch cfg.method case 'mean' tmp{j1,j2} = cellmean2(dat(seg==j1,seg==j2,:)); case 'median' error('taking the median from data in a cell-array is not yet implemented'); case 'min' tmp{j1,j2} = cellmin2(dat(seg==j1,seg==j2,:)); case 'max' tmp{j1,j2} = cellmax2(dat(seg==j1,seg==j2,:)); % case 'eig' % tmp{j1,j2} = celleig2(dat(seg==j1,seg==j2,:)); otherwise error('method %s not implemented for %s', cfg.method, dimord{i}); end % switch end % for j2 end % for j1 ft_progress('close'); elseif strncmp('{pos}', dimord{i}, 5) fprintf('creating %d parcels for parameter %s by taking the %s\n', numel(seglabel), fn{i}, cfg.method); tmp = cell(nseg, 1); ft_progress('init', cfg.feedback, 'computing parcellation'); for j=1:numel(seglabel) ft_progress(j/numel(seglabel), 'computing parcellation for %s', seglabel{j}); switch cfg.method case 'mean' tmp{j} = cellmean1(dat(seg==j)); case 'median' error('taking the median from data in a cell-array is not yet implemented'); case 'min' tmp{j} = cellmin1(dat(seg==j)); case 'max' tmp{j} = cellmax1(dat(seg==j)); % case 'eig' % tmp{j} = celleig1(dat(seg==j)); otherwise error('method %s not implemented for %s', cfg.method, dimord{i}); end % switch end % for ft_progress('close'); elseif strncmp('pos_pos', dimord{i}, 7) fprintf('creating %d*%d parcel combinations for parameter %s by taking the %s\n', numel(seglabel), numel(seglabel), fn{i}, cfg.method); siz = size(dat); siz(1) = nseg; siz(2) = nseg; tmp = nan(siz); ft_progress('init', cfg.feedback, 'computing parcellation'); k = 0; K = numel(seglabel)^2; for j1=1:numel(seglabel) for j2=1:numel(seglabel) k = k + 1; ft_progress(k/K, 'computing parcellation for %s combined with %s', seglabel{j1}, seglabel{j2}); switch cfg.method case 'mean' tmp(j1,j2,:) = arraymean2(dat(seg==j1,seg==j2,:)); case 'median' tmp(j1,j2,:) = arraymedian2(dat(seg==j1,seg==j2,:)); case 'min' tmp(j1,j2,:) = arraymin2(dat(seg==j1,seg==j2,:)); case 'max' tmp(j1,j2,:) = arraymax2(dat(seg==j1,seg==j2,:)); case 'eig' tmp(j1,j2,:) = arrayeig2(dat(seg==j1,seg==j2,:)); case 'maxabs' tmp(j1,j2,:) = arraymaxabs2(dat(seg==j1,seg==j2,:)); otherwise error('method %s not implemented for %s', cfg.method, dimord{i}); end % switch end % for j2 end % for j1 ft_progress('close'); elseif strncmp('pos', dimord{i}, 3) fprintf('creating %d parcels for %s by taking the %s\n', numel(seglabel), fn{i}, cfg.method); siz = size(dat); siz(1) = nseg; tmp = nan(siz); ft_progress('init', cfg.feedback, 'computing parcellation'); for j=1:numel(seglabel) ft_progress(j/numel(seglabel), 'computing parcellation for %s', seglabel{j}); switch cfg.method case 'mean' tmp(j,:) = arraymean1(dat(seg==j,:)); case 'mean_thresholded' cfg.mean = ft_getopt(cfg, 'mean', struct('threshold', [])); if isempty(cfg.mean.threshold), error('when cfg.method = ''mean_thresholded'', you should specify a cfg.mean.threshold'); end if numel(cfg.mean.threshold)==size(dat,1) % assume one threshold per vertex threshold = cfg.mean.threshold(seg==j,:); else threshold = cfg.mean.threshold; end tmp(j,:) = arraymean1(dat(seg==j,:), threshold); case 'median' tmp(j,:) = arraymedian1(dat(seg==j,:)); case 'min' tmp(j,:) = arraymin1(dat(seg==j,:)); case 'max' tmp(j,:) = arraymax1(dat(seg==j,:)); case 'maxabs' tmp(j,:) = arraymaxabs1(dat(seg==j,:)); case 'eig' tmp(j,:) = arrayeig1(dat(seg==j,:)); otherwise error('method %s not implemented for %s', cfg.method, dimord{i}); end % switch end % for ft_progress('close'); else error('unsupported dimord %s', dimord{i}) end % if pos, pos_pos, {pos}, etc. % update the dimord, use chan rather than pos % this makes it look just like timelock or freq data tok = tokenize(dimord{i}, '_'); tok(strcmp(tok, 'pos' )) = { 'chan' }; % replace pos by chan tok(strcmp(tok, '{pos}')) = {'{chan}'}; % replace pos by chan tok(strcmp(tok, '{pos')) = {'{chan' }; % replace pos by chan tok(strcmp(tok, 'pos}')) = { 'chan}'}; % replace pos by chan tmpdimord = sprintf('%s_', tok{:}); tmpdimord = tmpdimord(1:end-1); % exclude the last _ % store the results in the output structure parcel.(fn{i}) = tmp; parcel.([fn{i} 'dimord']) = tmpdimord; % to avoid confusion clear dat tmp tmpdimord j j1 j2 end % for each of the fields that should be parcellated % a brainordinate is a brain location that is specified by either a surface vertex (node) or a volume voxel parcel.brainordinate = keepfields(parcellation, {'pos', 'tri', 'dim', 'transform'}); % keep the information about the geometry fn = fieldnames(parcellation); for i=1:numel(fn) if isfield(parcellation, [fn{i} 'label']) % keep each of the labeled fields from the parcellation parcel.brainordinate.( fn{i} ) = parcellation.( fn{i} ); parcel.brainordinate.([fn{i} 'label']) = parcellation.([fn{i} 'label']); end end ft_postamble debug ft_postamble trackconfig ft_postamble previous source parcellation ft_postamble provenance parcel ft_postamble history parcel ft_postamble savevar parcel %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTIONS to complute something over the first dimension %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = arraymean1(x, threshold) if nargin==1 y = mean(x,1); else if numel(threshold)==1 % scalar comparison is possible elseif size(threshold,1) == size(x,1) % assume threshold to be column vector threshold = repmat(threshold, [1, size(x,2)]); end sel = sum(x>threshold,2); if ~isempty(sel) y = mean(x(sel>0,:),1); else y = nan+zeros(1,size(x,2)); end end function y = arraymedian1(x) y = median(x,1); function y = arraymin1(x) y = min(x,[], 1); function y = arraymax1(x) y = max(x,[], 1); function y = arrayeig1(x) siz = size(x); x = reshape(x, siz(1), prod(siz(2:end))); [u, s, v] = svds(x, 1); % x = u * s * v' y = s(1,1) * v(:,1); % retain the largest eigenvector with appropriate scaling y = reshape(y, [siz(2:end) 1]); % size should have at least two elements function y = arraymaxabs1(x) % take the value that is at max(abs(x)) [dum,ix] = max(abs(x), [], 1); y = x(ix); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTIONS to compute something over the first two dimensions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = arraymean2(x) siz = size(x); x = reshape(x, [siz(1)*siz(2) siz(3:end) 1]); % simplify it into a single dimension y = arraymean1(x); function y = arraymedian2(x) siz = size(x); x = reshape(x, [siz(1)*siz(2) siz(3:end) 1]); % simplify it into a single dimension y = arraymedian1(x); function y = arraymin2(x) siz = size(x); x = reshape(x, [siz(1)*siz(2) siz(3:end) 1]); % simplify it into a single dimension y = arraymin1(x); function y = arraymax2(x) siz = size(x); x = reshape(x, [siz(1)*siz(2) siz(3:end) 1]); % simplify it into a single dimension y = arraymax1(x); function y = arrayeig2(x) siz = size(x); x = reshape(x, [siz(1)*siz(2) siz(3:end) 1]); % simplify it into a single dimension y = arrayeig1(x); function y = arraymaxabs2(x) % take the value that is at max(abs(x)) siz = size(x); x = reshape(x, [siz(1)*siz(2) siz(3:end) 1]); % simplify it into a single dimension [dum,ix] = max(abs(x), [], 1); y = x(ix); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTIONS for doing something over the first dimension of a cell array %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = cellmean1(x) siz = size(x); if siz(1)==1 && siz(2)>1 siz([2 1]) = siz([1 2]); x = reshape(x, siz); end y = x{1}; n = 1; for i=2:siz(1) y = y + x{i}; n = n + 1; end y = y/n; function y = cellmin1(x) siz = size(x); if siz(1)==1 && siz(2)>1 siz([2 1]) = siz([1 2]); x = reshape(x, siz); end y = x{1}; for i=2:siz(1) y = min(x{i}, y); end function y = cellmax1(x) siz = size(x); if siz(1)==1 && siz(2)>1 siz([2 1]) = siz([1 2]); x = reshape(x, siz); end y = x{1}; for i=2:siz(1) y = max(x{i}, y); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTIONS to compute something over the first two dimensions of a cell array %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = cellmean2(x) siz = size(x); x = reshape(x, [siz(1)*siz(2) siz(3:end) 1]); % simplify it into a single dimension y = cellmean1(x); function y = cellmin2(x) siz = size(x); x = reshape(x, [siz(1)*siz(2) siz(3:end) 1]); % simplify it into a single dimension y = cellmin1(x); function y = cellmax2(x) siz = size(x); x = reshape(x, [siz(1)*siz(2) siz(3:end) 1]); % simplify it into a single dimension y = cellmax1(x);
github
lcnbeapp/beapp-master
besa2fieldtrip.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/besa2fieldtrip.m
16,198
utf_8
0c7a9f9810b768eb90d6a2e7ffeeab37
function data = besa2fieldtrip(input) % BESA2FIELDTRIP reads and converts various BESA datafiles into a FieldTrip % data structure, which subsequently can be used for statistical analysis % or other analysis methods implemented in Fieldtrip. % % Use as % [data] = besa2fieldtrip(filename) % where the filename should point to a BESA datafile (or data that % was exported by BESA). The output is a MATLAB structure that is % compatible with FieldTrip. % % The format of the output structure depends on the type of datafile: % *.avr is converted to a structure similar to the output of FT_TIMELOCKANALYSIS % *.mul is converted to a structure similar to the output of FT_TIMELOCKANALYSIS % *.swf is converted to a structure similar to the output of FT_TIMELOCKANALYSIS (*) % *.tfc is converted to a structure similar to the output of FT_FREQANALYSIS (*) % *.dat is converted to a structure similar to the output of FT_SOURCANALYSIS % *.dat combined with a *.gen or *.generic is converted to a structure similar to the output of FT_PREPROCESSING % % Note (*): If the BESA toolbox by Karsten Hochstatter is found on your % MATLAB path, the readBESAxxx functions will be used (where xxx=tfc/swf), % alternatively the private functions from FieldTrip will be used. % % See also EEGLAB2FIELDTRIP, SPM2FIELDTRIP % Copyright (C) 2005-2010, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble callinfo if isstruct(input) && numel(input)>1 % use a recursive call to convert multiple inputs data = cell(size(input)); for i=1:numel(input) data{i} = besa2fieldtrip(input(i)); end return end if isstruct(input) fprintf('besa2fieldtrip: converting structure\n'); %---------------------TFC-------------------------------------------------% if strcmp(input.structtype, 'besa_tfc') %fprintf('BESA tfc\n'); data.time = input.latencies; data.freq = input.frequencies; temp_chans = char(input.channellabels'); Nchan = size(temp_chans,1); %{ if strcmp(input.type,'COHERENCE_SQUARED') % it contains coherence between channel pairs fprintf('reading coherence between %d channel pairs\n', Nchan); for i=1:Nchan tmp = tokenize(deblank(temp_chans(i,:)), '-'); data.labelcmb{i,1} = deblank(tmp{1}); data.labelcmb{i,2} = deblank(tmp{2}); data.label{i,1} = deblank(temp_chans(i,:)); end data.cohspctrm = input.data; else %} % it contains power on channels fprintf('reading power on %d channels\n', Nchan); for i=1:Nchan data.label{i,1} = deblank(temp_chans(i,:)); end data.powspctrm = input.data; data.dimord = 'chan_freq_time'; data.condition = input.condition; %not original Fieldtrip fieldname %end clear temp; %--------------------Image------------------------------------------------% elseif strcmp(input.structtype, 'besa_image') %fprintf('BESA image\n'); data.avg.pow = input.data; xTemp = input.xcoordinates; yTemp = input.ycoordinates; zTemp = input.zcoordinates; data.xgrid = xTemp; data.ygrid = yTemp; data.zgrid = zTemp; nx = size(data.xgrid,2); ny = size(data.ygrid,2); nz = size(data.zgrid,2); % Number of points in each dimension data.dim = [nx ny nz]; % Array with all possible positions (x,y,z) data.pos = WritePosArray(xTemp,yTemp,zTemp,nx,ny,nz); data.inside = 1:prod(data.dim);%as in Fieldtrip - not correct data.outside = []; %--------------------Source Waveform--------------------------------------% elseif strcmp(input.structtype, 'besa_sourcewaveforms') %fprintf('BESA source waveforms\n'); data.label = input.labels'; %not the same as Fieldtrip! data.dimord = 'chan_time'; data.fsample = input.samplingrate; data.time = input.latencies / 1000.0; data.avg = input.waveforms'; data.cfg.filename = input.datafile; %--------------------Data Export------------------------------------------% elseif strcmp(input.structtype, 'besa_channels') %fprintf('BESA data export\n'); if isfield(input,'datatype') switch input.ft_datatype case {'Raw_Data','Epoched_Data','Segment'} data.fsample = input.samplingrate; data.label = input.channellabels'; for k=1:size(input.data,2) data.time{1,k} = input.data(k).latencies / 1000.0'; data.trial{1,k} = input.data(k).amplitudes'; end otherwise fprintf('ft_datatype other than Raw_Data, Epoched or Segment'); end else fprintf('workspace created with earlier MATLAB version'); end %--------------------else-------------------------------------------------% else error('unrecognized format of the input structure'); end elseif ischar(input) fprintf('besa2fieldtrip: reading from file\n'); % This function can either use the reading functions included in FieldTrip % (with contributions from Karsten, Vladimir and Robert), or the official % released functions by Karsten Hoechstetter from BESA. The functions in the % official toolbox have precedence. hasbesa = ft_hastoolbox('besa',1, 1); type = ft_filetype(input); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(type, 'besa_avr') && hasbesa fprintf('reading ERP/ERF\n'); % this should be similar to the output of TIMELOCKANALYSIS tmp = readBESAavr(input); % convert into a TIMELOCKANALYSIS compatible data structure data = []; data.label = []; if isfield(tmp, 'ChannelLabels'), data.label = fixlabels(tmp.ChannelLabels); end; data.avg = tmp.Data; data.time = tmp.Time / 1000; % convert to seconds data.fsample = 1000/tmp.DI; data.dimord = 'chan_time'; elseif strcmp(type, 'besa_avr') && ~hasbesa fprintf('reading ERP/ERF\n'); % this should be similar to the output of TIMELOCKANALYSIS tmp = read_besa_avr(input); % convert into a TIMELOCKANALYSIS compatible data structure data = []; data.label = fixlabels(tmp.label); data.avg = tmp.data; data.time = (0:(tmp.npnt-1)) * tmp.di + tmp.tsb; data.time = data.time / 1000; % convert to seconds data.fsample = 1000/tmp.di; data.dimord = 'chan_time'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(type, 'besa_mul') && hasbesa fprintf('reading ERP/ERF\n'); % this should be similar to the output of TIMELOCKANALYSIS tmp = readBESAmul(input); % convert into a TIMELOCKANALYSIS compatible data structure data = []; data.label = tmp.ChannelLabels(:); data.avg = tmp.data'; data.time = (0:(tmp.Npts-1)) * tmp.DI + tmp.TSB; data.time = data.time / 1000; %convert to seconds data.fsample = 1000/tmp.DI; data.dimord = 'chan_time'; elseif strcmp(type, 'besa_mul') && ~hasbesa fprintf('reading ERP/ERF\n'); % this should be similar to the output of TIMELOCKANALYSIS tmp = read_besa_mul(input); % convert into a TIMELOCKANALYSIS compatible data structure data = []; data.label = tmp.label(:); data.avg = tmp.data; data.time = (0:(tmp.TimePoints-1)) * tmp.SamplingInterval_ms_ + tmp.BeginSweep_ms_; data.time = data.time / 1000; % convert to seconds data.fsample = 1000/tmp.SamplingInterval_ms_; data.dimord = 'chan_time'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(type, 'besa_sb') if hasbesa fprintf('reading preprocessed channel data using BESA toolbox\n'); else error('this data format requires the BESA toolbox'); end [p, f, x] = fileparts(input); input = fullfile(p, [f '.dat']); [time,buf,ntrial] = readBESAsb(input); time = time/1000; % convert from ms to sec nchan = size(buf,1); ntime = size(buf,3); % convert into a PREPROCESSING compatible data structure data = []; data.trial = {}; data.time = {}; for i=1:ntrial data.trial{i} = reshape(buf(:,i,:), [nchan, ntime]); data.time{i} = time; end data.label = {}; for i=1:size(buf,1) data.label{i,1} = sprintf('chan%03d', i); end data.fsample = 1./mean(diff(time)); % time is already in seconds %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(type, 'besa_tfc') && hasbesa fprintf('reading time-frequency representation using BESA toolbox\n'); % this should be similar to the output of FREQANALYSIS tfc = readBESAtfc(input); Nchan = size(tfc.ChannelLabels,1); % convert into a FREQANALYSIS compatible data structure data = []; data.time = tfc.Time(:)'; data.freq = tfc.Frequency(:)'; if isfield(tfc, 'DataType') && strcmp(tfc.DataType, 'COHERENCE_SQUARED') % it contains coherence between channel pairs fprintf('reading coherence between %d channel pairs\n', Nchan); for i=1:Nchan tmp = tokenize(deblank(tfc.ChannelLabels(i,:)), '-'); data.labelcmb{i,1} = tmp{1}; data.labelcmb{i,2} = tmp{2}; end data.cohspctrm = permute(tfc.Data, [1 3 2]); else % it contains power on channels fprintf('reading power on %d channels\n', Nchan); for i=1:Nchan data.label{i,1} = deblank(tfc.ChannelLabels(i,:)); end data.powspctrm = permute(tfc.Data, [1 3 2]); end data.dimord = 'chan_freq_time'; data.condition = tfc.ConditionName; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(type, 'besa_tfc') && ~hasbesa fprintf('reading time-frequency representation\n'); % this should be similar to the output of FREQANALYSIS [ChannelLabels, Time, Frequency, Data, Info] = read_besa_tfc(input); Nchan = size(ChannelLabels,1); % convert into a FREQANALYSIS compatible data structure data = []; data.time = Time * 1e-3; % convert to seconds; data.freq = Frequency; if isfield(Info, 'DataType') && strcmp(Info.DataType, 'COHERENCE_SQUARED') % it contains coherence between channel pairs fprintf('reading coherence between %d channel pairs\n', Nchan); for i=1:Nchan tmp = tokenize(deblank(ChannelLabels(i,:)), '-'); data.labelcmb{i,1} = tmp{1}; data.labelcmb{i,2} = tmp{2}; end data.cohspctrm = permute(Data, [1 3 2]); else % it contains power on channels fprintf('reading power on %d channels\n', Nchan); for i=1:Nchan data.label{i} = deblank(ChannelLabels(i,:)); end data.powspctrm = permute(Data, [1 3 2]); end data.dimord = 'chan_freq_time'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(type, 'besa_swf') && hasbesa fprintf('reading source waveform using BESA toolbox\n'); swf = readBESAswf(input); % convert into a TIMELOCKANALYSIS compatible data structure data = []; data.label = fixlabels(swf.waveName); data.avg = swf.data; data.time = swf.Time * 1e-3; % convert to seconds data.fsample = 1/mean(diff(data.time)); data.dimord = 'chan_time'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(type, 'besa_swf') && ~hasbesa fprintf('reading source waveform\n'); % hmm, I guess that this should be similar to the output of TIMELOCKANALYSIS tmp = read_besa_swf(input); % convert into a TIMELOCKANALYSIS compatible data structure data = []; data.label = fixlabels(tmp.label); data.avg = tmp.data; data.time = (0:(tmp.npnt-1)) * tmp.di + tmp.tsb; data.time = data.time / 1000; % convert to seconds data.fsample = 1000/tmp.di; data.dimord = 'chan_time'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(type, 'besa_src') && hasbesa src = readBESAimage(input); data.xgrid = src.Coordinates.X; data.ygrid = src.Coordinates.Y; data.zgrid = src.Coordinates.Z; data.avg.pow = src.Data; data.dim = size(src.Data); [X, Y, Z] = ndgrid(data.xgrid, data.ygrid, data.zgrid); data.pos = [X(:) Y(:) Z(:)]; % cannot determine which voxels are inside the brain volume data.inside = 1:prod(data.dim); data.outside = []; elseif strcmp(type, 'besa_src') && ~hasbesa src = read_besa_src(input); data.xgrid = linspace(src.X(1), src.X(2), src.X(3)); data.ygrid = linspace(src.Y(1), src.Y(2), src.Y(3)); data.zgrid = linspace(src.Z(1), src.Z(2), src.Z(3)); data.avg.pow = src.vol; data.dim = size(src.vol); [X, Y, Z] = ndgrid(data.xgrid, data.ygrid, data.zgrid); data.pos = [X(:) Y(:) Z(:)]; % cannot determine which voxels are inside the brain volume data.inside = 1:prod(data.dim); data.outside = []; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(type, 'besa_pdg') % hmmm, I have to think about this one... error('sorry, pdg is not yet supported'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% else error('unrecognized file format for importing BESA data'); end end % isstruct || ischar % construct and add a configuration to the output cfg = []; if isstruct(input) && isfield(input,'datafile') cfg.filename = input.datafile; elseif isstruct(input) && ~isfield(input,'datafile') cfg.filename = 'Unknown'; elseif ischar(input) cfg.filename = input; end % do the general cleanup and bookkeeping at the end of the function ft_postamble callinfo ft_postamble history data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that fixes the channel labels, should be a cell-array %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [newlabels] = fixlabels(labels) if iscell(labels) && length(labels)>1 % seems to be ok newlabels = labels; elseif iscell(labels) && length(labels)==1 % could be a cell with a single long string in it if length(tokenize(labels{1}, ' '))>1 % seems like a long string that accidentaly ended up in a single cell newlabels = tokenize(labels{1}, ' '); else % seems to be ok newlabels = labels; end elseif ischar(labels) && any(size(labels)==1) newlabels = tokenize(labels(:)', ' '); % also ensure that it is a row-string elseif ischar(labels) && ~any(size(labels)==1) for i=1:size(labels) newlabels{i} = strtrim(labels(i,:)); end end % convert to column newlabels = newlabels(:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [PArray] = WritePosArray(x,y,z,mx,my,mz) A1 = repmat(x,1,my*mz); A21 = repmat(y,mx,mz); A2 = reshape(A21,1,mx*my*mz); A31 = repmat(z,mx*my,1); A3 = reshape(A31,1,mx*my*mz); PArray = [A1;A2;A3]';
github
lcnbeapp/beapp-master
ft_topoplotCC.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/ft_topoplotCC.m
12,799
utf_8
8416ba741caf630c1c2b3a2fc78e6ff8
function [cfg] = ft_topoplotCC(cfg, freq) % FT_TOPOPLOTCC plots the coherence between channel pairs % % Use as % ft_topoplotCC(cfg, freq) % % The configuration should contain: % cfg.feedback = string (default = 'textbar') % cfg.layout = specification of the layout, see FT_PREPARE_LAYOUT % cfg.foi = the frequency of interest which is to be plotted (default is the first frequency bin) % cfg.widthparam = string, parameter to be used to control the line width (see below) % cfg.alphaparam = string, parameter to be used to control the opacity (see below) % cfg.colorparam = string, parameter to be used to control the line color % % The widthparam should be indicated in pixels, e.g. usefull numbers are 1 % and larger. % % The alphaparam should be indicated as opacity between 0 (fully transparent) % and 1 (fully opaque). % % The default is to plot the connections as lines, but you can also use % bidirectional arrows: % cfg.arrowhead = string, 'none', 'stop', 'start', 'both' (default = 'none') % cfg.arrowsize = scalar, size of the arrow head in figure units, % i.e. the same units as the layout (default is automatically determined) % cfg.arrowoffset = scalar, amount that the arrow is shifted to the side in figure units, % i.e. the same units as the layout (default is automatically determined) % cfg.arrowlength = scalar, amount by which the length is reduced relative to the complete line (default = 0.8) % % To facilitate data-handling and distributed computing you can use % cfg.inputfile = ... % If you specify this option the input data will be read from a *.mat % file on disk. This mat files should contain only a single variable named 'data', % corresponding to the input structure. For this particular function, the input should be % structured as a cell array. % % See also FT_PREPARE_LAYOUT, FT_MULTIPLOTCC, FT_CONNECTIVITYPLOT % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble debug ft_preamble loadvar freq ft_preamble provenance freq ft_preamble trackconfig % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % check if the input data is valid for this function freq = ft_checkdata(freq, 'cmbrepresentation', 'sparse'); % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'required', {'foi', 'layout'}); % set the defaults cfg.feedback = ft_getopt(cfg, 'feedback', 'text'); cfg.alphaparam = ft_getopt(cfg, 'alphaparam', []); cfg.widthparam = ft_getopt(cfg, 'widthparam', []); cfg.colorparam = ft_getopt(cfg, 'colorparam', 'cohspctrm'); cfg.newfigure = ft_getopt(cfg, 'newfigure', 'yes'); cfg.arrowhead = ft_getopt(cfg, 'arrowhead', 'none'); % none, stop, start, both cfg.arrowsize = ft_getopt(cfg, 'arrowsize', nan); % length of the arrow head, should be in in figure units, i.e. the same units as the layout cfg.arrowoffset = ft_getopt(cfg, 'arrowoffset', nan); % absolute, should be in figure units, i.e. the same units as the layout cfg.arrowlength = ft_getopt(cfg, 'arrowlength', 0.8);% relative to the complete line cfg.linestyle = ft_getopt(cfg, 'linestyle', []); cfg.colormap = ft_getopt(cfg, 'colormap', colormap); lay = ft_prepare_layout(cfg, freq); beglabel = freq.labelcmb(:,1); endlabel = freq.labelcmb(:,2); ncmb = size(freq.labelcmb,1); % select the data to be used in the figure fbin = nearest(freq.freq, cfg.foi); if isfield(freq, cfg.widthparam) widthparam = freq.(cfg.widthparam)(:,fbin); else widthparam = ones(ncmb,1); end if isfield(freq, cfg.alphaparam) alphaparam = freq.(cfg.alphaparam)(:,fbin); else alphaparam = []; end if isfield(freq, cfg.colorparam) colorparam = freq.(cfg.colorparam)(:,fbin); else colorparam = []; end if strcmp(cfg.newfigure, 'yes') figure end hold on axis equal % set the figure window title funcname = mfilename(); if isfield(cfg, 'inputfile') && ~isempty(cfg.inputfile) dataname = cfg.inputfile; else dataname = inputname(2); end set(gcf, 'Name', sprintf('%d: %s: %s', double(gcf), funcname, join_str(', ',dataname))); set(gcf, 'NumberTitle', 'off'); if isnan(cfg.arrowsize) % use the size of the figure to estimate a decent number siz = axis; cfg.arrowsize = (siz(2) - siz(1))/50; warning('using an arrowsize of %f', cfg.arrowsize); end if isnan(cfg.arrowoffset) % use the size of the figure to estimate a decent number siz = axis; cfg.arrowoffset = (siz(2) - siz(1))/100; warning('using an arrowoffset of %f', cfg.arrowoffset); end rgb = cfg.colormap; if ~isempty(colorparam) cmin = min(colorparam(:)); cmax = max(colorparam(:)); % this line creates a sorting vector that cause the most extreme valued % arrows to be plotted last [srt, srtidx] = sort(abs(colorparam)); colorparam = (colorparam - cmin)./(cmax-cmin); colorparam = round(colorparam * (size(rgb,1)-1) + 1); end if strcmp(cfg.newfigure, 'yes') ft_plot_lay(lay, 'label', 'no', 'box', 'off'); end % if newfigure % fix the limits for the axis axis(axis); ft_progress('init', cfg.feedback, 'plotting connections...'); if ~exist('srtidx', 'var') srtidx = 1:ncmb; end for i=srtidx(:)' if strcmp(beglabel{i}, endlabel{i}) % skip autocombinations continue end if widthparam(i)>0 && (isempty(alphaparam)||alphaparam(i)>0) ft_progress(i/ncmb, 'plotting connection %d from %d (%s -> %s)\n', i, ncmb, beglabel{i}, endlabel{i}); begindx = strcmp(beglabel{i}, lay.label); endindx = strcmp(endlabel{i}, lay.label); xbeg = lay.pos(begindx,1); ybeg = lay.pos(begindx,2); xend = lay.pos(endindx,1); yend = lay.pos(endindx,2); if isempty(cfg.linestyle) if strcmp(cfg.arrowhead, 'none') x = [xbeg xend]'; y = [ybeg yend]'; % h = line(x, y); h = patch(x, y, 1); else arrowbeg = [xbeg ybeg]; arrowend = [xend yend]; center = (arrowbeg+arrowend)/2; direction = (arrowend - arrowbeg); direction = direction/norm(direction); offset = [direction(2) -direction(1)]; arrowbeg = cfg.arrowlength * (arrowbeg-center) + center + cfg.arrowoffset * offset; arrowend = cfg.arrowlength * (arrowend-center) + center + cfg.arrowoffset * offset; h = arrow(arrowbeg, arrowend, 'Ends', cfg.arrowhead, 'length', 0.05); end % if arrow if ~isempty(widthparam) set(h, 'LineWidth', widthparam(i)); end if ~isempty(alphaparam) set(h, 'EdgeAlpha', alphaparam(i)); set(h, 'FaceAlpha', alphaparam(i)); % for arrowheads end if ~isempty(colorparam) set(h, 'EdgeColor', rgb(colorparam(i),:)); set(h, 'FaceColor', rgb(colorparam(i),:)); % for arrowheads end elseif ~isempty(cfg.linestyle) % new style of plotting, using curved lines, this does not allow for % alpha mapping on the line segment switch cfg.linestyle case 'curve' tmp = cscvn([xbeg mean([xbeg,xend])*0.8 xend;ybeg mean([ybeg,yend])*0.8 yend]); pnt = fnplt(tmp); h = line(pnt(1,:)', pnt(2,:)'); if ~isempty(widthparam) set(h, 'LineWidth', widthparam(i)); end if ~isempty(colorparam) set(h, 'Color', rgb(colorparam(i),:)); end % deal with the arrow if ~strcmp(cfg.arrowhead, 'none') arrowbeg = pnt(:,1)'; arrowend = pnt(:,end)'; directionbeg = (arrowbeg - pnt(:,2)'); directionend = (arrowend - pnt(:,end-1)'); directionbeg = directionbeg/norm(directionbeg); directionend = directionend/norm(directionend); switch cfg.arrowhead case 'stop' pnt1 = arrowend - 0.05*directionend + 0.02*[directionend(2) -directionend(1)]; pnt2 = arrowend; pnt3 = arrowend - 0.05*directionend - 0.02*[directionend(2) -directionend(1)]; h_arrow = patch([pnt1(1) pnt2(1) pnt3(1)]', [pnt1(2) pnt2(2) pnt3(2)]', [0 0 0]); case 'start' pnt1 = arrowbeg - 0.05*directionbeg + 0.02*[directionbeg(2) -directionbeg(1)]; pnt2 = arrowbeg; pnt3 = arrowbeg - 0.05*directionbeg - 0.02*[directionbeg(2) -directionbeg(1)]; h_arrow = patch([pnt1(1) pnt2(1) pnt3(1)]', [pnt1(2) pnt2(2) pnt3(2)]', [0 0 0]); case 'both' pnt1 = arrowbeg - 0.05*directionbeg + 0.02*[directionbeg(2) -directionbeg(1)]; pnt2 = arrowbeg; pnt3 = arrowbeg - 0.05*directionbeg - 0.02*[directionbeg(2) -directionbeg(1)]; h_arrow(1) = patch([pnt1(1) pnt2(1) pnt3(1)]', [pnt1(2) pnt2(2) pnt3(2)]', [0 0 0]); pnt1 = arrowend - 0.05*directionend + 0.02*[directionend(2) -directionend(1)]; pnt2 = arrowend; pnt3 = arrowend - 0.05*directionend - 0.02*[directionend(2) -directionend(1)]; h_arrow(2) = patch([pnt1(1) pnt2(1) pnt3(1)]', [pnt1(2) pnt2(2) pnt3(2)]', [0 0 0]); end else h_arrow = []; end if ~isempty(widthparam) set(h, 'LineWidth', widthparam(i)); if ~isempty(h_arrow) set(h_arrow, 'LineWidth', widthparam(i)); end end if ~isempty(colorparam) set(h, 'Color', rgb(colorparam(i),:)); if ~isempty(h_arrow) set(h_arrow, 'Edgecolor', rgb(colorparam(i),:)); set(h_arrow, 'Facecolor', rgb(colorparam(i),:)); end end if ~isempty(alphaparam) if ~isempty(h_arrow) set(h_arrow, 'EdgeAlpha', alphaparam(i)); set(h_arrow, 'FaceAlpha', alphaparam(i)); % for arrowheads end end otherwise error('unsupported linestyle specified'); end end end end ft_progress('close'); % improve the fit in the axis axis tight % do the general cleanup and bookkeeping at the end of the function ft_postamble debug ft_postamble trackconfig ft_postamble previous freq ft_postamble provenance %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for plotting arrows, see also fieldtrip/private/arrow %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = arrow(arrowbeg, arrowend, varargin) ends = ft_getopt(varargin, 'ends'); length = ft_getopt(varargin, 'length'); % the length of the arrow head, in figure units color = [0 0 0]; % in RGB direction = (arrowend - arrowbeg); direction = direction/norm(direction); offset = [direction(2) -direction(1)]; pnt1 = arrowbeg; pnt2 = arrowend; h = patch([pnt1(1) pnt2(1)], [pnt1(2) pnt2(2)], color); switch ends case 'stop' pnt1 = arrowend - length*direction + 0.4*length*offset; pnt2 = arrowend; pnt3 = arrowend - length*direction - 0.4*length*offset; h(end+1) = patch([pnt1(1) pnt2(1) pnt3(1)]', [pnt1(2) pnt2(2) pnt3(2)]', color); case 'start' pnt1 = arrowbeg + length*direction + 0.4*length*offset; pnt2 = arrowbeg; pnt3 = arrowbeg + length*direction - 0.4*length*offset; h(end+1) = patch([pnt1(1) pnt2(1) pnt3(1)]', [pnt1(2) pnt2(2) pnt3(2)]', color); case 'both' pnt1 = arrowend - length*direction + 0.4*length*offset; pnt2 = arrowend; pnt3 = arrowend - length*direction - 0.4*length*offset; h(end+1) = patch([pnt1(1) pnt2(1) pnt3(1)]', [pnt1(2) pnt2(2) pnt3(2)]', color); pnt1 = arrowbeg + length*direction + 0.4*length*offset; pnt2 = arrowbeg; pnt3 = arrowbeg + length*direction - 0.4*length*offset; h(end+1) = patch([pnt1(1) pnt2(1) pnt3(1)]', [pnt1(2) pnt2(2) pnt3(2)]', color); case 'none' % don't draw arrow heads end
github
lcnbeapp/beapp-master
ft_struct2single.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_struct2single.m
2,879
utf_8
8bbd1d96564795e5223a0cac06d604c8
function [x] = ft_struct2single(x, maxdepth) % FT_STRUCT2SINGLE converts all double precision numeric data in a structure % into single precision, which takes up half the amount of memory compared % to double precision. It will also convert plain matrices and cell-arrays. % % Use as % x = ft_struct2single(x) % % Starting from MATLAB 7.0, you can use single precision data in your % computations, i.e. you do not have to convert back to double precision. % % MATLAB version 6.5 and older only support single precision for storing % data in memory or on disk, but do not allow computations on single % precision data. After reading a single precision structure from file, you % can convert it back with FT_STRUCT2DOUBLE. % % See also FT_STRUCT2DOUBLE % Copyright (C) 2005-2014, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if nargin<2 maxdepth = inf; end % convert the data, work recursively through the complete structure x = convert(x, 0, maxdepth); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this subfunction does the actual work %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [a] = convert(a, depth, maxdepth) if depth>maxdepth error('recursive depth exceeded'); end switch class(a) case 'struct' % process all fields of the structure recursively fna = fieldnames(a); % process all elements of the array for j=1:length(a(:)) % warning, this is a recursive call to traverse nested structures for i=1:length(fna) fn = fna{i}; ra = getfield(a(j), fn); ra = convert(ra, depth+1, maxdepth); a(j) = setfield(a(j), fn, ra); end end case 'cell' % process all elements of the cell-array recursively % warning, this is a recursive call to traverse nested structures for i=1:length(a(:)) a{i} = convert(a{i}, depth+1, maxdepth); end case {'double' 'int64' 'uint64' 'int32' 'uint32' 'int16' 'uint16' 'int8' 'uint8'} % convert the values to single precision if ~issparse(a) a = single(a); end otherwise % do nothing end
github
lcnbeapp/beapp-master
ft_channelselection.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_channelselection.m
21,775
utf_8
45acb4edda264cd6b5cd506dfde62c48
function [channel] = ft_channelselection(desired, datachannel, senstype) % FT_CHANNELSELECTION makes a selection of EEG and/or MEG channel labels. % This function translates the user-specified list of channels into channel % labels as they occur in the data. This channel selection procedure can be % used throughout FieldTrip. % % Use as: % channel = ft_channelselection(desired, datachannel) % % You can specify a mixture of real channel labels and of special strings, % or index numbers that will be replaced by the corresponding channel % labels. Channels that are not present in the raw datafile are % automatically removed from the channel list. % % E.g. the desired input element can be: % 'all' is replaced by all channels in the datafile % 'gui' this will pop up a graphical user interface to select the channels % 'C*' is replaced by all channels that match the wildcard, e.g. C1, C2, C3, ... % '*1' is replaced by all channels that match the wildcard, e.g. C1, P1, F1, ... % 'M*1' is replaced by all channels that match the wildcard, e.g. MEG0111, MEG0131, MEG0131, ... % 'meg' is replaced by all MEG channels (works for CTF, 4D, Neuromag and Yokogawa) % 'megref' is replaced by all MEG reference channels (works for CTF and 4D) % 'meggrad' is replaced by all MEG gradiometer channels (works for Yokogawa and Neuromag-306) % 'megmag' is replaced by all MEG magnetometer channels (works for Yokogawa and Neuromag-306) % 'eeg' is replaced by all recognized EEG channels (this is system dependent) % 'eeg1020' is replaced by 'Fp1', 'Fpz', 'Fp2', 'F7', 'F3', ... % 'eog' is replaced by all recognized EOG channels % 'ecg' is replaced by all recognized ECG channels % 'nirs' is replaced by all channels recognized as NIRS channels % 'emg' is replaced by all channels in the datafile starting with 'EMG' % 'lfp' is replaced by all channels in the datafile starting with 'lfp' % 'mua' is replaced by all channels in the datafile starting with 'mua' % 'spike' is replaced by all channels in the datafile starting with 'spike' % 10 is replaced by the 10th channel in the datafile % % Other channel groups are % 'EEG1010' with approximately 90 electrodes % 'EEG1005' with approximately 350 electrodes % 'EEGREF' for mastoid and ear electrodes (M1, M2, LM, RM, A1, A2) % 'MZ' for MEG zenith % 'ML' for MEG left % 'MR' for MEG right % 'MLx', 'MRx' and 'MZx' with x=C,F,O,P,T for left/right central, frontal, occipital, parietal and temporal % % You can also exclude channels or channel groups using the following syntax % {'all', '-POz', '-Fp1', -EOG'} % % See also FT_PREPROCESSING, FT_SENSLABEL, FT_MULTIPLOTER, FT_MULTIPLOTTFR, % FT_SINGLEPLOTER, FT_SINGLEPLOTTFR % Note that the order of channels that is returned should correspond with % the order of the channels in the data. % Copyright (C) 2003-2014, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % this is to avoid a recursion loop persistent recursion if isempty(recursion) recursion = false; end if nargin<3 senstype = ft_senstype(datachannel); end if ~iscell(datachannel) if ischar(datachannel) datachannel = {datachannel}; else error('please specify the data channels as a cell-array'); end end if ~ischar(desired) && ~isnumeric(desired) && ~iscell(desired) error('please specify the desired channels as a cell-array or a string'); end % start with the list of desired channels, this will be pruned/expanded channel = desired; if length(datachannel)~=length(unique(datachannel)) warning('discarding non-unique channel names'); sel = false(size(datachannel)); for i=1:length(datachannel) sel(i) = sum(strcmp(datachannel, datachannel{i}))==1; end datachannel = datachannel(sel); end if any(size(channel) == 0) % there is nothing to do if it is empty return end if ~iscell(datachannel) % ensure that a single input argument like 'all' also works datachannel = {datachannel}; end if isnumeric(channel) % remove channels tha fall outside the range channel = channel(channel>=1 & channel<=numel(datachannel)); % change index into channelname channel = datachannel(channel); return end if ~iscell(channel) % ensure that a single input argument like 'all' also works % the case of a vector with channel indices has already been dealt with channel = {channel}; end % ensure that both inputs are column vectors channel = channel(:); datachannel = datachannel(:); % remove channels that occur more than once, this sorts the channels alphabetically [channel, indx] = unique(channel); % undo the sorting, make the order identical to that of the data channels [dum, indx] = sort(indx); channel = channel(indx); [dataindx, chanindx] = match_str(datachannel, channel); if length(chanindx)==length(channel) % there is a perfect match between the channels and the datachannels, only some reordering is needed channel = channel(chanindx); % no need to look at channel groups return end % define the known groups with channel labels labelall = datachannel; label1020 = ft_senslabel('eeg1020'); % use external helper function label1010 = ft_senslabel('eeg1010'); % use external helper function label1005 = ft_senslabel('eeg1005'); % use external helper function labelchwilla = {'Fz', 'Cz', 'Pz', 'F7', 'F8', 'LAT', 'RAT', 'LT', 'RT', 'LTP', 'RTP', 'OL', 'OR', 'FzA', 'Oz', 'F7A', 'F8A', 'F3A', 'F4A', 'F3', 'F4', 'P3', 'P4', 'T5', 'T6', 'P3P', 'P4P'}'; labelbham = {'P9', 'PPO9h', 'PO7', 'PPO5h', 'PPO3h', 'PO5h', 'POO9h', 'PO9', 'I1', 'OI1h', 'O1', 'POO1', 'PO3h', 'PPO1h', 'PPO2h', 'POz', 'Oz', 'Iz', 'I2', 'OI2h', 'O2', 'POO2', 'PO4h', 'PPO4h', 'PO6h', 'POO10h', 'PO10', 'PO8', 'PPO6h', 'PPO10h', 'P10', 'P8', 'TPP9h', 'TP7', 'TTP7h', 'CP5', 'TPP7h', 'P7', 'P5', 'CPP5h', 'CCP5h', 'CP3', 'P3', 'CPP3h', 'CCP3h', 'CP1', 'P1', 'Pz', 'CPP1h', 'CPz', 'CPP2h', 'P2', 'CPP4h', 'CP2', 'CCP4h', 'CP4', 'P4', 'P6', 'CPP6h', 'CCP6h', 'CP6', 'TPP8h', 'TP8', 'TPP10h', 'T7', 'FTT7h', 'FT7', 'FC5', 'FCC5h', 'C5', 'C3', 'FCC3h', 'FC3', 'FC1', 'C1', 'CCP1h', 'Cz', 'FCC1h', 'FCz', 'FFC1h', 'Fz', 'FFC2h', 'FC2', 'FCC2h', 'CCP2h', 'C2', 'C4', 'FCC4h', 'FC4', 'FC6', 'FCC6h', 'C6', 'TTP8h', 'T8', 'FTT8h', 'FT8', 'FT9', 'FFT9h', 'F7', 'FFT7h', 'FFC5h', 'F5', 'AFF7h', 'AF7', 'AF5h', 'AFF5h', 'F3', 'FFC3h', 'F1', 'AF3h', 'Fp1', 'Fpz', 'Fp2', 'AFz', 'AF4h', 'F2', 'FFC4h', 'F4', 'AFF6h', 'AF6h', 'AF8', 'AFF8h', 'F6', 'FFC6h', 'FFT8h', 'F8', 'FFT10h', 'FT10'}; labelref = {'M1', 'M2', 'LM', 'RM', 'A1', 'A2'}'; labeleog = datachannel(strncmp('EOG', datachannel, length('EOG'))); % anything that starts with EOG labeleog = [labeleog(:); {'HEOG', 'VEOG', 'VEOG-L', 'VEOG-R', 'hEOG', 'vEOG', 'Eye_Ver', 'Eye_Hor'}']; % or any of these labelecg = datachannel(strncmp('ECG', datachannel, length('ECG'))); labelemg = datachannel(strncmp('EMG', datachannel, length('EMG'))); labellfp = datachannel(strncmp('lfp', datachannel, length('lfp'))); labelmua = datachannel(strncmp('mua', datachannel, length('mua'))); labelspike = datachannel(strncmp('spike', datachannel, length('spike'))); labelnirs = datachannel(~cellfun(@isempty, regexp(datachannel, sprintf('%s%s', regexptranslate('wildcard','Rx*-Tx*[*]'), '$')))); % use regular expressions to deal with the wildcards labelreg = false(size(datachannel)); findreg = []; for i=1:length(channel) if length(channel{i}) < 1 continue; end if strcmp((channel{i}(1)), '-') % skip channels to be excluded continue; end rexp = sprintf('%s%s', regexptranslate('wildcard',channel{i}), '$'); lreg = ~cellfun(@isempty, regexp(datachannel, rexp)); if any(lreg) labelreg = labelreg | lreg; findreg = [findreg; i]; end end if ~isempty(findreg) findreg = unique(findreg); % remove multiple occurances due to multiple wildcards labelreg = datachannel(labelreg); end % initialize all the system-specific variables to empty labelmeg = []; labelmeggrad = []; labelmegref = []; labelmegmag = []; labeleeg = []; switch senstype case {'yokogawa', 'yokogawa160', 'yokogawa160_planar', 'yokogawa64', 'yokogawa64_planar', 'yokogawa440', 'yokogawa440_planar'} % Yokogawa axial gradiometers channels start with AG, hardware planar gradiometer % channels start with PG, magnetometers start with M megax = strncmp('AG', datachannel, length('AG')); megpl = strncmp('PG', datachannel, length('PG')); megmag = strncmp('M', datachannel, length('M' )); megind = logical( megax + megpl + megmag); labelmeg = datachannel(megind); labelmegmag = datachannel(megmag); labelmeggrad = datachannel(megax | megpl); case {'ctf64'} labelml = datachannel(~cellfun(@isempty, regexp(datachannel, '^SL'))); % left MEG channels labelmr = datachannel(~cellfun(@isempty, regexp(datachannel, '^SR'))); % right MEG channels labelmeg = cat(1, labelml, labelmr); labelmegref = [datachannel(strncmp('B' , datachannel, 1)); datachannel(strncmp('G' , datachannel, 1)); datachannel(strncmp('P' , datachannel, 1)); datachannel(strncmp('Q' , datachannel, 1)); datachannel(strncmp('R' , datachannel, length('G' )))]; case {'ctf', 'ctf275', 'ctf151', 'ctf275_planar', 'ctf151_planar'} % all CTF MEG channels start with "M" % all CTF reference channels start with B, G, P, Q or R % all CTF EEG channels start with "EEG" labelmeg = datachannel(strncmp('M' , datachannel, length('M' ))); labelmegref = [datachannel(strncmp('B' , datachannel, 1)); datachannel(strncmp('G' , datachannel, 1)); datachannel(strncmp('P' , datachannel, 1)); datachannel(strncmp('Q' , datachannel, 1)); datachannel(strncmp('R' , datachannel, length('G' )))]; labeleeg = datachannel(strncmp('EEG', datachannel, length('EEG'))); % Not sure whether this should be here or outside the switch or % whether these specifications should be supported for systems % other than CTF. labelmz = datachannel(strncmp('MZ' , datachannel, length('MZ' ))); % central MEG channels labelml = datachannel(strncmp('ML' , datachannel, length('ML' ))); % left MEG channels labelmr = datachannel(strncmp('MR' , datachannel, length('MR' ))); % right MEG channels labelmlc = datachannel(strncmp('MLC', datachannel, length('MLC'))); labelmlf = datachannel(strncmp('MLF', datachannel, length('MLF'))); labelmlo = datachannel(strncmp('MLO', datachannel, length('MLO'))); labelmlp = datachannel(strncmp('MLP', datachannel, length('MLP'))); labelmlt = datachannel(strncmp('MLT', datachannel, length('MLT'))); labelmrc = datachannel(strncmp('MRC', datachannel, length('MRC'))); labelmrf = datachannel(strncmp('MRF', datachannel, length('MRF'))); labelmro = datachannel(strncmp('MRO', datachannel, length('MRO'))); labelmrp = datachannel(strncmp('MRP', datachannel, length('MRP'))); labelmrt = datachannel(strncmp('MRT', datachannel, length('MRT'))); labelmzc = datachannel(strncmp('MZC', datachannel, length('MZC'))); labelmzf = datachannel(strncmp('MZF', datachannel, length('MZF'))); labelmzo = datachannel(strncmp('MZO', datachannel, length('MZO'))); labelmzp = datachannel(strncmp('MZP', datachannel, length('MZP'))); case {'bti', 'bti248', 'bti248grad', 'bti148', 'bti248_planar', 'bti148_planar'} % all 4D-BTi MEG channels start with "A" % all 4D-BTi reference channels start with M or G labelmeg = datachannel(myregexp('^A[0-9]+$', datachannel)); labelmegref = [datachannel(myregexp('^M[CLR][xyz][aA]*$', datachannel)); datachannel(myregexp('^G[xyz][xyz]A$', datachannel)); datachannel(myregexp('^M[xyz][aA]*$', datachannel))]; labelmegrefa = datachannel(~cellfun(@isempty,strfind(datachannel, 'a'))); labelmegrefc = datachannel(strncmp('MC', datachannel, 2)); labelmegrefg = datachannel(myregexp('^G[xyz][xyz]A$', datachannel)); labelmegrefl = datachannel(strncmp('ML', datachannel, 2)); labelmegrefr = datachannel(strncmp('MR', datachannel, 2)); labelmegrefm = datachannel(myregexp('^M[xyz][aA]*$', datachannel)); case {'neuromag122' 'neuromag122alt', 'neuromag122_combined'} % all neuromag MEG channels start with MEG % all neuromag EEG channels start with EEG labelmeg = datachannel(strncmp('MEG', datachannel, length('MEG'))); labeleeg = datachannel(strncmp('EEG', datachannel, length('EEG'))); case {'neuromag306' 'neuromag306alt', 'neuromag306_combined'} % all neuromag MEG channels start with MEG % all neuromag EEG channels start with EEG % all neuromag-306 gradiometers follow pattern MEG*2,MEG*3 % all neuromag-306 magnetometers follow pattern MEG*1 labelmeg = datachannel(strncmp('MEG', datachannel, length('MEG'))); labeleeg = datachannel(strncmp('EEG', datachannel, length('EEG'))); labelmeggrad = labelmeg(~cellfun(@isempty, regexp(labelmeg, '^MEG.*[23]$'))); labelmegmag = labelmeg(~cellfun(@isempty, regexp(labelmeg, '^MEG.*1$'))); case {'ant128', 'biosemi64', 'biosemi128', 'biosemi256', 'egi32', 'egi64', 'egi128', 'egi256', 'eeg1020', 'eeg1010', 'eeg1005', 'ext1020'} % use an external helper function to define the list with EEG channel names labeleeg = ft_senslabel(ft_senstype(datachannel)); case {'itab153'} % all itab MEG channels start with MAG labelmeg = datachannel(strncmp('MAG', datachannel, length('MAG'))); end % switch ft_senstype % figure out if there are bad channels or channel groups that should be excluded findbadchannel = strncmp('-', channel, length('-')); % bad channels start with '-' badchannel = channel(findbadchannel); if ~isempty(badchannel) for i=1:length(badchannel) badchannel{i} = badchannel{i}(2:end); % remove the '-' from the channel label end badchannel = ft_channelselection(badchannel, datachannel); % support exclusion of channel groups end % determine if any of the known groups is mentioned in the channel list findall = find(strcmp(channel, 'all')); % findreg (for the wildcards) is dealt with in the channel group specification above findmeg = find(strcmpi(channel, 'MEG')); findemg = find(strcmpi(channel, 'EMG')); findecg = find(strcmpi(channel, 'ECG')); findeeg = find(strcmpi(channel, 'EEG')); findeeg1020 = find(strcmpi(channel, 'EEG1020')); findeeg1010 = find(strcmpi(channel, 'EEG1010')); findeeg1005 = find(strcmpi(channel, 'EEG1005')); findeegchwilla = find(strcmpi(channel, 'EEGCHWILLA')); findeegbham = find(strcmpi(channel, 'EEGBHAM')); findeegref = find(strcmpi(channel, 'EEGREF')); findmegref = find(strcmpi(channel, 'MEGREF')); findmeggrad = find(strcmpi(channel, 'MEGGRAD')); findmegmag = find(strcmpi(channel, 'MEGMAG')); findmegrefa = find(strcmpi(channel, 'MEGREFA')); findmegrefc = find(strcmpi(channel, 'MEGREFC')); findmegrefg = find(strcmpi(channel, 'MEGREFG')); findmegrefl = find(strcmpi(channel, 'MEGREFL')); findmegrefr = find(strcmpi(channel, 'MEGREFR')); findmegrefm = find(strcmpi(channel, 'MEGREFM')); findeog = find(strcmpi(channel, 'EOG')); findmz = find(strcmp(channel, 'MZ' )); findml = find(strcmp(channel, 'ML' )); findmr = find(strcmp(channel, 'MR' )); findmlc = find(strcmp(channel, 'MLC')); findmlf = find(strcmp(channel, 'MLF')); findmlo = find(strcmp(channel, 'MLO')); findmlp = find(strcmp(channel, 'MLP')); findmlt = find(strcmp(channel, 'MLT')); findmrc = find(strcmp(channel, 'MRC')); findmrf = find(strcmp(channel, 'MRF')); findmro = find(strcmp(channel, 'MRO')); findmrp = find(strcmp(channel, 'MRP')); findmrt = find(strcmp(channel, 'MRT')); findmzc = find(strcmp(channel, 'MZC')); findmzf = find(strcmp(channel, 'MZF')); findmzo = find(strcmp(channel, 'MZO')); findmzp = find(strcmp(channel, 'MZP')); findnirs = find(strcmpi(channel, 'NIRS')); findlfp = find(strcmpi(channel, 'lfp')); findmua = find(strcmpi(channel, 'mua')); findspike = find(strcmpi(channel, 'spike')); findgui = find(strcmpi(channel, 'gui')); % remove any occurences of groups in the channel list channel([ findall findreg findmeg findemg findecg findeeg findeeg1020 findeeg1010 findeeg1005 findeegchwilla findeegbham findeegref findmegref findmeggrad findmegmag findeog findmz findml findmr findmlc findmlf findmlo findmlp findmlt findmrc findmrf findmro findmrp findmrt findmzc findmzf findmzo findmzp findlfp findmua findspike findnirs findgui ]) = []; % add the full channel labels to the channel list if findall, channel = [channel; labelall]; end if findreg, channel = [channel; labelreg]; end if findmeg, channel = [channel; labelmeg]; end if findecg, channel = [channel; labelecg]; end if findemg, channel = [channel; labelemg]; end if findeeg, channel = [channel; labeleeg]; end if findeeg1020, channel = [channel; label1020]; end if findeeg1010, channel = [channel; label1010]; end if findeeg1005, channel = [channel; label1005]; end if findeegchwilla, channel = [channel; labelchwilla]; end if findeegbham, channel = [channel; labelbham]; end if findeegref, channel = [channel; labelref]; end if findmegref, channel = [channel; labelmegref]; end if findmeggrad, channel = [channel; labelmeggrad]; end if findmegmag, channel = [channel; labelmegmag]; end if findmegrefa, channel = [channel; labelmegrefa]; end if findmegrefc, channel = [channel; labelmegrefc]; end if findmegrefg, channel = [channel; labelmegrefg]; end if findmegrefl, channel = [channel; labelmegrefl]; end if findmegrefr, channel = [channel; labelmegrefr]; end if findmegrefm, channel = [channel; labelmegrefm]; end if findeog, channel = [channel; labeleog]; end if findmz , channel = [channel; labelmz ]; end if findml , channel = [channel; labelml ]; end if findmr , channel = [channel; labelmr ]; end if findmlc, channel = [channel; labelmlc]; end if findmlf, channel = [channel; labelmlf]; end if findmlo, channel = [channel; labelmlo]; end if findmlp, channel = [channel; labelmlp]; end if findmlt, channel = [channel; labelmlt]; end if findmrc, channel = [channel; labelmrc]; end if findmrf, channel = [channel; labelmrf]; end if findmro, channel = [channel; labelmro]; end if findmrp, channel = [channel; labelmrp]; end if findmrt, channel = [channel; labelmrt]; end if findmzc, channel = [channel; labelmzc]; end if findmzf, channel = [channel; labelmzf]; end if findmzo, channel = [channel; labelmzo]; end if findmzp, channel = [channel; labelmzp]; end if findlfp, channel = [channel; labellfp]; end if findmua, channel = [channel; labelmua]; end if findspike, channel = [channel; labelspike]; end if findnirs, channel = [channel; labelnirs]; end % remove channel labels that have been excluded by the user badindx = match_str(channel, badchannel); channel(badindx) = []; % remove channel labels that are not present in the data chanindx = match_str(channel, datachannel); channel = channel(chanindx); if findgui indx = select_channel_list(datachannel, match_str(datachannel, channel), 'Select channels'); channel = datachannel(indx); end % remove channels that occur more than once, this sorts the channels alphabetically channel = unique(channel); if isempty(channel) && ~recursion % try whether only lowercase channel labels makes a difference recursion = true; channel = ft_channelselection(desired, lower(datachannel)); recursion = false; % undo the conversion to lowercase, this sorts the channels alphabetically [c, ia, ib] = intersect(channel, lower(datachannel)); channel = datachannel(ib); end if isempty(channel) && ~recursion % try whether only uppercase channel labels makes a difference recursion = true; channel = ft_channelselection(desired, upper(datachannel)); recursion = false; % undo the conversion to uppercase, this sorts the channels alphabetically [c, ia, ib] = intersect(channel, lower(datachannel)); channel = datachannel(ib); end % undo the sorting, make the order identical to that of the data channels [tmp, indx] = match_str(datachannel, channel); channel = channel(indx); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function match = myregexp(pat, list) match = false(size(list)); for i=1:numel(list) match(i) = ~isempty(regexp(list{i}, pat, 'once')); end
github
lcnbeapp/beapp-master
ft_datatype_sens.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_datatype_sens.m
22,743
utf_8
fab01996ef9a98c643827fb2767fbaf3
function [sens] = ft_datatype_sens(sens, varargin) % FT_DATATYPE_SENS describes the FieldTrip structure that represents an EEG, ECoG, or % MEG sensor array. This structure is commonly called "elec" for EEG, "grad" for MEG, % "opto" for NIRS, or general "sens" for either one. % % For all sensor types a distinction should be made between the channel (i.e. the % output of the transducer that is A/D converted) and the sensor, which may have some % spatial extent. E.g. with EEG you can have a bipolar channel, where the position of % the channel can be represented as in between the position of the two electrodes. % % The structure for MEG gradiometers and/or magnetometers contains % sens.label = Mx1 cell-array with channel labels % sens.chanpos = Mx3 matrix with channel positions % sens.chanori = Mx3 matrix with channel orientations, used for synthetic planar gradient computation % sens.tra = MxN matrix to combine coils into channels % sens.coilpos = Nx3 matrix with coil positions % sens.coilori = Nx3 matrix with coil orientations % sens.balance = structure containing info about the balancing, See FT_APPLY_MONTAGE % and optionally % sens.chanposold = Mx3 matrix with original channel positions (in case % sens.chanpos has been updated to contain NaNs, e.g. % after ft_componentanalysis) % sens.chanoriold = Mx3 matrix with original channel orientations % sens.labelold = Mx1 cell-array with original channel labels % % The structure for EEG or ECoG channels contains % sens.label = Mx1 cell-array with channel labels % sens.elecpos = Nx3 matrix with electrode positions % sens.chanpos = Mx3 matrix with channel positions (often the same as electrode positions) % sens.tra = MxN matrix to combine electrodes into channels % In case sens.tra is not present in the EEG sensor array, the channels % are assumed to be average referenced. % % The structure for NIRS channels contains % sens.optopos = contains information about the position of the optodes % sens.optotype = contains information about the type of optode (receiver or transmitter) % sens.chanpos = contains information about the position of the channels (i.e. average of optopos) % sens.tra = NxC matrix, boolean, contains information about how receiver and transmitter form channels % sens.wavelength = 1xM vector of all wavelengths that were used % sens.transmits = NxM matrix, boolean, where N is the number of optodes and M the number of wavelengths per transmitter. Specifies what optode is transmitting at what wavelength (or nothing at all, which indicates that it is a receiver) % sens.laserstrength = 1xM vector of the strength of the emitted light of the lasers % % The following fields apply to MEG and EEG % sens.chantype = Mx1 cell-array with the type of the channel, see FT_CHANTYPE % sens.chanunit = Mx1 cell-array with the units of the channel signal, e.g. 'V', 'fT' or 'T/cm', see FT_CHANUNIT % % The following fields are optional % sens.type = string with the type of acquisition system, see FT_SENSTYPE % sens.fid = structure with fiducial information % % Historical fields: % pnt, pos, ori, pnt1, pnt2 % % Revision history: % (2016/latest) The chantype and chanunit have become required fields. % Original channel details are specified with the suffix "old" rather than "org". % All numeric values are represented in double precision. % It is possible to convert the amplitude and distance units (e.g. from T to fT and % from m to mm) and it is possible to express planar and axial gradiometer channels % either in units of amplitude or in units of amplitude/distance (i.e. proper % gradient). % % (2011v2) The chantype and chanunit have been added for MEG. % % (2011v1) To facilitate determining the position of channels (e.g. for plotting) % in case of balanced MEG or bipolar EEG, an explicit distinction has been made % between chanpos+chanori and coilpos+coilori (for MEG) and chanpos and elecpos % (for EEG). The pnt and ori fields are removed % % (2010) Added support for bipolar or otherwise more complex linear combinations % of EEG electrodes using sens.tra, similar to MEG. % % (2009) Noice reduction has been added for MEG systems in the balance field. % % (2006) The optional fields sens.type and sens.unit were added. % % (2003) The initial version was defined, which looked like this for EEG % sens.pnt = Mx3 matrix with electrode positions % sens.label = Mx1 cell-array with channel labels % and like this for MEG % sens.pnt = Nx3 matrix with coil positions % sens.ori = Nx3 matrix with coil orientations % sens.tra = MxN matrix to combine coils into channels % sens.label = Mx1 cell-array with channel labels % % See also FT_READ_SENS, FT_SENSTYPE, FT_CHANTYPE, FT_APPLY_MONTAGE, CTF2GRAD, FIF2GRAD, % BTI2GRAD, YOKOGAWA2GRAD, ITAB2GRAD % Copyright (C) 2011-2016, Robert Oostenveld & Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % undocumented options for the 2016 format % amplitude = string, can be 'T' or 'fT' % distance = string, can be 'm', 'cm' or 'mm' % scaling = string, can be 'amplitude' or 'amplitude/distance' % these are for remembering the type on subsequent calls with the same input arguments persistent previous_argin previous_argout current_argin = [{sens} varargin]; if isequal(current_argin, previous_argin) % don't do the whole cheking again, but return the previous output from cache sens = previous_argout{1}; return end % get the optional input arguments, which should be specified as key-value pairs version = ft_getopt(varargin, 'version', 'latest'); amplitude = ft_getopt(varargin, 'amplitude'); % should be 'V' 'uV' 'T' 'mT' 'uT' 'nT' 'pT' 'fT' distance = ft_getopt(varargin, 'distance'); % should be 'm' 'dm' 'cm' 'mm' scaling = ft_getopt(varargin, 'scaling'); % should be 'amplitude' or 'amplitude/distance', the default depends on the senstype if ~isempty(amplitude) && ~any(strcmp(amplitude, {'V' 'uV' 'T' 'mT' 'uT' 'nT' 'pT' 'fT'})) error('unsupported unit of amplitude "%s"', amplitude); end if ~isempty(distance) && ~any(strcmp(distance, {'m' 'dm' 'cm' 'mm'})) error('unsupported unit of distance "%s"', distance); end if strcmp(version, 'latest') version = '2016'; end if isempty(sens) return; end % this is needed further down nchan = length(sens.label); % there are many cases which deal with either eeg or meg ismeg = ft_senstype(sens, 'meg'); switch version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case '2016' % update it to the previous standard version sens = ft_datatype_sens(sens, 'version', '2011v2'); % ensure that all numbers are represented in double precision sens = ft_struct2double(sens); % use "old/new" rather than "org/new" if isfield(sens, 'labelorg') sens.labelold = sens.labelorg; sens = rmfield(sens, 'labelorg'); end if isfield(sens, 'chantypeorg') sens.chantypeold = sens.chantypeorg; sens = rmfield(sens, 'chantypeorg'); end if isfield(sens, 'chanuniteorg') sens.chanunitold = sens.chanunitorg; sens = rmfield(sens, 'chanunitorg'); end if isfield(sens, 'chanposorg') sens.chanposold = sens.chanposorg; sens = rmfield(sens, 'chanposorg'); end if isfield(sens, 'chanoriorg') sens.chanoriold = sens.chanoriorg; sens = rmfield(sens, 'chanoriorg'); end % in version 2011v2 this was optional, now it is required if ~isfield(sens, 'chantype') || all(strcmp(sens.chantype, 'unknown')) sens.chantype = ft_chantype(sens); end % in version 2011v2 this was optional, now it is required if ~isfield(sens, 'chanunit') || all(strcmp(sens.chanunit, 'unknown')) sens.chanunit = ft_chanunit(sens); end if ~isempty(distance) % update the units of distance, this also updates the tra matrix sens = ft_convert_units(sens, distance); else % determine the default, this may be needed to set the scaling distance = sens.unit; end if ~isempty(amplitude) && isfield(sens, 'tra') % update the tra matrix for the units of amplitude, this ensures that % the leadfield values remain consistent with the units for i=1:nchan if ~isempty(regexp(sens.chanunit{i}, 'm$', 'once')) % this channel is expressed as amplitude per distance sens.tra(i,:) = sens.tra(i,:) * ft_scalingfactor(sens.chanunit{i}, [amplitude '/' distance]); sens.chanunit{i} = [amplitude '/' distance]; elseif ~isempty(regexp(sens.chanunit{i}, '[T|V]$', 'once')) % this channel is expressed as amplitude sens.tra(i,:) = sens.tra(i,:) * ft_scalingfactor(sens.chanunit{i}, amplitude); sens.chanunit{i} = amplitude; else error('unexpected channel unit "%s" in channel %d', sens.chanunit{i}, i); end end else % determine the default amplityde, this may be needed to set the scaling if any(~cellfun(@isempty, regexp(sens.chanunit, '^T'))) % one of the channel units starts with T amplitude = 'T'; elseif any(~cellfun(@isempty, regexp(sens.chanunit, '^fT'))) % one of the channel units starts with fT amplitude = 'fT'; elseif any(~cellfun(@isempty, regexp(sens.chanunit, '^V'))) % one of the channel units starts with V amplitude = 'V'; elseif any(~cellfun(@isempty, regexp(sens.chanunit, '^uV'))) % one of the channel units starts with uV amplitude = 'uV'; else % this unknown amplitude will cause a problem if the scaling needs to be changed between amplitude and amplitude/distance amplitude = 'unknown'; end end % perform some sanity checks if ismeg sel_m = ~cellfun(@isempty, regexp(sens.chanunit, '/m$')); sel_dm = ~cellfun(@isempty, regexp(sens.chanunit, '/dm$')); sel_cm = ~cellfun(@isempty, regexp(sens.chanunit, '/cm$')); sel_mm = ~cellfun(@isempty, regexp(sens.chanunit, '/mm$')); if strcmp(sens.unit, 'm') && (any(sel_dm) || any(sel_cm) || any(sel_mm)) error('inconsistent units in input gradiometer'); elseif strcmp(sens.unit, 'dm') && (any(sel_m) || any(sel_cm) || any(sel_mm)) error('inconsistent units in input gradiometer'); elseif strcmp(sens.unit, 'cm') && (any(sel_m) || any(sel_dm) || any(sel_mm)) error('inconsistent units in input gradiometer'); elseif strcmp(sens.unit, 'mm') && (any(sel_m) || any(sel_dm) || any(sel_cm)) error('inconsistent units in input gradiometer'); end % the default should be amplitude/distance for neuromag and amplitude for all others if isempty(scaling) if ft_senstype(sens, 'neuromag') scaling = 'amplitude/distance'; elseif ft_senstype(sens, 'yokogawa440') warning('asuming that the default scaling should be amplitude rather than amplitude/distance'); scaling = 'amplitude'; else scaling = 'amplitude'; end end % update the gradiometer scaling if strcmp(scaling, 'amplitude') && isfield(sens, 'tra') for i=1:nchan if strcmp(sens.chanunit{i}, [amplitude '/' distance]) % this channel is expressed as amplitude per distance coil = find(abs(sens.tra(i,:))~=0); if length(coil)~=2 error('unexpected number of coils contributing to channel %d', i); end baseline = norm(sens.coilpos(coil(1),:) - sens.coilpos(coil(2),:)); sens.tra(i,:) = sens.tra(i,:)*baseline; % scale with the baseline distance sens.chanunit{i} = amplitude; elseif strcmp(sens.chanunit{i}, amplitude) % no conversion needed else % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3144 ft_warning(sprintf('unexpected channel unit "%s" in channel %d', sens.chanunit{i}, i)); end % if end % for elseif strcmp(scaling, 'amplitude/distance') && isfield(sens, 'tra') for i=1:nchan if strcmp(sens.chanunit{i}, amplitude) % this channel is expressed as amplitude coil = find(abs(sens.tra(i,:))~=0); if length(coil)==1 || strcmp(sens.chantype{i}, 'megmag') % this is a magnetometer channel, no conversion needed continue elseif length(coil)~=2 error('unexpected number of coils (%d) contributing to channel %s (%d)', length(coil), sens.label{i}, i); end baseline = norm(sens.coilpos(coil(1),:) - sens.coilpos(coil(2),:)); sens.tra(i,:) = sens.tra(i,:)/baseline; % scale with the baseline distance sens.chanunit{i} = [amplitude '/' distance]; elseif strcmp(sens.chanunit{i}, [amplitude '/' distance]) % no conversion needed else % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3144 ft_warning(sprintf('unexpected channel unit "%s" in channel %d', sens.chanunit{i}, i)); end % if end % for end % if strcmp scaling else sel_m = ~cellfun(@isempty, regexp(sens.chanunit, '/m$')); sel_dm = ~cellfun(@isempty, regexp(sens.chanunit, '/dm$')); sel_cm = ~cellfun(@isempty, regexp(sens.chanunit, '/cm$')); sel_mm = ~cellfun(@isempty, regexp(sens.chanunit, '/mm$')); if any(sel_m | sel_dm | sel_cm | sel_mm) error('scaling of amplitude/distance has not been considered yet for EEG'); end end % if iseeg or ismeg %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case '2011v2' if ~isempty(amplitude) || ~isempty(distance) || ~isempty(scaling) warning('amplitude, distance and scaling are not supported for version "%s"', version); end % This speeds up subsequent calls to ft_senstype and channelposition. % However, if it is not more precise than MEG or EEG, don't keep it in % the output (see further down). if ~isfield(sens, 'type') sens.type = ft_senstype(sens); end if isfield(sens, 'pnt') if ismeg % sensor description is a MEG sensor-array, containing oriented coils sens.coilpos = sens.pnt; sens = rmfield(sens, 'pnt'); sens.coilori = sens.ori; sens = rmfield(sens, 'ori'); else % sensor description is something else, EEG/ECoG etc sens.elecpos = sens.pnt; sens = rmfield(sens, 'pnt'); end end if ~isfield(sens, 'chanpos') if ismeg % sensor description is a MEG sensor-array, containing oriented coils [chanpos, chanori, lab] = channelposition(sens); % the channel order can be different in the two representations [selsens, selpos] = match_str(sens.label, lab); sens.chanpos = nan(length(sens.label), 3); sens.chanori = nan(length(sens.label), 3); % insert the determined position/orientation on the appropriate rows sens.chanpos(selsens,:) = chanpos(selpos,:); sens.chanori(selsens,:) = chanori(selpos,:); if length(selsens)~=length(sens.label) warning('cannot determine the position and orientation for all channels'); end else % sensor description is something else, EEG/ECoG etc % note that chanori will be all NaNs [chanpos, chanori, lab] = channelposition(sens); % the channel order can be different in the two representations [selsens, selpos] = match_str(sens.label, lab); sens.chanpos = nan(length(sens.label), 3); % insert the determined position/orientation on the appropriate rows sens.chanpos(selsens,:) = chanpos(selpos,:); if length(selsens)~=length(sens.label) warning('cannot determine the position and orientation for all channels'); end end end if ~isfield(sens, 'chantype') || all(strcmp(sens.chantype, 'unknown')) if ismeg sens.chantype = ft_chantype(sens); else % for EEG it is not required end end if ~isfield(sens, 'unit') % this should be done prior to calling ft_chanunit, since ft_chanunit uses this for planar neuromag channels sens = ft_convert_units(sens); end if ~isfield(sens, 'chanunit') || all(strcmp(sens.chanunit, 'unknown')) if ismeg sens.chanunit = ft_chanunit(sens); else % for EEG it is not required end end if any(strcmp(sens.type, {'meg', 'eeg', 'magnetometer', 'electrode', 'unknown'})) % this is not sufficiently informative, so better remove it % see also http://bugzilla.fcdonders.nl/show_bug.cgi?id=1806 sens = rmfield(sens, 'type'); end if size(sens.chanpos,1)~=length(sens.label) || ... isfield(sens, 'tra') && size(sens.tra,1)~=length(sens.label) || ... isfield(sens, 'tra') && isfield(sens, 'elecpos') && size(sens.tra,2)~=size(sens.elecpos,1) || ... isfield(sens, 'tra') && isfield(sens, 'coilpos') && size(sens.tra,2)~=size(sens.coilpos,1) || ... isfield(sens, 'tra') && isfield(sens, 'coilori') && size(sens.tra,2)~=size(sens.coilori,1) || ... isfield(sens, 'chanpos') && size(sens.chanpos,1)~=length(sens.label) || ... isfield(sens, 'chanori') && size(sens.chanori,1)~=length(sens.label) error('inconsistent number of channels in sensor description'); end if ismeg % ensure that the magnetometer/gradiometer balancing is specified if ~isfield(sens, 'balance') || ~isfield(sens.balance, 'current') sens.balance.current = 'none'; end % try to add the chantype and chanunit to the CTF G1BR montage if isfield(sens, 'balance') && isfield(sens.balance, 'G1BR') && ~isfield(sens.balance.G1BR, 'chantype') sens.balance.G1BR.chantypeorg = repmat({'unknown'}, size(sens.balance.G1BR.labelorg)); sens.balance.G1BR.chanunitorg = repmat({'unknown'}, size(sens.balance.G1BR.labelorg)); sens.balance.G1BR.chantypenew = repmat({'unknown'}, size(sens.balance.G1BR.labelnew)); sens.balance.G1BR.chanunitnew = repmat({'unknown'}, size(sens.balance.G1BR.labelnew)); % the synthetic gradient montage does not fundamentally change the chantype or chanunit [sel1, sel2] = match_str(sens.balance.G1BR.labelorg, sens.label); sens.balance.G1BR.chantypeorg(sel1) = sens.chantype(sel2); sens.balance.G1BR.chanunitorg(sel1) = sens.chanunit(sel2); [sel1, sel2] = match_str(sens.balance.G1BR.labelnew, sens.label); sens.balance.G1BR.chantypenew(sel1) = sens.chantype(sel2); sens.balance.G1BR.chanunitnew(sel1) = sens.chanunit(sel2); end % idem for G2BR if isfield(sens, 'balance') && isfield(sens.balance, 'G2BR') && ~isfield(sens.balance.G2BR, 'chantype') sens.balance.G2BR.chantypeorg = repmat({'unknown'}, size(sens.balance.G2BR.labelorg)); sens.balance.G2BR.chanunitorg = repmat({'unknown'}, size(sens.balance.G2BR.labelorg)); sens.balance.G2BR.chantypenew = repmat({'unknown'}, size(sens.balance.G2BR.labelnew)); sens.balance.G2BR.chanunitnew = repmat({'unknown'}, size(sens.balance.G2BR.labelnew)); % the synthetic gradient montage does not fundamentally change the chantype or chanunit [sel1, sel2] = match_str(sens.balance.G2BR.labelorg, sens.label); sens.balance.G2BR.chantypeorg(sel1) = sens.chantype(sel2); sens.balance.G2BR.chanunitorg(sel1) = sens.chanunit(sel2); [sel1, sel2] = match_str(sens.balance.G2BR.labelnew, sens.label); sens.balance.G2BR.chantypenew(sel1) = sens.chantype(sel2); sens.balance.G2BR.chanunitnew(sel1) = sens.chanunit(sel2); end % idem for G3BR if isfield(sens, 'balance') && isfield(sens.balance, 'G3BR') && ~isfield(sens.balance.G3BR, 'chantype') sens.balance.G3BR.chantypeorg = repmat({'unknown'}, size(sens.balance.G3BR.labelorg)); sens.balance.G3BR.chanunitorg = repmat({'unknown'}, size(sens.balance.G3BR.labelorg)); sens.balance.G3BR.chantypenew = repmat({'unknown'}, size(sens.balance.G3BR.labelnew)); sens.balance.G3BR.chanunitnew = repmat({'unknown'}, size(sens.balance.G3BR.labelnew)); % the synthetic gradient montage does not fundamentally change the chantype or chanunit [sel1, sel2] = match_str(sens.balance.G3BR.labelorg, sens.label); sens.balance.G3BR.chantypeorg(sel1) = sens.chantype(sel2); sens.balance.G3BR.chanunitorg(sel1) = sens.chanunit(sel2); [sel1, sel2] = match_str(sens.balance.G3BR.labelnew, sens.label); sens.balance.G3BR.chantypenew(sel1) = sens.chantype(sel2); sens.balance.G3BR.chanunitnew(sel1) = sens.chanunit(sel2); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% otherwise error('converting to version %s is not supported', version); end % switch % this makes the display with the "disp" command look better sens = sortfieldnames(sens); % remember the current input and output arguments, so that they can be % reused on a subsequent call in case the same input argument is given current_argout = {sens}; previous_argin = current_argin; previous_argout = current_argout; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function b = sortfieldnames(a) fn = sort(fieldnames(a)); for i=1:numel(fn) b.(fn{i}) = a.(fn{i}); end
github
lcnbeapp/beapp-master
ft_datatype.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_datatype.m
10,068
utf_8
0a0165e618d5828bde6132b5a5a7a2f2
function [type, dimord] = ft_datatype(data, desired) % FT_DATATYPE determines the type of data represented in a FieldTrip data % structure and returns a string with raw, freq, timelock source, comp, % spike, source, volume, dip, montage, event. % % Use as % [type, dimord] = ft_datatype(data) % [status] = ft_datatype(data, desired) % % See also FT_DATATYPE_COMP, FT_DATATYPE_FREQ, FT_DATATYPE_MVAR, % FT_DATATYPE_SEGMENTATION, FT_DATATYPE_PARCELLATION, FT_DATATYPE_SOURCE, % FT_DATATYPE_TIMELOCK, FT_DATATYPE_DIP, FT_DATATYPE_HEADMODEL, % FT_DATATYPE_RAW, FT_DATATYPE_SENS, FT_DATATYPE_SPIKE, FT_DATATYPE_VOLUME % Copyright (C) 2008-2015, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if nargin<2 desired = []; end % determine the type of input data israw = isfield(data, 'label') && isfield(data, 'time') && isa(data.time, 'cell') && isfield(data, 'trial') && isa(data.trial, 'cell') && ~isfield(data,'trialtime'); isfreq = (isfield(data, 'label') || isfield(data, 'labelcmb')) && isfield(data, 'freq') && ~isfield(data,'trialtime') && ~isfield(data,'origtrial'); %&& (isfield(data, 'powspctrm') || isfield(data, 'crsspctrm') || isfield(data, 'cohspctrm') || isfield(data, 'fourierspctrm') || isfield(data, 'powcovspctrm')); istimelock = isfield(data, 'label') && isfield(data, 'time') && ~isfield(data, 'freq') && ~isfield(data,'timestamp') && ~isfield(data,'trialtime') && ~(isfield(data, 'trial') && iscell(data.trial)) && ~isfield(data, 'pos'); %&& ((isfield(data, 'avg') && isnumeric(data.avg)) || (isfield(data, 'trial') && isnumeric(data.trial) || (isfield(data, 'cov') && isnumeric(data.cov)))); iscomp = isfield(data, 'label') && isfield(data, 'topo') || isfield(data, 'topolabel'); isvolume = isfield(data, 'transform') && isfield(data, 'dim') && ~isfield(data, 'pos'); issource = (isfield(data, 'pos') || isfield(data, 'pnt')) && isstruct(data) && numel(data)==1; % pnt is deprecated, this does not apply to a mesh array ismesh = (isfield(data, 'pos') || isfield(data, 'pnt')) && (isfield(data, 'tri') || isfield(data, 'tet') || isfield(data, 'hex')); % pnt is deprecated isdip = isfield(data, 'dip'); ismvar = isfield(data, 'dimord') && ~isempty(strfind(data.dimord, 'lag')); isfreqmvar = isfield(data, 'freq') && isfield(data, 'transfer'); ischan = check_chan(data); issegmentation = check_segmentation(data); isparcellation = check_parcellation(data); ismontage = isfield(data, 'labelorg') && isfield(data, 'labelnew') && isfield(data, 'tra'); isevent = isfield(data, 'type') && isfield(data, 'value') && isfield(data, 'sample') && isfield(data, 'offset') && isfield(data, 'duration'); isheadmodel = false; % FIXME this is not yet implemented if issource && isstruct(data) && numel(data)>1 % this applies to struct arrays with meshes, i.e. with a pnt+tri issource = false; end if ~isfreq % this applies to a freq structure from 2003 up to early 2006 isfreq = all(isfield(data, {'foi', 'label', 'dimord'})) && ~isempty(strfind(data.dimord, 'frq')); end % check if it is a spike structure spk_hastimestamp = isfield(data,'label') && isfield(data, 'timestamp') && isa(data.timestamp, 'cell'); spk_hastrials = isfield(data,'label') && isfield(data, 'time') && isa(data.time, 'cell') && isfield(data, 'trial') && isa(data.trial, 'cell') && isfield(data, 'trialtime') && isa(data.trialtime, 'numeric'); spk_hasorig = isfield(data,'origtrial') && isfield(data,'origtime'); % for compatibility isspike = isfield(data, 'label') && (spk_hastimestamp || spk_hastrials || spk_hasorig); % check if it is a sensor array isgrad = isfield(data, 'label') && isfield(data, 'coilpos') && isfield(data, 'coilori'); iselec = isfield(data, 'label') && isfield(data, 'elecpos'); if isspike type = 'spike'; elseif israw && iscomp type = 'raw+comp'; elseif istimelock && iscomp type = 'timelock+comp'; elseif isfreq && iscomp type = 'freq+comp'; elseif israw type = 'raw'; elseif iscomp type = 'comp'; elseif isfreqmvar % freqmvar should conditionally go before freq, otherwise the returned ft_datatype will be freq in the case of frequency mvar data type = 'freqmvar'; elseif isfreq type = 'freq'; elseif ismvar type = 'mvar'; elseif isdip % dip should conditionally go before timelock, otherwise the ft_datatype will be timelock type = 'dip'; elseif istimelock type = 'timelock'; elseif isvolume && issegmentation type = 'volume+label'; elseif isvolume type = 'volume'; elseif ismesh && isparcellation type = 'mesh+label'; elseif ismesh type = 'mesh'; elseif issource && isparcellation type = 'source+label'; elseif issource type = 'source'; elseif ischan % this results from avgovertime/avgoverfreq after timelockstatistics or freqstatistics type = 'chan'; elseif iselec type = 'elec'; elseif isgrad type = 'grad'; elseif ismontage type = 'montage'; elseif isevent type = 'event'; else type = 'unknown'; end if nargin>1 % return a boolean value switch desired case 'raw' type = any(strcmp(type, {'raw', 'raw+comp'})); case 'timelock' type = any(strcmp(type, {'timelock', 'timelock+comp'})); case 'freq' type = any(strcmp(type, {'freq', 'freq+comp'})); case 'comp' type = any(strcmp(type, {'comp', 'raw+comp', 'timelock+comp', 'freq+comp'})); case 'volume' type = any(strcmp(type, {'volume', 'volume+label'})); case 'source' type = any(strcmp(type, {'source', 'source+label', 'mesh', 'mesh+label'})); % a single mesh qualifies as source structure type = type && isstruct(data) && numel(data)==1; % an array of meshes does not qualify case 'mesh' type = any(strcmp(type, {'mesh', 'mesh+label'})); case 'segmentation' type = strcmp(type, 'volume+label'); case 'parcellation' type = any(strcmp(type, {'source+label' 'mesh+label'})); case 'sens' type = any(strcmp(type, {'elec', 'grad'})); otherwise type = strcmp(type, desired); end % switch end if nargout>1 % FIXME this should be replaced with getdimord in the calling code % also return the dimord of the input data if isfield(data, 'dimord') dimord = data.dimord; else dimord = 'unknown'; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [res] = check_chan(data) if ~isstruct(data) || any(isfield(data, {'time', 'freq', 'pos', 'dim', 'transform'})) res = false; elseif isfield(data, 'dimord') && any(strcmp(data.dimord, {'chan', 'chan_chan'})) res = true; else res = false; fn = fieldnames(data); for i=1:numel(fn) if isfield(data, [fn{i} 'dimord']) && any(strcmp(data.([fn{i} 'dimord']), {'chan', 'chan_chan'})) res = true; break; end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [res] = check_segmentation(volume) res = false; if ~isfield(volume, 'dim') && ~isfield(volume, 'transform') return end if isfield(volume, 'pos') return end if any(isfield(volume, {'seg', 'csf', 'white', 'gray', 'skull', 'scalp', 'brain'})) res = true; return end fn = fieldnames(volume); isboolean = []; cnt = 0; for i=1:length(fn) if isfield(volume, [fn{i} 'label']) res = true; return else if (islogical(volume.(fn{i})) || isnumeric(volume.(fn{i}))) && isequal(size(volume.(fn{i})),volume.dim) cnt = cnt+1; if islogical(volume.(fn{i})) isboolean(cnt) = true; else isboolean(cnt) = false; end end end end if ~isempty(isboolean) res = all(isboolean); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [res] = check_parcellation(source) res = false; if numel(source)>1 % this applies to struct arrays with meshes, i.e. with a pnt+tri return end if ~isfield(source, 'pos') return end fn = fieldnames(source); fb = false(size(fn)); npos = size(source.pos,1); for i=1:numel(fn) % for each of the fields check whether it might be a logical array with the size of the number of sources tmp = source.(fn{i}); fb(i) = numel(tmp)==npos && islogical(tmp); end if sum(fb)>1 % the presence of multiple logical arrays suggests it is a parcellation res = true; end if res == false % check if source has more D elements check = 0; for i = 1: length(fn) fname = fn{i}; switch fname case 'tri' npos = size(source.tri,1); check = 1; case 'hex' npos = size(source.hex,1); check = 1; case 'tet' npos = size(source.tet,1); check = 1; end end if check == 1 % check if elements are labelled for i=1:numel(fn) tmp = source.(fn{i}); fb(i) = numel(tmp)==npos && islogical(tmp); end if sum(fb)>1 res = true; end end end fn = fieldnames(source); for i=1:length(fn) if isfield(source, [fn{i} 'label']) && isnumeric(source.(fn{i})) res = true; return end end
github
lcnbeapp/beapp-master
ft_checkconfig.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_checkconfig.m
25,828
utf_8
dc8f84be30850438906132f672928729
function [cfg] = ft_checkconfig(cfg, varargin) % FT_CHECKCONFIG checks the input cfg of the main FieldTrip functions % in three steps. % % 1: It checks whether the cfg contains all the required options, it gives % a warning when renamed or deprecated options are used, and it makes sure % no forbidden options are used. If necessary and possible, this function % will adjust the cfg to the input requirements. If the input cfg does NOT % correspond to the requirements, this function gives an elaborate warning % message. % % 2: It controls the relevant cfg options that are being passed on to other % functions, by putting them into substructures or converting them into the % required format. % % 3: It controls the output cfg (data.cfg) such that it only contains % relevant and used fields. The size of fields in the output cfg is also % controlled: fields exceeding a certain maximum size are emptied. % This part of the functionality is still under construction! % % Use as % [cfg] = ft_checkconfig(cfg, ...) % % The behaviour of checkconfig can be controlled by the following cfg options, % which can be set as global FieldTrip defaults (see FT_DEFAULTS) % cfg.checkconfig = 'pedantic', 'loose' or 'silent' (control the feedback behaviour of checkconfig) % cfg.trackconfig = 'cleanup', 'report' or 'off' % cfg.checksize = number in bytes, can be inf (set max size allowed for output cfg fields) % % Optional input arguments should be specified as key-value pairs and can include % renamed = {'old', 'new'} % list the old and new option % renamedval = {'opt', 'old', 'new'} % list option and old and new value % allowedval = {'opt', 'allowed1'...} % list of allowed values for a particular option, anything else will throw an error % required = {'opt1', 'opt2', etc.} % list the required options % allowed = {'opt1', 'opt2', etc.} % list the allowed options, all other options are forbidden % forbidden = {'opt1', 'opt2', etc.} % list the forbidden options, these result in an error % deprecated = {'opt1', 'opt2', etc.} % list the deprecated options % unused = {'opt1', 'opt2', etc.} % list the unused options, these will be removed and a warning is issued % createsubcfg = {'subname', etc.} % list the names of the subcfg % dataset2files = 'yes', 'no' % converts dataset into headerfile and datafile % index2logical = 'yes', 'no' % converts cfg.index or cfg.grid.index into logical representation % checksize = 'yes', 'no' % remove large fields from the cfg % trackconfig = 'on', 'off' % start/end config tracking % % See also FT_CHECKDATA, FT_DEFAULTS % Copyright (C) 2007-2014, Robert Oostenveld, Saskia Haegens % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ renamed = ft_getopt(varargin, 'renamed'); allowed = ft_getopt(varargin, 'allowed'); required = ft_getopt(varargin, 'required'); deprecated = ft_getopt(varargin, 'deprecated'); unused = ft_getopt(varargin, 'unused'); forbidden = ft_getopt(varargin, 'forbidden'); renamedval = ft_getopt(varargin, 'renamedval'); allowedval = ft_getopt(varargin, 'allowedval'); createsubcfg = ft_getopt(varargin, 'createsubcfg'); checkfilenames = ft_getopt(varargin, 'dataset2files'); checkinside = ft_getopt(varargin, 'index2logical', 'off'); checksize = ft_getopt(varargin, 'checksize', 'off'); trackconfig = ft_getopt(varargin, 'trackconfig'); if ~isempty(trackconfig) && strcmp(trackconfig, 'on') % infer from the user configuration whether tracking should be enabled if isfield(cfg, 'trackconfig') && (strcmp(cfg.trackconfig, 'report') || strcmp(cfg.trackconfig, 'cleanup')) trackconfig = 'on'; % turn on configtracking if user requests report/cleanup else trackconfig = []; % disable configtracking if user doesn't request report/cleanup end end % these should be cell arrays and not strings if ischar(required), required = {required}; end if ischar(deprecated), deprecated = {deprecated}; end if ischar(unused), unused = {unused}; end if ischar(forbidden), forbidden = {forbidden}; end if ischar(createsubcfg), createsubcfg = {createsubcfg}; end if isfield(cfg, 'checkconfig') silent = strcmp(cfg.checkconfig, 'silent'); loose = strcmp(cfg.checkconfig, 'loose'); pedantic = strcmp(cfg.checkconfig, 'pedantic'); else silent = false; loose = true; pedantic = false; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % rename old to new options, give warning %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(renamed) if issubfield(cfg, renamed{1}) cfg = setsubfield(cfg, renamed{2}, (getsubfield(cfg, renamed{1}))); cfg = rmsubfield(cfg, renamed{1}); if silent % don't mention it elseif loose warning('use cfg.%s instead of cfg.%s', renamed{2}, renamed{1}); elseif pedantic error('use cfg.%s instead of cfg.%s', renamed{2}, renamed{1}); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % rename old to new value, give warning %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(renamedval) && issubfield(cfg, renamedval{1}) if strcmpi(getsubfield(cfg, renamedval{1}), renamedval{2}) cfg = setsubfield(cfg, renamedval{1}, renamedval{3}); if silent % don't mention it elseif loose warning('use cfg.%s=''%s'' instead of cfg.%s=''%s''', renamedval{1}, renamedval{3}, renamedval{1}, renamedval{2}); elseif pedantic error('use cfg.%s=''%s'' instead of cfg.%s=''%s''', renamedval{1}, renamedval{3}, renamedval{1}, renamedval{2}); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check for required fields, give error when missing %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(required) fieldsused = fieldnames(cfg); [c, ia, ib] = setxor(required, fieldsused); if ~isempty(ia) error('The field cfg.%s is required\n', required{ia}); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check for deprecated fields, give warning when present %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(deprecated) fieldsused = fieldnames(cfg); if any(ismember(deprecated, fieldsused)) if silent % don't mention it elseif loose warning('The option cfg.%s is deprecated, support is no longer guaranteed\n', deprecated{ismember(deprecated, fieldsused)}); elseif pedantic error('The option cfg.%s is not longer supported\n', deprecated{ismember(deprecated, fieldsused)}); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check for unused fields, give warning when present and remove them %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(unused) fieldsused = fieldnames(cfg); if any(ismember(unused, fieldsused)) cfg = rmfield(cfg, unused(ismember(unused, fieldsused))); if silent % don't mention it elseif loose warning('The field cfg.%s is unused, it will be removed from your configuration\n', unused{ismember(unused, fieldsused)}); elseif pedantic error('The field cfg.%s is unused\n', unused{ismember(unused, fieldsused)}); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check for required fields, give error when missing %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(allowed) % there are some fields that are always be allowed allowed = union(allowed, ignorefields('allowed')); fieldsused = fieldnames(cfg); [c, i] = setdiff(fieldsused, allowed); if ~isempty(c) error('The field cfg.%s is not allowed\n', c{1}); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check for forbidden fields, give error when present %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(forbidden) fieldsused = fieldnames(cfg); if any(ismember(forbidden, fieldsused)) cfg = rmfield(cfg, forbidden(ismember(forbidden, fieldsused))); if silent % don't mention it elseif loose warning('The field cfg.%s is forbidden, it will be removed from your configuration\n', forbidden{ismember(forbidden, fieldsused)}); elseif pedantic error('The field cfg.%s is forbidden\n', forbidden{ismember(forbidden, fieldsused)}); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check for allowed values, give error if non-allowed value is specified %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(allowedval) && isfield(cfg, allowedval{1}) ... && ~any(strcmp(cfg.(allowedval{1}), allowedval(2:end))) s = ['The only allowed values for cfg.' allowedval{1} ' are: ']; for k = 2:numel(allowedval) s = [s allowedval{k} ', ']; end s = s(1:end-2); % strip last comma error(s); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % backward compatibility for the gradiometer and electrode definition %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isfield(cfg, 'grad') && ~isempty(cfg.grad) cfg.grad = ft_datatype_sens(cfg.grad); end if isfield(cfg, 'elec')&& ~isempty(cfg.elec) cfg.elec = ft_datatype_sens(cfg.elec); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % backward compatibility for old neighbourstructures %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isfield(cfg, 'neighbours') && iscell(cfg.neighbours) warning('cfg.neighbours is in the old format - converting it to a structure array'); cfg.neighbours = fixneighbours(cfg.neighbours); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % createsubcfg % % This collects the optional arguments for some of the low-level % functions and puts them in a separate substructure. This function is to % ensure backward compatibility of end-user scripts, FieldTrip functions % and documentation that do not use the nested detailled configuration % but that use a flat configuration. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(createsubcfg) for j=1:length(createsubcfg) subname = createsubcfg{j}; if isfield(cfg, subname) % get the options that are already specified in the substructure subcfg = cfg.(subname); else % start with an empty substructure subcfg = []; end % add all other relevant options to the substructure switch subname case 'preproc' fieldname = { 'reref' 'refchannel' 'implicitref' 'detrend' 'bpfiltdir' 'bpfilter' 'bpfiltord' 'bpfilttype' 'bpfreq' 'bsfiltdir' 'bsfilter' 'bsfiltord' 'bsfilttype' 'bsfreq' 'demean' 'baselinewindow' 'denoise' 'dftfilter' 'dftfreq' 'hpfiltdir' 'hpfilter' 'hpfiltord' 'hpfilttype' 'hpfreq' 'lpfiltdir' 'lpfilter' 'lpfiltord' 'lpfilttype' 'lpfreq' 'medianfilter' 'medianfiltord' 'hilbert' 'derivative' 'rectify' 'boxcar' 'absdiff' }; case 'grid' fieldname = { 'xgrid' 'ygrid' 'zgrid' 'resolution' 'unit' 'filter' 'leadfield' 'inside' 'outside' 'pos' 'dim' 'tight' }; case 'dics' fieldname = { 'feedback' 'fixedori' 'keepcsd' 'keepfilter' 'keepmom' 'keepsubspace' 'lambda' 'normalize' 'normalizeparam' 'powmethod' 'projectnoise' 'reducerank' 'realfilter' 'subspace' }; case 'eloreta' fieldname = { 'keepfilter' 'keepmom' 'lambda' 'normalize' 'normalizeparam' 'reducerank' }; case 'sloreta' fieldname = { 'feedback' 'fixedori' 'keepcov' 'keepfilter' 'keepmom' 'keepsubspace' 'lambda' 'normalize' 'normalizeparam' 'powmethod' 'projectnoise' 'projectmom' 'reducerank' 'subspace' }; case 'lcmv' fieldname = { 'feedback' 'fixedori' 'keepcov' 'keepfilter' 'keepmom' 'keepsubspace' 'lambda' 'normalize' 'normalizeparam' 'powmethod' 'projectnoise' 'projectmom' 'reducerank' 'subspace' }; case 'pcc' fieldname = { 'feedback' 'keepfilter' 'keepmom' 'lambda' 'normalize' 'normalizeparam' %'powmethod' 'projectnoise' 'reducerank' 'keepcsd' 'realfilter' 'fixedori' }; case 'rv' fieldname = { 'feedback' 'lambda' }; case 'mne' fieldname = { 'feedback' 'lambda' 'keepfilter' 'prewhiten' 'snr' 'scalesourcecov' }; case 'harmony' fieldname = { 'feedback' 'lambda' 'keepfilter' 'prewhiten' 'snr' 'scalesourcecov' 'filter_order' 'filter_bs' 'connected_components' 'number_harmonics' }; case 'music' fieldname = { 'feedback' 'numcomponent' }; case 'sam' fieldname = { 'meansphereorigin' 'feedback' 'lambda' 'fixedori' 'reducerank' 'normalize' 'normalizeparam' }; case 'mvl' fieldname = {}; case {'npsf', 'granger' 'pdc' 'dtf'} % non-parametric spectral factorization -> csd2transfer fieldname = { 'block' 'blockindx' 'channelcmb' 'numiteration' 'tol' 'sfmethod' 'svd' 'init' 'checkconvergence' }; otherwise error('unexpected name of the subfunction'); fieldname = {}; end % switch subname for i=1:length(fieldname) if ~isfield(subcfg, fieldname{i}) && isfield(cfg, fieldname{i}) if silent % don't mention it elseif loose warning('The field cfg.%s is deprecated, please specify it as cfg.%s.%s instead of cfg.%s', fieldname{i}, subname, fieldname{i}); elseif pedantic error('The field cfg.%s is not longer supported, use cfg.%s.%s instead\n', fieldname{i}, subname, fieldname{i}); end subcfg = setfield(subcfg, fieldname{i}, getfield(cfg, fieldname{i})); % set it in the subconfiguration cfg = rmfield(cfg, fieldname{i}); % remove it from the main configuration end end % copy the substructure back into the main configuration structure cfg = setfield(cfg, subname, subcfg); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % checkinside, i.e. index2logical % % Converts indexed cfg.inside/outside into logical representation if neccessary. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if istrue(checkinside) if isfield(cfg, 'inside') && any(cfg.inside>1) inside = false(size(cfg.pos,1),1); inside(cfg.inside) = true; cfg = removefields(cfg, {'inside', 'outside'}); cfg.inside = inside; elseif isfield(cfg, 'grid') && isfield(cfg.grid, 'inside') && any(cfg.grid.inside>1) inside = false(size(cfg.grid.pos,1),1); inside(cfg.grid.inside) = true; cfg.grid = removefields(cfg.grid, {'inside', 'outside'}); cfg.grid.inside = inside; end end % if checkinside %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % checkfilenames, i.e. dataset2files % % Converts cfg.dataset into cfg.headerfile and cfg.datafile if neccessary. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if istrue(checkfilenames) % start with empty fields if they are not present if ~isfield(cfg, 'dataset') cfg.dataset = []; end if ~isfield(cfg, 'datafile') cfg.datafile = []; end if ~isfield(cfg, 'headerfile') cfg.headerfile = []; end if ~isempty(cfg.dataset) % the dataset is an abstract concept and might relate to a file, a % constellation of fioles or a directory containing multiple files if isequal(cfg.dataset, 'gui') || isequal(cfg.dataset, 'uigetfile') % display a graphical file selection dialog [f, p] = uigetfile('*.*', 'Select a data file'); if isequal(f, 0) error('User pressed cancel'); else d = fullfile(p, f); end cfg.dataset = d; elseif strcmp(cfg.dataset, 'uigetdir') % display a graphical directory selection dialog d = uigetdir('*.*', 'Select a data directory'); if isequal(d, 0) error('User pressed cancel'); end cfg.dataset = d; end % ensure that the headerfile and datafile are defined, which are sometimes different than the name of the dataset % this requires correct autodetection of the format of the data set [cfg.dataset, cfg.headerfile, cfg.datafile] = dataset2files(cfg.dataset, []); elseif ~isempty(cfg.datafile) && isempty(cfg.headerfile); % assume that the datafile also contains the header information cfg.dataset = cfg.datafile; cfg.headerfile = cfg.datafile; elseif isempty(cfg.datafile) && ~isempty(cfg.headerfile); % assume that the headerfile also contains the data cfg.dataset = cfg.headerfile; cfg.datafile = cfg.headerfile; end % fill dataformat if unspecified, doing this only once saves time later if ~isfield(cfg,'dataformat') || isempty(cfg.dataformat) cfg.dataformat = ft_filetype(cfg.datafile); end % fill headerformat if unspecified, doing this only once saves time later if ~isfield(cfg,'headerformat') || isempty(cfg.headerformat) cfg.headerformat = ft_filetype(cfg.headerfile); end % remove empty fields, otherwise a subsequent check on required fields doesn't make any sense if isempty(cfg.dataset), cfg = rmfield(cfg, 'dataset'); end if isempty(cfg.headerfile), cfg = rmfield(cfg, 'headerfile'); end if isempty(cfg.datafile), cfg = rmfield(cfg, 'datafile'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % configtracking % % switch configuration tracking on/off %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(trackconfig) try if strcmp(trackconfig, 'on') if isa(cfg, 'struct') % turn ON configuration tracking cfg = config(cfg); % remember that configtracking has been turned on cfg = access(cfg, 'set', 'counter', 1); elseif isa(cfg, 'config') % remember how many times trackconfig has been turned on cfg = access(cfg, 'set', 'counter', access(cfg, 'get', 'counter')+1); % count the 'ONs' end end if strcmp(trackconfig, 'off') && isa(cfg, 'config') % turn OFF configuration tracking, optionally give report and/or cleanup cfg = access(cfg, 'set', 'counter', access(cfg, 'get', 'counter')-1); % count(down) the 'OFFs' if access(cfg, 'get', 'counter')==0 % only proceed when number of 'ONs' matches number of 'OFFs' if strcmp(cfg.trackconfig, 'report') || strcmp(cfg.trackconfig, 'cleanup') % gather information about the tracked results r = access(cfg, 'reference'); o = access(cfg, 'original'); % this uses a helper function to identify the fields that should be ignored key = fieldnames(cfg); key = key(:)'; skipsel = match_str(key, ignorefields('trackconfig')); key(skipsel) = []; used = zeros(size(key)); original = zeros(size(key)); for i=1:length(key) used(i) = (r.(key{i})>0); original(i) = (o.(key{i})>0); end if ~silent % give report on screen fprintf('\nThe following config fields were specified by YOU and were USED\n'); sel = find(used & original); if numel(sel) fprintf(' cfg.%s\n', key{sel}); else fprintf(' <none>\n'); end fprintf('\nThe following config fields were specified by YOU and were NOT USED\n'); sel = find(~used & original); if numel(sel) fprintf(' cfg.%s\n', key{sel}); else fprintf(' <none>\n'); end fprintf('\nThe following config fields were set to DEFAULTS and were USED\n'); sel = find(used & ~original); if numel(sel) fprintf(' cfg.%s\n', key{sel}); else fprintf(' <none>\n'); end fprintf('\nThe following config fields were set to DEFAULTS and were NOT USED\n'); sel = find(~used & ~original); if numel(sel) fprintf(' cfg.%s\n', key{sel}); else fprintf(' <none>\n'); end end % report end % report/cleanup if strcmp(cfg.trackconfig, 'cleanup') % remove the unused options from the configuration unusedkey = key(~used); for i=1:length(unusedkey) cfg = rmfield(cfg, unusedkey{i}); end end % convert the configuration back to a struct cfg = struct(cfg); end end % off catch disp(lasterr); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check the size of fields in the cfg, remove large fields % the max allowed size should be specified in cfg.checksize (this can be % set with ft_defaults) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(checksize, 'yes') && ~isinf(cfg.checksize) cfg = checksizefun(cfg, cfg.checksize); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [cfg] = checksizefun(cfg, max_size) % first check the total size of the cfg s = whos('cfg'); if (s.bytes <= max_size) return; end % these fields should not be handled recursively norecursion = {'event', 'headmodel', 'leadfield'}; fieldsorig = fieldnames(cfg); for i=1:numel(fieldsorig) for k=1:numel(cfg) % process each structure in a struct-array if any(strcmp(fieldsorig{i}, ignorefields('checksize'))) % keep this field, regardless of its size continue elseif iscell(cfg(k).(fieldsorig{i})) % run recursively on each struct element that is contained in the cell-array for j=1:numel(cfg(k).(fieldsorig{i})) if isstruct(cfg(k).(fieldsorig{i}){j}) cfg(k).(fieldsorig{i}){j} = checksizefun(cfg(k).(fieldsorig{i}){j}, max_size); end end elseif isstruct(cfg(k).(fieldsorig{i})) && ~any(strcmp(fieldsorig{i}, norecursion)) % run recursively on a struct field cfg(k).(fieldsorig{i}) = checksizefun(cfg(k).(fieldsorig{i}), max_size); else % determine the size of the field and remove it if too large temp = cfg(k).(fieldsorig{i}); s = whos('temp'); if s.bytes>max_size cfg(k).(fieldsorig{i}) = 'empty - this was cleared by checkconfig'; end clear temp end end % for numel(cfg) end % for each of the fieldsorig %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION converts a cell array of structure arrays into a structure array %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [newNeighbours] = fixneighbours(neighbours) newNeighbours = struct; for i=1:numel(neighbours) if i==1, newNeighbours = neighbours{i}; end; newNeighbours(i) = neighbours{i}; end
github
lcnbeapp/beapp-master
ft_datatype_source.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_datatype_source.m
12,246
utf_8
ab7ac36100ef0e75b5989d6870ea0bbf
function [source] = ft_datatype_source(source, varargin) % FT_DATATYPE_SOURCE describes the FieldTrip MATLAB structure for data that is % represented at the source level. This is typically obtained with a beamformer of % minimum-norm source reconstruction using FT_SOURCEANALYSIS. % % An example of a source structure obtained after performing DICS (a frequency % domain beamformer scanning method) is shown here % % pos: [6732x3 double] positions at which the source activity could have been estimated % inside: [6732x1 logical] boolean vector that indicates at which positions the source activity was estimated % dim: [xdim ydim zdim] if the positions can be described as a 3D regular grid, this contains the % dimensionality of the 3D volume % cumtapcnt: [120x1 double] information about the number of tapers per original trial % time: 0.100 the latency at which the activity is estimated (in seconds) % freq: 30 the frequency at which the activity is estimated (in Hz) % pow: [6732x120 double] the estimated power at each source position % powdimord: 'pos_rpt' defines how the numeric data has to be interpreted, % in this case 6732 dipole positions x 120 repetitions (i.e. trials) % cfg: [1x1 struct] the configuration used by the function that generated this data structure % % Required fields: % - pos % % Optional fields: % - time, freq, pow, coh, eta, mom, ori, cumtapcnt, dim, transform, inside, cfg, dimord, other fields with a dimord % % Deprecated fields: % - method, outside % % Obsoleted fields: % - xgrid, ygrid, zgrid, transform, latency, frequency % % Historical fields: % - avg, cfg, cumtapcnt, df, dim, freq, frequency, inside, method, % outside, pos, time, trial, vol, see bug2513 % % Revision history: % % (2014) The subfields in the avg and trial fields are now present in the % main structure, e.g. source.avg.pow is now source.pow. Furthermore, the % inside is always represented as logical vector. % % (2011) The source representation should always be irregular, i.e. not % a 3-D volume, contain a "pos" field and not contain a "transform". % % (2010) The source structure should contain a general "dimord" or specific % dimords for each of the fields. The source reconstruction in the avg and % trial substructures has been moved to the toplevel. % % (2007) The xgrid/ygrid/zgrid fields have been removed, because they are % redundant. % % (2003) The initial version was defined % % See also FT_DATATYPE, FT_DATATYPE_COMP, FT_DATATYPE_DIP, FT_DATATYPE_FREQ, % FT_DATATYPE_MVAR, FT_DATATYPE_RAW, FT_DATATYPE_SOURCE, FT_DATATYPE_SPIKE, % FT_DATATYPE_TIMELOCK, FT_DATATYPE_VOLUME % Copyright (C) 2013-2014, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % FIXME: I am not sure whether the removal of the xgrid/ygrid/zgrid fields % was really in 2007 % get the optional input arguments, which should be specified as key-value pairs version = ft_getopt(varargin, 'version', 'latest'); if strcmp(version, 'latest') || strcmp(version, 'upcoming') version = '2014'; end if isempty(source) return; end % old data structures may use latency/frequency instead of time/freq. It is % unclear when these were introduced and removed again, but they were never % used by any FieldTrip function itself if isfield(source, 'frequency'), source.freq = source.frequency; source = rmfield(source, 'frequency'); end if isfield(source, 'latency'), source.time = source.latency; source = rmfield(source, 'latency'); end switch version case '2014' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ensure that it has individual source positions source = fixpos(source); % ensure that it is always logical source = fixinside(source, 'logical'); % remove obsolete fields if isfield(source, 'method') source = rmfield(source, 'method'); end if isfield(source, 'transform') source = rmfield(source, 'transform'); end if isfield(source, 'xgrid') source = rmfield(source, 'xgrid'); end if isfield(source, 'ygrid') source = rmfield(source, 'ygrid'); end if isfield(source, 'zgrid') source = rmfield(source, 'zgrid'); end if isfield(source, 'avg') && isstruct(source.avg) && isfield(source, 'trial') && isstruct(source.trial) && ~isempty(intersect(fieldnames(source.avg), fieldnames(source.trial))) % it is not possible to convert both since they have the same field names ft_warning('removing ''avg'', keeping ''trial'''); source = rmfield(source, 'avg'); end if isfield(source, 'avg') && isstruct(source.avg) % move the average fields to the main structure fn = fieldnames(source.avg); for i=1:length(fn) dat = source.avg.(fn{i}); if isequal(size(dat), [1 size(source.pos,1)]) source.(fn{i}) = dat'; else source.(fn{i}) = dat; end clear dat end % j source = rmfield(source, 'avg'); end if isfield(source, 'inside') % the inside is by definition logically indexed probe = find(source.inside, 1, 'first'); else % just take the first source position probe = 1; end if isfield(source, 'trial') && isstruct(source.trial) npos = size(source.pos,1); % concatenate the fields for each trial and move them to the main structure fn = fieldnames(source.trial); for i=1:length(fn) % some fields are descriptive and hence identical over trials if strcmp(fn{i}, 'csdlabel') source.csdlabel = dat; continue end % start with the first trial dat = source.trial(1).(fn{i}); datsiz = getdimsiz(source, fn{i}); nrpt = datsiz(1); datsiz = datsiz(2:end); if iscell(dat) datsiz(1) = nrpt; % swap the size of pos with the size of rpt val = cell(npos,1); indx = find(source.inside); for k=1:length(indx) val{indx(k)} = nan(datsiz); val{indx(k)}(1,:,:,:) = dat{indx(k)}; end % concatenate all data as {pos}_rpt_etc for j=2:nrpt dat = source.trial(j).(fn{i}); for k=1:length(indx) val{indx(k)}(j,:,:,:) = dat{indx(k)}; end end % for all trials source.(fn{i}) = val; else % concatenate all data as pos_rpt_etc val = nan([datsiz(1) nrpt datsiz(2:end)]); val(:,1,:,:,:) = dat(:,:,:,:); for j=2:length(source.trial) dat = source.trial(j).(fn{i}); val(:,j,:,:,:) = dat(:,:,:,:); end % for all trials source.(fn{i}) = val; % else % siz = size(dat); % if prod(siz)==npos % siz = [npos nrpt]; % elseif siz(1)==npos % siz = [npos nrpt siz(2:end)]; % end % val = nan(siz); % % concatenate all data as pos_rpt_etc % val(:,1,:,:,:) = dat(:); % for j=2:length(source.trial) % dat = source.trial(j).(fn{i}); % val(:,j,:,:,:) = dat(:); % end % for all trials % source.(fn{i}) = val; end end % for each field source = rmfield(source, 'trial'); end % if trial % ensure that it has a dimord (or multiple for the different fields) source = fixdimord(source); % ensure that all data fields have the correct dimensions fn = getdatfield(source); for i=1:numel(fn) dimord = getdimord(source, fn{i}); dimtok = tokenize(dimord, '_'); dimsiz = getdimsiz(source, fn{i}); dimsiz(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions if numel(dimsiz)>=3 && strcmp(dimtok{1}, 'dim1') && strcmp(dimtok{2}, 'dim2') && strcmp(dimtok{3}, 'dim3') % convert it from voxel-based representation to position-based representation try source.(fn{i}) = reshape(source.(fn{i}), [prod(dimsiz(1:3)) dimsiz(4:end) 1]); catch warning('could not reshape %s to the expected dimensions', fn{i}); end end end case '2011' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ensure that it has individual source positions source = fixpos(source); % remove obsolete fields if isfield(source, 'xgrid') source = rmfield(source, 'xgrid'); end if isfield(source, 'ygrid') source = rmfield(source, 'ygrid'); end if isfield(source, 'zgrid') source = rmfield(source, 'zgrid'); end if isfield(source, 'transform') source = rmfield(source, 'transform'); end % ensure that it has a dimord (or multiple for the different fields) source = fixdimord(source); case '2010' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ensure that it has individual source positions source = fixpos(source); % remove obsolete fields if isfield(source, 'xgrid') source = rmfield(source, 'xgrid'); end if isfield(source, 'ygrid') source = rmfield(source, 'ygrid'); end if isfield(source, 'zgrid') source = rmfield(source, 'zgrid'); end % ensure that it has a dimord (or multiple for the different fields) source = fixdimord(source); case '2007' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ensure that it has individual source positions source = fixpos(source); % remove obsolete fields if isfield(source, 'dimord') source = rmfield(source, 'dimord'); end if isfield(source, 'xgrid') source = rmfield(source, 'xgrid'); end if isfield(source, 'ygrid') source = rmfield(source, 'ygrid'); end if isfield(source, 'zgrid') source = rmfield(source, 'zgrid'); end case '2003' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isfield(source, 'dimord') source = rmfield(source, 'dimord'); end if ~isfield(source, 'xgrid') || ~isfield(source, 'ygrid') || ~isfield(source, 'zgrid') if isfield(source, 'dim') minx = min(source.pos(:,1)); maxx = max(source.pos(:,1)); miny = min(source.pos(:,2)); maxy = max(source.pos(:,2)); minz = min(source.pos(:,3)); maxz = max(source.pos(:,3)); source.xgrid = linspace(minx, maxx, source.dim(1)); source.ygrid = linspace(miny, maxy, source.dim(2)); source.zgrid = linspace(minz, maxz, source.dim(3)); end end otherwise %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% error('unsupported version "%s" for source datatype', version); end function pos = grid2pos(xgrid, ygrid, zgrid) [X, Y, Z] = ndgrid(xgrid, ygrid, zgrid); pos = [X(:) Y(:) Z(:)]; function pos = dim2pos(dim, transform) [X, Y, Z] = ndgrid(1:dim(1), 1:dim(2), 1:dim(3)); pos = [X(:) Y(:) Z(:)]; pos = ft_warp_apply(transform, pos, 'homogenous');
github
lcnbeapp/beapp-master
ft_warp_dykstra2012.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_warp_dykstra2012.m
5,113
utf_8
f62b920eb747153a6abe6350a926cc1b
function [coord_snapped] = ft_warp_dykstra2012(coord, surf, feedback) % FT_WARP_DYKSTRA2012 projects the ECoG grid / strip onto a cortex hull % while minimizing the distance from original positions and the % deformation of the grid. To align ECoG electrodes to the pial surface, % you first need to compute the cortex hull with FT_PREPARE_MESH. % FT_WARP_DYKSTRA2012 uses algorithm described in Dykstra et al. (2012, % Neuroimage) in which electrodes are projected onto pial surface while % minimizing the displacement of the electrodes from original location % and maintaining the grid shape. It relies on the optimization toolbox. % % See also FT_ELECTRODEREALIGN, FT_PREPARE_MESH % Copyright (C) 2012-2016, Gio Piantoni, Andrew Dykstra % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % determine whether the MATLAB Optimization toolbox is available and can be used ft_hastoolbox('optim', 1); disp('Please cite: Dykstra et al. 2012 Neuroimage PMID: 22155045') % get starting coordinates coord0 = coord; % compute pairs of neighbors pairs = knn_pairs(coord, 4); % anonymous function handles efun = @(coord_snapped) energy_electrodesnap(coord_snapped, coord, pairs); cfun = @(coord_snapped) dist_to_surface(coord_snapped, surf); % options options = optimset('Algorithm','active-set',... 'MaxIter', 50,... 'MaxFunEvals', Inf,... 'UseParallel', 'always',... 'GradObj', 'off',... 'TypicalX', coord(:),... 'DiffMaxChange', 2,... 'DiffMinChange', 0.3,... 'TolFun', 0.3,... 'TolCon', 0.01 * size(coord0, 1),... 'TolX', 0.5,... 'Diagnostics', 'off',... 'RelLineSrchBnd',1); if strcmp(feedback, 'yes') options = optimset(options, 'Display', 'iter'); else options = optimset(options, 'Display', 'final'); end % run minimization coord_snapped = fmincon(efun, coord0, [], [], [], [], [], [], cfun, options); end function [energy, denergy] = energy_electrodesnap(coord, coord_orig, pairs) % ENERGY_ELECTRODESNAP compute energy to be minimized, based on deformation % and distance of the electrodes from original distance energy_eshift = sum((coord - coord_orig).^2, 2); energy_deform = deformation_energy(coord, coord_orig, pairs); energy = mean(energy_eshift) + mean(energy_deform.^2); denergy=[]; end function energy = deformation_energy(coord, coord_orig, pairs) % DEFORMATION_ENERGY measure energy due to grid deformation dist = sqrt(sum((coord(pairs(:, 1), :) - coord(pairs(:, 2), :)) .^ 2, 2)); dist_orig = sqrt(sum((coord_orig(pairs(:, 1), :) - coord_orig(pairs(:, 2), :)) .^ 2, 2)); energy = (dist - dist_orig) .^2; end function [c, dist] = dist_to_surface(coord, surf) % DIST_TO_SURFACE Compute distance to surface, this is the fastest way to run % it, although running the loops in other directions might be more intuitive. c = []; dist = zeros(size(coord, 1), 1); for i0 = 1:size(coord, 1) dist_one_elec = zeros(size(surf.pos, 1), 1); for i1 = 1:size(surf.pos, 2) dist_one_elec = dist_one_elec + (surf.pos(:, i1) - coord(i0, i1)) .^ 2; end dist(i0) = min(dist_one_elec); end dist = sqrt(dist); end function pairs = knn_pairs(coord, k) % KNN_PAIRS compute pairs of neighbors of the grid knn_ind = knn_search(coord, coord, k); pairs = cat(3, knn_ind, repmat([1:size(coord,1)]',1,k)); pairs = permute(pairs,[3 1 2]); pairs = sort(reshape(pairs,2,[]),1)'; pairs = unique(pairs,'rows'); end function idx = knn_search(Q, R, K) %KNN_SEARCH perform search using k-Nearest Neighbors algorithm [N, M] = size(Q); L = size(R, 1); idx = zeros(N, K); D = idx; for k = 1:N d = zeros(L, 1); for t = 1:M d = d + (R(:, t) - Q(k, t)) .^ 2; end d(k) = inf; [s, t] = sort(d); idx(k, :) = t(1:K); D(k, :)= s(1:K); end end
github
lcnbeapp/beapp-master
ft_test_result.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_test_result.m
7,436
utf_8
a28cd88cb3548c06087d0b49b4d8b15b
function results = ft_test_result(varargin) % FT_TEST_RESULT checks the status of selected test scripts on the FieldTrip dashboard % % To get all dashboard results as a structure array, you would do % result = ft_test_result % % To print a table with the results on screen, you would do % ft_test_result comparerevision ea3c2b9 314d186 % ft_test_result comparematlab 2015b 2016b % ft_test_result comparemexext mexw32 mexw64 % ft_test_result compareos osx windows % % Additional query arguments are specified as key-value pairs and can include % matlabversion = string % fieldtripversion = string % hostname = string % user = string % branch = string % result = string % % See also FT_TEST_RUN, FT_VERSION % Copyright (C) 2016, Robert oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/donders/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % set the default command = 'query'; if nargin>0 if isequal(varargin{1}, 'compare') || isequal(varargin{1}, 'comparerevision') % comparerevision rev1 rev2 command = 'comparerevision'; arg1 = varargin{2}; arg2 = varargin{3}; varargin = varargin(4:end); elseif isequal(varargin{1}, 'matlab') || isequal(varargin{1}, 'comparematlab') % comparematlab ver1 ver2 command = 'comparematlab'; arg1 = varargin{2}; arg2 = varargin{3}; varargin = varargin(4:end); end end % construct the query string query = '?'; % the 'distict' parameter is mutually exclusive with all others queryparam = {'matlabversion', 'fieldtripversion', 'hostname', 'user', 'functionname', 'result', 'branch', 'distinct'}; for i=1:numel(queryparam) val = ft_getopt(varargin, queryparam{i}); if ~isempty(val) query = [query sprintf('%s=%s&', queryparam{i}, val)]; end end options = weboptions('ContentType','json'); % this returns the results as MATLAB structure switch command case 'query' results = webread(['http://dashboard.fieldtriptoolbox.org/api/' query], options); case 'comparerevision' dashboard1 = webread(['http://dashboard.fieldtriptoolbox.org/api/' query sprintf('&fieldtripversion=%s', arg1)], options); dashboard2 = webread(['http://dashboard.fieldtriptoolbox.org/api/' query sprintf('&fieldtripversion=%s', arg2)], options); assert(~isempty(dashboard1), 'no tests were returned for the first revision'); assert(~isempty(dashboard2), 'no tests were returned for the second revision'); functionname1 = {dashboard1.functionname}; functionname2 = {dashboard2.functionname}; functionname = unique(cat(2, functionname1, functionname2)); n = max(cellfun(@length, functionname)); line = cell(size(functionname)); order = nan(size(functionname)); for i=1:numel(functionname) sel1 = find(strcmp(functionname1, functionname{i})); sel2 = find(strcmp(functionname2, functionname{i})); res1 = getresult(dashboard1, sel1); res2 = getresult(dashboard2, sel2); line{i} = sprintf('%s : %s in %s, %s in %s\n', padto(functionname{i}, n), res1, arg1, res2, arg2); % determine the order if strcmp(res1, 'passed') && strcmp(res2, 'passed') order(i) = 1; elseif strcmp(res1, 'failed') && strcmp(res2, 'failed') order(i) = 2; elseif strcmp(res1, 'missing') && strcmp(res2, 'passed') order(i) = 3; elseif strcmp(res1, 'passed') && strcmp(res2, 'missing') order(i) = 4; elseif strcmp(res1, 'missing') && strcmp(res2, 'failed') order(i) = 5; elseif strcmp(res1, 'failed') && strcmp(res2, 'missing') order(i) = 6; elseif strcmp(res1, 'failed') && strcmp(res2, 'passed') order(i) = 7; elseif strcmp(res1, 'passed') && strcmp(res2, 'failed') order(i) = 8; else order(i) = 9; end end % for each functionname [order, index] = sort(order); line = line(index); for i=1:length(line) fprintf(line{i}); end case 'comparematlab' dashboard1 = webread(['http://dashboard.fieldtriptoolbox.org/api/' query sprintf('&matlabversion=%s', arg1)], options); dashboard2 = webread(['http://dashboard.fieldtriptoolbox.org/api/' query sprintf('&matlabversion=%s', arg2)], options); assert(~isempty(dashboard1), 'no tests were returned for the first matab version'); assert(~isempty(dashboard2), 'no tests were returned for the second matab version'); functionname1 = {dashboard1.functionname}; functionname2 = {dashboard2.functionname}; functionname = unique(cat(2, functionname1, functionname2)); n = max(cellfun(@length, functionname)); line = cell(size(functionname)); order = nan(size(functionname)); for i=1:numel(functionname) sel1 = find(strcmp(functionname1, functionname{i})); sel2 = find(strcmp(functionname2, functionname{i})); res1 = getresult(dashboard1, sel1); res2 = getresult(dashboard2, sel2); line{i} = sprintf('%s : %s in %s, %s in %s\n', padto(functionname{i}, n), res1, arg1, res2, arg2); % determine the order if strcmp(res1, 'passed') && strcmp(res2, 'passed') order(i) = 1; elseif strcmp(res1, 'failed') && strcmp(res2, 'failed') order(i) = 2; elseif strcmp(res1, 'missing') && strcmp(res2, 'passed') order(i) = 3; elseif strcmp(res1, 'passed') && strcmp(res2, 'missing') order(i) = 4; elseif strcmp(res1, 'missing') && strcmp(res2, 'failed') order(i) = 5; elseif strcmp(res1, 'failed') && strcmp(res2, 'missing') order(i) = 6; elseif strcmp(res1, 'failed') && strcmp(res2, 'passed') order(i) = 7; elseif strcmp(res1, 'passed') && strcmp(res2, 'failed') order(i) = 8; else order(i) = 9; end end % for each functionname [order, index] = sort(order); line = line(index); for i=1:length(line) fprintf(line{i}); end otherwise error('unsupported command "%s"', command); end % switch command %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str = padto(str, n) if n>length(str) str = [str repmat(' ', [1 n-length(str)])]; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str = getresult(dashboard, sel) if isempty(sel) str = 'missing'; elseif all(istrue([dashboard(sel).result])) str = 'passed'; elseif all(~istrue([dashboard(sel).result])) str = 'failed'; else str = 'ambiguous'; end
github
lcnbeapp/beapp-master
ft_warning.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_warning.m
7,789
utf_8
d832a7ad5e2f9bb42995e6e5d4caa198
function [ws, warned] = ft_warning(varargin) % FT_WARNING will throw a warning for every unique point in the % stacktrace only, e.g. in a for-loop a warning is thrown only once. % % Use as one of the following % ft_warning(string) % ft_warning(id, string) % Alternatively, you can use ft_warning using a timeout % ft_warning(string, timeout) % ft_warning(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. % % Use as ft_warning('-clear') to clear old warnings from the current % stack % % It can be used instead of the MATLAB built-in function WARNING, thus as % s = ft_warning(...) % or as % ft_warning(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. In other words, ft_warning accepts as an input the % same structure it returns as an output. This returns or restores the % states of warnings to their previous values. % % It can also be used as % [s w] = ft_warning(...) % where w is a boolean that indicates whether a warning as been thrown or not. % % Please note that you can NOT use it like this % ft_warning('the value is %d', 10) % instead you should do % ft_warning(sprintf('the value is %d', 10)) % Copyright (C) 2012-2016, Robert Oostenveld, J?rn M. Horschig % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ global ft_default warned = false; ws = []; stack = dbstack; if any(strcmp({stack(2:end).file}, 'ft_warning.m')) % don't call FT_WARNING recursively, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3068 return; end if nargin < 1 error('You need to specify at least a warning message'); end if isstruct(varargin{1}) warning(varargin{1}); return; end if ~isfield(ft_default, 'warning') ft_default.warning = []; end if ~isfield(ft_default.warning, 'stopwatch') ft_default.warning.stopwatch = []; end if ~isfield(ft_default.warning, 'identifier') ft_default.warning.identifier = []; end if ~isfield(ft_default.warning, 'ignore') ft_default.warning.ignore = {}; end % put the arguments we will pass to warning() in this cell array warningArgs = {}; if nargin==3 % calling syntax (id, msg, timeout) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = varargin{3}; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==2 && isnumeric(varargin{2}) % calling syntax (msg, timeout) warningArgs = varargin(1); msg = warningArgs{1}; timeout = varargin{2}; fname = warningArgs{1}; elseif nargin==2 && isequal(varargin{1}, 'off') ft_default.warning.ignore = union(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && isequal(varargin{1}, 'on') ft_default.warning.ignore = setdiff(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && ~isnumeric(varargin{2}) % calling syntax (id, msg) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = inf; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==1 % calling syntax (msg) warningArgs = varargin(1); msg = warningArgs{1}; timeout = inf; % default timeout in seconds fname = [warningArgs{1}]; end if ismember(msg, ft_default.warning.ignore) % do not show this warning return; end if isempty(timeout) error('Timeout ill-specified'); end if timeout ~= inf fname = fixname(fname); % make a nice string that is allowed as fieldname in a structures line = []; else % here, we create the fieldname functionA.functionB.functionC... [tmpfname, ft_default.warning.identifier, line] = fieldnameFromStack(ft_default.warning.identifier); if ~isempty(tmpfname), fname = tmpfname; clear tmpfname; end end if nargin==1 && ischar(varargin{1}) && strcmp('-clear', varargin{1}) if strcmp(fname, '-clear') % reset all fields if called outside a function ft_default.warning.identifier = []; ft_default.warning.stopwatch = []; else if issubfield(ft_default.warning.identifier, fname) ft_default.warning.identifier = rmsubfield(ft_default.warning.identifier, fname); end end return; end % and add the line number to make this unique for the last function fname = horzcat(fname, line); if ~issubfield('ft_default.warning.stopwatch', fname) ft_default.warning.stopwatch = setsubfield(ft_default.warning.stopwatch, fname, tic); end now = toc(getsubfield(ft_default.warning.stopwatch, fname)); % measure time since first function call if ~issubfield(ft_default.warning.identifier, fname) || ... (issubfield(ft_default.warning.identifier, fname) && now>getsubfield(ft_default.warning.identifier, [fname '.timeout'])) % create or reset field ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, fname, []); % warning never given before or timed out ws = warning(warningArgs{:}); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.timeout'], now+timeout); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.ws'], msg); warned = true; else % the warning has been issued before, but has not timed out yet ws = getsubfield(ft_default.warning.identifier, [fname '.ws']); end end % function ft_warning %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fname, ft_previous_warnings, line] = fieldnameFromStack(ft_previous_warnings) % stack(1) is this function, stack(2) is ft_warning stack = dbstack('-completenames'); if size(stack) < 3 fname = []; line = []; return; end i0 = 3; % ignore ft_preamble while strfind(stack(i0).name, 'ft_preamble') i0=i0+1; end fname = horzcat(fixname(stack(end).name)); if ~issubfield(ft_previous_warnings, fixname(stack(end).name)) ft_previous_warnings.(fixname(stack(end).name)) = []; % iteratively build up structure fields end for i=numel(stack)-1:-1:(i0) % skip postamble scripts if strncmp(stack(i).name, 'ft_postamble', 12) break; end fname = horzcat(fname, '.', horzcat(fixname(stack(i).name))); % , stack(i).file if ~issubfield(ft_previous_warnings, fname) % iteratively build up structure fields setsubfield(ft_previous_warnings, fname, []); end end % line of last function call line = ['.line', int2str(stack(i0).line)]; end % function outcome = issubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % outcome = eval(['isfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % outcome = isfield(strct, fname); % end % end % function strct = rmsubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % strct = eval(['rmfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % strct = rmfield(strct, fname); % end % end
github
lcnbeapp/beapp-master
ft_selectdata_new.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_selectdata_new.m
50,624
utf_8
9a80958f482cd3233df091925dbdcaa9
function [varargout] = ft_selectdata_new(cfg, varargin) % FT_SELECTDATA_NEW is deprecated, please use FT_SELECTDATA instead. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Old documentation for reference %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % This function makes a selection in the input data along specific data % dimensions, such as channels, time, frequency, trials, etc. It can also % be used to average the data along each of the specific dimensions. % % Use as % [data] = ft_selectdata_new(cfg, data, ...) % % The cfg artument is a configuration structure which can contain % cfg.tolerance = scalar, tolerance value to determine equality of time/frequency bins (default = 1e-5) % % For data with trials or subjects as repetitions, you can specify % cfg.trials = 1xN, trial indices to keep, can be 'all'. You can use logical indexing, where false(1,N) removes all the trials % cfg.avgoverrpt = string, can be 'yes' or 'no' (default = 'no') % % For data with a channel dimension you can specify % cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION % cfg.avgoverchan = string, can be 'yes' or 'no' (default = 'no') % % For data with a time dimension you can specify % cfg.latency = scalar -> can be 'all' % cfg.latency = [beg end] % cfg.avgovertime = string, can be 'yes' or 'no' (default = 'no') % % For data with a frequency dimension you can specify % cfg.frequency = scalar -> can be 'all' % cfg.frequency = [beg end] -> this is less common, preferred is to use foilim % cfg.foilim = [beg end] % cfg.avgoverfreq = string, can be 'yes' or 'no' (default = 'no') % % If multiple input arguments are provided, FT_SELECTDATA will adjust the % individual inputs such that either the intersection across inputs is % retained (i.e. only the channel/time/frequency points that are shared % across all input arguments), or the union across inputs is retained % (replacing missing data with nans). In either case, the order (e.g. of % the channel labels) is made consistent across inputs. Multiple inputs in % combination with the selection of trials is not supported. The exact % behavior can be specified with % cfg.select = 'intersect' or 'union' (default = 'intersect') % Copyright (C) 2012-2014, Robert Oostenveld & Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; ft_defaults % this ensures that the path is correct and that the ft_defaults global variable is available ft_preamble init % this will reset ft_warning and show the function help if nargin==0 and return an error ft_preamble provenance % this records the time and memory usage at teh beginning of the function ft_preamble trackconfig % this converts the cfg structure in a config object, which tracks the cfg options that are being used ft_preamble debug % this allows for displaying or saving the function name and input arguments upon an error ft_preamble loadvar varargin % this reads the input data in case the user specified the cfg.inputfile option % determine the characteristics of the input data dtype = ft_datatype(varargin{1}); for i=2:length(varargin) % ensure that all subsequent inputs are of the same type ok = ft_datatype(varargin{i}, dtype); if ~ok, error('input data should be of the same datatype'); end end cfg = ft_checkconfig(cfg, 'renamed', {'selmode', 'select'}); cfg = ft_checkconfig(cfg, 'renamed', {'toilim' 'latency'}); cfg = ft_checkconfig(cfg, 'renamed', {'avgoverroi' 'avgoverpos'}); cfg = ft_checkconfig(cfg, 'renamedval', {'parameter' 'avg.pow' 'pow'}); cfg = ft_checkconfig(cfg, 'renamedval', {'parameter' 'avg.mom' 'mom'}); cfg = ft_checkconfig(cfg, 'renamedval', {'parameter' 'avg.nai' 'nai'}); cfg = ft_checkconfig(cfg, 'renamedval', {'parameter' 'trial.pow' 'pow'}); cfg = ft_checkconfig(cfg, 'renamedval', {'parameter' 'trial.mom' 'mom'}); cfg = ft_checkconfig(cfg, 'renamedval', {'parameter' 'trial.nai' 'nai'}); cfg.tolerance = ft_getopt(cfg, 'tolerance', 1e-5); % default tolerance for checking equality of time/freq axes cfg.select = ft_getopt(cfg, 'select', 'intersect'); % default is to take intersection, alternative 'union' cfg.parameter = ft_getopt(cfg, 'parameter', {}); % this function only works for the upcoming (not yet standard) source representation without sub-structures % update the old-style beamformer source reconstruction to the upcoming representation if strcmp(dtype, 'source') for i=1:length(varargin) varargin{i} = ft_datatype_source(varargin{i}, 'version', 'upcoming'); end end if length(varargin)>1 && isfield(cfg, 'trials') && ~isequal(cfg.trials, 'all') error('it is ambiguous to make a subselection of trials while at the same time concatenating multiple data structures') end if strcmp(cfg.select, 'union') && any(strcmp(dtype, {'raw', 'comp', 'source'})) error('cfg.select ''union'' is not yet supported for %s data', dtype); end if ft_datatype(varargin{1}, 'raw') cfg.channel = ft_getopt(cfg, 'channel', 'all', 1); % empty definition by user is meaningful cfg.latency = ft_getopt(cfg, 'latency', 'all', 1); cfg.trials = ft_getopt(cfg, 'trials', 'all', 1); for i=1:length(varargin) varargin{i} = selfromraw(varargin{i}, 'rpt', cfg.trials, 'chan', cfg.channel, 'latency', cfg.latency); end else % not raw or comp cfg.channel = ft_getopt(cfg, 'channel', 'all', 1); cfg.latency = ft_getopt(cfg, 'latency', 'all', 1); cfg.trials = ft_getopt(cfg, 'trials', 'all', 1); if ~isfield(cfg, 'foilim') cfg.frequency = ft_getopt(cfg, 'frequency', 'all', 1); end if isempty(cfg.parameter) && isfield(varargin{1}, 'dimord') dimord = varargin{1}.dimord; elseif ischar(cfg.parameter) && isfield(varargin{1}, [cfg.parameter 'dimord']) dimord = varargin{1}.([cfg.parameter 'dimord']); elseif ischar(cfg.parameter) && isfield(varargin{1}, 'dimord') dimord = varargin{1}.dimord; else error('cannot determine which parameter to select from the data, please specify cfg.parameter'); end dimtok = tokenize(dimord, '_'); if isempty(cfg.parameter) || isequal(cfg.parameter ,'all') dimsiz = nan(size(dimtok)); dimfields = cell(size(dimtok)); % determine the size of each of the dimensions for i=1:numel(dimtok) % this switch-list is consistent with fixdimord switch dimtok{i} case 'time' dimsiz(i) = length(varargin{1}.time); dimfields{i} = 'time'; case 'freq' dimsiz(i) = length(varargin{1}.freq); dimfields{i} = 'freq'; case 'chan' dimsiz(i) = length(varargin{1}.label); dimfields{i} = 'label'; case 'chancmb' dimsiz(i) = size(varargin{1}.labelcmb,1); dimfields{i} = 'labelcmb'; case 'pos' dimsiz(i) = size(varargin{1}.pos,1); dimfields{i} = 'pos'; case '{pos}' dimsiz(i) = size(varargin{1}.pos,1); dimfields{i} = '{pos}'; case 'subj' % the number of elements along this dimension is implicit dimsiz(i) = nan; dimfields{i} = 'implicit'; case 'rpt' % the number of elements along this dimension is implicit dimsiz(i) = nan; dimfields{i} = 'implicit'; case 'rpttap' % the number of elements along this dimension is implicit dimsiz(i) = nan; dimfields{i} = 'implicit'; case 'ori' % the number of elements along this dimension is implicit dimsiz(i) = nan; dimfields{i} = 'implicit'; case 'comp' error('FIXME'); case 'refchan' error('FIXME'); case 'voxel' error('FIXME'); otherwise % try to guess the size from the corresponding field if isfield(varargin{1}, dimtok{i}) siz = varargin{1}.(dimtok{i}); if length(siz)==2 && any(siz==1) dimsiz(i) = prod(siz); dimfields{i} = dimtok{i}; end end end % switch end % for dimtok % deal with the data dimensions whose size is only implicitly represented if any(strcmp(dimfields, 'implicit')) fn = fieldnames(varargin{1})'; for i=1:numel(fn) val = varargin{1}.(fn{i}); siz = cellmatsize(val); clear val if isequalwithoutnans(siz, dimsiz) fprintf('using the "%s" field to determine the size along the unknown dimensions\n', fn{i}); % update the size of all dimensions dimsiz = size(varargin{1}.(fn{i})); % update the fieldname of each dimension dimfields(strcmp(dimfields, 'implicit')) = dimtok(strcmp(dimfields, 'implicit')); break end end if any(strcmp(dimfields, 'implicit')) % it failed error('could not determine the size of the implicit "%s" dimension', dimfields{strcmp(dimfields, 'implicit')}); end end % select the fields based on the dimord fn = fieldnames(varargin{1})'; % it should be a row-array fn = setdiff(fn, {'pos', 'label', 'time', 'freq', 'cfg', 'hdr', 'grad', 'elec'}); sel = false(size(fn)); for i=1:numel(fn) sel(i) = isequal(size(varargin{1}.(fn{i})), dimsiz) || isequal(size(varargin{1}.(fn{i})), [dimsiz 1]); end cfg.parameter = fn(sel); clear dimsiz dimfields end % is isempty(cfg.parameter) % these are the fields in which the selection will be made datfields = cfg.parameter; if ~iscell(datfields) datfields = {datfields}; end hasrpt = any(ismember(dimtok, {'rpt', 'subj'})); hasrpttap = any(ismember(dimtok, 'rpttap')); haspos = any(ismember(dimtok, {'pos', '{pos}'})); haschan = any(ismember(dimtok, 'chan')); haschancmb = any(ismember(dimtok, 'chancmb')); hasfreq = any(ismember(dimtok, 'freq')); hastime = any(ismember(dimtok, 'time')); haspos = haspos && isfield(varargin{1}, 'pos'); haschan = haschan && isfield(varargin{1}, 'label'); haschancmb = haschancmb && isfield(varargin{1}, 'labelcmb'); hasfreq = hasfreq && isfield(varargin{1}, 'freq'); hastime = hastime && isfield(varargin{1}, 'time'); avgoverpos = istrue(ft_getopt(cfg, 'avgoverpos', false)); % at some places it is also referred to as roi (region-of-interest) avgoverrpt = istrue(ft_getopt(cfg, 'avgoverrpt', false)); avgoverchan = istrue(ft_getopt(cfg, 'avgoverchan', false)); avgoverfreq = istrue(ft_getopt(cfg, 'avgoverfreq', false)); avgovertime = istrue(ft_getopt(cfg, 'avgovertime', false)); if avgoverpos, assert(haspos, 'there are no source positions, so averaging is not possible'); end if avgoverrpt, assert(hasrpt||hasrpttap, 'there are no repetitions, so averaging is not possible'); end if avgoverchan, assert(haschan, 'there is no channel dimension, so averaging is not possible'); end if avgoverfreq, assert(hasfreq, 'there is no frequency dimension, so averaging is not possible'); end if avgovertime, assert(hastime, 'there is no time dimension, so averaging over time is not possible'); end % by default we keep most of the dimensions in the data structure when averaging over them keeprptdim = istrue(ft_getopt(cfg, 'keeprptdim', false)); keepposdim = istrue(ft_getopt(cfg, 'keepposdim', true)); keepchandim = istrue(ft_getopt(cfg, 'keepchandim', true)); keepfreqdim = istrue(ft_getopt(cfg, 'keepfreqdim', true)); keeptimedim = istrue(ft_getopt(cfg, 'keeptimedim', true)); if strcmp(cfg.select, 'union') && (avgoverpos || avgoverrpt || avgoverchan || avgoverfreq || avgovertime) error('cfg.select ''union'' in combination with averaging across one of the dimensions is not implemented'); end if avgoverpos for i=1:length(varargin) % must be a source representation, not a volume representation varargin{i} = ft_checkdata(varargin{i}, 'datatype', 'source'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % PART 2: % ensure that the cfg is fully contained in the data and consistent over all inputs % get the selection along each of the dimensions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % FIXMEroboos this implementation is not yet complete % dtype = 'new'; switch dtype % this switch-list is consistent with ft_datatype case {'new'} % FIXMEroboos this implementation is not yet complete % trim the selection to all inputs if haspos, [selpos, cfg] = getselection_pos (cfg, varargin{:}, cfg.tolerance, cfg.select); end if haschan, [selchan, cfg] = getselection_chan (cfg, varargin{:}, cfg.select); end if haschancmb, [selchancmb, cfg] = getselection_chancmb(cfg, varargin{:}, cfg.select); end if hastime, [seltime, cfg] = getselection_time (cfg, varargin{:}, cfg.tolerance, cfg.select); end if hasfreq, [selfreq, cfg] = getselection_freq (cfg, varargin{:}, cfg.tolerance, cfg.select); end for i=1:numel(varargin) % the rpt selection should only work with a single data argument % in case tapers were kept, selrpt~=selrpttap, otherwise selrpt==selrpttap [selrpt{i}, dum, rptdim{i}, selrpttap{i}] = getselection_rpt(cfg, varargin{i}, 'datfields', datfields); if haspos, varargin{i} = makeselection(varargin{i}, find(ismember(dimtok, {'pos', '{pos}'})), selpos{i}, avgoverpos, datfields, cfg.select); end if haschan, varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'chan')), selchan{i}, avgoverchan, datfields, cfg.select); end if haschancmb, varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'chancmb')), selchancmb{i}, false, datfields, cfg.select); end if hastime, varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'time')), seltime{i}, avgovertime, datfields, cfg.select); end if hasfreq, varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'freq')), selfreq{i}, avgoverfreq, datfields, cfg.select); end if hasrpt, varargin{i} = makeselection(varargin{i}, find(ismember(dimtok,{'rpt', 'subj'})), selrpt{i}, avgoverrpt, datfields, 'intersect'); end if hasrpttap, varargin{i} = makeselection(varargin{i}, rptdim{i}, selrpttap{i}, avgoverrpt, datfields, 'intersect'); end if haspos, varargin{i} = makeselection_pos(varargin{i}, selpos{i}, avgoverpos); end % update the pos field if haschan, varargin{i} = makeselection_chan(varargin{i}, selchan{i}, avgoverchan); end % update the label field if hastime, varargin{i} = makeselection_time(varargin{i}, seltime{i}, avgovertime); end % update the time field if hasfreq, varargin{i} = makeselection_freq(varargin{i}, selfreq{i}, avgoverfreq); end % update the time field if hasrpt || hasrpttap, varargin{i} = makeselection_rpt (varargin{i}, selrpt{i}); end % avgoverrpt for the supporting fields is dealt with later % also deal with the supporting cumtapcnt field, because it has a frequency dimension when time dimension is present % this is a temporary workaround, see http://bugzilla.fcdonders.nl/show_bug.cgi?id=2509 if isfield(varargin{i}, 'cumtapcnt') && hastime varargin{i} = makeselection_cumtapcnt(varargin{i}, selfreq{i}, avgoverfreq); end % make an exception for the covariance here (JM 20131128) if isfield(varargin{i}, 'cov') && (all(~isnan(selrpt{i})) || all(~isnan(selchan{i}))) varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok, 'chan'))+[0 1], selchan{i}, avgoverchan, {'cov'}, cfg.select); varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok, 'rpt')), selrpt{i}, avgoverrpt, {'cov'}, 'intersect'); datfields = [datfields {'cov'}]; end end % for varargin % in the case of selmode='union', create the union of the descriptive axes if strcmp(cfg.select, 'union') if haschan label = varargin{1}.label; for i=2:numel(varargin) tmplabel = varargin{i}.label; emptylabel = find(cellfun('isempty', label)); for k=emptylabel(:)' label{k} = tmplabel{k}; end end for i=1:numel(varargin) varargin{i}.label = label; end end % haschan if hastime time = varargin{1}.time; for i=2:numel(varargin) tmptime = varargin{i}.time; time(~isfinite(time)) = tmptime(~isfinite(time)); end for i=1:numel(varargin) varargin{i}.time = time; end end % hastime end % select=union case 'timelock' % trim the selection to all inputs [selchan, cfg] = getselection_chan(cfg, varargin{:}, cfg.select); [seltime, cfg] = getselection_time(cfg, varargin{:}, cfg.tolerance, cfg.select); selrpt = cell(numel(varargin),1); for i=1:numel(varargin) [selrpt{i}] = getselection_rpt (cfg, varargin{i}, 'datfields', datfields); varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'chan')), selchan{i}, avgoverchan, datfields, cfg.select); varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'time')), seltime{i}, avgovertime, datfields, cfg.select); varargin{i} = makeselection(varargin{i}, find(ismember(dimtok,{'rpt', 'rpttap', 'subj'})), selrpt{i}, avgoverrpt, datfields, 'intersect'); varargin{i} = makeselection_chan(varargin{i}, selchan{i}, avgoverchan); % update the label field varargin{i} = makeselection_time(varargin{i}, seltime{i}, avgovertime); % update the time field varargin{i} = makeselection_rpt (varargin{i}, selrpt{i}); % avgoverrpt for the supporting fields is dealt with later % make an exception for the covariance here (JM 20131128) if isfield(varargin{i}, 'cov') && (all(~isnan(selrpt{i})) || all(~isnan(selchan{i}))) varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok, 'chan'))+[0 1], selchan{i}, avgoverchan, {'cov'}, cfg.select); varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok, 'rpt')), selrpt{i}, avgoverrpt, {'cov'}, 'intersect'); datfields = [datfields {'cov'}]; end end % varargin % in the case of selmode='union', create the union of the descriptive axes if strcmp(cfg.select, 'union') label = varargin{1}.label; time = varargin{1}.time; for i=2:numel(varargin) tmplabel = varargin{i}.label; tmptime = varargin{i}.time; time(~isfinite(time)) = tmptime(~isfinite(time)); emptylabel = find(cellfun('isempty', label)); for k=emptylabel(:)' label{k} = tmplabel{k}; end end for i=1:numel(varargin) varargin{i}.label = label; varargin{i}.time = time; end end case 'freq' % trim the selection to all inputs [selchan, cfg] = getselection_chan(cfg, varargin{:}, cfg.select); % tolerance not needed [selfreq, cfg] = getselection_freq(cfg, varargin{:}, cfg.tolerance, cfg.select); % freq is always present if hastime, [seltime, cfg] = getselection_time(cfg, varargin{:}, cfg.tolerance, cfg.select); end selrpt = cell(numel(varargin),1); selrpttap = cell(numel(varargin),1); rptdim = cell(numel(varargin),1); for i=1:numel(varargin) % the rpt selection stays within this loop, it only should work with a single data argument anyway % in case tapers were kept, selrpt~=selrpttap, otherwise selrpt==selrpttap [selrpt{i}, dum, rptdim{i}, selrpttap{i}] = getselection_rpt(cfg, varargin{i}, 'datfields', datfields); varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'chan')), selchan{i}, avgoverchan, datfields, cfg.select); varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'freq')), selfreq{i}, avgoverfreq, datfields, cfg.select); varargin{i} = makeselection(varargin{i}, rptdim{i}, selrpttap{i}, avgoverrpt, datfields, 'intersect'); varargin{i} = makeselection_chan(varargin{i}, selchan{i}, avgoverchan); % update the label field varargin{i} = makeselection_freq(varargin{i}, selfreq{i}, avgoverfreq); % update the freq field varargin{i} = makeselection_rpt(varargin{i}, selrpt{i}); % avgoverrpt for the supporting fields is dealt with later if hastime varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'time')), seltime{i}, avgovertime, datfields, cfg.select); varargin{i} = makeselection_time(varargin{i}, seltime{i}, avgovertime); % update the time field end % also deal with the supporting cumtapcnt field, because it has a frequency dimension when time dimension is present % this is a temporary workaround, see http://bugzilla.fcdonders.nl/show_bug.cgi?id=2509 if hastime && isfield(varargin{i}, 'cumtapcnt') varargin{i} = makeselection_cumtapcnt(varargin{i}, selfreq{i}, avgoverfreq); end end % varargin % in the case of selmode='union', create the union of the descriptive axes if strcmp(cfg.select, 'union') label = varargin{1}.label; freq = varargin{1}.freq; if hastime, time = varargin{1}.time; end for i=2:numel(varargin) tmpfreq = varargin{i}.freq; tmplabel = varargin{i}.label; if hastime, tmptime = varargin{i}.time; end freq(~isfinite(freq)) = tmpfreq(~isfinite(freq)); if hastime, time(~isfinite(time)) = tmptime(~isfinite(time)); end emptylabel = find(cellfun('isempty', label)); for k=emptylabel(:)' label{k} = tmplabel{k}; end end for i=1:numel(varargin) varargin{i}.freq = freq; varargin{i}.label = label; if hastime, varargin{i}.time = time; end end end case 'source' % trim the selection to all inputs [selpos, cfg] = getselection_pos(cfg, varargin{:}, cfg.tolerance, cfg.select); if hastime, [seltime, cfg] = getselection_time(cfg, varargin{:}, cfg.tolerance, cfg.select); end if hasfreq, [selfreq, cfg] = getselection_freq(cfg, varargin{:}, cfg.tolerance, cfg.select); end for i=1:numel(varargin) % get the selection from all inputs varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'pos') | strcmp(dimtok,'{pos}')), selpos{i}, avgoverpos, datfields, cfg.select); varargin{i} = makeselection_pos(varargin{i}, selpos{i}, avgoverpos); % update the pos field % FIXME this code does not deal with repetitions if hastime, varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'time')), seltime{i}, avgovertime, datfields, cfg.select); varargin{i} = makeselection_time(varargin{i}, seltime{i}, avgovertime); % update the time field end if hasfreq, varargin{i} = makeselection(varargin{i}, find(strcmp(dimtok,'freq')), selfreq{i}, avgoverfreq, datfields, cfg.select); varargin{i} = makeselection_freq(varargin{i}, selfreq{i}, avgoverfreq); % update the freq field end end % varargin case 'freqmvar' error('FIXME'); case 'mvar' error('FIXME'); case 'spike' error('FIXME'); case 'volume' error('FIXME'); case 'dip' error('FIXME'); case 'chan' % this results from avgovertime/avgoverfreq after timelockstatistics or freqstatistics error('FIXME'); otherwise % try to get the selection based on the field name seldim = cell(size(dimtok)); for j=1:numel(seldim) seldim(j) = feval(['getselection_' dimtok{j}], cfg, varargin{i}); end end % switch dtype % update the fields and the dimord keepdim = true(size(dimtok)); keepfield = unique(dimtok); sel = strcmp(keepfield, '{pos}'); if any(sel), keepfield(sel) = {'pos'}; end sel = strcmp(keepfield, 'chan'); if any(sel), keepfield(sel) = {'label'}; end if avgoverchan && ~keepchandim keepdim(strcmp(dimtok, 'chan')) = false; keepfield = setdiff(keepfield, 'label'); else keepfield = [keepfield 'label']; end if avgoverfreq && ~keepfreqdim keepdim(strcmp(dimtok, 'freq')) = false; keepfield = setdiff(keepfield, 'freq'); else keepfield = [keepfield 'freq']; end if avgovertime && ~keeptimedim keepdim(strcmp(dimtok, 'time')) = false; keepfield = setdiff(keepfield, 'time'); else keepfield = [keepfield 'time']; end if avgoverpos && ~keepposdim keepdim(strcmp(dimtok, 'pos')) = false; keepdim(strcmp(dimtok, '{pos}')) = false; keepfield = setdiff(keepfield, {'pos' '{pos}' 'dim'}); else keepfield = [keepfield {'pos' '{pos}' 'dim'}]; end if avgoverrpt && ~keeprptdim keepdim(ismember(dimtok, {'rpt', 'rpttap', 'subj'})) = false; keepfield = setdiff(keepfield, {'cumtapcnt' 'cumsumcnt' 'sampleinfo' 'trialinfo'}); else keepfield = [keepfield {'cumtapcnt' 'cumsumcnt' 'sampleinfo' 'trialinfo'}]; end % remove all fields from the dimord that do not pertain to the selection for i=1:numel(varargin) varargin{i}.dimord = sprintf('%s_', dimtok{keepdim}); varargin{i}.dimord = varargin{i}.dimord(1:end-1); % remove the last '_' end for i=1:numel(varargin) for j=1:numel(datfields) varargin{i}.(datfields{j}) = squeezedim(varargin{i}.(datfields{j}), ~keepdim); end end % remove all fields from the data that do not pertain to the selection for i=1:numel(varargin) varargin{i} = keepfields(varargin{i}, [datfields {'cfg' 'dimord' 'elec' 'grad'} keepfield]); end end % if raw or something else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % PART 3: % if desired, concatenate over repetitions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% varargout = varargin; ft_postamble debug % this clears the onCleanup function used for debugging in case of an error ft_postamble trackconfig % this converts the config object back into a struct and can report on the unused fields ft_postamble provenance % this records the time and memory at the end of the function, prints them on screen and adds this information together with the function name and MATLAB version etc. to the output cfg % ft_postamble previous varargin % this copies the datain.cfg structure into the cfg.previous field. You can also use it for multiple inputs, or for "varargin" % ft_postamble history varargout % this adds the local cfg structure to the output data structure, i.e. dataout.cfg = cfg % note that the cfg.previous thingy does not work with the postamble, % because the postamble puts the cfgs of all input arguments in the (first) % output argument's xxx.cfg for k = 1:numel(varargout) varargout{k}.cfg = cfg; if isfield(varargin{k}, 'cfg') varargout{k}.cfg.previous = varargin{k}.cfg; end end % ft_postamble savevar varargout % this saves the output data structure to disk in case the user specified the cfg.outputfile option if nargout>numel(varargout) % also return the input cfg varargout{end+1} = cfg; end end % main function ft_selectdata %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = makeselection(data, seldim, selindx, avgoverdim, datfields, selmode) if numel(seldim) > 1 for k = 1:numel(seldim) data = makeselection(data, seldim(k), selindx, avgoverdim, datfields, selmode); end return; end switch selmode case 'intersect' for i=1:numel(datfields) % the selindx value of NaN indicates that it is not needed to make a selection if isempty(selindx) || all(~isnan(selindx)) data.(datfields{i}) = cellmatselect(data.(datfields{i}), seldim, selindx); end if avgoverdim data.(datfields{i}) = cellmatmean(data.(datfields{i}), seldim); end end % for datfields case 'union' for i=1:numel(datfields) tmp = data.(datfields{i}); siz = size(tmp); siz(seldim) = numel(selindx); data.(datfields{i}) = nan+zeros(siz); sel = isfinite(selindx); switch seldim case 1 data.(datfields{i})(sel,:,:,:,:,:) = tmp(selindx(sel),:,:,:,:,:); case 2 data.(datfields{i})(:,sel,:,:,:,:) = tmp(:,selindx(sel),:,:,:,:); case 3 data.(datfields{i})(:,:,sel,:,:,:) = tmp(:,:,selindx(sel),:,:,:); case 4 data.(datfields{i})(:,:,:,sel,:,:) = tmp(:,:,:,selindx(sel),:,:); case 5 data.(datfields{i})(:,:,:,:,sel,:) = tmp(:,:,:,:,selindx(sel),:); case 6 data.(datfields{i})(:,:,:,:,:,sel) = tmp(:,:,:,:,:,selindx(sel)); otherwise error('unsupported dimension (%d) for making a selection for %s', seldim, datfields{i}); end end if avgoverdim data.(datfields{i}) = mean(data.(datfields{i}), seldim); end end % switch end % function makeselection %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = makeselection_chan(data, selchan, avgoverchan) if avgoverchan && all(isnan(selchan)) str = sprintf('%s, ', data.label{:}); str = str(1:(end-2)); str = sprintf('mean(%s)', str); data.label = {str}; elseif avgoverchan && ~any(isnan(selchan)) str = sprintf('%s, ', data.label{selchan}); str = str(1:(end-2)); str = sprintf('mean(%s)', str); data.label = {str}; % remove the last '+' elseif all(isfinite(selchan)) data.label = data.label(selchan); data.label = data.label(:); elseif numel(selchan)==1 && any(~isfinite(selchan)) % do nothing elseif numel(selchan)>1 && any(~isfinite(selchan)) tmp = cell(numel(selchan),1); for k = 1:numel(tmp) if isfinite(selchan(k)) tmp{k} = data.label{selchan(k)}; end end data.label = tmp; elseif isempty(selchan) data.label = {}; end end % function makeselection_chan %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = makeselection_freq(data, selfreq, avgoverfreq) if avgoverfreq % compute the mean frequency if ~isnan(selfreq) data.freq = mean(data.freq(selfreq)); else data.freq = mean(data.freq); end elseif numel(selfreq)==1 && ~isfinite(selfreq) % do nothing elseif numel(selfreq)==1 && isfinite(selfreq) data.freq = data.freq(selfreq); elseif numel(selfreq)>1 && any(~isfinite(selfreq)) tmp = selfreq(:)'; sel = isfinite(selfreq); tmp(sel) = data.freq(selfreq(sel)); data.freq = tmp; elseif numel(selfreq)>1 && all(isfinite(selfreq)) data.freq = data.freq(selfreq); elseif isempty(selfreq) data.freq = zeros(1,0); end end % function makeselection_freq %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = makeselection_time(data, seltime, avgovertime) if avgovertime % compute the mean latency if ~isnan(seltime) data.time = mean(data.time(seltime)); else data.time = mean(data.time); end elseif numel(seltime)==1 && ~isfinite(seltime) % do nothing elseif numel(seltime)==1 && isfinite(seltime) data.time = data.time(seltime); elseif numel(seltime)>1 && any(~isfinite(seltime)) tmp = seltime(:)'; sel = isfinite(seltime); tmp(sel) = data.time(seltime(sel)); data.time = tmp; elseif numel(seltime)>1 && all(isfinite(seltime)) data.time = data.time(seltime); elseif isempty(seltime) data.time = zeros(1,0); end end % function makeselection_time %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = makeselection_cumtapcnt(data, selfreq, avgoverfreq) if ~isfield(data, 'time') error('the subfunction makeselection_cumtapcnt should only be called when there is a time dimension in the data'); end if ~isfield(data, 'cumtapcnt') return; end if avgoverfreq if ~isnan(selfreq) data.cumtapcnt = mean(data.cumtapcnt(:,selfreq),2); else data.cumtapcnt = mean(data.cumtapcnt,2); end elseif numel(selfreq)==1 && ~isfinite(selfreq) % do nothing elseif numel(selfreq)==1 && isfinite(selfreq) data.cumtapcnt = data.cumtapcnt(:,selfreq); elseif numel(selfreq)>1 && any(~isfinite(selfreq)) tmp = selfreq(:)'; tmp2 = zeros(size(data.cumtapcnt,1), numel(selfreq)); sel = isfinite(selfreq); tmp2(:, sel) = data.cumtapcnt(:,selfreq(sel)); data.freq = tmp2; elseif numel(selfreq)>1 && all(isfinite(selfreq)) data.cumtapcnt = data.cumtapcnt(:,selfreq); elseif isempty(selfreq) %data.cumtapcnt = zeros(1,0); end end % function makeselection_cumtapcnt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = makeselection_rpt(data, selrpt) if all(isfinite(selrpt)) || isempty(selrpt) if isfield(data, 'cumtapcnt') data.cumtapcnt = data.cumtapcnt(selrpt,:,:); end if isfield(data, 'cumsumcnt') data.cumsumcnt = data.cumsumcnt(selrpt,:,:); end if isfield(data, 'trialinfo') data.trialinfo = data.trialinfo(selrpt,:); end if isfield(data, 'sampleinfo') data.sampleinfo = data.sampleinfo(selrpt,:); end end end % function makeselection_rpt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = makeselection_pos(data, selpos, avgoverpos) if ~isnan(selpos) data.pos = data.pos(selpos, :); end if avgoverpos data.pos = mean(data.pos, 1); end end % function makeselection_pos %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [chanindx, cfg] = getselection_chan(cfg, varargin) selmode = varargin{end}; ndata = numel(varargin)-1; varargin = varargin(1:ndata); % loop over data once to initialize chanindx = cell(ndata,1); label = cell(1,0); if isfield(cfg, 'channel') for k = 1:ndata selchannel = ft_channelselection(cfg.channel, varargin{k}.label); label = union(label, selchannel); end indx = nan+zeros(numel(label), ndata); for k = 1:ndata [ix, iy] = match_str(label, varargin{k}.label); indx(ix,k) = iy; end switch selmode case 'intersect' sel = sum(isfinite(indx),2)==ndata; indx = indx(sel,:); label = varargin{1}.label(indx(:,1)); case 'union' % don't do a subselection otherwise error('invalid value for cfg.select'); end % switch for k = 1:ndata chanindx{k,1} = indx(:,k); end cfg.channel = label; else for k = 1:ndata % the nan return value specifies that no selection was specified chanindx{k,1} = nan; end end end % function getselection_chan %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [chancmbindx, cfg] = getselection_chancmb(cfg, varargin) selmode = varargin{end}; ndata = numel(varargin)-1; varargin = varargin(1:ndata); chancmbindx = cell(ndata,1); if isfield(cfg, 'channelcmb') for k = 1:ndata cfg.channelcmb = ft_channelcombination(cfg.channelcmb, varargin{k}.labelcmb); end error('selection of channelcmb is not yet implemented'); else for k = 1:ndata % the nan return value specifies that no selection was specified chancmbindx{k} = nan; end end end % function getselection_chancmb %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [timeindx, cfg] = getselection_time(cfg, varargin) % possible specifications are % cfg.latency = value -> can be 'all' % cfg.latency = [beg end] ndata = numel(varargin)-2; tol = varargin{end-1}; selmode = varargin{end}; % loop over data once to initialize timeindx = cell(numel(varargin)-2,1); timeaxis = zeros(1,0); for k = 1:ndata assert(isfield(varargin{k}, 'time'), 'the input data should have a time axis'); % the nan return value specifies that no selection was specified timeindx{k,1} = nan; % update the axis along which the frequencies are defined timeaxis = union(timeaxis, round(varargin{k}.time(:)/tol)*tol); end indx = nan+zeros(numel(timeaxis), ndata); for k = 1:ndata [dum, ix, iy] = intersect(timeaxis, round(varargin{k}.time(:)/tol)*tol); indx(ix,k) = iy; end switch selmode case 'intersect' sel = sum(isfinite(indx),2)==ndata; indx = indx(sel,:); timeaxis = varargin{1}.time(indx(:,1)); case 'union' % don't do a subselection otherwise error('invalid value for cfg.select'); end if isfield(cfg, 'latency') % deal with string selection if ischar(cfg.latency) if strcmp(cfg.latency, 'all') cfg.latency = [min(timeaxis) max(timeaxis)]; else error('incorrect specification of cfg.latency'); end end % deal with numeric selection if numel(cfg.latency)==1 % this single value should be within the time axis of each input data structure tbin = nearest(timeaxis, cfg.latency, true, true); cfg.latency = timeaxis(tbin); for k = 1:ndata timeindx{k,1} = indx(tbin, k); end elseif numel(cfg.latency)==2 % the [min max] range can be specifed with +inf or -inf, but should % at least partially overlap with the time axis of the input data mintime = min(timeaxis); maxtime = max(timeaxis); if all(cfg.latency<mintime) || all(cfg.latency>maxtime) error('the selected time range falls outside the time axis in the data'); end tbeg = nearest(timeaxis, cfg.latency(1), false, false); tend = nearest(timeaxis, cfg.latency(2), false, false); cfg.latency = timeaxis([tbeg tend]); for k = 1:ndata timeindx{k,1} = indx(tbeg:tend, k); end elseif size(cfg.latency,2)==2 % this may be used for specification of the computation, not for data selection elseif isempty(cfg.latency) for k = 1:ndata timeindx{k,1} = []; end else error('incorrect specification of cfg.latency'); end end % if cfg.latency % % Note: cfg.toilim handling removed as it was renamed to cfg.latency for k = 1:ndata if isequal(timeindx, 1:length(timeaxis)) % the cfg was updated, but no selection is needed for the data timeindx{k,1} = nan; end end end % function getselection_time %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [freqindx, cfg] = getselection_freq(cfg, varargin) % possible specifications are % cfg.frequency = value -> can be 'all' % cfg.frequency = [beg end] -> this is less common, preferred is to use foilim % cfg.foilim = [beg end] ndata = numel(varargin)-2; tol = varargin{end-1}; selmode = varargin{end}; % loop over data once to initialize freqindx = cell(numel(varargin)-2,1); freqaxis = zeros(1,0); for k = 1:ndata assert(isfield(varargin{k}, 'freq'), 'the input data should have a frequency axis'); % the nan return value specifies that no selection was specified freqindx{k,1} = nan; % update the axis along which the frequencies are defined freqaxis = union(freqaxis, round(varargin{k}.freq(:)/tol)*tol); end indx = nan+zeros(numel(freqaxis), ndata); for k = 1:ndata [dum, ix, iy] = intersect(freqaxis, round(varargin{k}.freq(:)/tol)*tol); indx(ix,k) = iy; end switch selmode case 'intersect' sel = sum(isfinite(indx),2)==ndata; indx = indx(sel,:); freqaxis = varargin{1}.freq(indx(:,1)); case 'union' % don't do a subselection otherwise error('invalid value for cfg.select'); end if isfield(cfg, 'frequency') % deal with string selection if ischar(cfg.frequency) if strcmp(cfg.frequency, 'all') cfg.frequency = [min(freqaxis) max(freqaxis)]; else error('incorrect specification of cfg.frequency'); end end % deal with numeric selection if numel(cfg.frequency)==1 % this single value should be within the frequency axis of each input data structure fbin = nearest(freqaxis, cfg.frequency, true, true); cfg.frequency = freqaxis(fbin); for k = 1:ndata freqindx{k,1} = indx(fbin,k); end elseif numel(cfg.frequency)==2 % the [min max] range can be specifed with +inf or -inf, but should % at least partially overlap with the freq axis of the input data minfreq = min(freqaxis); maxfreq = max(freqaxis); if all(cfg.frequency<minfreq) || all(cfg.frequency>maxfreq) error('the selected range falls outside the frequency axis in the data'); end fbeg = nearest(freqaxis, cfg.frequency(1), false, false); fend = nearest(freqaxis, cfg.frequency(2), false, false); cfg.frequency = freqaxis([fbeg fend]); for k = 1:ndata freqindx{k,1} = indx(fbeg:fend,k); end elseif size(cfg.frequency,2)==2 % this may be used for specification of the computation, not for data selection elseif isempty(cfg.frequency) for k = 1:ndata freqindx{k,1} = []; end else error('incorrect specification of cfg.frequency'); end end % if cfg.frequency if isfield(cfg, 'foilim') if ~ischar(cfg.foilim) && numel(cfg.foilim)==2 % the [min max] range can be specifed with +inf or -inf, but should % at least partially overlap with the time axis of the input data minfreq = min(freqaxis); maxfreq = max(freqaxis); if all(cfg.foilim<minfreq) || all(cfg.foilim>maxfreq) error('the selected range falls outside the frequency axis in the data'); end fbin = nan(1,2); fbin(1) = nearest(freqaxis, cfg.foilim(1), false, false); fbin(2) = nearest(freqaxis, cfg.foilim(2), false, false); cfg.foilim = freqaxis(fbin); for k = 1:ndata freqindx{k,1} = indx(fbin(1):fbin(2), k); end else error('incorrect specification of cfg.foilim'); end end % cfg.foilim for k = 1:ndata if isequal(freqindx{k}, 1:length(varargin{k}.freq)) % the cfg was updated, but no selection is needed for the data freqindx{k} = nan; end end end % function getselection_freq %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [rptindx, cfg, rptdim, rptindxtap] = getselection_rpt(cfg, data, varargin) % this should deal with cfg.trials datfields = ft_getopt(varargin, 'datfields'); % start with the initual guess for the dimord if isfield(data, 'dimord') dimord = data.dimord; end % perhaps there is a specific dimord for the data fields of interest for i=1:length(datfields) if isfield(data, [datfields{i} 'dimord']) dimord = data.([datfields{i} 'dimord']); break end end dimtok = tokenize(dimord, '_'); if isfield(cfg, 'trials') && ~isequal(cfg.trials, 'all') && ~isempty(datfields) rptdim = find(strcmp(dimtok, 'rpt') | strcmp(dimtok, 'rpttap') | strcmp(dimtok, 'subj')); rptindx = nan; % the nan return value specifies that no selection was specified rptindxtap = nan; % the nan return value specifies that no selection was specified if isempty(rptdim) return else rptindx = ft_getopt(cfg, 'trials'); if islogical(rptindx) % convert from booleans to indices rptindx = find(rptindx); end rptindx = unique(sort(rptindx)); rptindx = unique(sort(rptindx)); rptsiz = size(data.(datfields{1}), rptdim); if strcmp(dimtok{rptdim}, 'rpttap') % account for the tapers sumtapcnt = [0;cumsum(data.cumtapcnt(:))]; begtapcnt = sumtapcnt(1:end-1)+1; endtapcnt = sumtapcnt(2:end); begtapcnt = begtapcnt(rptindx); endtapcnt = endtapcnt(rptindx); tapers = zeros(1,sumtapcnt(end)); for k = 1:length(begtapcnt) tapers(begtapcnt(k):endtapcnt(k)) = k; end rptindxtap = find(tapers); [srt,ix] = sort(tapers(tapers~=0)); rptindxtap = rptindxtap(ix); % cfg.trials = rptindx; % TODO FIXME think about whether this is a good or a bad thing... %warning('cfg.trials accounts for the number of tapers now'); else rptindxtap = rptindx; end if ~isempty(rptindx) && rptindx(1)<1 error('cannot select rpt/subj/rpttap smaller than 1'); elseif ~isempty(rptindx) && rptindx(end)>rptsiz error('cannot select rpt/subj/rpttap larger than the number of repetitions in the data'); end % commented out because of rpttap dilemma... % cfg.trials = rptindx; return end else % recover the rptdim if possible rptdim = find(strcmp(dimtok, 'rpt') | strcmp(dimtok, 'rpttap') | strcmp(dimtok, 'subj')); rptindx = nan; rptindxtap = nan; end % if isfield cfg.trials end % function getselection_rpt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [posindx, cfg] = getselection_pos(cfg, varargin) % possible specifications are <none> ndata = numel(varargin)-2; tol = varargin{end-1}; % FIXME this is still ignored selmode = varargin{end}; % FIXME this is still ignored for i=2:ndata if ~isequal(varargin{i}.pos, varargin{1}.pos) % FIXME it would be possible here to make a selection based on intersect or union error('source positions are different'); end end % for for i=1:ndata posindx{i} = nan; % the nan return value specifies that no selection was specified end end % function getselection_pos %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function x = squeezedim(x, dim) siz = size(x); for i=(numel(siz)+1):numel(dim) % all trailing singleton dimensions have length 1 siz(i) = 1; end x = reshape(x, [siz(~dim) 1]); end % function squeezedim %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ok = isequalwithoutnans(a, b) % this is *only* used to compare matrix sizes, so we can ignore any % singleton last dimension numdiff = numel(b)-numel(a); if numdiff > 0 % assume singleton dimensions missing in a a = [a(:); ones(numdiff, 1)]; b = b(:); elseif numdiff < 0 % assume singleton dimensions missing in b b = [b(:); ones(abs(numdiff), 1)]; a = a(:); end c = ~isnan(a(:)) & ~isnan(b(:)); ok = isequal(a(c), b(c)); end % function isequalwithoutnans %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to determine the size of data representations like {pos}_ori_time % FIXME this will fail for {xxx_yyy}_zzz %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function siz = cellmatsize(x) if iscell(x) cellsize = numel(x); % the number of elements in the cell-array [dum, indx] = max(cellfun(@numel, x)); matsize = size(x{indx}); % the size of the content of the cell-array siz = [cellsize matsize]; % concatenate the two else siz = size(x); end end % function cellmatsize %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to make a selextion in data representations like {pos}_ori_time % FIXME this will fail for {xxx_yyy}_zzz %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function x = cellmatselect(x, seldim, selindx) if iscell(x) if seldim==1 x = x(selindx); else for i=1:numel(x) switch seldim case 2 x{i} = x{i}(selindx,:,:,:,:); case 3 x{i} = x{i}(:,selindx,:,:,:); case 4 x{i} = x{i}(:,:,selindx,:,:); case 5 x{i} = x{i}(:,:,:,selindx,:); case 6 x{i} = x{i}(:,:,:,:,selindx); otherwise error('unsupported dimension (%d) for making a selection', seldim); end % switch end % for end else switch seldim case 1 x = x(selindx,:,:,:,:,:); case 2 x = x(:,selindx,:,:,:,:); case 3 x = x(:,:,selindx,:,:,:); case 4 x = x(:,:,:,selindx,:,:); case 5 x = x(:,:,:,:,selindx,:); case 6 x = x(:,:,:,:,:,selindx); otherwise error('unsupported dimension (%d) for making a selection', seldim); end end end % function cellmatselect %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to take an average in data representations like {pos}_ori_time % FIXME this will fail for {xxx_yyy}_zzz %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function x = cellmatmean(x, seldim) if iscell(x) if seldim==1 for i=2:numel(x) x{1} = x{1} + x{i}; end x = {x{1}/numel(x)}; else for i=1:numel(x) x{i} = mean(x{i}, seldim-1); end % for end else x = mean(x, seldim); end end % function cellmatmean function dimord = paramdimord(data, param) if isfield(data, [param 'dimord']) dimord = data.([param 'dimord']); else dimord = data.dimord; end end % function paramdimord function dimtok = paramdimtok(data, param) dimord = paramdimord(data, param); dimtok = tokenize(dimord, '_'); end % function paramdimtok
github
lcnbeapp/beapp-master
ft_hastoolbox.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_hastoolbox.m
24,831
utf_8
43bae19e25ce108f013f1c401e497630
function [status] = ft_hastoolbox(toolbox, autoadd, silent) % FT_HASTOOLBOX tests whether an external toolbox is installed. Optionally % it will try to determine the path to the toolbox and install it % automatically. % % Use as % [status] = ft_hastoolbox(toolbox, autoadd, silent) % % autoadd = 0 means that it will not be added % autoadd = 1 means that give an error if it cannot be added % autoadd = 2 means that give a warning if it cannot be added % autoadd = 3 means that it remains silent if it cannot be added % % silent = 0 means that it will give some feedback about adding the toolbox % silent = 1 means that it will not give feedback % Copyright (C) 2005-2013, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % this function is called many times in FieldTrip and associated toolboxes % use efficient handling if the same toolbox has been investigated before % persistent previous previouspath % % if ~isequal(previouspath, path) % previous = []; % end % % if isempty(previous) % previous = struct; % elseif isfield(previous, fixname(toolbox)) % status = previous.(fixname(toolbox)); % return % end if isdeployed % it is not possible to check the presence of functions or change the path in a compiled application status = 1; return end % this points the user to the website where he/she can download the toolbox url = { 'AFNI' 'see http://afni.nimh.nih.gov' 'DSS' 'see http://www.cis.hut.fi/projects/dss' 'EEGLAB' 'see http://www.sccn.ucsd.edu/eeglab' 'NWAY' 'see http://www.models.kvl.dk/source/nwaytoolbox' 'SPM99' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM2' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM5' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM8' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM12' 'see http://www.fil.ion.ucl.ac.uk/spm' 'MEG-PD' 'see http://www.kolumbus.fi/kuutela/programs/meg-pd' 'MEG-CALC' 'this is a commercial toolbox from Neuromag, see http://www.neuromag.com' 'BIOSIG' 'see http://biosig.sourceforge.net' 'EEG' 'see http://eeg.sourceforge.net' 'EEGSF' 'see http://eeg.sourceforge.net' % alternative name 'MRI' 'see http://eeg.sourceforge.net' % alternative name 'NEUROSHARE' 'see http://www.neuroshare.org' 'BESA' 'see http://www.besa.de/downloads/matlab/ and get the "BESA MATLAB Readers"' 'MATLAB2BESA' 'see http://www.besa.de/downloads/matlab/ and get the "MATLAB to BESA Export functions"' 'EEPROBE' 'see http://www.ant-neuro.com, or contact Maarten van der Velde' 'YOKOGAWA' 'this is deprecated, please use YOKOGAWA_MEG_READER instead' 'YOKOGAWA_MEG_READER' 'see http://www.yokogawa.com/me/me-login-en.htm' 'BEOWULF' 'see http://robertoostenveld.nl, or contact Robert Oostenveld' 'MENTAT' 'see http://robertoostenveld.nl, or contact Robert Oostenveld' 'SON2' 'see http://www.kcl.ac.uk/depsta/biomedical/cfnr/lidierth.html, or contact Malcolm Lidierth' '4D-VERSION' 'contact Christian Wienbruch' 'COMM' 'see http://www.mathworks.com/products/communications' 'SIGNAL' 'see http://www.mathworks.com/products/signal' 'OPTIM' 'see http://www.mathworks.com/products/optim' 'IMAGE' 'see http://www.mathworks.com/products/image' % Mathworks refers to this as IMAGES 'SPLINES' 'see http://www.mathworks.com/products/splines' 'DISTCOMP' 'see http://www.mathworks.nl/products/parallel-computing/' 'COMPILER' 'see http://www.mathworks.com/products/compiler' 'FASTICA' 'see http://www.cis.hut.fi/projects/ica/fastica' 'BRAINSTORM' 'see http://neuroimage.ucs.edu/brainstorm' 'FILEIO' 'see http://www.fieldtriptoolbox.org' 'PREPROC' 'see http://www.fieldtriptoolbox.org' 'FORWARD' 'see http://www.fieldtriptoolbox.org' 'INVERSE' 'see http://www.fieldtriptoolbox.org' 'SPECEST' 'see http://www.fieldtriptoolbox.org' 'REALTIME' 'see http://www.fieldtriptoolbox.org' 'PLOTTING' 'see http://www.fieldtriptoolbox.org' 'SPIKE' 'see http://www.fieldtriptoolbox.org' 'CONNECTIVITY' 'see http://www.fieldtriptoolbox.org' 'PEER' 'see http://www.fieldtriptoolbox.org' 'PLOTTING' 'see http://www.fieldtriptoolbox.org' 'DENOISE' 'see http://lumiere.ens.fr/Audition/adc/meg, or contact Alain de Cheveigne' 'BCI2000' 'see http://bci2000.org' 'NLXNETCOM' 'see http://www.neuralynx.com' 'DIPOLI' 'see ftp://ftp.fcdonders.nl/pub/fieldtrip/external' 'MNE' 'see http://www.nmr.mgh.harvard.edu/martinos/userInfo/data/sofMNE.php' 'TCP_UDP_IP' 'see http://www.mathworks.com/matlabcentral/fileexchange/345, or contact Peter Rydesaeter' 'BEMCP' 'contact Christophe Phillips' 'OPENMEEG' 'see http://gforge.inria.fr/projects/openmeeg and http://gforge.inria.fr/frs/?group_id=435' 'PRTOOLS' 'see http://www.prtools.org' 'ITAB' 'contact Stefania Della Penna' 'BSMART' 'see http://www.brain-smart.org' 'PEER' 'see http://www.fieldtriptoolbox.org/development/peer' 'FREESURFER' 'see http://surfer.nmr.mgh.harvard.edu/fswiki' 'SIMBIO' 'see https://www.mrt.uni-jena.de/simbio/index.php/Main_Page' 'VGRID' 'see http://www.rheinahrcampus.de/~medsim/vgrid/manual.html' 'FNS' 'see http://hhvn.nmsu.edu/wiki/index.php/FNS' 'GIFTI' 'see http://www.artefact.tk/software/matlab/gifti' 'XML4MAT' 'see http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0' 'SQDPROJECT' 'see http://www.isr.umd.edu/Labs/CSSL/simonlab' 'BCT' 'see http://www.brain-connectivity-toolbox.net/' 'CCA' 'see http://www.imt.liu.se/~magnus/cca or contact Magnus Borga' 'EGI_MFF' 'see http://www.egi.com/ or contact either Phan Luu or Colin Davey at EGI' 'TOOLBOX_GRAPH' 'see http://www.mathworks.com/matlabcentral/fileexchange/5355-toolbox-graph or contact Gabriel Peyre' 'NETCDF' 'see http://www.mathworks.com/matlabcentral/fileexchange/15177' 'MYSQL' 'see http://www.mathworks.com/matlabcentral/fileexchange/8663-mysql-database-connector' 'ISO2MESH' 'see http://iso2mesh.sourceforge.net/cgi-bin/index.cgi?Home or contact Qianqian Fang' 'DATAHASH' 'see http://www.mathworks.com/matlabcentral/fileexchange/31272' 'IBTB' 'see http://www.ibtb.org' 'ICASSO' 'see http://www.cis.hut.fi/projects/ica/icasso' 'XUNIT' 'see http://www.mathworks.com/matlabcentral/fileexchange/22846-matlab-xunit-test-framework' 'PLEXON' 'available from http://www.plexon.com/assets/downloads/sdk/ReadingPLXandDDTfilesinMatlab-mexw.zip' 'MISC' 'various functions that were downloaded from http://www.mathworks.com/matlabcentral/fileexchange and elsewhere' '35625-INFORMATION-THEORY-TOOLBOX' 'see http://www.mathworks.com/matlabcentral/fileexchange/35625-information-theory-toolbox' '29046-MUTUAL-INFORMATION' 'see http://www.mathworks.com/matlabcentral/fileexchange/35625-information-theory-toolbox' '14888-MUTUAL-INFORMATION-COMPUTATION' 'see http://www.mathworks.com/matlabcentral/fileexchange/14888-mutual-information-computation' 'PLOT2SVG' 'see http://www.mathworks.com/matlabcentral/fileexchange/7401-scalable-vector-graphics-svg-export-of-figures' 'BRAINSUITE' 'see http://brainsuite.bmap.ucla.edu/processing/additional-tools/' 'BRAINVISA' 'see http://brainvisa.info' 'FILEEXCHANGE' 'see http://www.mathworks.com/matlabcentral/fileexchange/' 'NEURALYNX_V6' 'see http://neuralynx.com/research_software/file_converters_and_utilities/ and take the version from Neuralynx (windows only)' 'NEURALYNX_V3' 'see http://neuralynx.com/research_software/file_converters_and_utilities/ and take the version from Ueli Rutishauser' 'NPMK' 'see https://github.com/BlackrockMicrosystems/NPMK' 'VIDEOMEG' 'see https://github.com/andreyzhd/VideoMEG' 'WAVEFRONT' 'see http://mathworks.com/matlabcentral/fileexchange/27982-wavefront-obj-toolbox' 'NEURONE' 'see http://www.megaemg.com/support/unrestricted-downloads' }; if nargin<2 % default is not to add the path automatically autoadd = 0; end if nargin<3 % default is not to be silent silent = 0; end % determine whether the toolbox is installed toolbox = upper(toolbox); % In case SPM8 or higher not available, allow to use fallback toolbox fallback_toolbox=''; switch toolbox case 'AFNI' dependency={'BrikLoad', 'BrikInfo'}; case 'DSS' dependency={'denss', 'dss_create_state'}; case 'EEGLAB' dependency = 'runica'; case 'NWAY' dependency = 'parafac'; case 'SPM' dependency = 'spm'; % any version of SPM is fine case 'SPM99' dependency = {'spm', get_spm_version()==99}; case 'SPM2' dependency = {'spm', get_spm_version()==2}; case 'SPM5' dependency = {'spm', get_spm_version()==5}; case 'SPM8' dependency = {'spm', get_spm_version()==8}; case 'SPM8UP' % version 8 or later, but not SPM 9X dependency = {'spm', get_spm_version()>=8, get_spm_version()<95}; %This is to avoid crashes when trying to add SPM to the path fallback_toolbox = 'SPM8'; case 'SPM12' dependency = {'spm', get_spm_version()==12}; case 'MEG-PD' dependency = {'rawdata', 'channames'}; case 'MEG-CALC' dependency = {'megmodel', 'megfield', 'megtrans'}; case 'BIOSIG' dependency = {'sopen', 'sread'}; case 'EEG' dependency = {'ctf_read_res4', 'ctf_read_meg4'}; case 'EEGSF' % alternative name dependency = {'ctf_read_res4', 'ctf_read_meg4'}; case 'MRI' % other functions in the mri section dependency = {'avw_hdr_read', 'avw_img_read'}; case 'NEUROSHARE' dependency = {'ns_OpenFile', 'ns_SetLibrary', ... 'ns_GetAnalogData'}; case 'ARTINIS' dependency = {'read_artinis_oxy3'}; case 'BESA' dependency = {'readBESAavr', 'readBESAelp', 'readBESAswf'}; case 'MATLAB2BESA' dependency = {'besa_save2Avr', 'besa_save2Elp', 'besa_save2Swf'}; case 'EEPROBE' dependency = {'read_eep_avr', 'read_eep_cnt'}; case 'YOKOGAWA' dependency = @()hasyokogawa('16bitBeta6'); case 'YOKOGAWA12BITBETA3' dependency = @()hasyokogawa('12bitBeta3'); case 'YOKOGAWA16BITBETA3' dependency = @()hasyokogawa('16bitBeta3'); case 'YOKOGAWA16BITBETA6' dependency = @()hasyokogawa('16bitBeta6'); case 'YOKOGAWA_MEG_READER' dependency = @()hasyokogawa('1.4'); case 'BEOWULF' dependency = {'evalwulf', 'evalwulf', 'evalwulf'}; case 'MENTAT' dependency = {'pcompile', 'pfor', 'peval'}; case 'SON2' dependency = {'SONFileHeader', 'SONChanList', 'SONGetChannel'}; case '4D-VERSION' dependency = {'read4d', 'read4dhdr'}; case {'STATS', 'STATISTICS'} dependency = has_license('statistics_toolbox'); % check the availability of a toolbox license case {'OPTIM', 'OPTIMIZATION'} dependency = has_license('optimization_toolbox'); % check the availability of a toolbox license case {'SPLINES', 'CURVE_FITTING'} dependency = has_license('curve_fitting_toolbox'); % check the availability of a toolbox license case 'COMM' dependency = {has_license('communication_toolbox'), 'de2bi'}; % also check the availability of a toolbox license case 'SIGNAL' dependency = {has_license('signal_toolbox'), 'window'}; % also check the availability of a toolbox license case 'IMAGE' dependency = has_license('image_toolbox'); % check the availability of a toolbox license case {'DCT', 'DISTCOMP'} dependency = has_license('distrib_computing_toolbox'); % check the availability of a toolbox license case 'COMPILER' dependency = has_license('compiler'); % check the availability of a toolbox license case 'FASTICA' dependency = 'fpica'; case 'BRAINSTORM' dependency = 'bem_xfer'; case 'DENOISE' dependency = {'tsr', 'sns'}; case 'CTF' dependency = {'getCTFBalanceCoefs', 'getCTFdata'}; case 'BCI2000' dependency = {'load_bcidat'}; case 'NLXNETCOM' dependency = {'MatlabNetComClient', 'NlxConnectToServer', ... 'NlxGetNewCSCData'}; case 'DIPOLI' dependency = {'dipoli.maci', 'file'}; case 'MNE' dependency = {'fiff_read_meas_info', 'fiff_setup_read_raw'}; case 'TCP_UDP_IP' dependency = {'pnet', 'pnet_getvar', 'pnet_putvar'}; case 'BEMCP' dependency = {'bem_Cij_cog', 'bem_Cij_lin', 'bem_Cij_cst'}; case 'OPENMEEG' dependency = {'om_save_tri'}; case 'PRTOOLS' dependency = {'prversion', 'dataset', 'svc'}; case 'ITAB' dependency = {'lcReadHeader', 'lcReadData'}; case 'BSMART' dependency = 'bsmart'; case 'FREESURFER' dependency = {'MRIread', 'vox2ras_0to1'}; case 'FNS' dependency = 'elecsfwd'; case 'SIMBIO' dependency = {'calc_stiff_matrix_val', 'sb_transfer'}; case 'VGRID' dependency = 'vgrid'; case 'GIFTI' dependency = 'gifti'; case 'XML4MAT' dependency = {'xml2struct', 'xml2whos'}; case 'SQDPROJECT' dependency = {'sqdread', 'sqdwrite'}; case 'BCT' dependency = {'macaque71.mat', 'motif4funct_wei'}; case 'CCA' dependency = {'ccabss'}; case 'EGI_MFF' dependency = {'mff_getObject', 'mff_getSummaryInfo'}; case 'TOOLBOX_GRAPH' dependency = 'toolbox_graph'; case 'NETCDF' dependency = {'netcdf'}; case 'MYSQL' % not sure if 'which' would work fine here, so use 'exist' dependency = has_mex('mysql'); % this only consists of a single mex file case 'ISO2MESH' dependency = {'vol2surf', 'qmeshcut'}; case 'QSUB' dependency = {'qsubfeval', 'qsubcellfun'}; case 'ENGINE' dependency = {'enginefeval', 'enginecellfun'}; case 'DATAHASH' dependency = {'DataHash'}; case 'IBTB' dependency = {'make_ibtb','binr'}; case 'ICASSO' dependency = {'icassoEst'}; case 'XUNIT' dependency = {'initTestSuite', 'runtests'}; case 'PLEXON' dependency = {'plx_adchan_gains', 'mexPlex'}; case '35625-INFORMATION-THEORY-TOOLBOX' dependency = {'conditionalEntropy', 'entropy', 'jointEntropy',... 'mutualInformation' 'nmi' 'nvi' 'relativeEntropy'}; case '29046-MUTUAL-INFORMATION' dependency = {'MI', 'license.txt'}; case '14888-MUTUAL-INFORMATION-COMPUTATION' dependency = {'condentropy', 'demo_mi', 'estcondentropy.cpp',... 'estjointentropy.cpp', 'estpa.cpp', ... 'findjointstateab.cpp', 'makeosmex.m',... 'mutualinfo.m', 'condmutualinfo.m',... 'entropy.m', 'estentropy.cpp',... 'estmutualinfo.cpp', 'estpab.cpp',... 'jointentropy.m' 'mergemultivariables.m' }; case 'PLOT2SVG' dependency = {'plot2svg.m', 'simulink2svg.m'}; case 'BRAINSUITE' dependency = {'readdfs.m', 'writedfc.m'}; case 'BRAINVISA' dependency = {'loadmesh.m', 'plotmesh.m', 'savemesh.m'}; case 'NEURALYNX_V6' dependency = has_mex('Nlx2MatCSC'); case 'NEURALYNX_V3' dependency = has_mex('Nlx2MatCSC_v3'); case 'NPMK' dependency = {'OpenNSx' 'OpenNEV'}; case 'VIDEOMEG' dependency = {'comp_tstamps' 'load_audio0123', 'load_video123'}; case 'WAVEFRONT' dependency = {'write_wobj' 'read_wobj'}; case 'NEURONE' dependency = {'readneurone' 'readneuronedata' 'readneuroneevents'}; % the following are FieldTrip modules/toolboxes case 'FILEIO' dependency = {'ft_read_header', 'ft_read_data', ... 'ft_read_event', 'ft_read_sens'}; case 'FORWARD' dependency = {'ft_compute_leadfield', 'ft_prepare_vol_sens'}; case 'PLOTTING' dependency = {'ft_plot_topo', 'ft_plot_mesh', 'ft_plot_matrix'}; case 'PEER' dependency = {'peerslave', 'peermaster'}; case 'CONNECTIVITY' dependency = {'ft_connectivity_corr', 'ft_connectivity_granger'}; case 'SPIKE' dependency = {'ft_spiketriggeredaverage', 'ft_spiketriggeredspectrum'}; case 'FILEEXCHANGE' dependency = is_subdir_in_fieldtrip_path('/external/fileexchange'); case {'INVERSE', 'REALTIME', 'SPECEST', 'PREPROC', ... 'COMPAT', 'STATFUN', 'TRIALFUN', 'UTILITIES/COMPAT', ... 'FILEIO/COMPAT', 'PREPROC/COMPAT', 'FORWARD/COMPAT', ... 'PLOTTING/COMPAT', 'TEMPLATE/LAYOUT', 'TEMPLATE/ANATOMY' ,... 'TEMPLATE/HEADMODEL', 'TEMPLATE/ELECTRODE', ... 'TEMPLATE/NEIGHBOURS', 'TEMPLATE/SOURCEMODEL'} dependency = is_subdir_in_fieldtrip_path(toolbox); otherwise if ~silent, warning('cannot determine whether the %s toolbox is present', toolbox); end dependency = false; end status = is_present(dependency); if ~status && ~isempty(fallback_toolbox) % in case of SPM8UP toolbox = fallback_toolbox; end % try to determine the path of the requested toolbox if autoadd>0 && ~status % for core FieldTrip modules prefix = fileparts(which('ft_defaults')); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % for external FieldTrip modules prefix = fullfile(fileparts(which('ft_defaults')), 'external'); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); licensefile = [lower(toolbox) '_license']; if status && exist(licensefile, 'file') % this will execute openmeeg_license and mne_license % which display the license on screen for three seconds feval(licensefile); end end % for contributed FieldTrip extensions prefix = fullfile(fileparts(which('ft_defaults')), 'contrib'); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); licensefile = [lower(toolbox) '_license']; if status && exist(licensefile, 'file') % this will execute openmeeg_license and mne_license % which display the license on screen for three seconds feval(licensefile); end end % for linux computers in the Donders Centre for Cognitive Neuroimaging prefix = '/home/common/matlab'; if ~status && isdir(prefix) status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % for windows computers in the Donders Centre for Cognitive Neuroimaging prefix = 'h:\common\matlab'; if ~status && isdir(prefix) status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % use the MATLAB subdirectory in your homedirectory, this works on linux and mac prefix = fullfile(getenv('HOME'), 'matlab'); if ~status && isdir(prefix) status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end if ~status % the toolbox is not on the path and cannot be added sel = find(strcmp(url(:,1), toolbox)); if ~isempty(sel) msg = sprintf('the %s toolbox is not installed, %s', toolbox, url{sel, 2}); else msg = sprintf('the %s toolbox is not installed', toolbox); end if autoadd==1 error(msg); elseif autoadd==2 ft_warning(msg); else % fail silently end end end % this function is called many times in FieldTrip and associated toolboxes % use efficient handling if the same toolbox has been investigated before if status previous.(fixname(toolbox)) = status; end % remember the previous path, allows us to determine on the next call % whether the path has been modified outise of this function previouspath = path; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = myaddpath(toolbox, silent) if isdeployed warning('cannot change path settings for %s in a compiled application', toolbox); status = 1; elseif exist(toolbox, 'dir') if ~silent, ws = warning('backtrace', 'off'); warning('adding %s toolbox to your MATLAB path', toolbox); warning(ws); % return to the previous warning level end addpath(toolbox); status = 1; elseif (~isempty(regexp(toolbox, 'spm5$', 'once')) || ~isempty(regexp(toolbox, 'spm8$', 'once')) || ~isempty(regexp(toolbox, 'spm12$', 'once'))) && exist([toolbox 'b'], 'dir') status = myaddpath([toolbox 'b'], silent); else status = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function path = unixpath(path) %path(path=='\') = '/'; % replace backward slashes with forward slashes path = strrep(path,'\','/'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = hasfunction(funname, toolbox) try % call the function without any input arguments, which probably is inapropriate feval(funname); % it might be that the function without any input already works fine status = true; catch % either the function returned an error, or the function is not available % availability is influenced by the function being present and by having a % license for the function, i.e. in a concurrent licensing setting it might % be that all toolbox licenses are in use m = lasterror; if strcmp(m.identifier, 'MATLAB:license:checkouterror') if nargin>1 warning('the %s toolbox is available, but you don''t have a license for it', toolbox); else warning('the function ''%s'' is available, but you don''t have a license for it', funname); end status = false; elseif strcmp(m.identifier, 'MATLAB:UndefinedFunction') status = false; else % the function seems to be available and it gave an unknown error, % which is to be expected with inappropriate input arguments status = true; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = is_subdir_in_fieldtrip_path(toolbox_name) fttrunkpath = unixpath(fileparts(which('ft_defaults'))); fttoolboxpath = fullfile(fttrunkpath, lower(toolbox_name)); needle=[pathsep fttoolboxpath pathsep]; haystack = [pathsep path() pathsep]; status = ~isempty(findstr(needle, haystack)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = has_mex(name) full_name=[name '.' mexext]; status = (exist(full_name, 'file')==3); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function v = get_spm_version() if ~is_present('spm') v=NaN; return end version_str = spm('ver'); token = regexp(version_str,'(\d*)','tokens'); v = str2num([token{:}{:}]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = has_license(toolbox_name) status = license('checkout', toolbox_name)==1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = is_present(dependency) if iscell(dependency) % use recursion status = all(cellfun(@is_present,dependency)); elseif islogical(dependency) % boolean status = all(dependency); elseif ischar(dependency) % name of a function status = is_function_present_in_search_path(dependency); elseif isa(dependency, 'function_handle') status = dependency(); else assert(false,'this should not happen'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = is_function_present_in_search_path(function_name) w = which(function_name); % must be in path and not a variable status = ~isempty(w) && ~isequal(w, 'variable');
github
lcnbeapp/beapp-master
ft_test_run.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_test_run.m
6,568
utf_8
dfb4c969efe2182d441bddabe08d3dc6
function status = ft_test_run(varargin) % FT_TEST_RUN executes selected FieldTrip test scripts. It checks whether each test % script runs without problems as indicated by an explicit error and posts the % results on the FieldTrip dashboard. % % Use as % ft_test_run functionname % % Additional optional arguments are specified as key-value pairs and can include % dependency = string % maxmem = string % maxwalltime = string % % Test functions should not require any input arguments. % Output arguments of the test function will not be considered. % % See also FT_TEST_RESULT, FT_VERSION % Copyright (C) 2016, Robert oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/donders/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ optbeg = find(ismember(varargin, {'dependency', 'maxmem', 'maxwalltime'})); if ~isempty(optbeg) optarg = varargin(optbeg:end); varargin = varargin(1:optbeg-1); else optarg = {}; end % get the optional input arguments dependency = ft_getopt(optarg, 'dependency', {}); maxmem = ft_getopt(optarg, 'maxmem', inf); maxwalltime = ft_getopt(optarg, 'maxwalltime', inf); if ischar(dependency) % this should be a cell-array dependency = {dependency}; end if ischar(maxwalltime) % it is probably formatted as HH:MM:SS maxwalltime = str2walltime(maxwalltime); end if ischar(maxmem) % it is probably formatted as XXmb, or XXgb, ... maxmem = str2mem(maxmem); end % get the version and the path [revision, ftpath] = ft_version; % testing a work-in-progress version is not supported assert(istrue(ft_version('clean')), 'this requires all local changes to be committed'); %% determine the list of functions to test if ~isempty(varargin) && exist(varargin{1}, 'file') functionlist = varargin; else d = dir(fullfile(ftpath, 'test', 'test_*.m')); functionlist = {d.name}'; for i=1:numel(functionlist) functionlist{i} = functionlist{i}(1:end-2); % remove the extension end end %% determine the list of files to test filelist = cell(size(functionlist)); for i=1:numel(functionlist) filelist{i} = which(functionlist{i}); end fprintf('considering %d test scripts for execution\n', numel(filelist)); %% make a subselection based on the filters sel = true(size(filelist)); mem = zeros(size(filelist)); tim = zeros(size(filelist)); for i=1:numel(filelist) fid = fopen(filelist{i}, 'rt'); str = fread(fid, [1 inf], 'char=>char'); fclose(fid); line = tokenize(str, 10); if ~isempty(dependency) sel(i) = false; else sel(i) = true; end for k=1:numel(line) for j=1:numel(dependency) [s, e] = regexp(line{k}, sprintf('%% TEST.*%s.*', dependency{j}), 'once', 'start', 'end'); if ~isempty(s) sel(i) = true; end end [s, e] = regexp(line{k}, '% WALLTIME.*', 'once', 'start', 'end'); if ~isempty(s) s = s + length('% WALLTIME'); % strip this part tim(i) = str2walltime(line{k}(s:e)); end [s, e] = regexp(line{k}, '% MEM.*', 'once', 'start', 'end'); if ~isempty(s) s = s + length('% MEM'); % strip this part mem(i) = str2mem(line{k}(s:e)); end end % for each line end % for each function/file fprintf('%3d scripts do not meet the requirements for dependencies\n', sum(~sel)); fprintf('%3d scripts do not meet the requirements for memory\n', sum(mem>maxmem)); fprintf('%3d scripts do not meet the requirements for walltime \n', sum(tim>maxwalltime)); % remove test scripts that exceed walltime or memory sel(tim>maxwalltime) = false; sel(mem>maxmem) = false; % make the subselection of functions to test functionlist = functionlist(sel); fprintf('executing %d test scripts\n', numel(functionlist)); %% run over all tests for i=1:numel(functionlist) close all fprintf('================================================================================\n');; fprintf('=== evaluating %s\n', functionlist{i}); try stopwatch = tic; eval(functionlist{i}); status = true; runtime = round(toc(stopwatch)); fprintf('=== %s PASSED in %d seconds\n', functionlist{i}, runtime); catch status = false; runtime = round(toc(stopwatch)); fprintf('=== %s FAILED in %d seconds\n', functionlist{i}, runtime); end close all result = []; result.matlabversion = version('-release'); result.fieldtripversion = revision; result.branch = ft_version('branch'); result.hostname = gethostname; result.user = getusername; result.result = status; result.runtime = runtime; result.functionname = functionlist{i}; options = weboptions('MediaType','application/json'); webwrite('http://dashboard.fieldtriptoolbox.org/api', result, options); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function walltime = str2walltime(str) str = lower(strtrim(str)); walltime = str2double(str); if isnan(walltime) str = strtrim(str); hms = sscanf(str, '%d:%d:%d'); % hours, minutes, seconds walltime = 60*60*hms(1) + 60*hms(2) + hms(3); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function mem = str2mem(str) str = lower(strtrim(str)); mem = str2double(str); if isnan(mem) if ~isempty(regexp(str, '[0-9]*kb', 'once')) mem = str2double(str(1:end-2)) * 2^10; elseif ~isempty(regexp(str, '[0-9]*mb', 'once')) mem = str2double(str(1:end-2)) * 2^20; elseif ~isempty(regexp(str, '[0-9]*gb', 'once')) mem = str2double(str(1:end-2)) * 2^30; elseif ~isempty(regexp(str, '[0-9]*tb', 'once')) mem = str2double(str(1:end-2)) * 2^40; else mem = str2double(str); end end
github
lcnbeapp/beapp-master
ft_checkdata.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_checkdata.m
57,523
utf_8
361ae795581b786433b88af3f624763d
function [data] = ft_checkdata(data, varargin) % FT_CHECKDATA checks the input data of the main FieldTrip functions, e.g. whether % the type of data strucure corresponds with the required data. If neccessary % and possible, this function will adjust the data structure to the input % requirements (e.g. change dimord, average over trials, convert inside from % index into logical). % % If the input data does NOT correspond to the requirements, this function % is supposed to give a elaborate warning message and if applicable point % the user to external documentation (link to website). % % Use as % [data] = ft_checkdata(data, ...) % % Optional input arguments should be specified as key-value pairs and can include % feedback = yes, no % datatype = raw, freq, timelock, comp, spike, source, dip, volume, segmentation, parcellation % dimord = any combination of time, freq, chan, refchan, rpt, subj, chancmb, rpttap, pos % senstype = ctf151, ctf275, ctf151_planar, ctf275_planar, neuromag122, neuromag306, bti148, bti248, bti248_planar, magnetometer, electrode % inside = logical, index % ismeg = yes, no % isnirs = yes, no % hasunit = yes, no % hascoordsys = yes, no % hassampleinfo = yes, no, ifmakessense (only applies to raw data) % hascumtapcnt = yes, no (only applies to freq data) % hasdim = yes, no % hasdof = yes, no % cmbrepresentation = sparse, full (applies to covariance and cross-spectral density) % fsample = sampling frequency to use to go from SPIKE to RAW representation % segmentationstyle = indexed, probabilistic (only applies to segmentation) % parcellationstyle = indexed, probabilistic (only applies to parcellation) % hasbrain = yes, no (only applies to segmentation) % % For some options you can specify multiple values, e.g. % [data] = ft_checkdata(data, 'senstype', {'ctf151', 'ctf275'}), e.g. in megrealign % [data] = ft_checkdata(data, 'datatype', {'timelock', 'freq'}), e.g. in sourceanalysis % Copyright (C) 2007-2015, Robert Oostenveld % Copyright (C) 2010-2012, Martin Vinck % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % in case of an error this function could use dbstack for more detailled % user feedback % % this function should replace/encapsulate % fixdimord % fixinside % fixprecision % fixvolume % data2raw % raw2data % grid2transform % transform2grid % fourier2crsspctrm % freq2cumtapcnt % sensortype % time2offset % offset2time % fixsens -> this is kept a separate function because it should also be % called from other modules % % other potential uses for this function: % time -> offset in freqanalysis % average over trials % csd as matrix % FIXME the following is difficult, if not impossible, to support without knowing the parameter % FIXME it is presently (dec 2014) not being used anywhere in FT, so can be removed % hastrials = yes, no % get the optional input arguments feedback = ft_getopt(varargin, 'feedback', 'no'); dtype = ft_getopt(varargin, 'datatype'); % should not conflict with the ft_datatype function dimord = ft_getopt(varargin, 'dimord'); stype = ft_getopt(varargin, 'senstype'); % senstype is a function name which should not be masked ismeg = ft_getopt(varargin, 'ismeg'); isnirs = ft_getopt(varargin, 'isnirs'); inside = ft_getopt(varargin, 'inside'); % can be 'logical' or 'index' hastrials = ft_getopt(varargin, 'hastrials'); hasunit = ft_getopt(varargin, 'hasunit', 'no'); hascoordsys = ft_getopt(varargin, 'hascoordsys', 'no'); hassampleinfo = ft_getopt(varargin, 'hassampleinfo', 'ifmakessense'); hasdim = ft_getopt(varargin, 'hasdim'); hascumtapcnt = ft_getopt(varargin, 'hascumtapcnt'); hasdof = ft_getopt(varargin, 'hasdof'); cmbrepresentation = ft_getopt(varargin, 'cmbrepresentation'); channelcmb = ft_getopt(varargin, 'channelcmb'); fsample = ft_getopt(varargin, 'fsample'); segmentationstyle = ft_getopt(varargin, 'segmentationstyle'); % this will be passed on to the corresponding ft_datatype_xxx function parcellationstyle = ft_getopt(varargin, 'parcellationstyle'); % this will be passed on to the corresponding ft_datatype_xxx function hasbrain = ft_getopt(varargin, 'hasbrain'); % check whether people are using deprecated stuff depHastrialdef = ft_getopt(varargin, 'hastrialdef'); if (~isempty(depHastrialdef)) ft_warning('ft_checkdata option ''hastrialdef'' is deprecated; use ''hassampleinfo'' instead'); hassampleinfo = depHastrialdef; end % determine the type of input data % this can be raw, freq, timelock, comp, spike, source, volume, dip israw = ft_datatype(data, 'raw'); isfreq = ft_datatype(data, 'freq'); istimelock = ft_datatype(data, 'timelock'); iscomp = ft_datatype(data, 'comp'); isspike = ft_datatype(data, 'spike'); isvolume = ft_datatype(data, 'volume'); issegmentation = ft_datatype(data, 'segmentation'); isparcellation = ft_datatype(data, 'parcellation'); issource = ft_datatype(data, 'source'); isdip = ft_datatype(data, 'dip'); ismvar = ft_datatype(data, 'mvar'); isfreqmvar = ft_datatype(data, 'freqmvar'); ischan = ft_datatype(data, 'chan'); ismesh = ft_datatype(data, 'mesh'); % FIXME use the istrue function on ismeg and hasxxx options if ~isequal(feedback, 'no') if iscomp % it can be comp and raw/timelock/freq at the same time, therefore this has to go first nchan = size(data.topo,1); ncomp = size(data.topo,2); fprintf('the input is component data with %d components and %d original channels\n', ncomp, nchan); end if israw nchan = length(data.label); ntrial = length(data.trial); fprintf('the input is raw data with %d channels and %d trials\n', nchan, ntrial); elseif istimelock nchan = length(data.label); ntime = length(data.time); fprintf('the input is timelock data with %d channels and %d timebins\n', nchan, ntime); elseif isfreq if isfield(data, 'label') nchan = length(data.label); nfreq = length(data.freq); if isfield(data, 'time'), ntime = num2str(length(data.time)); else ntime = 'no'; end fprintf('the input is freq data with %d channels, %d frequencybins and %s timebins\n', nchan, nfreq, ntime); elseif isfield(data, 'labelcmb') nchan = length(data.labelcmb); nfreq = length(data.freq); if isfield(data, 'time'), ntime = num2str(length(data.time)); else ntime = 'no'; end fprintf('the input is freq data with %d channel combinations, %d frequencybins and %s timebins\n', nchan, nfreq, ntime); else error('cannot infer freq dimensions'); end elseif isspike nchan = length(data.label); fprintf('the input is spike data with %d channels\n', nchan); elseif isvolume if issegmentation subtype = 'segmented volume'; else subtype = 'volume'; end fprintf('the input is %s data with dimensions [%d %d %d]\n', subtype, data.dim(1), data.dim(2), data.dim(3)); clear subtype elseif issource data = fixpos(data); % ensure that positions are in pos, not in pnt nsource = size(data.pos, 1); if isparcellation subtype = 'parcellated source'; else subtype = 'source'; end if isfield(data, 'dim') fprintf('the input is %s data with %d brainordinates on a [%d %d %d] grid\n', subtype, nsource, data.dim(1), data.dim(2), data.dim(3)); elseif isfield(data, 'tri') fprintf('the input is %s data with %d vertex positions and %d triangles\n', subtype, nsource, size(data.tri, 1)); else fprintf('the input is %s data with %d brainordinates\n', subtype, nsource); end clear subtype elseif isdip fprintf('the input is dipole data\n'); elseif ismvar fprintf('the input is mvar data\n'); elseif isfreqmvar fprintf('the input is freqmvar data\n'); elseif ischan nchan = length(data.label); if isfield(data, 'brainordinate') fprintf('the input is parcellated data with %d parcels\n', nchan); else fprintf('the input is chan data with %d channels\n', nchan); end end elseif ismesh data = fixpos(data); if numel(data)==1 if isfield(data,'tri') fprintf('the input is mesh data with %d vertices and %d triangles\n', size(data.pos,1), size(data.tri,1)); elseif isfield(data,'hex') fprintf('the input is mesh data with %d vertices and %d hexahedrons\n', size(data.pos,1), size(data.hex,1)); elseif isfield(data,'tet') fprintf('the input is mesh data with %d vertices and %d tetrahedrons\n', size(data.pos,1), size(data.tet,1)); else fprintf('the input is mesh data with %d vertices', size(data.pos,1)); end else fprintf('the input is mesh data multiple surfaces\n'); end end % give feedback if issource && isvolume % it should be either one or the other: the choice here is to represent it as volume description since that is simpler to handle % the conversion is done by removing the grid positions data = rmfield(data, 'pos'); issource = false; end % the ft_datatype_XXX functions ensures the consistency of the XXX datatype % and provides a detailed description of the dataformat and its history if iscomp % this should go before israw/istimelock/isfreq data = ft_datatype_comp(data, 'hassampleinfo', hassampleinfo); elseif israw data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); elseif istimelock data = ft_datatype_timelock(data); elseif isfreq data = ft_datatype_freq(data); elseif isspike data = ft_datatype_spike(data); elseif issegmentation % this should go before isvolume data = ft_datatype_segmentation(data, 'segmentationstyle', segmentationstyle, 'hasbrain', hasbrain); elseif isvolume data = ft_datatype_volume(data); elseif isparcellation % this should go before issource data = ft_datatype_parcellation(data, 'parcellationstyle', parcellationstyle); elseif issource data = ft_datatype_source(data); elseif isdip data = ft_datatype_dip(data); elseif ismvar || isfreqmvar data = ft_datatype_mvar(data); end if ~isempty(dtype) if ~isa(dtype, 'cell') dtype = {dtype}; end okflag = 0; for i=1:length(dtype) % check that the data matches with one or more of the required ft_datatypes switch dtype{i} case 'raw+comp' okflag = okflag + (israw & iscomp); case 'freq+comp' okflag = okflag + (isfreq & iscomp); case 'timelock+comp' okflag = okflag + (istimelock & iscomp); case 'raw' okflag = okflag + (israw & ~iscomp); case 'freq' okflag = okflag + (isfreq & ~iscomp); case 'timelock' okflag = okflag + (istimelock & ~iscomp); case 'comp' okflag = okflag + (iscomp & ~(israw | istimelock | isfreq)); case 'spike' okflag = okflag + isspike; case 'volume' okflag = okflag + isvolume; case 'source' okflag = okflag + issource; case 'dip' okflag = okflag + isdip; case 'mvar' okflag = okflag + ismvar; case 'freqmvar' okflag = okflag + isfreqmvar; case 'chan' okflag = okflag + ischan; case 'segmentation' okflag = okflag + issegmentation; case 'parcellation' okflag = okflag + isparcellation; case 'mesh' okflag = okflag + ismesh; end % switch dtype end % for dtype % try to convert the data if needed for iCell = 1:length(dtype) if okflag % the requested datatype is specified in descending order of % preference (if there is a preference at all), so don't bother % checking the rest of the requested data types if we already % succeeded in converting break; end if isequal(dtype(iCell), {'parcellation'}) && issegmentation data = volume2source(data); % segmentation=volume, parcellation=source data = ft_datatype_parcellation(data); issegmentation = 0; isvolume = 0; isparcellation = 1; issource = 1; okflag = 1; elseif isequal(dtype(iCell), {'segmentation'}) && isparcellation data = source2volume(data); % segmentation=volume, parcellation=source data = ft_datatype_segmentation(data); isparcellation = 0; issource = 0; issegmentation = 1; isvolume = 1; okflag = 1; elseif isequal(dtype(iCell), {'source'}) && isvolume data = volume2source(data); data = ft_datatype_source(data); isvolume = 0; issource = 1; okflag = 1; elseif isequal(dtype(iCell), {'volume'}) && (ischan || istimelock || isfreq) data = parcellated2source(data); data = ft_datatype_volume(data); ischan = 0; isvolume = 1; okflag = 1; elseif isequal(dtype(iCell), {'source'}) && (ischan || istimelock || isfreq) data = parcellated2source(data); data = ft_datatype_source(data); ischan = 0; issource = 1; okflag = 1; elseif isequal(dtype(iCell), {'volume'}) && issource data = source2volume(data); data = ft_datatype_volume(data); isvolume = 1; issource = 0; okflag = 1; elseif isequal(dtype(iCell), {'raw+comp'}) && istimelock && iscomp data = timelock2raw(data); data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); istimelock = 0; iscomp = 1; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && issource data = source2raw(data); data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); issource = 0; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && istimelock if iscomp data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired iscomp = 0; end data = timelock2raw(data); data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); istimelock = 0; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'comp'}) && israw data = keepfields(data, {'label', 'topo', 'topolabel', 'unmixing', 'elec', 'grad', 'cfg'}); % these are the only relevant fields data = ft_datatype_comp(data); israw = 0; iscomp = 1; okflag = 1; elseif isequal(dtype(iCell), {'comp'}) && istimelock data = keepfields(data, {'label', 'topo', 'topolabel', 'unmixing', 'elec', 'grad', 'cfg'}); % these are the only relevant fields data = ft_datatype_comp(data); istimelock = 0; iscomp = 1; okflag = 1; elseif isequal(dtype(iCell), {'comp'}) && isfreq data = keepfields(data, {'label', 'topo', 'topolabel', 'unmixing', 'elec', 'grad', 'cfg'}); % these are the only relevant fields data = ft_datatype_comp(data); isfreq = 0; iscomp = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && israw if iscomp data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired iscomp = 0; end data = ft_datatype_raw(data); okflag = 1; elseif isequal(dtype(iCell), {'timelock'}) && istimelock if iscomp data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired iscomp = 0; end data = ft_datatype_timelock(data); okflag = 1; elseif isequal(dtype(iCell), {'freq'}) && isfreq if iscomp data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired iscomp = 0; end data = ft_datatype_freq(data); okflag = 1; elseif isequal(dtype(iCell), {'timelock'}) && israw if iscomp data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired iscomp = 0; end data = raw2timelock(data); data = ft_datatype_timelock(data); israw = 0; istimelock = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && isfreq if iscomp data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired iscomp = 0; end data = freq2raw(data); data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); isfreq = 0; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && ischan data = chan2timelock(data); data = timelock2raw(data); data = ft_datatype_raw(data); ischan = 0; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'timelock'}) && ischan data = chan2timelock(data); data = ft_datatype_timelock(data); ischan = 0; istimelock = 1; okflag = 1; elseif isequal(dtype(iCell), {'freq'}) && ischan data = chan2freq(data); data = ft_datatype_freq(data); ischan = 0; isfreq = 1; okflag = 1; elseif isequal(dtype(iCell), {'spike'}) && israw data = raw2spike(data); data = ft_datatype_spike(data); israw = 0; isspike = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && isspike data = spike2raw(data,fsample); data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); isspike = 0; israw = 1; okflag = 1; end end % for iCell if ~okflag % construct an error message if length(dtype)>1 str = sprintf('%s, ', dtype{1:(end-2)}); str = sprintf('%s%s or %s', str, dtype{end-1}, dtype{end}); else str = dtype{1}; end error('This function requires %s data as input.', str); end % if okflag end if ~isempty(dimord) if ~isa(dimord, 'cell') dimord = {dimord}; end if isfield(data, 'dimord') okflag = any(strcmp(data.dimord, dimord)); else okflag = 0; end if ~okflag % construct an error message if length(dimord)>1 str = sprintf('%s, ', dimord{1:(end-2)}); str = sprintf('%s%s or %s', str, dimord{end-1}, dimord{end}); else str = dimord{1}; end error('This function requires data with a dimord of %s.', str); end % if okflag end if ~isempty(stype) if ~isa(stype, 'cell') stype = {stype}; end if isfield(data, 'grad') || isfield(data, 'elec') || isfield(data, 'opto') if any(strcmp(ft_senstype(data), stype)) okflag = 1; elseif any(cellfun(@ft_senstype, repmat({data}, size(stype)), stype)) % this is required to detect more general types, such as "meg" or "ctf" rather than "ctf275" okflag = 1; else okflag = 0; end end if ~okflag % construct an error message if length(stype)>1 str = sprintf('%s, ', stype{1:(end-2)}); str = sprintf('%s%s or %s', str, stype{end-1}, stype{end}); else str = stype{1}; end error('This function requires %s data as input, but you are giving %s data.', str, ft_senstype(data)); end % if okflag end if ~isempty(ismeg) if isequal(ismeg, 'yes') okflag = isfield(data, 'grad'); elseif isequal(ismeg, 'no') okflag = ~isfield(data, 'grad'); end if ~okflag && isequal(ismeg, 'yes') error('This function requires MEG data with a ''grad'' field'); elseif ~okflag && isequal(ismeg, 'no') error('This function should not be given MEG data with a ''grad'' field'); end % if okflag end if ~isempty(isnirs) if isequal(isnirs, 'yes') okflag = isfield(data, 'opto'); elseif isequal(isnirs, 'no') okflag = ~isfield(data, 'opto'); end if ~okflag && isequal(isnirs, 'yes') error('This function requires NIRS data with an ''opto'' field'); elseif ~okflag && isequal(isnirs, 'no') error('This function should not be given NIRS data with an ''opto'' field'); end % if okflag end if ~isempty(inside) if strcmp(inside, 'index') warning('the indexed representation of inside/outside source locations is deprecated'); end % TODO absorb the fixinside function into this code data = fixinside(data, inside); okflag = isfield(data, 'inside'); if ~okflag % construct an error message error('This function requires data with an ''inside'' field.'); end % if okflag end if istrue(hasunit) && ~isfield(data, 'unit') % calling convert_units with only the input data adds the units without converting data = ft_convert_units(data); end % if hasunit if istrue(hascoordsys) && ~isfield(data, 'coordsys') data = ft_determine_coordsys(data); end % if hascoordsys if isequal(hastrials, 'yes') okflag = isfield(data, 'trial'); if ~okflag && isfield(data, 'dimord') % instead look in the dimord for rpt or subj okflag = ~isempty(strfind(data.dimord, 'rpt')) || ... ~isempty(strfind(data.dimord, 'rpttap')) || ... ~isempty(strfind(data.dimord, 'subj')); end if ~okflag error('This function requires data with a ''trial'' field'); end % if okflag end if strcmp(hasdim, 'yes') && ~isfield(data, 'dim') data.dim = pos2dim(data.pos); elseif strcmp(hasdim, 'no') && isfield(data, 'dim') data = rmfield(data, 'dim'); end % if hasdim if strcmp(hascumtapcnt, 'yes') && ~isfield(data, 'cumtapcnt') error('This function requires data with a ''cumtapcnt'' field'); elseif strcmp(hascumtapcnt, 'no') && isfield(data, 'cumtapcnt') data = rmfield(data, 'cumtapcnt'); end % if hascumtapcnt if strcmp(hasdof, 'yes') && ~isfield(data, 'dof') error('This function requires data with a ''dof'' field'); elseif strcmp(hasdof, 'no') && isfield(data, 'dof') data = rmfield(data, 'dof'); end % if hasdof if ~isempty(cmbrepresentation) if istimelock data = fixcov(data, cmbrepresentation); elseif isfreq data = fixcsd(data, cmbrepresentation, channelcmb); elseif isfreqmvar data = fixcsd(data, cmbrepresentation, channelcmb); else error('This function requires data with a covariance, coherence or cross-spectrum'); end end % cmbrepresentation if isfield(data, 'grad') % ensure that the gradiometer structure is up to date data.grad = ft_datatype_sens(data.grad); end if isfield(data, 'elec') % ensure that the electrode structure is up to date data.elec = ft_datatype_sens(data.elec); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % represent the covariance matrix in a particular manner %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = fixcov(data, desired) if any(isfield(data, {'cov', 'corr'})) if ~isfield(data, 'labelcmb') current = 'full'; else current = 'sparse'; end else error('Could not determine the current representation of the covariance matrix'); end if isequal(current, desired) % nothing to do elseif strcmp(current, 'full') && strcmp(desired, 'sparse') % FIXME should be implemented error('not yet implemented'); elseif strcmp(current, 'sparse') && strcmp(desired, 'full') % FIXME should be implemented error('not yet implemented'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % represent the cross-spectral density matrix in a particular manner %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = fixcsd(data, desired, channelcmb) % FIXCSD converts univariate frequency domain data (fourierspctrm) into a bivariate % representation (crsspctrm), or changes the representation of bivariate frequency % domain data (sparse/full/sparsewithpow, sparsewithpow only works for crsspctrm or % fourierspctrm) % Copyright (C) 2010, Jan-Mathijs Schoffelen, Robert Oostenveld if isfield(data, 'crsspctrm') && isfield(data, 'powspctrm') current = 'sparsewithpow'; elseif isfield(data, 'powspctrm') current = 'sparsewithpow'; elseif isfield(data, 'fourierspctrm') && ~isfield(data, 'labelcmb') current = 'fourier'; elseif ~isfield(data, 'labelcmb') current = 'full'; elseif isfield(data, 'labelcmb') current = 'sparse'; else error('Could not determine the current representation of the %s matrix', param); end % first go from univariate fourier to the required bivariate representation if isequal(current, desired) % nothing to do elseif strcmp(current, 'fourier') && strcmp(desired, 'sparsewithpow') dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpttap', dimtok)), nrpt = size(data.cumtapcnt,1); flag = 0; else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end fastflag = all(data.cumtapcnt(:)==data.cumtapcnt(1)); flag = nrpt==1; % needed to truncate the singleton dimension upfront %create auto-spectra nchan = length(data.label); if fastflag % all trials have the same amount of tapers powspctrm = zeros(nrpt,nchan,nfrq,ntim); ntap = data.cumtapcnt(1); for p = 1:ntap powspctrm = powspctrm + abs(data.fourierspctrm(p:ntap:end,:,:,:,:)).^2; end powspctrm = powspctrm./ntap; else % different amount of tapers powspctrm = zeros(nrpt,nchan,nfrq,ntim)+i.*zeros(nrpt,nchan,nfrq,ntim); sumtapcnt = [0;cumsum(data.cumtapcnt(:))]; for p = 1:nrpt indx = (sumtapcnt(p)+1):sumtapcnt(p+1); tmpdat = data.fourierspctrm(indx,:,:,:); powspctrm(p,:,:,:) = (sum(tmpdat.*conj(tmpdat),1))./data.cumtapcnt(p); end end %create cross-spectra if ~isempty(channelcmb), ncmb = size(channelcmb,1); cmbindx = zeros(ncmb,2); labelcmb = cell(ncmb,2); for k = 1:ncmb ch1 = find(strcmp(data.label, channelcmb(k,1))); ch2 = find(strcmp(data.label, channelcmb(k,2))); if ~isempty(ch1) && ~isempty(ch2), cmbindx(k,:) = [ch1 ch2]; labelcmb(k,:) = data.label([ch1 ch2])'; end end crsspctrm = zeros(nrpt,ncmb,nfrq,ntim)+i.*zeros(nrpt,ncmb,nfrq,ntim); if fastflag for p = 1:ntap tmpdat1 = data.fourierspctrm(p:ntap:end,cmbindx(:,1),:,:,:); tmpdat2 = data.fourierspctrm(p:ntap:end,cmbindx(:,2),:,:,:); crsspctrm = crsspctrm + tmpdat1.*conj(tmpdat2); end crsspctrm = crsspctrm./ntap; else for p = 1:nrpt indx = (sumtapcnt(p)+1):sumtapcnt(p+1); tmpdat1 = data.fourierspctrm(indx,cmbindx(:,1),:,:); tmpdat2 = data.fourierspctrm(indx,cmbindx(:,2),:,:); crsspctrm(p,:,:,:) = (sum(tmpdat1.*conj(tmpdat2),1))./data.cumtapcnt(p); end end data.crsspctrm = crsspctrm; data.labelcmb = labelcmb; end data.powspctrm = powspctrm; data = rmfield(data, 'fourierspctrm'); if ntim>1, data.dimord = 'chan_freq_time'; else data.dimord = 'chan_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end if flag, siz = size(data.powspctrm); data.powspctrm = reshape(data.powspctrm, [siz(2:end) 1]); if isfield(data, 'crsspctrm') siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, [siz(2:end) 1]); end end elseif strcmp(current, 'fourier') && strcmp(desired, 'sparse') if isempty(channelcmb), error('no channel combinations are specified'); end dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpttap', dimtok)), nrpt = size(data.cumtapcnt,1); flag = 0; else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end flag = nrpt==1; % flag needed to squeeze first dimension if singleton ncmb = size(channelcmb,1); cmbindx = zeros(ncmb,2); labelcmb = cell(ncmb,2); for k = 1:ncmb ch1 = find(strcmp(data.label, channelcmb(k,1))); ch2 = find(strcmp(data.label, channelcmb(k,2))); if ~isempty(ch1) && ~isempty(ch2), cmbindx(k,:) = [ch1 ch2]; labelcmb(k,:) = data.label([ch1 ch2])'; end end sumtapcnt = [0;cumsum(data.cumtapcnt(:))]; fastflag = all(data.cumtapcnt(:)==data.cumtapcnt(1)); if fastflag && nrpt>1 ntap = data.cumtapcnt(1); % compute running sum across tapers siz = [size(data.fourierspctrm) 1]; for p = 1:ntap indx = p:ntap:nrpt*ntap; if p==1. tmpc = zeros(numel(indx), size(cmbindx,1), siz(3), siz(4)) + ... 1i.*zeros(numel(indx), size(cmbindx,1), siz(3), siz(4)); end for k = 1:size(cmbindx,1) tmpc(:,k,:,:) = data.fourierspctrm(indx,cmbindx(k,1),:,:).* ... conj(data.fourierspctrm(indx,cmbindx(k,2),:,:)); end if p==1 crsspctrm = tmpc; else crsspctrm = tmpc + crsspctrm; end end crsspctrm = crsspctrm./ntap; else crsspctrm = zeros(nrpt, ncmb, nfrq, ntim); for p = 1:nrpt indx = (sumtapcnt(p)+1):sumtapcnt(p+1); tmpdat1 = data.fourierspctrm(indx,cmbindx(:,1),:,:); tmpdat2 = data.fourierspctrm(indx,cmbindx(:,2),:,:); crsspctrm(p,:,:,:) = (sum(tmpdat1.*conj(tmpdat2),1))./data.cumtapcnt(p); end end data.crsspctrm = crsspctrm; data.labelcmb = labelcmb; data = rmfield(data, 'fourierspctrm'); data = rmfield(data, 'label'); if ntim>1, data.dimord = 'chancmb_freq_time'; else data.dimord = 'chancmb_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end if flag, % deal with the singleton 'rpt', i.e. remove it siz = size(data.powspctrm); data.powspctrm = reshape(data.powspctrm, [siz(2:end) 1]); if isfield(data,'crsspctrm') % this conditional statement is needed in case there's a single channel siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, [siz(2:end) 1]); end end elseif strcmp(current, 'fourier') && strcmp(desired, 'full') % this is how it is currently and the desired functionality of prepare_freq_matrices dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpttap', dimtok)), nrpt = size(data.cumtapcnt, 1); flag = 0; else nrpt = 1; flag = 1; end if ~isempty(strmatch('rpttap',dimtok)), nrpt=size(data.cumtapcnt, 1); else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end if any(data.cumtapcnt(1,:) ~= data.cumtapcnt(1,1)), error('this only works when all frequencies have the same number of tapers'); end nchan = length(data.label); crsspctrm = zeros(nrpt,nchan,nchan,nfrq,ntim); sumtapcnt = [0;cumsum(data.cumtapcnt(:,1))]; for k = 1:ntim for m = 1:nfrq for p = 1:nrpt %FIXME speed this up in the case that all trials have equal number of tapers indx = (sumtapcnt(p)+1):sumtapcnt(p+1); tmpdat = transpose(data.fourierspctrm(indx,:,m,k)); crsspctrm(p,:,:,m,k) = (tmpdat*tmpdat')./data.cumtapcnt(p); clear tmpdat; end end end data.crsspctrm = crsspctrm; data = rmfield(data, 'fourierspctrm'); if ntim>1, data.dimord = 'chan_chan_freq_time'; else data.dimord = 'chan_chan_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end % remove first singleton dimension if flag || nrpt==1, siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, siz(2:end)); end elseif strcmp(current, 'fourier') && strcmp(desired, 'fullfast'), dimtok = tokenize(data.dimord, '_'); nrpt = size(data.fourierspctrm, 1); nchn = numel(data.label); nfrq = numel(data.freq); if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end data.fourierspctrm = reshape(data.fourierspctrm, [nrpt nchn nfrq*ntim]); data.fourierspctrm(~isfinite(data.fourierspctrm)) = 0; crsspctrm = complex(zeros(nchn,nchn,nfrq*ntim)); for k = 1:nfrq*ntim tmp = transpose(data.fourierspctrm(:,:,k)); n = sum(tmp~=0,2); crsspctrm(:,:,k) = tmp*tmp'./n(1); end data = rmfield(data, 'fourierspctrm'); data.crsspctrm = reshape(crsspctrm, [nchn nchn nfrq ntim]); if isfield(data, 'time'), data.dimord = 'chan_chan_freq_time'; else data.dimord = 'chan_chan_freq'; end if isfield(data, 'trialinfo'), data = rmfield(data, 'trialinfo'); end; if isfield(data, 'sampleinfo'), data = rmfield(data, 'sampleinfo'); end; if isfield(data, 'cumsumcnt'), data = rmfield(data, 'cumsumcnt'); end; if isfield(data, 'cumtapcnt'), data = rmfield(data, 'cumtapcnt'); end; end % convert to the requested bivariate representation % from one bivariate representation to another if isequal(current, desired) % nothing to do elseif (strcmp(current, 'full') && strcmp(desired, 'fourier')) || ... (strcmp(current, 'sparse') && strcmp(desired, 'fourier')) || ... (strcmp(current, 'sparsewithpow') && strcmp(desired, 'fourier')) % this is not possible error('converting the cross-spectrum into a Fourier representation is not possible'); elseif strcmp(current, 'full') && strcmp(desired, 'sparsewithpow') error('not yet implemented'); elseif strcmp(current, 'sparse') && strcmp(desired, 'sparsewithpow') % convert back to crsspctrm/powspctrm representation: useful for plotting functions etc indx = labelcmb2indx(data.labelcmb); autoindx = indx(indx(:,1)==indx(:,2), 1); cmbindx = setdiff([1:size(indx,1)]', autoindx); if strcmp(data.dimord(1:3), 'rpt') data.powspctrm = data.crsspctrm(:, autoindx, :, :); data.crsspctrm = data.crsspctrm(:, cmbindx, :, :); else data.powspctrm = data.crsspctrm(autoindx, :, :); data.crsspctrm = data.crsspctrm(cmbindx, :, :); end data.label = data.labelcmb(autoindx,1); data.labelcmb = data.labelcmb(cmbindx, :); if isempty(cmbindx) data = rmfield(data, 'crsspctrm'); data = rmfield(data, 'labelcmb'); end elseif strcmp(current, 'full') && strcmp(desired, 'sparse') dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end nchan = length(data.label); ncmb = nchan*nchan; labelcmb = cell(ncmb, 2); cmbindx = zeros(nchan, nchan); k = 1; for j=1:nchan for m=1:nchan labelcmb{k, 1} = data.label{m}; labelcmb{k, 2} = data.label{j}; cmbindx(m,j) = k; k = k+1; end end % reshape all possible fields fn = fieldnames(data); for ii=1:numel(fn) if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim; if nrpt>1, data.(fn{ii}) = reshape(data.(fn{ii}), nrpt, ncmb, nfrq, ntim); else data.(fn{ii}) = reshape(data.(fn{ii}), ncmb, nfrq, ntim); end end end % remove obsolete fields data = rmfield(data, 'label'); try data = rmfield(data, 'dof'); end % replace updated fields data.labelcmb = labelcmb; if ntim>1, data.dimord = 'chancmb_freq_time'; else data.dimord = 'chancmb_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end elseif strcmp(current, 'sparsewithpow') && strcmp(desired, 'sparse') % this representation for sparse data contains autospectra as e.g. {'A' 'A'} in labelcmb if isfield(data, 'crsspctrm'), dimtok = tokenize(data.dimord, '_'); catdim = match_str(dimtok, {'chan' 'chancmb'}); data.crsspctrm = cat(catdim, data.powspctrm, data.crsspctrm); data.labelcmb = [data.label(:) data.label(:); data.labelcmb]; data = rmfield(data, 'powspctrm'); data.dimord = strrep(data.dimord, 'chan_', 'chancmb_'); else data.crsspctrm = data.powspctrm; data.labelcmb = [data.label(:) data.label(:)]; data = rmfield(data, 'powspctrm'); data.dimord = strrep(data.dimord, 'chan_', 'chancmb_'); end data = rmfield(data, 'label'); elseif strcmp(current, 'sparse') && strcmp(desired, 'full') dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end if ~isfield(data, 'label') % ensure that the bivariate spectral factorization results can be % processed. FIXME this is experimental and will not work if the user % did something weird before for k = 1:numel(data.labelcmb) tmp = tokenize(data.labelcmb{k}, '['); data.labelcmb{k} = tmp{1}; end data.label = unique(data.labelcmb(:)); end nchan = length(data.label); ncmb = size(data.labelcmb,1); cmbindx = zeros(nchan,nchan); for k = 1:size(data.labelcmb,1) ch1 = find(strcmp(data.label, data.labelcmb(k,1))); ch2 = find(strcmp(data.label, data.labelcmb(k,2))); if ~isempty(ch1) && ~isempty(ch2), cmbindx(ch1,ch2) = k; end end complete = all(cmbindx(:)~=0); % remove obsolete fields try data = rmfield(data, 'powspctrm'); end try data = rmfield(data, 'labelcmb'); end try data = rmfield(data, 'dof'); end fn = fieldnames(data); for ii=1:numel(fn) if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim; if nrpt==1, data.(fn{ii}) = reshape(data.(fn{ii}), [nrpt ncmb nfrq ntim]); end tmpall = nan(nrpt,nchan,nchan,nfrq,ntim); for j = 1:nrpt for k = 1:ntim for m = 1:nfrq tmpdat = nan(nchan,nchan); indx = find(cmbindx); if ~complete % this realizes the missing combinations to be represented as the % conjugate of the corresponding combination across the diagonal tmpdat(indx) = reshape(data.(fn{ii})(j,cmbindx(indx),m,k),[numel(indx) 1]); tmpdat = ctranspose(tmpdat); end tmpdat(indx) = reshape(data.(fn{ii})(j,cmbindx(indx),m,k),[numel(indx) 1]); tmpall(j,:,:,m,k) = tmpdat; end % for m end % for k end % for j % replace the data in the old representation with the new representation if nrpt>1, data.(fn{ii}) = tmpall; else data.(fn{ii}) = reshape(tmpall, [nchan nchan nfrq ntim]); end end % if numel end % for ii if ntim>1, data.dimord = 'chan_chan_freq_time'; else data.dimord = 'chan_chan_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end elseif strcmp(current, 'sparse') && strcmp(desired, 'fullfast') dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end if ~isfield(data, 'label') data.label = unique(data.labelcmb(:)); end nchan = length(data.label); ncmb = size(data.labelcmb,1); cmbindx = zeros(nchan,nchan); for k = 1:size(data.labelcmb,1) ch1 = find(strcmp(data.label, data.labelcmb(k,1))); ch2 = find(strcmp(data.label, data.labelcmb(k,2))); if ~isempty(ch1) && ~isempty(ch2), cmbindx(ch1,ch2) = k; end end complete = all(cmbindx(:)~=0); fn = fieldnames(data); for ii=1:numel(fn) if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim; if nrpt==1, data.(fn{ii}) = reshape(data.(fn{ii}), [nrpt ncmb nfrq ntim]); end tmpall = nan(nchan,nchan,nfrq,ntim); for k = 1:ntim for m = 1:nfrq tmpdat = nan(nchan,nchan); indx = find(cmbindx); if ~complete % this realizes the missing combinations to be represented as the % conjugate of the corresponding combination across the diagonal tmpdat(indx) = reshape(nanmean(data.(fn{ii})(:,cmbindx(indx),m,k)),[numel(indx) 1]); tmpdat = ctranspose(tmpdat); end tmpdat(indx) = reshape(nanmean(data.(fn{ii})(:,cmbindx(indx),m,k)),[numel(indx) 1]); tmpall(:,:,m,k) = tmpdat; end % for m end % for k % replace the data in the old representation with the new representation if nrpt>1, data.(fn{ii}) = tmpall; else data.(fn{ii}) = reshape(tmpall, [nchan nchan nfrq ntim]); end end % if numel end % for ii % remove obsolete fields try data = rmfield(data, 'powspctrm'); end try data = rmfield(data, 'labelcmb'); end try data = rmfield(data, 'dof'); end if ntim>1, data.dimord = 'chan_chan_freq_time'; else data.dimord = 'chan_chan_freq'; end elseif strcmp(current, 'sparsewithpow') && any(strcmp(desired, {'full', 'fullfast'})) % recursively call ft_checkdata, but ensure channel order to be the same % as the original input. origlabelorder = data.label; % keep track of the original order of the channels data = ft_checkdata(data, 'cmbrepresentation', 'sparse'); data.label = origlabelorder; % this avoids the labels to be alphabetized in the next call data = ft_checkdata(data, 'cmbrepresentation', 'full'); end % convert from one to another bivariate representation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [source] = parcellated2source(data) if ~isfield(data, 'brainordinate') error('projecting parcellated data onto the full brain model geometry requires the specification of brainordinates'); end % the main structure contains the functional data on the parcels % the brainordinate sub-structure contains the original geometrical model source = data.brainordinate; data = rmfield(data, 'brainordinate'); if isfield(data, 'cfg') source.cfg = data.cfg; end fn = fieldnames(data); fn = setdiff(fn, {'label', 'time', 'freq', 'hdr', 'cfg', 'grad', 'elec', 'dimord', 'unit'}); % remove irrelevant fields fn(~cellfun(@isempty, regexp(fn, 'dimord$'))) = []; % remove irrelevant (dimord) fields sel = false(size(fn)); for i=1:numel(fn) try sel(i) = ismember(getdimord(data, fn{i}), {'chan', 'chan_time', 'chan_freq', 'chan_freq_time', 'chan_chan'}); end end parameter = fn(sel); fn = fieldnames(source); sel = false(size(fn)); for i=1:numel(fn) tmp = source.(fn{i}); sel(i) = iscell(tmp) && isequal(tmp(:), data.label(:)); end parcelparam = fn(sel); if numel(parcelparam)~=1 error('cannot determine which parcellation to use'); else parcelparam = parcelparam{1}(1:(end-5)); % minus the 'label' end for i=1:numel(parameter) source.(parameter{i}) = unparcellate(data, source, parameter{i}, parcelparam); end % copy over fields (these are necessary for visualising the data in ft_sourceplot) source = copyfields(data, source, {'time', 'freq'}); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = volume2source(data) if isfield(data, 'dimord') % it is a modern source description else % it is an old-fashioned source description xgrid = 1:data.dim(1); ygrid = 1:data.dim(2); zgrid = 1:data.dim(3); [x y z] = ndgrid(xgrid, ygrid, zgrid); data.pos = ft_warp_apply(data.transform, [x(:) y(:) z(:)]); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = source2volume(data) if isfield(data, 'dimord') % it is a modern source description %this part depends on the assumption that the list of positions is describing a full 3D volume in %an ordered way which allows for the extraction of a transformation matrix %i.e. slice by slice try if isfield(data, 'dim'), data.dim = pos2dim(data.pos, data.dim); else data.dim = pos2dim(data); end catch end end if isfield(data, 'dim') && length(data.dim)>=3, data.transform = pos2transform(data.pos, data.dim); end % remove the unwanted fields data = removefields(data, {'pos', 'xgrid', 'ygrid', 'zgrid', 'tri', 'tet', 'hex'}); % make inside a volume data = fixinside(data, 'logical'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = freq2raw(freq) if isfield(freq, 'powspctrm') param = 'powspctrm'; elseif isfield(freq, 'fourierspctrm') param = 'fourierspctrm'; else error('not supported for this data representation'); end if strcmp(freq.dimord, 'rpt_chan_freq_time') || strcmp(freq.dimord, 'rpttap_chan_freq_time') dat = freq.(param); elseif strcmp(freq.dimord, 'chan_freq_time') dat = freq.(param); dat = reshape(dat, [1 size(dat)]); % add a singleton dimension else error('not supported for dimord %s', freq.dimord); end nrpt = size(dat,1); nchan = size(dat,2); nfreq = size(dat,3); ntime = size(dat,4); data = []; % create the channel labels like "MLP11@12Hz"" k = 0; for i=1:nfreq for j=1:nchan k = k+1; data.label{k} = sprintf('%s@%dHz', freq.label{j}, freq.freq(i)); end end % reshape and copy the data as if it were timecourses only for i=1:nrpt data.time{i} = freq.time; data.trial{i} = reshape(dat(i,:,:,:), nchan*nfreq, ntime); if any(isnan(data.trial{i}(1,:))), tmp = data.trial{i}(1,:); begsmp = find(isfinite(tmp),1, 'first'); endsmp = find(isfinite(tmp),1, 'last' ); data.trial{i} = data.trial{i}(:, begsmp:endsmp); data.time{i} = data.time{i}(begsmp:endsmp); end end if isfield(freq, 'trialinfo'), data.trialinfo = freq.trialinfo; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = raw2timelock(data) nsmp = cellfun('size',data.time,2); data = ft_checkdata(data, 'hassampleinfo', 'yes'); ntrial = numel(data.trial); nchan = numel(data.label); if ntrial==1 data.time = data.time{1}; data.avg = data.trial{1}; data = rmfield(data, 'trial'); data.dimord = 'chan_time'; else % code below tries to construct a general time-axis where samples of all trials can fall on % find earliest beginning and latest ending begtime = min(cellfun(@min,data.time)); endtime = max(cellfun(@max,data.time)); % find 'common' sampling rate fsample = 1./mean(cellfun(@mean,cellfun(@diff,data.time,'uniformoutput',false))); % estimate number of samples nsmp = round((endtime-begtime)*fsample) + 1; % numerical round-off issues should be dealt with by this round, as they will/should never cause an extra sample to appear % construct general time-axis time = linspace(begtime,endtime,nsmp); % concatenate all trials tmptrial = nan(ntrial, nchan, length(time)); begsmp = nan(ntrial, 1); endsmp = nan(ntrial, 1); for i=1:ntrial begsmp(i) = nearest(time, data.time{i}(1)); endsmp(i) = nearest(time, data.time{i}(end)); tmptrial(i,:,begsmp(i):endsmp(i)) = data.trial{i}; end % update the sampleinfo begpad = begsmp - min(begsmp); endpad = max(endsmp) - endsmp; if isfield(data, 'sampleinfo') data.sampleinfo = data.sampleinfo + [-begpad(:) endpad(:)]; end % construct the output timelocked data % data.avg = reshape(nanmean(tmptrial, 1), nchan, length(tmptime)); % data.var = reshape(nanvar (tmptrial, [], 1), nchan, length(tmptime)) % data.dof = reshape(sum(~isnan(tmptrial), 1), nchan, length(tmptime)); data.trial = tmptrial; data.time = time; data.dimord = 'rpt_chan_time'; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = timelock2raw(data) switch data.dimord case 'chan_time' data.trial{1} = data.avg; data.time = {data.time}; data = rmfield(data, 'avg'); case 'rpt_chan_time' tmptrial = {}; tmptime = {}; ntrial = size(data.trial,1); nchan = size(data.trial,2); ntime = size(data.trial,3); for i=1:ntrial tmptrial{i} = reshape(data.trial(i,:,:), [nchan, ntime]); tmptime{i} = data.time; end data = rmfield(data, 'trial'); data.trial = tmptrial; data.time = tmptime; case 'subj_chan_time' tmptrial = {}; tmptime = {}; ntrial = size(data.individual,1); nchan = size(data.individual,2); ntime = size(data.individual,3); for i=1:ntrial tmptrial{i} = reshape(data.individual(i,:,:), [nchan, ntime]); tmptime{i} = data.time; end data = rmfield(data, 'individual'); data.trial = tmptrial; data.time = tmptime; otherwise error('unsupported dimord'); end % remove the unwanted fields if isfield(data, 'avg'), data = rmfield(data, 'avg'); end if isfield(data, 'var'), data = rmfield(data, 'var'); end if isfield(data, 'cov'), data = rmfield(data, 'cov'); end if isfield(data, 'dimord'), data = rmfield(data, 'dimord'); end if isfield(data, 'numsamples'), data = rmfield(data, 'numsamples'); end if isfield(data, 'dof'), data = rmfield(data, 'dof'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = chan2freq(data) data.dimord = [data.dimord '_freq']; data.freq = 0; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = chan2timelock(data) data.dimord = [data.dimord '_time']; data.time = 0; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [spike] = raw2spike(data) fprintf('converting raw data into spike data\n'); nTrials = length(data.trial); [spikelabel] = detectspikechan(data); spikesel = match_str(data.label, spikelabel); nUnits = length(spikesel); if nUnits==0 error('cannot convert raw data to spike format since the raw data structure does not contain spike channels'); end trialTimes = zeros(nTrials,2); for iUnit = 1:nUnits unitIndx = spikesel(iUnit); spikeTimes = []; % we dont know how large it will be, so use concatenation inside loop trialInds = []; for iTrial = 1:nTrials % read in the spike times [spikeTimesTrial] = getspiketimes(data, iTrial, unitIndx); nSpikes = length(spikeTimesTrial); spikeTimes = [spikeTimes; spikeTimesTrial(:)]; trialInds = [trialInds; ones(nSpikes,1)*iTrial]; % get the begs and ends of trials hasNum = find(~isnan(data.time{iTrial})); if iUnit==1, trialTimes(iTrial,:) = data.time{iTrial}([hasNum(1) hasNum(end)]); end end spike.label{iUnit} = data.label{unitIndx}; spike.waveform{iUnit} = []; spike.time{iUnit} = spikeTimes(:)'; spike.trial{iUnit} = trialInds(:)'; if iUnit==1, spike.trialtime = trialTimes; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = spike2raw(spike, fsample) if nargin<2 || isempty(fsample) timeDiff = abs(diff(sort([spike.time{:}]))); fsample = 1/min(timeDiff(timeDiff>0)); warning('Desired sampling rate for spike data not specified, automatically resampled to %f', fsample); end % get some sizes nUnits = length(spike.label); nTrials = size(spike.trialtime,1); % preallocate data.trial(1:nTrials) = {[]}; data.time(1:nTrials) = {[]}; for iTrial = 1:nTrials % make bins: note that the spike.time is already within spike.trialtime x = [spike.trialtime(iTrial,1):(1/fsample):spike.trialtime(iTrial,2)]; timeBins = [x x(end)+1/fsample] - (0.5/fsample); time = (spike.trialtime(iTrial,1):(1/fsample):spike.trialtime(iTrial,2)); % convert to continuous trialData = zeros(nUnits,length(time)); for iUnit = 1:nUnits % get the timestamps and only select those timestamps that are in the trial ts = spike.time{iUnit}; hasTrial = spike.trial{iUnit}==iTrial; ts = ts(hasTrial); N = histc(ts,timeBins); if isempty(N) N = zeros(1,length(timeBins)-1); else N(end) = []; end % store it in a matrix trialData(iUnit,:) = N; end data.trial{iTrial} = trialData; data.time{iTrial} = time; end % for all trials % create the associated labels and other aspects of data such as the header data.label = spike.label; data.fsample = fsample; if isfield(spike,'hdr'), data.hdr = spike.hdr; end if isfield(spike,'cfg'), data.cfg = spike.cfg; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = source2raw(source) fn = fieldnames(source); fn = setdiff(fn, {'pos', 'dim', 'transform', 'time', 'freq', 'cfg'}); for i=1:length(fn) dimord{i} = getdimord(source, fn{i}); end sel = strcmp(dimord, 'pos_time'); assert(sum(sel)>0, 'the source structure does not contain a suitable field to represent as raw channel-level data'); assert(sum(sel)<2, 'the source structure contains multiple fields that can be represented as raw channel-level data'); fn = fn{sel}; dimord = dimord{sel}; switch dimord case 'pos_time' % add fake raw channel data to the original data structure data.trial{1} = source.(fn); data.time{1} = source.time; % add fake channel labels data.label = {}; for i=1:size(source.pos,1) data.label{i} = sprintf('source%d', i); end data.label = data.label(:); data.cfg = source.cfg; otherwise % FIXME other formats could be implemented as well end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for detection of channels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [spikelabel, eeglabel] = detectspikechan(data) maxRate = 2000; % default on what we still consider a neuronal signal: this firing rate should never be exceeded % autodetect the spike channels ntrial = length(data.trial); nchans = length(data.label); spikechan = zeros(nchans,1); for i=1:ntrial for j=1:nchans hasAllInts = all(isnan(data.trial{i}(j,:)) | data.trial{i}(j,:) == round(data.trial{i}(j,:))); hasAllPosInts = all(isnan(data.trial{i}(j,:)) | data.trial{i}(j,:)>=0); T = nansum(diff(data.time{i}),2); % total time fr = nansum(data.trial{i}(j,:),2) ./ T; spikechan(j) = spikechan(j) + double(hasAllInts & hasAllPosInts & fr<=maxRate); end end spikechan = (spikechan==ntrial); spikelabel = data.label(spikechan); eeglabel = data.label(~spikechan); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [spikeTimes] = getspiketimes(data, trial, unit) spikeIndx = logical(data.trial{trial}(unit,:)); spikeCount = data.trial{trial}(unit,spikeIndx); spikeTimes = data.time{trial}(spikeIndx); if isempty(spikeTimes), return; end multiSpikes = find(spikeCount>1); % get the additional samples and spike times, we need only loop through the bins [addSamples, addTimes] = deal([]); for iBin = multiSpikes(:)' % looping over row vector addTimes = [addTimes ones(1,spikeCount(iBin))*spikeTimes(iBin)]; addSamples = [addSamples ones(1,spikeCount(iBin))*spikeIndx(iBin)]; end % before adding these times, first remove the old ones spikeTimes(multiSpikes) = []; spikeTimes = sort([spikeTimes(:); addTimes(:)]);
github
lcnbeapp/beapp-master
nearest.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/nearest.m
6,174
utf_8
e7381a0e2eb9c75fcbb90e07f575a6ae
function [indx] = nearest(array, val, insideflag, toleranceflag) % NEAREST return the index of an array nearest to a scalar % % Use as % [indx] = nearest(array, val, insideflag, toleranceflag) % % The second input val can be a scalar, or a [minval maxval] vector for % limits selection. % % If not specified or if left empty, the insideflag and the toleranceflag % will default to false. % % The boolean insideflag can be used to specify whether the value should be % within the array or not. For example nearest(1:10, -inf) will return 1, % but nearest(1:10, -inf, true) will return an error because -inf is not % within the array. % % The boolean toleranceflag is used when insideflag is true. It can be used % to specify whether some tolerance should be allowed for values that are % just outside the array. For example nearest(1:10, 0.99, true, false) will % return an error, but nearest(1:10, 0.99, true, true) will return 1. The % tolerance that is allowed is half the distance between the subsequent % values in the array. % % See also FIND % Copyright (C) 2002-2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ mbreal(array); mbreal(val); mbvector(array); assert(all(~isnan(val)), 'incorrect value (NaN)'); if numel(val)==2 % interpret this as a range specification like [minval maxval] % see also http://bugzilla.fcdonders.nl/show_bug.cgi?id=1431 intervaltol = eps; sel = find(array>=val(1) & array<=val(2)); if isempty(sel) error('The limits you selected are outside the range available in the data'); end indx = sel([1 end]); if indx(1)>1 && abs(array(indx(1)-1)-val(1))<=intervaltol indx(1) = indx(1)-1; end if indx(2)<length(array) && abs(array(indx(2)+1)-val(2))<=intervaltol indx(2) = indx(2)+1; end return end mbscalar(val); if nargin<3 || isempty(insideflag) insideflag = false; end if nargin<4 || isempty(toleranceflag) toleranceflag = false; end % ensure that it is a column vector array = array(:); % determine the most extreme values in the array minarray = min(array); maxarray = max(array); % do some strict checks whether the value lies within the min-max range if insideflag if ~toleranceflag if val<minarray || val>maxarray if numel(array)==1 warning('the selected value %g should be within the range of the array from %g to %g', val, minarray, maxarray); else error('the selected value %g should be within the range of the array from %g to %g', val, minarray, maxarray); end end else if ~isequal(array, sort(array)) error('the input array should be sorted from small to large'); end if numel(array)<2 error('the input array must have multiple elements to compute the tolerance'); end mintolerance = (array(2)-array(1))/2; maxtolerance = (array(end)-array(end-1))/2; if val<(minarray-mintolerance) || val>(maxarray+maxtolerance) error('the value %g should be within the range of the array from %g to %g with a tolerance of %g and %g on both sides', val, minarray, maxarray, mintolerance, maxtolerance); end end % toleragceflag end % insideflag % FIXME it would be possible to do some soft checks and potentially give a % warning in case the user did not explicitly specify the inside and % tolerance flags % note that [dum, indx] = min([1 1 2]) will return indx=1 % and that [dum, indx] = max([1 2 2]) will return indx=2 % whereas it is desired to have consistently the match that is most towards the side of the array if val>maxarray % return the last occurence of the largest number [dum, indx] = max(flipud(array)); indx = numel(array) + 1 - indx; elseif val<minarray % return the first occurence of the smallest number [dum, indx] = min(array); else % implements a threshold to correct for errors due to numerical precision % see http://bugzilla.fcdonders.nl/show_bug.cgi?id=498 and http://bugzilla.fcdonders.nl/show_bug.cgi?id=1943 % if maxarray==minarray % precision = 1; % else % precision = (maxarray-minarray) / 10^6; % end % % % return the first occurence of the nearest number % [dum, indx] = min(round((abs(array(:) - val)./precision)).*precision); % use find instead, see http://bugzilla.fcdonders.nl/show_bug.cgi?id=1943 wassorted = true; if ~issorted(array) wassorted = false; [array, xidx] = sort(array); end indx2 = find(array<=val, 1, 'last'); indx3 = find(array>=val, 1, 'first'); if abs(array(indx2)-val) <= abs(array(indx3)-val) indx = indx2; else indx = indx3; end if ~wassorted indx = xidx(indx); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function mbreal(a) if ~isreal(a) error('Argument to mbreal must be real'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function mbscalar(a) if ~all(size(a)==1) error('Argument to mbscalar must be scalar'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function mbvector(a) if ndims(a) > 2 || (size(a, 1) > 1 && size(a, 2) > 1) error('Argument to mbvector must be a vector'); end
github
lcnbeapp/beapp-master
ft_checkopt.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_checkopt.m
5,085
utf_8
c8bce4359cc4a8be5591788b5984166d
function opt = ft_checkopt(opt, key, allowedtype, allowedval) % FT_CHECKOPT does a validity test on the types and values of a configuration % structure or cell-array with key-value pairs. % % Use as % opt = ft_checkopt(opt, key) % opt = ft_checkopt(opt, key, allowedtype) % opt = ft_checkopt(opt, key, allowedtype, allowedval) % % For allowedtype you can specify a string or a cell-array with multiple % strings. All the default MATLAB types can be specified, such as % 'double' % 'logical' % 'char' % 'single' % 'float' % 'int16' % 'cell' % 'struct' % 'function_handle' % Furthermore, the following custom types can be specified % 'doublescalar' % 'doublevector' % 'doublebivector' i.e. [1 1] or [1 2] % 'ascendingdoublevector' i.e. [1 2 3 4 5], but not [1 3 2 4 5] % 'ascendingdoublebivector' i.e. [1 2], but not [2 1] % 'doublematrix' % 'numericscalar' % 'numericvector' % 'numericmatrix' % 'charcell' % % For allowedval you can specify a single value or a cell-array % with multiple values. % % This function will give an error or it returns the input configuration % structure or cell-array without modifications. A match on any of the % allowed types and any of the allowed values is sufficient to let this % function pass. % % See also FT_GETOPT, FT_SETOPT % Copyright (C) 2011-2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if nargin<3 allowedtype = {}; end if ~iscell(allowedtype) allowedtype = {allowedtype}; end if nargin<4 allowedval = {}; end if ~iscell(allowedval) allowedval = {allowedval}; end % get the value that belongs to this key val = ft_getopt(opt, key); % the default will be [] if isempty(val) && ~any(strcmp(allowedtype, 'empty')) if isnan(ft_getopt(opt, key, nan)) error('the option "%s" was not specified or was empty', key); end end % check that the type of the option is allowed ok = isempty(allowedtype); for i=1:length(allowedtype) switch allowedtype{i} case 'empty' ok = isempty(val); case 'charcell' ok = isa(val, 'cell') && all(cellfun(@ischar, val(:))); case 'doublescalar' ok = isa(val, 'double') && numel(val)==1; case 'doublevector' ok = isa(val, 'double') && sum(size(val)>1)==1; case 'ascendingdoublevector' ok = isa(val,'double') && issorted(val); case 'doublebivector' ok = isa(val,'double') && sum(size(val)>1)==1 && length(val)==2; case 'ascendingdoublebivector' ok = isa(val,'double') && sum(size(val)>1)==1 && length(val)==2 && val(2)>val(1); case 'doublematrix' ok = isa(val, 'double') && sum(size(val)>1)>1; case 'numericscalar' ok = isnumeric(val) && numel(val)==1; case 'numericvector' ok = isnumeric(val) && sum(size(val)>1)==1; case 'numericmatrix' ok = isnumeric(val) && sum(size(val)>1)>1; otherwise ok = isa(val, allowedtype{i}); end if ok % no reason to do additional checks break end end % for allowedtype % construct a string that describes the type of the input variable if isnumeric(val) && numel(val)==1 valtype = sprintf('%s scalar', class(val)); elseif isnumeric(val) && numel(val)==length(val) valtype = sprintf('%s vector', class(val)); elseif isnumeric(val) && length(size(val))==2 valtype = sprintf('%s matrix', class(val)); elseif isnumeric(val) valtype = sprintf('%s array', class(val)); else valtype = class(val); end if ~ok if length(allowedtype)==1 error('the type of the option "%s" is invalid, it should be "%s" instead of "%s"', key, allowedtype{1}, valtype); else error('the type of the option "%s" is invalid, it should be any of %s instead of "%s"', key, printcell(allowedtype), valtype); end end % check that the type of the option is allowed ok = isempty(allowedval); for i=1:length(allowedval) ok = isequal(val, allowedval{i}); if ok % no reason to do additional checks break end end % for allowedtype if ~ok error('the value of the option "%s" is invalid', key); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [s] = printcell(c) if ~isempty(c) s = sprintf('%s, ', c{:}); s = sprintf('{%s}', s(1:end-2)); else s = '{}'; end
github
lcnbeapp/beapp-master
ft_struct2double.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_struct2double.m
2,812
utf_8
862ae4b495515d398d89bfab714c0e10
function [x] = ft_struct2double(x, maxdepth) % FT_STRUCT2DOUBLE converts all single precision numeric data in a structure % into double precision. It will also convert plain matrices and % cell-arrays. % % Use as % x = ft_struct2double(x) % % Starting from MATLAB 7.0, you can use single precision data in your % computations, i.e. you do not have to convert back to double precision. % % MATLAB version 6.5 and older only support single precision for storing % data in memory or on disk, but do not allow computations on single % precision data. Therefore you should converted your data from single to % double precision after reading from file. % % See also FT_STRUCT2SINGLE % Copyright (C) 2005-2014, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if nargin<2 maxdepth = inf; end % convert the data, work recursively through the complete structure x = convert(x, 0, maxdepth); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this subfunction does the actual work %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [a] = convert(a, depth, maxdepth) if depth>maxdepth error('recursive depth exceeded'); end switch class(a) case 'struct' % process all fields of the structure recursively fna = fieldnames(a); % process all elements of the array for j=1:length(a(:)) % warning, this is a recursive call to traverse nested structures for i=1:length(fna) fn = fna{i}; ra = getfield(a(j), fn); ra = convert(ra, depth+1, maxdepth); a(j) = setfield(a(j), fn, ra); end end case 'cell' % process all elements of the cell-array recursively % warning, this is a recursive call to traverse nested structures for i=1:length(a(:)) a{i} = convert(a{i}, depth+1, maxdepth); end case {'single' 'int64' 'uint64' 'int32' 'uint32' 'int16' 'uint16' 'int8' 'uint8'} % convert the values to double precision a = double(a); case 'double' % keep as it is otherwise % do nothing end
github
lcnbeapp/beapp-master
printstruct.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/printstruct.m
6,112
utf_8
e5ecd75e63c034fa964cc6f7976c1f23
function str = printstruct(name, val) % PRINTSTRUCT converts a MATLAB structure into a multi-line string that can be % interpreted by MATLAB, resulting in the original structure. % % Use as % str = printstruct(val) % or % str = printstruct(name, val) % where "val" is any MATLAB variable, e.g. a scalar, vector, matrix, structure, or % cell-array. If you pass the name of the variable, the output is a piece of MATLAB code % that you can execute, i.e. an ASCII serialized representation of the variable. % % Example % a.field1 = 1; % a.field2 = 2; % s = printstruct(a) % % b = rand(3); % s = printstruct(b) % % s = printstruct('c', randn(10)>0.5) % % See also DISP % Copyright (C) 2006-2013, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if nargin==1 val = name; name = inputname(1); end if isa(val, 'config') % this is FieldTrip specific: the @config object resembles a structure but tracks the % access to each field. In this case it is to be treated as a normal structure. val = struct(val); end % note here that because we don't know the final size of the string, % iteratively appending is actually faster than creating a cell array and % subsequently doing a cat(2, strings{:}) (also sprintf() is slow) str = ''; % note further that in the string concatenations I use the numerical value % of a newline (\n), which is 10 if numel(val) == 0 if iscell(val) str = [name ' = {};' 10]; else str = [name ' = [];' 10]; end elseif isstruct(val) if numel(val)>1 str = cell(size(val)); for i=1:numel(val) str{i} = printstruct(sprintf('%s(%d)', name, i), val(i)); end str = cat(2, str{:}); return else % print it as a named structure fn = fieldnames(val); for i=1:length(fn) fv = val.(fn{i}); switch class(fv) case 'char' line = printstr([name '.' fn{i}], fv); case {'single' 'double' 'int8' 'int16' 'int32' 'int64' 'uint8' 'uint16' 'uint32' 'uint64' 'logical'} if ismatrix(fv) line = [name '.' fn{i} ' = ' printmat(fv) ';' 10]; else line = '''FIXME: printing multidimensional arrays is not supported'''; end case 'cell' line = printcell([name '.' fn{i}], fv); case 'struct' line = [printstruct([name '.' fn{i}], fv) 10]; case 'function_handle' line = printstr([name '.' fn{i}], func2str(fv)); otherwise error('unsupported'); end if numel(line)>1 && line(end)==10 && line(end-1)==10 % do not repeat the end-of-line str = [str line(1:end-1)]; else str = [str line]; end end end elseif ~isstruct(val) % print it as a named variable switch class(val) case 'char' str = printstr(name, val); case {'double' 'single' 'int8' 'int16' 'int32' 'int64' 'uint8' 'uint16' 'uint32' 'uint64' 'logical'} str = [name ' = ' printmat(val)]; case 'cell' str = printcell(name, val); otherwise error('unsupported'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str = printcell(name, val) siz = size(val); if isempty(val) str = sprintf('%s = {};\n', name); return; end if all(size(val)==1) str = sprintf('%s = { %s };\n', name, printval(val{1})); else str = sprintf('%s = {\n', name); for i=1:siz(1) dum = ''; for j=1:(siz(2)-1) dum = [dum ' ' printval(val{i,j}) ',']; % add the element with a comma end dum = [dum ' ' printval(val{i,siz(2)})]; % add the last one without comma str = [str dum 10]; end str = sprintf('%s};\n', str); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str = printstr(name, val) siz = size(val); if siz(1)>1 str = sprintf('%s = \n', name); for i=1:siz(1) str = [str sprintf(' %s\n', printval(val(i,:)))]; end elseif siz(1)==1 str = sprintf('%s = %s;\n', name, printval(val)); else str = sprintf('%s = '''';\n', name); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str = printmat(val) if numel(val) == 0 str = '[]'; elseif numel(val) == 1 % an integer will never get trailing decimals when using %g str = sprintf('%g', val); elseif ismatrix(val) if isa(val, 'double') str = mat2str(val); else % add class information for non-double numeric matrices str = mat2str(val, 'class'); end str = strrep(str, ';', [';' 10]); else warning('multidimensional arrays are not supported'); str = '''FIXME: printing multidimensional arrays is not supported'''; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str = printval(val) switch class(val) case 'char' str = ['''' val '''']; case {'single' 'double' 'int8' 'int16' 'int32' 'int64' 'uint8' 'uint16' 'uint32' 'uint64' 'logical'} str = printmat(val); case 'function_handle' str = ['@' func2str(val)]; case 'struct' % print it as an anonymous structure str = 'struct('; fn = fieldnames(val); for i=1:numel(fn) str = [str '''' fn{i} '''' ', ' printval(val.(fn{i}))]; end str = [str ')']; otherwise warning('cannot print unknown object at this level'); str = '''FIXME: printing unknown objects is not supported'''; end
github
lcnbeapp/beapp-master
ft_datatype_raw.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_datatype_raw.m
11,069
utf_8
03bdcca0ba9819b1dd39d0c90de61ee3
function [data] = ft_datatype_raw(data, varargin) % FT_DATATYPE_RAW describes the FieldTrip MATLAB structure for raw data % % The raw datatype represents sensor-level time-domain data typically % obtained after calling FT_DEFINETRIAL and FT_PREPROCESSING. It contains % one or multiple segments of data, each represented as Nchan X Ntime % arrays. % % An example of a raw data structure with 151 MEG channels is % % label: {151x1 cell} the channel labels (e.g. 'MRC13') % time: {1x266 cell} the timeaxis [1*Ntime double] per trial % trial: {1x266 cell} the numeric data [151*Ntime double] per trial % sampleinfo: [266x2 double] the begin and endsample of each trial relative to the recording on disk % trialinfo: [266x1 double] optional trigger or condition codes for each trial % hdr: [1x1 struct] the full header information of the original dataset on disk % grad: [1x1 struct] information about the sensor array (for EEG it is called elec) % cfg: [1x1 struct] the configuration used by the function that generated this data structure % % Required fields: % - time, trial, label % % Optional fields: % - sampleinfo, trialinfo, grad, elec, hdr, cfg % % Deprecated fields: % - fsample % % Obsoleted fields: % - offset % % Historical fields: % - cfg, elec, fsample, grad, hdr, label, offset, sampleinfo, time, % trial, trialdef, see bug2513 % % Revision history: % % (2011/latest) The description of the sensors has changed, see FT_DATATYPE_SENS % for further information. % % (2010v2) The trialdef field has been replaced by the sampleinfo and % trialinfo fields. The sampleinfo corresponds to trl(:,1:2), the trialinfo % to trl(4:end). % % (2010v1) In 2010/Q3 it shortly contained the trialdef field which was a copy % of the trial definition (trl) is generated by FT_DEFINETRIAL. % % (2007) It used to contain the offset field, which correcponds to trl(:,3). % Since the offset field is redundant with the time axis, the offset field is % from now on not present any more. It can be recreated if needed. % % (2003) The initial version was defined % % See also FT_DATATYPE, FT_DATATYPE_COMP, FT_DATATYPE_TIMELOCK, FT_DATATYPE_FREQ, % FT_DATATYPE_SPIKE, FT_DATATYPE_SENS % Copyright (C) 2011, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % get the optional input arguments, which should be specified as key-value pairs version = ft_getopt(varargin, 'version', 'latest'); hassampleinfo = ft_getopt(varargin, 'hassampleinfo', 'ifmakessense'); % can be yes/no/ifmakessense hastrialinfo = ft_getopt(varargin, 'hastrialinfo', 'ifmakessense'); % can be yes/no/ifmakessense % do some sanity checks assert(isfield(data, 'trial') && isfield(data, 'time') && isfield(data, 'label'), 'inconsistent raw data structure, some field is missing'); assert(length(data.trial)==length(data.time), 'inconsistent number of trials in raw data structure'); for i=1:length(data.trial) assert(size(data.trial{i},2)==length(data.time{i}), 'inconsistent number of samples in trial %d', i); assert(size(data.trial{i},1)==length(data.label), 'inconsistent number of channels in trial %d', i); end if isequal(hassampleinfo, 'ifmakessense') hassampleinfo = 'no'; % default to not adding it if isfield(data, 'sampleinfo') && size(data.sampleinfo,1)~=numel(data.trial) % it does not make sense, so don't keep it hassampleinfo = 'no'; end if isfield(data, 'sampleinfo') hassampleinfo = 'yes'; % if it's already there, consider keeping it numsmp = data.sampleinfo(:,2)-data.sampleinfo(:,1)+1; for i=1:length(data.trial) if size(data.trial{i},2)~=numsmp(i); % it does not make sense, so don't keep it hassampleinfo = 'no'; % the actual removal will be done further down warning('removing inconsistent sampleinfo'); break; end end end end if isequal(hastrialinfo, 'ifmakessense') hastrialinfo = 'no'; if isfield(data, 'trialinfo') hastrialinfo = 'yes'; if size(data.trialinfo,1)~=numel(data.trial) % it does not make sense, so don't keep it hastrialinfo = 'no'; warning('removing inconsistent trialinfo'); end end end % convert it into true/false hassampleinfo = istrue(hassampleinfo); hastrialinfo = istrue(hastrialinfo); if strcmp(version, 'latest') version = '2011'; end if isempty(data) return; end switch version case '2011' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isfield(data, 'grad') % ensure that the gradiometer structure is up to date data.grad = ft_datatype_sens(data.grad); end if isfield(data, 'elec') % ensure that the electrode structure is up to date data.elec = ft_datatype_sens(data.elec); end if ~isfield(data, 'fsample') for i=1:length(data.time) if length(data.time{i})>1 data.fsample = 1/mean(diff(data.time{i})); break else data.fsample = nan; end end if isnan(data.fsample) warning('cannot determine sampling frequency'); end end if isfield(data, 'offset') data = rmfield(data, 'offset'); end % the trialdef field should be renamed into sampleinfo if isfield(data, 'trialdef') data.sampleinfo = data.trialdef; data = rmfield(data, 'trialdef'); end if (hassampleinfo && ~isfield(data, 'sampleinfo')) || (hastrialinfo && ~isfield(data, 'trialinfo')) % try to reconstruct the sampleinfo and trialinfo data = fixsampleinfo(data); end if ~hassampleinfo && isfield(data, 'sampleinfo') data = rmfield(data, 'sampleinfo'); end if ~hastrialinfo && isfield(data, 'trialinfo') data = rmfield(data, 'trialinfo'); end case '2010v2' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isfield(data, 'fsample') data.fsample = 1/mean(diff(data.time{1})); end if isfield(data, 'offset') data = rmfield(data, 'offset'); end % the trialdef field should be renamed into sampleinfo if isfield(data, 'trialdef') data.sampleinfo = data.trialdef; data = rmfield(data, 'trialdef'); end if (hassampleinfo && ~isfield(data, 'sampleinfo')) || (hastrialinfo && ~isfield(data, 'trialinfo')) % try to reconstruct the sampleinfo and trialinfo data = fixsampleinfo(data); end if ~hassampleinfo && isfield(data, 'sampleinfo') data = rmfield(data, 'sampleinfo'); end if ~hastrialinfo && isfield(data, 'trialinfo') data = rmfield(data, 'trialinfo'); end case {'2010v1' '2010'} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isfield(data, 'fsample') data.fsample = 1/mean(diff(data.time{1})); end if isfield(data, 'offset') data = rmfield(data, 'offset'); end if ~isfield(data, 'trialdef') && hascfg % try to find it in the nested configuration history data.trialdef = ft_findcfg(data.cfg, 'trl'); end case '2007' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isfield(data, 'fsample') data.fsample = 1/mean(diff(data.time{1})); end if isfield(data, 'offset') data = rmfield(data, 'offset'); end case '2003' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isfield(data, 'fsample') data.fsample = 1/mean(diff(data.time{1})); end if ~isfield(data, 'offset') data.offset = zeros(length(data.time),1); for i=1:length(data.time); data.offset(i) = round(data.time{i}(1)*data.fsample); end end otherwise %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% error('unsupported version "%s" for raw datatype', version); end % Numerical inaccuracies in the binary representations of floating point % values may accumulate. The following code corrects for small inaccuracies % in the time axes of the trials. See http://bugzilla.fcdonders.nl/show_bug.cgi?id=1390 data = fixtimeaxes(data); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = fixtimeaxes(data) if ~isfield(data, 'fsample') fsample = 1/mean(diff(data.time{1})); else fsample = data.fsample; end begtime = zeros(1, length(data.time)); endtime = zeros(1, length(data.time)); numsample = zeros(1, length(data.time)); for i=1:length(data.time) begtime(i) = data.time{i}(1); endtime(i) = data.time{i}(end); numsample(i) = length(data.time{i}); end % compute the differences over trials and the tolerance tolerance = 0.01*(1/fsample); begdifference = abs(begtime-begtime(1)); enddifference = abs(endtime-endtime(1)); % check whether begin and/or end are identical, or close to identical begidentical = all(begdifference==0); endidentical = all(enddifference==0); begsimilar = all(begdifference < tolerance); endsimilar = all(enddifference < tolerance); % Compute the offset of each trial relative to the first trial, and express % that in samples. Non-integer numbers indicate that there is a slight skew % in the time over trials. This works in case of variable length trials. offset = fsample * (begtime-begtime(1)); skew = abs(offset - round(offset)); % try to determine all cases where a correction is needed % note that this does not yet address all possible cases where a fix might be needed needfix = false; needfix = needfix || ~begidentical && begsimilar; needfix = needfix || ~endidentical && endsimilar; needfix = needfix || ~all(skew==0) && all(skew<0.01); % if the skew is less than 1% it will be corrected if needfix ft_warning('correcting numerical inaccuracy in the time axes'); for i=1:length(data.time) % reconstruct the time axis of each trial, using the begin latency of % the first trial and the integer offset in samples of each trial data.time{i} = begtime(1) + ((1:numsample(i)) - 1 + round(offset(i)))/fsample; end end
github
lcnbeapp/beapp-master
ft_compile_mex.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_compile_mex.m
7,899
utf_8
af2e1571d581fe3e6893aebec491bb67
function ft_compile_mex(force) % FT_COMPILE_MEX can be used for compiling most of the FieldTrip MEX files Note that % this function does not put the MEX files in the correct location in the private % folders, this is managed by a Bash script. In case you are not working with Git and % you want to recompile the mex files for your platform, you can find all mex files % for your platform and move them to a backup directory that is not on your MATLAB % path. Subsequently you can rtun this function to recompile it on your platform with % your compiler settings % % The standards procedure for compiling mex files is detailled on % http://www.fieldtriptoolbox.org/development/guidelines/code#compiling_mex_files % % Please note that this script does NOT set up your MEX environment for you, so in % case you haven't selected the C compiler on Windows yet, you need to type 'mex % -setup' first to choose either the LCC, Borland or Microsoft compiler. If you want % to use MinGW, you also need to install Gnumex (http://gnumex.sourceforget.net), % which comes with its own procedure for setting up the MEX environment. % % The logic in this script is to first build a list of files that actually need % compilation for the particular platform that MATLAB is running on, and then to go % through that list. Functions are added to the list by giving their destination % directory and (relative to that) the name of the source file (without the .c). % Optionally, you can specify a list of platform this file needs to be compiled on % only, and a list of platforms where you don't compile it on. Finally, you can give % extra arguments to the MEX command, e.g., for including other c-sources or giving % compiler flags. % % See also MEX % Copyright (C) 2010, Stefan Klanke % % $Id$ if nargin<1 force=false; end % Possible COMPUTER types % GLNX86 % GLNXA64 % PCWIN % PCWIN64 % MAC % MACI % MACI64 [ftver, ftpath] = ft_version; L = []; L = add_mex_source(L,'fileio/@uint64','abs'); L = add_mex_source(L,'fileio/@uint64','min'); L = add_mex_source(L,'fileio/@uint64','max'); L = add_mex_source(L,'fileio/@uint64','plus'); L = add_mex_source(L,'fileio/@uint64','minus'); L = add_mex_source(L,'fileio/@uint64','times'); L = add_mex_source(L,'fileio/@uint64','rdivide'); L = add_mex_source(L,'@config/private','deepcopy'); L = add_mex_source(L,'@config/private','increment'); L = add_mex_source(L,'@config/private','setzero'); L = add_mex_source(L,'realtime/online_mri','ft_omri_smooth_volume'); L = add_mex_source(L,'realtime/src/acquisition/siemens/src', 'sap2matlab', [], [], 'siemensap.c -I../include'); L = add_mex_source(L,'src','ft_getopt'); L = add_mex_source(L,'src','read_16bit'); L = add_mex_source(L,'src','read_24bit'); L = add_mex_source(L,'src','read_ctf_shm', {'GLNX86'}); % only compile on GLNX86 L = add_mex_source(L,'src','write_ctf_shm', {'GLNX86'}); % only compile on GLNX86 L = add_mex_source(L,'src','lmoutr',[],[],'geometry.c -I.'); L = add_mex_source(L,'src','ltrisect',[],[],'geometry.c -I.'); L = add_mex_source(L,'src','plinproj',[],[],'geometry.c -I.'); L = add_mex_source(L,'src','ptriproj',[],[],'geometry.c -I.'); L = add_mex_source(L,'src','routlm',[],[],'geometry.c -I.'); L = add_mex_source(L,'src','solid_angle',[],[],'geometry.c -I.'); L = add_mex_source(L,'src','rfbevent',[],{'PCWIN', 'PCWIN64'},'d3des.c -I.'); % do not compile on WIN32 and WIN64 L = add_mex_source(L,'src','meg_leadfield1'); L = add_mex_source(L,'src','splint_gh'); L = add_mex_source(L,'src','plgndr'); L = add_mex_source(L,'src','ft_spike_sub_crossx'); L = add_mex_source(L,'src','rename'); L = add_mex_source(L,'src','getpid'); L = add_mex_source(L,'src','nanmean'); L = add_mex_source(L,'src','nanstd'); L = add_mex_source(L,'src','nanvar'); L = add_mex_source(L,'src','nansum'); L = add_mex_source(L,'src','nanstd'); L = add_mex_source(L,'src','det2x2'); L = add_mex_source(L,'src','inv2x2'); L = add_mex_source(L,'src','mtimes2x2'); L = add_mex_source(L,'src','sandwich2x2'); L = add_mex_source(L,'src','combineClusters'); % this one is located elsewhere L = add_mex_source(L,'external/fileexchange','CalcMD5',[],[],'CFLAGS=''-std=c99 -fPIC'''); % this one depends on the MATLAB version if ft_platform_supports('libmx_c_interface') % use the C interface L = add_mex_source(L,'src','mxSerialize_c'); L = add_mex_source(L,'src','mxDeserialize_c'); else % use the C++ interface L = add_mex_source(L,'src','mxSerialize_cpp'); L = add_mex_source(L,'src','mxDeserialize_cpp'); end oldDir = pwd; try compile_mex_list(L, ftpath, force); catch % the "catch me" syntax is broken on MATLAB74, this fixes it me = lasterror; cd(oldDir); rethrow(me); end cd(oldDir); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION % % Use as % list = add_mex_source(list, directory, relName, includePlatform, excludePlatform, extras) % % The list is a structure array of directory names, source file names, and % extra arguments required for the compilation of MEX files. This function will % create a new element of this structure and append it to L. % % directory = target directory of the mex-file % relName = source file relative to 'directory' % includePlatform = list of platforms this MEX file should only be compiled for. % use an empty matrix [] to compile for all platforms % excludePlatform = list of platforms this MEX file should NOT be compiled for. % extras = extra arguments to the MEX command, e.g. additional source files % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function L = add_mex_source(L, directory, relName, includePlatform, excludePlatform, extras) % Check if this file only needs compilation on certain platforms (including this one) if nargin>3 && ~isempty(includePlatform) ok = false; for k=1:numel(includePlatform) if strcmp(includePlatform{k}, computer) ok = true; break; end end if ~ok return end end % Check if this file cannot be compiled on certain platforms (including this one) if nargin>4 && ~isempty(excludePlatform) ok = true; for k=1:numel(excludePlatform) if strcmp(excludePlatform{k}, computer) return; end end end L(end+1).dir = directory; L(end).relName = relName; if nargin>5 L(end).extras = extras; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION % % Use as % compile_mex_list(L, baseDir) % % Compile a list of MEX files as determined by the input argument L. % The second argument 'baseDir' is the common base directory for the % files listed in L. The third argument is a flag that determines % whether to force (re-)compilation even if the MEX file is up-to-date. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function compile_mex_list(L, baseDir, force) for i=1:length(L) [relDir, name] = fileparts(L(i).relName); sfname1 = fullfile(baseDir, L(i).dir, [L(i).relName '.c']); sfname2 = fullfile(baseDir, L(i).dir, [L(i).relName '.cpp']); if exist(sfname1, 'file') sfname = sfname1; L(i).ext = 'c'; elseif exist(sfname2, 'file') sfname = sfname2; L(i).ext = 'cpp'; else sfname = ''; L(i).ext = ''; fprintf(1,'Error: source file for %s cannot be found.\n', L(i).relName); continue; end SF = dir(sfname); if ~force mfname = [baseDir filesep L(i).dir filesep name '.' mexext]; MF = dir(mfname); if numel(MF)==1 && datenum(SF.date) <= datenum(MF.date) fprintf(1,'Skipping up-to-date MEX file %s/%s\n', L(i).dir, name); continue; end end fprintf(1,'Compiling MEX file %s/%s ...\n', L(i).dir, name); cd([baseDir '/' L(i).dir]); cmd = sprintf('mex %s.%s %s', L(i).relName, L(i).ext, L(i).extras); eval(cmd); end
github
lcnbeapp/beapp-master
ft_selectdata.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_selectdata.m
49,158
utf_8
7a2848867b0ce4107732993c753c7589
function [varargout] = ft_selectdata(varargin) % FT_SELECTDATA makes a selection in the input data along specific data % dimensions, such as channels, time, frequency, trials, etc. It can also % be used to average the data along each of the specific dimensions. % % Use as % [data] = ft_selectdata(cfg, data, ...) % % The cfg argument is a configuration structure which can contain % cfg.tolerance = scalar, tolerance value to determine equality of time/frequency bins (default = 1e-5) % % For data with trials or subjects as repetitions, you can specify % cfg.trials = 1xN, trial indices to keep, can be 'all'. You can use logical indexing, where false(1,N) removes all the trials % cfg.avgoverrpt = string, can be 'yes' or 'no' (default = 'no') % % For data with a channel dimension you can specify % cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION % cfg.avgoverchan = string, can be 'yes' or 'no' (default = 'no') % cfg.nanmean = string, can be 'yes' or 'no' (default = 'no') % % For data with channel combinations you can specify % cfg.channelcmb = Nx2 cell-array with selection of channels (default = 'all'), see FT_CHANNELCOMBINATION % cfg.avgoverchancmb = string, can be 'yes' or 'no' (default = 'no') % % For data with a time dimension you can specify % cfg.latency = scalar -> can be 'all', 'prestim', 'poststim' % cfg.latency = [beg end] % cfg.avgovertime = string, can be 'yes' or 'no' (default = 'no') % cfg.nanmean = string, can be 'yes' or 'no' (default = 'no') % % For data with a frequency dimension you can specify % cfg.frequency = scalar -> can be 'all' % cfg.frequency = [beg end] % cfg.avgoverfreq = string, can be 'yes' or 'no' (default = 'no') % cfg.nanmean = string, can be 'yes' or 'no' (default = 'no') % % If multiple input arguments are provided, FT_SELECTDATA will adjust the individual inputs % such that either the intersection across inputs is retained (i.e. only the channel, time, % and frequency points that are shared across all input arguments), or that the union across % inputs is retained (replacing missing data with nans). In either case, the order (e.g. of % the channels) is made consistent across inputs. The behavior can be specified with % cfg.select = string, can be 'intersect' or 'union' (default = 'intersect') % % See also FT_DATATYPE, FT_CHANNELSELECTION, FT_CHANNELCOMBINATION % Undocumented options % cfg.keeprptdim = 'yes' or 'no' % cfg.keepposdim = 'yes' or 'no' % cfg.keepchandim = 'yes' or 'no' % cfg.keepchancmbdim = 'yes' or 'no' % cfg.keepfreqdim = 'yes' or 'no' % cfg.keeptimedim = 'yes' or 'no' % Copyright (C) 2012-2014, Robert Oostenveld & Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if nargin==1 || (nargin>2 && ischar(varargin{end-1})) || (isstruct(varargin{1}) && ~ft_datatype(varargin{1}, 'unknown')) % this is the OLD calling style, like this % data = ft_selectdata(data, 'key1', value1, 'key2', value2, ...) % or with multiple input data structures like this % data = ft_selectdata(data1, data2, 'key1', value1, 'key2', value2, ...) [varargout{1:nargout}] = ft_selectdata_old(varargin{:}); return end % reorganize the input arguments cfg = varargin{1}; varargin = varargin(2:end); % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; ft_defaults % this ensures that the path is correct and that the ft_defaults global variable is available ft_preamble init % this will reset ft_warning and show the function help if nargin==0 and return an error ft_preamble provenance % this records the time and memory usage at teh beginning of the function ft_preamble trackconfig % this converts the cfg structure in a config object, which tracks the cfg options that are being used ft_preamble debug % this allows for displaying or saving the function name and input arguments upon an error ft_preamble loadvar varargin % this reads the input data in case the user specified the cfg.inputfile option % determine the characteristics of the input data dtype = ft_datatype(varargin{1}); for i=2:length(varargin) % ensure that all subsequent inputs are of the same type ok = ft_datatype(varargin{i}, dtype); if ~ok, error('input data should be of the same datatype'); end end % ensure that the user does not give invalid selection options cfg = ft_checkconfig(cfg, 'forbidden', {'foi', 'toi'}); cfg = ft_checkconfig(cfg, 'renamed', {'selmode', 'select'}); cfg = ft_checkconfig(cfg, 'renamed', {'toilim', 'latency'}); cfg = ft_checkconfig(cfg, 'renamed', {'foilim', 'frequency'}); cfg = ft_checkconfig(cfg, 'renamed', {'avgoverroi', 'avgoverpos'}); cfg = ft_checkconfig(cfg, 'renamedval', {'parameter', 'avg.pow', 'pow'}); cfg = ft_checkconfig(cfg, 'renamedval', {'parameter', 'avg.mom', 'mom'}); cfg = ft_checkconfig(cfg, 'renamedval', {'parameter', 'avg.nai', 'nai'}); cfg = ft_checkconfig(cfg, 'renamedval', {'parameter', 'trial.pow', 'pow'}); cfg = ft_checkconfig(cfg, 'renamedval', {'parameter', 'trial.mom', 'mom'}); cfg = ft_checkconfig(cfg, 'renamedval', {'parameter', 'trial.nai', 'nai'}); cfg.tolerance = ft_getopt(cfg, 'tolerance', 1e-5); % default tolerance for checking equality of time/freq axes cfg.select = ft_getopt(cfg, 'select', 'intersect'); % default is to take intersection, alternative 'union' if strcmp(dtype, 'volume') || strcmp(dtype, 'segmentation') % it must be a source representation, not a volume representation for i=1:length(varargin) varargin{i} = ft_checkdata(varargin{i}, 'datatype', 'source'); end dtype = 'source'; end % this function only works for the upcoming (not yet standard) source representation without sub-structures % update the old-style beamformer source reconstruction to the upcoming representation if strcmp(dtype, 'source') if isfield(varargin{1}, 'avg') restoreavg = fieldnames(varargin{1}.avg); else restoreavg = {}; end for i=1:length(varargin) varargin{i} = ft_datatype_source(varargin{i}, 'version', 'upcoming'); end end cfg.latency = ft_getopt(cfg, 'latency', 'all', 1); if isnumeric(cfg.latency) && numel(cfg.latency)==2 && cfg.latency(1)==cfg.latency(2) % this is better specified by a single number cfg.latency = cfg.latency(1); end cfg.channel = ft_getopt(cfg, 'channel', 'all', 1); cfg.trials = ft_getopt(cfg, 'trials', 'all', 1); if length(varargin)>1 && ~isequal(cfg.trials, 'all') error('it is ambiguous to make a subselection of trials while at the same time concatenating multiple data structures') end cfg.frequency = ft_getopt(cfg, 'frequency', 'all', 1); if isnumeric(cfg.frequency) && numel(cfg.frequency)==2 && cfg.frequency(1)==cfg.frequency(2) % this is better specified by a single number cfg.frequency = cfg.frequency(1); end datfield = fieldnames(varargin{1}); for i=2:length(varargin) % only consider fields that are present in all inputs datfield = intersect(datfield, fieldnames(varargin{i})); end datfield = setdiff(datfield, {'label' 'labelcmb'}); % these fields will be used for selection, but are not treated as data fields datfield = setdiff(datfield, {'dim'}); % not used for selection, also not treated as data field xtrafield = {'cfg' 'hdr' 'fsample' 'fsampleorig' 'grad' 'elec' 'opto' 'transform' 'unit' 'topolabel'}; % these fields will not be touched in any way by the code datfield = setdiff(datfield, xtrafield); orgdim1 = datfield(~cellfun(@isempty, regexp(datfield, 'label$'))); % xxxlabel datfield = setdiff(datfield, orgdim1); datfield = datfield(:)'; orgdim1 = datfield(~cellfun(@isempty, regexp(datfield, 'dimord$'))); % xxxdimord datfield = setdiff(datfield, orgdim1); datfield = datfield(:)'; sel = strcmp(datfield, 'cumtapcnt'); if any(sel) % move this field to the end, as it is needed to make the selections in the other fields datfield(sel) = []; datfield = [datfield {'cumtapcnt'}]; end orgdim2 = cell(size(orgdim1)); for i=1:length(orgdim1) orgdim2{i} = varargin{1}.(orgdim1{i}); end dimord = cell(size(datfield)); for i=1:length(datfield) dimord{i} = getdimord(varargin{1}, datfield{i}); end % do not consider fields of which the dimensions are unknown % sel = cellfun(@isempty, regexp(dimord, 'unknown')); % for i=find(~sel) % fprintf('not including "%s" in selection\n', datfield{i}); % end % datfield = datfield(sel); % dimord = dimord(sel); % determine all dimensions that are present in all data fields dimtok = {}; for i=1:length(datfield) dimtok = cat(2, dimtok, tokenize(dimord{i}, '_')); end dimtok = unique(dimtok); hasspike = any(ismember(dimtok, 'spike')); haspos = any(ismember(dimtok, {'pos', '{pos}'})); haschan = any(ismember(dimtok, {'chan', '{chan}'})); haschancmb = any(ismember(dimtok, 'chancmb')); hasfreq = any(ismember(dimtok, 'freq')); hastime = any(ismember(dimtok, 'time')); hasrpt = any(ismember(dimtok, {'rpt', 'subj'})); hasrpttap = any(ismember(dimtok, 'rpttap')); if hasspike % cfg.latency is used to select individual spikes, not to select from a continuously sampled time axis hastime = false; end clear dimtok haspos = haspos && isfield(varargin{1}, 'pos'); haschan = haschan && isfield(varargin{1}, 'label'); haschancmb = haschancmb && isfield(varargin{1}, 'labelcmb'); hasfreq = hasfreq && isfield(varargin{1}, 'freq'); hastime = hastime && isfield(varargin{1}, 'time'); % do a sanity check on all input arguments if haspos, assert(all(cellfun(@isfield, varargin, repmat({'pos'}, size(varargin)))), 'not all input arguments have a "pos" field'); end if haschan, assert(all(cellfun(@isfield, varargin, repmat({'label'}, size(varargin)))), 'not all input arguments have a "label" field'); end if haschancmb, assert(all(cellfun(@isfield, varargin, repmat({'labelcmb'}, size(varargin)))), 'not all input arguments have a "labelcmb" field'); end if hasfreq, assert(all(cellfun(@isfield, varargin, repmat({'freq'}, size(varargin)))), 'not all input arguments have a "freq" field'); end if hastime, assert(all(cellfun(@isfield, varargin, repmat({'time'}, size(varargin)))), 'not all input arguments have a "time" field'); end avgoverpos = istrue(ft_getopt(cfg, 'avgoverpos', false)); % at some places it is also referred to as roi (region-of-interest) avgoverchan = istrue(ft_getopt(cfg, 'avgoverchan', false)); avgoverchancmb = istrue(ft_getopt(cfg, 'avgoverchancmb', false)); avgoverfreq = istrue(ft_getopt(cfg, 'avgoverfreq', false)); avgovertime = istrue(ft_getopt(cfg, 'avgovertime', false)); avgoverrpt = istrue(ft_getopt(cfg, 'avgoverrpt', false)); % do a sanity check for the averaging options if avgoverpos, assert(haspos, 'there are no source positions, so averaging is not possible'); end if avgoverchan, assert(haschan, 'there is no channel dimension, so averaging is not possible'); end if avgoverchancmb, assert(haschancmb, 'there are no channel combinations, so averaging is not possible'); end if avgoverfreq, assert(hasfreq, 'there is no frequency dimension, so averaging is not possible'); end if avgovertime, assert(hastime, 'there is no time dimension, so averaging over time is not possible'); end if avgoverrpt, assert(hasrpt||hasrpttap, 'there are no repetitions, so averaging is not possible'); end % set averaging function cfg.nanmean = ft_getopt(cfg, 'nanmean', 'no'); if strcmp(cfg.nanmean, 'yes') average = @nanmean; else average = @mean; end % by default we keep most of the dimensions in the data structure when averaging over them keepposdim = istrue(ft_getopt(cfg, 'keepposdim', true)); keepchandim = istrue(ft_getopt(cfg, 'keepchandim', true)); keepchancmbdim = istrue(ft_getopt(cfg, 'keepchancmbdim', true)); keepfreqdim = istrue(ft_getopt(cfg, 'keepfreqdim', true)); keeptimedim = istrue(ft_getopt(cfg, 'keeptimedim', true)); keeprptdim = istrue(ft_getopt(cfg, 'keeprptdim', ~avgoverrpt)); if ~keepposdim, assert(avgoverpos, 'removing a dimension is only possible when averaging'); end if ~keepchandim, assert(avgoverchan, 'removing a dimension is only possible when averaging'); end if ~keepchancmbdim, assert(avgoverchancmb, 'removing a dimension is only possible when averaging'); end if ~keepfreqdim, assert(avgoverfreq, 'removing a dimension is only possible when averaging'); end if ~keeptimedim, assert(avgovertime, 'removing a dimension is only possible when averaging'); end if ~keeprptdim, assert(avgoverrpt, 'removing a dimension is only possible when averaging'); end if strcmp(cfg.select, 'union') && (avgoverpos || avgoverchan || avgoverchancmb || avgoverfreq || avgovertime || avgoverrpt) error('cfg.select ''union'' in combination with averaging across one of the dimensions is not possible'); end % trim the selection to all inputs, rpt and rpttap are dealt with later if hasspike, [selspike, cfg] = getselection_spike (cfg, varargin{:}); end if haspos, [selpos, cfg] = getselection_pos (cfg, varargin{:}, cfg.tolerance, cfg.select); end if haschan, [selchan, cfg] = getselection_chan (cfg, varargin{:}, cfg.select); end if haschancmb, [selchancmb, cfg] = getselection_chancmb(cfg, varargin{:}, cfg.select); end if hasfreq, [selfreq, cfg] = getselection_freq (cfg, varargin{:}, cfg.tolerance, cfg.select); end if hastime, [seltime, cfg] = getselection_time (cfg, varargin{:}, cfg.tolerance, cfg.select); end % this is to keep track of all fields that should be retained in the output keepfield = datfield; for i=1:numel(varargin) for j=1:numel(datfield) dimtok = tokenize(dimord{j}, '_'); % the rpt selection should only work with a single data argument % in case tapers were kept, selrpt~=selrpttap, otherwise selrpt==selrpttap [selrpt{i}, dum, rptdim{i}, selrpttap{i}] = getselection_rpt(cfg, varargin{i}, dimord{j}); % check for the presence of each dimension in each datafield fieldhasspike = ismember('spike', dimtok); fieldhaspos = ismember('pos', dimtok) || ismember('{pos}', dimtok); fieldhaschan = (ismember('chan', dimtok) || ismember('{chan}', dimtok)) && isfield(varargin{1}, 'label'); fieldhaschancmb = ismember('chancmb', dimtok); fieldhastime = ismember('time', dimtok) && ~hasspike; fieldhasfreq = ismember('freq', dimtok); fieldhasrpt = ismember('rpt', dimtok) | ismember('subj', dimtok) | ismember('{rpt}', dimtok); fieldhasrpttap = ismember('rpttap', dimtok); % cfg.latency is used to select individual spikes, not to select from a continuously sampled time axis if fieldhasspike, varargin{i} = makeselection(varargin{i}, datfield{j}, dimtok, find(strcmp(dimtok,'spike')), selspike{i}, false, 'intersect', average); end if fieldhaspos, varargin{i} = makeselection(varargin{i}, datfield{j}, dimtok, find(ismember(dimtok, {'pos', '{pos}'})), selpos{i}, avgoverpos, cfg.select, average); end if fieldhaschan, varargin{i} = makeselection(varargin{i}, datfield{j}, dimtok, find(ismember(dimtok,{'chan' '{chan}'})), selchan{i}, avgoverchan, cfg.select, average); end if fieldhaschancmb, varargin{i} = makeselection(varargin{i}, datfield{j}, dimtok, find(strcmp(dimtok,'chancmb')), selchancmb{i}, avgoverchancmb, cfg.select, average); end if fieldhastime, varargin{i} = makeselection(varargin{i}, datfield{j}, dimtok, find(strcmp(dimtok,'time')), seltime{i}, avgovertime, cfg.select, average); end if fieldhasfreq, varargin{i} = makeselection(varargin{i}, datfield{j}, dimtok, find(strcmp(dimtok,'freq')), selfreq{i}, avgoverfreq, cfg.select, average); end if fieldhasrpt, varargin{i} = makeselection(varargin{i}, datfield{j}, dimtok, rptdim{i}, selrpt{i}, avgoverrpt, 'intersect', average); end if fieldhasrpttap, varargin{i} = makeselection(varargin{i}, datfield{j}, dimtok, rptdim{i}, selrpttap{i}, avgoverrpt, 'intersect', average); end % update the fields that should be kept in the structure as a whole % and update the dimord for this specific datfield keepdim = true(size(dimtok)); if avgoverchan && ~keepchandim keepdim(strcmp(dimtok, 'chan')) = false; keepfield = setdiff(keepfield, 'label'); else keepfield = [keepfield 'label']; end if avgoverchancmb && ~keepchancmbdim keepdim(strcmp(dimtok, 'chancmb')) = false; keepfield = setdiff(keepfield, 'labelcmb'); else keepfield = [keepfield 'labelcmb']; end if avgoverfreq && ~keepfreqdim keepdim(strcmp(dimtok, 'freq')) = false; keepfield = setdiff(keepfield, 'freq'); else keepfield = [keepfield 'freq']; end if avgovertime && ~keeptimedim keepdim(strcmp(dimtok, 'time')) = false; keepfield = setdiff(keepfield, 'time'); else keepfield = [keepfield 'time']; end if avgoverpos && ~keepposdim keepdim(strcmp(dimtok, 'pos')) = false; keepdim(strcmp(dimtok, '{pos}')) = false; keepdim(strcmp(dimtok, 'dim')) = false; keepfield = setdiff(keepfield, {'pos' '{pos}' 'dim'}); elseif avgoverpos && keepposdim keepfield = setdiff(keepfield, {'dim'}); % this should be removed anyway else keepfield = [keepfield {'pos' '{pos}' 'dim'}]; end if avgoverrpt && ~keeprptdim keepdim(strcmp(dimtok, 'rpt')) = false; keepdim(strcmp(dimtok, 'rpttap')) = false; keepdim(strcmp(dimtok, 'subj')) = false; end varargin{i}.(datfield{j}) = squeezedim(varargin{i}.(datfield{j}), ~keepdim); end % for datfield % also update the fields that describe the dimensions, time/freq/pos have been dealt with as data if haschan, varargin{i} = makeselection_chan (varargin{i}, selchan{i}, avgoverchan); end % update the label field if haschancmb, varargin{i} = makeselection_chancmb(varargin{i}, selchancmb{i}, avgoverchancmb); end % update the labelcmb field end % for varargin if strcmp(cfg.select, 'union') % create the union of the descriptive axes if haspos, varargin = makeunion(varargin, 'pos'); end if haschan, varargin = makeunion(varargin, 'label'); end if haschancmb, varargin = makeunion(varargin, 'labelcmb'); end if hastime, varargin = makeunion(varargin, 'time'); end if hasfreq, varargin = makeunion(varargin, 'freq'); end end % remove all fields from the data structure that do not pertain to the selection sel = strcmp(keepfield, '{pos}'); if any(sel), keepfield(sel) = {'pos'}; end sel = strcmp(keepfield, 'chan'); if any(sel), keepfield(sel) = {'label'}; end sel = strcmp(keepfield, 'chancmb'); if any(sel), keepfield(sel) = {'labelcmb'}; end if avgoverrpt % these are invalid after averaging keepfield = setdiff(keepfield, {'cumsumcnt' 'cumtapcnt' 'trialinfo' 'sampleinfo'}); end if avgovertime || ~isequal(cfg.latency, 'all') % these are invalid after averaging or making a latency selection keepfield = setdiff(keepfield, {'sampleinfo'}); end for i=1:numel(varargin) varargin{i} = keepfields(varargin{i}, [keepfield xtrafield]); end % restore the original dimord fields in the data for i=1:length(orgdim1) dimtok = tokenize(orgdim2{i}, '_'); % using a setdiff may result in double occurrences of chan and pos to % disappear, so this causes problems as per bug 2962 % if ~keeprptdim, dimtok = setdiff(dimtok, {'rpt' 'rpttap' 'subj'}); end % if ~keepposdim, dimtok = setdiff(dimtok, {'pos' '{pos}'}); end % if ~keepchandim, dimtok = setdiff(dimtok, {'chan'}); end % if ~keepfreqdim, dimtok = setdiff(dimtok, {'freq'}); end % if ~keeptimedim, dimtok = setdiff(dimtok, {'time'}); end if ~keeprptdim, dimtok = dimtok(~ismember(dimtok, {'rpt' 'rpttap' 'subj'})); end if ~keepposdim, dimtok = dimtok(~ismember(dimtok, {'pos' '{pos}'})); end if ~keepchandim, dimtok = dimtok(~ismember(dimtok, {'chan'})); end if ~keepfreqdim, dimtok = dimtok(~ismember(dimtok, {'freq'})); end if ~keeptimedim, dimtok = dimtok(~ismember(dimtok, {'time'})); end dimord = sprintf('%s_', dimtok{:}); dimord = dimord(1:end-1); % remove the trailing _ for j=1:length(varargin) varargin{j}.(orgdim1{i}) = dimord; end end % restore the source.avg field, this keeps the output reasonably consistent with the % old-style source representation of the input if strcmp(dtype, 'source') && ~isempty(restoreavg) for i=1:length(varargin) varargin{i}.avg = keepfields(varargin{i}, restoreavg); varargin{i} = removefields(varargin{i}, restoreavg); end end varargout = varargin; ft_postamble debug % this clears the onCleanup function used for debugging in case of an error ft_postamble trackconfig % this converts the config object back into a struct and can report on the unused fields ft_postamble provenance % this records the time and memory at the end of the function, prints them on screen and adds this information together with the function name and MATLAB version etc. to the output cfg % ft_postamble previous varargin % this copies the datain.cfg structure into the cfg.previous field. You can also use it for multiple inputs, or for "varargin" % ft_postamble history varargout % this adds the local cfg structure to the output data structure, i.e. dataout.cfg = cfg % note that the cfg.previous thingy does not work with the postamble, % because the postamble puts the cfgs of all input arguments in the (first) % output argument's xxx.cfg for k = 1:numel(varargout) varargout{k}.cfg = cfg; if isfield(varargin{k}, 'cfg') varargout{k}.cfg.previous = varargin{k}.cfg; end end % ft_postamble savevar varargout % this saves the output data structure to disk in case the user specified the cfg.outputfile option if nargout>numel(varargout) % also return the input cfg with the combined selection over all input data structures varargout{end+1} = cfg; end end % main function ft_selectdata %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = makeselection(data, datfield, dimtok, seldim, selindx, avgoverdim, selmode, average) if numel(seldim) > 1 for k = 1:numel(seldim) data = makeselection(data, datfield, dimtok, seldim(k), selindx, avgoverdim, selmode, average); end return; end if isnumeric(data.(datfield)) if isrow(data.(datfield)) && seldim==1 if length(dimtok)==1 seldim = 2; % switch row and column end elseif iscolumn(data.(datfield)) && seldim==2 if length(dimtok)==1 seldim = 1; % switch row and column end end elseif iscell(data.(datfield)) if isrow(data.(datfield){1}) && seldim==2 if length(dimtok)==2 seldim = 3; % switch row and column end elseif iscolumn(data.(datfield){1}) && seldim==3 if length(dimtok)==2 seldim = 2; % switch row and column end end end % an empty selindx means that nothing(!) should be selected and hence everything should be removed, which is different than keeping everything % the selindx value of NaN indicates that it is not needed to make a selection switch selmode case 'intersect' if iscell(selindx) % there are multiple selections in multipe vectors, the selection is in the matrices contained within the cell array for j=1:numel(selindx) if ~isempty(selindx{j}) && all(isnan(selindx{j})) % no selection needs to be made else data.(datfield){j} = cellmatselect(data.(datfield){j}, seldim-1, selindx{j}, numel(dimtok)==1); end end else % there is a single selection in a single vector if ~isempty(selindx) && all(isnan(selindx)) % no selection needs to be made else data.(datfield) = cellmatselect(data.(datfield), seldim, selindx, numel(dimtok)==1); end end if avgoverdim data.(datfield) = cellmatmean(data.(datfield), seldim, average); end case 'union' if ~isempty(selindx) && all(isnan(selindx)) % no selection needs to be made else tmp = data.(datfield); siz = size(tmp); siz(seldim) = numel(selindx); data.(datfield) = nan(siz); sel = isfinite(selindx); switch seldim case 1 data.(datfield)(sel,:,:,:,:,:) = tmp(selindx(sel),:,:,:,:,:); case 2 data.(datfield)(:,sel,:,:,:,:) = tmp(:,selindx(sel),:,:,:,:); case 3 data.(datfield)(:,:,sel,:,:,:) = tmp(:,:,selindx(sel),:,:,:); case 4 data.(datfield)(:,:,:,sel,:,:) = tmp(:,:,:,selindx(sel),:,:); case 5 data.(datfield)(:,:,:,:,sel,:) = tmp(:,:,:,:,selindx(sel),:); case 6 data.(datfield)(:,:,:,:,:,sel) = tmp(:,:,:,:,:,selindx(sel)); otherwise error('unsupported dimension (%d) for making a selection for %s', seldim, datfield); end end if avgoverdim data.(datfield) = average(data.(datfield), seldim); end end % switch end % function makeselection %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = makeselection_chan(data, selchan, avgoverchan) if isempty(selchan) %error('no channels were selected'); data.label = {}; elseif avgoverchan && all(isnan(selchan)) str = sprintf('%s, ', data.label{:}); str = str(1:end-2); str = sprintf('mean(%s)', str); data.label = {str}; elseif avgoverchan && ~any(isnan(selchan)) str = sprintf('%s, ', data.label{selchan}); str = str(1:end-2); str = sprintf('mean(%s)', str); data.label = {str}; % remove the last '+' elseif all(isfinite(selchan)) data.label = data.label(selchan); data.label = data.label(:); elseif numel(selchan)==1 && any(~isfinite(selchan)) % do nothing elseif numel(selchan)>1 && any(~isfinite(selchan)) tmp = cell(numel(selchan),1); for k = 1:numel(tmp) if isfinite(selchan(k)) tmp{k} = data.label{selchan(k)}; end end data.label = tmp; else % this should never happen error('cannot figure out how to select channels'); end end % function makeselection_chan %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = makeselection_chancmb(data, selchancmb, avgoverchancmb) if isempty(selchancmb) error('no channel combinations were selected'); elseif avgoverchancmb && all(isnan(selchancmb)) % naming the channel combinations becomes ambiguous, but should not % suggest that the mean was computed prior to combining str1 = sprintf('%s, ', data.labelcmb{:,1}); str1 = str1(1:end-2); % str1 = sprintf('mean(%s)', str1); str2 = sprintf('%s, ', data.labelcmb{:,2}); str2 = str2(1:end-2); % str2 = sprintf('mean(%s)', str2); data.label = {str1, str2}; elseif avgoverchancmb && ~any(isnan(selchancmb)) % naming the channel combinations becomes ambiguous, but should not % suggest that the mean was computed prior to combining str1 = sprintf('%s, ', data.labelcmb{selchancmb,1}); str1 = str1(1:end-2); % str1 = sprintf('mean(%s)', str1); str2 = sprintf('%s, ', data.labelcmb{selchancmb,2}); str2 = str2(1:end-2); % str2 = sprintf('mean(%s)', str2); data.label = {str1, str2}; elseif all(isfinite(selchancmb)) data.labelcmb = data.labelcmb(selchancmb,:); elseif numel(selchancmb)==1 && any(~isfinite(selchancmb)) % do nothing elseif numel(selchancmb)>1 && any(~isfinite(selchancmb)) tmp = cell(numel(selchancmb),2); for k = 1:size(tmp,1) if isfinite(selchan(k)) tmp{k,1} = data.labelcmb{selchan(k),1}; tmp{k,2} = data.labelcmb{selchan(k),2}; end end data.labelcmb = tmp; else % this should never happen error('cannot figure out how to select channelcombinations'); end end % function makeselection_chancmb %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [chanindx, cfg] = getselection_chan(cfg, varargin) selmode = varargin{end}; ndata = numel(varargin)-1; varargin = varargin(1:ndata); % loop over data once to initialize chanindx = cell(ndata,1); label = cell(1,0); for k = 1:ndata selchannel = ft_channelselection(cfg.channel, varargin{k}.label); label = union(label, selchannel); end % this call to match_str ensures that that labels are always in the % order of the first input argument see bug_2917, but also temporarily keep % the labels from the other data structures not present in the first one % (in case selmode = 'union') [ix, iy] = match_str(varargin{1}.label, label); label1 = varargin{1}.label(:); % ensure column array label = [label1(ix); label(setdiff(1:numel(label),iy))]; indx = nan+zeros(numel(label), ndata); for k = 1:ndata [ix, iy] = match_str(label, varargin{k}.label); indx(ix,k) = iy; end switch selmode case 'intersect' sel = sum(isfinite(indx),2)==ndata; indx = indx(sel,:); label = varargin{1}.label(indx(:,1)); case 'union' % don't do a subselection otherwise error('invalid value for cfg.select'); end % switch ok = false(size(indx,1),1); for k = 1:ndata % loop through the columns to preserve the order of the channels, where % the order of the input arguments determines the final order ix = find(~ok); [srt,srtix] = sort(indx(ix,k)); indx(ix,:) = indx(ix(srtix),:); ok = ok | isfinite(indx(:,k)); end for k = 1:ndata % do a sanity check on double occurrences if numel(unique(indx(isfinite(indx(:,k)),k)))<sum(isfinite(indx(:,k))) error('the selection of channels across input arguments leads to double occurrences'); end chanindx{k} = indx(:,k); end for k = 1:ndata if isequal(chanindx{k}, (1:numel(varargin{k}.label))') % no actual selection is needed for this data structure chanindx{k} = nan; end end cfg.channel = label; end % function getselection_chan %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [chancmbindx, cfg] = getselection_chancmb(cfg, varargin) selmode = varargin{end}; ndata = numel(varargin)-1; varargin = varargin(1:ndata); chancmbindx = cell(ndata,1); if ~isfield(cfg, 'channelcmb') for k=1:ndata % the nan return value specifies that no selection was specified chancmbindx{k} = nan; end else switch selmode case 'intersect' for k=1:ndata if ~isfield(varargin{k}, 'label') cfg.channelcmb = ft_channelcombination(cfg.channelcmb, unique(varargin{k}.labelcmb(:))); else cfg.channelcmb = ft_channelcombination(cfg.channelcmb, varargin{k}.label); end end ncfgcmb = size(cfg.channelcmb,1); cfgcmb = cell(ncfgcmb, 1); for i=1:ncfgcmb cfgcmb{i} = sprintf('%s&%s', cfg.channelcmb{i,1}, cfg.channelcmb{i,2}); end for k=1:ndata ndatcmb = size(varargin{k}.labelcmb,1); datcmb = cell(ndatcmb, 1); for i=1:ndatcmb datcmb{i} = sprintf('%s&%s', varargin{k}.labelcmb{i,1}, varargin{k}.labelcmb{i,2}); end % return the order according to the (joint) configuration, not according to the (individual) data % FIXME this should adhere to the general code guidelines, where % the order returned will be according to the first data argument! [dum, chancmbindx{k}] = match_str(cfgcmb, datcmb); end case 'union' % FIXME this is not yet implemented error('union of channel combination is not yet supported'); otherwise error('invalid value for cfg.select'); end % switch end end % function getselection_chancmb %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [spikeindx, cfg] = getselection_spike(cfg, varargin) % possible specifications are % cfg.latency = string -> 'all' % cfg.latency = [beg end] % cfg.trials = string -> 'all' % cfg.trials = vector with indices ndata = numel(varargin); varargin = varargin(1:ndata); if isequal(cfg.latency, 'all') && isequal(cfg.trials, 'all') spikeindx = cell(1,ndata); for i=1:ndata spikeindx{i} = num2cell(nan(1, length(varargin{i}.time))); end return end trialbeg = varargin{1}.trialtime(:,1); trialend = varargin{1}.trialtime(:,2); for i=2:ndata trialbeg = cat(1, trialbeg, varargin{1}.trialtime(:,1)); trialend = cat(1, trialend, varargin{1}.trialtime(:,2)); end % convert string into a numeric selection if ischar(cfg.latency) switch cfg.latency case 'all' cfg.latency = [-inf inf]; case 'maxperiod' cfg.latency = [min(trialbeg) max(trialend)]; case 'minperiod' cfg.latency = [max(trialbeg) min(trialend)]; case 'prestim' cfg.latency = [min(trialbeg) 0]; case 'poststim' cfg.latency = [0 max(trialend)]; otherwise error('incorrect specification of cfg.latency'); end % switch end spikeindx = cell(1,ndata); for i=1:ndata nchan = length(varargin{i}.time); spikeindx{i} = cell(1,nchan); for j=1:nchan selbegtime = varargin{i}.time{j}>=cfg.latency(1); selendtime = varargin{i}.time{j}<=cfg.latency(2); if isequal(cfg.trials, 'all') seltrial = true(size(varargin{i}.trial{j})); else seltrial = ismember(varargin{i}.trial{j}, cfg.trials); end spikeindx{i}{j} = find(selbegtime & selendtime & seltrial); end end end % function getselection_spiketime %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [timeindx, cfg] = getselection_time(cfg, varargin) % possible specifications are % cfg.latency = value -> can be 'all' % cfg.latency = [beg end] if ft_datatype(varargin{1}, 'spike') error('latency selection in spike data is not supported') end selmode = varargin{end}; tol = varargin{end-1}; ndata = numel(varargin)-2; varargin = varargin(1:ndata); if isequal(cfg.latency, 'all') && iscell(varargin{1}.time) % for raw data this means that all trials should be selected as they are % for timelock/freq data it is still needed to make the intersection between data arguments timeindx = cell(1,ndata); for i=1:ndata % the nan return value specifies that no selection was specified timeindx{i} = num2cell(nan(1, length(varargin{i}.time))); end return end % if there is a single timelock/freq input, there is one time vector % if there are multiple timelock/freq inputs, there are multiple time vectors % if there is a single raw input, there are multiple time vectors % if there are multiple raw inputs, there are multiple time vectors % collect all time axes in one large cell-array alltimecell = {}; if iscell(varargin{1}.time) for k = 1:ndata alltimecell = [alltimecell varargin{k}.time{:}]; end else for k = 1:ndata alltimecell = [alltimecell {varargin{k}.time}]; end end % the nan return value specifies that no selection was specified timeindx = repmat({nan}, size(alltimecell)); % loop over data once to determine the union of all time axes alltimevec = zeros(1,0); for k = 1:length(alltimecell) alltimevec = union(alltimevec, round(alltimecell{k}/tol)*tol); end indx = nan(numel(alltimevec), numel(alltimecell)); for k = 1:numel(alltimecell) [dum, ix, iy] = intersect(alltimevec, round(alltimecell{k}/tol)*tol); indx(ix,k) = iy; end switch selmode case 'intersect' sel = sum(isfinite(indx),2)==numel(alltimecell); indx = indx(sel,:); alltimevec = alltimevec(sel); case 'union' % don't do a subselection otherwise error('invalid value for cfg.select'); end % Note that cfg.toilim handling has been removed, as it was renamed to cfg.latency % convert a string selection into a numeric selection if ischar(cfg.latency) switch cfg.latency case {'all' 'maxperlen'} cfg.latency = [min(alltimevec) max(alltimevec)]; case 'prestim' cfg.latency = [min(alltimevec) 0]; case 'poststim' cfg.latency = [0 max(alltimevec)]; otherwise error('incorrect specification of cfg.latency'); end % switch end % deal with numeric selection if isempty(cfg.latency) for k = 1:numel(alltimecell) % FIXME I do not understand this % this signifies that all time bins are deselected and should be removed timeindx{k} = []; end elseif numel(cfg.latency)==1 % this single value should be within the time axis of each input data structure if numel(alltimevec)>1 tbin = nearest(alltimevec, cfg.latency, true, true); % determine the numerical tolerance else tbin = nearest(alltimevec, cfg.latency, true, false); % don't consider tolerance end cfg.latency = alltimevec(tbin); for k = 1:ndata timeindx{k} = indx(tbin, k); end elseif numel(cfg.latency)==2 % the [min max] range can be specifed with +inf or -inf, but should % at least partially overlap with the time axis of the input data mintime = min(alltimevec); maxtime = max(alltimevec); if all(cfg.latency<mintime) || all(cfg.latency>maxtime) error('the selected time range falls outside the time axis in the data'); end tbeg = nearest(alltimevec, cfg.latency(1), false, false); tend = nearest(alltimevec, cfg.latency(2), false, false); cfg.latency = alltimevec([tbeg tend]); for k = 1:numel(alltimecell) timeindx{k} = indx(tbeg:tend, k); end elseif size(cfg.latency,2)==2 % this may be used for specification of the computation, not for data selection else error('incorrect specification of cfg.latency'); end for k = 1:numel(alltimecell) if isequal(timeindx{k}(:)', 1:length(alltimecell{k})) % no actual selection is needed for this data structure timeindx{k} = nan; end end if iscell(varargin{1}.time) % split all time axes again over the different input raw data structures dum = cell(1,ndata); for k = 1:ndata sel = 1:length(varargin{k}.time); dum{k} = timeindx(sel); % get the first selection timeindx(sel) = []; % remove the first selection end timeindx = dum; else % no splitting is needed, each input data structure has one selection end end % function getselection_time %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [freqindx, cfg] = getselection_freq(cfg, varargin) % possible specifications are % cfg.frequency = value -> can be 'all' % cfg.frequency = [beg end] selmode = varargin{end}; tol = varargin{end-1}; ndata = numel(varargin)-2; varargin = varargin(1:ndata); % loop over data once to initialize freqindx = cell(ndata,1); freqaxis = zeros(1,0); for k = 1:ndata % the nan return value specifies that no selection was specified freqindx{k} = nan; % update the axis along which the frequencies are defined freqaxis = union(freqaxis, round(varargin{k}.freq(:)/tol)*tol); end indx = nan+zeros(numel(freqaxis), ndata); for k = 1:ndata [dum, ix, iy] = intersect(freqaxis, round(varargin{k}.freq(:)/tol)*tol); indx(ix,k) = iy; end switch selmode case 'intersect' sel = sum(isfinite(indx),2)==ndata; indx = indx(sel,:); freqaxis = varargin{1}.freq(indx(:,1)); case 'union' % don't do a subselection otherwise error('invalid value for cfg.select'); end if isfield(cfg, 'frequency') % deal with string selection % some of these do not make sense, but are here for consistency with ft_multiplotER if ischar(cfg.frequency) if strcmp(cfg.frequency, 'all') cfg.frequency = [min(freqaxis) max(freqaxis)]; elseif strcmp(cfg.frequency, 'maxmin') cfg.frequency = [min(freqaxis) max(freqaxis)]; % the same as 'all' elseif strcmp(cfg.frequency, 'minzero') cfg.frequency = [min(freqaxis) 0]; elseif strcmp(cfg.frequency, 'maxabs') cfg.frequency = [-max(abs(freqaxis)) max(abs(freqaxis))]; elseif strcmp(cfg.frequency, 'zeromax') cfg.frequency = [0 max(freqaxis)]; elseif strcmp(cfg.frequency, 'zeromax') cfg.frequency = [0 max(freqaxis)]; else error('incorrect specification of cfg.frequency'); end end % deal with numeric selection if isempty(cfg.frequency) for k = 1:ndata % FIXME I do not understand this % this signifies that all frequency bins are deselected and should be removed freqindx{k} = []; end elseif numel(cfg.frequency)==1 % this single value should be within the frequency axis of each input data structure if numel(freqaxis)>1 fbin = nearest(freqaxis, cfg.frequency, true, true); % determine the numerical tolerance else fbin = nearest(freqaxis, cfg.frequency, true, false); % don't consider tolerance end cfg.frequency = freqaxis(fbin); for k = 1:ndata freqindx{k} = indx(fbin,k); end elseif numel(cfg.frequency)==2 % the [min max] range can be specifed with +inf or -inf, but should % at least partially overlap with the freq axis of the input data minfreq = min(freqaxis); maxfreq = max(freqaxis); if all(cfg.frequency<minfreq) || all(cfg.frequency>maxfreq) error('the selected range falls outside the frequency axis in the data'); end fbeg = nearest(freqaxis, cfg.frequency(1), false, false); fend = nearest(freqaxis, cfg.frequency(2), false, false); cfg.frequency = freqaxis([fbeg fend]); for k = 1:ndata freqindx{k} = indx(fbeg:fend,k); end elseif size(cfg.frequency,2)==2 % this may be used for specification of the computation, not for data selection else error('incorrect specification of cfg.frequency'); end end % if cfg.frequency for k = 1:ndata if isequal(freqindx{k}, 1:length(varargin{k}.freq)) % the cfg was updated, but no selection is needed for the data freqindx{k} = nan; end end end % function getselection_freq %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [rptindx, cfg, rptdim, rpttapindx] = getselection_rpt(cfg, varargin) % this should deal with cfg.trials dimord = varargin{end}; ndata = numel(varargin)-1; data = varargin{1:ndata}; % this syntax ensures that it will only work on a single data input dimtok = tokenize(dimord, '_'); rptdim = find(strcmp(dimtok, '{rpt}') | strcmp(dimtok, 'rpt') | strcmp(dimtok, 'rpttap') | strcmp(dimtok, 'subj')); if isequal(cfg.trials, 'all') rptindx = nan; % the nan return value specifies that no selection was specified rpttapindx = nan; % the nan return value specifies that no selection was specified elseif isempty(rptdim) rptindx = nan; % the nan return value specifies that no selection was specified rpttapindx = nan; % the nan return value specifies that no selection was specified else rptindx = ft_getopt(cfg, 'trials'); if islogical(rptindx) % convert from booleans to indices rptindx = find(rptindx); end rptindx = unique(sort(rptindx)); if strcmp(dimtok{rptdim}, 'rpttap') && isfield(data, 'cumtapcnt') % there are tapers in the data % determine for each taper to which trial it belongs if numel(data.cumtapcnt)~=length(data.cumtapcnt) error('FIXME this is not yet implemented for mtmconvol with keeptrials and varying number of tapers per frequency'); end nrpt = length(data.cumtapcnt); taper = zeros(nrpt, 1); sumtapcnt = cumsum([0; data.cumtapcnt(:)]); begtapcnt = sumtapcnt(1:end-1)+1; endtapcnt = sumtapcnt(2:end); for i=1:nrpt taper(begtapcnt(i):endtapcnt(i)) = i; end rpttapindx = find(ismember(taper, rptindx)); else % there are no tapers in the data rpttapindx = rptindx; end end end % function getselection_rpt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [posindx, cfg] = getselection_pos(cfg, varargin) % possible specifications are <none> ndata = numel(varargin)-2; tol = varargin{end-1}; % FIXME this is still ignored selmode = varargin{end}; % FIXME this is still ignored data = varargin(1:ndata); for i=1:ndata if ~isequal(varargin{i}.pos, varargin{1}.pos) % FIXME it would be possible here to make a selection based on intersect or union error('not yet implemented'); end end if strcmp(cfg.select, 'union') % FIXME it would be possible here to make a selection based on intersect or union error('not yet implemented'); end for i=1:ndata posindx{i} = nan; % the nan return value specifies that no selection was specified end end % function getselection_pos %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function x = squeezedim(x, dim) siz = size(x); for i=(numel(siz)+1):numel(dim) % all trailing singleton dimensions have length 1 siz(i) = 1; end if isvector(x) % there is no harm to keep it as it is else x = reshape(x, [siz(~dim) 1]); end end % function squeezedim %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function x = makeunion(x, field) old = cellfun(@getfield, x, repmat({field}, size(x)), 'uniformoutput', false); if iscell(old{1}) % empty is indicated to represent missing value for a cell array (label, labelcmb) new = old{1}; for i=2:length(old) sel = ~cellfun(@isempty, old{i}); new(sel) = old{i}(sel); end else % nan is indicated to represent missing value for a numeric array (time, freq, pos) new = old{1}; for i=2:length(old) sel = ~isnan(old{i}); new(sel) = old{i}(sel); end end x = cellfun(@setfield, x, repmat({field}, size(x)), repmat({new}, size(x)), 'uniformoutput', false); end % function makeunion %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to make a selextion in data representations like {pos}_ori_time % FIXME this will fail for {xxx_yyy}_zzz %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function x = cellmatselect(x, seldim, selindx, maybevector) if nargin<4 % some fields are a vector with an unspecified singleton dimension, these can be transposed % if the singleton dimension represents something explicit, they should not be transposed % they might for example represent a single trial, or a single channel maybevector = true; end if iscell(x) if seldim==1 x = x(selindx); else for i=1:numel(x) if isempty(x{i}) continue end switch seldim case 2 if maybevector && isvector(x{i}) % sometimes the data is 1xN, whereas the dimord describes only the first dimension % in this case a row and column vector can be interpreted as equivalent x{i} = x{i}(selindx); else x{i} = x{i}(selindx,:,:,:,:); end case 3 x{i} = x{i}(:,selindx,:,:,:); case 4 x{i} = x{i}(:,:,selindx,:,:); case 5 x{i} = x{i}(:,:,:,selindx,:); case 6 x{i} = x{i}(:,:,:,:,selindx); otherwise error('unsupported dimension (%d) for making a selection', seldim); end % switch end % for end else switch seldim case 1 if maybevector && isvector(x) % sometimes the data is 1xN, whereas the dimord describes only the first dimension % in this case a row and column vector can be interpreted as equivalent x = x(selindx); else x = x(selindx,:,:,:,:,:); end case 2 x = x(:,selindx,:,:,:,:); case 3 x = x(:,:,selindx,:,:,:); case 4 x = x(:,:,:,selindx,:,:); case 5 x = x(:,:,:,:,selindx,:); case 6 x = x(:,:,:,:,:,selindx); otherwise error('unsupported dimension (%d) for making a selection', seldim); end end end % function cellmatselect %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to take an average in data representations like {pos}_ori_time % FIXME this will fail for {xxx_yyy}_zzz %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function x = cellmatmean(x, seldim, average) if iscell(x) if seldim==1 for i=2:numel(x) x{1} = x{1} + x{i}; end x = {x{1}/numel(x)}; else for i=1:numel(x) x{i} = average(x{i}, seldim-1); end % for end else x = average(x, seldim); end end % function cellmatmean
github
lcnbeapp/beapp-master
ft_transform_geometry.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/ft_transform_geometry.m
4,001
utf_8
65ab78e845b70fd7afc0d6c59e0fc89e
function [output] = ft_transform_geometry(transform, input) % FT_TRANSFORM_GEOMETRY applies a homogeneous coordinate transformation to % a structure with geometric information, for example a volume conduction model % for the head, gradiometer of electrode structure containing EEG or MEG % sensor positions and MEG coil orientations, a head shape or a source model. % % The units in which the transformation matrix is expressed are assumed to % be the same units as the units in which the geometric object is % expressed. Depending on the input object, the homogeneous transformation % matrix should be limited to a rigid-body translation plus rotation % (MEG-gradiometer array), or to a rigid-body translation plus rotation % plus a global rescaling (volume conductor geometry). % % Use as % output = ft_transform_geometry(transform, input) % % See also FT_WARP_APPLY, FT_HEADCOORDINATES % Copyright (C) 2011, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_transform_geometry.m$ % flg rescaling check allowscaling = ~ft_senstype(input, 'meg'); % determine the rotation matrix rotation = eye(4); rotation(1:3,1:3) = transform(1:3,1:3); if any(abs(transform(4,:)-[0 0 0 1])>100*eps) error('invalid transformation matrix'); end if ~allowscaling % allow for some numerical imprecision if abs(det(rotation)-1)>1e-6%100*eps %if abs(det(rotation)-1)>100*eps % allow for some numerical imprecision error('only a rigid body transformation without rescaling is allowed'); end end if allowscaling % FIXME build in a check for uniform rescaling probably do svd or so % FIXME insert check for nonuniform scaling, should give an error end tfields = {'pos' 'pnt' 'o' 'coilpos' 'chanpos' 'chanposold' 'chanposorg' 'elecpos', 'nas', 'lpa', 'rpa', 'zpoint'}; % apply rotation plus translation rfields = {'ori' 'nrm' 'coilori' 'chanori' 'chanoriold' 'chanoriorg'}; % only apply rotation mfields = {'transform'}; % plain matrix multiplication recfields = {'fid' 'bnd' 'orig'}; % recurse into these fields % the field 'r' is not included here, because it applies to a volume % conductor model, and scaling is not allowed, so r will not change. fnames = fieldnames(input); for k = 1:numel(fnames) if ~isempty(input.(fnames{k})) if any(strcmp(fnames{k}, tfields)) input.(fnames{k}) = apply(transform, input.(fnames{k})); elseif any(strcmp(fnames{k}, rfields)) input.(fnames{k}) = apply(rotation, input.(fnames{k})); elseif any(strcmp(fnames{k}, mfields)) input.(fnames{k}) = transform*input.(fnames{k}); elseif any(strcmp(fnames{k}, recfields)) for j = 1:numel(input.(fnames{k})) input.(fnames{k})(j) = ft_transform_geometry(transform, input.(fnames{k})(j)); end else % do nothing end end end output = input; return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that applies the homogeneous transformation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [new] = apply(transform, old) old(:,4) = 1; new = old * transform'; new = new(:,1:3);
github
lcnbeapp/beapp-master
getdimord.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/private/getdimord.m
20,107
utf_8
706f4f45a5d4ae7535c204b8c010f76b
function dimord = getdimord(data, field, varargin) % GETDIMORD % % Use as % dimord = getdimord(data, field) % % See also GETDIMSIZ, GETDATFIELD if ~isfield(data, field) && isfield(data, 'avg') && isfield(data.avg, field) field = ['avg.' field]; elseif ~isfield(data, field) && isfield(data, 'trial') && isfield(data.trial, field) field = ['trial.' field]; elseif ~isfield(data, field) error('field "%s" not present in data', field); end if strncmp(field, 'avg.', 4) prefix = ''; field = field(5:end); % strip the avg data.(field) = data.avg.(field); % copy the avg into the main structure data = rmfield(data, 'avg'); elseif strncmp(field, 'trial.', 6) prefix = '(rpt)_'; field = field(7:end); % strip the trial data.(field) = data.trial(1).(field); % copy the first trial into the main structure data = rmfield(data, 'trial'); else prefix = ''; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 1: the specific dimord is simply present %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isfield(data, [field 'dimord']) dimord = data.([field 'dimord']); return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if not present, we need some additional information about the data strucure %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % nan means that the value is not known and might remain unknown % inf means that the value is not known but should be known ntime = inf; nfreq = inf; nchan = inf; nchancmb = inf; nsubj = nan; nrpt = nan; nrpttap = nan; npos = inf; nori = nan; % this will be 3 in many cases ntopochan = inf; nspike = inf; % this is only for the first spike channel nlag = nan; ndim1 = nan; ndim2 = nan; ndim3 = nan; % use an anonymous function assign = @(var, val) assignin('caller', var, val); % it is possible to pass additional ATTEMPTs such as nrpt, nrpttap, etc for i=1:2:length(varargin) assign(varargin{i}, varargin{i+1}); end % try to determine the size of each possible dimension in the data if isfield(data, 'label') nchan = length(data.label); end if isfield(data, 'labelcmb') nchancmb = size(data.labelcmb, 1); end if isfield(data, 'time') if iscell(data.time) && ~isempty(data.time) tmp = getdimsiz(data, 'time'); ntime = tmp(3); % raw data may contain variable length trials else ntime = length(data.time); end end if isfield(data, 'freq') nfreq = length(data.freq); end if isfield(data, 'trial') && ft_datatype(data, 'raw') nrpt = length(data.trial); end if isfield(data, 'trialtime') && ft_datatype(data, 'spike') nrpt = size(data.trialtime,1); end if isfield(data, 'cumtapcnt') nrpt = size(data.cumtapcnt,1); if numel(data.cumtapcnt)==length(data.cumtapcnt) % it is a vector, hence it only represents repetitions nrpttap = sum(data.cumtapcnt); else % it is a matrix, hence it is repetitions by frequencies % this happens after mtmconvol with keeptrials nrpttap = sum(data.cumtapcnt,2); if any(nrpttap~=nrpttap(1)) warning('unexpected variation of the number of tapers over trials') nrpttap = nan; else nrpttap = nrpttap(1); end end end if isfield(data, 'pos') npos = size(data.pos,1); elseif isfield(data, 'dim') npos = prod(data.dim); end if isfield(data, 'dim') ndim1 = data.dim(1); ndim2 = data.dim(2); ndim3 = data.dim(3); end if isfield(data, 'csdlabel') % this is used in PCC beamformers if length(data.csdlabel)==npos % each position has its own labels len = cellfun(@numel, data.csdlabel); len = len(len~=0); if all(len==len(1)) % they all have the same length nori = len(1); end else % one list of labels for all positions nori = length(data.csdlabel); end elseif isfinite(npos) % assume that there are three dipole orientations per source nori = 3; end if isfield(data, 'topolabel') % this is used in ICA and PCA decompositions ntopochan = length(data.topolabel); end if isfield(data, 'timestamp') && iscell(data.timestamp) nspike = length(data.timestamp{1}); % spike data: only for the first channel end if ft_datatype(data, 'mvar') && isfield(data, 'coeffs') nlag = size(data.coeffs,3); end % determine the size of the actual data datsiz = getdimsiz(data, field); tok = {'subj' 'rpt' 'rpttap' 'chan' 'chancmb' 'freq' 'time' 'pos' 'ori' 'topochan' 'lag' 'dim1' 'dim2' 'dim3'}; siz = [nsubj nrpt nrpttap nchan nchancmb nfreq ntime npos nori ntopochan nlag ndim1 ndim2 ndim3]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 2: a general dimord is present and might apply %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isfield(data, 'dimord') dimtok = tokenize(data.dimord, '_'); if length(dimtok)>length(datsiz) && check_trailingdimsunitlength(data, dimtok((length(datsiz)+1):end)) % add the trailing singleton dimensions to datsiz, if needed datsiz = [datsiz ones(1,max(0,length(dimtok)-length(datsiz)))]; end if length(dimtok)==length(datsiz) || (length(dimtok)==(length(datsiz)-1) && datsiz(end)==1) success = false(size(dimtok)); for i=1:length(dimtok) sel = strcmp(tok, dimtok{i}); if any(sel) && datsiz(i)==siz(sel) success(i) = true; elseif strcmp(dimtok{i}, 'subj') % the number of subjects cannot be determined, and will be indicated as nan success(i) = true; elseif strcmp(dimtok{i}, 'rpt') % the number of trials is hard to determine, and might be indicated as nan success(i) = true; end end % for if all(success) dimord = data.dimord; return end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 3: look at the size of some common fields that are known %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch field % the logic for this code is to first check whether the size of a field % has an exact match to a potential dimensionality, if not, check for a % partial match (ignoring nans) % note that the case for a cell dimension (typically pos) is handled at % the end of this section case {'pos'} if isequalwithoutnans(datsiz, [npos 3]) dimord = 'pos_unknown'; end case {'individual'} if isequalwithoutnans(datsiz, [nsubj nchan ntime]) dimord = 'subj_chan_time'; end case {'avg' 'var' 'dof'} if isequal(datsiz, [nrpt nchan ntime]) dimord = 'rpt_chan_time'; elseif isequal(datsiz, [nchan ntime]) dimord = 'chan_time'; elseif isequalwithoutnans(datsiz, [nrpt nchan ntime]) dimord = 'rpt_chan_time'; elseif isequalwithoutnans(datsiz, [nchan ntime]) dimord = 'chan_time'; end case {'powspctrm' 'fourierspctrm'} if isequal(datsiz, [nrpt nchan nfreq ntime]) dimord = 'rpt_chan_freq_time'; elseif isequal(datsiz, [nrpt nchan nfreq]) dimord = 'rpt_chan_freq'; elseif isequal(datsiz, [nchan nfreq ntime]) dimord = 'chan_freq_time'; elseif isequal(datsiz, [nchan nfreq]) dimord = 'chan_freq'; elseif isequalwithoutnans(datsiz, [nrpt nchan nfreq ntime]) dimord = 'rpt_chan_freq_time'; elseif isequalwithoutnans(datsiz, [nrpt nchan nfreq]) dimord = 'rpt_chan_freq'; elseif isequalwithoutnans(datsiz, [nchan nfreq ntime]) dimord = 'chan_freq_time'; elseif isequalwithoutnans(datsiz, [nchan nfreq]) dimord = 'chan_freq'; end case {'crsspctrm' 'cohspctrm'} if isequal(datsiz, [nrpt nchancmb nfreq ntime]) dimord = 'rpt_chancmb_freq_time'; elseif isequal(datsiz, [nrpt nchancmb nfreq]) dimord = 'rpt_chancmb_freq'; elseif isequal(datsiz, [nchancmb nfreq ntime]) dimord = 'chancmb_freq_time'; elseif isequal(datsiz, [nchancmb nfreq]) dimord = 'chancmb_freq'; elseif isequal(datsiz, [nrpt nchan nchan nfreq ntime]) dimord = 'rpt_chan_chan_freq_time'; elseif isequal(datsiz, [nrpt nchan nchan nfreq]) dimord = 'rpt_chan_chan_freq'; elseif isequal(datsiz, [nchan nchan nfreq ntime]) dimord = 'chan_chan_freq_time'; elseif isequal(datsiz, [nchan nchan nfreq]) dimord = 'chan_chan_freq'; elseif isequal(datsiz, [npos nori]) dimord = 'pos_ori'; elseif isequal(datsiz, [npos 1]) dimord = 'pos'; elseif isequalwithoutnans(datsiz, [nrpt nchancmb nfreq ntime]) dimord = 'rpt_chancmb_freq_time'; elseif isequalwithoutnans(datsiz, [nrpt nchancmb nfreq]) dimord = 'rpt_chancmb_freq'; elseif isequalwithoutnans(datsiz, [nchancmb nfreq ntime]) dimord = 'chancmb_freq_time'; elseif isequalwithoutnans(datsiz, [nchancmb nfreq]) dimord = 'chancmb_freq'; elseif isequalwithoutnans(datsiz, [nrpt nchan nchan nfreq ntime]) dimord = 'rpt_chan_chan_freq_time'; elseif isequalwithoutnans(datsiz, [nrpt nchan nchan nfreq]) dimord = 'rpt_chan_chan_freq'; elseif isequalwithoutnans(datsiz, [nchan nchan nfreq ntime]) dimord = 'chan_chan_freq_time'; elseif isequalwithoutnans(datsiz, [nchan nchan nfreq]) dimord = 'chan_chan_freq'; elseif isequalwithoutnans(datsiz, [npos nori]) dimord = 'pos_ori'; elseif isequalwithoutnans(datsiz, [npos 1]) dimord = 'pos'; end case {'cov' 'coh' 'csd' 'noisecov' 'noisecsd'} % these occur in timelock and in source structures if isequal(datsiz, [nrpt nchan nchan]) dimord = 'rpt_chan_chan'; elseif isequal(datsiz, [nchan nchan]) dimord = 'chan_chan'; elseif isequal(datsiz, [npos nori nori]) dimord = 'pos_ori_ori'; elseif isequal(datsiz, [npos nrpt nori nori]) dimord = 'pos_rpt_ori_ori'; elseif isequalwithoutnans(datsiz, [nrpt nchan nchan]) dimord = 'rpt_chan_chan'; elseif isequalwithoutnans(datsiz, [nchan nchan]) dimord = 'chan_chan'; elseif isequalwithoutnans(datsiz, [npos nori nori]) dimord = 'pos_ori_ori'; elseif isequalwithoutnans(datsiz, [npos nrpt nori nori]) dimord = 'pos_rpt_ori_ori'; end case {'tf'} if isequal(datsiz, [npos nfreq ntime]) dimord = 'pos_freq_time'; end case {'pow'} if isequal(datsiz, [npos ntime]) dimord = 'pos_time'; elseif isequal(datsiz, [npos nfreq]) dimord = 'pos_freq'; elseif isequal(datsiz, [npos nrpt]) dimord = 'pos_rpt'; elseif isequal(datsiz, [nrpt npos ntime]) dimord = 'rpt_pos_time'; elseif isequal(datsiz, [nrpt npos nfreq]) dimord = 'rpt_pos_freq'; elseif isequal(datsiz, [npos 1]) % in case there are no repetitions dimord = 'pos'; elseif isequalwithoutnans(datsiz, [npos ntime]) dimord = 'pos_time'; elseif isequalwithoutnans(datsiz, [npos nfreq]) dimord = 'pos_freq'; elseif isequalwithoutnans(datsiz, [npos nrpt]) dimord = 'pos_rpt'; elseif isequalwithoutnans(datsiz, [nrpt npos ntime]) dimord = 'rpt_pos_time'; elseif isequalwithoutnans(datsiz, [nrpt npos nfreq]) dimord = 'rpt_pos_freq'; end case {'mom','itc','aa','stat','pval','statitc','pitc'} if isequal(datsiz, [npos nori nrpt]) dimord = 'pos_ori_rpt'; elseif isequal(datsiz, [npos nori ntime]) dimord = 'pos_ori_time'; elseif isequal(datsiz, [npos nori nfreq]) dimord = 'pos_ori_nfreq'; elseif isequal(datsiz, [npos ntime]) dimord = 'pos_time'; elseif isequal(datsiz, [npos nfreq]) dimord = 'pos_freq'; elseif isequal(datsiz, [npos 3]) dimord = 'pos_ori'; elseif isequal(datsiz, [npos 1]) dimord = 'pos'; elseif isequal(datsiz, [npos nrpt]) dimord = 'pos_rpt'; elseif isequalwithoutnans(datsiz, [npos nori nrpt]) dimord = 'pos_ori_rpt'; elseif isequalwithoutnans(datsiz, [npos nori ntime]) dimord = 'pos_ori_time'; elseif isequalwithoutnans(datsiz, [npos nori nfreq]) dimord = 'pos_ori_nfreq'; elseif isequalwithoutnans(datsiz, [npos ntime]) dimord = 'pos_time'; elseif isequalwithoutnans(datsiz, [npos nfreq]) dimord = 'pos_freq'; elseif isequalwithoutnans(datsiz, [npos 3]) dimord = 'pos_ori'; elseif isequalwithoutnans(datsiz, [npos 1]) dimord = 'pos'; elseif isequalwithoutnans(datsiz, [npos nrpt]) dimord = 'pos_rpt'; elseif isequalwithoutnans(datsiz, [npos nrpt nori ntime]) dimord = 'pos_rpt_ori_time'; elseif isequalwithoutnans(datsiz, [npos nrpt 1 ntime]) dimord = 'pos_rpt_ori_time'; elseif isequal(datsiz, [npos nfreq ntime]) dimord = 'pos_freq_time'; end case {'filter'} if isequalwithoutnans(datsiz, [npos nori nchan]) || (isequal(datsiz([1 2]), [npos nori]) && isinf(nchan)) dimord = 'pos_ori_chan'; end case {'leadfield'} if isequalwithoutnans(datsiz, [npos nchan nori]) || (isequal(datsiz([1 3]), [npos nori]) && isinf(nchan)) dimord = 'pos_chan_ori'; end case {'ori' 'eta'} if isequal(datsiz, [npos nori]) || isequal(datsiz, [npos 3]) dimord = 'pos_ori'; end case {'csdlabel'} if isequal(datsiz, [npos nori]) || isequal(datsiz, [npos 3]) dimord = 'pos_ori'; end case {'trial'} if ~iscell(data.(field)) && isequalwithoutnans(datsiz, [nrpt nchan ntime]) dimord = 'rpt_chan_time'; elseif isequalwithoutnans(datsiz, [nrpt nchan ntime]) dimord = '{rpt}_chan_time'; elseif isequalwithoutnans(datsiz, [nchan nspike]) || isequalwithoutnans(datsiz, [nchan 1 nspike]) dimord = '{chan}_spike'; end case {'sampleinfo' 'trialinfo' 'trialtime'} if isequalwithoutnans(datsiz, [nrpt nan]) dimord = 'rpt_other'; end case {'cumtapcnt' 'cumsumcnt'} if isequalwithoutnans(datsiz, [nrpt nan]) dimord = 'rpt_other'; end case {'topo'} if isequalwithoutnans(datsiz, [ntopochan nchan]) dimord = 'topochan_chan'; end case {'unmixing'} if isequalwithoutnans(datsiz, [nchan ntopochan]) dimord = 'chan_topochan'; end case {'inside'} if isequalwithoutnans(datsiz, [npos]) dimord = 'pos'; end case {'timestamp' 'time'} if ft_datatype(data, 'spike') && iscell(data.(field)) && datsiz(1)==nchan dimord = '{chan}_spike'; elseif ft_datatype(data, 'raw') && iscell(data.(field)) && datsiz(1)==nrpt dimord = '{rpt}_time'; elseif isvector(data.(field)) && isequal(datsiz, [1 ntime ones(1,numel(datsiz)-2)]) dimord = 'time'; end case {'freq'} if isvector(data.(field)) && isequal(datsiz, [1 nfreq]) dimord = 'freq'; end otherwise if isfield(data, 'dim') && isequal(datsiz, data.dim) dimord = 'dim1_dim2_dim3'; end end % switch field % deal with possible first pos which is a cell if exist('dimord', 'var') && strcmp(dimord(1:3), 'pos') && iscell(data.(field)) dimord = ['{pos}' dimord(4:end)]; end if ~exist('dimord', 'var') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 4: there is only one way that the dimensions can be interpreted %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% dimtok = cell(size(datsiz)); for i=1:length(datsiz) sel = find(siz==datsiz(i)); if length(sel)==1 % there is exactly one corresponding dimension dimtok{i} = tok{sel}; else % there are zero or multiple corresponding dimensions dimtok{i} = []; end end if all(~cellfun(@isempty, dimtok)) if iscell(data.(field)) dimtok{1} = ['{' dimtok{1} '}']; end dimord = sprintf('%s_', dimtok{:}); dimord = dimord(1:end-1); return end end % if dimord does not exist if ~exist('dimord', 'var') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 5: compare the size with the known size of each dimension %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% sel = ~isnan(siz) & ~isinf(siz); % nan means that the value is not known and might remain unknown % inf means that the value is not known and but should be known if length(unique(siz(sel)))==length(siz(sel)) % this should only be done if there is no chance of confusing dimensions dimtok = cell(size(datsiz)); dimtok(datsiz==npos) = {'pos'}; dimtok(datsiz==nori) = {'ori'}; dimtok(datsiz==nrpttap) = {'rpttap'}; dimtok(datsiz==nrpt) = {'rpt'}; dimtok(datsiz==nsubj) = {'subj'}; dimtok(datsiz==nchancmb) = {'chancmb'}; dimtok(datsiz==nchan) = {'chan'}; dimtok(datsiz==nfreq) = {'freq'}; dimtok(datsiz==ntime) = {'time'}; dimtok(datsiz==ndim1) = {'dim1'}; dimtok(datsiz==ndim2) = {'dim2'}; dimtok(datsiz==ndim3) = {'dim3'}; if isempty(dimtok{end}) && datsiz(end)==1 % remove the unknown trailing singleton dimension dimtok = dimtok(1:end-1); elseif isequal(dimtok{1}, 'pos') && isempty(dimtok{2}) && datsiz(2)==1 % remove the unknown leading singleton dimension dimtok(2) = []; end if all(~cellfun(@isempty, dimtok)) if iscell(data.(field)) dimtok{1} = ['{' dimtok{1} '}']; end dimord = sprintf('%s_', dimtok{:}); dimord = dimord(1:end-1); return end end end % if dimord does not exist if ~exist('dimord', 'var') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 6: check whether it is a 3-D volume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isequal(datsiz, [ndim1 ndim2 ndim3]) dimord = 'dim1_dim2_dim3'; end end % if dimord does not exist %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % FINAL RESORT: return "unknown" for all unknown dimensions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~exist('dimord', 'var') % this should not happen % if it does, it might help in diagnosis to have a very informative warning message % since there have been problems with trials not being selected correctly due to the warning going unnoticed % it is better to throw an error than a warning warning('could not determine dimord of "%s" in the following data', field) disp(data); dimtok(cellfun(@isempty, dimtok)) = {'unknown'}; if all(~cellfun(@isempty, dimtok)) if iscell(data.(field)) dimtok{1} = ['{' dimtok{1} '}']; end dimord = sprintf('%s_', dimtok{:}); dimord = dimord(1:end-1); end end % add '(rpt)' in case of source.trial dimord = [prefix dimord]; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ok = isequalwithoutnans(a, b) % this is *only* used to compare matrix sizes, so we can ignore any singleton last dimension numdiff = numel(b)-numel(a); if numdiff > 0 % assume singleton dimensions missing in a a = [a(:); ones(numdiff, 1)]; b = b(:); elseif numdiff < 0 % assume singleton dimensions missing in b b = [b(:); ones(abs(numdiff), 1)]; a = a(:); end c = ~isnan(a(:)) & ~isnan(b(:)); ok = isequal(a(c), b(c)); end % function isequalwithoutnans %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ok = check_trailingdimsunitlength(data, dimtok) ok = false; for k = 1:numel(dimtok) switch dimtok{k} case 'chan' ok = numel(data.label)==1; otherwise if isfield(data, dimtok{k}); % check whether field exists ok = numel(data.(dimtok{k}))==1; end; end if ok, break; end end end % function check_trailingdimsunitlength
github
lcnbeapp/beapp-master
pinvNx2.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/private/pinvNx2.m
1,116
utf_8
a10c4b3cf66f4a8756fdb95d62b5e04a
function y = pinvNx2(x) % PINVNX2 computes a pseudo-inverse of the slices of an Nx2xM real-valued matrix. % Output has dimensionality 2xNxM. This implementation is generally faster % than calling pinv in a for-loop, once M > 2 siz = [size(x) 1]; xtx = zeros([2,2,siz(3:end)]); xtx(1,1,:,:) = sum(x(:,1,:,:).^2,1); xtx(2,2,:,:) = sum(x(:,2,:,:).^2,1); tmp = sum(x(:,1,:,:).*x(:,2,:,:),1); xtx(1,2,:,:) = tmp; xtx(2,1,:,:) = tmp; ixtx = inv2x2(xtx); y = mtimes2xN(ixtx, permute(x, [2 1 3:ndims(x)])); function [d] = inv2x2(x) % INV2X2 computes inverse of matrix x, where x = 2x2xN, using explicit analytic definition adjx = [x(2,2,:,:) -x(1,2,:,:); -x(2,1,:,:) x(1,1,:,:)]; denom = x(1,1,:,:).*x(2,2,:,:) - x(1,2,:,:).*x(2,1,:,:); d = adjx./denom([1 1],[1 1],:,:); function [z] = mtimes2xN(x, y) % MTIMES2XN computes x*y where x = 2x2xM and y = 2xNxM % and output dimensionatity is 2xNxM siz = size(y); z = zeros(siz); for k = 1:siz(2) z(1,k,:,:) = x(1,1,:,:).*y(1,k,:,:) + x(1,2,:,:).*y(2,k,:,:); z(2,k,:,:) = x(2,1,:,:).*y(1,k,:,:) + x(2,2,:,:).*y(2,k,:,:); end
github
lcnbeapp/beapp-master
individual2sn.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/private/individual2sn.m
4,944
utf_8
8972e941e1b5082b8d0c29a8c3f70454
function [warped]= individual2sn(P, input) % INDIVIDUAL2SN warps the input coordinates (defined as Nx3 matrix) from % individual headspace coordinates into normalised MNI coordinates, using the % (inverse of the) warp parameters defined in the structure spmparams. % % this is code inspired by nutmeg and spm: nut_mri2mni, nut_spm_sn2def and % nut_spm_invdef which were themselves modified from code originally written % by John Ashburner: % http://www.sph.umich.edu/~nichols/JohnsGems2.html % % Use as % [warped] = individual2sn(P, input) % % Input parameters: % P = structure that contains the contents of an spm generated _sn.mat % file % input = Nx3 array containing the input positions % Copyright (C) 2013, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ ft_hastoolbox('spm8up', 1); % The following is a three-step procedure % 1: create the spatial deformation field from the sn parameters [Def, M] = get_sn2def(P); % 2a: invert the spatial deformation field [p,f,e] = fileparts(which('spm_invdef')); templatedirname = fullfile(p,'templates'); d = dir([templatedirname,'/T1*']); VT = spm_vol(fullfile(templatedirname,d(1).name)); [iy1,iy2,iy3] = spm_invdef(Def{1},Def{2},Def{3},VT.dim(1:3),inv(VT.mat),M); % 2b: write the deformation fields in x/y/z direction to temporary files V1.fname = [tempname '.img']; V1.dim(1:3) = VT.dim(1:3); V1.pinfo = [1 0 0]'; V1.mat = VT.mat; V1.dt = [64 0]; V1.descrip = 'Inverse deformation field'; spm_write_vol(V1,iy1); V2.fname = [tempname '.img']; V2.dim(1:3) = VT.dim(1:3); V2.pinfo = [1 0 0]'; V2.mat = VT.mat; V2.dt = [64 0]; V2.descrip = 'Inverse deformation field'; spm_write_vol(V2,iy2); V3.fname = [tempname '.img']; V3.dim(1:3) = VT.dim(1:3); V3.pinfo = [1 0 0]'; V3.mat = VT.mat; V3.dt = [64 0]; V3.descrip = 'Inverse deformation field'; spm_write_vol(V3,iy3); % 3: extract the coordinates warped = ft_warp_apply(inv(V1.mat), input); % Express as voxel indices warped = cat(2, spm_sample_vol(V1,warped(:,1),warped(:,2),warped(:,3),1), ... spm_sample_vol(V2,warped(:,1),warped(:,2),warped(:,3),1), ... spm_sample_vol(V3,warped(:,1),warped(:,2),warped(:,3),1)); %_______________________________________________________________________ function [Def,mat] = get_sn2def(sn) % Convert a SPM _sn.mat file into a deformation field, and return it. % This is code that was taken from SPM8. dim = sn.VG(1).dim; x = 1:dim(1); y = 1:dim(2); z = 1:dim(3); mat = sn.VG(1).mat; [X,Y] = ndgrid(x,y); st = size(sn.Tr); if (prod(st) == 0), affine_only = true; basX = 0; basY = 0; basZ = 0; else affine_only = false; basX = spm_dctmtx(sn.VG(1).dim(1),st(1),x-1); basY = spm_dctmtx(sn.VG(1).dim(2),st(2),y-1); basZ = spm_dctmtx(sn.VG(1).dim(3),st(3),z-1); end, Def = single(0); Def(numel(x),numel(y),numel(z)) = 0; Def = {Def; Def; Def}; for j=1:length(z) if (~affine_only) tx = reshape( reshape(sn.Tr(:,:,:,1),st(1)*st(2),st(3)) *basZ(j,:)', st(1), st(2) ); ty = reshape( reshape(sn.Tr(:,:,:,2),st(1)*st(2),st(3)) *basZ(j,:)', st(1), st(2) ); tz = reshape( reshape(sn.Tr(:,:,:,3),st(1)*st(2),st(3)) *basZ(j,:)', st(1), st(2) ); X1 = X + basX*tx*basY'; Y1 = Y + basX*ty*basY'; Z1 = z(j) + basX*tz*basY'; end Mult = sn.VF.mat*sn.Affine; if (~affine_only) X2= Mult(1,1)*X1 + Mult(1,2)*Y1 + Mult(1,3)*Z1 + Mult(1,4); Y2= Mult(2,1)*X1 + Mult(2,2)*Y1 + Mult(2,3)*Z1 + Mult(2,4); Z2= Mult(3,1)*X1 + Mult(3,2)*Y1 + Mult(3,3)*Z1 + Mult(3,4); else X2= Mult(1,1)*X + Mult(1,2)*Y + (Mult(1,3)*z(j) + Mult(1,4)); Y2= Mult(2,1)*X + Mult(2,2)*Y + (Mult(2,3)*z(j) + Mult(2,4)); Z2= Mult(3,1)*X + Mult(3,2)*Y + (Mult(3,3)*z(j) + Mult(3,4)); end Def{1}(:,:,j) = single(X2); Def{2}(:,:,j) = single(Y2); Def{3}(:,:,j) = single(Z2); end; %_______________________________________________________________________
github
lcnbeapp/beapp-master
ft_platform_supports.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/private/ft_platform_supports.m
9,557
utf_8
eb0e55d84d57e6873cce8df6cad90d96
function tf = ft_platform_supports(what,varargin) % FT_PLATFORM_SUPPORTS returns a boolean indicating whether the current platform % supports a specific capability % % Usage: % tf = ft_platform_supports(what) % tf = ft_platform_supports('matlabversion', min_version, max_version) % % The following values are allowed for the 'what' parameter: % value means that the following is supported: % % 'which-all' which(...,'all') % 'exists-in-private-directory' exists(...) will look in the /private % subdirectory to see if a file exists % 'onCleanup' onCleanup(...) % 'alim' alim(...) % 'int32_logical_operations' bitand(a,b) with a, b of type int32 % 'graphics_objects' graphics sysem is object-oriented % 'libmx_c_interface' libmx is supported through mex in the % C-language (recent Matlab versions only % support C++) % 'stats' all statistical functions in % FieldTrip's external/stats directory % 'program_invocation_name' program_invocation_name() (GNU Octave) % 'singleCompThread' start Matlab with -singleCompThread % 'nosplash' -nosplash % 'nodisplay' -nodisplay % 'nojvm' -nojvm % 'no-gui' start GNU Octave with --no-gui % 'RandStream.setGlobalStream' RandStream.setGlobalStream(...) % 'RandStream.setDefaultStream' RandStream.setDefaultStream(...) % 'rng' rng(...) % 'rand-state' rand('state') % 'urlread-timeout' urlread(..., 'Timeout', t) % 'griddata-vector-input' griddata(...,...,...,a,b) with a and b % vectors % 'griddata-v4' griddata(...,...,...,...,...,'v4'), % that is v4 interpolation support % 'uimenu' uimenu(...) if ~ischar(what) error('first argument must be a string'); end switch what case 'matlabversion' tf = is_matlab() && matlabversion(varargin{:}); case 'exists-in-private-directory' tf = is_matlab(); case 'which-all' tf = is_matlab(); case 'onCleanup' tf = is_octave() || matlabversion(7.8, Inf); case 'alim' tf = is_matlab(); case 'int32_logical_operations' % earlier version of Matlab don't support bitand (and similar) % operations on int32 tf = is_octave() || ~matlabversion(-inf, '2012a'); case 'graphics_objects' % introduced in Matlab 2014b, graphics is handled through objects; % previous versions use numeric handles tf = is_matlab() && matlabversion('2014b', Inf); case 'libmx_c_interface' % removed after 2013b tf = matlabversion(-Inf, '2013b'); case 'stats' root_dir=fileparts(which('ft_defaults')); external_stats_dir=fullfile(root_dir,'external','stats'); % these files are only used by other functions in the external/stats % directory exclude_mfiles={'common_size.m',... 'iscomplex.m',... 'lgamma.m'}; tf = has_all_functions_in_dir(external_stats_dir,exclude_mfiles); case 'program_invocation_name' % Octave supports program_invocation_name, which returns the path % of the binary that was run to start Octave tf = is_octave(); case 'singleCompThread' tf = is_matlab() && matlabversion(7.8, inf); case {'nosplash','nodisplay','nojvm'} % Only on Matlab tf = is_matlab(); case 'no-gui' % Only on Octave tf = is_octave(); case 'RandStream.setDefaultStream' tf = is_matlab() && matlabversion('2008b', '2011b'); case 'RandStream.setGlobalStream' tf = is_matlab() && matlabversion('2012a', inf); case 'randomized_PRNG_on_startup' tf = is_octave() || ~matlabversion(-Inf,'7.3'); case 'rng' % recent Matlab versions tf = is_matlab() && matlabversion('7.12',Inf); case 'rand-state' % GNU Octave tf = is_octave(); case 'urlread-timeout' tf = is_matlab() && matlabversion('2012b',Inf); case 'griddata-vector-input' tf = is_matlab(); case 'griddata-v4' tf = is_matlab() && matlabversion('2009a',Inf); case 'uimenu' tf = is_matlab(); otherwise error('unsupported value for first argument: %s', what); end % switch end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = is_matlab() tf = ~is_octave(); end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = is_octave() persistent cached_tf; if isempty(cached_tf) cached_tf = logical(exist('OCTAVE_VERSION', 'builtin')); end tf = cached_tf; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = has_all_functions_in_dir(in_dir, exclude_mfiles) % returns true if all functions in in_dir are already provided by the % platform m_files=dir(fullfile(in_dir,'*.m')); n=numel(m_files); for k=1:n m_filename=m_files(k).name; if isempty(which(m_filename)) && ... isempty(strmatch(m_filename,exclude_mfiles)) tf=false; return; end end tf=true; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [inInterval] = matlabversion(min, max) % MATLABVERSION checks if the current MATLAB version is within the interval % specified by min and max. % % Use, e.g., as: % if matlabversion(7.0, 7.9) % % do something % end % % Both strings and numbers, as well as infinities, are supported, eg.: % matlabversion(7.1, 7.9) % is version between 7.1 and 7.9? % matlabversion(6, '7.10') % is version between 6 and 7.10? (note: '7.10', not 7.10) % matlabversion(-Inf, 7.6) % is version <= 7.6? % matlabversion('2009b') % exactly 2009b % matlabversion('2008b', '2010a') % between two versions % matlabversion('2008b', Inf) % from a version onwards % etc. % % See also VERSION, VER, VERLESSTHAN % Copyright (C) 2006, Robert Oostenveld % Copyright (C) 2010, Eelke Spaak % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % this does not change over subsequent calls, making it persistent speeds it up persistent curVer if nargin<2 max = min; end if isempty(curVer) curVer = version(); end if ((ischar(min) && isempty(str2num(min))) || (ischar(max) && isempty(str2num(max)))) % perform comparison with respect to release string ind = strfind(curVer, '(R'); [year, ab] = parseMatlabRelease(curVer((ind + 2):(numel(curVer) - 1))); [minY, minAb] = parseMatlabRelease(min); [maxY, maxAb] = parseMatlabRelease(max); inInterval = orderedComparison(minY, minAb, maxY, maxAb, year, ab); else % perform comparison with respect to version number [major, minor] = parseMatlabVersion(curVer); [minMajor, minMinor] = parseMatlabVersion(min); [maxMajor, maxMinor] = parseMatlabVersion(max); inInterval = orderedComparison(minMajor, minMinor, maxMajor, maxMinor, major, minor); end end % function function [year, ab] = parseMatlabRelease(str) if (str == Inf) year = Inf; ab = Inf; elseif (str == -Inf) year = -Inf; ab = -Inf; else year = str2num(str(1:4)); ab = str(5); end end % function function [major, minor] = parseMatlabVersion(ver) if (ver == Inf) major = Inf; minor = Inf; elseif (ver == -Inf) major = -Inf; minor = -Inf; elseif (isnumeric(ver)) major = floor(ver); minor = int8((ver - floor(ver)) * 10); else % ver is string (e.g. '7.10'), parse accordingly [major, rest] = strtok(ver, '.'); major = str2num(major); minor = str2num(strtok(rest, '.')); end end % function % checks if testA is in interval (lowerA,upperA); if at edges, checks if testB is in interval (lowerB,upperB). function inInterval = orderedComparison(lowerA, lowerB, upperA, upperB, testA, testB) if (testA < lowerA || testA > upperA) inInterval = false; else inInterval = true; if (testA == lowerA) inInterval = inInterval && (testB >= lowerB); end if (testA == upperA) inInterval = inInterval && (testB <= upperB); end end end % function
github
lcnbeapp/beapp-master
getdimsiz.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/private/getdimsiz.m
2,235
utf_8
340d495a654f2f6752aa1af7ac915390
function dimsiz = getdimsiz(data, field) % GETDIMSIZ % % Use as % dimsiz = getdimsiz(data, field) % % If the length of the vector that is returned is smaller than the % number of dimensions that you would expect from GETDIMORD, you % should assume that it has trailing singleton dimensions. % % Example use % dimord = getdimord(datastructure, fieldname); % dimtok = tokenize(dimord, '_'); % dimsiz = getdimsiz(datastructure, fieldname); % dimsiz(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions % % See also GETDIMORD, GETDATFIELD if ~isfield(data, field) && isfield(data, 'avg') && isfield(data.avg, field) field = ['avg.' field]; elseif ~isfield(data, field) && isfield(data, 'trial') && isfield(data.trial, field) field = ['trial.' field]; elseif ~isfield(data, field) error('field "%s" not present in data', field); end if strncmp(field, 'avg.', 4) prefix = []; field = field(5:end); % strip the avg data.(field) = data.avg.(field); % move the avg into the main structure data = rmfield(data, 'avg'); elseif strncmp(field, 'trial.', 6) prefix = numel(data.trial); field = field(7:end); % strip the trial data.(field) = data.trial(1).(field); % move the first trial into the main structure data = rmfield(data, 'trial'); else prefix = []; end dimsiz = cellmatsize(data.(field)); % add nrpt in case of source.trial dimsiz = [prefix dimsiz]; end % main function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to determine the size of data representations like {pos}_ori_time % FIXME this will fail for {xxx_yyy}_zzz %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function siz = cellmatsize(x) if iscell(x) if isempty(x) siz = 0; return % nothing else to do elseif isvector(x) cellsize = numel(x); % the number of elements in the cell-array else cellsize = size(x); x = x(:); % convert to vector for further size detection end [dum, indx] = max(cellfun(@numel, x)); matsize = size(x{indx}); % the size of the content of the cell-array siz = [cellsize matsize]; % concatenate the two else siz = size(x); end end % function cellmatsize
github
lcnbeapp/beapp-master
project_elec.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/utilities/private/project_elec.m
3,791
utf_8
61bc3f095e4ced1311048c06823bb037
function [el, prj] = project_elec(elc, pnt, tri) % PROJECT_ELEC projects electrodes on a triangulated surface % and returns triangle index, la/mu parameters and distance % % Use as % [el, prj] = project_elec(elc, pnt, tri) % which returns % el = Nx4 matrix with [tri, la, mu, dist] for each electrode % prj = Nx3 matrix with the projected electrode position % % See also TRANSFER_ELEC % Copyright (C) 1999-2013, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ Nelc = size(elc,1); el = zeros(Nelc, 4); % this is a work-around for http://bugzilla.fcdonders.nl/show_bug.cgi?id=2369 elc = double(elc); pnt = double(pnt); tri = double(tri); for i=1:Nelc [proj,dist] = ptriprojn(pnt(tri(:,1),:), pnt(tri(:,2),:), pnt(tri(:,3),:), elc(i,:), 1); [mindist, minindx] = min(abs(dist)); [la, mu] = lmoutr(pnt(tri(minindx,1),:), pnt(tri(minindx,2),:), pnt(tri(minindx,3),:), proj(minindx,:)); smallest_dist = dist(minindx); smallest_tri = minindx; smallest_la = la; smallest_mu = mu; % the following can be done faster, because the smallest_dist can be % directly selected % Ntri = size(tri,1); % for j=1:Ntri % %[proj, dist] = ptriproj(pnt(tri(j,1),:), pnt(tri(j,2),:), pnt(tri(j,3),:), elc(i,:), 1); % if dist(j)<smallest_dist % % remember the triangle index, distance and la/mu % [la, mu] = lmoutr(pnt(tri(j,1),:), pnt(tri(j,2),:), pnt(tri(j,3),:), proj(j,:)); % smallest_dist = dist(j); % smallest_tri = j; % smallest_la = la; % smallest_mu = mu; % end % end % store the projection for this electrode el(i,:) = [smallest_tri smallest_la smallest_mu smallest_dist]; end if nargout>1 prj = zeros(size(elc)); for i=1:Nelc v1 = pnt(tri(el(i,1),1),:); v2 = pnt(tri(el(i,1),2),:); v3 = pnt(tri(el(i,1),3),:); la = el(i,2); mu = el(i,3); prj(i,:) = routlm(v1, v2, v3, la, mu); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION this is an alternative implementation that will also work for % polygons %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function prj = polyproj(elc,pnt) % projects a point on a plane, e.g. an electrode on a polygon % pnt is a Nx3 matrix with multiple vertices that span the plane % these vertices can be slightly off the plane center = mean(pnt,1); % shift the vertices to have zero mean pnt(:,1) = pnt(:,1) - center(1); pnt(:,2) = pnt(:,2) - center(2); pnt(:,3) = pnt(:,3) - center(3); elc(:,1) = elc(:,1) - center(1); elc(:,2) = elc(:,2) - center(2); elc(:,3) = elc(:,3) - center(3); pnt = pnt'; elc = elc'; [u, s, v] = svd(pnt); % The vertices are assumed to ly in plane, at least reasonably. That means % that from the three eigenvectors there is one which is very small, i.e. % the one orthogonal to the plane. Project the electrodes along that % direction. u(:,3) = 0; prj = u * u' * elc; prj = prj'; prj(:,1) = prj(:,1) + center(1); prj(:,2) = prj(:,2) + center(2); prj(:,3) = prj(:,3) + center(3);
github
lcnbeapp/beapp-master
peerslave.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/peer/peerslave.m
8,422
utf_8
196853955545e0384a80090dff57d1e1
function peerslave(varargin) % PEERSLAVE starts the low-level peer services and switches to slave mode. % Subsequently it will wait untill a job comes in and execute it. % % Use as % peerslave(...) % % Optional input arguments should be passed as key-value pairs. The % following options are available to limit the peer network, i.e. to % form sub-networks. % group = string % allowuser = {...} % allowgroup = {...} % allowhost = {...} % refuseuser = {...} % refusegroup = {...} % refusehost = {...} % The allow options will prevent peers that do not match the requirements % to be added to the (dynamic) list of known peers. Consequently, these % options limit which peers know each other. A master will not send jobs % to peers that it does not know. A slave will not accept jobs from a peer % that it does not know. % % The following options are available to limit the number and duration % of the jobs that the slave will execute. % maxnum = number (default = inf) % maxtime = number (default = inf) % maxidle = number (default = inf) % % The following options are available to limit the available resources % that available for job execution. % memavail = number, amount of memory available (default = inf) % cpuavail = number, speed of the CPU (default = inf) % timavail = number, maximum duration of a single job (default = inf) % % See also PEERMASTER, PEERRESET, PEERFEVAL, PEERCELLFUN % Undocumented options % sleep = number in seconds (default = 0.01) % threads = number, maximum number of threads to use (default = automatic) % ----------------------------------------------------------------------- % Copyright (C) 2010, Robert Oostenveld % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <http://www.gnu.org/licenses/ % % $Id$ % ----------------------------------------------------------------------- if ft_platform_supports('onCleanup') % switch to zombie when finished or when ctrl-c gets pressed % the onCleanup function does not exist for older versions onCleanup(@peerzombie); end % get the optional input arguments maxnum = ft_getopt(varargin, 'maxnum', inf); maxtime = ft_getopt(varargin, 'maxtime', inf); maxidle = ft_getopt(varargin, 'maxidle', inf); sleep = ft_getopt(varargin, 'sleep', 0.01); memavail = ft_getopt(varargin, 'memavail'); cpuavail = ft_getopt(varargin, 'cpuavail'); timavail = ft_getopt(varargin, 'timavail'); threads = ft_getopt(varargin, 'threads'); group = ft_getopt(varargin, 'group'); allowuser = ft_getopt(varargin, 'allowuser', {}); allowgroup = ft_getopt(varargin, 'allowgroup', {}); allowhost = ft_getopt(varargin, 'allowhost', {}); refuseuser = ft_getopt(varargin, 'refuseuser', {}); refusegroup = ft_getopt(varargin, 'refusegroup', {}); refusehost = ft_getopt(varargin, 'refusehost', {}); if ~isempty(threads) && exist('maxNumCompThreads', 'file') % this function is only available from MATLAB version 7.5 (R2007b) upward % and has become deprecated in MATLAB version 7.9 (R2009b) ws = warning('off', 'MATLAB:maxNumCompThreads:Deprecated'); maxNumCompThreads(threads); warning(ws); end % these should be cell arrays if ~iscell(allowuser) && ischar(allowuser) allowuser = {allowuser}; end if ~iscell(allowgroup) && ischar(allowgroup) allowgroup = {allowgroup}; end if ~iscell(allowhost) && ischar(allowhost) allowhost = {allowhost}; end if ~iscell(refuseuser) && ischar(refuseuser) refuseuser = {refuseuser}; end if ~iscell(refusegroup) && ischar(refusegroup) refusegroup = {refusegroup}; end if ~iscell(refusehost) && ischar(refusehost) refusehost = {refusehost}; end % this should not be user-configurable % if ~isempty(user) % peer('user', user); % end % this should not be user-configurable % if ~isempty(hostname) % peer('hostname', hostname); % end % the group can be specified by the user if ~isempty(group) peer('group', group); end % switch to idle slave mode peer('status', 2); % check the current access restrictions info = peerinfo; access = true; access = access && isequal(info.allowhost, allowhost); access = access && isequal(info.allowuser, allowuser); access = access && isequal(info.allowgroup, allowgroup); access = access && isequal(info.refusehost, refusehost); access = access && isequal(info.refuseuser, refuseuser); access = access && isequal(info.refusegroup, refusegroup); if ~access % impose the updated access restrictions peer('allowhost', allowhost); peer('allowuser', allowuser); peer('allowgroup', allowgroup); peer('refusehost', refusehost); peer('refuseuser', refuseuser); peer('refusegroup', refusegroup); end % check the current status of the maintenance threads threads = true; threads = threads && peer('announce', 'status'); threads = threads && peer('discover', 'status'); threads = threads && peer('expire', 'status'); threads = threads && peer('tcpserver', 'status'); % threads = threads && peer('udsserver', 'status'); if ~threads % start the maintenance threads ws = warning('off'); peer('announce', 'start'); peer('discover', 'start'); peer('expire', 'start'); peer('tcpserver', 'start'); % peer('udsserver', 'start'); warning(ws); end % the available resources will be announced and are used to drop requests that are too large if ~isempty(memavail), peer('memavail', memavail); end if ~isempty(cpuavail), peer('cpuavail', cpuavail); end if ~isempty(timavail), peer('timavail', timavail); end % keep track of the time and number of jobs stopwatch = tic; prevtime = toc(stopwatch); idlestart = toc(stopwatch); jobnum = 0; while true if (toc(stopwatch)-idlestart) >= maxidle fprintf('maxidle exceeded, stopping as slave\n'); break; end if toc(stopwatch)>=maxtime fprintf('maxtime exceeded, stopping as slave\n'); break; end if jobnum>=maxnum fprintf('maxnum exceeded, stopping as slave\n'); break; end joblist = peer('joblist'); if isempty(joblist) % wait a little bit and try again pause(sleep); % display the time every second currtime = toc(stopwatch); if (currtime-prevtime>=10) prevtime = currtime; disp(datestr(now)); end else % set the status to "busy slave" peer('status', 3); % increment the job counter jobnum = jobnum + 1; % reset the error and warning messages lasterr(''); lastwarn(''); % get the last job from the list, which will be the oldest joblist = joblist(end); fprintf('executing job %d from %s@%s (jobid=%d, memreq=%d, timreq=%d)\n', jobnum, joblist.user, joblist.hostname, joblist.jobid, joblist.memreq, joblist.timreq); % get the input arguments and options [argin, options] = peer('get', joblist.jobid); % set the options that will be used in the watchdog % options = {options{:}, 'masterid', joblist.hostid}; % add the masterid as option % options = {options{:}, 'timavail', 2*(timavail+1)}; % add the timavail as option, empty is ok % evaluate the job [argout, options] = peerexec(argin, options); % write the results back to the master try peer('put', joblist.hostid, argout, options, 'jobid', joblist.jobid); catch warning('failed to return job results to the master'); end % remove the job from the tcpserver peer('clear', joblist.jobid); % remember when the slave becomes idle idlestart = toc(stopwatch); % set the status to "idle slave" peer('status', 2); end % isempty(joblist) end % while true %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION this masks the regular version, this one only updates the status %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function peerzombie peer('status', 0);
github
lcnbeapp/beapp-master
peercellfun.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/peer/peercellfun.m
24,302
utf_8
3754d5d1bf8da977815e1ebf1080f286
function varargout = peercellfun(fname, varargin) % PEERCELLFUN applies a function to each element of a cell-array. The % function execution is done in parallel on all avaialble peers. % % Use as % argout = peercellfun(fname, x1, x2, ...) % % This function has a number of optional arguments that have to passed % as key-value pairs at the end of the list of input arguments. All other % input arguments (including other key-value pairs) will be passed to the % function to be evaluated. % UniformOutput = boolean (default = false) % StopOnError = boolean (default = true) % RetryOnError = number, number of retries for failed jobs expressed as ratio (default = 0.05) % MaxBusy = number, amount of slaves allowed to be busy (default = inf) % diary = string, can be 'always', 'never', 'warning', 'error' (default = 'error') % timreq = number, initial estimate for the time required to run a single job (default = 3600) % mintimreq = number, minimum time required to run a single job (default is automatic) % memreq = number, initial estimate for the memory required to run a single job (default = 2*1024^3) % minmemreq = number, minimum memory required to run a single job (default is automatic) % order = string, can be 'random' or 'original' (default = 'random') % % Example % fname = 'power'; % x1 = {1, 2, 3, 4, 5}; % x2 = {2, 2, 2, 2, 2}; % y = peercellfun(fname, x1, x2); % % See also PEERMASTER, PEERSLAVE, PEERLIST, PEERINFO, PEERFEVAL, CELLFUN, DFEVAL % ----------------------------------------------------------------------- % Copyright (C) 2010, Robert Oostenveld % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <http://www.gnu.org/licenses/ % % $Id$ % ----------------------------------------------------------------------- if ft_platform_supports('onCleanup') % switch to zombie when finished or when ctrl-c gets pressed % the onCleanup function does not exist for older versions onCleanup(@peerzombie); end % locate the begin of the optional key-value arguments optbeg = find(cellfun(@ischar, varargin)); optarg = varargin(optbeg:end); % get the optional input arguments UniformOutput = ft_getopt(optarg, 'UniformOutput', false ); StopOnError = ft_getopt(optarg, 'StopOnError', true ); MaxBusy = ft_getopt(optarg, 'MaxBusy', inf ); RetryOnError = ft_getopt(optarg, 'RetryOnError', 0.050 ); % ratio, fraction of the total jobs sleep = ft_getopt(optarg, 'sleep', 0.050 ); % time in seconds diary = ft_getopt(optarg, 'diary', 'error' ); % 'always', 'never', 'warning', 'error' order = ft_getopt(optarg, 'order', 'random'); % 'random', 'original' timreq = ft_getopt(optarg, 'timreq', [] ); mintimreq = ft_getopt(optarg, 'mintimreq', [] ); memreq = ft_getopt(optarg, 'memreq', [] ); % see below minmemreq = ft_getopt(optarg, 'minmemreq', [] ); % see below if isempty(timreq) && isempty(mintimreq) % assume an initial job duration of 1 hour % the time required by the jobs will be estimated and timreq will be auto-adjusted timreq = 3600; mintimreq = 0; elseif isempty(timreq) % use the specified mimimum as the initial value that a job required % it will be auto-adjusted to larger values, not to smaller values timreq = mintimreq; elseif isempty(mintimreq) % jobs will be killed by the slave if they take more than 3 times the estimated time at submission % use the user-supplied initial value, the minimum should not be less than 1/3 of that mintimreq = timreq/3; end if isempty(memreq) && isempty(minmemreq) % assume an initial memory requirement of 1 GB % the memory required by the jobs will be estimated and memreq will be auto-adjusted memreq = 2*1024^3; minmemreq = 0; elseif isempty(memreq) % use the specified mimimum as the initial value that a job required % it will be auto-adjusted to larger values, not to smaller values memreq = minmemreq; elseif isempty(minmemreq) % jobs will be killed by the slave if they take more than 1.5 times the estimated time at submission % use the user-supplied initial value, the minimum should not be less than 1/1.5 times that minmemreq = memreq/1.5; end % convert from 'yes'/'no' into boolean value UniformOutput = istrue(UniformOutput); % convert from a fraction into an integer number RetryOnError = floor(RetryOnError * numel(varargin{1})); % skip the optional key-value arguments if ~isempty(optbeg) varargin = varargin(1:(optbeg-1)); end if isa(fname, 'function_handle') % convert the function handle back into a string (e.g. @plus should be 'plus') fname = func2str(fname); end % there are potentially errors to catch from the which() function if isempty(which(fname)) error('Not a valid M-file (%s).', fname); end % determine the number of input arguments and the number of jobs numargin = numel(varargin); numjob = numel(varargin{1}); % it can be difficult to determine the number of output arguments try numargout = nargout(fname); catch % the "catch me" syntax is broken on MATLAB74, this fixes it nargout_err = lasterror; if strcmp(nargout_err.identifier, 'MATLAB:narginout:doesNotApply') % e.g. in case of nargin('plus') numargout = 1; else rethrow(nargout_err); end end if numargout<0 % the nargout function returns -1 in case of a variable number of output arguments numargout = 1; elseif numargout>nargout % the number of output arguments is constrained by the users' call to this function numargout = nargout; elseif nargout>numargout error('Too many output arguments.'); end % check the input arguments for i=1:numargin if ~isa(varargin{i}, 'cell') error('input argument #%d should be a cell-array', i+1); end if numel(varargin{i})~=numjob error('inconsistent number of elements in input #%d', i+1); end end % check the availability of peer slaves list = peerlist; list = list([list.status]==2 | [list.status]==3); if isempty(list) warning('there is no peer available as slave, reverting to local cellfun'); % prepare the output arguments varargout = cell(1,numargout); % use the standard cellfun [varargout{:}] = cellfun(str2func(fname), varargin{:}, 'UniformOutput', UniformOutput); return end % prepare some arrays that are used for bookkeeping jobid = nan(1, numjob); puttime = nan(1, numjob); timused = nan(1, numjob); memused = nan(1, numjob); submitted = false(1, numjob); collected = false(1, numjob); busy = false(1, numjob); lastseen = inf(1, numjob); submittime = inf(1, numjob); collecttime = inf(1, numjob); resubmitted = []; % this will contain a growing list with structures % remove any remains from an aborted previous call joblist = peer('joblist'); for i=1:length(joblist) peer('clear', joblist(i).jobid); end % start the timer stopwatch = tic; % these are used for printing feedback on screen prevnumsubmitted = 0; prevnumcollected = 0; prevnumbusy = 0; prevtimreq = timreq; prevmemreq = memreq; if any(collected) % update the estimate of the time and memory that will be needed for the next job % note that it cannot be updated if all collected jobs have failed (in case of stoponerror=false) if ~isempty(nanmax(timused)) timreq = nanmax(timused); timreq = max(timreq, mintimreq); memreq = nanmax(memused); memreq = max(memreq, minmemreq); end end if any(submitted) && any(busy) % update based on the time already spent on the slowest job elapsed = toc(stopwatch) - min(submittime(submitted & busy)); timreq = max(timreq, elapsed); timreq = max(timreq, mintimreq); end % determine the initial job order, small numbers are submitted first if strcmp(order, 'random') priority = randperm(numjob); elseif strcmp(order, 'original') priority = 1:numjob; else error('unsupported order'); end % post all jobs and gather their results while ~all(submitted) || ~all(collected) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % PART 1: submit the jobs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % select all jobs that still need to be submitted submit = find(~submitted); if ~isempty(submit) && (sum(submitted)-sum(collected))<MaxBusy % determine the job to submit, the one with the smallest priority number goes first [dum, sel] = min(priority(submit)); submit = submit(sel(1)); % redistribute the input arguments argin = cell(1, numargin); for j=1:numargin argin{j} = varargin{j}{submit}; end % submit the job for execution ws = warning('off', 'FieldTrip:peer:noSlaveAvailable'); % peerfeval will give a warning if the submission timed out [curjobid curputtime] = peerfeval(fname, argin{:}, 'timeout', 5, 'memreq', memreq, 'timreq', timreq, 'diary', diary, 'nargout', numargout); warning(ws); if ~isempty(curjobid) % fprintf('submitted job %d\n', submit); jobid(submit) = curjobid; puttime(submit) = curputtime; submitted(submit) = true; submittime(submit) = toc(stopwatch); clear curjobid curputtime % give some feedback if abs(memreq-prevmemreq)>1000 fprintf('updating memreq to %s\n', print_mem(memreq)); end % give some feedback if abs(timreq-prevtimreq)>1 fprintf('updating timreq to %s\n', print_tim(timreq)); end end clear argin end % if ~isempty(submitlist) % get the list of jobs that are busy busylist = peerlist('busy'); busy(:) = false; if ~isempty(busylist) current = [busylist.current]; [dum, sel] = intersect(jobid, [current.jobid]); busy(sel) = true; % this indicates that the job execution is currently busy lastseen(sel) = toc(stopwatch); % keep track of when the job was seen the last time end if sum(collected)>prevnumcollected || sum(busy)~=prevnumbusy % give an update of the progress fprintf('submitted %d/%d, collected %d/%d, busy %d, speedup %.1f\n', sum(submitted), numel(submitted), sum(collected), numel(collected), sum(busy), nansum(timused(collected))/toc(stopwatch)); end prevnumsubmitted = sum(submitted); prevnumcollected = sum(collected); prevnumbusy = sum(busy); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % PART 2: collect the job results that have finished sofar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % get the list of job results joblist = peer('joblist'); % get the output of all jobs that have finished for i=1:numel(joblist) % figure out to which job these results belong collect = find(jobid == joblist(i).jobid); if isempty(collect) && ~isempty(resubmitted) % it might be that these results are from a previously resubmitted job collect = [resubmitted([resubmitted.jobid] == joblist(i).jobid).jobnum]; if ~isempty(collect) && ~collected(collect) % forget the resubmitted job, take these results instead warning('the original job %d did return, reverting to its original results', collect); end end if isempty(collect) % this job is not interesting to collect, probably it reflects some junk % from a previous call or a failed resubmission peer('clear', joblist(i).jobid); continue; end if collected(collect) % this job is the result of a resubmission, where the original result did return peer('clear', joblist(i).jobid); continue; end % collect the output arguments try ws = warning('Off','Backtrace'); [argout, options] = peerget(joblist(i).jobid, 'timeout', inf, 'output', 'cell', 'diary', diary, 'StopOnError', StopOnError); warning(ws); catch % the "catch me" syntax is broken on MATLAB74, this fixes it peerget_err = lasterror; % the peerslave command line executable itself can return a number of errors % 1) could not start the MATLAB engine % 2) failed to execute the job (argin) % 3) failed to execute the job (optin) % 4) failed to execute the job (eval) % 5) failed to execute the job (argout) % 6) failed to execute the job (optout) % 7) failed to execute the job % errors 1-3 are not the users fault and happen prior to execution, therefore they should always result in a resubmission if ~isempty(strfind(peerget_err.message, 'could not start the MATLAB engine')) || ... ~isempty(strfind(peerget_err.message, 'failed to execute the job (argin)')) || ... ~isempty(strfind(peerget_err.message, 'failed to execute the job (optin)')) % this is due to a license problem or a memory problem if ~isempty(strfind(peerget_err.message, 'could not start the MATLAB engine')) warning('resubmitting job %d because the MATLAB engine could not get a license', collect); end % reset all job information, this will cause it to be automatically resubmitted jobid (collect) = nan; puttime (collect) = nan; timused (collect) = nan; memused (collect) = nan; submitted (collect) = false; collected (collect) = false; busy (collect) = false; lastseen (collect) = inf; submittime (collect) = inf; collecttime(collect) = inf; continue else % the returned error is more serious and requires the users attention if RetryOnError>0 % dercease the counter for the remaining retries RetryOnError = RetryOnError - 1; % give the user some information fprintf('an error was detected during the execution of job %d\n', collect); fprintf('??? %s\n', peerget_err.message); fprintf('resubmitting the failed job (%d retries remaining)\n', RetryOnError); % reset all job information, this will cause it to be automatically resubmitted jobid (collect) = nan; puttime (collect) = nan; timused (collect) = nan; memused (collect) = nan; submitted (collect) = false; collected (collect) = false; busy (collect) = false; lastseen (collect) = inf; submittime (collect) = inf; collecttime(collect) = inf; continue else fprintf('an error was detected during the execution of job %d\n', collect); rethrow(peerget_err); end end end % fprintf('collected job %d\n', collect); collected(collect) = true; collecttime(collect) = toc(stopwatch); % redistribute the output arguments for j=1:numargout varargout{j}{collect} = argout{j}; end % gather the job statistics % these are empty in case an error happened during remote evaluation, therefore the default value of NaN is specified timused(collect) = ft_getopt(options, 'timused', nan); memused(collect) = ft_getopt(options, 'memused', nan); end % for joblist prevtimreq = timreq; prevmemreq = memreq; if any(collected) % update the estimate of the time and memory that will be needed for the next job % note that it cannot be updated if all collected jobs have failed (in case of stoponerror=false) if ~isempty(nanmax(timused)) timreq = nanmax(timused); timreq = max(timreq, mintimreq); memreq = nanmax(memused); memreq = max(memreq, minmemreq); end end if any(submitted) && any(busy) % update based on the time already spent on the slowest job elapsed = toc(stopwatch) - min(submittime(submitted & busy)); timreq = max(timreq, elapsed); timreq = max(timreq, mintimreq); end % get the list of jobs that are busy busylist = peerlist('busy'); busy(:) = false; if ~isempty(busylist) current = [busylist.current]; [dum, sel] = intersect(jobid, [current.jobid]); busy(sel) = true; % this indicates that the job execution is currently busy lastseen(sel) = toc(stopwatch); % keep track of when the job was seen the last time end if sum(collected)>prevnumcollected || sum(busy)~=prevnumbusy % give an update of the progress fprintf('submitted %d/%d, collected %d/%d, busy %d, speedup %.1f\n', sum(submitted), numel(submitted), sum(collected), numel(collected), sum(busy), nansum(timused(collected))/toc(stopwatch)); end prevnumsubmitted = sum(submitted); prevnumcollected = sum(collected); prevnumbusy = sum(busy); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % PART 3: flag jobs that take too long for resubmission %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this is only a warning, no action is taken here % sel = find((toc(stopwatch)-lastseen)>60); % for i=1:length(sel) % warning('job %d has not been seen for 60 seconds\n', sel(i)); % end % search for jobs that were submitted but that are still not busy after 60 seconds % this happens if the peerslave is not able to get a MATLAB license elapsed = toc(stopwatch) - submittime; elapsed(~submitted) = 0; elapsed(collected) = 0; elapsed(~isinf(lastseen)) = 0; % once started there is no reason to resubmit "because it takes too long to get started" sel = find(elapsed>60); for i=1:length(sel) warning('resubmitting job %d because it takes too long to get started', sel(i)); % remember the job that will be resubmitted, it still might return its results resubmitted(end+1).jobnum = sel(i); resubmitted(end ).jobid = jobid(sel(i)); resubmitted(end ).time = toc(stopwatch); resubmitted(end ).reason = 'startup'; % reset all job information, this will cause it to be automatically resubmitted jobid (sel(i)) = nan; puttime (sel(i)) = nan; timused (sel(i)) = nan; memused (sel(i)) = nan; submitted (sel(i)) = false; collected (sel(i)) = false; busy (sel(i)) = false; lastseen (sel(i)) = inf; submittime (sel(i)) = inf; collecttime(sel(i)) = inf; % increase the priority number, the resubmission should as late as possible % to increase the chance of the original job returning its results priority(sel(i)) = max(priority)+1; end % search for jobs that take too long to return their results % use an estimate of the time it requires a job to complete % assume that it will not take more than 3x the required time % this is also what is used by the peerslave to kill the job estimated = 3*timreq; % add some time to allow the MATLAB engine to start estimated = estimated + 60; % test whether one of the submitted jobs should be resubmitted elapsed = toc(stopwatch) - submittime; sel = find(submitted & ~collected & (elapsed>estimated)); for i=1:length(sel) warning('resubmitting job %d because it takes too long to finish (estimated = %s)', sel(i), print_tim(estimated)); % remember the job that will be resubmitted, it still might return its results resubmitted(end+1).jobnum = sel(i); resubmitted(end ).jobid = jobid(sel(i)); resubmitted(end ).time = toc(stopwatch); resubmitted(end ).reason = 'duration'; % reset all job information, this will cause it to be automatically resubmitted jobid (sel(i)) = nan; puttime (sel(i)) = nan; timused (sel(i)) = nan; memused (sel(i)) = nan; submitted (sel(i)) = false; collected (sel(i)) = false; busy (sel(i)) = false; lastseen (sel(i)) = inf; submittime (sel(i)) = inf; collecttime(sel(i)) = inf; % increase the priority number, the resubmission should as late as possible % to increase the chance of the original job returning its results priority(sel(i)) = max(priority)+1; end if all(submitted) % wait a little bit, then try again to submit or collect a job pause(sleep); end % get the list of jobs that are busy busylist = peerlist('busy'); busy(:) = false; if ~isempty(busylist) current = [busylist.current]; [dum, sel] = intersect(jobid, [current.jobid]); busy(sel) = true; % this indicates that the job execution is currently busy lastseen(sel) = toc(stopwatch); % keep track of when the job was seen the last time end if sum(collected)>prevnumcollected || sum(busy)~=prevnumbusy % give an update of the progress fprintf('submitted %d/%d, collected %d/%d, busy %d, speedup %.1f\n', sum(submitted), numel(submitted), sum(collected), numel(collected), sum(busy), nansum(timused(collected))/toc(stopwatch)); end prevnumsubmitted = sum(submitted); prevnumcollected = sum(collected); prevnumbusy = sum(busy); end % while not all jobs have finished if numargout>0 && UniformOutput % check whether the output can be converted to a uniform one for i=1:numel(varargout) for j=1:numel(varargout{i}) if numel(varargout{i}{j})~=1 % this error message is consistent with the one from cellfun error('Non-scalar in Uniform output, at index %d, output %d. Set ''UniformOutput'' to false.', j, i); end end end % convert the output to a uniform one for i=1:numargout varargout{i} = [varargout{i}{:}]; end end % ensure the output to have the same size/dimensions as the input for i=1:numargout varargout{i} = reshape(varargout{i}, size(varargin{1})); end % compare the time used inside this function with the total execution time fprintf('computational time = %.1f sec, elapsed = %.1f sec, speedup %.1f x (memreq = %s, timreq = %s)\n', nansum(timused), toc(stopwatch), nansum(timused)/toc(stopwatch), print_mem(memreq), print_tim(timreq)); if all(puttime>timused) % FIXME this could be detected in the loop above, and the strategy could automatically % be adjusted from using the peers to local execution warning('copying the jobs over the network took more time than their execution'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION this masks the regular version, this one only updates the status %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function peerzombie peer('status', 0); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = nanmax(x) y = max(x(~isnan(x(:)))); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = nanmin(x) y = min(x(~isnan(x(:)))); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = nanmean(x) x = x(~isnan(x(:))); y = mean(x); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = nanstd(x) x = x(~isnan(x(:))); y = std(x); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = nansum(x) x = x(~isnan(x(:))); y = sum(x);
github
lcnbeapp/beapp-master
print_mem.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/peer/private/print_mem.m
432
utf_8
2aec5a412cc63c6c38e768ddba2bf30c
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for pretty-printing %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str = print_mem(val) if val<1024 str = sprintf('%d bytes', val); elseif val<1024^2 str = sprintf('%.1f KB', val/1024); elseif val<1024^3 str = sprintf('%.1f MB', val/1024^2); else str = sprintf('%.1f GB', val/1024^3); end