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
|
lcnhappe/happe-master
|
std_uniformfiles.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_uniformfiles.m
| 3,122 |
utf_8
|
4338ced427d77d85832ff2965d6735b9
|
% std_uniformfiles() - Check uniform channel distribution accross data files
%
% Usage:
% >> boolval = std_uniformfiles(STUDY, ALLEEG);
%
% Inputs:
% STUDY - EEGLAB STUDY
%
% Outputs:
% boolval - [-1|0|1] 0 if non uniform, 1 if uniform, -1 if error
%
% Authors: Arnaud Delorme, SCCN/UCSD, CERCO/CNRS, 2010-
% Copyright (C) Arnaud Delorme
%
% 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 uniformlabels = std_uniformfiles( STUDY, ALLEEG );
if nargin < 2
help std_checkconsist;
return;
end;
filetypes = { 'daterp' 'datspec' 'datersp' 'datitc' 'dattimef' };
% set channel interpolation mode
% ------------------------------
uniformlabels = [];
count = 1;
selectedtypes = {};
for index = 1:length(filetypes)
% scan datasets
% -------------
[ tmpstruct compinds filepresent ] = std_fileinfo(ALLEEG, filetypes{index});
% check if the structures are equal
% ---------------------------------
if ~isempty(tmpstruct)
if any(filepresent == 0)
uniformlabels = -1;
return;
else
firstval = tmpstruct(1).labels;
uniformlabels(count) = length(firstval);
for dat = 2:length(tmpstruct)
tmpval = tmpstruct(dat).labels;
if ~isequal(firstval, tmpval)
uniformlabels(count) = 0;
end;
end;
selectedtypes{count} = filetypes{index};
count = count+1;
end;
end;
end;
% check output
% ------------
if any(uniformlabels == 0)
if any(uniformlabels) == 1
disp('Warning: conflict between datafiles - all should have the same channel distribution');
for index = 1:length(selectedtypes)
if uniformlabels(index)
fprintf(' Data files with extention "%s" have interpolated channels\n', selectedtypes{index});
else fprintf(' Data files with extention "%s" have non-interpolated channels\n', selectedtypes{index});
end;
end;
uniformlabels = -1;
else
uniformlabels = 0;
end;
else
if ~(length(unique(uniformlabels)) == 1)
fprintf('Warning: Data files have different number of channel in each file\n');
for index = 1:length(selectedtypes)
fprintf(' Data files with extention "%s" have %d channels\n', selectedtypes{index}, uniformlabels(index));
end;
end;
uniformlabels = 1;
end;
|
github
|
lcnhappe/happe-master
|
iseeglabdeployed.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/iseeglabdeployed.m
| 154 |
utf_8
|
cb8716ae372b37132bb2a58c54d09cd0
|
% iseeglabdeployed - true for EEGLAB compile version and false otherwise
function val = iseeglabdeployed
try
val = isdeployed;
catch
val = 0;
end
|
github
|
lcnhappe/happe-master
|
eeg_getversion.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/eeg_getversion.m
| 1,551 |
utf_8
|
a6ee3614031195b8aaf40cfab1251520
|
% eeg_getversion() - obtain EEGLAB version number
%
% Usage:
% >> vers = eeg_getversion;
% >> [vers vnum] = eeg_getversion;
%
% Outputs:
% vers = [string] EEGLAB version number
% vnum = [float] numerical value for the version. For example 11.3.2.4b
% is converted to 11.324
%
% Authors: Arnaud Delorme, SCCN/INC/UCSD, 2010
% Copyright (C) 2010 Arnaud Delorme, SCCN/INC/UCSD
%
% 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
function [vers, versnum, releaseDate] = eeg_getversion;
vers = '';
filepath = fileparts(which('eeglab.m'));
filename = dir(fullfile(filepath, 'Contents.m'));
releaseDate = filename.date;
if isempty(filename), return; end;
fid = fopen(fullfile(filepath, filename.name), 'r');
fgetl(fid);
versionline = fgetl(fid);
vers = versionline(11:end);
fclose(fid);
tmpvers = vers;
if isempty(str2num(tmpvers(end))), tmpvers(end) = []; end;
indsDot = find(tmpvers == '.' );
tmpvers(indsDot(2:end)) = [];
versnum = str2num(tmpvers);
|
github
|
lcnhappe/happe-master
|
gethelpvar.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/gethelpvar.m
| 9,432 |
utf_8
|
7d60bb94c02933e99c9a469f683938dc
|
% gethelpvar() - convert a Matlab m-file help-message header
% into out variables
% Usage:
% >> [vartext, varnames] = gethelpvar( filein, varlist);
%
% Inputs:
% filein - input filename (with .m extension)
% varlist - optional list of variable to return. If absent
% retrun all variables.
%
% Outputs:
% vartext - variable text
% varnames - name of the varialbe returned;
%
% Notes: see help2html() for file format
%
% Example: >> gethelpvar( 'gethelpvar.m', 'filein')
%
% Author: Arnaud Delorme, Salk Institute 20 April 2002
%
% See also: help2html()
% 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 [alltext, allvars] = gethelpvar( filename, varlist )
if nargin < 1
help gethelpvar;
return;
end;
% input file
% ----------
fid = fopen( filename, 'r');
if fid == -1
error('File not found');
end;
cont = 1;
% scan file
% -----------
str = fgets( fid );
% if first line is the name of the function, reload
if str(1) ~= '%', str = fgets( fid ); end;
% state variables
% -----------
maindescription = 1;
varname = [];
oldvarname = [];
vartext = [];
newvar = 0;
allvars = {};
alltext = {};
indexout = 1;
while (str(1) == '%')
str = deblank(str(2:end-1));
% --- DECODING INPUT
newvar = 0;
str = deblank2(str);
if ~isempty(str)
% find a title
% ------------
i2d = findstr(str, ':');
newtitle = 0;
if ~isempty(i2d)
i2d = i2d(1);
switch lower(str(1:i2d))
case { 'usage:' 'authors:' 'author:' 'notes:' 'note:' 'input:' ...
'inputs:' 'outputs:' 'output' 'example:' 'examples:' 'see also:' }, newtitle = 1;
end;
if (i2d == length(str)) & (str(1) ~= '%'), newtitle = 1; end;
end;
if newtitle
tilehtml = str(1:i2d);
newtitle = 1;
oldvarname = varname;
oldvartext = vartext;
if i2d < length(str)
%vartext = formatstr(str(i2d+1:end), g.refcall);
vartext = str(i2d+1:end);
else vartext = [];
end;
varname = [];
else
% not a title
% ------------
% scan lines
[tok1 strrm] = strtok( str );
[tok2 strrm] = strtok( strrm );
if ~isempty(tok2) & ( isequal(tok2,'-') | isequal(tok2,'=')) % new variable
newvar = 1;
oldvarname = varname;
oldvartext = vartext;
varname = tok1;
strrm = deblank(strrm); % remove tail blanks
strrm = deblank(strrm(end:-1:1)); % remove initial blanks
%strrm = formatstr( strrm(end:-1:1), g.refcall);
strrm = strrm(end:-1:1);
vartext = strrm;
else
% continue current text
str = deblank(str); % remove tail blanks
str = deblank(str(end:-1:1)); % remove initial blanks
%str = formatstr( str(end:-1:1), g.refcall );
str = str(end:-1:1);
if isempty(vartext)
vartext = str;
else
if ~isempty(varname)
vartext = [ vartext 10 str]; % espace if in array
else
if length(vartext)>3 & all(vartext( end-2:end) == '.')
vartext = [ deblank2(vartext(1:end-3)) 10 str]; % espace if '...'
else
vartext = [ vartext 10 str]; % CR otherwise
end;
end;
end;
end;
newtitle = 0;
end;
% --- END OF DECODING
str = fgets( fid );
% test if last entry
% ------------------
if str(1) ~= '%'
if ~newtitle
if ~isempty(oldvarname)
allvars{indexout} = oldvarname;
alltext{indexout} = oldvartext;
indexout = indexout + 1;
%fprintf( fo, [ '</tr>' g.normrow g.normcol1 g.var '</td>\n' ], oldvarname);
%fprintf( fo, [ g.normcol2 g.vartext '</td></tr>\n' ], oldvartext);
else
if ~isempty(oldvartext)
%fprintf( fo, [ g.normcol2 g.tabtext '</td></tr>\n' ], oldvartext);
end;
end;
newvar = 1;
oldvarname = varname;
oldvartext = vartext;
end;
end;
% test if new input for an array
% ------------------------------
if newvar | newtitle
if maindescription
if ~isempty(oldvartext) % FUNCTION TITLE
maintext = oldvartext;
maindescription = 0;
functioname = oldvarname( 1:findstr( oldvarname, '()' )-1);
%fprintf( fo, [g.normrow g.normcol1 g.functionname '</td>\n'],upper(functioname));
%fprintf( fo, [g.normcol2 g.description '</td></tr>\n'], [ upper(oldvartext(1)) oldvartext(2:end) ]);
% INSERT IMAGE IF PRESENT
%imagename = [ htmlfile( 1:findstr( htmlfile, functioname )-1) functioname '.jpg' ];
%if exist( imagename ) % do not make link if the file does not exist
%fprintf(fo, [ g.normrow g.doublecol ...
% '<CENTER><BR><A HREF="' imagename '" target="_blank"><img SRC=' imagename ...
% ' height=150 width=200></A></CENTER></td></tr>' ]);
%end;
end;
elseif ~isempty(oldvarname)
allvars{indexout} = oldvarname;
alltext{indexout} = oldvartext;
indexout = indexout + 1;
%fprintf( fo, [ '</tr>' g.normrow g.normcol1 g.var '</td>\n' ], oldvarname);
%fprintf( fo, [ g.normcol2 g.vartext '</td></tr>\n' ], oldvartext);
else
if ~isempty(oldvartext)
%fprintf( fo, [ g.normcol2 g.text '</td></tr>\n' ], oldvartext);
end;
end;
end;
% print title
% -----------
if newtitle
%fprintf( fo, [ g.normrow g.doublecol '<BR></td></tr>' g.normrow g.normcol1 g.title '</td>\n' ], tilehtml);
if str(1) ~= '%' % last input
%fprintf( fo, [ g.normcol2 g.text '</td></tr>\n' ], vartext);
end;
oldvarname = [];
oldvartext = [];
end;
else
str = fgets( fid );
end;
end;
fclose( fid );
% remove quotes of variables
% --------------------------
for index = 1:length(allvars)
if allvars{index}(1) == '''', allvars{index} = eval( allvars{index} ); end;
end;
if exist('varlist') == 1
if ~iscell(varlist), varlist = { varlist }; end;
newtxt = mat2cell(zeros(length(varlist), 1), length(varlist), 1); % preallocation
for index = 1:length(varlist)
loc = strmatch( varlist{index}, allvars);
if ~isempty(loc)
newtxt{index} = alltext{loc(1)};
else
disp([ 'warning: variable ''' varlist{index} ''' not found']);
newtxt{index} = '';
end;
end;
alltext = newtxt;
end;
return;
% -----------------
% sub-functions
% -----------------
function str = deblank2( str ); % deblank two ways
str = deblank(str(end:-1:1)); % remove initial blanks
str = deblank(str(end:-1:1)); % remove tail blanks
return;
function strout = formatstr( str, refcall );
[tok1 strrm] = strtok( str );
strout = [];
while ~isempty(tok1)
tokout = functionformat( tok1, refcall );
if isempty( strout)
strout = tokout;
else
strout = [strout ' ' tokout ];
end;
[tok1 strrm] = strtok( strrm );
end;
return;
function tokout = functionformat( tokin, refcall );
tokout = tokin; % default
[test, realtokin, tail] = testfunc1( tokin );
if ~test, [test, realtokin, tail] = testfunc2( tokin ); end;
if test
i1 = findstr( refcall, '%s');
i2 = findstr( refcall(i1(1):end), '''');
if isempty(i2) i2 = length( refcall(i1(1):end) )+1; end;
filename = [ realtokin refcall(i1+2:i1+i2-2)];
if exist( filename ) % do not make link if the file does not exist
tokout = sprintf( [ '<A HREF="' refcall '">%s</A>' tail ' ' ], realtokin, realtokin );
end;
end;
return;
function [test, realtokin, tail] = testfunc1( tokin ) % test if is string is 'function()[,]'
test = 0; realtokin = ''; tail = '';
if ~isempty( findstr( tokin, '()' ) )
realtokin = tokin( 1:findstr( tokin, '()' )-1);
if length(realtokin) < (length(tokin)-2) tail = tokin(end); else tail = []; end;
test = 1;
end;
return;
function [test, realtokin, tail] = testfunc2( tokin ) % test if is string is 'FUNCTION[,]'
test = 0; realtokin = ''; tail = '';
if all( upper(tokin) == tokin)
if tokin(end) == ','
realtokin = tokin(1:end-1);
tail = ',';
else
realtokin = tokin;
end;
testokin = realtokin;
testokin(findstr(testokin, '_')) = 'A';
testokin(findstr(testokin, '2')) = 'A';
if all(double(testokin) > 64) & all(double(testokin) < 91)
test = 1;
end;
realtokin = lower(realtokin);
end;
return;
|
github
|
lcnhappe/happe-master
|
eeg_retrieve.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/eeg_retrieve.m
| 2,820 |
utf_8
|
fc0ecd37ff8b71e41ef51d43a4aca461
|
% eeg_retrieve() - Retrieve an EEG dataset from the variable
% containing all datasets (standard: ALLEEG).
%
% Usage: >> EEG = eeg_retrieve( ALLEEG, index );
%
% Inputs:
% ALLEEG - variable containing all datasets
% index - index of the dataset to retrieve
%
% Outputs:
% EEG - output dataset. The workspace variable EEG is also updated
% ALLEEG - updated ALLEEG structure
% CURRENTSET - workspace variable index of the current dataset
%
% Note: The function performs >> EEG = ALLEEG(index);
% It also runs eeg_checkset() on it.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeg_store(), 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 [EEG, ALLEEG, CURRENTSET] = eeg_retrieve( ALLEEG, CURRENTSET);
if nargin < 2
help eeg_retrieve;
return;
end;
%try
eeglab_options;
try, % check whether recent changes to this dataset have been saved or not
%--------------------------------------------------------------------
tmpsaved = { ALLEEG.saved };
tmpsaved = tmpsaved(CURRENTSET);
catch, tmpsaved = 'no';
end;
if length(CURRENTSET) > 1 & option_storedisk
[ EEG tmpcom ] = eeg_checkset(ALLEEG(CURRENTSET)); % do not load data if several datasets
if length(CURRENTSET) ~= length(ALLEEG)
[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);
else
ALLEEG = EEG;
end;
else
if CURRENTSET ~= 0
[ EEG tmpcom ] = eeg_checkset(ALLEEG(CURRENTSET), 'loaddata');
[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);
else
EEG = eeg_emptyset; % empty dataset
return;
end;
end;
% retain saved field
% ------------------
for index = 1:length(CURRENTSET)
ALLEEG(CURRENTSET(index)).saved = tmpsaved{index};
EEG(index).saved = tmpsaved{index};
end;
%catch
% fprintf('Warning: cannot retrieve dataset with index %d\n', CURRENTSET);
% return;
%end;
return;
|
github
|
lcnhappe/happe-master
|
vararg2str.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/vararg2str.m
| 6,803 |
utf_8
|
547476651c6901a530169197da722d2d
|
% vararg2str() - transform arguments into string for evaluation
% using the eval() command
%
% Usage:
% >> strout = vararg2str( allargs );
% >> strout = vararg2str( allargs, inputnames, inputnum, nostrconv );
%
% Inputs:
% allargs - Cell array containing all arguments
% inputnames - Cell array of input names for these arguments, if any.
% inputnum - Vector of indices for all inputs. If present, the
% string output may by replaced by varargin{num}.
% Include NaN in the vector to avoid specific parameters
% being converted in this way.
% nostrconv - Vector of 0s and 1s indicating where the string
% should be not be converted.
%
% Outputs:
% strout - output string
%
% Author: Arnaud Delorme, CNL / Salk Institute, 9 April 2002
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 9 April 2002
%
% 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 strout = vararg2str(allargs, inputnam, inputnum, int2str );
if nargin < 1
help vararg2str;
return;
end;
if isempty(allargs)
strout = '';
return;
end;
% default arguments
% -----------------
if nargin < 2
inputnam(1:length(allargs)) = {''};
else
if length(inputnam) < length(allargs)
inputnam(end+1:length(allargs)) = {''};
end;
end;
if nargin < 3
inputnum(1:length(allargs)) = NaN;
else
if length(inputnum) < length(allargs)
inputnum(end+1:length(allargs)) = NaN;
end;
end;
if nargin < 4
int2str(1:length(allargs)) = 0;
else
if length(int2str) < length(allargs)
int2str(end+1:length(allargs)) = 0;
end;
end;
if ~iscell( allargs )
allargs = { allargs };
end;
% actual conversion
% -----------------
strout = '';
for index = 1:length(allargs)
tmpvar = allargs{index};
if ~isempty(inputnam{index})
strout = [ strout ',' inputnam{index} ];
else
if isstr( tmpvar )
if int2str(index)
strout = [ strout ',' tmpvar ];
else
strout = [ strout ',' str2str( tmpvar ) ];
end;
elseif isnumeric( tmpvar ) | islogical( tmpvar )
strout = [ strout ',' array2str( tmpvar ) ];
elseif iscell( tmpvar )
tmpres = vararg2str( tmpvar );
comas = find( tmpres == ',' );
tmpres(comas) = ' ';
strout = [ strout ',{' tmpres '}' ];
elseif isstruct(tmpvar)
strout = [ strout ',' struct2str( tmpvar ) ];
else
error('Unrecognized input');
end;
end;
end;
if ~isempty(strout)
strout = strout(2:end);
end;
% convert string to string
% ------------------------
function str = str2str( array )
if isempty( array), str = ''''''; return; end;
str = '';
for index = 1:size(array,1)
tmparray = deblank(array(index,:));
if isempty(tmparray)
str = [ str ','' ''' ];
else
str = [ str ',''' doublequotes(tmparray) '''' ];
end;
end;
if size(array,1) > 1
str = [ 'strvcat(' str(2:end) ')'];
else
str = str(2:end);
end;
return;
% convert array to string
% -----------------------
function str = array2str( array )
if isempty( array), str = '[]'; return; end;
if prod(size(array)) == 1, str = num2str(array); return; end;
if size(array,1) == 1, str = [ '[' contarray(array) '] ' ]; return; end;
if size(array,2) == 1, str = [ '[' contarray(array') ']'' ' ]; return; end;
str = '';
for index = 1:size(array,1)
str = [ str ';' contarray(array(index,:)) ];
end;
str = [ '[' str(2:end) ']' ];
return;
% convert struct to string
% ------------------------
function str = struct2str( structure )
if isempty( structure )
str = 'struct([])'; return;
end;
str = '';
allfields = fieldnames( structure );
for index = 1:length( allfields )
strtmp = '';
eval( [ 'allcontent = { structure.' allfields{index} ' };' ] ); % getfield generates a bug
str = [ str, '''' allfields{index} ''',{' vararg2str( allcontent ) '},' ];
end;
str = [ 'struct(' str(1:end-1) ')' ];
return;
% double the quotes in strings
% ----------------------------
function str = doublequotes( str )
quoteloc = union_bc(findstr( str, ''''), union(findstr(str, '%'), findstr(str, '\')));
if ~isempty(quoteloc)
for index = length(quoteloc):-1:1
str = [ str(1:quoteloc(index)) str(quoteloc(index):end) ];
end;
end;
return;
% test continuous arrays
% ----------------------
function str = contarray( array )
array = double(array);
tmpind = find( round(array) ~= array );
if prod(size(array)) == 1
str = num2str(array);
return;
end;
if size(array,1) == 1 & size(array,2) == 2
str = [num2str(array(1)) ' ' num2str(array(2))];
return;
end;
if isempty(tmpind) | all(isnan(array(tmpind)))
str = num2str(array(1));
skip = 0;
indent = array(2) - array(1);
for index = 2:length(array)
if array(index) ~= array(index-1)+indent | indent == 0
if skip <= 1
if skip == 0
str = [str ' ' num2str(array(index))];
else
str = [str ' ' num2str(array(index-1)) ' ' num2str(array(index))];
end;
else
if indent == 1
str = [str ':' num2str(array(index-1)) ' ' num2str(array(index))];
else
str = [str ':' num2str(indent) ':' num2str(array(index-1)) ' ' num2str(array(index))];
end;
end;
skip = 0;
indent = array(index) - array(index-1);
else
skip = skip + 1;
end;
end;
if array(index) == array(index-1)+indent
if skip ~= 0
if indent == 1
str = [str ':' num2str(array(index)) ];
elseif indent == 0
str = [str ' ' num2str(array(index)) ];
else
str = [str ':' num2str(indent) ':' num2str(array(index)) ];
end;
end;
end;
else
if length(array) < 10
str = num2str(array(1));
for index = 2:length(array)
str = [str ' ' num2str(array(index)) ];
end;
else
str = num2str(double(array));
end;
end;
|
github
|
lcnhappe/happe-master
|
unique_bc.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/unique_bc.m
| 717 |
utf_8
|
1ac4b80ca073d969c0b6d0e7a0db1f3d
|
% unique_bc - unique backward compatible with Matlab versions prior to 2013a
function [C,IA,IB] = unique_bc(A,varargin);
errorFlag = error_bc;
v = version;
indp = find(v == '.');
v = str2num(v(1:indp(2)-1));
if v > 7.19, v = floor(v) + rem(v,1)/10; end;
if nargin > 2
ind = strmatch('legacy', varargin);
if ~isempty(ind)
varargin(ind) = [];
end;
end;
if v >= 7.14
[C,IA,IB] = unique(A,varargin{:},'legacy');
if errorFlag
[C2,IA2] = unique(A,varargin{:});
if ~isequal(C, C2) || ~isequal(IA, IA2) || ~isequal(IB, IB2)
warning('backward compatibility issue with call to unique function');
end;
end;
else
[C,IA,IB] = unique(A,varargin{:});
end;
|
github
|
lcnhappe/happe-master
|
setdiff_bc.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/setdiff_bc.m
| 704 |
utf_8
|
6ff610d1b3099610817bea2fc877650d
|
% setdiff_bc - setdiff backward compatible with Matlab versions prior to 2013a
function [C,IA] = setdiff_bc(A,B,varargin);
errorFlag = error_bc;
v = version;
indp = find(v == '.');
v = str2num(v(1:indp(2)-1));
if v > 7.19, v = floor(v) + rem(v,1)/10; end;
if nargin > 2
ind = strmatch('legacy', varargin);
if ~isempty(ind)
varargin(ind) = [];
end;
end;
if v >= 7.14
[C,IA] = setdiff(A,B,varargin{:},'legacy');
if errorFlag
[C2,IA2] = setdiff(A,B,varargin{:});
if (~isequal(C, C2) || ~isequal(IA, IA2))
warning('backward compatibility issue with call to setdiff function');
end;
end;
else
[C,IA] = setdiff(A,B,varargin{:});
end;
|
github
|
lcnhappe/happe-master
|
union_bc.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/union_bc.m
| 724 |
utf_8
|
958b5b56de3e20c3892b2d7809e830fd
|
% union_bc - union backward compatible with Matlab versions prior to 2013a
function [C,IA,IB] = union_bc(A,B,varargin);
errorFlag = error_bc;
v = version;
indp = find(v == '.');
v = str2num(v(1:indp(2)-1));
if v > 7.19, v = floor(v) + rem(v,1)/10; end;
if nargin > 2
ind = strmatch('legacy', varargin);
if ~isempty(ind)
varargin(ind) = [];
end;
end;
if v >= 7.14
[C,IA,IB] = union(A,B,varargin{:},'legacy');
if errorFlag
[C2,IA2,IB2] = union(A,B,varargin{:});
if (~isequal(C, C2) || ~isequal(IA, IA2) || ~isequal(IB, IB2))
warning('backward compatibility issue with call to union function');
end;
end;
else
[C,IA,IB] = union(A,B,varargin{:});
end;
|
github
|
lcnhappe/happe-master
|
getkeyval.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/getkeyval.m
| 4,294 |
utf_8
|
f3f11db9f974963b9b8b34e48f778ae9
|
% getkeyval() - get variable value from a 'key', 'val' sequence string.
%
% Usage:
% >> val = getkeyval( keyvalstr, varname, mode, defaultval);
%
% Inputs:
% keyvalstr - string containing 'key', 'val' arguments
% varname - string for the name of the variable or index
% of the value to retrieve (assuming arguments are
% separated by comas).
% mode - if the value extracted is an integer array, the
% 'mode' variable can contain a subset of indexes to return.
% If mode is 'present', then either 0 or 1 is returned
% depending on wether the variable is present.
% defaultval - default value if the varible is not found
%
% Outputs:
% val - a value for the variable
%
% Note: this function is helpful for finding arguments in string commands
% stored in command history.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 29 July 2002
%
% See also: gethelpvar()
% Copyright (C) 2002 [email protected], Arnaud Delorme, CNL / Salk Institute
%
% 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 txt = getkeyval(lastcom, var, mode, default)
% mode can be present for 0 and 1 if the variable is present
if nargin < 1
help getkeyval;
return;
end;
if nargin < 4
default = '';
end;
if isempty(lastcom)
txt = default; return;
end;
if nargin < 3
mode = '';
end;
if isstr(mode) & strcmp(mode, 'present')
if ~isempty(findstr(var, lastcom))
txt = 1; return;
else
txt = 0; return;
end;
end;
if isnumeric(var)
comas = findstr(lastcom, ',');
if length(comas) >= var
txt = lastcom(comas(var-1)+1:comas(var)-1);
tmpval = eval( txt );
if isempty(tmpval), txt = '';
else txt = vararg2str( tmpval );
end;
return;
% txt = deblank(txt(end:-1:1));
% txt = deblank(txt(end:-1:1));
%
% if ~isempty(txt) & txt(end) == '}', txt = txt(2:end-1); end;
% if ~isempty(txt)
% txt = deblank(txt(end:-1:1));
% txt = deblank(txt(end:-1:1));
% end;
% if ~isempty(txt) & txt(end) == ']', txt = txt(2:end-1); end;
% if ~isempty(txt)
% txt = deblank(txt(end:-1:1));
% txt = deblank(txt(end:-1:1));
% end;
% if ~isempty(txt) & txt(end) == '''', txt = txt(2:end-1); end;
else
txt = default;
end;
%fprintf('%s:%s\n', var, txt);
return;
else
comas = findstr(lastcom, ','); % finding all comas
comas = [ comas findstr(lastcom, ');') ]; % and end of lines
varloc = findstr(lastcom, var);
if ~isempty(varloc)
% finding comas surrounding 'val' var in 'key', 'val' sequence
comas = comas(find(comas >varloc(end)));
txt = lastcom(comas(1)+1:comas(2)-1);
txt = deblank(txt(end:-1:1));
txt = deblank(txt(end:-1:1));
if strcmp(mode, 'full')
parent = findstr(lastcom, '}');
if ~isempty(parent)
comas = comas(find(comas >parent(1)));
txt = lastcom(comas(1)+1:comas(2)-1);
end;
txt = [ '''' var ''', ' txt ];
elseif isnumeric(mode)
txt = str2num(txt);
if ~isempty(mode)
if length(txt) >= max(mode)
if all(isnan(txt(mode))), txt = '';
else txt = num2str(txt(mode));
end;
elseif length(txt) >= mode(1)
if all(isnan(txt(mode(1)))), txt = '';
else txt = num2str(txt(mode(1)));
end;
else
txt = default;
end;
else
txt = num2str(txt);
end;
elseif txt(1) == ''''
txt = txt(2:end-1); % remove quotes for text
end;
else
txt = default;
end;
end;
%fprintf('%s:%s\n', var, txt);
|
github
|
lcnhappe/happe-master
|
is_sccn.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/is_sccn.m
| 388 |
utf_8
|
99847041e8b1f185a51f93939d33b819
|
% is_sccn() - returns 1 if computer is located at SCCN (Swartz Center
% for computational Neuroscience) and 0 otherwise
function bool = is_sccn;
bool = 0;
domnane = ' ';
try
eval([ 'if isunix, [tmp domname] = unix(''hostname -d'');' ...
'end;' ...
'bool = strcmpi(domname(1:end-1), ''ucsd.edu'');' ], '');
catch,
end;
|
github
|
lcnhappe/happe-master
|
gettext.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/gettext.m
| 2,465 |
utf_8
|
414488f77905ebf88c561e892df73cd7
|
% gettext() - This function prints a dialog box on screen and waits for
% the user to enter a string. There is a cancel button which
% returns a value of [].
% Usage:
% >> out = gettext(label1,label2,...,label7);
%
% Author: Colin Humphries, CNL / Salk Institute, La Jolla, 1997
% Copyright (C) 1997 Colin Humphries, Salk Institute
%
% 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 out = gettext(label1,label2,label3,label4,label5,label6,label7);
global is_text_entered
is_text_entered = 0;
for i = 1:nargin
eval(['leng(i) = length(label',num2str(i),');'])
end
figurelength = 15*1.0*max(leng);
if figurelength < 240
figurelength = 290;
end
figureheight = 80+nargin*18;
% Set figure
figure('Position',[302 396 figurelength figureheight],'color',[.6 .6 .6],'NumberTitle','off')
f1 = gcf;
ax = axes('Units','Pixels','Position',[0 0 figurelength figureheight],'Visible','off','XLim',[0 figurelength],'YLim',[0 figureheight]);
for i = 1:nargin
eval(['text(figurelength/2,',num2str(figureheight-(i-1)*18-20),',label',num2str(i),',''color'',''k'',''FontSize'',16,''HorizontalAlignment'',''center'')'])
end
% Set up uicontrols
TIMESTRING = ['global is_text_entered;is_text_entered = 1;clear is_text_entered'];
u = uicontrol('Style','Edit','Units','Pixels','Position',[15 20 figurelength-95 25],'HorizontalAlignment','left','Callback',TIMESTRING);
TIMESTRING = ['global is_text_entered;is_text_entered = 2;clear is_text_entered'];
v = uicontrol('Style','Pushbutton','Units','Pixels','Position',[figurelength-70 20 55 25],'String','Cancel','Callback',TIMESTRING);
while(is_text_entered == 0)
drawnow
end
if is_text_entered == 1
out = get(u,'string');
else
out = [];
end
clear is_text_entered
delete(f1)
|
github
|
lcnhappe/happe-master
|
eeg_getdatact.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/eeg_getdatact.m
| 12,037 |
utf_8
|
bc4bb0dfeb0f9183cb320544ba36fbdd
|
% eeg_getdatact() - get EEG data from a specified dataset or
% component activity
%
% Usage:
% >> signal = eeg_getdatact( EEG );
% >> signal = eeg_getdatact( EEG, 'key', 'val');
%
% Inputs:
% EEG - Input dataset
%
% Optional input:
% 'channel' - [integer array] read only specific channels.
% Default is to read all data channels.
% 'component' - [integer array] read only specific components
% 'projchan' - [integer or cell array] channel(s) onto which the component
% should be projected.
% 'rmcomps' - [integer array] remove selected components from data
% channels. This is only to be used with channel data not
% when selecting components.
% 'trialindices' - [integer array] only read specific trials. Default is
% to read all trials.
% 'samples' - [integer array] only read specific samples. Default is
% to read all samples.
% 'reshape' - ['2d'|'3d'] reshape data. Default is '3d' when possible.
% 'verbose' - ['on'|'off'] verbose mode. Default is 'on'.
%
% Outputs:
% signal - EEG data or component activity
%
% Author: Arnaud Delorme, SCCN & CERCO, CNRS, 2008-
%
% See also: eeg_checkset()
% Copyright (C) 15 Feb 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 [data boundaries] = eeg_getdatact( EEG, varargin);
data = [];
if nargin < 1
help eeg_getdatact;
return;
end;
% reading data from several datasets and concatening it
% -----------------------------------------------------
if iscell(EEG) || (~isstr(EEG) && length(EEG) > 1)
% decode some arguments
% ---------------------
trials = cell(1,length(EEG));
rmcomps = cell(1,length(EEG));
for iArg = length(varargin)-1:-2:1
if strcmpi(varargin{iArg}, 'trialindices')
trials = varargin{iArg+1};
varargin(iArg:iArg+1) = [];
elseif strcmpi(varargin{iArg}, 'rmcomps')
rmcomps = varargin{iArg+1};
varargin(iArg:iArg+1) = [];
end;
end;
if isnumeric(rmcomps), rmtmp = rmcomps; rmcomps = cell(1,length(EEG)); rmcomps(:) = { rmtmp }; end;
% concatenate datasets
% --------------------
data = [];
boundaries = [];
for dat = 1:length(EEG)
if iscell(EEG)
[tmpdata datboundaries] = eeg_getdatact(EEG{dat}, 'trialindices', trials{dat}, 'rmcomps', rmcomps{dat}, varargin{:} );
else [tmpdata datboundaries] = eeg_getdatact(EEG(dat), 'trialindices', trials{dat}, 'rmcomps', rmcomps{dat}, varargin{:} );
end;
if isempty(data),
data = tmpdata;
boundaries = datboundaries;
else
if all([ EEG.trials ] == 1) % continuous data
if size(data,1) ~= size(tmpdata,1), error('Datasets to be concatenated do not have the same number of channels'); end;
% adding boundaries
if ~isempty(datboundaries)
boundaries = [boundaries datboundaries size(data,2)];
else
boundaries = [boundaries size(data,2)];
end;
data(:,end+1:end+size(tmpdata,2)) = tmpdata; % concatenating trials
else
if size(data,1) ~= size(tmpdata,1), error('Datasets to be concatenated do not have the same number of channels'); end;
if size(data,2) ~= size(tmpdata,2), error('Datasets to be concatenated do not have the same number of time points'); end;
data(:,:,end+1:end+size(tmpdata,3)) = tmpdata; % concatenating trials
end;
end;
end;
return;
end;
% if string load dataset
% ----------------------
if isstr(EEG)
EEG = pop_loadset('filename', EEG, 'loadmode', 'info');
end;
opt = finputcheck(varargin, { ...
'channel' 'integer' {} [];
'verbose' 'string' { 'on','off' } 'on';
'reshape' 'string' { '2d','3d' } '3d';
'projchan' {'integer','cell' } { {} {} } [];
'component' 'integer' {} [];
'samples' 'integer' {} [];
'interp' 'struct' { } struct([]);
'trialindices' {'integer','cell'} { {} {} } [];
'rmcomps' {'integer','cell'} { {} {} } [] }, 'eeg_getdatact');
if isstr(opt), error(opt); end;
channelNotDefined = 0;
if isempty(opt.channel), opt.channel = [1:EEG.nbchan]; channelNotDefined = 1;
elseif isequal(opt.channel, [1:EEG.nbchan]) && ~isempty(opt.interp) channelNotDefined = 1;
end;
if isempty(opt.trialindices), opt.trialindices = [1:EEG.trials]; end;
if iscell( opt.trialindices), opt.trialindices = opt.trialindices{1}; end;
if iscell(opt.rmcomps ), opt.rmcomps = opt.rmcomps{1}; end;
if (~isempty(opt.rmcomps) | ~isempty(opt.component)) & isempty(EEG.icaweights)
error('No ICA weight in dataset');
end;
if strcmpi(EEG.data, 'in set file')
EEG = pop_loadset('filename', EEG.filename, 'filepath', EEG.filepath);
end;
% get data boundaries if continuous data
% --------------------------------------
boundaries = [];
if nargout > 1 && EEG.trials == 1 && ~isempty(EEG.event) && isfield(EEG.event, 'type') && isstr(EEG.event(1).type)
if ~isempty(opt.samples)
disp('WARNING: eeg_getdatact.m, boundaries are not accurate when selecting data samples');
end;
tmpevent = EEG.event;
tmpbound = strmatch('boundary', lower({ tmpevent.type }));
if ~isempty(tmpbound)
boundaries = [tmpevent(tmpbound).latency ]-0.5;
end;
end;
% getting channel or component activation
% ---------------------------------------
filename = fullfile(EEG.filepath, [ EEG.filename(1:end-4) '.icaact' ] );
if ~isempty(opt.component) & ~isempty(EEG.icaact)
data = EEG.icaact(opt.component,:,:);
elseif ~isempty(opt.component) & exist(filename)
% reading ICA file
% ----------------
data = repmat(single(0), [ length(opt.component) EEG.pnts EEG.trials ]);
fid = fopen( filename, 'r', 'ieee-le'); %little endian (see also pop_saveset)
if fid == -1, error( ['file ' filename ' could not be open' ]); end;
for ind = 1:length(opt.component)
fseek(fid, (opt.component(ind)-1)*EEG.pnts*EEG.trials*4, -1);
data(ind,:) = fread(fid, [EEG.trials*EEG.pnts 1], 'float32')';
end;
fclose(fid);
elseif ~isempty(opt.component)
if isempty(EEG.icaact)
data = eeg_getdatact( EEG );
data = (EEG.icaweights(opt.component,:)*EEG.icasphere)*data(EEG.icachansind,:);
else
data = EEG.icaact(opt.component,:,:);
end;
else
if isnumeric(EEG.data) % channel
data = EEG.data;
else % channel but no data loaded
filename = fullfile(EEG.filepath, EEG.data);
fid = fopen( filename, 'r', 'ieee-le'); %little endian (see also pop_saveset)
if fid == -1
error( ['file ' filename ' not found. If you have renamed/moved' 10 ...
'the .set file, you must also rename/move the associated data file.' ]);
else
if strcmpi(opt.verbose, 'on')
fprintf('Reading float file ''%s''...\n', filename);
end;
end;
% old format = .fdt; new format = .dat (transposed)
% -------------------------------------------------
datformat = 0;
if length(filename) > 3
if strcmpi(filename(end-2:end), 'dat')
datformat = 1;
end;
end;
EEG.datfile = EEG.data;
% reading data file
% -----------------
eeglab_options;
if length(opt.channel) == EEG.nbchan && option_memmapdata
fclose(fid);
data = mmo(filename, [EEG.nbchan EEG.pnts EEG.trials], false);
%data = memmapdata(filename, [EEG.nbchan EEG.pnts EEG.trials]);
else
if datformat
if length(opt.channel) == EEG.nbchan || ~isempty(opt.interp)
data = fread(fid, [EEG.trials*EEG.pnts EEG.nbchan], 'float32')';
else
data = repmat(single(0), [ length(opt.channel) EEG.pnts EEG.trials ]);
for ind = 1:length(opt.channel)
fseek(fid, (opt.channel(ind)-1)*EEG.pnts*EEG.trials*4, -1);
data(ind,:) = fread(fid, [EEG.trials*EEG.pnts 1], 'float32')';
end;
opt.channel = [1:size(data,1)];
end;
else
data = fread(fid, [EEG.nbchan Inf], 'float32');
end;
fclose(fid);
end;
end;
% subracting components from data
% -------------------------------
if ~isempty(opt.rmcomps)
if strcmpi(opt.verbose, 'on')
fprintf('Removing %d artifactual components\n', length(opt.rmcomps));
end;
rmcomps = eeg_getdatact( EEG, 'component', opt.rmcomps); % loaded from file
rmchan = [];
rmchanica = [];
for index = 1:length(opt.channel)
tmpicaind = find(opt.channel(index) == EEG.icachansind);
if ~isempty(tmpicaind)
rmchan = [ rmchan index ];
rmchanica = [ rmchanica tmpicaind ];
end;
end;
data(rmchan,:) = data(rmchan,:) - EEG.icawinv(rmchanica,opt.rmcomps)*rmcomps(:,:);
%EEG = eeg_checkset(EEG, 'loaddata');
%EEG = pop_subcomp(EEG, opt.rmcomps);
%data = EEG.data(opt.channel,:,:);
%if strcmpi(EEG.subject, 'julien') & strcmpi(EEG.condition, 'oddball') & strcmpi(EEG.group, 'after')
% jjjjf
%end;
end;
if ~isempty(opt.interp)
EEG.data = data;
EEG.event = [];
EEG.epoch = [];
EEG = eeg_interp(EEG, opt.interp, 'spherical');
data = EEG.data;
if channelNotDefined, opt.channel = [1:EEG.nbchan]; end;
end;
if ~isequal(opt.channel, [1:EEG.nbchan])
data = data(intersect(opt.channel,[1:EEG.nbchan]),:,:);
end;
end;
% projecting components on data channels
% --------------------------------------
if ~isempty(opt.projchan)
if iscell(opt.projchan)
opt.projchan = std_chaninds(EEG, opt.projchan);
end;
finalChanInds = [];
for iChan = 1:length(opt.projchan)
tmpInd = find(EEG.icachansind == opt.projchan(iChan));
if isempty(tmpInd)
error(sprintf('Warning: can not backproject component on channel %d (not used for ICA)\n', opt.projchan(iChan)));
end;
finalChanInds = [ finalChanInds tmpInd ];
end;
data = EEG.icawinv(finalChanInds, opt.component)*data(:,:);
end;
if size(data,2)*size(data,3) ~= EEG.pnts*EEG.trials
disp('WARNING: The file size on disk does not correspond to the dataset, file has been truncated');
end;
try,
if EEG.trials == 1, EEG.pnts = size(data,2); end;
if strcmpi(opt.reshape, '3d')
data = reshape(data, size(data,1), EEG.pnts, EEG.trials);
else data = reshape(data, size(data,1), EEG.pnts*EEG.trials);
end;
catch
error('The file size on disk does not correspond to the dataset information.');
end;
% select trials
% -------------
if length(opt.trialindices) ~= EEG.trials
data = data(:,:,opt.trialindices);
end;
if ~isempty(opt.samples)
data = data(:,opt.samples,:);
end;
|
github
|
lcnhappe/happe-master
|
eeg_readoptions.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/eeg_readoptions.m
| 3,419 |
utf_8
|
4104fa6db19f22201a63ba183b0d2f5f
|
% eeg_readoptions() - Read EEGLAB memory options file (eeg_options) into a
% structure variable (opt).
%
% Usage:
% [ header, opt ] = eeg_readoptions( filename, opt );
%
% Input:
% filename - [string] name of the option file
% opt - [struct] option structure containing backup values
%
% Outputs:
% header - [string] file header.
% opt - [struct] option structure containing an array of 3 fields
% varname -> all variable names.
% value -> value for each variable name
% description -> all description associated with each variable
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2006-
%
% See also: eeg_options(), eeg_editoptions()
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, 2006-
%
% 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 [ header, opt ] = eeg_readoptions( filename, opt_backup );
if nargin < 1
help eeg_readoptions;
return;
end;
if nargin < 2
opt_backup = [];
end;
if isstr(filename)
fid = fopen(filename, 'r');
else fid = filename;
end;
% skip header
% -----------
header = '';
str = fgets( fid );
while (str(1) == '%')
header = [ header str];
str = fgets( fid );
end;
% read variables values and description
% --------------------------------------
str = fgetl( fid ); % jump a line
index = 1;
opt = [];
while (str(1) ~= -1)
if str(1) == '%'
opt(index).description = str(3:end-1);
opt(index).value = [];
opt(index).varname = '';
else
[ opt(index).varname str ] = strtok(str); % variable name
[ equal str ] = strtok(str); % =
[ opt(index).value str ] = strtok(str); % value
[ tmp str ] = strtok(str); % ;
[ tmp dsc ] = strtok(str); % comment
dsc = deblank( dsc(end:-1:1) );
opt(index).description = deblank( dsc(end:-1:1) );
opt(index).value = str2num( opt(index).value );
end;
str = fgets( fid ); % jump a line
index = index+1;
end;
fclose(fid);
% replace in backup structure if any
% ----------------------------------
if ~isempty(opt_backup)
if ~isempty(opt)
for index = 1:length(opt_backup)
ind = strmatch(opt_backup(index).varname, { opt.varname }, 'exact');
if ~isempty(ind) & ~isempty(opt_backup(index).varname)
opt_backup(index).value = opt(ind).value;
end;
end;
end;
opt = opt_backup;
end;
|
github
|
lcnhappe/happe-master
|
hlp_argstruct2linearcell.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/hlp_argstruct2linearcell.m
| 1,953 |
utf_8
|
cf2a64e0864d59a83ffeefe20c9f2b09
|
% hlp_argstruct2linearcell() - Linearize configation output of arg_guipanel
%
% Usage:
% >> cellval = hlp_argstruct2linearcells( cfg );
%
% Inputs:
% cfg - output configuration structure from arg_guipanel
%
% Output:
% cellval - cell array of output values
%
% Author: Arnaud Delorme, SCCN & CERCO, CNRS, 2013-
% Copyright (C) 2013 Arnaud Delorme
%
% 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 cellval = hlp_argstruct2linearcell(cfg);
cellval = {};
if isstruct(cfg)
ff = fieldnames(cfg);
for iField = 1:length(ff)
if ~strcmpi(ff{iField}, 'arg_direct')
if strcmpi(ff{iField}, 'arg_selection')
cellval = { cfg.arg_selection cellval{:} };
else
val = cfg.(ff{iField});
if isstruct(val)
val = hlp_argstruct2linearcell(val);
cellval = { cellval{:} ff{iField} val{:} };
elseif iscell(val)
cellval = { cellval{:} ff{iField} vararg2str(val) };
else
cellval = { cellval{:} ff{iField} val };
end;
end;
end;
end
else
cellval = cfg;
end;
|
github
|
lcnhappe/happe-master
|
eeg_checkset.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/eeg_checkset.m
| 69,153 |
utf_8
|
7137e26ebd92dd9dfed8b74e47be557d
|
% eeg_checkset() - check the consistency of the fields of an EEG dataset
% Also: See EEG dataset structure field descriptions below.
%
% Usage: >> [EEGOUT,changes] = eeg_checkset(EEG); % perform all checks
% except 'makeur'
% >> [EEGOUT,changes] = eeg_checkset(EEG, 'keyword'); % perform 'keyword' check(s)
%
% Inputs:
% EEG - EEGLAB dataset structure or (ALLEEG) array of EEG structures
%
% Optional keywords:
% 'icaconsist' - if EEG contains several datasets, check whether they have
% the same ICA decomposition
% 'epochconsist' - if EEG contains several datasets, check whether they have
% identical epoch lengths and time limits.
% 'chanconsist' - if EEG contains several datasets, check whether they have
% the same number of channela and channel labels.
% 'data' - check whether EEG contains data (EEG.data)
% 'loaddata' - load data array (if necessary)
% 'savedata' - save data array (if necessary - see EEG.saved below)
% 'contdata' - check whether EEG contains continuous data
% 'epoch' - check whether EEG contains epoched or continuous data
% 'ica' - check whether EEG contains an ICA decomposition
% 'besa' - check whether EEG contains component dipole locations
% 'event' - check whether EEG contains an event array
% 'makeur' - remake the EEG.urevent structure
% 'checkur' - check whether the EEG.urevent structure is consistent
% with the EEG.event structure
% 'chanlocsize' - check the EEG.chanlocs structure length; show warning if
% necessary.
% 'chanlocs_homogeneous' - check whether EEG contains consistent channel
% information; if not, correct it.
% 'eventconsistency' - check whether EEG.event information are consistent;
% rebuild event* subfields of the 'EEG.epoch' structure
% (can be time consuming).
% Outputs:
% EEGOUT - output EEGLAB dataset or dataset array
% changes - change code: 'no' = no changes; 'yes' = the EEG
% structure was modified
%
% ===========================================================
% The structure of an EEG dataset under EEGLAB (as of v5.03):
%
% Basic dataset information:
% EEG.setname - descriptive name|title for the dataset
% EEG.filename - filename of the dataset file on disk
% EEG.filepath - filepath (directory/folder) of the dataset file(s)
% EEG.trials - number of epochs (or trials) in the dataset.
% If data are continuous, this number is 1.
% EEG.pnts - number of time points (or data frames) per trial (epoch).
% If data are continuous (trials=1), the total number
% of time points (frames) in the dataset
% EEG.nbchan - number of channels
% EEG.srate - data sampling rate (in Hz)
% EEG.xmin - epoch start latency|time (in sec. relative to the
% time-locking event at time 0)
% EEG.xmax - epoch end latency|time (in seconds)
% EEG.times - vector of latencies|times in seconds (one per time point)
% EEG.ref - ['common'|'averef'|integer] reference channel type or number
% EEG.history - cell array of ascii pop-window commands that created
% or modified the dataset
% EEG.comments - comments about the nature of the dataset (edit this via
% menu selection Edit > About this dataset)
% EEG.etc - miscellaneous (technical or temporary) dataset information
% EEG.saved - ['yes'|'no'] 'no' flags need to save dataset changes before exit
%
% The data:
% EEG.data - two-dimensional continuous data array (chans, frames)
% ELSE, three-dim. epoched data array (chans, frames, epochs)
%
% The channel locations sub-structures:
% EEG.chanlocs - structure array containing names and locations
% of the channels on the scalp
% EEG.urchanlocs - original (ur) dataset chanlocs structure containing
% all channels originally collected with these data
% (before channel rejection)
% EEG.chaninfo - structure containing additional channel info
% EEG.ref - type of channel reference ('common'|'averef'|+/-int]
% EEG.splinefile - location of the spline file used by headplot() to plot
% data scalp maps in 3-D
%
% The event and epoch sub-structures:
% EEG.event - event structure containing times and nature of experimental
% events recorded as occurring at data time points
% EEG.urevent - original (ur) event structure containing all experimental
% events recorded as occurring at the original data time points
% (before data rejection)
% EEG.epoch - epoch event information and epoch-associated data structure array (one per epoch)
% EEG.eventdescription - cell array of strings describing event fields.
% EEG.epochdescription - cell array of strings describing epoch fields.
% --> See the http://sccn.ucsd.edu/eeglab/maintut/eeglabscript.html for details
%
% ICA (or other linear) data components:
% EEG.icasphere - sphering array returned by linear (ICA) decomposition
% EEG.icaweights - unmixing weights array returned by linear (ICA) decomposition
% EEG.icawinv - inverse (ICA) weight matrix. Columns gives the projected
% topographies of the components to the electrodes.
% EEG.icaact - ICA activations matrix (components, frames, epochs)
% Note: [] here means that 'compute_ica' option has bee set
% to 0 under 'File > Memory options' In this case,
% component activations are computed only as needed.
% EEG.icasplinefile - location of the spline file used by headplot() to plot
% component scalp maps in 3-D
% EEG.chaninfo.icachansind - indices of channels used in the ICA decomposition
% EEG.dipfit - array of structures containing component map dipole models
%
% Variables indicating membership of the dataset in a studyset:
% EEG.subject - studyset subject code
% EEG.group - studyset group code
% EEG.condition - studyset experimental condition code
% EEG.session - studyset session number
%
% Variables used for manual and semi-automatic data rejection:
% EEG.specdata - data spectrum for every single trial
% EEG.specica - data spectrum for every single trial
% EEG.stats - statistics used for data rejection
% EEG.stats.kurtc - component kurtosis values
% EEG.stats.kurtg - global kurtosis of components
% EEG.stats.kurta - kurtosis of accepted epochs
% EEG.stats.kurtr - kurtosis of rejected epochs
% EEG.stats.kurtd - kurtosis of spatial distribution
% EEG.reject - statistics used for data rejection
% EEG.reject.entropy - entropy of epochs
% EEG.reject.entropyc - entropy of components
% EEG.reject.threshold - rejection thresholds
% EEG.reject.icareject - epochs rejected by ICA criteria
% EEG.reject.gcompreject - rejected ICA components
% EEG.reject.sigreject - epochs rejected by single-channel criteria
% EEG.reject.elecreject - epochs rejected by raw data criteria
%
% 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
% 01-25-02 reformated help & license -ad
% 01-26-02 chandeg events and trial condition format -ad
% 01-27-02 debug when trial condition is empty -ad
% 02-15-02 remove icawinv recompute for pop_epoch -ad & ja
% 02-16-02 remove last modification and test icawinv separatelly -ad
% 02-16-02 empty event and epoch check -ad
% 03-07-02 add the eeglab options -ad
% 03-07-02 corrected typos and rate/point calculation -ad & ja
% 03-15-02 add channel location reading & checking -ad
% 03-15-02 add checking of ICA and epochs with pop_up windows -ad
% 03-27-02 recorrected rate/point calculation -ad & sm
function [EEG, res] = eeg_checkset( EEG, varargin );
msg = '';
res = 'no';
com = sprintf('EEG = eeg_checkset( EEG );');
if nargin < 1
help eeg_checkset;
return;
end;
if isempty(EEG), return; end;
if ~isfield(EEG, 'data'), return; end;
% checking multiple datasets
% --------------------------
if length(EEG) > 1
if nargin > 1
switch varargin{1}
case 'epochconsist', % test epoch consistency
% ----------------------
res = 'no';
datasettype = unique_bc( [ EEG.trials ] );
if datasettype(1) == 1 & length(datasettype) == 1, return; % continuous data
elseif datasettype(1) == 1, return; % continuous and epoch data
end;
allpnts = unique_bc( [ EEG.pnts ] );
allxmin = unique_bc( [ EEG.xmin ] );
if length(allpnts) == 1 & length(allxmin) == 1, res = 'yes'; end;
return;
case 'chanconsist' % test channel number and name consistency
% ----------------------------------------
res = 'yes';
chanlen = unique_bc( [ EEG.nbchan ] );
anyempty = unique_bc( cellfun( 'isempty', { EEG.chanlocs }) );
if length(chanlen) == 1 & all(anyempty == 0)
tmpchanlocs = EEG(1).chanlocs;
channame1 = { tmpchanlocs.labels };
for i = 2:length(EEG)
tmpchanlocs = EEG(i).chanlocs;
channame2 = { tmpchanlocs.labels };
if length(intersect(channame1, channame2)) ~= length(channame1), res = 'no'; end;
end;
else res = 'no';
end;
return;
case 'icaconsist' % test ICA decomposition consistency
% ----------------------------------
res = 'yes';
anyempty = unique_bc( cellfun( 'isempty', { EEG.icaweights }) );
if length(anyempty) == 1 & anyempty(1) == 0
ica1 = EEG(1).icawinv;
for i = 2:length(EEG)
if ~isequal(EEG(1).icawinv, EEG(i).icawinv)
res = 'no';
end;
end;
else res = 'no';
end;
return;
end;
end;
end;
% reading these option take time because
% of disk access
% --------------
eeglab_options;
% standard checking
% -----------------
ALLEEG = EEG;
for inddataset = 1:length(ALLEEG)
EEG = ALLEEG(inddataset);
% additional checks
% -----------------
res = -1; % error code
if ~isempty( varargin)
for index = 1:length( varargin )
switch varargin{ index }
case 'data',; % already done at the top
case 'contdata',;
if EEG.trials > 1
errordlg2(strvcat('Error: function only works on continuous data'), 'Error');
return;
end;
case 'ica',
if isempty(EEG.icaweights)
errordlg2(strvcat('Error: no ICA decomposition. use menu "Tools > Run ICA" first.'), 'Error');
return;
end;
case 'epoch',
if EEG.trials == 1
errordlg2(strvcat('Extract epochs before running that function', 'Use Tools > Extract epochs'), 'Error');
return
end;
case 'besa',
if ~isfield(EEG, 'sources')
errordlg2(strvcat('No dipole information', '1) Export component maps: Tools > Localize ... BESA > Export ...' ...
, '2) Run BESA to localize the equivalent dipoles', ...
'3) Import the BESA dipoles: Tools > Localize ... BESA > Import ...'), 'Error');
return
end;
case 'event',
if isempty(EEG.event)
errordlg2(strvcat('Requires events. You need to add events first.', ...
'Use "File > Import event info" or "File > Import epoch info"'), 'Error');
return;
end;
case 'chanloc',
tmplocs = EEG.chanlocs;
if isempty(tmplocs) || ~isfield(tmplocs, 'theta') || all(cellfun('isempty', { tmplocs.theta }))
errordlg2( strvcat('This functionality requires channel location information.', ...
'Enter the channel file name via "Edit > Edit dataset info".', ...
'For channel file format, see ''>> help readlocs'' from the command line.'), 'Error');
return;
end;
case 'chanlocs_homogeneous',
tmplocs = EEG.chanlocs;
if isempty(tmplocs) || ~isfield(tmplocs, 'theta') || all(cellfun('isempty', { tmplocs.theta }))
errordlg2( strvcat('This functionality requires channel location information.', ...
'Enter the channel file name via "Edit > Edit dataset info".', ...
'For channel file format, see ''>> help readlocs'' from the command line.'), 'Error');
return;
end;
if ~isfield(EEG.chanlocs, 'X') || isempty(EEG.chanlocs(1).X)
EEG.chanlocs = convertlocs(EEG.chanlocs, 'topo2all');
res = [ inputname(1) ' = eeg_checkset(' inputname(1) ', ''chanlocs_homogeneous'' ); ' ];
end;
case 'chanlocsize',
if ~isempty(EEG.chanlocs)
if length(EEG.chanlocs) > EEG.nbchan
questdlg2(strvcat('Warning: there is one more electrode location than', ...
'data channels. EEGLAB will consider the last electrode to be the', ...
'common reference channel. If this is not the case, remove the', ...
'extra channel'), 'Warning', 'Ok', 'Ok');
end;
end;
case 'makeur',
if ~isempty(EEG.event)
if isfield(EEG.event, 'urevent'),
EEG.event = rmfield(EEG.event, 'urevent');
disp('eeg_checkset note: re-creating the original event table (EEG.urevent)');
else
disp('eeg_checkset note: creating the original event table (EEG.urevent)');
end;
EEG.urevent = EEG.event;
for index = 1:length(EEG.event)
EEG.event(index).urevent = index;
end;
end;
case 'checkur',
if ~isempty(EEG.event)
if isfield(EEG.event, 'urevent') & ~isempty(EEG.urevent)
urlatencies = [ EEG.urevent.latency ];
[newlat tmpind] = sort(urlatencies);
if ~isequal(newlat, urlatencies)
EEG.urevent = EEG.urevent(tmpind);
[tmp tmpind2] = sort(tmpind);
for index = 1:length(EEG.event)
EEG.event(index).urevent = tmpind2(EEG.event(index).urevent);
end;
end;
end;
end;
case 'eventconsistency',
[EEG res] = eeg_checkset(EEG);
if isempty(EEG.event), return; end;
% check events (slow)
% ------------
if isfield(EEG.event, 'type')
eventInds = arrayfun(@(x)isempty(x.type), EEG.event);
if any(eventInds)
if all(arrayfun(@(x)isnumeric(x.type), EEG.event))
for ind = find(eventInds), EEG.event(ind).type = NaN; end;
else for ind = find(eventInds), EEG.event(ind).type = 'empty'; end;
end;
end;
if ~all(arrayfun(@(x)ischar(x.type), EEG.event)) && ~all(arrayfun(@(x)isnumeric(x.type), EEG.event))
disp('Warning: converting all event types to strings');
for ind = 1:length(EEG.event)
EEG.event(ind).type = num2str(EEG.event(ind).type);
end;
EEG = eeg_checkset(EEG, 'eventconsistency');
end;
end;
% remove the events which latency are out of boundary
% ---------------------------------------------------
if isfield(EEG.event, 'latency')
if isfield(EEG.event, 'type') && ischar(EEG.event(1).type)
if strcmpi(EEG.event(1).type, 'boundary') & isfield(EEG.event, 'duration')
if EEG.event(1).duration < 1
EEG.event(1) = [];
elseif EEG.event(1).latency > 0 & EEG.event(1).latency < 1
EEG.event(1).latency = 0.5;
end;
end;
end;
try, tmpevent = EEG.event; alllatencies = [ tmpevent.latency ];
catch, error('Checkset: error empty latency entry for new events added by user');
end;
I1 = find(alllatencies < 0.5);
I2 = find(alllatencies > EEG.pnts*EEG.trials+1); % The addition of 1 was included
% because, if data epochs are extracted from -1 to
% time 0, this allow to include the last event in
% the last epoch (otherwise all epochs have an
% event except the last one
if (length(I1) + length(I2)) > 0
fprintf('eeg_checkset warning: %d/%d events had out-of-bounds latencies and were removed\n', ...
length(I1) + length(I2), length(EEG.event));
EEG.event(union(I1, I2)) = [];
end;
end;
if isempty(EEG.event), return; end;
% save information for non latency fields updates
% -----------------------------------------------
difffield = [];
if ~isempty(EEG.event) && isfield(EEG.event, 'epoch')
% remove fields with empty epochs
% -------------------------------
removeevent = [];
try, tmpevent = EEG.event; allepochs = [ tmpevent.epoch ];
removeevent = find( allepochs < 1 | allepochs > EEG.trials);
if ~isempty(removeevent)
disp([ 'eeg_checkset warning: ' int2str(length(removeevent)) ' event had invalid epoch numbers and were removed']);
end;
catch,
for indexevent = 1:length(EEG.event)
if isempty( EEG.event(indexevent).epoch ) || ~isnumeric(EEG.event(indexevent).epoch) ...
| EEG.event(indexevent).epoch < 1 || EEG.event(indexevent).epoch > EEG.trials
removeevent = [removeevent indexevent];
disp([ 'eeg_checkset warning: event ' int2str(indexevent) ' has an invalid epoch number: removed']);
end;
end;
end;
EEG.event(removeevent) = [];
tmpevent = EEG.event;
allepochs = [ tmpevent.epoch ];
% uniformize fields content for the different epochs
% --------------------------------------------------
% THIS WAS REMOVED SINCE SOME FIELDS ARE ASSOCIATED WITH THE EVENT AND NOT WITH THE EPOCH
% I PUT IT BACK, BUT IT DOES NOT ERASE NON-EMPTY VALUES
difffield = fieldnames(EEG.event);
difffield = difffield(~(strcmp(difffield,'latency')|strcmp(difffield,'epoch')|strcmp(difffield,'type')));
for index = 1:length(difffield)
tmpevent = EEG.event;
allvalues = { tmpevent.(difffield{index}) };
try
valempt = cellfun('isempty', allvalues);
catch
valempt = mycellfun('isempty', allvalues);
end;
arraytmpinfo = cell(1,EEG.trials);
% spetial case of duration
% ------------------------
if strcmp( difffield{index}, 'duration')
if any(valempt)
fprintf(['eeg_checkset: found empty values for field ''' difffield{index} ...
''' (filling with 0)\n']);
end;
for indexevent = find(valempt)
EEG.event(indexevent).duration = 0;
end;
else
% get the field content
% ---------------------
indexevent = find(~valempt);
arraytmpinfo(allepochs(indexevent)) = allvalues(indexevent);
% uniformize content for all epochs
% ---------------------------------
indexevent = find(valempt);
tmpevent = EEG.event;
[tmpevent(indexevent).(difffield{index})] = arraytmpinfo{allepochs(indexevent)};
EEG.event = tmpevent;
if any(valempt)
fprintf(['eeg_checkset: found empty values for field ''' difffield{index} '''\n']);
fprintf([' filling with values of other events in the same epochs\n']);
end;
end;
end;
end;
if isempty(EEG.event), return; end;
% uniformize fields (str or int) if necessary
% -------------------------------------------
fnames = fieldnames(EEG.event);
for fidx = 1:length(fnames)
fname = fnames{fidx};
tmpevent = EEG.event;
allvalues = { tmpevent.(fname) };
try
% find indices of numeric values among values of this event property
valreal = ~cellfun('isclass', allvalues, 'char');
catch
valreal = mycellfun('isclass', allvalues, 'double');
end;
format = 'ok';
if ~all(valreal) % all valreal ok
format = 'str';
if all(valreal == 0) % all valreal=0 ok
format = 'ok';
end;
end;
if strcmp(format, 'str')
fprintf('eeg_checkset note: value format of event field ''%s'' made uniform\n', fname);
% get the field content
% ---------------------
for indexevent = 1:length(EEG.event)
if valreal(indexevent)
EEG.event = setfield(EEG.event, { indexevent }, fname, num2str(allvalues{indexevent}) );
end;
end;
end;
end;
% check boundary events
% ---------------------
tmpevent = EEG.event;
if isfield(tmpevent, 'type') && ~isnumeric(tmpevent(1).type)
allEventTypes = { tmpevent.type };
boundsInd = strmatch('boundary', allEventTypes);
if ~isempty(boundsInd),
bounds = [ tmpevent(boundsInd).latency ];
% remove last event if necessary
if EEG.trials==1;%this if block added by James Desjardins (Jan 13th, 2014)
if round(bounds(end)-0.5+1) >= size(EEG.data,2), EEG.event(boundsInd(end)) = []; bounds(end) = []; end; % remove final boundary if any
end
% The first boundary below need to be kept for
% urevent latency calculation
% if bounds(1) < 0, EEG.event(bounds(1)) = []; end; % remove initial boundary if any
indDoublet = find(bounds(2:end)-bounds(1:end-1)==0);
if ~isempty(indDoublet)
disp('Warning: duplicate boundary event removed');
for indBound = 1:length(indDoublet)
EEG.event(boundsInd(indDoublet(indBound)+1)).duration = EEG.event(boundsInd(indDoublet(indBound)+1)).duration+EEG.event(boundsInd(indDoublet(indBound))).duration;
end;
EEG.event(boundsInd(indDoublet)) = [];
end;
end;
end;
if isempty(EEG.event), return; end;
% check that numeric format is double (Matlab 7)
% -----------------------------------
allfields = fieldnames(EEG.event);
if ~isempty(EEG.event)
for index = 1:length(allfields)
tmpval = EEG.event(1).(allfields{index});
if isnumeric(tmpval) && ~isa(tmpval, 'double')
for indexevent = 1:length(EEG.event)
tmpval = getfield(EEG.event, { indexevent }, allfields{index} );
EEG.event = setfield(EEG.event, { indexevent }, allfields{index}, double(tmpval));
end;
end;
end;
end;
% check duration field, replace empty by 0
% ----------------------------------------
if isfield(EEG.event, 'duration')
tmpevent = EEG.event;
try, valempt = cellfun('isempty' , { tmpevent.duration });
catch, valempt = mycellfun('isempty', { tmpevent.duration });
end;
if any(valempt),
for index = find(valempt)
EEG.event(index).duration = 0;
end;
end;
end;
% resort events
% -------------
if isfield(EEG.event, 'latency')
try,
if isfield(EEG.event, 'epoch')
TMPEEG = pop_editeventvals(EEG, 'sort', { 'epoch' 0 'latency' 0 });
else
TMPEEG = pop_editeventvals(EEG, 'sort', { 'latency' 0 });
end;
if ~isequal(TMPEEG.event, EEG.event)
EEG = TMPEEG;
disp('Event resorted by increasing latencies.');
end;
catch,
disp('eeg_checkset: problem when attempting to resort event latencies.');
end;
end;
% check latency of first event
% ----------------------------
if ~isempty(EEG.event)
if isfield(EEG.event, 'latency')
if EEG.event(1).latency < 0.5
EEG.event(1).latency = 0.5;
end;
end;
end;
% build epoch structure
% ---------------------
try,
if EEG.trials > 1 & ~isempty(EEG.event)
% erase existing event-related fields
% ------------------------------
if ~isfield(EEG,'epoch')
EEG.epoch = [];
end
if ~isempty(EEG.epoch)
if length(EEG.epoch) ~= EEG.trials
disp('Warning: number of epoch entries does not match number of dataset trials;');
disp(' user-defined epoch entries will be erased.');
EEG.epoch = [];
else
fn = fieldnames(EEG.epoch);
EEG.epoch = rmfield(EEG.epoch,fn(strncmp('event',fn,5)));
end
end
% set event field
% ---------------
tmpevent = EEG.event;
eventepoch = [tmpevent.epoch];
epochevent = cell(1,EEG.trials);
destdata = epochevent;
EEG.epoch(length(epochevent)).event = [];
for k=1:length(epochevent)
epochevent{k} = find(eventepoch==k);
end
tmpepoch = EEG.epoch;
[tmpepoch.event] = epochevent{:};
EEG.epoch = tmpepoch;
maxlen = max(cellfun(@length,epochevent));
% copy event information into the epoch array
% -------------------------------------------
eventfields = fieldnames(EEG.event)';
eventfields = eventfields(~strcmp(eventfields,'epoch'));
tmpevent = EEG.event;
for k = 1:length(eventfields)
fname = eventfields{k};
switch fname
case 'latency'
sourcedata = round(eeg_point2lat([tmpevent.(fname)],[tmpevent.epoch],EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3) * 10^8 )/10^8;
sourcedata = num2cell(sourcedata);
case 'duration'
sourcedata = num2cell([tmpevent.(fname)]/EEG.srate*1000);
otherwise
sourcedata = {tmpevent.(fname)};
end
if maxlen == 1
destdata = cell(1,length(epochevent));
destdata(~cellfun('isempty',epochevent)) = sourcedata([epochevent{:}]);
else
for l=1:length(epochevent)
destdata{l} = sourcedata(epochevent{l});
end
end
tmpepoch = EEG.epoch;
[tmpepoch.(['event' fname])] = destdata{:};
EEG.epoch = tmpepoch;
end
end;
catch,
errordlg2(['Warning: minor problem encountered when generating' 10 ...
'the EEG.epoch structure (used only in user scripts)']); return;
end;
case { 'loaddata' 'savedata' 'chanconsist' 'icaconsist' 'epochconsist' }, res = '';
otherwise, error('eeg_checkset: unknown option');
end;
end;
end;
res = [];
% check name consistency
% ----------------------
if ~isempty(EEG.setname)
if ~ischar(EEG.setname)
EEG.setname = '';
else
if size(EEG.setname,1) > 1
disp('eeg_checkset warning: invalid dataset name, removed');
EEG.setname = '';
end;
end;
else
EEG.setname = '';
end;
% checking history and convert if necessary
% -----------------------------------------
if isfield(EEG, 'history') & size(EEG.history,1) > 1
allcoms = cellstr(EEG.history);
EEG.history = deblank(allcoms{1});
for index = 2:length(allcoms)
EEG.history = [ EEG.history 10 deblank(allcoms{index}) ];
end;
end;
% read data if necessary
% ----------------------
if ischar(EEG.data) & nargin > 1
if strcmpi(varargin{1}, 'loaddata')
EEG.data = eeg_getdatact(EEG);
end;
end;
% save data if necessary
% ----------------------
if nargin > 1
% datfile available?
% ------------------
datfile = 0;
if isfield(EEG, 'datfile')
if ~isempty(EEG.datfile)
datfile = 1;
end;
end;
% save data
% ---------
if strcmpi(varargin{1}, 'savedata') & option_storedisk
error('eeg_checkset: cannot call savedata any more');
% the code below is deprecated
if ~ischar(EEG.data) % not already saved
disp('Writing previous dataset to disk...');
if datfile
tmpdata = reshape(EEG.data, EEG.nbchan, EEG.pnts*EEG.trials);
floatwrite( tmpdata', fullfile(EEG.filepath, EEG.datfile), 'ieee-le');
EEG.data = EEG.datfile;
end;
EEG.icaact = [];
% saving dataset
% --------------
filename = fullfile(EEG(1).filepath, EEG(1).filename);
if ~ischar(EEG.data) & option_single, EEG.data = single(EEG.data); end;
v = version;
if str2num(v(1)) >= 7, save( filename, '-v6', '-mat', 'EEG'); % Matlab 7
else save( filename, '-mat', 'EEG');
end;
if ~ischar(EEG.data), EEG.data = 'in set file'; end;
res = sprintf('%s = eeg_checkset( %s, ''savedata'');', inputname(1), inputname(1));
end;
end;
end;
% numerical format
% ----------------
if isnumeric(EEG.data)
v = version;
EEG.icawinv = double(EEG.icawinv); % required for dipole fitting, otherwise it crashes
EEG.icaweights = double(EEG.icaweights);
EEG.icasphere = double(EEG.icasphere);
if ~isempty(findstr(v, 'R11')) | ~isempty(findstr(v, 'R12')) | ~isempty(findstr(v, 'R13'))
EEG.data = double(EEG.data);
EEG.icaact = double(EEG.icaact);
else
try,
if isa(EEG.data, 'double') & option_single
EEG.data = single(EEG.data);
EEG.icaact = single(EEG.icaact);
end;
catch,
disp('WARNING: EEGLAB ran out of memory while converting dataset to single precision.');
disp(' Save dataset (preferably saving data to a separate file; see File > Memory options).');
disp(' Then reload it.');
end;
end;
end;
% verify the type of the variables
% --------------------------------
% data dimensions -------------------------
if isnumeric(EEG.data) && ~isempty(EEG.data)
if ~isequal(size(EEG.data,1), EEG.nbchan)
disp( [ 'eeg_checkset warning: number of columns in data (' int2str(size(EEG.data,1)) ...
') does not match the number of channels (' int2str(EEG.nbchan) '): corrected' ]);
res = com;
EEG.nbchan = size(EEG.data,1);
end;
if (ndims(EEG.data)) < 3 & (EEG.pnts > 1)
if mod(size(EEG.data,2), EEG.pnts) ~= 0
if popask( [ 'eeg_checkset error: the number of frames does not divide the number of columns in the data.' 10 ...
'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the command line)'])
error('eeg_checkset error: user abort');
%res = com;
%EEG.pnts = size(EEG.data,2);
%EEG = eeg_checkset(EEG);
%return;
else
res = com;
return;
%error( 'eeg_checkset error: number of points does not divide the number of columns in data');
end;
else
if EEG.trials > 1
disp( 'eeg_checkset note: data array made 3-D');
res = com;
end;
if size(EEG.data,2) ~= EEG.pnts
EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts, size(EEG.data,2)/EEG.pnts);
end;
end;
end;
% size of data -----------
if size(EEG.data,3) ~= EEG.trials
disp( ['eeg_checkset warning: 3rd dimension size of data (' int2str(size(EEG.data,3)) ...
') does not match the number of epochs (' int2str(EEG.trials) '), corrected' ]);
res = com;
EEG.trials = size(EEG.data,3);
end;
if size(EEG.data,2) ~= EEG.pnts
disp( [ 'eeg_checkset warning: number of columns in data (' int2str(size(EEG.data,2)) ...
') does not match the number of points (' int2str(EEG.pnts) '): corrected' ]);
res = com;
EEG.pnts = size(EEG.data,2);
end;
end;
% parameters consistency
% -------------------------
if round(EEG.srate*(EEG.xmax-EEG.xmin)+1) ~= EEG.pnts
fprintf( 'eeg_checkset note: upper time limit (xmax) adjusted so (xmax-xmin)*srate+1 = number of frames\n');
if EEG.srate == 0
EEG.srate = 1;
end;
EEG.xmax = (EEG.pnts-1)/EEG.srate+EEG.xmin;
res = com;
end;
% deal with event arrays
% ----------------------
if ~isfield(EEG, 'event'), EEG.event = []; res = com; end;
if ~isempty(EEG.event)
if EEG.trials > 1 & ~isfield(EEG.event, 'epoch')
if popask( [ 'eeg_checkset error: the event info structure does not contain an ''epoch'' field.' ...
'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the commandline)'])
error('eeg_checkset error(): user abort');
%res = com;
%EEG.event = [];
%EEG = eeg_checkset(EEG);
%return;
else
res = com;
return;
%error('eeg_checkset error: no epoch field in event structure');
end;
end;
else
EEG.event = [];
end;
if isempty(EEG.event)
EEG.eventdescription = {};
end;
if ~isfield(EEG, 'eventdescription') | ~iscell(EEG.eventdescription)
EEG.eventdescription = cell(1, length(fieldnames(EEG.event)));
res = com;
else
if ~isempty(EEG.event)
if length(EEG.eventdescription) > length( fieldnames(EEG.event))
EEG.eventdescription = EEG.eventdescription(1:length( fieldnames(EEG.event)));
elseif length(EEG.eventdescription) < length( fieldnames(EEG.event))
EEG.eventdescription(end+1:length( fieldnames(EEG.event))) = {''};
end;
end;
end;
% create urevent if continuous data
% ---------------------------------
%if ~isempty(EEG.event) & ~isfield(EEG, 'urevent')
% EEG.urevent = EEG.event;
% disp('eeg_checkset note: creating the original event table (EEG.urevent)');
% for index = 1:length(EEG.event)
% EEG.event(index).urevent = index;
% end;
%end;
if isfield(EEG, 'urevent') & isfield(EEG.urevent, 'urevent')
EEG.urevent = rmfield(EEG.urevent, 'urevent');
end;
% deal with epoch arrays
% ----------------------
if ~isfield(EEG, 'epoch'), EEG.epoch = []; res = com; end;
% check if only one epoch
% -----------------------
if EEG.trials == 1
if isfield(EEG.event, 'epoch')
EEG.event = rmfield(EEG.event, 'epoch'); res = com;
end;
if ~isempty(EEG.epoch)
EEG.epoch = []; res = com;
end;
end;
if ~isfield(EEG, 'epochdescription'), EEG.epochdescription = {}; res = com; end;
if ~isempty(EEG.epoch)
if isstruct(EEG.epoch), l = length( EEG.epoch);
else l = size( EEG.epoch, 2);
end;
if l ~= EEG.trials
if popask( [ 'eeg_checkset error: the number of epoch indices in the epoch array/struct (' ...
int2str(l) ') is different from the number of epochs in the data (' int2str(EEG.trials) ').' 10 ...
'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the commandline)'])
error('eeg_checkset error: user abort');
%res = com;
%EEG.epoch = [];
%EEG = eeg_checkset(EEG);
%return;
else
res = com;
return;
%error('eeg_checkset error: epoch structure size invalid');
end;
end;
else
EEG.epoch = [];
end;
% check ica
% ---------
if ~isfield(EEG, 'icachansind')
if isempty(EEG.icaweights)
EEG.icachansind = []; res = com;
else
EEG.icachansind = [1:EEG.nbchan]; res = com;
end;
elseif isempty(EEG.icachansind)
if isempty(EEG.icaweights)
EEG.icachansind = []; res = com;
else
EEG.icachansind = [1:EEG.nbchan]; res = com;
end;
end;
if ~isempty(EEG.icasphere)
if ~isempty(EEG.icaweights)
if size(EEG.icaweights,2) ~= size(EEG.icasphere,1)
if popask( [ 'eeg_checkset error: number of columns in weights array (' int2str(size(EEG.icaweights,2)) ')' 10 ...
'does not match the number of rows in the sphere array (' int2str(size(EEG.icasphere,1)) ')' 10 ...
'Should EEGLAB remove ICA information ?' 10 '(press Cancel to fix the problem from the commandline)'])
res = com;
EEG.icasphere = [];
EEG.icaweights = [];
EEG = eeg_checkset(EEG);
return;
else
error('eeg_checkset error: user abort');
res = com;
return;
%error('eeg_checkset error: invalid weight and sphere array sizes');
end;
end;
if isnumeric(EEG.data)
if length(EEG.icachansind) ~= size(EEG.icasphere,2)
if popask( [ 'eeg_checkset error: number of elements in ''icachansind'' (' int2str(length(EEG.icachansind)) ')' 10 ...
'does not match the number of columns in the sphere array (' int2str(size(EEG.icasphere,2)) ')' 10 ...
'Should EEGLAB remove ICA information ?' 10 '(press Cancel to fix the problem from the commandline)'])
res = com;
EEG.icasphere = [];
EEG.icaweights = [];
EEG = eeg_checkset(EEG);
return;
else
error('eeg_checkset error: user abort');
res = com;
return;
%error('eeg_checkset error: invalid weight and sphere array sizes');
end;
end;
if isempty(EEG.icaact) | (size(EEG.icaact,1) ~= size(EEG.icaweights,1)) | (size(EEG.icaact,2) ~= size(EEG.data,2))
EEG.icaweights = double(EEG.icaweights);
EEG.icawinv = double(EEG.icawinv);
% scale ICA components to RMS microvolt
if option_scaleicarms
if ~isempty(EEG.icawinv)
if mean(mean(abs(pinv(EEG.icaweights * EEG.icasphere)-EEG.icawinv))) < 0.0001
disp('Scaling components to RMS microvolt');
scaling = repmat(sqrt(mean(EEG(1).icawinv(:,:).^2))', [1 size(EEG.icaweights,2)]);
EEG.etc.icaweights_beforerms = EEG.icaweights;
EEG.etc.icasphere_beforerms = EEG.icasphere;
EEG.icaweights = EEG.icaweights .* scaling;
EEG.icawinv = pinv(EEG.icaweights * EEG.icasphere);
end;
end;
end;
if ~isempty(EEG.data) && option_computeica
fprintf('eeg_checkset: recomputing the ICA activation matrix ...\n');
res = com;
% Make compatible with Matlab 7
if any(isnan(EEG.data(:)))
tmpdata = EEG.data(EEG.icachansind,:);
fprintf('eeg_checkset: recomputing ICA ignoring NaN indices ...\n');
tmpindices = find(~sum(isnan(tmpdata))); % was: tmpindices = find(~isnan(EEG.data(1,:)));
EEG.icaact = zeros(size(EEG.icaweights,1), size(tmpdata,2)); EEG.icaact(:) = NaN;
EEG.icaact(:,tmpindices) = (EEG.icaweights*EEG.icasphere)*tmpdata(:,tmpindices);
else
EEG.icaact = (EEG.icaweights*EEG.icasphere)*EEG.data(EEG.icachansind,:); % automatically does single or double
end;
EEG.icaact = reshape( EEG.icaact, size(EEG.icaact,1), EEG.pnts, EEG.trials);
end;
end;
end;
if isempty(EEG.icawinv)
EEG.icawinv = pinv(EEG.icaweights*EEG.icasphere); % a priori same result as inv
res = com;
end;
else
disp( [ 'eeg_checkset warning: weights matrix cannot be empty if sphere matrix is not, correcting ...' ]);
res = com;
EEG.icasphere = [];
end;
if option_computeica
if ~isempty(EEG.icaact) & ndims(EEG.icaact) < 3 & (EEG.trials > 1)
disp( [ 'eeg_checkset note: independent component made 3-D' ]);
res = com;
EEG.icaact = reshape(EEG.icaact, size(EEG.icaact,1), EEG.pnts, EEG.trials);
end;
else
if ~isempty(EEG.icaact)
fprintf('eeg_checkset: removing ICA activation matrix (as per edit options) ...\n');
end;
EEG.icaact = [];
end;
else
if ~isempty( EEG.icaweights ), EEG.icaweights = []; res = com; end;
if ~isempty( EEG.icawinv ), EEG.icawinv = []; res = com; end;
if ~isempty( EEG.icaact ), EEG.icaact = []; res = com; end;
end;
if isempty(EEG.icaact)
EEG.icaact = [];
end;
% -------------
% check chanlocs
% -------------
if ~isfield(EEG, 'chaninfo')
EEG.chaninfo = [];
end;
if ~isempty( EEG.chanlocs )
% reference (use EEG structure)
% ---------
if ~isfield(EEG, 'ref'), EEG.ref = ''; end;
if strcmpi(EEG.ref, 'averef')
ref = 'average';
else ref = '';
end;
if ~isfield( EEG.chanlocs, 'ref')
EEG.chanlocs(1).ref = ref;
end;
charrefs = cellfun('isclass',{EEG.chanlocs.ref},'char');
if any(charrefs) ref = ''; end
for tmpind = find(~charrefs)
EEG.chanlocs(tmpind).ref = ref;
end
if ~isstruct( EEG.chanlocs)
if exist( EEG.chanlocs ) ~= 2
disp( [ 'eeg_checkset warning: channel file does not exist or is not in Matlab path: filename removed from EEG struct' ]);
EEG.chanlocs = [];
res = com;
else
res = com;
try, EEG.chanlocs = readlocs( EEG.chanlocs );
disp( [ 'eeg_checkset: channel file read' ]);
catch, EEG.chanlocs = []; end;
end;
else
if ~isfield(EEG.chanlocs,'labels')
disp('eeg_checkset warning: no field label in channel location structure, removing it');
EEG.chanlocs = [];
res = com;
end;
end;
if isstruct( EEG.chanlocs)
if length( EEG.chanlocs) ~= EEG.nbchan && length( EEG.chanlocs) ~= EEG.nbchan+1 && ~isempty(EEG.data)
disp( [ 'eeg_checkset warning: number of channels different in data and channel file/struct: channel file/struct removed' ]);
EEG.chanlocs = [];
res = com;
end;
end;
% force Nosedir to +X (done here because of DIPFIT)
% -------------------
if isfield(EEG.chaninfo, 'nosedir')
if strcmpi(EEG.chaninfo.nosedir, '+x')
rotate = 0;
elseif all(isfield(EEG.chanlocs,{'X','Y','theta','sph_theta'}))
disp('EEG checkset note for expert users: Noze direction now set to default +X in EEG.chanlocs and EEG.dipfit.');
if strcmpi(EEG.chaninfo.nosedir, '+y')
rotate = 270;
elseif strcmpi(EEG.chaninfo.nosedir, '-x')
rotate = 180;
else rotate = 90;
end;
for index = 1:length(EEG.chanlocs)
if ~isempty(EEG.chanlocs(index).theta)
rotategrad = rotate/180*pi;
coord = (EEG.chanlocs(index).Y + EEG.chanlocs(index).X*sqrt(-1))*exp(sqrt(-1)*-rotategrad);
EEG.chanlocs(index).Y = real(coord);
EEG.chanlocs(index).X = imag(coord);
EEG.chanlocs(index).theta = EEG.chanlocs(index).theta -rotate;
EEG.chanlocs(index).sph_theta = EEG.chanlocs(index).sph_theta+rotate;
if EEG.chanlocs(index).theta <-180, EEG.chanlocs(index).theta =EEG.chanlocs(index).theta +360; end;
if EEG.chanlocs(index).sph_theta>180 , EEG.chanlocs(index).sph_theta=EEG.chanlocs(index).sph_theta-360; end;
end;
end;
if isfield(EEG, 'dipfit')
if isfield(EEG.dipfit, 'coord_transform')
if isempty(EEG.dipfit.coord_transform)
EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1];
end;
EEG.dipfit.coord_transform(6) = EEG.dipfit.coord_transform(6)+rotategrad;
end;
end;
end;
EEG.chaninfo.nosedir = '+X';
end;
% general checking of channels
% ----------------------------
EEG = eeg_checkchanlocs(EEG);
if EEG.nbchan ~= length(EEG.chanlocs)
EEG.chanlocs = [];
EEG.chaninfo = [];
disp('Warning: the size of the channel location structure does not match with');
disp(' number of channels. Channel information have been removed.');
end;
end;
EEG.chaninfo.icachansind = EEG.icachansind; % just a copy for programming convinience
%if ~isfield(EEG, 'urchanlocs')
% EEG.urchanlocs = EEG.chanlocs;
% for index = 1:length(EEG.chanlocs)
% EEG.chanlocs(index).urchan = index;
% end;
% disp('eeg_checkset note: creating backup chanlocs structure (urchanlocs)');
%end;
% check reference
% ---------------
if ~isfield(EEG, 'ref')
EEG.ref = 'common';
end;
if ischar(EEG.ref) & strcmpi(EEG.ref, 'common')
if length(EEG.chanlocs) > EEG.nbchan
disp('Extra common reference electrode location detected');
EEG.ref = EEG.nbchan+1;
end;
end;
% DIPFIT structure
% ----------------
if ~isfield(EEG,'dipfit') || isempty(EEG.dipfit)
EEG.dipfit = []; res = com;
else
try
% check if dipfitdefs is present
dipfitdefs;
if isfield(EEG.dipfit, 'vol') & ~isfield(EEG.dipfit, 'hdmfile')
if exist('pop_dipfit_settings')
disp('Old DIPFIT structure detected: converting to DIPFIT 2 format');
EEG.dipfit.hdmfile = template_models(1).hdmfile;
EEG.dipfit.coordformat = template_models(1).coordformat;
EEG.dipfit.mrifile = template_models(1).mrifile;
EEG.dipfit.chanfile = template_models(1).chanfile;
EEG.dipfit.coord_transform = [];
EEG.saved = 'no';
res = com;
end;
end;
if isfield(EEG.dipfit, 'hdmfile')
if length(EEG.dipfit.hdmfile) > 8
if strcmpi(EEG.dipfit.hdmfile(end-8), template_models(1).hdmfile(end-8)), EEG.dipfit.hdmfile = template_models(1).hdmfile; end;
if strcmpi(EEG.dipfit.hdmfile(end-8), template_models(2).hdmfile(end-8)), EEG.dipfit.hdmfile = template_models(2).hdmfile; end;
end;
if length(EEG.dipfit.mrifile) > 8
if strcmpi(EEG.dipfit.mrifile(end-8), template_models(1).mrifile(end-8)), EEG.dipfit.mrifile = template_models(1).mrifile; end;
if strcmpi(EEG.dipfit.mrifile(end-8), template_models(2).mrifile(end-8)), EEG.dipfit.mrifile = template_models(2).mrifile; end;
end;
if length(EEG.dipfit.chanfile) > 8
if strcmpi(EEG.dipfit.chanfile(end-8), template_models(1).chanfile(end-8)), EEG.dipfit.chanfile = template_models(1).chanfile; end;
if strcmpi(EEG.dipfit.chanfile(end-8), template_models(2).chanfile(end-8)), EEG.dipfit.chanfile = template_models(2).chanfile; end;
end;
end;
if isfield(EEG.dipfit, 'coord_transform')
if isempty(EEG.dipfit.coord_transform)
EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1];
end;
elseif ~isempty(EEG.dipfit)
EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1];
end;
catch
e = lasterror;
if ~strcmp(e.identifier,'MATLAB:UndefinedFunction')
% if we got some error aside from dipfitdefs not being present, rethrow it
rethrow(e);
end
end
end;
% check events (fast)
% ------------
if isfield(EEG.event, 'type')
tmpevent = EEG.event(1:min(length(EEG.event), 100));
if ~all(cellfun(@ischar, { tmpevent.type })) && ~all(cellfun(@isnumeric, { tmpevent.type }))
disp('Warning: converting all event types to strings');
for ind = 1:length(EEG.event)
EEG.event(ind).type = num2str(EEG.event(ind).type);
end;
EEG = eeg_checkset(EEG, 'eventconsistency');
end;
end;
% EEG.times (only for epoched datasets)
% ---------
if ~isfield(EEG, 'times') || isempty(EEG.times) || length(EEG.times) ~= EEG.pnts
EEG.times = linspace(EEG.xmin*1000, EEG.xmax*1000, EEG.pnts);
end;
if ~isfield(EEG, 'history') EEG.history = ''; res = com; end;
if ~isfield(EEG, 'splinefile') EEG.splinefile = ''; res = com; end;
if ~isfield(EEG, 'icasplinefile') EEG.icasplinefile = ''; res = com; end;
if ~isfield(EEG, 'saved') EEG.saved = 'no'; res = com; end;
if ~isfield(EEG, 'subject') EEG.subject = ''; res = com; end;
if ~isfield(EEG, 'condition') EEG.condition = ''; res = com; end;
if ~isfield(EEG, 'group') EEG.group = ''; res = com; end;
if ~isfield(EEG, 'session') EEG.session = []; res = com; end;
if ~isfield(EEG, 'urchanlocs') EEG.urchanlocs = []; res = com; end;
if ~isfield(EEG, 'specdata') EEG.specdata = []; res = com; end;
if ~isfield(EEG, 'specicaact') EEG.specicaact = []; res = com; end;
if ~isfield(EEG, 'comments') EEG.comments = ''; res = com; end;
if ~isfield(EEG, 'etc' ) EEG.etc = []; res = com; end;
if ~isfield(EEG, 'urevent' ) EEG.urevent = []; res = com; end;
if ~isfield(EEG, 'ref') | isempty(EEG.ref) EEG.ref = 'common'; res = com; end;
% create fields if absent
% -----------------------
if ~isfield(EEG, 'reject') EEG.reject.rejjp = []; res = com; end;
listf = { 'rejjp' 'rejkurt' 'rejmanual' 'rejthresh' 'rejconst', 'rejfreq' ...
'icarejjp' 'icarejkurt' 'icarejmanual' 'icarejthresh' 'icarejconst', 'icarejfreq'};
for index = 1:length(listf)
name = listf{index};
elecfield = [name 'E'];
if ~isfield(EEG.reject, elecfield), EEG.reject.(elecfield) = []; res = com; end;
if ~isfield(EEG.reject, name)
EEG.reject.(name) = [];
res = com;
elseif ~isempty(EEG.reject.(name)) && isempty(EEG.reject.(elecfield))
% check if electrode array is empty with rejection array is not
nbchan = fastif(strcmp(name, 'ica'), size(EEG.icaweights,1), EEG.nbchan);
EEG.reject = setfield(EEG.reject, elecfield, zeros(nbchan, length(getfield(EEG.reject, name)))); res = com;
end;
end;
if ~isfield(EEG.reject, 'rejglobal') EEG.reject.rejglobal = []; res = com; end;
if ~isfield(EEG.reject, 'rejglobalE') EEG.reject.rejglobalE = []; res = com; end;
% check event consistency based on bug 1971
% -----------------------------------------
if ~isfield(EEG.etc, 'eeglabvers') % this means modified by earlier version of EEGLAB
bugstring = { 'EEG = eeg_eegrej( EEG, [1 ' ...
'EEG = eeg_eegrej( EEG, [0 ' ...
'EEG = pop_select( EEG,''notime'',[0 ' ...
'EEG = pop_select( EEG,''nopoint'',[1 ' ...
'EEG = pop_select( EEG,''time'',[' ...
'EEG = pop_select( EEG,''point'',[' };
strind = [];
for iBug = 1:length(bugstring)
strindtmp = strfind(EEG.history, bugstring{iBug});
if ~isempty(strindtmp) && (iBug == 5 || iBug == 6)
for iStr = length(strindtmp):-1:1
tmpstr = EEG.history(strindtmp(iStr)+length(bugstring{iBug}):end);
firstspace = find(tmpstr == ' ');
tmpstr = tmpstr(1:firstspace(1)); % get first value for rejected data
if str2double(tmpstr) == 0 && iBug == 5, strindtmp(iStr) = []; end; % time starting with 0 (no bug here)
if str2double(tmpstr) == 1 && iBug == 6, strindtmp(iStr) = []; end; % point starting with 1 (no bug here)
end;
end;
strind = [ strind strindtmp(:)' ];
end;
if any(strind)
warndlg2([ 'NOTICE: ACCORDING TO THIS DATASET''S HISTORY, SINCE YOU REJECTED THE BEGINNING' 10 ...
'OF THE DATA IN A PREVIOUS EEGLAB VERSION, EVENTS RECORDS IN THIS DATASET HAVE' 10 ...
'BEEN CORRUPTED. YOU MUST GO BACK TO THE CONTINUOUS DATA AND REPROCESS THIS' 10 ...
'DATASET. FOR MORE INFORMATION SEE https://sccn.ucsd.edu/wiki/EEGLAB_bug1971' ]);
end;
end;
tmpvers = eeg_getversion;
if ~isfield(EEG.etc, 'eeglabvers') || ~isequal(EEG.etc.eeglabvers, tmpvers)
EEG.etc.eeglabvers = tmpvers;
EEG = eeg_hist( EEG, ['EEG.etc.eeglabvers = ''' tmpvers '''; % this tracks which version of EEGLAB is being used, you may ignore it'] );
res = com;
end;
% default colors for rejection
% ----------------------------
if ~isfield(EEG.reject, 'rejmanualcol') EEG.reject.rejmanualcol = [1.0000 1 0.783]; res = com; end;
if ~isfield(EEG.reject, 'rejthreshcol') EEG.reject.rejthreshcol = [0.8487 1.0000 0.5008]; res = com; end;
if ~isfield(EEG.reject, 'rejconstcol') EEG.reject.rejconstcol = [0.6940 1.0000 0.7008]; res = com; end;
if ~isfield(EEG.reject, 'rejjpcol') EEG.reject.rejjpcol = [1.0000 0.6991 0.7537]; res = com; end;
if ~isfield(EEG.reject, 'rejkurtcol') EEG.reject.rejkurtcol = [0.6880 0.7042 1.0000]; res = com; end;
if ~isfield(EEG.reject, 'rejfreqcol') EEG.reject.rejfreqcol = [0.9596 0.7193 1.0000]; res = com; end;
if ~isfield(EEG.reject, 'disprej') EEG.reject.disprej = { }; end;
if ~isfield(EEG, 'stats') EEG.stats.jp = []; res = com; end;
if ~isfield(EEG.stats, 'jp') EEG.stats.jp = []; res = com; end;
if ~isfield(EEG.stats, 'jpE') EEG.stats.jpE = []; res = com; end;
if ~isfield(EEG.stats, 'icajp') EEG.stats.icajp = []; res = com; end;
if ~isfield(EEG.stats, 'icajpE') EEG.stats.icajpE = []; res = com; end;
if ~isfield(EEG.stats, 'kurt') EEG.stats.kurt = []; res = com; end;
if ~isfield(EEG.stats, 'kurtE') EEG.stats.kurtE = []; res = com; end;
if ~isfield(EEG.stats, 'icakurt') EEG.stats.icakurt = []; res = com; end;
if ~isfield(EEG.stats, 'icakurtE') EEG.stats.icakurtE = []; res = com; end;
% component rejection
% -------------------
if ~isfield(EEG.stats, 'compenta') EEG.stats.compenta = []; res = com; end;
if ~isfield(EEG.stats, 'compentr') EEG.stats.compentr = []; res = com; end;
if ~isfield(EEG.stats, 'compkurta') EEG.stats.compkurta = []; res = com; end;
if ~isfield(EEG.stats, 'compkurtr') EEG.stats.compkurtr = []; res = com; end;
if ~isfield(EEG.stats, 'compkurtdist') EEG.stats.compkurtdist = []; res = com; end;
if ~isfield(EEG.reject, 'threshold') EEG.reject.threshold = [0.8 0.8 0.8]; res = com; end;
if ~isfield(EEG.reject, 'threshentropy') EEG.reject.threshentropy = 600; res = com; end;
if ~isfield(EEG.reject, 'threshkurtact') EEG.reject.threshkurtact = 600; res = com; end;
if ~isfield(EEG.reject, 'threshkurtdist') EEG.reject.threshkurtdist = 600; res = com; end;
if ~isfield(EEG.reject, 'gcompreject') EEG.reject.gcompreject = []; res = com; end;
if length(EEG.reject.gcompreject) ~= size(EEG.icaweights,1)
EEG.reject.gcompreject = zeros(1, size(EEG.icaweights,1));
end;
% remove old fields
% -----------------
if isfield(EEG, 'averef'), EEG = rmfield(EEG, 'averef'); end;
if isfield(EEG, 'rt' ), EEG = rmfield(EEG, 'rt'); end;
% store in new structure
% ----------------------
if isstruct(EEG)
if ~exist('ALLEEGNEW','var')
ALLEEGNEW = EEG;
else
ALLEEGNEW(inddataset) = EEG;
end;
end;
end;
% recorder fields
% ---------------
fieldorder = { 'setname' ...
'filename' ...
'filepath' ...
'subject' ...
'group' ...
'condition' ...
'session' ...
'comments' ...
'nbchan' ...
'trials' ...
'pnts' ...
'srate' ...
'xmin' ...
'xmax' ...
'times' ...
'data' ...
'icaact' ...
'icawinv' ...
'icasphere' ...
'icaweights' ...
'icachansind' ...
'chanlocs' ...
'urchanlocs' ...
'chaninfo' ...
'ref' ...
'event' ...
'urevent' ...
'eventdescription' ...
'epoch' ...
'epochdescription' ...
'reject' ...
'stats' ...
'specdata' ...
'specicaact' ...
'splinefile' ...
'icasplinefile' ...
'dipfit' ...
'history' ...
'saved' ...
'etc' };
for fcell = fieldnames(EEG)'
fname = fcell{1};
if ~any(strcmp(fieldorder,fname))
fieldorder{end+1} = fname;
end
end
try
ALLEEGNEW = orderfields(ALLEEGNEW, fieldorder);
EEG = ALLEEGNEW;
catch
disp('Couldn''t order data set fields properly.');
end;
if exist('ALLEEGNEW','var')
EEG = ALLEEGNEW;
end;
if ~isa(EEG, 'eegobj') && option_eegobject
EEG = eegobj(EEG);
end;
return;
function num = popask( text )
ButtonName=questdlg2( text, ...
'Confirmation', 'Cancel', 'Yes','Yes');
switch lower(ButtonName),
case 'cancel', num = 0;
case 'yes', num = 1;
end;
function res = mycellfun(com, vals, classtype);
res = zeros(1, length(vals));
switch com
case 'isempty',
for index = 1:length(vals), res(index) = isempty(vals{index}); end;
case 'isclass'
if strcmp(classtype, 'double')
for index = 1:length(vals), res(index) = isnumeric(vals{index}); end;
else
error('unknown cellfun command');
end;
otherwise error('unknown cellfun command');
end;
|
github
|
lcnhappe/happe-master
|
ismember_bc.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/ismember_bc.m
| 711 |
utf_8
|
565a06126820e316b2bf233d652bf24c
|
% ismember_bc - ismember backward compatible with Matlab versions prior to 2013a
function [C,IA] = ismember_bc(A,B,varargin);
errorFlag = error_bc;
v = version;
indp = find(v == '.');
v = str2num(v(1:indp(2)-1));
if v > 7.19, v = floor(v) + rem(v,1)/10; end;
if nargin > 2
ind = strmatch('legacy', varargin);
if ~isempty(ind)
varargin(ind) = [];
end;
end;
if v >= 7.14
[C,IA] = ismember(A,B,varargin{:},'legacy');
if errorFlag
[C2,IA2] = ismember(A,B,varargin{:});
if (~isequal(C, C2) || ~isequal(IA, IA2))
warning('backward compatibility issue with call to ismember function');
end;
end;
else
[C,IA] = ismember(A,B,varargin{:});
end;
|
github
|
lcnhappe/happe-master
|
intersect_bc.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/intersect_bc.m
| 752 |
utf_8
|
72bc774f899f5fb5e3b75d2c1ef99049
|
% intersect_bc - intersect backward compatible with Matlab versions prior to 2013a
function [C,IA,IB] = intersect_bc(A,B,varargin);
errorFlag = error_bc;
v = version;
indp = find(v == '.');
v = str2num(v(1:indp(2)-1));
if v > 7.19, v = floor(v) + rem(v,1)/10; end;
if nargin > 2
ind = strmatch('legacy', varargin);
if ~isempty(ind)
varargin(ind) = [];
end;
end;
if v >= 7.14
[C,IA,IB] = intersect(A,B,varargin{:},'legacy');
if errorFlag
[C2,IA2,IB2] = intersect(A,B,varargin{:});
if (~isequal(C, C2) || ~isequal(IA, IA2) || ~isequal(IB, IB2))
warning('backward compatibility issue with call to intersect function');
end;
end;
else
[C,IA,IB] = intersect(A,B,varargin{:});
end;
|
github
|
lcnhappe/happe-master
|
plugin_getweb.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/plugin_getweb.m
| 6,337 |
utf_8
|
d6ad7bd9e33713cfe1317b4e55cd3c3f
|
function plugin = plugin_getweb(type, pluginOri, mode)
if nargin < 1, help plugin_getweb; return; end;
if nargin < 2, pluginOri = []; end;
if nargin < 3, mode = 'merge'; end; % 'merge' or 'newlist'
% convert plugin list format if necessary
if isfield(pluginOri, 'plugin'), pluginOri = plugin_convert(pluginOri); end;
try
disp( [ 'Retreiving URL with ' type ' extensions...' ] );
if strcmpi(type, 'import')
[tmp status] = plugin_urlread('http://sccn.ucsd.edu/wiki/Plugin_list_import');
else
[tmp status] = plugin_urlread('http://sccn.ucsd.edu/wiki/Plugin_list_process');
end;
catch,
error('Cannot connect to the Internet to retrieve extension list');
end;
% retreiving download statistics
try
disp( [ 'Retreiving download statistics...' ] );
[stats status] = plugin_urlread('http://sccn.ucsd.edu/eeglab/plugin_uploader/plugin_getcountall.php');
stats = textscan(stats, '%s%d%s%s');
catch,
stats = {};
disp('Cannot connect to the Internet to retrieve statistics for extensions');
end;
if status == 0
error('Cannot connect to the Internet to retrieve extension list');
end;
% parse the web page
% ------------------
try
plugin = parseTable(tmp);
catch
error('Cannot parse extension list - please contact [email protected]');
end;
% find correspondance with plugin list
% ------------------------------------
if ~isempty(pluginOri)
currentNames = lower({ pluginOri.name });
else currentNames = {};
end;
allMatch = [];
for iRow = 1:length(plugin)
% fix links
if isfield(plugin, 'zip'), plugin(iRow).zip = strrep(plugin(iRow).zip, '&', '&'); end;
% get number of downloads
if ~isempty(stats)
indMatch = strmatch(plugin(iRow).name, stats{1}, 'exact');
if ~isempty(indMatch)
plugin(iRow).downloads = stats{2}(indMatch(1));
if length(stats) > 2 && ~isempty(stats{3}{indMatch(1)})
plugin(iRow).version = stats{3}{indMatch(1)};
plugin(iRow).zip = stats{4}{indMatch(1)};
end;
else plugin(iRow).downloads = 0;
end;
else plugin(iRow).downloads = 0;
end;
% match with existiting plugins
indMatch = strmatch(lower(plugin(iRow).name), currentNames, 'exact');
if isempty(indMatch)
plugin(iRow).currentversion = '-';
plugin(iRow).installed = 0;
plugin(iRow).installorupdate = 1;
plugin(iRow).status = 'notinstalled';
else
if length(indMatch) > 1
disp([ 'Warning: duplicate extension ' plugin(iRow).name ' instaled' ]);
end;
plugin(iRow).currentversion = pluginOri(indMatch).currentversion;
plugin(iRow).foldername = pluginOri(indMatch).foldername;
plugin(iRow).status = pluginOri(indMatch).status;
plugin(iRow).installed = 1;
if strcmpi(plugin(iRow).currentversion, plugin(iRow).version)
plugin(iRow).installorupdate = 0;
else
plugin(iRow).installorupdate = 1;
end;
allMatch = [ allMatch indMatch(:)' ];
end;
end;
% put all the installed plugins first
% -----------------------------------
if ~isempty(plugin)
[tmp reorder] = sort([plugin.installed], 'descend');
plugin = plugin(reorder);
% plugin(1).currentversion = '0.9';
% plugin(1).version = '1';
% plugin(1).foldername = 'test';
% plugin(1).installed = 1;
% plugin(1).installorupdate = 1;
% plugin(1).description = 'test';
% plugin(1).webdoc = 'test';
% plugin(1).name = 'test';
end;
if strcmpi(mode, 'merge') && ~isempty(pluginOri)
indices = setdiff([1:length(pluginOri)], allMatch);
fields = fieldnames(pluginOri);
lenPlugin = length(plugin);
for indPlugin = 1:length(indices)
for indField = 1:length(fields)
value = getfield(pluginOri, { indices(indPlugin) }, fields{ indField });
plugin = setfield(plugin , { lenPlugin+indPlugin }, fields{ indField }, value);
end;
end;
end;
% parse the web table
% ===================
function plugin = parseTable(tmp);
plugin = [];
if isempty(tmp), return; end;
% get table content
% -----------------
tableBeg = findstr('Plug-in name', tmp);
tableEnd = findstr('</table>', tmp(tableBeg:end));
tableContent = tmp(tableBeg:tableBeg+tableEnd-2);
endFirstLine = findstr('</tr>', tableContent);
tableContent = tableContent(endFirstLine(1)+5:end);
% parse table entries
% -------------------
posBegRow = findstr('<tr>' , tableContent);
posEndRow = findstr('</tr>', tableContent);
if length(posBegRow) ~= length(posEndRow) || isempty(posBegRow)
error('Cannot connect to the Internet to retrieve plugin list');
end;
for iRow = 1:length(posBegRow)
rowContent = tableContent(posBegRow(iRow)+4:posEndRow(iRow)-1);
posBegCol = findstr('<td>' , rowContent);
posEndCol = findstr('</td>', rowContent);
for iCol = 1:length(posBegCol)
table{iRow,iCol} = rowContent(posBegCol(iCol)+4:posEndCol(iCol)-1);
end;
end;
%% extract zip link and plugin name from first column
% --------------------------------------------------
%href="http://www.unicog.org/pm/uploads/MEG/ADJUST_PLUGIN.zip" class="external text" title="http://www.unicog.org/pm/uploads/MEG/ADJUST_PLUGIN.zip" rel="nofollow">ADJUST PLUGIN</a></td
for iRow = 1:size(table,1)
% get link
[plugin(iRow).name plugin(iRow).webdoc] = parsehttplink(table{iRow,1});
plugin(iRow).version = table{iRow,2};
tmp = deblank(table{iRow,3}(end:-1:1));
plugin(iRow).description = deblank(tmp(end:-1:1));
[tmp plugin(iRow).zip] = parsehttplink(table{iRow,4});
end;
function [txt link] = parsehttplink(currentRow)
openTag = find(currentRow == '<');
closeTag = find(currentRow == '>');
if isempty(openTag)
link = '';
txt = currentRow;
else
% parse link
link = currentRow(openTag(1)+1:closeTag(1)-1);
hrefpos = findstr('href', link);
link = link(hrefpos:end);
quoteInd = find(link == '"');
link = link(quoteInd(1)+1:quoteInd(2)-1);
for iTag = length(openTag):-1:1
currentRow(openTag(iTag):closeTag(iTag)) = [];
end;
txt = currentRow;
end;
|
github
|
lcnhappe/happe-master
|
eeg_checkchanlocs.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/eeg_checkchanlocs.m
| 8,655 |
utf_8
|
2664c683e10493731ebda7dfec52968f
|
% eeg_checkchanlocs() - Check the consistency of the channel locations structure
% of an EEGLAB dataset.
%
% Usage:
% >> EEG = eeg_checkchanlocs( EEG, 'key1', value1, 'key2', value2, ... );
% >> [chanlocs chaninfo] = eeg_checkchanlocs( chanlocs, chaninfo, 'key1', value1, 'key2', value2, ... );
%
% Inputs:
% EEG - EEG dataset
% chanlocs - EEG.chanlocs structure
% chaninfo - EEG.chaninfo structure
%
% Outputs:
% EEG - new EEGLAB dataset with updated channel location structures
% EEG.chanlocs, EEG.urchanlocs, EEG.chaninfo
% chanlocs - updated channel location structure
% chaninfo - updated chaninfo structure
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, March 2, 2011
% Copyright (C) SCCN/INC/UCSD, March 2, 2011, [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
% Hey Arno -- this is a quick fix to make an analysis work for Makoto
% I think the old version had a bug...
function [chans, chaninfo, chanedit]= eeg_checkchanlocs(chans, chaninfo);
if nargin < 1
help eeg_checkchanlocs;
return;
end;
if nargin < 2
chaninfo = [];
end;
processingEEGstruct = 0;
if isfield(chans, 'data')
processingEEGstruct = 1;
tmpEEG = chans;
chans = tmpEEG.chanlocs;
chaninfo = tmpEEG.chaninfo;
end;
if ~isfield(chans, 'datachan')
[chanedit,dummy,complicated] = insertchans(chans, chaninfo);
else
chanedit = chans;
complicated = true;
end;
nosevals = { '+X' '-X' '+Y' '-Y' };
if ~isfield(chaninfo, 'plotrad'), chaninfo.plotrad = []; end;
if ~isfield(chaninfo, 'shrink'), chaninfo.shrink = []; end;
if ~isfield(chaninfo, 'nosedir'), chaninfo.nosedir = nosevals{1}; end;
% handles deprecated fields
% -------------------------
plotrad = [];
if isfield(chanedit, 'plotrad'),
plotrad = chanedit(1).plotrad;
chanedit = rmfield(chanedit, 'plotrad');
if isstr(plotrad) & ~isempty(str2num(plotrad)), plotrad = str2num(plotrad); end;
chaninfo.plotrad = plotrad;
end;
if isfield(chanedit, 'shrink') && ~isempty(chanedit(1).shrink)
shrinkorskirt = 1;
if ~isstr(chanedit(1).shrink)
plotrad = 0.5/(1-chanedit(1).shrink); % convert old values
end;
chanedit = rmfield(chanedit, 'shrink');
chaninfo.plotrad = plotrad;
end;
% set non-existent fields to []
% -----------------------------
fields = { 'labels' 'theta' 'radius' 'X' 'Y' 'Z' 'sph_theta' 'sph_phi' 'sph_radius' 'type' 'ref' 'urchan' };
fieldtype = { 'str' 'num' 'num' 'num' 'num' 'num' 'num' 'num' 'num' 'str' 'str' 'num' };
check_newfields = true; %length(fieldnames(chanedit)) < length(fields);
if ~isempty(chanedit)
for index = 1:length(fields)
if check_newfields && ~isfield(chanedit, fields{index})
% new field
% ---------
if strcmpi(fieldtype{index}, 'num')
chanedit = setfield(chanedit, {1}, fields{index}, []);
else
for indchan = 1:length(chanedit)
chanedit = setfield(chanedit, {indchan}, fields{index}, '');
end;
end;
else
% existing fields
% ---------------
allvals = {chanedit.(fields{index})};
if strcmpi(fieldtype{index}, 'num')
if ~all(cellfun('isclass',allvals,'double'))
numok = cellfun(@isnumeric, allvals);
if any(numok == 0)
for indConvert = find(numok == 0)
chanedit = setfield(chanedit, {indConvert}, fields{index}, []);
end;
end;
end
else
strok = cellfun('isclass', allvals,'char');
if strcmpi(fields{index}, 'labels'), prefix = 'E'; else prefix = ''; end;
if any(strok == 0)
for indConvert = find(strok == 0)
try
strval = [ prefix num2str(getfield(chanedit, {indConvert}, fields{index})) ];
chanedit = setfield(chanedit, {indConvert}, fields{index}, strval);
catch
chanedit = setfield(chanedit, {indConvert}, fields{index}, '');
end;
end;
end;
end;
end;
end;
end;
if ~isequal(fieldnames(chanedit)',fields)
try
chanedit = orderfields(chanedit, fields);
catch, end;
end
% check if duplicate channel label
% --------------------------------
if isfield(chanedit, 'labels')
tmp = sort({chanedit.labels});
if any(strcmp(tmp(1:end-1),tmp(2:end)))
disp('Warning: some channels have the same label');
end
end;
% check for empty channel label
% -----------------------------
if isfield(chanedit, 'labels')
indEmpty = find(cellfun(@isempty, {chanedit.labels}));
if ~isempty(indEmpty)
tmpWarning = warning('backtrace');
warning backtrace off;
warning('channel labels should not be empty, creating unique labels');
warning(tmpWarning);
for index = indEmpty
chanedit(index).labels = sprintf('E%d', index);
end;
end;
end;
% remove fields
% -------------
if isfield(chanedit, 'sph_phi_besa' ), chanedit = rmfield(chanedit, 'sph_phi_besa'); end;
if isfield(chanedit, 'sph_theta_besa'), chanedit = rmfield(chanedit, 'sph_theta_besa'); end;
% reconstruct the chans structure
% -------------------------------
if complicated
[chans chaninfo.nodatchans] = getnodatchan( chanedit );
if ~isfield(chaninfo, 'nodatchans'), chaninfo.nodatchans = []; end;
if isempty(chanedit)
for iField = 1:length(fields)
chanedit = setfield(chanedit, fields{iField}, []);
end;
end;
else
chans = rmfield(chanedit,'datachan');
chaninfo.nodatchans = [];
end
if processingEEGstruct
tmpEEG.chanlocs = chans;
tmpEEG.chaninfo = chaninfo;
chans = tmpEEG;
end;
% ---------------------------------------------
% separate data channels from non-data channels
% ---------------------------------------------
function [chans, fidsval] = getnodatchan(chans)
if isfield(chans,'datachan')
[chans(cellfun('isempty',{chans.datachan})).datachan] = deal(0);
fids = [chans.datachan] == 0;
fidsval = chans(fids);
chans = rmfield(chans(~fids),'datachan');
else
fids = [];
end;
% ----------------------------------------
% fuse data channels and non-data channels
% ----------------------------------------
function [chans, chaninfo,complicated] = insertchans(chans, chaninfo, nchans)
if nargin < 3, nchans = length(chans); end;
[chans.datachan] = deal(1);
complicated = false; % whether we need complicated treatment of datachans & co further down the road.....
if isfield(chans,'type')
mask = strcmpi({chans.type},'FID') | strcmpi({chans.type},'IGNORE');
if any(mask)
[chans(mask).datachan] = deal(0);
complicated = true;
end
end
if length(chans) > nchans & nchans ~= 0 % reference at the end of the structure
chans(end).datachan = 0;
complicated = true;
end;
if isfield(chaninfo, 'nodatchans')
if ~isempty(chaninfo.nodatchans) && isstruct(chaninfo.nodatchans)
chanlen = length(chans);
for index = 1:length(chaninfo.nodatchans)
fields = fieldnames( chaninfo.nodatchans );
ind = chanlen+index;
for f = 1:length( fields )
chans = setfield(chans, { ind }, fields{f}, getfield( chaninfo.nodatchans, { index }, fields{f}));
end;
chans(ind).datachan = 0;
complicated = true;
end;
chaninfo = rmfield(chaninfo, 'nodatchans');
% put these channels first
% ------------------------
% tmp = chans(chanlen+1:end);
% chans(length(tmp)+1:end) = chans(1:end-length(tmp));
% chans(1:length(tmp)) = tmp;
end;
end;
|
github
|
lcnhappe/happe-master
|
removepath.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/removepath.m
| 513 |
utf_8
|
34d13ec0480b1b9ac75172c48ddc833e
|
% remove all path with a given parent path
% varargin contains a list of path to exclude
function removepath(parentpath, varargin)
if isempty(parentpath), return; end;
folder = path;
if ispc, sep = ';'; else sep = ':'; end;
indSep = find(folder == sep);
indSep = [ 0 indSep length(folder)+1 ];
for iSep = 1:length(indSep)-1
curPath = folder(indSep(iSep)+1:indSep(iSep+1)-1);
if ~isempty(strfind(curPath, parentpath)) && ~any(strmatch(curPath, varargin, 'exact'))
rmpath(curPath);
end;
end;
|
github
|
lcnhappe/happe-master
|
pop_editoptions.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/pop_editoptions.m
| 12,328 |
utf_8
|
640ce0d9927c2f7fa8fc7e1955a0c98e
|
% pop_editoptions() - Edit memory-saving eeglab() options. These are stored in
% a file 'eeg_options.m'. With no argument, pop up a window
% to allow the user to set/unset these options. Store
% user choices in a new 'eeg_options.m' file in the
% working directory.
%
% Usage: >> pop_editoptions;
% >> pop_editoptions( 'key1', value1, 'key2', value2, ...);
%
% Graphic interface inputs:
% "If set, keep at most one dataset in memory ..." - [checkbox] If set, EEGLAB will only retain the current
% dataset in memory. All other datasets will be automatically
% read and writen to disk. All EEGLAB functionalities are preserved
% even for dataset stored on disk.
% "If set, write data in same file as dataset ..." - [checkbox] Set -> dataset data (EEG.data) are
% saved in the EEG structure in the standard Matlab dataset (.set) file.
% Unset -> The EEG.data are saved as a transposed stream of 32-bit
% floats in a separate binary file. As of Matlab 4.51, the order
% of the data in the binary file is as in the transpose of EEG.data
% (i.e., as in EEG.data', frames by channels). This allows quick
% reading of single channels from the data, e.g. when comparing
% channels across datasets. The stored files have the extension
% .dat instead of the pre-4.51, non-transposed .fdt. Both file types
% are read by the dataset load function. Command line equivalent is
% option_savematlab.
% "Precompute ICA activations" - [checkbox] If set, all the ICA activation
% time courses are precomputed (this requires more RAM).
% Command line equivalent: option_computeica.
% "If set, remember old folder when reading dataset" - [checkbox] this option
% is convinient if the file you are working on are not in the
% current folder.
%
% Commandline keywords:
% 'option_computeica' - [0|1] If 1, compute the ICA component activitations and
% store them in a new variable. If 0, compute ICA activations
% only when needed (& only partially, if possible) and do not
% store the results).
% NOTE: Turn OFF the options above when working with very large datasets or on
% computers with limited memory.
% 'option_savematlab' - [0|1] If 1, datasets are saved as single Matlab .set files.
% If 0, dataset data are saved in separate 32-bit binary float
% .dat files. See the corresponding GUI option above for details.
% Outputs:
% In the output workspace, variables 'option_computeica',
% and 'option_savematlab' are updated, and a new 'eeg_options.m' file may be
% written to the working directory. The copy of 'eeg_options.m' placed in your
% working directory overwrites system defaults whenever EEGLAB operates in this
% directory (assuming your working directory is in your MATLABPATH - see path()).
% To adjust these options system-wide, edit the master "eeg_options.m" file in the
% EEGLAB directory heirarchy.
%
% Author: Arnaud Delorme, SCCN / INC / UCSD, March 2002
%
% See also: eeg_options(), eeg_readoptions()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 09 March 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 com = pop_editoptions(varargin);
com = '';
datasets_in_memory = 0;
if nargin > 0
if ~isstr(varargin{1})
datasets_in_memory = varargin{1};
varargin = {};
end;
end;
% parse the eeg_options file
% ----------------------------
eeglab_options;
if iseeglabdeployed
filename = fullfile(eeglabexefolder,'eeg_options.txt');
eegoptionbackup = fullfile(eeglabexefolder,'eeg_optionsbackup.txt');
else
% folder for eeg_options file (also update the eeglab_options)
if ~isempty(EEGOPTION_PATH)
homefolder = EEGOPTION_PATH;
elseif ispc
if ~exist('evalc'), eval('evalc = @(x)(eval(x));'); end;
homefolder = deblank(evalc('!echo %USERPROFILE%'));
else homefolder = '~';
end;
filename = fullfile(homefolder, 'eeg_options.m');
eegoptionbackup = which('eeg_optionsbackup.m');
end;
fid = fopen( filename, 'r+'); % existing file
storelocal = 0;
if fid == -1
filepath = homefolder;
filename = 'eeg_options.m';
fid = fopen( fullfile(filepath, filename), 'w'); % new file possible?
if fid == -1
error([ 'Cannot write into HOME folder: ' homefolder 10 'You may specify another folder for the eeg_option.m' 10 'file by editing the icadefs.m file' ]);
end;
fclose(fid);
delete(fullfile(filepath, filename));
% read variables values and description
% --------------------------------------
[ header opt ] = eeg_readoptions( eegoptionbackup );
else
[filepath filename ext] = fileparts(filename);
filename = [ filename ext ];
fprintf('Using option file in directory %s\n', filepath);
% read variables values and description
% --------------------------------------
[ header opt ] = eeg_readoptions( eegoptionbackup );
[ header opt ] = eeg_readoptions( fid, opt ); % use opt from above as default
end;
if nargin < 2
geometry = { [6 1] };
tmpfile = fullfile(filepath, filename);
cb_file = [ '[filename, filepath] = uiputfile(''eeg_options.txt'', ''Pick a folder to save option file'');' ...
'if filename(1) ~= 0,' ...
' filepath = fullfile(filepath, ''eeg_options.m'');' ...
' set(gcf, ''userdata'', filepath);' ...
' if length(filepath) > 100,' ...
' filepath = [ ''...'' filepath(end-100:end) ];' ...
' end;' ...
' set(findobj(gcf, ''tag'', ''filename''), ''string'', filepath);' ...
'end;' ...
'clear filepath;' ];
uilist = { ...
{ 'Style', 'text', 'string', '', 'fontweight', 'bold' }, ...
{ 'Style', 'text', 'string', 'Set/Unset', 'fontweight', 'bold' } };
% add all fields to graphic interface
% -----------------------------------
for index = 1:length(opt)
% format the description to fit a help box
% ----------------------------------------
descrip = { 'string', opt(index).description }; % strmultiline(description{ index }, 80, 10) };
% create the gui for this variable
% --------------------------------
geometry = { geometry{:} [4 0.3 0.1] };
if strcmpi(opt(index).varname, 'option_storedisk') & datasets_in_memory
cb_nomodif = [ 'set(gcbo, ''value'', ~get(gcbo, ''value''));' ...
'warndlg2(strvcat(''This option may only be modified when at most one dataset is stored in memory.''));' ];
elseif strcmpi(opt(index).varname, 'option_memmapdata')
cb_nomodif = [ 'if get(gcbo, ''value''), warndlg2(strvcat(''Matlab memory is beta, use at your own risk'')); end;' ];
elseif strcmpi(opt(index).varname, 'option_donotusetoolboxes')
cb_nomodif = [ 'if get(gcbo, ''value''), warndlg2([''You have selected the option to disable'' 10 ''Matlab toolboxes. Use with caution.'' 10 ''Matlab toolboxes will be removed from'' 10 ''your path. Unlicking this option later will not'' 10 ''add back the toolboxes. You will need'' 10 ''to add them back manually. If you are unsure'' 10 ''if you want to disable Matlab toolboxes'' 10 ''deselect the option now.'' ]); end;' ];
else
cb_nomodif = '';
end;
if ~isempty(opt(index).value)
uilist = { uilist{:}, { 'Style', 'text', descrip{:}, 'horizontalalignment', 'left' }, ...
{ 'Style', 'checkbox', 'string', ' ', 'value', opt(index).value 'callback' cb_nomodif } { } };
else
uilist = { uilist{:}, { 'Style', 'text', descrip{:}, 'fontweight' 'bold', 'horizontalalignment', 'left' }, ...
{ } { } };
end;
end;
% change option file
uilist = { uilist{:} {} ...
{ 'Style', 'text', 'string', 'Option file:' 'fontweight', 'bold' }, ...
{ 'Style', 'text', 'string', tmpfile 'tag' 'filename' }, ...
{} { 'Style', 'pushbutton', 'string', '...' 'callback' cb_file } };
geometry = { geometry{:} [1] [1 6 0.1 0.8] };
[results userdat ] = inputgui( geometry, uilist, 'pophelp(''pop_editoptions'');', 'Memory options - pop_editoptions()', ...
[], 'normal');
if ~isempty(userdat)
filepath = fileparts(userdat);
args = { 'filename' filename };
end;
if length(results) == 0, return; end;
% decode inputs
% -------------
args = {};
count = 1;
for index = 1:length(opt)
if ~isempty(opt(index).varname)
args = { args{:}, opt(index).varname, results{count} };
count = count+1;
end;
end;
else
% no interactive inputs
% ---------------------
args = varargin;
end;
% change default folder option
% ----------------------------
W_MAIN = findobj('tag', 'EEGLAB');
if ~isempty(W_MAIN)
tmpuserdata = get(W_MAIN, 'userdata');
tmpuserdata{3} = filepath;
set(W_MAIN, 'userdata', tmpuserdata);
end;
% decode inputs
% -------------
for index = 1:2:length(args)
ind = strmatch(args{index}, { opt.varname }, 'exact');
if isempty(ind)
if strcmpi(args{index}, 'option_savematlab')
disp('pop_editoptions: option_savematlab is obsolete, use option_savetwofiles instead');
ind = strmatch('option_savetwofiles', { opt.varname }, 'exact');
opt(ind).value = ~args{index+1};
else
error(['Variable name ''' args{index} ''' is invalid']);
end;
else
opt(ind).value = args{index+1};
end;
end;
% write to eeg_options file
% -------------------------
fid = fopen( fullfile(filepath, filename), 'w');
addpath(filepath);
if fid == -1
error('File writing error, check writing permission');
end;
fprintf(fid, '%s\n', header);
for index = 1:length(opt)
if isempty(opt(index).varname)
fprintf( fid, '%% %s\n', opt(index).description);
else
fprintf( fid, '%s = %d ; %% %s\n', opt(index).varname, opt(index).value, opt(index).description);
end;
end;
fclose(fid);
% clear it from the MATLAB function cache
clear(fullfile(filepath,filename));
% generate the output text command
% --------------------------------
com = 'pop_editoptions(';
for index = 1:2:length(args)
com = sprintf( '%s ''%s'', %d,', com, args{index}, args{index+1});
end;
com = [com(1:end-1) ');'];
clear functions
% ---------------------------
function chopedtext = choptext( tmptext )
chopedtext = '';
while length(tmptext) > 30
blanks = findstr( tmptext, ' ');
[tmp I] = min( abs(blanks - 30) );
chopedtext = [ chopedtext ''' 10 ''' tmptext(1:blanks(I)) ];
tmptext = tmptext(blanks(I)+1:end);
end;
chopedtext = [ chopedtext ''' 10 ''' tmptext];
chopedtext = chopedtext(7:end);
return;
function num = popask( text )
ButtonName=questdlg2( text, ...
'Confirmation', 'Cancel', 'Yes','Yes');
switch lower(ButtonName),
case 'cancel', num = 0;
case 'yes', num = 1;
end;
|
github
|
lcnhappe/happe-master
|
pop_delset.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/pop_delset.m
| 2,422 |
utf_8
|
44b38052f003e12e39320b5613f097ae
|
% pop_delset() - Delete a dataset from the variable containing
% all datasets.
%
% Usage: >> ALLEEG = pop_delset(ALLEEG, indices);
%
% Inputs:
% ALLEEG - array of EEG datasets
% indices - indices of datasets to delete. None -> a pop_up window asks
% the user to choose. Index < 0 -> it's positive is given as
% the default in the pop-up window (ex: -3 -> default 3).
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: pop_copyset(), 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
% load a set and store it in the current set
% ------------------------------------------
function [ALLSET, command] = pop_delset(ALLSET, set_in);
command = '';
if nargin < 1
help pop_delset;
return;
end;
if isempty( ALLSET )
error('Cannot delete dataset. Restart eeglab to clear all dataset information');
return;
end;
if nargin < 2 | set_in < 0
% which set to delete
% -----------------
promptstr = { 'Dataset(s) to delete:' };
if nargin == 2
inistr = { int2str(-set_in) };
else
inistr = { '1' };
end;
result = inputdlg2( promptstr, 'Delete dataset -- pop_delset()', 1, inistr, 'pop_delset');
size_result = size( result );
if size_result(1) == 0 return; end;
set_in = eval( [ '[' result{1} ']' ] );
end;
if isempty(set_in)
return;
end;
A = fieldnames( ALLSET );
A(:,2) = cell(size(A));
A = A';
for i = set_in
try
ALLSET(i) = struct(A{:});
%ALLSET = setfield(ALLSET, {set_in}, A{:}, cell(size(A)));
catch
error('Error: no such dataset');
return;
end;
end;
command = sprintf('%s = pop_delset( %s, [%s] );', inputname(1), inputname(1), int2str(set_in));
return;
|
github
|
lcnhappe/happe-master
|
pop_rejmenu.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/pop_rejmenu.m
| 23,728 |
utf_8
|
6acbdd38985f06d47dd90f857a5d8679
|
% pop_rejmenu() - Main menu for rejecting trials in an EEG dataset
%
% Usage: >> pop_rejmenu(INEEG, typerej);
%
% Inputs:
% INEEG - input dataset
% typerej - data to reject on (0 = component activations;
% 1 = raw electrode data). {Default: 1 = reject on raw data}
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeglab(), pop_eegplot(), pop_eegthresh, pop_rejtrend()
% pop_rejkurt(), pop_jointprob(), pop_rejspec()
% 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 pop_rejmenu( EEG, icacomp );
if icacomp == 0
if isempty( EEG.icasphere )
disp('Error: you must first run ICA on the data'); return;
end;
end;
if icacomp == 1 rejtitle = 'Reject trials using data statistics - pop_rejmenu()'; tagmenu = 'rejtrialraw';
else rejtitle = 'Reject trials using component activity statistics - pop_rejmenu()'; tagmenu = 'rejtrialica';
end;
if ~isempty( findobj('tag', tagmenu))
error('cannot open two identical windows; close the first one first');
end;
figure('visible', 'off', 'numbertitle', 'off', 'name', rejtitle, 'tag', tagmenu);
% definition of callbacks
% -----------------------
checkstatus = [ 'rejstatus = get( findobj(''parent'', gcbf, ''tag'', ''rejstatus''), ''value'');' ...
'if rejstatus == 3,' ...
' EEG.reject.disprej = {};' ...
' if get( findobj(''parent'', gcbf, ''tag'', ''IManual''), ''value''), EEG.reject.disprej{1} = ''manual''; end;' ...
' if get( findobj(''parent'', gcbf, ''tag'', ''IThresh''), ''value''), EEG.reject.disprej{2} = ''thresh''; end;' ...
' if get( findobj(''parent'', gcbf, ''tag'', ''IConst''), ''value''), EEG.reject.disprej{3} = ''const''; end;' ...
' if get( findobj(''parent'', gcbf, ''tag'', ''IEnt''), ''value''), EEG.reject.disprej{4} = ''jp''; end;' ...
' if get( findobj(''parent'', gcbf, ''tag'', ''IKurt''), ''value''), EEG.reject.disprej{5} = ''kurt''; end;' ...
' if get( findobj(''parent'', gcbf, ''tag'', ''IFreq''), ''value''), EEG.reject.disprej{6} = ''freq''; end;' ...
'end;' ...
'rejstatus = rejstatus-1;' ]; % from 1-3 range, go to 0-2 range
if icacomp, ICAPREFIX = '';
else ICAPREFIX = 'ica';
end;
% tmp_comall is used when returning from eegplot
tmp_comall = [ 'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ...
'''''), ''''tag'''', ''''mantrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejmanual)));' ...
'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ...
'''''), ''''tag'''', ''''threshtrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejthresh)));' ...
'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ...
'''''), ''''tag'''', ''''freqtrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejfreq)));' ...
'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ...
'''''), ''''tag'''', ''''consttrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejconst)));' ...
'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ...
'''''), ''''tag'''', ''''enttrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejjp)));' ...
'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ...
'''''), ''''tag'''', ''''kurttrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejkurt)));' ];
cb_manual = [ checkstatus ...
'pop_eegplot( EEG, ' int2str( icacomp ) ', rejstatus, 0,''' tmp_comall ''');' ...
'clear rejstatus;' ];
% -----------------------------------------------------
cb_compthresh = [ ' posthresh = get( findobj(''parent'', gcbf, ''tag'', ''threshpos''), ''string'' );' ...
' negthresh = get( findobj(''parent'', gcbf, ''tag'', ''threshneg''), ''string'' );' ...
' startime = get( findobj(''parent'', gcbf, ''tag'', ''threshstart''), ''string'' );' ...
' endtime = get( findobj(''parent'', gcbf, ''tag'', ''threshend''), ''string'' );' ...
' elecrange = get( findobj(''parent'', gcbf, ''tag'', ''threshelec''), ''string'' );' ...
checkstatus ...
'[EEG Itmp LASTCOM] = pop_eegthresh( EEG,' int2str(icacomp) ...
', elecrange, negthresh, posthresh, str2num(startime)/1000, str2num(endtime)/1000, rejstatus, 0,''' tmp_comall ''');' ...
'EEG = eegh(LASTCOM, EEG);' ...
'clear com Itmp elecrange posthresh negthresh startime endtime rejstatus;' ];
% ' set(findobj(''parent'', gcbf, ''tag'', ''threshtrial''), ''string'', num2str(EEG.trials - length(Itmp)));' ...
% 'eegh(LASTCOM);' ...
% 'clear Itmp elecrange posthresh negthresh startime endtime rejstatus;' ];
% -----------------------------------------------------
cb_compfreq = [ ' posthresh = get( findobj(''parent'', gcbf, ''tag'', ''freqpos''), ''string'' );' ...
' negthresh = get( findobj(''parent'', gcbf, ''tag'', ''freqneg''), ''string'' );' ...
' startfreq = get( findobj(''parent'', gcbf, ''tag'', ''freqstart''), ''string'' );' ...
' endfreq = get( findobj(''parent'', gcbf, ''tag'', ''freqend''), ''string'' );' ...
' elecrange = get( findobj(''parent'', gcbf, ''tag'', ''freqelec''), ''string'' );' ...
checkstatus ...
'[EEG Itmp LASTCOM] = pop_rejspec( EEG,' int2str(icacomp) ...
', elecrange, negthresh, posthresh, startfreq, endfreq, rejstatus, 0,''' tmp_comall ''');' ...
'EEG = eegh(LASTCOM, EEG);' ...
'clear Itmp elecrange posthresh negthresh startfreq endfreq rejstatus;' ];
% -----------------------------------------------------
cb_compconstrej = [ ' minslope = get( findobj(''parent'', gcbf, ''tag'', ''constpnts''), ''string'' );' ...
' minstd = get( findobj(''parent'', gcbf, ''tag'', ''conststd''), ''string'' );' ...
' elecrange = get( findobj(''parent'', gcbf, ''tag'', ''constelec''), ''string'' );' ...
checkstatus ...
'[rej LASTCOM] = pop_rejtrend(EEG,' int2str(icacomp) ', elecrange, ''' ...
int2str(EEG.pnts) ''', minslope, minstd, rejstatus, 0,''' tmp_comall ''');' ...
'EEG = eegh(LASTCOM, EEG);' ...
'clear rej elecrange minslope minstd rejstatus;' ];
% -----------------------------------------------------
cb_compenthead = [ ' locthresh = get( findobj(''parent'', gcbf, ''tag'', ''entloc''), ''string'' );', ...
' globthresh = get( findobj(''parent'', gcbf, ''tag'', ''entglob''), ''string'' );', ...
' elecrange = get( findobj(''parent'', gcbf, ''tag'', ''entelec''), ''string'' );' ];
cb_compenttail = [ ' set( findobj(''parent'', gcbf, ''tag'', ''entloc''), ''string'', num2str(locthresh) );', ...
' set( findobj(''parent'', gcbf, ''tag'', ''entglob''), ''string'', num2str(globthresh) );', ...
' set( findobj(''parent'', gcbf, ''tag'', ''enttrial''), ''string'', num2str(nrej) );' ...
'EEG = eegh(LASTCOM, EEG);' ...
'clear nrej elecrange locthresh globthresh rejstatus;' ];
cb_compentplot = [ cb_compenthead ...
'[EEG locthresh globthresh nrej LASTCOM] = pop_jointprob( EEG, ' int2str(icacomp) ...
', elecrange, locthresh, globthresh, 0, 0,''' tmp_comall ''');', ...
cb_compenttail ];
cb_compentcalc = [ cb_compenthead ...
'[EEG locthresh globthresh nrej LASTCOM] = pop_jointprob( EEG, ' int2str(icacomp) ...
', [ str2num(elecrange) ], str2num(locthresh), str2num(globthresh), 0, 0);', ...
cb_compenttail ];
cb_compenteeg = [ cb_compenthead ...
checkstatus ...
'[EEG locthresh globthresh nrej LASTCOM] = pop_jointprob( EEG, ' int2str(icacomp) ...
', elecrange, locthresh, globthresh, rejstatus, 0, 1,''' tmp_comall ''');', ...
cb_compenttail ];
% -----------------------------------------------------
cb_compkurthead =[ ' locthresh = get( findobj(''parent'', gcbf, ''tag'', ''kurtloc''), ''string'' );', ...
' globthresh = get( findobj(''parent'', gcbf, ''tag'', ''kurtglob''), ''string'' );', ...
' elecrange = get( findobj(''parent'', gcbf, ''tag'', ''kurtelec''), ''string'' );' ];
cb_compkurttail =[ ' set( findobj(''parent'', gcbf, ''tag'', ''kurtloc''), ''string'', num2str(locthresh) );', ...
' set( findobj(''parent'', gcbf, ''tag'', ''kurtglob''), ''string'', num2str(globthresh) );', ...
' set( findobj(''parent'', gcbf, ''tag'', ''kurttrial''), ''string'', num2str(nrej) );' ...
'EEG = eegh(LASTCOM, EEG);' ...
'clear nrej elecrange locthresh globthresh rejstatus;' ];
cb_compkurtplot = [ cb_compkurthead ...
'[EEG locthresh globthresh nrej LASTCOM] = pop_rejkurt( EEG, ' int2str(icacomp) ...
', elecrange, locthresh, globthresh, 0, 0,''' tmp_comall ''');', ...
cb_compkurttail ];
cb_compkurtcalc = [ cb_compkurthead ...
'[EEG locthresh globthresh nrej LASTCOM] = pop_rejkurt( EEG, ' int2str(icacomp) ...
', [ str2num(elecrange) ], str2num(locthresh), str2num(globthresh), 0, 0);', ...
cb_compkurttail ];
cb_compkurteeg = [ cb_compkurthead ...
checkstatus ...
'[EEG locthresh globthresh nrej LASTCOM] = pop_rejkurt( EEG, ' int2str(icacomp) ...
', elecrange, locthresh, globthresh, rejstatus, 0, 1,''' tmp_comall ''');', ...
cb_compkurttail ];
% -----------------------------------------------------
cb_reject = [ 'set( findobj(''parent'', gcbf, ''tag'', ''rejstatus''), ''value'', 3);' ... % force status to 3
checkstatus ...
'[EEG LASTCOM] = eeg_rejsuperpose(EEG,' int2str(icacomp) ',1,1,1,1,1,1,1); EEG = eegh(LASTCOM, EEG);' ...
'if isempty(find(EEG.reject.rejglobal)),' ...
' warndlg2(strvcat(''No epoch selected...'', ''When using thresholding, click update'',''marks in the EEG plotting window''));' ...
'else,' ...
' [EEG LASTCOM] = pop_rejepoch( EEG, EEG.reject.rejglobal, 1);' ...
' if ~isempty(LASTCOM), ' ...
' EEG = eegh(LASTCOM, EEG); [ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET); eegh(LASTCOM);' ...
' end; eeglab redraw; close(gcbf);' ...
'end;' ];
cb_clear = [ 'close gcbf; EEG = rmfield( EEG, ''reject''); EEG.reject.rejmanual = [];' ...
'EEG=eeg_checkset(EEG); pop_rejmenu(' inputname(1) ',' int2str(icacomp) ');' ];
cb_close = [ 'close gcbf;' ...
'disp(''Marks stored in dataset'');' ...
'[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);' ...
'eegh(''[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);'');'];
lisboxoptions = { 'string', [ 'Show only the new trials marked for rejection by the measure selected above|' ...
'Show previous and new trials marked for rejection by the measure selected above|' ...
'Show all trials marked for rejection by the measure selected above or checked below'], 'tag', 'rejstatus', 'value', 1, 'callback', ...
[ 'if get(gcbo, ''value'') == 3,' ...
' set(findobj(''parent'', gcbf, ''style'', ''checkbox''), ''enable'', ''on'');' ...
'else' ...
' set(findobj(''parent'', gcbf, ''style'', ''checkbox''), ''enable'', ''off'');' ...
'end;' ] };
chanliststr = [fastif(icacomp,'Electrode(s)','Component(s)') ];
chanlistval = fastif(icacomp, [ '1:' int2str(EEG.nbchan) ], [ '1:' int2str(size(EEG.icaweights,1)) ]);
% assess previous rejections
% --------------------------
sizeman = 0;
sizethresh = 0;
sizetrend = 0;
sizejp = 0;
sizekurt = 0;
sizespec = 0;
if icacomp == 1
if ~isempty(EEG.reject.rejmanual), sizeman = length(find(EEG.reject.rejmanual)); end;
if ~isempty(EEG.reject.rejconst), sizetrend = length(find(EEG.reject.rejconst)); end;
if ~isempty(EEG.reject.rejjp), sizejp = length(find(EEG.reject.rejjp)); end;
if ~isempty(EEG.reject.rejkurt), sizekurt = length(find(EEG.reject.rejkurt)); end;
if ~isempty(EEG.reject.rejfreq), sizespec = length(find(EEG.reject.rejfreq)); end;
else
if ~isempty(EEG.reject.icarejmanual), sizeman = length(find(EEG.reject.icarejmanual)); end;
if ~isempty(EEG.reject.icarejconst), sizetrend = length(find(EEG.reject.icarejconst)); end;
if ~isempty(EEG.reject.icarejjp), sizejp = length(find(EEG.reject.icarejjp)); end;
if ~isempty(EEG.reject.icarejkurt), sizekurt = length(find(EEG.reject.icarejkurt)); end;
if ~isempty(EEG.reject.icarejfreq), sizespec = length(find(EEG.reject.icarejfreq)); end;
end;
stdl = [0.25 1.2 0.8 1.2 0.8]; % standard line
titl = [0.9 0.18 1.55]; % title line
geometry = { [0.883 0.195 .2 .45 .4 .4] ...
[1] titl stdl stdl stdl stdl ...
[1] titl stdl stdl stdl ...
[1] titl stdl stdl stdl ...
[1] titl stdl stdl stdl ...
[1] titl stdl stdl stdl stdl ...
[1] [1] [1] [1 1 1] [1 1 1] ...
[1] [1 1 1]};
listui = {{'Style', 'text', 'string', 'Mark trials by appearance', 'fontweight', 'bold' }, ...
{ 'Style', 'pushbutton', 'string', '', 'tag', 'butmanual', ...
'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejmanualcol); if length(tmpcolor) ~= 1,' ...
'EEG.reject.rejmanualcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] },...
{ } { 'Style', 'pushbutton', 'string', fastif(icacomp,'Scroll Data','Scroll Acts.'), 'callback', cb_manual }, ...
{ 'Style', 'text', 'string', 'Marked trials' }, ...
{ 'Style', 'text', 'string', int2str(sizeman), 'tag', 'mantrial' }, ...
{ }, ...
... % ---------------------------------------------------------------------------
{ 'Style', 'text', 'string', 'Find abnormal values', 'fontweight', 'bold' }, ...
{ 'Style', 'pushbutton', 'string', '', 'tag', 'butthresh', ...
'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejthreshcol); if length(tmpcolor) ~= 1,' ...
'EEG.reject.rejthreshcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] }, { },...
...
{ }, { 'Style', 'text', 'string', ['Upper limit(s) ' fastif(icacomp,'(uV)', '(std. dev.)')] }, ...
{ 'Style', 'edit', 'string', '25', 'tag', 'threshpos' }, ...
{ 'Style', 'text', 'string', ['Lower limit(s) ' fastif(icacomp,'(uV)', '(std. dev.)')] }, ...
{ 'Style', 'edit', 'string', '-25', 'tag', 'threshneg' }, ...
...
{ }, { 'Style', 'text', 'string', 'Start time(s) (ms)' }, ...
{ 'Style', 'edit', 'string', int2str(EEG.xmin*1000), 'tag', 'threshstart' }, ...
{ 'Style', 'text', 'string', 'Ending time(s) (ms)' }, ...
{ 'Style', 'edit', 'string', int2str(EEG.xmax*1000), 'tag', 'threshend' }, ...
...
{ }, { 'Style', 'text', 'string', chanliststr }, ...
{ 'Style', 'edit', 'string', chanlistval, 'tag', 'threshelec' }, ...
{ 'Style', 'text', 'string', 'Currently marked trials' }, ...
{ 'Style', 'text', 'string', int2str(sizethresh), 'tag', 'threshtrial' }, ...
...
{ }, { 'Style', 'pushbutton', 'string', 'Calc / Plot', 'callback', cb_compthresh }, ...
{ }, { },{ 'Style', 'pushbutton', 'string', 'HELP', 'callback', 'pophelp(''pop_eegthresh'');' }, ...
... % ---------------------------------------------------------------------------
{ }, { 'Style', 'text', 'string', 'Find abnormal trends', 'fontweight', 'bold' }, ...
{ 'Style', 'pushbutton', 'string', '', 'tag', 'buttrend', ...
'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejconstcol); if length(tmpcolor) ~= 1,' ...
'EEG.reject.rejconstcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] }, { },...
...
{ }, { 'Style', 'text', 'string', ['Max slope ' fastif(icacomp, ...
'(uV/epoch)', ...
'(std. dev./epoch)') ] }, ...
{ 'Style', 'edit', 'string', '50', 'tag', 'constpnts' }, ...
{ 'Style', 'text', 'string', 'R-squared limit (0 to 1)' }, ...
{ 'Style', 'edit', 'string', '0.3', 'tag', 'conststd' }, ...
...
{ }, { 'Style', 'text', 'string', chanliststr }, ...
{ 'Style', 'edit', 'string', chanlistval, 'tag', 'constelec' }, ...
{ 'Style', 'text', 'string', 'Currently marked trials' }, ...
{ 'Style', 'text', 'string', int2str(sizetrend), 'tag', 'consttrial' }, ...
...
{ }, { 'Style', 'pushbutton', 'string', 'Calc / Plot', 'callback', cb_compconstrej }, ...
{ }, { }, { 'Style', 'pushbutton', 'string', 'HELP', 'callback', 'pophelp(''pop_rejtrend'');' }, ...
... % ---------------------------------------------------------------------------
{ }, { 'Style', 'text', 'string', 'Find improbable data', 'fontweight', 'bold' }, ...
{ 'Style', 'pushbutton', 'string', '', 'tag', 'butjp', ...
'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejjpcol); if length(tmpcolor) ~= 1,' ...
'EEG.reject.rejjpcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] }, { },...
...
{ }, { 'Style', 'text', 'string', fastif(icacomp, 'Single-channel limit (std. dev.)', 'Single-comp. limit (std. dev.)') }, ...
{ 'Style', 'edit', 'string', fastif(icacomp, '5', '20'), 'tag', 'entloc' }, ...
{ 'Style', 'text', 'string', fastif(icacomp, 'All channels limit (std. dev.)', 'All comp. limit (std. dev.)') }, ...
{ 'Style', 'edit', 'string', '5', 'tag', 'entglob' }, ...
...
{ }, { 'Style', 'text', 'string', chanliststr }, ...
{ 'Style', 'edit', 'string', chanlistval, 'tag', 'entelec' }, ...
{ 'Style', 'text', 'string', 'Currently marked trials' }, ...
{ 'Style', 'text', 'string', int2str(sizejp), 'tag', 'enttrial' }, ...
...
{ }, { 'Style', 'pushbutton', 'string', 'Calculate', 'callback', cb_compentcalc }, ...
{ 'Style', 'pushbutton', 'string', 'Scroll Data', 'callback', cb_compenteeg }, ...
{ 'Style', 'pushbutton', 'string', 'PLOT', 'callback', cb_compentplot }, ...
{ 'Style', 'pushbutton', 'string', 'HELP', 'callback', 'pophelp(''pop_jointprob'');' }, ...
... % ---------------------------------------------------------------------------
{ }, { 'Style', 'text', 'string', 'Find abnormal distributions', 'fontweight', 'bold' }, ...
{ 'Style', 'pushbutton', 'string', '', 'tag', 'butkurt', ...
'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejkurtcol); if length(tmpcolor) ~= 1,' ...
'EEG.reject.rejkurtcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] }, { },...
...
{ }, { 'Style', 'text', 'string', fastif(icacomp, 'Single-channel limit (std. dev.)', 'Single-comp. limit (std. dev.)') }, ...
{ 'Style', 'edit', 'string', fastif(icacomp, '5', '20'), 'tag', 'kurtloc' }, ...
{ 'Style', 'text', 'string', fastif(icacomp, 'All channels limit (std. dev.)', 'All comp. limit (std. dev.)') }, ...
{ 'Style', 'edit', 'string', '5', 'tag', 'kurtglob' }, ...
...
{ }, { 'Style', 'text', 'string', chanliststr }, ...
{ 'Style', 'edit', 'string', chanlistval, 'tag', 'kurtelec' }, ...
{ 'Style', 'text', 'string', 'Currently marked trials' }, ...
{ 'Style', 'text', 'string', int2str(sizekurt), 'tag', 'kurttrial' }, ...
...
{ }, { 'Style', 'pushbutton', 'string', 'Calculate', 'callback', cb_compkurtcalc }, ...
{ 'Style', 'pushbutton', 'string', 'Scroll Data', 'callback', cb_compkurteeg }, ...
{ 'Style', 'pushbutton', 'string', 'PLOT', 'callback', cb_compkurtplot }, ...
{ 'Style', 'pushbutton', 'string', 'HELP', 'callback', 'pophelp(''pop_rejkurt'');' }, ...
... % ---------------------------------------------------------------------------
{ }, { 'Style', 'text', 'string', 'Find abnormal spectra (slow)', 'fontweight', 'bold' }, ...
{ 'Style', 'pushbutton', 'string', '', 'tag', 'butspec', ...
'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejfreqcol); if length(tmpcolor) ~= 1,' ...
'EEG.reject.rejfreqcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] }, { },...
...
{ }, { 'Style', 'text', 'string', 'Upper limit(s) (dB)' }, ...
{ 'Style', 'edit', 'string', '25', 'tag', 'freqpos' }, ...
{ 'Style', 'text', 'string', 'Lower limit(s) (dB)' }, ...
{ 'Style', 'edit', 'string', '-25', 'tag', 'freqneg' }, ...
...
{ }, { 'Style', 'text', 'string', 'Low frequency(s) (Hz)' }, ...
{ 'Style', 'edit', 'string', '0', 'tag', 'freqstart' }, ...
{ 'Style', 'text', 'string', 'High frequency(s) (Hz)' }, ...
{ 'Style', 'edit', 'string', '50', 'tag', 'freqend' }, ...
...
{ }, { 'Style', 'text', 'string', chanliststr }, ...
{ 'Style', 'edit', 'string', chanlistval, 'tag', 'freqelec' }, ...
{ 'Style', 'text', 'string', 'Currently marked trials' }, ...
{ 'Style', 'text', 'string', int2str(sizespec), 'tag', 'freqtrial' }, ...
...
{ }, { 'Style', 'pushbutton', 'string', 'Calc / Plot', 'callback', cb_compfreq }, ...
{ }, { },{ 'Style', 'pushbutton', 'string', 'HELP', 'callback', 'pophelp(''pop_rejspec'');' }, ...
...
{}, ... % ---------------------------------------------------------------------------
...
{ 'Style', 'text', 'string', 'Plotting options', 'fontweight', 'bold' }, ...
{ 'style', 'listbox', lisboxoptions{:}, 'value', 3 }, ...
{ 'style', 'checkbox', 'String', 'Abnormal appearance', 'tag', 'IManual', 'value', 1, ...
'callback', 'set(gcbo, ''value'', 1); disp(''This checkbox must be set so that you may mark/unmark data epochs'');'}, ...
{ 'style', 'checkbox', 'String', 'Abnormal values', 'tag', 'IThresh', 'value', 1}, ...
{ 'style', 'checkbox', 'String', 'Abnormal trends', 'tag', 'IConst', 'value', 1}, ...
{ 'style', 'checkbox', 'String', 'Improbable epochs', 'tag', 'IEnt', 'value', 1}, ...
{ 'style', 'checkbox', 'String', 'Abnormal distributions', 'tag', 'IKurt', 'value', 1}, ...
{ 'style', 'checkbox', 'String', 'Abnormal spectra', 'tag', 'IFreq', 'value', 1}, ...
...
{ }, ...
{ 'Style', 'pushbutton', 'string', 'CLOSE (KEEP MARKS)', 'callback', cb_close }, ...
{ 'Style', 'pushbutton', 'string', 'CLEAR ALL MARKS', 'callback', cb_clear }, ...
{ 'Style', 'pushbutton', 'string', 'REJECT MARKED TRIALS', 'callback', cb_reject }};
allh = supergui( gcf, geometry, [], listui{:});
% { 'style', 'checkbox', 'String', ['Include ' fastif(icacomp, 'ica data', 'raw data')], 'tag', 'IOthertype', 'value', 1}, { }, ...
set(gcf, 'userdata', { allh });
set(findobj('parent', gcf', 'tag', 'butmanual'), 'backgroundcolor', EEG.reject.rejmanualcol);
set(findobj('parent', gcf', 'tag', 'butthresh'), 'backgroundcolor', EEG.reject.rejthreshcol);
set(findobj('parent', gcf', 'tag', 'buttrend'), 'backgroundcolor', EEG.reject.rejconstcol);
set(findobj('parent', gcf', 'tag', 'butjp'), 'backgroundcolor', EEG.reject.rejjpcol);
set(findobj('parent', gcf', 'tag', 'butkurt'), 'backgroundcolor', EEG.reject.rejkurtcol);
set(findobj('parent', gcf', 'tag', 'butspec'), 'backgroundcolor', EEG.reject.rejfreqcol);
set( findobj('parent', gcf, 'tag', 'rejstatus'), 'style', 'popup');
|
github
|
lcnhappe/happe-master
|
plugin_extract.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/plugin_extract.m
| 13,795 |
utf_8
|
7b0ac3bbdf7c634198dacd247b55052a
|
function restartEeglabFlag = plugin_extract(type, pluginlist, page)
if nargin < 3, page = 1; end;
% type may be 'import' or 'process'
restartEeglabFlag = false;
pluginsPerPage = 15;
% check the presence of unzip
%str = evalc('!unzip');
%if length(str) < 200
% error([ '"unzip" could not be found. Instal unzip and make sure' 10 'it is accessible under Matlab by adding the program to' 10 'the path and typing "!unzip"' ]);
%end;
if ~isstruct(type)
plugin = plugin_getweb(type, pluginlist, 'newlist');
% sort plugins by download score
[tmp scoreOrder] = sort([ plugin.downloads ], 2, 'descend');
plugin = plugin(scoreOrder);
else
plugin = type;
end;
% select page
allPlugins = plugin;
numPlugin = length(plugin);
moreThanOnePage = 0;
if numPlugin > pluginsPerPage
plugin = plugin(pluginsPerPage*(page-1)+1:min(length(plugin),pluginsPerPage*page));
moreThanOnePage = 1;
end;
% find which menu to show
newInstallFlag = false;
installedFlag = false;
deactivatedFlag = false;
for iPlugin = length(plugin):-1:1
if ~plugin(iPlugin).installed, newInstallFlag = true; end;
if plugin(iPlugin).installed && ~strcmpi(plugin(iPlugin).status, 'deactivated'), installedFlag = true; end;
if strcmpi(plugin(iPlugin).status, 'deactivated'), deactivatedFlag = true; end;
end;
uilist = {};
geom = {};
geomvert = [];
pluginIndices = [];
callback = [ 'tmptag = get(gcbo, ''tag'');' ...
'if tmptag(3) == ''1'', tmptag(3) = ''2''; else tmptag(3) = ''1''; end;' ...
'if get(gcbo, ''value''), set(findobj(gcbf, ''tag'', tmptag), ''value'', 0); end; clear tmptag;' ];
% ------------------
% plugins to install
% ------------------
maxchar = 60;
geom = {};
lineGeom = [ 0.28 0.28 0.95 0.6 0.6 3 0.35 ];
if newInstallFlag
uilist = { {} { 'style' 'text' 'string' 'Extensions available for install on the internet' 'fontweight' 'bold' 'fontsize' 18 'tag' 'title' } };
uilist = { uilist{:} { 'style' 'text' 'string' 'I' 'tag' 'install' } { } ...
{ 'style' 'text' 'string' 'Plugin' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Vers.' 'tag' 'verweb' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Score' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Description' 'fontweight' 'bold' } {}};
geom = { [1 5.5] lineGeom };
geomvert = [1 1];
for iRow = 1:length(plugin)
if ~plugin(iRow).installed && ~strcmpi(plugin(iRow).status, 'deactivated')
% text for description
description = plugin(iRow).description;
if length(description) > maxchar+2
description = [ description(1:min(maxchar,length(description))) '...' ];
end;
enableWebDoc = fastif(isempty(plugin(iRow).webdoc), 'off', 'on');
userdata = '';
if plugin(iRow).installed && plugin(iRow).installorupdate, userdata = 'colortored'; end;
uilist = { uilist{:}, ...
{ 'style' 'checkbox' 'string' '' 'value' 0 'enable' 'on' }, ...
{ 'style' 'checkbox' 'string' '' 'visible' 'off' }, ...
{ 'style' 'text' 'string' plugin(iRow).name }, ...
{ 'style' 'text' 'string' plugin(iRow).version 'tag' 'latestversion' 'userdata' userdata }, ...
{ 'style' 'text' 'string' int2str(plugin(iRow).downloads) }, ...
{ 'style' 'text' 'string' description }, ...
{ 'style' 'pushbutton' 'string' 'Doc' 'enable' enableWebDoc 'callback' myweb(plugin(iRow).webdoc) } };
geom = { geom{:}, lineGeom };
geomvert = [ geomvert 1];
pluginIndices = [ pluginIndices iRow ];
end;
end;
end;
% -----------------
% installed plugins
% -----------------
if installedFlag
uilist = { uilist{:} {} {} { 'style' 'text' 'string' 'Installed extensions' 'fontweight' 'bold' 'fontsize' 18 'tag' 'title' } };
uilist = { uilist{:} { 'style' 'text' 'string' 'I' 'tag' 'update' } ...
{ 'style' 'text' 'string' 'I' 'tag' 'deactivate' } ...
{ 'style' 'text' 'string' 'Plugin' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Vers.' 'tag' 'verweb' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Score' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Description' 'fontweight' 'bold' } {}};
geom = { geom{:} 1 [1 5.5] lineGeom };
geomvert = [geomvert 1 1 1];
for iRow = 1:length(plugin)
if plugin(iRow).installed && ~strcmpi(plugin(iRow).status, 'deactivated')
% text for description
description = plugin(iRow).description;
if length(description) > maxchar+2
description = [ description(1:min(maxchar,length(description))) '...' ];
end;
enableWebDoc = fastif(isempty(plugin(iRow).webdoc), 'off', 'on');
userdata = '';
if plugin(iRow).installorupdate,
textnew = [ 'Click update to install version ' plugin(iRow).version ' now available on the web' ];
userdata = 'colortored';
else
textnew = description;
end;
uilist = { uilist{:}, ...
{ 'style' 'checkbox' 'string' '' 'value' 0 'enable' fastif(plugin(iRow).installorupdate, 'on', 'off') 'tag' [ 'cb1' int2str(iRow) ] 'callback' callback }, ...
{ 'style' 'checkbox' 'string' '' 'enable' 'on' 'tag' [ 'cb2' int2str(iRow) ] 'callback' callback }, ...
{ 'style' 'text' 'string' plugin(iRow).name }, ...
{ 'style' 'text' 'string' plugin(iRow).currentversion 'tag' 'latestversion'}, ...
{ 'style' 'text' 'string' int2str(plugin(iRow).downloads) }, ...
{ 'style' 'text' 'string' textnew 'userdata' userdata }, ...
{ 'style' 'pushbutton' 'string' 'Doc' 'enable' enableWebDoc 'callback' myweb(plugin(iRow).webdoc) } };
geom = { geom{:}, lineGeom };
geomvert = [ geomvert 1];
pluginIndices = [ pluginIndices iRow ];
end;
end;
end;
% -------------------
% deactivated plugins
% -------------------
%geom = { geom{:} 1 1 };
%geomvert = [geomvert 0.5 1];
%uilist = { uilist{:} {} { 'style' 'text' 'string' 'To manage deactivated plugins, use menu item File > Manage plugins > Manage deactivated plugins' } };
if deactivatedFlag
uilist = { uilist{:} {} {} { 'style' 'text' 'string' 'List of deactivated extensions ' 'fontweight' 'bold' 'fontsize' 18 'tag' 'title' } };
uilist = { uilist{:} ...
{ 'style' 'text' 'string' 'I' 'tag' 'reactivate' } ...
{ 'style' 'text' 'string' 'I' 'tag' 'remove1' } ...
{ 'style' 'text' 'string' 'Plugin' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Vers.' 'tag' 'verweb' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Score' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Description' 'fontweight' 'bold' } {}};
geom = { geom{:} 1 [1 5.5] lineGeom };
geomvert = [geomvert 1 1 1];
for iRow = 1:length(plugin)
if strcmpi(plugin(iRow).status, 'deactivated')
% text for description
description = plugin(iRow).description;
if length(description) > maxchar+2
description = [ description(1:min(maxchar,length(description))) '...' ];
end;
userdata = '';
enableWebDoc = fastif(isempty(plugin(iRow).webdoc), 'off', 'on');
uilist = { uilist{:}, ...
{ 'style' 'checkbox' 'string' '' 'tag' [ 'cb1' int2str(iRow) ] 'callback' callback }, ...
{ 'style' 'checkbox' 'string' '' 'tag' [ 'cb2' int2str(iRow) ] 'callback' callback }, ...
{ 'style' 'text' 'string' plugin(iRow).name }, ...
{ 'style' 'text' 'string' plugin(iRow).version 'tag' 'latestversion' }, ...
{ 'style' 'text' 'string' int2str(plugin(iRow).downloads) }, ...
{ 'style' 'text' 'string' description }, ...
{ 'style' 'pushbutton' 'string' 'Doc' 'enable' enableWebDoc 'callback' myweb(plugin(iRow).webdoc) } };
geom = { geom{:}, lineGeom };
geomvert = [ geomvert 1];
pluginIndices = [ pluginIndices iRow ];
end;
end;
end;
evalStr = [ 'uisettxt(gcf, ''update'' , ''Update'' , ''rotation'', 90, ''fontsize'', 14);' ...
'uisettxt(gcf, ''deactivate'' , ''Deactivate'' , ''rotation'', 90, ''fontsize'', 14);' ...
'uisettxt(gcf, ''install'' , ''Install'' , ''rotation'', 90, ''fontsize'', 14);' ...
'uisettxt(gcf, ''reactivate'' , ''Reactivate'' , ''rotation'', 90, ''fontsize'', 14);' ...
'uisettxt(gcf, ''remove1'' , ''Remove'' , ''rotation'', 90, ''fontsize'', 14);' ...
'set(findobj(gcf, ''tag'', ''title''), ''fontsize'', 16);' ...
'tmpobj = findobj(gcf, ''userdata'', ''colortored'');' ...
'set(tmpobj, ''Foregroundcolor'', [1 0 0]);' ...
'tmppos = get(gcf, ''position'');' ...
'set(gcf, ''position'', [tmppos(1:2) 800 tmppos(4)]);' ...
'clear tmpobj tmppos;' ...
];
if 1
% version with button
if page == 1, enablePpage = 'off'; else enablePpage = 'on'; end;
if page*pluginsPerPage > numPlugin, enableNpage = 'off'; else enableNpage = 'on'; end;
callBackPpage = [ 'tmpobj = get(gcbf, ''userdata''); close gcbf; restartEeglabFlag = plugin_extract(tmpobj, [], ' int2str(page-1) '); clear tmpobj;' ];
callBackNpage = [ 'tmpobj = get(gcbf, ''userdata''); close gcbf; restartEeglabFlag = plugin_extract(tmpobj, [], ' int2str(page+1) '); clear tmpobj;' ];
uilist = { uilist{:}, {} { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', '< Prev. page', 'tag' 'ppage' 'callback', callBackPpage 'enable' enablePpage } };
uilist = { uilist{:}, { 'width' 80 'align' 'left' 'stickto' 'on', 'Style', 'pushbutton', 'string', 'Next page >', 'tag' 'npage' 'callback', callBackNpage 'enable' enableNpage } };
uilist = { uilist{:}, { 'width' 80 'align' 'right' 'Style', 'pushbutton', 'string', 'Cancel', 'tag' 'cancel' 'callback', 'close gcbf' } };
uilist = { uilist{:}, { 'width' 80 'align' 'right' 'stickto' 'on' 'Style', 'pushbutton', 'tag', 'ok', 'string', 'OK', 'callback', 'set(gcbo, ''userdata'', ''retuninginputui'');' } };
geom = { geom{:} [1] [1 1 1 1] };
geomvert = [ geomvert 1 1];
res = inputgui('uilist', uilist, 'geometry', geom, 'geomvert', geomvert, 'eval', evalStr, 'addbuttons', 'off', 'skipline', 'off', 'userdata', allPlugins);
try, restartEeglabFlag = evalin('base', 'restartEeglabFlag;'); catch, end;
evalin('base', 'clear restartEeglabFlag;');
else
% no buttons
res = inputgui('uilist', uilist, 'geometry', geom, 'geomvert', geomvert, 'eval', evalStr);
end;
if isempty(res), return; end;
% decode inputs
% -------------
for iRow = 1:length(pluginIndices)
plugin(pluginIndices(iRow)).install = res{(iRow-1)*2+1};
plugin(pluginIndices(iRow)).remove = res{(iRow-1)*2+2};
end;
% install plugins
% ---------------
firstPlugin = 1;
for iRow = 1:length(plugin)
if plugin(iRow).install
restartEeglabFlag = true;
if ~firstPlugin, disp('---------------------------------'); end; firstPlugin = 0;
if strcmpi(plugin(iRow).status, 'deactivated')
fprintf('Reactivating extension %s\n', plugin(iRow).name);
plugin_reactivate(plugin(iRow).foldername);
if plugin(iRow).installorupdate
res = questdlg2([ 'Extension ' plugin(iRow).foldername ' has been reactivated but' 10 'a new version is available. Do you want to install it?' ], 'Warning', 'No', 'Yes', 'Yes');
if strcmpi(res, 'yes')
plugin_deactivate(plugin(iRow).foldername);
if plugin_install(plugin(iRow).zip, plugin(iRow).name, plugin(iRow).version) == -1
plugin_reactivate(plugin(iRow).foldername);
else
plugin_remove(plugin(iRow).foldername);
end;
end;
end;
else
if plugin(iRow).installed
fprintf('Updating extension %s\n', plugin(iRow).name);
plugin_deactivate(plugin(iRow).foldername);
if plugin_install(plugin(iRow).zip, plugin(iRow).name, plugin(iRow).version) == -1
plugin_reactivate(plugin(iRow).foldername);
else
plugin_remove(plugin(iRow).foldername);
end;
else
fprintf('Installing extension %s\n', plugin(iRow).name);
plugin_install(plugin(iRow).zip, plugin(iRow).name, plugin(iRow).version);
end;
end;
elseif plugin(iRow).remove
if ~firstPlugin, disp('---------------------------------'); end; firstPlugin = 0;
restartEeglabFlag = true;
if strcmpi(plugin(iRow).status, 'deactivated')
fprintf('Removing extension %s\n', plugin(iRow).name);
plugin_remove(plugin(iRow).foldername);
else
fprintf('Deactivating extension %s\n', plugin(iRow).name);
plugin_deactivate(plugin(iRow).foldername);
end;
end;
end;
function str = myweb(url);
%if isempty(strfind(url, 'wiki'))
% str = [ 'web(''' url ''');' ];
%else
str = [ 'web(''' url ''', ''-browser'');' ];
%end;
|
github
|
lcnhappe/happe-master
|
eeg_store.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/eeg_store.m
| 5,423 |
utf_8
|
d4bd75d1e701aaaba164772acc07725e
|
% eeg_store() - store specified EEG dataset(s) in the ALLEG variable
% containing all current datasets, after first checking
% dataset consistency using eeg_checkset().
%
% Usage: >> [ALLEEG EEG index] = eeg_store(ALLEEG, EEG);
% >> [ALLEEG EEG index] = eeg_store(ALLEEG, EEG, index);
%
% Inputs:
% ALLEEG - variable containing all current EEGLAB datasets
% EEG - dataset(s) to store - usually the current dataset.
% May also be an array of datasets; these will be
% checked and stored separately in ALLEEG.
% index - (optional), ALLEEG index (or indices) to use to store
% the new dataset(s). If no index is given, eeg_store()
% uses the lowest empty slot(s) in the ALLEEG array.
% Outputs:
% ALLEEG - array of all current datasets
% EEG - EEG dataset (after syntax checking)
% index - index of the new dataset
%
% Note: When 3 arguments are given, after checking the consistency of
% the input dataset structures this function simply performs
% >> ALLEEG(index) = EEG;
%
% Typical use:
% >> [ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG);
% creates a new dataset in variable ALLEEG.
% >> [ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);
% overwrites the current dataset in variable ALLEEG.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeglab(), eeg_checkset(), eeg_retrieve()
% 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
% uses the global variable EEG ALLEEG CURRENTSET
% store set
% ------------------
function [ALLEEG, EEG, storeSetIndex] = eeg_store(ALLEEG, EEG, storeSetIndex, varargin);
% check parameter consistency
% ------------------------------
if nargin >= 3
if length(EEG) ~= length(storeSetIndex) & storeSetIndex(1) ~= 0
error('Length of input dataset structure must equal the length of the index array');
end;
end;
% considering multiple datasets
% -----------------------------
if length(EEG) > 1
TMPEEG = EEG;
if nargin >= 3 & storeSetIndex(1) ~= 0
for index=1:length(TMPEEG)
EEG = TMPEEG(index);
tmpsaved = EEG.saved;
if strcmpi(tmpsaved, 'justloaded'), tmpsaved = 'yes'; end;
[ALLEEG, EEG] = eeg_store(ALLEEG, EEG, storeSetIndex(index), varargin{:});
ALLEEG(storeSetIndex(index)).saved = tmpsaved;
TMPEEG(index).saved = tmpsaved;
end;
else
for index=1:length(TMPEEG)
EEG = TMPEEG(index);
tmpsaved = EEG.saved;
if strcmpi(tmpsaved, 'justloaded'), tmpsaved = 'yes'; end;
[ALLEEG, EEG, storeSetIndex(index)] = eeg_store(ALLEEG, EEG);
ALLEEG(storeSetIndex(index)).saved = tmpsaved;
TMPEEG(index).saved = tmpsaved;
end;
end;
EEG = TMPEEG;
return;
end;
if nargin < 3
% creating new dataset
% -> erasing file information
% ---------------------------
EEG.filename = '';
EEG.filepath = '';
EEG.datfile = '';
end;
if isempty(varargin) % no text output and no check (study loading)
[ EEG com ] = eeg_checkset(EEG);
else
com = '';
end;
if nargin > 2,
if storeSetIndex == 0 || strcmpi(EEG.saved, 'justloaded')
EEG.saved = 'yes'; % just loaded
else
EEG.saved = 'no';
end;
elseif strcmpi(EEG.saved, 'justloaded')
EEG.saved = 'yes';
else
EEG.saved = 'no';
end;
EEG = eeg_hist(EEG, com);
% find first free index
% ---------------------
findindex = 0;
if nargin < 3, findindex = 1;
elseif storeSetIndex == 0, findindex = 1;
end;
if findindex
i = 1;
while (i<2000)
try
if isempty(ALLEEG(i).data);
storeSetIndex = i; i = 2000;
end;
i = i+1;
catch
storeSetIndex = i; i = 2000;
end;
end;
if isempty(varargin) % no text output and no check
fprintf('Creating a new ALLEEG dataset %d\n', storeSetIndex);
end;
else
if isempty(storeSetIndex) | storeSetIndex == 0
storeSetIndex = 1;
end;
end;
if ~isempty( ALLEEG )
try
ALLEEG(storeSetIndex) = EEG;
catch
allfields = fieldnames( EEG );
for i=1:length( allfields )
eval( ['ALLEEG(' int2str(storeSetIndex) ').' allfields{i} ' = EEG.' allfields{i} ';' ]);
end;
if ~isfield(EEG, 'datfile') & isfield(ALLEEG, 'datfile')
ALLEEG(storeSetIndex).datfile = '';
end;
end;
else
ALLEEG = EEG;
if storeSetIndex ~= 1
ALLEEG(storeSetIndex+1) = EEG;
ALLEEG(1) = ALLEEG(storeSetIndex); % empty
ALLEEG(storeSetIndex) = ALLEEG(storeSetIndex+1);
ALLEEG = ALLEEG(1:storeSetIndex);
end;
end;
return;
|
github
|
lcnhappe/happe-master
|
eeg_eval.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/eeg_eval.m
| 4,224 |
utf_8
|
a33398d975e05e64806a16536fdcca32
|
% eeg_eval() - apply eeglab function to a collection of input datasets
%
% Usage:
% >> OUTEEG = eeg_eval(funcname, INEEG, 'key1', value1, 'key2', value2 ...);
%
% Inputs:
% funcname - [string] name of the function
% INEEG - EEGLAB input dataset(s)
%
% Optional inputs
% 'params' - [cell array] funcname parameters.
% 'warning' - ['on'|'off'] warning pop-up window if several dataset
% stored on disk that will be automatically overwritten.
% Default is 'on'.
%
% Outputs:
% OUTEEG - output dataset(s)
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2005
%
% see also: eeglab()
% Copyright (C) 2005 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 [EEG, com] = eeg_eval( funcname, EEG, varargin);
com = '';
if nargin < 2
help eeg_eval;
return;
end;
% check input parameters
% ----------------------
g = finputcheck( varargin, { 'params' 'cell' {} {};
'warning' 'string' { 'on','off' } 'on' }, 'eeg_eval');
if isstr(g), error(g); end;
% warning pop up
% --------------
eeglab_options;
if strcmpi(g.warning, 'on')
if ~option_storedisk
res = questdlg2(strvcat( 'When processing multiple datasets, it is not', ...
'possible to enter new names for the newly created', ...
'datasets and old datasets are overwritten.', ...
'You may still cancel this operation though.'), ...
'Multiple dataset warning', 'Cancel', 'Proceed', 'Proceed');
else
res = questdlg2( [ 'Data files on disk will be automatically overwritten.' 10 ...
'Are you sure you want to proceed with this operation?' ], ...
'Confirmation', 'Cancel', 'Proceed', 'Proceed');
end;
switch lower(res),
case 'cancel', return;
case 'proceed',;
end;
end;
% execute function
% ----------------
v = version;
if str2num(v(1)) == '5' % Matlab 5
command = [ 'TMPEEG = ' funcname '( TMPEEG, ' vararg2str(g.params) ');' ];
else
eval( [ 'func = @' funcname ';' ] );
end;
NEWEEG = [];
for i = 1:length(EEG)
fprintf('Processing group dataset %d of %d named: %s ****************\n', i, length(EEG), EEG(i).setname);
TMPEEG = eeg_retrieve(EEG, i);
if v(1) == '5', eval(command); % Matlab 5
else TMPEEG = feval(func, TMPEEG, g.params{:}); % Matlab 6 and higher
end;
TMPEEG = eeg_checkset(TMPEEG);
TMPEEG.saved = 'no';
if option_storedisk
TMPEEG = pop_saveset(TMPEEG, 'savemode', 'resave');
TMPEEG = update_datafield(TMPEEG);
end;
NEWEEG = eeg_store(NEWEEG, TMPEEG, i);
if option_storedisk
NEWEEG(i).saved = 'yes'; % eeg_store by default set it to no
end;
end;
EEG = NEWEEG;
% history
% -------
if nargout > 1
com = sprintf('%s = %s( %s,%s);', funcname, inputname(2), funcname, inputname(2), vararg2str(g.params));
end;
function EEG = update_datafield(EEG);
if ~isfield(EEG, 'datfile'), EEG.datfile = ''; end;
if ~isempty(EEG.datfile)
EEG.data = EEG.datfile;
else
EEG.data = 'in set file';
end;
EEG.icaact = [];
|
github
|
lcnhappe/happe-master
|
eegh.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/eegh.m
| 4,073 |
utf_8
|
71f03408b617f0adfa6816bce5a1adbd
|
% eegh() - history function.
%
% Usage:
% >> eegh( arg );
% >> eegh( arg1, arg2 );
%
% Inputs:
% - With no argument, it return the command history.
% - arg is a string: with a string argument it pulls the command
% onto the stack.
% - arg is a number>0: execute the element in the stack at the
% required position.
% - arg is a number<0: unstack the required number of elements
% - arg is 0 : clear stack
% - arg1 is 'find' and arg2 is a string, try to find the closest command
% in the stack containing the string
% - arg1 is a string and arg2 is a structure, also add the history to
% the structure in filed 'history'.
%
% Global variables used:
% LASTCOM - last command
% ALLCOM - all the commands
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, 2001
%
% See also:
% eeglab() (a graphical interface for eeg plotting, space frequency
% decomposition, ICA, ... under Matlab for which this command
% was designed).
% Copyright (C) 2001 Arnaud Delorme, SCCN/INC/UCSD, [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
% To increase/decrease the maximum depth of the stack, edit the eeg_consts file
function str = eegh( command, str );
mode = 1; % mode = 1, full print, mode = 0, truncated print
global ALLCOM;
%if nargin == 2
% fprintf('2: %s\n', command);
%elseif nargin == 1
% fprintf('1: %s\n', command);
%end;
if nargin < 1
if isempty(ALLCOM)
fprintf('No history\n');
else
for index = 1:length(ALLCOM)
if mode == 0, txt = ALLCOM{ index }; fprintf('%d: ', index);
else txt = ALLCOM{ length(ALLCOM)-index+1 };
end;
if (length(txt) > 72) & (mode == 0)
fprintf('%s...\n', txt(1:70) );
else
fprintf('%s\n', txt );
end;
end;
end;
if nargout > 0
str = strvcat(ALLCOM);
end;
elseif nargin == 1
if isempty( command )
return;
end;
if isstr( command )
if ~isempty(ALLCOM) && isequal(ALLCOM{1}, command), return; end;
if isempty(ALLCOM)
ALLCOM = { command };
else
ALLCOM = { command ALLCOM{:}};
end;
global LASTCOM;
LASTCOM = command;
else
if command == 0
ALLCOM = [];
else if command < 0
ALLCOM = ALLCOM( -command+1:end ); % unstack elements
else
txt = ALLCOM{command};
if length(txt) > 72
fprintf('%s...\n', txt(1:70) );
else
fprintf('%s\n', txt );
end;
evalin( 'base', ALLCOM{command} ); % execute element
eegh( ALLCOM{command} ); % add to history
end;
end;
end;
else % nargin == 2
if ~isstruct(str)
if strcmp(command, 'find')
for index = 1:length(ALLCOM)
if ~isempty(findstr(ALLCOM{index}, str))
str = ALLCOM{index};
return;
end;
end;
str = [];
end;
else
% warning also some code present in eeg_store and pop_newset
if ~isempty(ALLCOM) && isequal(ALLCOM{1}, command), return; end;
eegh(command); % add to history
if ~isempty(command)
if length(str) == 1
str = eeg_hist(str, command);
else
for i = 1:length(str)
str(i) = eeg_hist(str(i), [ '% multiple datasets command: ' command ]);
end;
end;
end;
end;
end;
|
github
|
lcnhappe/happe-master
|
eeglabexefolder.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/eeglabexefolder.m
| 1,076 |
utf_8
|
bea2b2d54e501ccc2c6e113759384061
|
% eeglabexefolder - return the exe folder for EEGLAB. This function is only
% relevant for the compiled version of EEGLAB.
%
% Author: Arnaud Delorme, SCCN & CERCO, CNRS, 2008-
% Copyright (C) 15 Feb 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 str = eeglabexefolder;
str = ctfroot;
inds = find(str == filesep);
str = str(1:inds(end)-1);
|
github
|
lcnhappe/happe-master
|
eeg_hist.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/eeg_hist.m
| 1,405 |
utf_8
|
5da5613eba9f720215dbf40a723b2008
|
% eeg_hist() - history for EEGLAB dataset.
%
% Usage:
% >> EEGOUT = eeg_hist( EEGIN, command );
%
% Inputs:
% EEGIN - input dataset
% command - [string] eeglab command
%
% Global variables used:
% EEGOUT - output dataset with updated history field
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, Dec 2003
%
% See also: eegh(), eeglab()
% Copyright (C) 2003 Arnaud Delorme, SCCN/INC/UCSD, [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 = eeg_hist( EEG, command );
if nargin < 2
help eeg_hist;
end;
if ~isfield(EEG, 'history')
EEG.history = '';
end;
if ~isempty(command)
try
EEG.history = [ EEG.history 10 command ];
catch
EEG.history = strvcat(EEG.history, command);
end;
end;
|
github
|
lcnhappe/happe-master
|
plugin_movepath.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/plugin_movepath.m
| 4,313 |
utf_8
|
3227a2fd281e8711ca0580850c1c0f20
|
%plugin_movepath()- Given a path to a plugin folder, this function will
% put the plugin at the bottom of the path.
%
% Usage:
% plugin_movepath('x','begin'); % Put plugin 'x' at the top of the path
% plugin_movepath('x','end'); % Put plugin 'x' at the bottom of the path
% plugin_movepath('x','begin','warns',1); % Put plugin 'x' at the top of the path and show warnings
%
% Inputs:
% foldername - [string] Plugin name or part of it
% pluginpos - {'begin','end'} Position to move the plugin in the path.
% To the top ('begin') or to the bottom ('end').
% Optional inputs:
% warns -[0,1] Allow isplay [1] or do not display [0] warnings.
% Warnings are restored at the end of the process. Default[0]
% Outputs:
% oldpath - Original MATLAB path before entering this function
% newpath - MATLAB path after being modified by this function
%
% Author: Ramon Martinez-Cancino and Arnaud Delorme, SCCN, 2016
%
% Copyright (C) 2016 Ramon Martinez-Cancino,INC, SCCN
%
% 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[oldpath, newpath] = plugin_movepath(foldername,pluginpos, varargin)
oldpath = []; newpath = [];
try
options = varargin;
if ~isempty( varargin ),
for i = 1:2:numel(options)
g.(options{i}) = options{i+1};
end
else g = []; end;
catch
disp('plugin_movepath() error: calling convention {''key'', value, ... } error'); return;
end;
try g.warns; catch, g.warns = 0; end; % NO warnings by default
% Checking entries
if sum(strcmp(pluginpos,{'begin','end'})) ~= 1
fprintf(2,'plugin_movepath error: Invalid function argument\n');
return;
end
% Look in the plugin list for the plugin name provided
global PLUGINLIST
hitindx = find(~cellfun(@isempty,strfind(lower({PLUGINLIST.plugin}),lower(foldername))));
if isempty(hitindx)
fprintf(2,'plugin_movepath error: Unidentified plugin folder\n')
return;
else
eeglabfolder = fileparts(which('eeglab.m'));
pluginfolder = fullfile(eeglabfolder,'plugins',PLUGINLIST(hitindx).foldername );
end
% Backing up old path
if ismatlab
oldpath = matlabpath;
else
oldpath = path;
end;
% Retreiving path
comp = computer;
if strcmpi(comp(1:2), 'PC')
newpathtest = [ pluginfolder ';' ];
else
newpathtest = [ pluginfolder ':' ];
end;
ind = strfind(oldpath, newpathtest);
% Checking out if the work is already done
if strcmp(pluginpos,'begin') && ind == 1, return; end;
if strcmp(pluginpos,'end') && strcmp(oldpath(end-length(pluginfolder):end),pluginfolder), return; end;
% Shooting down warnings
if ~g.warns
tmpwarn = warning;
warning off;
end
% Remove folder and subfolders from path
rmpath(genpath(pluginfolder));
% Add folder to the path again in the requested position
if strcmp(pluginpos,'begin')
addpath(genpath(pluginfolder),'-begin');
fprintf(1,['EEGLAB warning: to avoid name conflict ' PLUGINLIST(hitindx).foldername ' functions relocated at the end of the path\n']);
elseif strcmp(pluginpos,'end')
addpath(genpath(pluginfolder),'-end');
fprintf(1,['EEGLAB warning: to avoid name conflict ' PLUGINLIST(hitindx).foldername ' functions relocated at the end of the path\n']);
end
% Restoring warnings
if ~g.warns
warning(tmpwarn);
end
newpath = path; % Retreiving new path
% required here because path not added yet
% to the admin folder
function res = ismatlab;
v = version;
if v(1) > '4'
res = 1;
else
res = 0;
end;
|
github
|
lcnhappe/happe-master
|
eeglab_error.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/eeglab_error.m
| 3,159 |
utf_8
|
52bd326118eafedfeaaa94a2741cbedc
|
% eeglab_error() - generate an eeglab error.
%
% Usage: >> eeglab_error;
%
% Inputs: none, simply capture the last error generated.
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2006-
%
% see also: eeglab()
% Copyright (C) 2006 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 eeglab_error
% handling errors
% ----------------
tmplasterr = lasterr;
[iseeglaberror tmplasterr header] = testeeglaberror(tmplasterr);
ft_error = false;
if iseeglaberror
tmp = lasterror; % Add more information to eeglab errors JRI, RMC
tmplasterr = sprintf('%s,\n\n (Error occurred in function %s() at line %d)',...
tmplasterr, tmp.stack(1).name, tmp.stack(1).line);
errordlg2(tmplasterr, header);
else
try
tmp = lasterror;
if length(tmp.stack(1).name) && all(tmp.stack(1).name(1:3) == 'ft_')
ft_error = true;
end;
tmperr = [ 'EEGLAB error in function ' tmp.stack(1).name '() at line ' int2str(tmp.stack(1).line) ':' 10 10 lasterr ];
catch % Matlab 5 and when the stack is empty
tmperr = [ 'EEGLAB error:' 10 10 tmplasterr ];
end;
if ~ft_error
tmperr = [ tmperr 10 10 'If you think this is a bug, please submit a detailed ' 10 ...
'description of how to reproduce the problem (and upload' 10 ...
'a small dataset) at http://sccn.ucsd.edu/eeglab/bugzilla' ];
else
tmperr = [ tmperr 10 10 'This is a problem with FIELDTRIP. The Fieldtrip version you downloaded' 10 ...
'is corrupted. Please manually replace Fieldtrip with an earlier version' 10 ...
'and/or email the Fieldtrip developpers so they can fix the issue.' ];
end;
errordlg2(tmperr, header);
end;
function [ val str header ] = testeeglaberror(str)
header = 'EEGLAB error';
val = 0;
try,
if strcmp(str(1:5), 'Error'),
val = 1;
str = str(12:end); %Corrected extraction of function name, occurs after 'Error using ' JRI, RMC
indendofline = find(str == 10);
funcname = str(1:indendofline(1)-1);
str = str(indendofline(1)+1:end);
header = [ funcname ' error' ];
end;
catch
end;
|
github
|
lcnhappe/happe-master
|
plugin_installstartup.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/adminfunc/plugin_installstartup.m
| 3,762 |
utf_8
|
37419d82594718647942d0ca8356c632
|
% plugin_installstartup() - install popular toolboxes when EEGLAB starts
%
% Usage:
% >> restartEeglabFlag = plugin_installstartup; % pop up window
%
% Outputs:
% restartEeglabFlag - [0|1] restart EEGLAB
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Oct. 29, 2013-
% Copyright (C) 2013 Arnaud Delorme, SCCN, INC, UCSD, [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 restartEeglabFlag = plugin_installstartup
% { 'style' 'checkbox' 'string' 'Neuroelectromagnetic Forward Head Modeling Toolbox (NFT): Advanced source localization tools - beta (Zeynep Akalin Acar, 100 Mb)' 'value' 1 'enable' 'on' } ...
uilist = { { 'style' 'text' 'String' 'Download and install some popular third party EEGLAB plug-ins' 'fontweight', 'bold','tag', 'title'} ...
{ } ...
{ 'style' 'checkbox' 'string' 'Brain Vision Analyser data import plugin (40 Kb)' 'value' 1 'enable' 'on' } ...
{ 'style' 'checkbox' 'string' 'ANT data import plugin (800 Kb)' 'value' 1 'enable' 'on' } ...
{ 'style' 'checkbox' 'string' 'Measure Projection Toolbox (MPT) for ulti-subject ICA analysis (415 Mb)' 'value' 1 'enable' 'on' } ...
{ 'style' 'checkbox' 'string' 'Source Information Flow Toolbox (SIFT) for causal analysis of EEG sources (600 Mb)' 'value' 1 'enable' 'on' } ...
{ 'style' 'checkbox' 'string' 'BCILAB for real-time and offline BCI platform (200 Mb)' 'value' 1 'enable' 'on' } ...
{ 'style' 'checkbox' 'string' 'LIMO for linear analysis of MEEG data using single trials (2.5 Mb)' 'value' 1 'enable' 'on' } ...
{ } ...
{ 'style' 'radiobutton' 'string' 'Do not show this query again' 'value' 0 } ...
{} ...
{ 'style' 'text' 'String' 'Note: manage plug-in tools using EEGLAB menu item, "File > Plug-ins > Manage plug-ins"' } ...
{} ...
{ 'Style', 'pushbutton', 'string', 'Do not install now', 'tag' 'cancel' 'callback', 'set(gcbf, ''userdata'', ''cancel'');' } { } ...
{ 'Style', 'pushbutton', 'string', 'Install plugins now', 'tag', 'ok', 'callback', 'set(gcbf, ''userdata'', ''ok'');' } ...
};
geomline = [1];
geom = { [1] [1] geomline geomline geomline geomline geomline geomline [1] geomline [1] [1] [1] [1 1 1]};
geomvert = [ 1 0.5 1 1 1 1 1 1 0.3 1 0.3 1 1 1];
%result = inputgui( 'geometry', geom, 'uilist', uilist, 'helpcom', 'pophelp(''plugin_installstartup'')', 'title', 'Install popular plugins', 'geomvert', geomvert, 'eval', evalstr);
fig = figure('visible', 'off');
[tmp1 tmp2 handles] = supergui( 'geomhoriz', geom, 'uilist', uilist, 'title', 'Install popular plugins', 'geomvert', geomvert, 'fig', fig); %, 'eval', evalstr);
set(findobj(fig, 'tag', 'title'), 'fontsize', 16);
waitfor( fig, 'userdata');
% decode inputs
handles
results = cellfun(@(x)(get
get(handles, 'value')
|
github
|
lcnhappe/happe-master
|
topoplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/topoplot.m
| 70,628 |
utf_8
|
583a17ef238d3edc7ac2be5e6f200825
|
% topoplot() - plot a topographic map of a scalp data field in a 2-D circular view
% (looking down at the top of the head) using interpolation on a fine
% cartesian grid. Can also show specified channnel location(s), or return
% an interpolated value at an arbitrary scalp location (see 'noplot').
% By default, channel locations below head center (arc_length 0.5) are
% shown in a 'skirt' outside the cartoon head (see 'plotrad' and 'headrad'
% options below). Nose is at top of plot; left is left; right is right.
% Using option 'plotgrid', the plot may be one or more rectangular grids.
% Usage:
% >> topoplot(datavector, EEG.chanlocs); % plot a map using an EEG chanlocs structure
% >> topoplot(datavector, 'my_chan.locs'); % read a channel locations file and plot a map
% >> topoplot('example'); % give an example of an electrode location file
% >> [h grid_or_val plotrad_or_grid, xmesh, ymesh]= ...
% topoplot(datavector, chan_locs, 'Input1','Value1', ...);
% Required Inputs:
% datavector - single vector of channel values. Else, if a vector of selected subset
% (int) channel numbers -> mark their location(s) using 'style' 'blank'.
% chan_locs - name of an EEG electrode position file (>> topoplot example).
% Else, an EEG.chanlocs structure (>> help readlocs or >> topoplot example)
% Optional inputs:
% 'maplimits' - 'absmax' -> scale map colors to +/- the absolute-max (makes green 0);
% 'maxmin' -> scale colors to the data range (makes green mid-range);
% [lo.hi] -> use user-definined lo/hi limits
% {default: 'absmax'}
% 'style' - 'map' -> plot colored map only
% 'contour' -> plot contour lines only
% 'both' -> plot both colored map and contour lines
% 'fill' -> plot constant color between contour lines
% 'blank' -> plot electrode locations only {default: 'both'}
% 'electrodes' - 'on','off','labels','numbers','ptslabels','ptsnumbers'. To set the 'pts'
% marker,,see 'Plot detail options' below. {default: 'on' -> mark electrode
% locations with points ('.') unless more than 64 channels, then 'off'}.
% 'plotchans' - [vector] channel numbers (indices) to use in making the head plot.
% {default: [] -> plot all chans}
% 'chantype' - cell array of channel type(s) to plot. Will also accept a single quoted
% string type. Channel type for channel k is field EEG.chanlocs(k).type.
% If present, overrides 'plotchans' and also 'chaninfo' with field
% 'chantype'. Ex. 'EEG' or {'EEG','EOG'} {default: all, or 'plotchans' arg}
% 'plotgrid' - [channels] Plot channel data in one or more rectangular grids, as
% specified by [channels], a position matrix of channel numbers defining
% the topographic locations of the channels in the grid. Zero values are
% given the figure background color; negative integers, the color of the
% polarity-reversed channel values. Ex: >> figure; ...
% >> topoplot(values,'chanlocs','plotgrid',[11 12 0; 13 14 15]);
% % Plot a (2,3) grid of data values from channels 11-15 with one empty
% grid cell (top right) {default: no grid plot}
% 'nosedir' - ['+X'|'-X'|'+Y'|'-Y'] direction of nose {default: '+X'}
% 'chaninfo' - [struct] optional structure containing fields 'nosedir', 'plotrad'
% and/or 'chantype'. See these (separate) field definitions above, below.
% {default: nosedir +X, plotrad 0.5, all channels}
% 'plotrad' - [0.15<=float<=1.0] plotting radius = max channel arc_length to plot.
% See >> topoplot example. If plotrad > 0.5, chans with arc_length > 0.5
% (i.e. below ears-eyes) are plotted in a circular 'skirt' outside the
% cartoon head. See 'intrad' below. {default: max(max(chanlocs.radius),0.5);
% If the chanlocs structure includes a field chanlocs.plotrad, its value
% is used by default}.
% 'headrad' - [0.15<=float<=1.0] drawing radius (arc_length) for the cartoon head.
% NOTE: Only headrad = 0.5 is anatomically correct! 0 -> don't draw head;
% 'rim' -> show cartoon head at outer edge of the plot {default: 0.5}
% 'intrad' - [0.15<=float<=1.0] radius of the scalp map interpolation area (square or
% disk, see 'intsquare' below). Interpolate electrodes in this area and use
% this limit to define boundaries of the scalp map interpolated data matrix
% {default: max channel location radius}
% 'intsquare' - ['on'|'off'] 'on' -> Interpolate values at electrodes located in the whole
% square containing the (radius intrad) interpolation disk; 'off' -> Interpolate
% values from electrodes shown in the interpolation disk only {default: 'on'}.
% 'conv' - ['on'|'off'] Show map interpolation only out to the convext hull of
% the electrode locations to minimize extrapolation. Use this option ['on'] when
% plotting pvalues {default: 'off'}
% 'noplot' - ['on'|'off'|[rad theta]] do not plot (but return interpolated data).
% Else, if [rad theta] are coordinates of a (possibly missing) channel,
% returns interpolated value for channel location. For more info,
% see >> topoplot 'example' {default: 'off'}
% 'verbose' - ['on'|'off'] comment on operations on command line {default: 'on'}.
%
% Plot detail options:
% 'drawaxis' - ['on'|'off'] draw axis on the top left corner.
% 'emarker' - Matlab marker char | {markerchar color size linewidth} char, else cell array
% specifying the electrode 'pts' marker. Ex: {'s','r',32,1} -> 32-point solid
% red square. {default: {'.','k',[],1} where marker size ([]) depends on the number
% of channels plotted}.
% 'emarker2' - {markchans}|{markchans marker color size linewidth} cell array specifying
% an alternate marker for specified 'plotchans'. Ex: {[3 17],'s','g'}
% {default: none, or if {markchans} only are specified, then {markchans,'o','r',10,1}}
% 'hcolor' - color of the cartoon head. Use 'hcolor','none' to plot no head. {default: 'k' = black}
% 'shading' - 'flat','interp' {default: 'flat'}
% 'numcontour' - number of contour lines {default: 6}
% 'contourvals' - values for contour {default: same as input values}
% 'pmask' - values for masking topoplot. Array of zeros and 1 of the same size as the input
% value array {default: []}
% 'color' - color of the contours {default: dark grey}
% 'whitebk ' - ('on'|'off') make the background color white (e.g., to print empty plotgrid channels)
% {default: 'off'}
% 'gridscale' - [int > 32] size (nrows) of interpolated scalp map data matrix {default: 67}
% 'colormap' - (n,3) any size colormap {default: existing colormap}
% 'circgrid' - [int > 100] number of elements (angles) in head and border circles {201}
% 'emarkercolor' - cell array of colors for 'blank' option.
% 'plotdisk' - ['on'|'off'] plot disk instead of dots for electrodefor 'blank' option. Size of disk
% is controled by input values at each electrode. If an imaginary value is provided,
% plot partial circle with red for the real value and blue for the imaginary one.
%
% Dipole plotting options:
% 'dipole' - [xi yi xe ye ze] plot dipole on the top of the scalp map
% from coordinate (xi,yi) to coordinates (xe,ye,ze) (dipole head
% model has radius 1). If several rows, plot one dipole per row.
% Coordinates returned by dipplot() may be used. Can accept
% an EEG.dipfit.model structure (See >> help dipplot).
% Ex: ,'dipole',EEG.dipfit.model(17) % Plot dipole(s) for comp. 17.
% 'dipnorm' - ['on'|'off'] normalize dipole length {default: 'on'}.
% 'diporient' - [-1|1] invert dipole orientation {default: 1}.
% 'diplen' - [real] scale dipole length {default: 1}.
% 'dipscale' - [real] scale dipole size {default: 1}.
% 'dipsphere' - [real] size of the dipole sphere. {default: 85 mm}.
% 'dipcolor' - [color] dipole color as Matlab code code or [r g b] vector
% {default: 'k' = black}.
% Outputs:
% handle - handle of the colored surface.If
% contour only is plotted, then is the handle of
% the countourgroup. (If no surface or contour is plotted,
% return "gca", the handle of the current plot)
% grid_or_val - [matrix] the interpolated data image (with off-head points = NaN).
% Else, single interpolated value at the specified 'noplot' arg channel
% location ([rad theta]), if any.
% plotrad_or_grid - IF grid image returned above, then the 'plotrad' radius of the grid.
% Else, the grid image
% xmesh, ymesh - x and y values of the returned grid (above)
%
% Chan_locs format:
% See >> topoplot 'example'
%
% Examples:
%
% To plot channel locations only:
% >> figure; topoplot([],EEG.chanlocs,'style','blank','electrodes','labelpoint','chaninfo',EEG.chaninfo);
%
% Notes: - To change the plot map masking ring to a new figure background color,
% >> set(findobj(gca,'type','patch'),'facecolor',get(gcf,'color'))
% - Topoplots may be rotated. From the commandline >> view([deg 90]) {default: [0 90])
% - When plotting pvalues make sure to use the option 'conv' to minimize extrapolation effects
%
% Authors: Andy Spydell, Colin Humphries, Arnaud Delorme & Scott Makeig
% CNL / Salk Institute, 8/1996-/10/2001; SCCN/INC/UCSD, Nov. 2001 -
%
% See also: timtopo(), envtopo()
% Deprecated options:
% 'shrink' - ['on'|'off'|'force'|factor] Deprecated. 'on' -> If max channel arc_length
% > 0.5, shrink electrode coordinates towards vertex to plot all channels
% by making max arc_length 0.5. 'force' -> Normalize arc_length
% so the channel max is 0.5. factor -> Apply a specified shrink
% factor (range (0,1) = shrink fraction). {default: 'off'}
% 'electcolor' {'k'} ... electrode marking details and their {defaults}.
% 'emarker' {'.'}|'emarkersize' {14}|'emarkersizemark' {40}|'efontsize' {var} -
% electrode marking details and their {defaults}.
% 'ecolor' - color of the electrode markers {default: 'k' = black}
% 'interplimits' - ['electrodes'|'head'] 'electrodes'-> interpolate the electrode grid;
% 'head'-> interpolate the whole disk {default: 'head'}.
% Unimplemented future options:
% Copyright (C) Colin Humphries & Scott Makeig, CNL / Salk Institute, Aug, 1996
%
% 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
% Topoplot Version 2.1
% Early development history:
% Begun by Andy Spydell and Scott Makeig, NHRC, 7-23-96
% 8-96 Revised by Colin Humphries, CNL / Salk Institute, La Jolla CA
% -changed surf command to imagesc (faster)
% -can now handle arbitrary scaling of electrode distances
% -can now handle non integer angles in chan_locs
% 4-4-97 Revised again by Colin Humphries, reformatted by SM
% -added parameters
% -changed chan_locs format
% 2-26-98 Revised by Colin
% -changed image back to surface command
% -added fill and blank styles
% -removed extra background colormap entry (now use any colormap)
% -added parameters for electrode colors and labels
% -now each topoplot axes use the caxis command again.
% -removed OUTPUT parameter
% 3-11-98 changed default emarkersize, improve help msg -sm
% 5-24-01 made default emarkersize vary with number of channels -sm
% 01-25-02 reformated help & license, added link -ad
% 03-15-02 added readlocs and the use of eloc input structure -ad
% 03-25-02 added 'labelpoint' options and allow Values=[] -ad &sm
% 03-25-02 added details to "Unknown parameter" warning -sm & ad
function [handle,Zi,grid,Xi,Yi] = topoplot(Values,loc_file,varargin)
%
%%%%%%%%%%%%%%%%%%%%%%%% Set defaults %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
icadefs % read defaults MAXTOPOPLOTCHANS and DEFAULT_ELOC and BACKCOLOR
if ~exist('BACKCOLOR') % if icadefs.m does not define BACKCOLOR
BACKCOLOR = [.93 .96 1]; % EEGLAB standard
end
whitebk = 'off'; % by default, make gridplot background color = EEGLAB screen background color
persistent warningInterp;
plotgrid = 'off';
plotchans = [];
noplot = 'off';
handle = [];
Zi = [];
chanval = NaN;
rmax = 0.5; % actual head radius - Don't change this!
INTERPLIMITS = 'head'; % head, electrodes
INTSQUARE = 'on'; % default, interpolate electrodes located though the whole square containing
% the plotting disk
default_intrad = 1; % indicator for (no) specified intrad
MAPLIMITS = 'absmax'; % absmax, maxmin, [values]
GRID_SCALE = 67; % plot map on a 67X67 grid
CIRCGRID = 201; % number of angles to use in drawing circles
AXHEADFAC = 1.3; % head to axes scaling factor
CONTOURNUM = 6; % number of contour levels to plot
STYLE = 'both'; % default 'style': both,straight,fill,contour,blank
HEADCOLOR = [0 0 0]; % default head color (black)
CCOLOR = [0.2 0.2 0.2]; % default contour color
ELECTRODES = []; % default 'electrodes': on|off|label - set below
MAXDEFAULTSHOWLOCS = 64;% if more channels than this, don't show electrode locations by default
EMARKER = '.'; % mark electrode locations with small disks
ECOLOR = [0 0 0]; % default electrode color = black
EMARKERSIZE = []; % default depends on number of electrodes, set in code
EMARKERLINEWIDTH = 1; % default edge linewidth for emarkers
EMARKERSIZE1CHAN = 20; % default selected channel location marker size
EMARKERCOLOR1CHAN = 'red'; % selected channel location marker color
EMARKER2CHANS = []; % mark subset of electrode locations with small disks
EMARKER2 = 'o'; % mark subset of electrode locations with small disks
EMARKER2COLOR = 'r'; % mark subset of electrode locations with small disks
EMARKERSIZE2 = 10; % default selected channel location marker size
EMARKER2LINEWIDTH = 1;
EFSIZE = get(0,'DefaultAxesFontSize'); % use current default fontsize for electrode labels
HLINEWIDTH = 2; % default linewidth for head, nose, ears
BLANKINGRINGWIDTH = .035;% width of the blanking ring
HEADRINGWIDTH = .007;% width of the cartoon head ring
SHADING = 'flat'; % default 'shading': flat|interp
shrinkfactor = []; % shrink mode (dprecated)
intrad = []; % default interpolation square is to outermost electrode (<=1.0)
plotrad = []; % plotting radius ([] = auto, based on outermost channel location)
headrad = []; % default plotting radius for cartoon head is 0.5
squeezefac = 1.0;
MINPLOTRAD = 0.15; % can't make a topoplot with smaller plotrad (contours fail)
VERBOSE = 'off';
MASKSURF = 'off';
CONVHULL = 'off'; % dont mask outside the electrodes convex hull
DRAWAXIS = 'off';
PLOTDISK = 'off';
CHOOSECHANTYPE = 0;
ContourVals = Values;
PMASKFLAG = 0;
COLORARRAY = { [1 0 0] [0.5 0 0] [0 0 0] };
%COLORARRAY2 = { [1 0 0] [0.5 0 0] [0 0 0] };
gb = [0 0];
COLORARRAY2 = { [gb 0] [gb 1/4] [gb 2/4] [gb 3/4] [gb 1] };
%%%%%% Dipole defaults %%%%%%%%%%%%
DIPOLE = [];
DIPNORM = 'on';
DIPSPHERE = 85;
DIPLEN = 1;
DIPSCALE = 1;
DIPORIENT = 1;
DIPCOLOR = [0 0 0];
NOSEDIR = '+X';
CHANINFO = [];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%%%%%%%%%%%%%%%%%%%%%%% Handle arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if nargin< 1
help topoplot;
return
end
% calling topoplot from Fieldtrip
% -------------------------------
fieldtrip = 0;
if nargin < 2, loc_file = []; end;
if isstruct(Values) | ~isstruct(loc_file), fieldtrip == 1; end;
if isstr(loc_file), if exist(loc_file) ~= 2, fieldtrip == 1; end; end;
if fieldtrip
error('Wrong calling format, are you trying to use the topoplot Fieldtrip function?');
end;
nargs = nargin;
if nargs == 1
if isstr(Values)
if any(strcmp(lower(Values),{'example','demo'}))
fprintf(['This is an example of an electrode location file,\n',...
'an ascii file consisting of the following four columns:\n',...
' channel_number degrees arc_length channel_name\n\n',...
'Example:\n',...
' 1 -18 .352 Fp1 \n',...
' 2 18 .352 Fp2 \n',...
' 5 -90 .181 C3 \n',...
' 6 90 .181 C4 \n',...
' 7 -90 .500 A1 \n',...
' 8 90 .500 A2 \n',...
' 9 -142 .231 P3 \n',...
'10 142 .231 P4 \n',...
'11 0 .181 Fz \n',...
'12 0 0 Cz \n',...
'13 180 .181 Pz \n\n',...
...
'In topoplot() coordinates, 0 deg. points to the nose, positive\n',...
'angles point to the right hemisphere, and negative to the left.\n',...
'The model head sphere has a circumference of 2; the vertex\n',...
'(Cz) has arc_length 0. Locations with arc_length > 0.5 are below\n',...
'head center and are plotted outside the head cartoon.\n',...
'Option plotrad controls how much of this lower-head "skirt" is shown.\n',...
'Option headrad controls if and where the cartoon head will be drawn.\n',...
'Option intrad controls how many channels will be included in the interpolation.\n',...
])
return
end
end
end
if nargs < 2
loc_file = DEFAULT_ELOC;
if ~exist(loc_file)
fprintf('default locations file "%s" not found - specify chan_locs in topoplot() call.\n',loc_file)
error(' ')
end
end
if isempty(loc_file)
loc_file = 0;
end
if isnumeric(loc_file) & loc_file == 0
loc_file = DEFAULT_ELOC;
end
if nargs > 2
if ~(round(nargs/2) == nargs/2)
error('Odd number of input arguments??')
end
for i = 1:2:length(varargin)
Param = varargin{i};
Value = varargin{i+1};
if ~isstr(Param)
error('Flag arguments must be strings')
end
Param = lower(Param);
switch Param
case 'conv'
CONVHULL = lower(Value);
if ~strcmp(CONVHULL,'on') & ~strcmp(CONVHULL,'off')
error('Value of ''conv'' must be ''on'' or ''off''.');
end
case 'colormap'
if size(Value,2)~=3
error('Colormap must be a n x 3 matrix')
end
colormap(Value)
case 'plotdisk'
PLOTDISK = lower(Value);
if ~strcmp(PLOTDISK,'on') & ~strcmp(PLOTDISK,'off')
error('Value of ''plotdisk'' must be ''on'' or ''off''.');
end
case 'intsquare'
INTSQUARE = lower(Value);
if ~strcmp(INTSQUARE,'on') & ~strcmp(INTSQUARE,'off')
error('Value of ''intsquare'' must be ''on'' or ''off''.');
end
case 'emarkercolors'
COLORARRAY = Value;
case {'interplimits','headlimits'}
if ~isstr(Value)
error('''interplimits'' value must be a string')
end
Value = lower(Value);
if ~strcmp(Value,'electrodes') & ~strcmp(Value,'head')
error('Incorrect value for interplimits')
end
INTERPLIMITS = Value;
case 'verbose'
VERBOSE = Value;
case 'nosedir'
NOSEDIR = Value;
if isempty(strmatch(lower(NOSEDIR), { '+x', '-x', '+y', '-y' }))
error('Invalid nose direction');
end;
case 'chaninfo'
CHANINFO = Value;
if isfield(CHANINFO, 'nosedir'), NOSEDIR = CHANINFO.nosedir; end;
if isfield(CHANINFO, 'shrink' ), shrinkfactor = CHANINFO.shrink; end;
if isfield(CHANINFO, 'plotrad') & isempty(plotrad), plotrad = CHANINFO.plotrad; end;
if isfield(CHANINFO, 'chantype')
chantype = CHANINFO.chantype;
if ischar(chantype), chantype = cellstr(chantype); end
CHOOSECHANTYPE = 1;
end
case 'chantype'
chantype = Value;
CHOOSECHANTYPE = 1;
if ischar(chantype), chantype = cellstr(chantype); end
if ~iscell(chantype), error('chantype must be cell array. e.g. {''EEG'', ''EOG''}'); end
case 'drawaxis'
DRAWAXIS = Value;
case 'maplimits'
MAPLIMITS = Value;
case 'masksurf'
MASKSURF = Value;
case 'circgrid'
CIRCGRID = Value;
if isstr(CIRCGRID) | CIRCGRID<100
error('''circgrid'' value must be an int > 100');
end
case 'style'
STYLE = lower(Value);
case 'numcontour'
CONTOURNUM = Value;
case 'electrodes'
ELECTRODES = lower(Value);
if strcmpi(ELECTRODES,'pointlabels') | strcmpi(ELECTRODES,'ptslabels') ...
| strcmpi(ELECTRODES,'labelspts') | strcmpi(ELECTRODES,'ptlabels') ...
| strcmpi(ELECTRODES,'labelpts')
ELECTRODES = 'labelpoint'; % backwards compatability
elseif strcmpi(ELECTRODES,'pointnumbers') | strcmpi(ELECTRODES,'ptsnumbers') ...
| strcmpi(ELECTRODES,'numberspts') | strcmpi(ELECTRODES,'ptnumbers') ...
| strcmpi(ELECTRODES,'numberpts') | strcmpi(ELECTRODES,'ptsnums') ...
| strcmpi(ELECTRODES,'numspts')
ELECTRODES = 'numpoint'; % backwards compatability
elseif strcmpi(ELECTRODES,'nums')
ELECTRODES = 'numbers'; % backwards compatability
elseif strcmpi(ELECTRODES,'pts')
ELECTRODES = 'on'; % backwards compatability
elseif ~strcmp(ELECTRODES,'off') ...
& ~strcmpi(ELECTRODES,'on') ...
& ~strcmp(ELECTRODES,'labels') ...
& ~strcmpi(ELECTRODES,'numbers') ...
& ~strcmpi(ELECTRODES,'labelpoint') ...
& ~strcmpi(ELECTRODES,'numpoint')
error('Unknown value for keyword ''electrodes''');
end
case 'dipole'
DIPOLE = Value;
case 'dipsphere'
DIPSPHERE = Value;
case 'dipnorm'
DIPNORM = Value;
case 'diplen'
DIPLEN = Value;
case 'dipscale'
DIPSCALE = Value;
case 'contourvals'
ContourVals = Value;
case 'pmask'
ContourVals = Value;
PMASKFLAG = 1;
case 'diporient'
DIPORIENT = Value;
case 'dipcolor'
DIPCOLOR = Value;
case 'emarker'
if ischar(Value)
EMARKER = Value;
elseif ~iscell(Value) | length(Value) > 4
error('''emarker'' argument must be a cell array {marker color size linewidth}')
else
EMARKER = Value{1};
end
if length(Value) > 1
ECOLOR = Value{2};
end
if length(Value) > 2
EMARKERSIZE = Value{3};
end
if length(Value) > 3
EMARKERLINEWIDTH = Value{4};
end
case 'emarker2'
if ~iscell(Value) | length(Value) > 5
error('''emarker2'' argument must be a cell array {chans marker color size linewidth}')
end
EMARKER2CHANS = abs(Value{1}); % ignore channels < 0
if length(Value) > 1
EMARKER2 = Value{2};
end
if length(Value) > 2
EMARKER2COLOR = Value{3};
end
if length(Value) > 3
EMARKERSIZE2 = Value{4};
end
if length(Value) > 4
EMARKER2LINEWIDTH = Value{5};
end
case 'shrink'
shrinkfactor = Value;
case 'intrad'
intrad = Value;
if isstr(intrad) | (intrad < MINPLOTRAD | intrad > 1)
error('intrad argument should be a number between 0.15 and 1.0');
end
case 'plotrad'
plotrad = Value;
if isstr(plotrad) | (plotrad < MINPLOTRAD | plotrad > 1)
error('plotrad argument should be a number between 0.15 and 1.0');
end
case 'headrad'
headrad = Value;
if isstr(headrad) & ( strcmpi(headrad,'off') | strcmpi(headrad,'none') )
headrad = 0; % undocumented 'no head' alternatives
end
if isempty(headrad) % [] -> none also
headrad = 0;
end
if ~isstr(headrad)
if ~(headrad==0) & (headrad < MINPLOTRAD | headrad>1)
error('bad value for headrad');
end
elseif ~strcmpi(headrad,'rim')
error('bad value for headrad');
end
case {'headcolor','hcolor'}
HEADCOLOR = Value;
case {'contourcolor','ccolor'}
CCOLOR = Value;
case {'electcolor','ecolor'}
ECOLOR = Value;
case {'emarkersize','emsize'}
EMARKERSIZE = Value;
case {'emarkersize1chan','emarkersizemark'}
EMARKERSIZE1CHAN= Value;
case {'efontsize','efsize'}
EFSIZE = Value;
case 'shading'
SHADING = lower(Value);
if ~any(strcmp(SHADING,{'flat','interp'}))
error('Invalid shading parameter')
end
if strcmpi(SHADING,'interp') && isempty(warningInterp)
warning('Using interpolated shading in scalp topographies prevent to export them as vectorized figures');
warningInterp = 1;
end;
case 'noplot'
noplot = Value;
if ~isstr(noplot)
if length(noplot) ~= 2
error('''noplot'' location should be [radius, angle]')
else
chanrad = noplot(1);
chantheta = noplot(2);
noplot = 'on';
end
end
case 'gridscale'
GRID_SCALE = Value;
if isstr(GRID_SCALE) | GRID_SCALE ~= round(GRID_SCALE) | GRID_SCALE < 32
error('''gridscale'' value must be integer > 32.');
end
case {'plotgrid','gridplot'}
plotgrid = 'on';
gridchans = Value;
case 'plotchans'
plotchans = Value(:);
if find(plotchans<=0)
error('''plotchans'' values must be > 0');
end
% if max(abs(plotchans))>max(Values) | max(abs(plotchans))>length(Values) -sm ???
case {'whitebk','whiteback','forprint'}
whitebk = Value;
otherwise
error(['Unknown input parameter ''' Param ''' ???'])
end
end
end
if strcmpi(whitebk, 'on')
BACKCOLOR = [ 1 1 1 ];
end;
if isempty(find(strcmp(varargin,'colormap')))
cmap = colormap(DEFAULT_COLORMAP);
else
cmap = colormap;
end
cmaplen = size(cmap,1);
if strcmp(STYLE,'blank') % else if Values holds numbers of channels to mark
if length(Values) < length(loc_file)
ContourVals = zeros(1,length(loc_file));
ContourVals(Values) = 1;
Values = ContourVals;
end;
end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%% test args for plotting an electrode grid %%%%%%%%%%%%%%%%%%%%%%
%
if strcmp(plotgrid,'on')
STYLE = 'grid';
gchans = sort(find(abs(gridchans(:))>0));
% if setdiff(gchans,unique(gchans))
% fprintf('topoplot() warning: ''plotgrid'' channel matrix has duplicate channels\n');
% end
if ~isempty(plotchans)
if intersect(gchans,abs(plotchans))
fprintf('topoplot() warning: ''plotgrid'' and ''plotchans'' have channels in common\n');
end
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%% misc arg tests %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isempty(ELECTRODES) % if electrode labeling not specified
if length(Values) > MAXDEFAULTSHOWLOCS % if more channels than default max
ELECTRODES = 'off'; % don't show electrodes
else % else if fewer chans,
ELECTRODES = 'on'; % do
end
end
if isempty(Values)
STYLE = 'blank';
end
[r,c] = size(Values);
if r>1 & c>1,
error('input data must be a single vector');
end
Values = Values(:); % make Values a column vector
ContourVals = ContourVals(:); % values for contour
if ~isempty(intrad) & ~isempty(plotrad) & intrad < plotrad
error('intrad must be >= plotrad');
end
if ~strcmpi(STYLE,'grid') % if not plot grid only
%
%%%%%%%%%%%%%%%%%%%% Read the channel location information %%%%%%%%%%%%%%%%%%%%%%%%
%
if isstr(loc_file)
[tmpeloc labels Th Rd indices] = readlocs( loc_file);
elseif isstruct(loc_file) % a locs struct
[tmpeloc labels Th Rd indices] = readlocs( loc_file );
% Note: Th and Rd correspond to indices channels-with-coordinates only
else
error('loc_file must be a EEG.locs struct or locs filename');
end
Th = pi/180*Th; % convert degrees to radians
allchansind = 1:length(Th);
if ~isempty(plotchans)
if max(plotchans) > length(Th)
error('''plotchans'' values must be <= max channel index');
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% channels to plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(plotchans)
plotchans = intersect_bc(plotchans, indices);
end;
if ~isempty(Values) & ~strcmpi( STYLE, 'blank') & isempty(plotchans)
plotchans = indices;
end
if isempty(plotchans) & strcmpi( STYLE, 'blank')
plotchans = indices;
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%% filter for channel type(s), if specified %%%%%%%%%%%%%%%%%%%%%
%
if CHOOSECHANTYPE,
newplotchans = eeg_chantype(loc_file,chantype);
plotchans = intersect_bc(newplotchans, plotchans);
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%% filter channels used for components %%%%%%%%%%%%%%%%%%%%%
%
if isfield(CHANINFO, 'icachansind') & ~isempty(Values) & length(Values) ~= length(tmpeloc)
% test if ICA component
% ---------------------
if length(CHANINFO.icachansind) == length(Values)
% if only a subset of channels are to be plotted
% and ICA components also use a subject of channel
% we must find the new indices for these channels
plotchans = intersect_bc(CHANINFO.icachansind, plotchans);
tmpvals = zeros(1, length(tmpeloc));
tmpvals(CHANINFO.icachansind) = Values;
Values = tmpvals;
tmpvals = zeros(1, length(tmpeloc));
tmpvals(CHANINFO.icachansind) = ContourVals;
ContourVals = tmpvals;
end;
end;
%
%%%%%%%%%%%%%%%%%%% last channel is reference? %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if length(tmpeloc) == length(Values) + 1 % remove last channel if necessary
% (common reference channel)
if plotchans(end) == length(tmpeloc)
plotchans(end) = [];
end;
end;
%
%%%%%%%%%%%%%%%%%%% remove infinite and NaN values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if length(Values) > 1
inds = union_bc(find(isnan(Values)), find(isinf(Values))); % NaN and Inf values
plotchans = setdiff_bc(plotchans, inds);
end;
if strcmp(plotgrid,'on')
plotchans = setxor(plotchans,gchans); % remove grid chans from head plotchans
end
[x,y] = pol2cart(Th,Rd); % transform electrode locations from polar to cartesian coordinates
plotchans = abs(plotchans); % reverse indicated channel polarities
allchansind = allchansind(plotchans);
Th = Th(plotchans);
Rd = Rd(plotchans);
x = x(plotchans);
y = y(plotchans);
labels = labels(plotchans); % remove labels for electrodes without locations
labels = strvcat(labels); % make a label string matrix
if ~isempty(Values) & length(Values) > 1
Values = Values(plotchans);
ContourVals = ContourVals(plotchans);
end;
%
%%%%%%%%%%%%%%%%%% Read plotting radius from chanlocs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isempty(plotrad) & isfield(tmpeloc, 'plotrad'),
plotrad = tmpeloc(1).plotrad;
if isstr(plotrad) % plotrad shouldn't be a string
plotrad = str2num(plotrad) % just checking
end
if plotrad < MINPLOTRAD | plotrad > 1.0
fprintf('Bad value (%g) for plotrad.\n',plotrad);
error(' ');
end
if strcmpi(VERBOSE,'on') & ~isempty(plotrad)
fprintf('Plotting radius plotrad (%g) set from EEG.chanlocs.\n',plotrad);
end
end;
if isempty(plotrad)
plotrad = min(1.0,max(Rd)*1.02); % default: just outside the outermost electrode location
plotrad = max(plotrad,0.5); % default: plot out to the 0.5 head boundary
end % don't plot channels with Rd > 1 (below head)
if isempty(intrad)
default_intrad = 1; % indicator for (no) specified intrad
intrad = min(1.0,max(Rd)*1.02); % default: just outside the outermost electrode location
else
default_intrad = 0; % indicator for (no) specified intrad
if plotrad > intrad
plotrad = intrad;
end
end % don't interpolate channels with Rd > 1 (below head)
if isstr(plotrad) | plotrad < MINPLOTRAD | plotrad > 1.0
error('plotrad must be between 0.15 and 1.0');
end
%
%%%%%%%%%%%%%%%%%%%%%%% Set radius of head cartoon %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isempty(headrad) % never set -> defaults
if plotrad >= rmax
headrad = rmax; % (anatomically correct)
else % if plotrad < rmax
headrad = 0; % don't plot head
if strcmpi(VERBOSE, 'on')
fprintf('topoplot(): not plotting cartoon head since plotrad (%5.4g) < 0.5\n',...
plotrad);
end
end
elseif strcmpi(headrad,'rim') % force plotting at rim of map
headrad = plotrad;
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Shrink mode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(shrinkfactor) | isfield(tmpeloc, 'shrink'),
if isempty(shrinkfactor) & isfield(tmpeloc, 'shrink'),
shrinkfactor = tmpeloc(1).shrink;
if strcmpi(VERBOSE,'on')
if isstr(shrinkfactor)
fprintf('Automatically shrinking coordinates to lie above the head perimter.\n');
else
fprintf('Automatically shrinking coordinates by %3.2f\n', shrinkfactor);
end;
end
end;
if isstr(shrinkfactor)
if strcmpi(shrinkfactor, 'on') | strcmpi(shrinkfactor, 'force') | strcmpi(shrinkfactor, 'auto')
if abs(headrad-rmax) > 1e-2
fprintf(' NOTE -> the head cartoon will NOT accurately indicate the actual electrode locations\n');
end
if strcmpi(VERBOSE,'on')
fprintf(' Shrink flag -> plotting cartoon head at plotrad\n');
end
headrad = plotrad; % plot head around outer electrodes, no matter if 0.5 or not
end
else % apply shrinkfactor
plotrad = rmax/(1-shrinkfactor);
headrad = plotrad; % make deprecated 'shrink' mode plot
if strcmpi(VERBOSE,'on')
fprintf(' %g%% shrink applied.');
if abs(headrad-rmax) > 1e-2
fprintf(' Warning: With this "shrink" setting, the cartoon head will NOT be anatomically correct.\n');
else
fprintf('\n');
end
end
end
end; % if shrink
%
%%%%%%%%%%%%%%%%% Issue warning if headrad ~= rmax %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if headrad ~= 0.5 & strcmpi(VERBOSE, 'on')
fprintf(' NB: Plotting map using ''plotrad'' %-4.3g,',plotrad);
fprintf( ' ''headrad'' %-4.3g\n',headrad);
fprintf('Warning: The plotting radius of the cartoon head is NOT anatomically correct (0.5).\n')
end
%
%%%%%%%%%%%%%%%%%%%%% Find plotting channels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
pltchans = find(Rd <= plotrad); % plot channels inside plotting circle
if strcmpi(INTSQUARE,'on') % interpolate channels in the radius intrad square
intchans = find(x <= intrad & y <= intrad); % interpolate and plot channels inside interpolation square
else
intchans = find(Rd <= intrad); % interpolate channels in the radius intrad circle only
end
%
%%%%%%%%%%%%%%%%%%%%% Eliminate channels not plotted %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
allx = x;
ally = y;
intchans; % interpolate using only the 'intchans' channels
pltchans; % plot using only indicated 'plotchans' channels
if length(pltchans) < length(Rd) & strcmpi(VERBOSE, 'on')
fprintf('Interpolating %d and plotting %d of the %d scalp electrodes.\n', ...
length(intchans),length(pltchans),length(Rd));
end;
% fprintf('topoplot(): plotting %d channels\n',length(pltchans));
if ~isempty(EMARKER2CHANS)
if strcmpi(STYLE,'blank')
error('emarker2 not defined for style ''blank'' - use marking channel numbers in place of data');
else % mark1chans and mark2chans are subsets of pltchans for markers 1 and 2
[tmp1 mark1chans tmp2] = setxor(pltchans,EMARKER2CHANS);
[tmp3 tmp4 mark2chans] = intersect_bc(EMARKER2CHANS,pltchans);
end
end
if ~isempty(Values)
if length(Values) == length(Th) % if as many map Values as channel locs
intValues = Values(intchans);
intContourVals = ContourVals(intchans);
Values = Values(pltchans);
ContourVals = ContourVals(pltchans);
end;
end; % now channel parameters and values all refer to plotting channels only
allchansind = allchansind(pltchans);
intTh = Th(intchans); % eliminate channels outside the interpolation area
intRd = Rd(intchans);
intx = x(intchans);
inty = y(intchans);
Th = Th(pltchans); % eliminate channels outside the plotting area
Rd = Rd(pltchans);
x = x(pltchans);
y = y(pltchans);
labels= labels(pltchans,:);
%
%%%%%%%%%%%%%%% Squeeze channel locations to <= rmax %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
squeezefac = rmax/plotrad;
intRd = intRd*squeezefac; % squeeze electrode arc_lengths towards the vertex
Rd = Rd*squeezefac; % squeeze electrode arc_lengths towards the vertex
% to plot all inside the head cartoon
intx = intx*squeezefac;
inty = inty*squeezefac;
x = x*squeezefac;
y = y*squeezefac;
allx = allx*squeezefac;
ally = ally*squeezefac;
% Note: Now outermost channel will be plotted just inside rmax
else % if strcmpi(STYLE,'grid')
intx = rmax; inty=rmax;
end % if ~strcmpi(STYLE,'grid')
%
%%%%%%%%%%%%%%%% rotate channels based on chaninfo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(lower(NOSEDIR), '+x')
rotate = 0;
else
if strcmpi(lower(NOSEDIR), '+y')
rotate = 3*pi/2;
elseif strcmpi(lower(NOSEDIR), '-x')
rotate = pi;
else rotate = pi/2;
end;
allcoords = (inty + intx*sqrt(-1))*exp(sqrt(-1)*rotate);
intx = imag(allcoords);
inty = real(allcoords);
allcoords = (ally + allx*sqrt(-1))*exp(sqrt(-1)*rotate);
allx = imag(allcoords);
ally = real(allcoords);
allcoords = (y + x*sqrt(-1))*exp(sqrt(-1)*rotate);
x = imag(allcoords);
y = real(allcoords);
end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Make the plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~strcmpi(STYLE,'blank') % if draw interpolated scalp map
if ~strcmpi(STYLE,'grid') % not a rectangular channel grid
%
%%%%%%%%%%%%%%%% Find limits for interpolation %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if default_intrad % if no specified intrad
if strcmpi(INTERPLIMITS,'head') % intrad is 'head'
xmin = min(-rmax,min(intx)); xmax = max(rmax,max(intx));
ymin = min(-rmax,min(inty)); ymax = max(rmax,max(inty));
else % INTERPLIMITS = rectangle containing electrodes -- DEPRECATED OPTION!
xmin = max(-rmax,min(intx)); xmax = min(rmax,max(intx));
ymin = max(-rmax,min(inty)); ymax = min(rmax,max(inty));
end
else % some other intrad specified
xmin = -intrad*squeezefac; xmax = intrad*squeezefac; % use the specified intrad value
ymin = -intrad*squeezefac; ymax = intrad*squeezefac;
end
%
%%%%%%%%%%%%%%%%%%%%%%% Interpolate scalp map data %%%%%%%%%%%%%%%%%%%%%%%%
%
xi = linspace(xmin,xmax,GRID_SCALE); % x-axis description (row vector)
yi = linspace(ymin,ymax,GRID_SCALE); % y-axis description (row vector)
try
[Xi,Yi,Zi] = griddata(inty,intx,double(intValues),yi',xi,'v4'); % interpolate data
[Xi,Yi,ZiC] = griddata(inty,intx,double(intContourVals),yi',xi,'v4'); % interpolate data
catch,
[Xi,Yi,Zi] = griddata(inty,intx,intValues',yi,xi'); % interpolate data (Octave)
[Xi,Yi,ZiC] = griddata(inty,intx,intContourVals',yi,xi'); % interpolate data
end;
%
%%%%%%%%%%%%%%%%%%%%%%% Mask out data outside the head %%%%%%%%%%%%%%%%%%%%%
%
mask = (sqrt(Xi.^2 + Yi.^2) <= rmax); % mask outside the plotting circle
ii = find(mask == 0);
Zi(ii) = NaN; % mask non-plotting voxels with NaNs
ZiC(ii) = NaN; % mask non-plotting voxels with NaNs
grid = plotrad; % unless 'noplot', then 3rd output arg is plotrad
%
%%%%%%%%%% Return interpolated value at designated scalp location %%%%%%%%%%
%
if exist('chanrad') % optional first argument to 'noplot'
chantheta = (chantheta/360)*2*pi;
chancoords = round(ceil(GRID_SCALE/2)+GRID_SCALE/2*2*chanrad*[cos(-chantheta),...
-sin(-chantheta)]);
if chancoords(1)<1 ...
| chancoords(1) > GRID_SCALE ...
| chancoords(2)<1 ...
| chancoords(2)>GRID_SCALE
error('designated ''noplot'' channel out of bounds')
else
chanval = Zi(chancoords(1),chancoords(2));
grid = Zi;
Zi = chanval; % return interpolated value instead of Zi
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%% Return interpolated image only %%%%%%%%%%%%%%%%%
%
if strcmpi(noplot, 'on')
if strcmpi(VERBOSE,'on')
fprintf('topoplot(): no plot requested.\n')
end
return;
end
%
%%%%%%%%%%%%%%%%%%%%%%% Calculate colormap limits %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isstr(MAPLIMITS)
if strcmp(MAPLIMITS,'absmax')
amax = max(max(abs(Zi)));
amin = -amax;
elseif strcmp(MAPLIMITS,'maxmin') | strcmp(MAPLIMITS,'minmax')
amin = min(min(Zi));
amax = max(max(Zi));
else
error('unknown ''maplimits'' value.');
end
elseif length(MAPLIMITS) == 2
amin = MAPLIMITS(1);
amax = MAPLIMITS(2);
else
error('unknown ''maplimits'' value');
end
delta = xi(2)-xi(1); % length of grid entry
end % if ~strcmpi(STYLE,'grid')
%
%%%%%%%%%%%%%%%%%%%%%%%%%% Scale the axes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%cla % clear current axis
hold on
h = gca; % uses current axes
% instead of default larger AXHEADFAC
if squeezefac<0.92 & plotrad-headrad > 0.05 % (size of head in axes)
AXHEADFAC = 1.05; % do not leave room for external ears if head cartoon
% shrunk enough by the 'skirt' option
end
set(gca,'Xlim',[-rmax rmax]*AXHEADFAC,'Ylim',[-rmax rmax]*AXHEADFAC);
% specify size of head axes in gca
unsh = (GRID_SCALE+1)/GRID_SCALE; % un-shrink the effects of 'interp' SHADING
%
%%%%%%%%%%%%%%%%%%%%%%%% Plot grid only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
disp('Warning: When plotting pvalues in totoplot, use option ''conv'' to minimize extrapolation effects');
if strcmpi(STYLE,'grid') % plot grid only
%
% The goal below is to make the grid cells square - not yet achieved in all cases? -sm
%
g1 = size(gridchans,1);
g2 = size(gridchans,2);
gmax = max([g1 g2]);
Xi = linspace(-rmax*g2/gmax,rmax*g2/gmax,g1+1);
Xi = Xi+rmax/g1; Xi = Xi(1:end-1);
Yi = linspace(-rmax*g1/gmax,rmax*g1/gmax,g2+1);
Yi = Yi+rmax/g2; Yi = Yi(1:end-1); Yi = Yi(end:-1:1); % by trial and error!
%
%%%%%%%%%%% collect the gridchans values %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
gridvalues = zeros(size(gridchans));
for j=1:size(gridchans,1)
for k=1:size(gridchans,2)
gc = gridchans(j,k);
if gc > 0
gridvalues(j,k) = Values(gc);
elseif gc < 0
gridvalues(j,k) = -Values(gc);
else
gridvalues(j,k) = nan; % not-a-number = no value
end
end
end
%
%%%%%%%%%%% reset color limits for grid plot %%%%%%%%%%%%%%%%%%%%%%%%%
%
if isstr(MAPLIMITS)
if strcmp(MAPLIMITS,'maxmin') | strcmp(MAPLIMITS,'minmax')
amin = min(min(gridvalues(~isnan(gridvalues))));
amax = max(max(gridvalues(~isnan(gridvalues))));
elseif strcmp(MAPLIMITS,'absmax')
% 11/21/2005 Toby edit
% This should now work as specified. Before it only crashed (using
% "plotgrid" and "maplimits>absmax" options).
amax = max(max(abs(gridvalues(~isnan(gridvalues)))));
amin = -amax;
%amin = -max(max(abs([amin amax])));
%amax = max(max(abs([amin amax])));
else
error('unknown ''maplimits'' value');
end
elseif length(MAPLIMITS) == 2
amin = MAPLIMITS(1);
amax = MAPLIMITS(2);
else
error('unknown ''maplimits'' value');
end
%
%%%%%%%%%% explicitly compute grid colors, allowing BACKCOLOR %%%%%%
%
gridvalues = 1+floor(cmaplen*(gridvalues-amin)/(amax-amin));
gridvalues(find(gridvalues == cmaplen+1)) = cmaplen;
gridcolors = zeros([size(gridvalues),3]);
for j=1:size(gridchans,1)
for k=1:size(gridchans,2)
if ~isnan(gridvalues(j,k))
gridcolors(j,k,:) = cmap(gridvalues(j,k),:);
else
if strcmpi(whitebk,'off')
gridcolors(j,k,:) = BACKCOLOR; % gridchans == 0 -> background color
% This allows the plot to show 'space' between separate sub-grids or strips
else % 'on'
gridcolors(j,k,:) = [1 1 1]; BACKCOLOR; % gridchans == 0 -> white for printing
end
end
end
end
%
%%%%%%%%%% draw the gridplot image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
handle=imagesc(Xi,Yi,gridcolors); % plot grid with explicit colors
axis square
%
%%%%%%%%%%%%%%%%%%%%%%%% Plot map contours only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(STYLE,'contour') % plot surface contours only
[cls chs] = contour(Xi,Yi,ZiC,CONTOURNUM,'k');
handle = chs; % handle to a contourgroup object
% for h=chs, set(h,'color',CCOLOR); end
%
%%%%%%%%%%%%%%%%%%%%%%%% Else plot map and contours %%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(STYLE,'both') % plot interpolated surface and surface contours
if strcmp(SHADING,'interp')
tmph = surface(Xi*unsh,Yi*unsh,zeros(size(Zi))-0.1,Zi,...
'EdgeColor','none','FaceColor',SHADING);
else % SHADING == 'flat'
tmph = surface(Xi-delta/2,Yi-delta/2,zeros(size(Zi))-0.1,Zi,...
'EdgeColor','none','FaceColor',SHADING);
end
if strcmpi(MASKSURF, 'on')
set(tmph, 'visible', 'off');
handle = tmph;
end;
warning off;
if ~PMASKFLAG
[cls chs] = contour(Xi,Yi,ZiC,CONTOURNUM,'k');
else
ZiC(find(ZiC > 0.5 )) = NaN;
[cls chs] = contourf(Xi,Yi,ZiC,0,'k');
subh = get(chs, 'children');
for indsubh = 1:length(subh)
numfaces = size(get(subh(indsubh), 'XData'),1);
set(subh(indsubh), 'FaceVertexCData', ones(numfaces,3), 'Cdatamapping', 'direct', 'facealpha', 0.5, 'linewidth', 2);
end;
end;
handle = tmph; % surface handle
for h=chs, set(h,'color',CCOLOR); end
warning on;
%
%%%%%%%%%%%%%%%%%%%%%%%% Else plot map only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(STYLE,'straight') | strcmp(STYLE,'map') % 'straight' was former arg
if strcmp(SHADING,'interp') % 'interp' mode is shifted somehow... but how?
tmph = surface(Xi*unsh,Yi*unsh,zeros(size(Zi)),Zi,'EdgeColor','none',...
'FaceColor',SHADING);
else
tmph = surface(Xi-delta/2,Yi-delta/2,zeros(size(Zi)),Zi,'EdgeColor','none',...
'FaceColor',SHADING);
end
if strcmpi(MASKSURF, 'on')
set(tmph, 'visible', 'off');
handle = tmph;
end;
handle = tmph; % surface handle
%
%%%%%%%%%%%%%%%%%% Else fill contours with uniform colors %%%%%%%%%%%%%%%%%%
%
elseif strcmp(STYLE,'fill')
[cls chs] = contourf(Xi,Yi,Zi,CONTOURNUM,'k');
handle = chs; % handle to a contourgroup object
% for h=chs, set(h,'color',CCOLOR); end
% <- 'not line objects.' Why does 'both' work above???
else
error('Invalid style')
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Set color axis %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% caxis([amin amax]); % set coloraxis
% 7/30/2014 Ramon: +-5% for the color limits were added
cax_sgn = sign([amin amax]); % getting sign
caxis([amin+cax_sgn(1)*(0.05*abs(amin)) amax+cax_sgn(2)*(0.05*abs(amax))]); % Adding 5% to the color limits
else % if STYLE 'blank'
%
%%%%%%%%%%%%%%%%%%%%%%% Draw blank head %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(noplot, 'on')
if strcmpi(VERBOSE,'on')
fprintf('topoplot(): no plot requested.\n')
end
return;
end
%cla
hold on
set(gca,'Xlim',[-rmax rmax]*AXHEADFAC,'Ylim',[-rmax rmax]*AXHEADFAC)
% pos = get(gca,'position');
% fprintf('Current axes size %g,%g\n',pos(3),pos(4));
if strcmp(ELECTRODES,'labelpoint') | strcmp(ELECTRODES,'numpoint')
text(-0.6,-0.6, ...
[ int2str(length(Rd)) ' of ' int2str(length(tmpeloc)) ' electrode locations shown']);
text(-0.6,-0.7, [ 'Click on electrodes to toggle name/number']);
tl = title('Channel locations');
set(tl, 'fontweight', 'bold');
end;
end % STYLE 'blank'
if exist('handle') ~= 1
handle = gca;
end;
if ~strcmpi(STYLE,'grid') % if not plot grid only
%
%%%%%%%%%%%%%%%%%%% Plot filled ring to mask jagged grid boundary %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
hwidth = HEADRINGWIDTH; % width of head ring
hin = squeezefac*headrad*(1- hwidth/2); % inner head ring radius
if strcmp(SHADING,'interp')
rwidth = BLANKINGRINGWIDTH*1.3; % width of blanking outer ring
else
rwidth = BLANKINGRINGWIDTH; % width of blanking outer ring
end
rin = rmax*(1-rwidth/2); % inner ring radius
if hin>rin
rin = hin; % dont blank inside the head ring
end
if strcmp(CONVHULL,'on') %%%%%%%%% mask outside the convex hull of the electrodes %%%%%%%%%
cnv = convhull(allx,ally);
cnvfac = round(CIRCGRID/length(cnv)); % spline interpolate the convex hull
if cnvfac < 1, cnvfac=1; end;
CIRCGRID = cnvfac*length(cnv);
startangle = atan2(allx(cnv(1)),ally(cnv(1)));
circ = linspace(0+startangle,2*pi+startangle,CIRCGRID);
rx = sin(circ);
ry = cos(circ);
allx = allx(:)'; % make x (elec locations; + to nose) a row vector
ally = ally(:)'; % make y (elec locations, + to r? ear) a row vector
erad = sqrt(allx(cnv).^2+ally(cnv).^2); % convert to polar coordinates
eang = atan2(allx(cnv),ally(cnv));
eang = unwrap(eang);
eradi =spline(linspace(0,1,3*length(cnv)), [erad erad erad], ...
linspace(0,1,3*length(cnv)*cnvfac));
eangi =spline(linspace(0,1,3*length(cnv)), [eang+2*pi eang eang-2*pi], ...
linspace(0,1,3*length(cnv)*cnvfac));
xx = eradi.*sin(eangi); % convert back to rect coordinates
yy = eradi.*cos(eangi);
yy = yy(CIRCGRID+1:2*CIRCGRID);
xx = xx(CIRCGRID+1:2*CIRCGRID);
eangi = eangi(CIRCGRID+1:2*CIRCGRID);
eradi = eradi(CIRCGRID+1:2*CIRCGRID);
xx = xx*1.02; yy = yy*1.02; % extend spline outside electrode marks
splrad = sqrt(xx.^2+yy.^2); % arc radius of spline points (yy,xx)
oob = find(splrad >= rin); % enforce an upper bound on xx,yy
xx(oob) = rin*xx(oob)./splrad(oob); % max radius = rin
yy(oob) = rin*yy(oob)./splrad(oob); % max radius = rin
splrad = sqrt(xx.^2+yy.^2); % arc radius of spline points (yy,xx)
oob = find(splrad < hin); % don't let splrad be inside the head cartoon
xx(oob) = hin*xx(oob)./splrad(oob); % min radius = hin
yy(oob) = hin*yy(oob)./splrad(oob); % min radius = hin
ringy = [[ry(:)' ry(1) ]*(rin+rwidth) yy yy(1)];
ringx = [[rx(:)' rx(1) ]*(rin+rwidth) xx xx(1)];
ringh2= patch(ringy,ringx,ones(size(ringy)),BACKCOLOR,'edgecolor','none'); hold on
% plot(ry*rmax,rx*rmax,'b') % debugging line
else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% mask the jagged border around rmax %%%%%%%%%%%%%%%5%%%%%%
circ = linspace(0,2*pi,CIRCGRID);
rx = sin(circ);
ry = cos(circ);
ringx = [[rx(:)' rx(1) ]*(rin+rwidth) [rx(:)' rx(1)]*rin];
ringy = [[ry(:)' ry(1) ]*(rin+rwidth) [ry(:)' ry(1)]*rin];
if ~strcmpi(STYLE,'blank')
ringh= patch(ringx,ringy,0.01*ones(size(ringx)),BACKCOLOR,'edgecolor','none'); hold on
end
% plot(ry*rmax,rx*rmax,'b') % debugging line
end
%f1= fill(rin*[rx rX],rin*[ry rY],BACKCOLOR,'edgecolor',BACKCOLOR); hold on
%f2= fill(rin*[rx rX*(1+rwidth)],rin*[ry rY*(1+rwidth)],BACKCOLOR,'edgecolor',BACKCOLOR);
% Former line-style border smoothing - width did not scale with plot
% brdr=plot(1.015*cos(circ).*rmax,1.015*sin(circ).*rmax,... % old line-based method
% 'color',HEADCOLOR,'Linestyle','-','LineWidth',HLINEWIDTH); % plot skirt outline
% set(brdr,'color',BACKCOLOR,'linewidth',HLINEWIDTH + 4); % hide the disk edge jaggies
%
%%%%%%%%%%%%%%%%%%%%%%%%% Plot cartoon head, ears, nose %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if headrad > 0 % if cartoon head to be plotted
%
%%%%%%%%%%%%%%%%%%% Plot head outline %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
headx = [[rx(:)' rx(1) ]*(hin+hwidth) [rx(:)' rx(1)]*hin];
heady = [[ry(:)' ry(1) ]*(hin+hwidth) [ry(:)' ry(1)]*hin];
if ~isstr(HEADCOLOR) | ~strcmpi(HEADCOLOR,'none')
%ringh= patch(headx,heady,ones(size(headx)),HEADCOLOR,'edgecolor',HEADCOLOR,'linewidth', HLINEWIDTH); hold on
headx = [rx(:)' rx(1)]*hin;
heady = [ry(:)' ry(1)]*hin;
ringh= plot(headx,heady);
set(ringh, 'color',HEADCOLOR,'linewidth', HLINEWIDTH); hold on
end
% rx = sin(circ); rX = rx(end:-1:1);
% ry = cos(circ); rY = ry(end:-1:1);
% for k=2:2:CIRCGRID
% rx(k) = rx(k)*(1+hwidth);
% ry(k) = ry(k)*(1+hwidth);
% end
% f3= fill(hin*[rx rX],hin*[ry rY],HEADCOLOR,'edgecolor',HEADCOLOR); hold on
% f4= fill(hin*[rx rX*(1+hwidth)],hin*[ry rY*(1+hwidth)],HEADCOLOR,'edgecolor',HEADCOLOR);
% Former line-style head
% plot(cos(circ).*squeezefac*headrad,sin(circ).*squeezefac*headrad,...
% 'color',HEADCOLOR,'Linestyle','-','LineWidth',HLINEWIDTH); % plot head outline
%
%%%%%%%%%%%%%%%%%%% Plot ears and nose %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
base = rmax-.0046;
basex = 0.18*rmax; % nose width
tip = 1.15*rmax;
tiphw = .04*rmax; % nose tip half width
tipr = .01*rmax; % nose tip rounding
q = .04; % ear lengthening
EarX = [.497-.005 .510 .518 .5299 .5419 .54 .547 .532 .510 .489-.005]; % rmax = 0.5
EarY = [q+.0555 q+.0775 q+.0783 q+.0746 q+.0555 -.0055 -.0932 -.1313 -.1384 -.1199];
sf = headrad/plotrad; % squeeze the model ears and nose
% by this factor
if ~isstr(HEADCOLOR) | ~strcmpi(HEADCOLOR,'none')
plot3([basex;tiphw;0;-tiphw;-basex]*sf,[base;tip-tipr;tip;tip-tipr;base]*sf,...
2*ones(size([basex;tiphw;0;-tiphw;-basex])),...
'Color',HEADCOLOR,'LineWidth',HLINEWIDTH); % plot nose
plot3(EarX*sf,EarY*sf,2*ones(size(EarX)),'color',HEADCOLOR,'LineWidth',HLINEWIDTH) % plot left ear
plot3(-EarX*sf,EarY*sf,2*ones(size(EarY)),'color',HEADCOLOR,'LineWidth',HLINEWIDTH) % plot right ear
end
end
%
% %%%%%%%%%%%%%%%%%%% Show electrode information %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
plotax = gca;
axis square % make plotax square
axis off
pos = get(gca,'position');
xlm = get(gca,'xlim');
ylm = get(gca,'ylim');
% textax = axes('position',pos,'xlim',xlm,'ylim',ylm); % make new axes so clicking numbers <-> labels
% will work inside head cartoon patch
% axes(textax);
axis square % make textax square
pos = get(gca,'position');
set(plotax,'position',pos);
xlm = get(gca,'xlim');
set(plotax,'xlim',xlm);
ylm = get(gca,'ylim');
set(plotax,'ylim',ylm); % copy position and axis limits again
axis equal;
set(gca, 'xlim', [-0.525 0.525]); set(plotax, 'xlim', [-0.525 0.525]);
set(gca, 'ylim', [-0.525 0.525]); set(plotax, 'ylim', [-0.525 0.525]);
%get(textax,'pos') % test if equal!
%get(plotax,'pos')
%get(textax,'xlim')
%get(plotax,'xlim')
%get(textax,'ylim')
%get(plotax,'ylim')
if isempty(EMARKERSIZE)
EMARKERSIZE = 10;
if length(y)>=160
EMARKERSIZE = 3;
elseif length(y)>=128
EMARKERSIZE = 3;
elseif length(y)>=100
EMARKERSIZE = 3;
elseif length(y)>=80
EMARKERSIZE = 4;
elseif length(y)>=64
EMARKERSIZE = 5;
elseif length(y)>=48
EMARKERSIZE = 6;
elseif length(y)>=32
EMARKERSIZE = 8;
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Mark electrode locations only %%%%%%%%%%%%%%%%%%%%%%%%%%
%
ELECTRODE_HEIGHT = 2.1; % z value for plotting electrode information (above the surf)
if strcmp(ELECTRODES,'on') % plot electrodes as spots
if isempty(EMARKER2CHANS)
hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
else % plot markers for normal chans and EMARKER2CHANS separately
hp2 = plot3(y(mark1chans),x(mark1chans),ones(size((mark1chans)))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
hp2b = plot3(y(mark2chans),x(mark2chans),ones(size((mark2chans)))*ELECTRODE_HEIGHT,...
EMARKER2,'Color',EMARKER2COLOR,'markerfacecolor',EMARKER2COLOR,'linewidth',EMARKER2LINEWIDTH,'markersize',EMARKERSIZE2);
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Print electrode labels only %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'labels') % print electrode names (labels)
for i = 1:size(labels,1)
text(double(y(i)),double(x(i)),...
ELECTRODE_HEIGHT,labels(i,:),'HorizontalAlignment','center',...
'VerticalAlignment','middle','Color',ECOLOR,...
'FontSize',EFSIZE)
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Mark electrode locations plus labels %%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'labelpoint')
if isempty(EMARKER2CHANS)
hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
else
hp2 = plot3(y(mark1chans),x(mark1chans),ones(size((mark1chans)))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
hp2b = plot3(y(mark2chans),x(mark2chans),ones(size((mark2chans)))*ELECTRODE_HEIGHT,...
EMARKER2,'Color',EMARKER2COLOR,'markerfacecolor',EMARKER2COLOR,'linewidth',EMARKER2LINEWIDTH,'markersize',EMARKERSIZE2);
end
for i = 1:size(labels,1)
hh(i) = text(double(y(i)+0.01),double(x(i)),...
ELECTRODE_HEIGHT,labels(i,:),'HorizontalAlignment','left',...
'VerticalAlignment','middle','Color', ECOLOR,'userdata', num2str(allchansind(i)), ...
'FontSize',EFSIZE, 'buttondownfcn', ...
['tmpstr = get(gco, ''userdata'');'...
'set(gco, ''userdata'', get(gco, ''string''));' ...
'set(gco, ''string'', tmpstr); clear tmpstr;'] );
end
%
%%%%%%%%%%%%%%%%%%%%%%% Mark electrode locations plus numbers %%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'numpoint')
if isempty(EMARKER2CHANS)
hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
else
hp2 = plot3(y(mark1chans),x(mark1chans),ones(size((mark1chans)))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
hp2b = plot3(y(mark2chans),x(mark2chans),ones(size((mark2chans)))*ELECTRODE_HEIGHT,...
EMARKER2,'Color',EMARKER2COLOR,'markerfacecolor',EMARKER2COLOR,'linewidth',EMARKER2LINEWIDTH,'markersize',EMARKERSIZE2);
end
for i = 1:size(labels,1)
hh(i) = text(double(y(i)+0.01),double(x(i)),...
ELECTRODE_HEIGHT,num2str(allchansind(i)),'HorizontalAlignment','left',...
'VerticalAlignment','middle','Color', ECOLOR,'userdata', labels(i,:) , ...
'FontSize',EFSIZE, 'buttondownfcn', ...
['tmpstr = get(gco, ''userdata'');'...
'set(gco, ''userdata'', get(gco, ''string''));' ...
'set(gco, ''string'', tmpstr); clear tmpstr;'] );
end
%
%%%%%%%%%%%%%%%%%%%%%% Print electrode numbers only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'numbers')
for i = 1:size(labels,1)
text(double(y(i)),double(x(i)),...
ELECTRODE_HEIGHT,int2str(allchansind(i)),'HorizontalAlignment','center',...
'VerticalAlignment','middle','Color',ECOLOR,...
'FontSize',EFSIZE)
end
%
%%%%%%%%%%%%%%%%%%%%%% Mark emarker2 electrodes only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'off') & ~isempty(EMARKER2CHANS)
hp2b = plot3(y(mark2chans),x(mark2chans),ones(size((mark2chans)))*ELECTRODE_HEIGHT,...
EMARKER2,'Color',EMARKER2COLOR,'markerfacecolor',EMARKER2COLOR,'linewidth',EMARKER2LINEWIDTH,'markersize',EMARKERSIZE2);
end
%
%%%%%%%% Mark specified electrode locations with red filled disks %%%%%%%%%%%%%%%%%%%%%%
%
try,
if strcmpi(STYLE,'blank') % if mark-selected-channel-locations mode
for kk = 1:length(1:length(x))
if abs(Values(kk))
if PLOTDISK
angleRatio = real(Values(kk))/(real(Values(kk))+imag(Values(kk)))*360;
radius = real(Values(kk))+imag(Values(kk));
allradius = [0.02 0.03 0.037 0.044 0.05];
radius = allradius(radius);
hp2 = disk(y(kk),x(kk),radius, [1 0 0], 0 , angleRatio, 16);
if angleRatio ~= 360
hp2 = disk(y(kk),x(kk),radius, [0 0 1], angleRatio, 360, 16);
end;
else
tmpcolor = COLORARRAY{max(1,min(Values(kk), length(COLORARRAY)))};
hp2 = plot3(y(kk),x(kk),ELECTRODE_HEIGHT,EMARKER,'Color', tmpcolor, 'markersize', EMARKERSIZE1CHAN);
hp2 = disk(y(kk),x(kk),0.04, tmpcolor, 0, 360, 10);
end;
end;
end
end
catch, end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%% Plot dipole(s) on the scalp map %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(DIPOLE)
hold on;
tmp = DIPOLE;
if isstruct(DIPOLE)
if ~isfield(tmp,'posxyz')
error('dipole structure is not an EEG.dipfit.model')
end
DIPOLE = []; % Note: invert x and y from dipplot usage
DIPOLE(:,1) = -tmp.posxyz(:,2)/DIPSPHERE; % -y -> x
DIPOLE(:,2) = tmp.posxyz(:,1)/DIPSPHERE; % x -> y
DIPOLE(:,3) = -tmp.momxyz(:,2);
DIPOLE(:,4) = tmp.momxyz(:,1);
else
DIPOLE(:,1) = -tmp(:,2); % same for vector input
DIPOLE(:,2) = tmp(:,1);
DIPOLE(:,3) = -tmp(:,4);
DIPOLE(:,4) = tmp(:,3);
end;
for index = 1:size(DIPOLE,1)
if ~any(DIPOLE(index,:))
DIPOLE(index,:) = [];
end
end;
DIPOLE(:,1:4) = DIPOLE(:,1:4)*rmax*(rmax/plotrad); % scale radius from 1 -> rmax (0.5)
DIPOLE(:,3:end) = (DIPOLE(:,3:end))*rmax/100000*(rmax/plotrad);
if strcmpi(DIPNORM, 'on')
for index = 1:size(DIPOLE,1)
DIPOLE(index,3:4) = DIPOLE(index,3:4)/norm(DIPOLE(index,3:end))*0.2;
end;
end;
DIPOLE(:, 3:4) = DIPORIENT*DIPOLE(:, 3:4)*DIPLEN;
PLOT_DIPOLE=1;
if sum(DIPOLE(1,3:4).^2) <= 0.00001
if strcmpi(VERBOSE,'on')
fprintf('Note: dipole is length 0 - not plotted\n')
end
PLOT_DIPOLE = 0;
end
if 0 % sum(DIPOLE(1,1:2).^2) > plotrad
if strcmpi(VERBOSE,'on')
fprintf('Note: dipole is outside plotting area - not plotted\n')
end
PLOT_DIPOLE = 0;
end
if PLOT_DIPOLE
for index = 1:size(DIPOLE,1)
hh = plot( DIPOLE(index, 1), DIPOLE(index, 2), '.');
set(hh, 'color', DIPCOLOR, 'markersize', DIPSCALE*30);
hh = line( [DIPOLE(index, 1) DIPOLE(index, 1)+DIPOLE(index, 3)]', ...
[DIPOLE(index, 2) DIPOLE(index, 2)+DIPOLE(index, 4)]',[10 10]);
set(hh, 'color', DIPCOLOR, 'linewidth', DIPSCALE*30/7);
end;
end;
end;
end % if ~ 'gridplot'
%
%%%%%%%%%%%%% Plot axis orientation %%%%%%%%%%%%%%%%%%%%
%
if strcmpi(DRAWAXIS, 'on')
axes('position', [0 0.85 0.08 0.1]);
axis off;
coordend1 = sqrt(-1)*3;
coordend2 = -3;
coordend1 = coordend1*exp(sqrt(-1)*rotate);
coordend2 = coordend2*exp(sqrt(-1)*rotate);
line([5 5+round(real(coordend1))]', [5 5+round(imag(coordend1))]', 'color', 'k');
line([5 5+round(real(coordend2))]', [5 5+round(imag(coordend2))]', 'color', 'k');
if round(real(coordend2))<0
text( 5+round(real(coordend2))*1.2, 5+round(imag(coordend2))*1.2-2, '+Y');
else text( 5+round(real(coordend2))*1.2, 5+round(imag(coordend2))*1.2, '+Y');
end;
if round(real(coordend1))<0
text( 5+round(real(coordend1))*1.2, 5+round(imag(coordend1))*1.2+1.5, '+X');
else text( 5+round(real(coordend1))*1.2, 5+round(imag(coordend1))*1.2, '+X');
end;
set(gca, 'xlim', [0 10], 'ylim', [0 10]);
end;
%
%%%%%%%%%%%%% Set EEGLAB background color to match head border %%%%%%%%%%%%%%%%%%%%%%%%
%
try,
set(gcf, 'color', BACKCOLOR);
catch,
end;
hold off
axis off
return
%
%%%%%%%%%%%%% Draw circle %%%%%%%%%%%%%%%%%%%%%%%%
%
function h2 = disk(X, Y, radius, colorfill, oriangle, endangle, segments)
A = linspace(oriangle/180*pi, endangle/180*pi, segments-1);
if endangle-oriangle == 360
A = linspace(oriangle/180*pi, endangle/180*pi, segments);
h2 = patch( [X + cos(A)*radius(1)], [Y + sin(A)*radius(end)], zeros(1,segments)+3, colorfill);
else A = linspace(oriangle/180*pi, endangle/180*pi, segments-1);
h2 = patch( [X X + cos(A)*radius(1)], [Y Y + sin(A)*radius(end)], zeros(1,segments)+3, colorfill);
end;
set(h2, 'FaceColor', colorfill);
set(h2, 'EdgeColor', 'none');
|
github
|
lcnhappe/happe-master
|
readegilocs.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/readegilocs.m
| 2,898 |
utf_8
|
db357ca683b59cbb87ff64dc2cc5bb0b
|
% readegilocs() - look up locations for EGI EEG dataset.
%
% Usage:
% >> EEG = readegilocs(EEG);
% >> EEG = readegilocs(EEG, fileloc);
%
% Inputs:
% EEG - EEGLAB data structure
%
% Optional input:
% fileloc - EGI channel location file
%
% Outputs:
% EEG - EEGLAB data structure with channel location structure
%
% Author: Arnaud Delorme, SCCN/UCSD
%
% See also: pop_readegi(), readegi()
% Copyright (C) 12 Nov 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 EEG = readegilocs(EEG, fileloc);
if nargin < 1
help readegilocs;
return;
end;
% importing channel locations
% ---------------------------
found = 1;
if nargin < 2
switch EEG.nbchan
case { 32 33 }, fileloc = 'GSN-HydroCel-32.sfp';
case { 64 65 }, fileloc = 'GSN65v2_0.sfp';
case { 128 129 }, fileloc = 'GSN129.sfp';
case { 256 257 }, fileloc = 'GSN-HydroCel-257.sfp';
otherwise, found = 0;
end;
end;
if found
fprintf('EGI channel location automatically detected %s ********* WARNING please check that this the proper file\n', fileloc);
if EEG.nbchan == 64 || EEG.nbchan == 65 || EEG.nbchan == 256 || EEG.nbchan == 257
fprintf( [ 'Warning: this function assumes you have a 64-channel system Version 2\n' ...
' if this is not the case, update the channel location with the proper file' ]);
end;
% remove the last channel for 33 channels
peeglab = fileparts(which('eeglab.m'));
fileloc = fullfile(peeglab, 'sample_locs', fileloc);
locs = readlocs(fileloc);
locs(1).type = 'FID';
locs(2).type = 'FID';
locs(3).type = 'FID';
locs(end).type = 'REF';
if EEG.nbchan == 256 || EEG.nbchan == 257
if EEG.nbchan == 256
chaninfo.nodatchans = locs([end]);
locs([end]) = [];
end;
elseif mod(EEG.nbchan,2) == 0,
chaninfo.nodatchans = locs([1 2 3 end]);
locs([1 2 3 end]) = [];
else
chaninfo.nodatchans = locs([1 2 3]);
locs([1 2 3]) = [];
end; % remove reference
chaninfo.filename = fileloc;
EEG.chanlocs = locs;
EEG.urchanlocs = locs;
EEG.chaninfo = chaninfo;
end;
|
github
|
lcnhappe/happe-master
|
eyelike.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/eyelike.m
| 748 |
utf_8
|
83fb00bb12b75f143a88314e92ebe31f
|
% eyelike() - calculate a permutation matrix P and a scaling (diagonal) maxtrix S
% such that S*P*E is eyelike (so permutation acts on the rows of E).
% E must be a square matrix.
% Usage:
% >> [eyelike, S, P] = eyelike(E);
%
% Author: Benjamin Blankertz ([email protected]) 3/2/00
function [eyelikeres, S, P]= eyelike(E)
[N, M]= size(E);
if N ~= M
fprintf('eyeLike(): input matrix must be square.\n');
return
end
R= E./repmat(sum(abs(E),2),1,N);
Rabs= abs(R);
P= zeros(N);
for n=1:N
[so, si]= sort(-Rabs(:));
[chosenV, chosenH]= ind2sub([N N], si(1));
P(chosenH,chosenV)= 1;
Rabs(chosenV,:)= repmat(-inf, 1, N);
Rabs(:,chosenH)= repmat(-inf, N, 1);
end
S= diag(1./diag(P*E));
eyelikeres= S*P*E;
|
github
|
lcnhappe/happe-master
|
trial2eegplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/trial2eegplot.m
| 1,822 |
utf_8
|
5c1c543407f5710d59e780a95904b9d5
|
% trial2eegplot() - convert eeglab format to eeplot format of rejection window
%
% Usage:
% >> eegplotarray = trial2eegplot(rej, rejE, points, color);
%
% Inputs:
% rej - rejection vector (0 and 1) with one value per trial
% rejE - electrode rejection array (size nb_elec x trials) also
% made of 0 and 1.
% points - number of points per trials
% color - color of the windows for eegplot()
%
% Outputs:
% eegplotarray - array defining windows which is compatible with
% the function eegplot()
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eegtresh(), eeglab(), eegplot(), 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
% ----------------------------------------------------------
function rejeegplot = trial2eegplot( rej, rejE, pnts, color)
rej = find(rej>0);
rejE = rejE(:, rej)';
rejeegplot = zeros(length(rej), size(rejE,2)+5);
rejeegplot(:, 6:end) = rejE;
rejeegplot(:, 1) = (rej(:)-1)*pnts;
rejeegplot(:, 2) = rej(:)*pnts-1;
rejeegplot(:, 3:5) = ones(size(rejeegplot,1),1)*color;
return
|
github
|
lcnhappe/happe-master
|
eegplot2event.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/eegplot2event.m
| 2,932 |
utf_8
|
f36ca0fc4d6df10d0b3f83cc6f657f74
|
% eegplot2event() - convert EEGPLOT rejections into events
% compatible with the eeg_eegrej function for rejecting
% continuous portions of datasets.
%
% Usage:
% >> [events] = eegplot2event( eegplotrej, type, colorin, colorout );
%
% Inputs:
% eegplotrej - EEGPLOT output (TMPREJ; see eegplot for more details)
% type - type of the event. Default -1.
% colorin - only extract rejection of specific colors (here a n x 3
% array must be given). Default: extract all rejections.
% colorout - do not extract rejection of specified colors.
%
% Outputs:
% events - array of events compatible with the eeg_eegrej function
% for rejecting continuous portions of datasets.
%
% Example:
% NEWEEG = eeg_eegrej(EEG,eegplot2event(TMPREJ, -1));
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eegplot(), eeg_multieegplot(), eegplot2trial(), 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 events = eegplot2event( TMPREJ, type, color, colorout )
if nargin < 1
help eegplot2event;
return;
end;
if nargin < 2
type = -1;
end;
% only take into account specific colors
% --------------------------------------
if exist('color') == 1
for index = 1:size(color,1)
tmpcol1 = TMPREJ(:,3) + 255*TMPREJ(:,4) + 255*255*TMPREJ(:,5);
tmpcol2 = color(index,1)+255*color(index,2)+255*255*color(index,3);
I = find( tmpcol1 == tmpcol2);
if isempty(I)
fprintf('Warning: color [%d %d %d] not found\n', ...
color(index,1), color(index,2), color(index,3));
end;
TMPREJ = TMPREJ(I,:);
end;
end;
% remove other specific colors
% ----------------------------
if exist('colorout') == 1
for index = 1:size(colorout,1)
tmpcol1 = TMPREJ(:,3) + 255*TMPREJ(:,4) + 255*255*TMPREJ(:,5);
tmpcol2 = colorout(index,1)+255*colorout(index,2)+255*255*colorout(index,3);
I = find( tmpcol1 ~= tmpcol2);
TMPREJ = TMPREJ(I,:);
end;
end;
events = [];
if ~isempty(TMPREJ)
events = TMPREJ(:,1:5);
events = [ type*ones(size(events,1), 1) ones(size(events,1), 1) round(events(:,1:2)) events(:,3:5)];
end;
return;
|
github
|
lcnhappe/happe-master
|
celltomat.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/celltomat.m
| 1,264 |
utf_8
|
2c99b2d1c464697b97f856035aa819f6
|
% celltomat() - convert cell array to matrix
%
% Usage: >> M = celltomat( C );
%
% Author: Arnaud Delorme, CNL / Salk Institute, Jan 25 2002
%
% Note: This function overloads the neuralnet toolbox function CELLTOMAT,
% but does not have all its capacities. Delete this version if you have
% the toolbox.
% Copyright (C) Jan 25 2002 Arnaud Delorme, CNL / Salk Institute
%
% 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 M = celltomat( C, varargin );
if nargin < 1
help celltomat;
return;
end;
M = zeros(size(C));
for i=1:size(C,1)
for j=1:size(C,2)
M(i,j) = C{i,j};
end;
end;
|
github
|
lcnhappe/happe-master
|
matsel.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/matsel.m
| 3,756 |
utf_8
|
3779008d46e2601576fba59179f48a0c
|
% matsel() - select rows, columns, and epochs from given multi-epoch data matrix
%
% Usage:
% >> [dataout] = matsel(data,frames,framelist);
% >> [dataout] = matsel(data,frames,framelist,chanlist);
% >> [dataout] = matsel(data,frames,framelist,chanlist,epochlist);
%
% Inputs:
% data - input data matrix (chans,frames*epochs)
% frames - frames (data columns) per epoch (0 -> frames*epochs)
% framelist - list of frames per epoch to select (0 -> 1:frames)
% chanlist - list of chans to select (0 -> 1:chans)
% epochlist - list of epochs to select (0 -> 1:epochs)
%
% Note: The size of dataout is (length(chanlist), length(framelist)*length(epochlist))
%
% Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 5-21-96
% Copyright (C) 5-21-96 Scott Makeig, SCCN/INC/UCSD, [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
% 5-25-96 added chanlist, epochlist -sm
% 10-05-97 added out of bounds tests for chanlist and framelist -sm
% 02-04-00 truncate to epochs*frames if necessary -sm
% 01-25-02 reformated help & license -ad
function [dataout] = matsel(data,frames,framelist,chanlist,epochlist)
if nargin<1
help matsel
return
end
[chans framestot] = size(data);
if isempty(data)
fprintf('matsel(): empty data matrix!?\n')
help matsel
return
end
if nargin < 5,
epochlist = 0;
end
if nargin < 4,
chanlist = 0;
end
if nargin < 3,
fprintf('matsel(): needs at least 3 arguments.\n\n');
return
end
if frames == 0,
frames = framestot;
end
if framelist == 0,
framelist = [1:frames];
end
framesout = length(framelist);
if isempty(chanlist) | chanlist == 0,
chanlist = [1:chans];
end
chansout = length(chanlist);
epochs = floor(framestot/frames);
if epochs*frames ~= framestot
fprintf('matsel(): data length %d was not a multiple of %d frames.\n',...
framestot,frames);
data = data(:,1:epochs*frames);
end
if isempty(epochlist) | epochlist == 0,
epochlist = [1:epochs];
end
epochsout = length(epochlist);
if max(epochlist)>epochs
fprintf('matsel() error: max index in epochlist (%d) > epochs in data (%d)\n',...
max(epochlist),epochs);
return
end
if max(framelist)>frames
fprintf('matsel() error: max index in framelist (%d) > frames per epoch (%d)\n',...
max(framelist),frames);
return
end
if min(framelist)<1
fprintf('matsel() error: framelist min (%d) < 1\n', min(framelist));
return
end
if min(epochlist)<1
fprintf('matsel() error: epochlist min (%d) < 1\n', min(epochlist));
return
end
if max(chanlist)>chans
fprintf('matsel() error: chanlist max (%d) > chans (%d)\n',...
max(chanlist),chans);
return
end
if min(chanlist)<1
fprintf('matsel() error: chanlist min (%d) <1\n',...
min(chanlist));
return
end
dataout = zeros(chansout,framesout*epochsout);
for e=1:epochsout
dataout(:,framesout*(e-1)+1:framesout*e) = ...
data(chanlist,framelist+(epochlist(e)-1)*frames);
end
|
github
|
lcnhappe/happe-master
|
axcopy.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/axcopy.m
| 3,330 |
utf_8
|
1c1014b531a21afc497c89e4ffe2ef09
|
% axcopy() - Copy a Matlab figure axis and its graphic objects to a new pop-up window
% using the left mouse button.
%
% Usage: >> axcopy
% >> axcopy(fig)
% >> axcopy('noticks')
% >> axcopy(fig, command)
%
% Notes:
% 1) Clicking the left mouse button on a Matlab figure axis copies the graphic objects
% in the axis to a new (pop-up) figure window.
% 2) Option 'noticks' does not make x and y tickloabelmodes 'auto' in the pop-up.
% 2) The command option is an optional string that is evaluated in the new window
% when it pops up. This allows the user to customize the pop-up display.
% 3) Deleting the pop-up window containing the copied axis leaves the selected axis
% as the current graphic axis (gca).
% Authors: Tzyy-Ping Jung & Scott Makeig, SCCN/INC/UCSD, La Jolla, 2000
% Copyright (C) 2000 Tzyy-Ping Jung & Scott Makeig, SCCN/INC/UCSD, 3-16-00
%
% 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
% requires copyaxes.m
% 4-2-00 added 'noticks' -sm
% 01-25-02 reformated help & license -ad
% 02-16-02 debuged exist('fig') -> exist('fig') == 1 -ad
% 02-16-02 added the ignore parent size option -ad
% 03-11-02 remove size option and added command option -ad
function axcopy(fig, command)
if (exist('fig') == 1) & strcmp(fig,'noticks')
noticks = 1;
if nargin> 1
shift
else
fig = [];
end
end
if ~(exist('fig') ==1) | isempty(fig) | fig == 0
fig = gcf;
end
if ~strcmpi(get(fig, 'type'), 'axes')
%hndl= findobj('parent',fig,'type','axes');
%--
childs = get(fig,'Children');
hndl = childs(find(strcmpi(get(childs,'Type'),'axes')));
else
hndl=fig;
end;
offidx=[];
if exist('command') ~= 1
comstr = 'copyaxis';
else
command_dbl = double(command);
comstr = double(['copyaxis(''' char(command_dbl) ''')']);
end;
for a=1:length(hndl) % make all axes visible
%allobjs = findobj('parent',hndl(a));
%--
allobjs = get(hndl(a),'Children');
for index = 1:length(allobjs)
if isempty(get(allobjs(index), 'ButtonDownFcn'))
set(allobjs(index), 'ButtonDownFcn', char(comstr));
end;
end;
end
if ~strcmpi(get(fig, 'type'), 'axes')
figure(fig);
else
figure(get(fig, 'parent'));
end;
if exist('command') ~= 1
set(hndl(a),'ButtonDownFcn','copyaxis');
else
% set(hndl,'ButtonDownFcn',['copyaxis(''' command ''')']);
comstr = double(['copyaxis(''' char(command_dbl) ''')']);
set(hndl,'ButtonDownFcn',char(comstr));
end;
%set(hndl,'ButtonDownFcn','copyaxis');
%if ~exist('noticks')
%axis on
%set(gca,'xticklabelmode','auto')
%set(gca,'yticklabelmode','auto')
%end
|
github
|
lcnhappe/happe-master
|
eegthresh.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/eegthresh.m
| 4,825 |
utf_8
|
fd6a3945cb7a5cd79d0869f38eaa59ca
|
% eegthresh() - reject trials with out-of-bounds channel values within a
% specified epoch time range.
%
% Usage:
% >> [Iin, Iout, newsignal, elec] = eegthresh( signal, frames, ...
% elecs, negthresh, posthresh, timerange, starttime,endtime);
%
% Required inputs:
% signal - 2-D data matrix [channels, frames*sweeps],
% or 3-D data matrix [channels, frames, sweeps]
% frames - number of points per epoch
% elecs - [int vector] electrode indices to reject on
% negthresh - minimum rejection threshold(s) in uV. This can be an array
% of values for individual electrodes. If fewer values than
% electrodes, the last value is used for the remaining
% electrodes.
% posthresh - maximum rejection threshold(s) in uV (same syntax as for
% negthresh)
% timerange - [mintime maxtime] time range limits of the signal
% starttime - Starting limit (in seconds or Hz) of range to perform
% rejection (same syntax as negthresh)
% endtime - Ending limit (in seconds or Hz) of range to perform
% rejection (same syntax as negthresh)
%
% Outputs:
% Iin - Indexes of epochs accepted
% Iout - Indexes of epochs rejected
% newsignal - input data after epoch rejection
% elec - electrode that triggered the rejections (array of 0s
% and 1s with the same number of columns as Iout
% and number of rows = number of electrodes).
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: pop_eegthresh(), 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 [Iin, Iout, newsignal, elec] = eegthresh( signal, pnts, electrodes, negthresh, posthresh, timerange, starttime, endtime);
if nargin < 7
help eegthresh;
return;
end;
if starttime < timerange(1)
disp('eegthresh: starting point out of range, adjusted');
starttime = timerange(1);
end;
if endtime > timerange(2)
disp('eegthresh: ending point out of range, adjusted');
endtime = timerange(2);
end;
% complete thresholds values if necessary
%----------------------------------------
if size(posthresh,2) < size(electrodes,2)
posthresh = [ posthresh posthresh(end)*ones(1,size(electrodes,2)-size(posthresh,2))];
end;
if size(negthresh,2) < size(electrodes,2)
negthresh = [ negthresh negthresh(end)*ones(1,size(electrodes,2)-size(negthresh,2))];
end;
% complete timeselect values if necessary
%----------------------------------------
if size(starttime,2) < size(electrodes,2)
starttime = [ starttime starttime(end)*ones(1,size(electrodes,2)-size(starttime,2))];
end;
if size(endtime,2) < size(electrodes,2)
endtime = [ endtime endtime(end)*ones(1,size(electrodes,2)-size(endtime,2))];
end;
% find the maximum for each trial
%--------------------------------
sweeps = size(signal(1,:),2)/pnts;
signal = reshape(signal(electrodes,:), size(electrodes(:),1), pnts, sweeps);
% reject the selected trials
%---------------------------
elec = zeros(size(electrodes(:),1), sweeps);
allelec = zeros(1, sweeps);
for indexe = 1:size(electrodes(:),1)
% transform the time range
% ------------------------
framelowlimit = max(1,floor((starttime(indexe)-timerange(1))/(timerange(2)-timerange(1))*(pnts-1))+1);
framehighlimit = floor((endtime(indexe) -timerange(1))/(timerange(2)-timerange(1))*(pnts-1))+1;
% remove outliers
% ---------------
sigtmp = squeeze(signal(indexe,framelowlimit:framehighlimit,:));
if size(signal,3) == 1, sigtmp = sigtmp'; end;
sigmax = max(sigtmp, [], 1);
sigmin = min(sigtmp, [], 1);
elec(indexe,:) = ( sigmin < negthresh(indexe) ) | ( sigmax > posthresh(indexe) );
allelec = allelec | elec(indexe,:);
end;
Iout = find( allelec == 1 );
Iin = find( allelec == 0 );
elec = elec(:,Iout);
% reject the selected trials
%---------------------------
newsignal = reshape(signal, size(signal,1), pnts, sweeps);
if ~isempty(Iin)
newsignal = newsignal(:,:,Iin);
if ndims(signal) == 2
newsignal = newsignal(:,:);
end;
else
newsignal = [];
end;
return;
|
github
|
lcnhappe/happe-master
|
qqdiagram.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/qqdiagram.m
| 4,745 |
utf_8
|
f9f838e5edd084613e8c54cb85cbb56f
|
% qqdiagram() - Empirical quantile-quantile diagram.
%
% Description:
% The quantiles (percentiles) of the input distribution Y are plotted (Y-axis)
% against the corresponding quantiles of the input distribution X.
% If only X is given, the corresponding quantiles are plotted (Y-axis)
% against the quantiles of a Gaussian distribution ('Normal plot').
% Two black dots indicate the lower and upper quartiles.
% If the data in X and Y belong the same distribution the plot will be linear.
% In this case,the red and black reference lines (.-.-.-.-) will overlap.
% This will be true also if the data in X and Y belong to two distributions with
% the same shape, one distribution being rescaled and shifted with respect to the
% other.
% If only X is given, a line is plotted to indicate the mean of X, and a segment
% is plotted to indicate the standard deviation of X. If the data in X are normally
% distributed, the red and black reference lines (.-.-.-.-) will overlap.
%
% Usage:
% >> ah = qqdiagram( x, y, pk );
%
% Inputs:
% x - vector of observations
%
% Optional inputs:
% y - second vector of observation to compare the first to
% pk - the empirical quantiles will be estimated at the values in pk [0..1]
%
% Author: Luca Finelli, CNL / Salk Institute - SCCN, 20 August 2002
%
% Reference: Stahel W., Statistische Datenanalyse, Vieweg, Braunschweig/Wiesbaden, 1995
%
% See also:
% quantile(), signalstat(), eeglab()
% Copyright (C) 2002 Luca Finelli, Salk/SCCN, La Jolla, CA
%
% Reference: Stahel, W. Statistische Datenanalyse, Vieweg, Braunschweig/Wiesbaden 1995
%
% 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 qqdiagram( x , y, pk )
if nargin < 1
help qqdiagram;
return;
end;
if (nargin == 3 & (any(pk > 1) | any(pk < 0)))
error('qqdiagram(): elements in pk must be between 0 and 1');
end
if nargin==1
y=x;
nn=max(1000,10*length(y))+1;
x=randn(1,nn);
end
if nargin < 3
nx=sum(~isnan(x));
ny=sum(~isnan(y));
k=min(nx,ny);
pk=((1:k) - 0.5) ./ k; % values to estimate the empirical quantiles at
else
k=length(pk);
end
if nx==k
xx=sort(x(~isnan(x)));
else
xx=quantile(x(~isnan(x)),pk);
end
if ny==k
yy=sort(y(~isnan(y)));
else
yy=quantile(y(~isnan(y)),pk);
end
% QQ diagram
plot(xx,yy,'+')
hold on
% x-axis range
maxx=max(xx);
minx=min(xx);
rangex=maxx-minx;
xmin=minx-rangex/50;
xmax=maxx+rangex/50;
% Quartiles
xqrt1=quantile(x,0.25); xqrt3=quantile(x,0.75);
yqrt1=quantile(y,0.25); yqrt3=quantile(y,0.75);
plot([xqrt1 xqrt3],[yqrt1 yqrt3],'k-','LineWidth',2); % IQR range
% Drawing the line
sigma=(yqrt3-yqrt1)/(xqrt3-xqrt1);
cy=(yqrt1 + yqrt3)/2;
if nargin ==1
maxy=max(y);
miny=min(y);
rangey=maxy-miny;
ymin=miny-rangey/50;
ymax=maxy+rangey/50;
plot([(miny-cy)/sigma (maxy-cy)/sigma],[miny maxy],'r-.') % the line
% For normally distributed data, the slope of the plot line
% is equal to the ratio of the standard deviation of the distributions
plot([0 (maxy-mean(y))/std(y)],[mean(y) maxy],'k-.') % the ideal line
xlim=get(gca,'XLim');
plot([1 1],[ymin mean(y)+std(y)],'k--')
plot([1 1],[mean(y) mean(y)+std(y)],'k-','LineWidth',2)
% textx = 1.0;
% texty = mean(y)+3.0*rangey/50.0;
% text(double(textx), double(texty),' St. Dev.','horizontalalignment','center')
set(gca,'xtick',get(gca,'xtick')); % show that vertical line is at 1 sd
plot([0 0],[ymin mean(y)],'k--')
plot(xlim,[mean(y) mean(y)],'k--')
% text(double(xlim(1)), double(mean(y)+rangey/50),'Mean X')
plot([xqrt1 xqrt3],[yqrt1 yqrt3],'k.','MarkerSize',10)
set(gca,'XLim',[xmin xmax],'YLim',[ymin ymax])
xlabel('Standard Normal Quantiles')
ylabel('X Quantiles')
else
cx=(xqrt1 + xqrt3)/2;
maxy=cy+sigma*(max(x)-cx);
miny=cy-sigma*(cx-min(x));
plot([min(x) max(x)],[miny maxy],'r-.'); % the line
xlabel('X Quantiles');
ylabel('Y Quantiles');
end
|
github
|
lcnhappe/happe-master
|
loaddat.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/loaddat.m
| 1,775 |
utf_8
|
7d7aa4df464e400f37de47be51520ea6
|
% loaddat() - loading neuroscan format data file into matlab.
%
% Usage:
% >> [typeeeg, rt, response, n] = loaddat( filename );
%
% Inputs:
% filename - input Neuroscan .dat file
%
% Outputs:
% typeeeg - type of the sweeps
% rt - reaction time of the subject
% response - response of the subject
% n - number of sweeps
%
% See also: loadeeg()
% 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 [tmptypeeeg, tmprt, tmpresponseeeg, n] = loaddat( FILENAME)
if nargin<1
fprintf('Not enought arguments\n');
help loaddat
return;
end;
BOOL='int16';
ULONG='int32';
FLOAT='float32';
fid=fopen(FILENAME,'r','ieee-le');
if fid<0
fprintf(2,['Error LOADEEG: File ' FILENAME ' not found\n']);
return;
end;
% skip the first 20 lines
% -----------------------
for index=1:20 fgetl(fid); end;
% read the matrix
% ---------------
tmpMat = fscanf(fid, '%f', [5, inf]);
tmptypeeeg = tmpMat(3,:);
tmpresponseeeg = tmpMat(4,:);
tmprt = tmpMat(5,:);
n = size( tmpMat, 2);
fclose(fid);
return;
|
github
|
lcnhappe/happe-master
|
cbar.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/cbar.m
| 6,149 |
utf_8
|
d94610ba8d3cbc14b360527461547953
|
% cbar() - Display full or partial color bar
%
% Usage:
% >> cbar % create a vertical cbar on the right side of a figure
% >> cbar(type) % specify direction as 'vert' or 'horiz'
% >> cbar(type,colors) % specify which colormap colors to plot
% else
% >> cbar(axhandle) % specify the axes to draw cbar in
%
% >> h = cbar(type|axhandle,colors, minmax, grad)
%
% Inputs:
% type - ['vert'|'horiz'] direction of the cbar {default: 'vert')
% ELSE axhandle = handle of axes to draw the cbar
% colors - vector of colormap indices to display, or integer to truncate upper
% limit by.
% (int n -> display colors [1:end-n]) {default: 0}
% minmax - [min, max] range of values to label on colorbar
% grad - [integer] number of tick labels. {default: 5}.
%
% Example:
% >> colormap('default') % default colormap is 64-color 'jet'
% >> cbar('vert',33:64); % plot a vertical cbar colored green->red
% % useful for showing >0 (warm) and 0 (green)
% % values only in a green=0 plot
%
% Author: Colin Humphries, Arnaud Delorme, CNL / Salk Institute, Feb. 1998-
%
% See also: colorbar()
% Copyright (C) Colin Humphries, CNL / Salk Institute, Feb. 1998
%
% 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
% 12-13-98 added minmax arg -Scott Makeig
% 01-25-02 reformated help & license, added links -ad
function [handle]=cbar(arg,colors,minmax, grad)
if nargin < 2
colors = 0;
end
posscale = 'off';
if nargin < 1
arg = 'vert';
ax = [];
else
if isempty(arg)
arg = 0;
end
if arg(1) == 0
ax = [];
arg = 'vert';
elseif strcmpi(arg, 'pos')
ax = [];
arg = 'vert';
posscale = 'on';
else
if ischar(arg)
ax = [];
else
ax = arg;
arg = [];
end
end
end
if nargin>2
if size(minmax,1) ~= 1 | size(minmax,2) ~= 2
help cbar
fprintf('cbar() : minmax arg must be [min,max]\n');
return
end
end
if nargin < 4
grad = 5;
end;
%obj = findobj('tag','cbar','parent',gcf);
%if ~isempty(obj) & ~isempty(arg)
% arg = [];
% ax = obj;
%end
try
icadefs;
catch
warning('cbar.m unable to find icadefs.m');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Choose colorbar position
%%%%%%%%%%%%%%%%%%%%%%%%%%%
if (length(colors) == 1) & (colors == 0)
t = caxis;
else
t = [0 1];
end
if ~isempty(arg)
if strcmp(arg,'vert')
cax = gca;
pos = get(cax,'Position');
stripe = 0.04;
edge = 0.01;
space = .02;
% set(cax,'Position',[pos(1) pos(2) pos(3)*(1-stripe-edge-space) pos(4)])
% rect = [pos(1)+(1-stripe-edge)*pos(3) pos(2) stripe*pos(3) pos(4)];
set(cax,'Position',[pos(1) pos(2) pos(3) pos(4)])
rect = [pos(1)+pos(3)+space pos(2) stripe*pos(3) pos(4)];
ax = axes('Position', rect);
elseif strcmp(arg,'horiz')
cax = gca;
pos = get(cax,'Position');
stripe = 0.075;
space = .1;
set(cax,'Position',...
[pos(1) pos(2)+(stripe+space)*pos(4) pos(3) (1-stripe-space)*pos(4)])
rect = [pos(1) pos(2) pos(3) stripe*pos(4)];
ax = axes('Position', rect);
end
else
pos = get(ax,'Position');
if pos(3) > pos(4)
arg = 'horiz';
else
arg = 'vert';
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Draw colorbar using image()
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if exist('DEFAULT_COLORMAP', 'var')
map = colormap(eval( [ DEFAULT_COLORMAP '(' int2str(max(size(colormap,1), max(colors))) ')' ]));
else
map = colormap;
end
n = size(map,1);
if length(colors) == 1
if strcmp(arg,'vert')
if strcmpi(posscale, 'on')
image([0 1],[0 t(2)],[ceil(n/2):n-colors]');
else
image([0 1],t,[1:n-colors]');
end;
set(ax,'xticklabelmode','manual')
set(ax,'xticklabel',[],'YAxisLocation','right')
else
image(t,[0 1],[1:n-colors]);
set(ax,'yticklabelmode','manual')
set(ax,'yticklabel',[],'YAxisLocation','right')
end
set(ax,'Ydir','normal','YAxisLocation','right')
else % length > 1
if max(colors) > n
error('Color vector excedes size of colormap')
end
if strcmp(arg,'vert')
image([0 1],t,[colors]');
set(ax,'xticklabelmode','manual')
set(ax,'xticklabel',[])
else
image([0 1],t,[colors]);
set(ax,'yticklabelmode','manual')
set(ax,'yticklabel',[],'YAxisLocation','right')
end
set(ax,'Ydir','normal','YAxisLocation','right')
end
%%%%%%%%%%%%%%%%%%%%%%%%%
% Adjust cbar ticklabels
%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin > 2
if strcmp(arg,'vert')
Cax = get(ax,'Ylim');
else
Cax = get(ax,'Xlim');
end;
CBTicks = [Cax(1):(Cax(2)-Cax(1))/(grad-1):Cax(2)]; % caxis tick positions
CBLabels = [minmax(1):(minmax(2)-minmax(1))/(grad-1):minmax(2)]; % tick labels
dec = floor(log10(max(abs(minmax)))); % decade of largest abs value
CBLabels = ([minmax]* [ linspace(1,0, grad);linspace(0, 1, grad)]);
%[1.0 .75 .50 .25 0.0; 0.0 .25 .50 .75 1.0]);
if dec<1
CBLabels = round(CBLabels*10^(1-dec))*10^(dec-1);
elseif dec == 1
CBLabels = round(CBLabels*10^(2-dec))*10^(dec-2);
else
CBLabels = round(CBLabels);
end
% minmax
% CBTicks
% CBLabels
if strcmp(arg,'vert')
set(ax,'Ytick',CBTicks);
set(ax,'Yticklabel',CBLabels);
else
set(ax,'Xtick',CBTicks);
set(ax,'Xticklabel',CBLabels);
end
end
handle = ax;
%%%%%%%%%%%%%%%%%%
% Adjust cbar tag
%%%%%%%%%%%%%%%%%%
set(ax,'tag','cbar');
if exist('DEFAULT_COLORMAP', 'var')
colormap(DEFAULT_COLORMAP);
end
|
github
|
lcnhappe/happe-master
|
readlocs.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/readlocs.m
| 33,881 |
utf_8
|
7e1d85669932dffeca11a8fad52e02ca
|
% readlocs() - read electrode location coordinates and other information from a file.
% Several standard file formats are supported. Users may also specify
% a custom column format. Defined format examples are given below
% (see File Formats).
% Usage:
% >> eloc = readlocs( filename );
% >> EEG.chanlocs = readlocs( filename, 'key', 'val', ... );
% >> [eloc, labels, theta, radius, indices] = ...
% readlocs( filename, 'key', 'val', ... );
% Inputs:
% filename - Name of the file containing the electrode locations
% {default: 2-D polar coordinates} (see >> help topoplot )
%
% Optional inputs:
% 'filetype' - ['loc'|'sph'|'sfp'|'xyz'|'asc'|'polhemus'|'besa'|'chanedit'|'custom']
% Type of the file to read. By default the file type is determined
% using the file extension (see below under File Formats),
% 'loc' an EEGLAB 2-D polar coordinates channel locations file
% Coordinates are theta and radius (see definitions below).
% 'sph' Matlab spherical coordinates (Note: spherical
% coordinates used by Matlab functions are different
% from spherical coordinates used by BESA - see below).
% 'sfp' EGI Cartesian coordinates (NOT Matlab Cartesian - see below).
% 'xyz' Matlab/EEGLAB Cartesian coordinates (NOT EGI Cartesian).
% z is toward nose; y is toward left ear; z is toward vertex
% 'asc' Neuroscan polar coordinates.
% 'polhemus' or 'polhemusx' - Polhemus electrode location file recorded
% with 'X' on sensor pointing to subject (see below and readelp()).
% 'polhemusy' - Polhemus electrode location file recorded with
% 'Y' on sensor pointing to subject (see below and readelp()).
% 'besa' BESA-'.elp' spherical coordinates. (Not MATLAB spherical -
% see below).
% 'chanedit' - EEGLAB channel location file created by pop_chanedit().
% 'custom' - Ascii file with columns in user-defined 'format' (see below).
% 'importmode' - ['eeglab'|'native'] for location files containing 3-D cartesian electrode
% coordinates, import either in EEGLAB format (nose pointing toward +X).
% This may not always be possible since EEGLAB might not be able to
% determine the nose direction for scanned electrode files. 'native' import
% original carthesian coordinates (user can then specify the position of
% the nose when calling the topoplot() function; in EEGLAB the position
% of the nose is stored in the EEG.chaninfo structure). {default 'eeglab'}
% 'format' - [cell array] Format of a 'custom' channel location file (see above).
% {default: if no file type is defined. The cell array contains
% labels defining the meaning of each column of the input file.
% 'channum' [positive integer] channel number.
% 'labels' [string] channel name (no spaces).
% 'theta' [real degrees] 2-D angle in polar coordinates.
% positive => rotating from nose (0) toward left ear
% 'radius' [real] radius for 2-D polar coords; 0.5 is the head
% disk radius and limit for topoplot() plotting).
% 'X' [real] Matlab-Cartesian X coordinate (to nose).
% 'Y' [real] Matlab-Cartesian Y coordinate (to left ear).
% 'Z' [real] Matlab-Cartesian Z coordinate (to vertex).
% '-X','-Y','-Z' Matlab-Cartesian coordinates pointing opposite
% to the above.
% 'sph_theta' [real degrees] Matlab spherical horizontal angle.
% positive => rotating from nose (0) toward left ear.
% 'sph_phi' [real degrees] Matlab spherical elevation angle.
% positive => rotating from horizontal (0) upwards.
% 'sph_radius' [real] distance from head center (unused).
% 'sph_phi_besa' [real degrees] BESA phi angle from vertical.
% positive => rotating from vertex (0) towards right ear.
% 'sph_theta_besa' [real degrees] BESA theta horiz/azimuthal angle.
% positive => rotating from right ear (0) toward nose.
% 'ignore' ignore column}.
% The input file may also contain other channel information fields.
% 'type' channel type: 'EEG', 'MEG', 'EMG', 'ECG', others ...
% 'calib' [real near 1.0] channel calibration value.
% 'gain' [real > 1] channel gain.
% 'custom1' custom field #1.
% 'custom2', 'custom3', 'custom4', etc. more custom fields
% 'skiplines' - [integer] Number of header lines to skip (in 'custom' file types only).
% Note: Characters on a line following '%' will be treated as comments.
% 'readchans' - [integer array] indices of electrodes to read. {default: all}
% 'center' - [(1,3) real array or 'auto'] center of xyz coordinates for conversion
% to spherical or polar, Specify the center of the sphere here, or 'auto'.
% This uses the center of the sphere that best fits all the electrode
% locations read. {default: [0 0 0]}
% Outputs:
% eloc - structure containing the channel names and locations (if present).
% It has three fields: 'eloc.labels', 'eloc.theta' and 'eloc.radius'
% identical in meaning to the EEGLAB struct 'EEG.chanlocs'.
% labels - cell array of strings giving the names of the electrodes. NOTE: Unlike the
% three outputs below, includes labels of channels *without* location info.
% theta - vector (in degrees) of polar angles of the electrode locations.
% radius - vector of polar-coordinate radii (arc_lengths) of the electrode locations
% indices - indices, k, of channels with non-empty 'locs(k).theta' coordinate
%
% File formats:
% If 'filetype' is unspecified, the file extension determines its type.
%
% '.loc' or '.locs' or '.eloc':
% polar coordinates. Notes: angles in degrees:
% right ear is 90; left ear -90; head disk radius is 0.5.
% Fields: N angle radius label
% Sample: 1 -18 .511 Fp1
% 2 18 .511 Fp2
% 3 -90 .256 C3
% 4 90 .256 C4
% ...
% Note: In previous releases, channel labels had to contain exactly
% four characters (spaces replaced by '.'). This format still works,
% though dots are no longer required.
% '.sph':
% Matlab spherical coordinates. Notes: theta is the azimuthal/horizontal angle
% in deg.: 0 is toward nose, 90 rotated to left ear. Following this, performs
% the elevation (phi). Angles in degrees.
% Fields: N theta phi label
% Sample: 1 18 -2 Fp1
% 2 -18 -2 Fp2
% 3 90 44 C3
% 4 -90 44 C4
% ...
% '.elc':
% Cartesian 3-D electrode coordinates scanned using the EETrak software.
% See readeetraklocs().
% '.elp':
% Polhemus-.'elp' Cartesian coordinates. By default, an .elp extension is read
% as PolhemusX-elp in which 'X' on the Polhemus sensor is pointed toward the
% subject. Polhemus files are not in columnar format (see readelp()).
% '.elp':
% BESA-'.elp' spherical coordinates: Need to specify 'filetype','besa'.
% The elevation angle (phi) is measured from the vertical axis. Positive
% rotation is toward right ear. Next, perform azimuthal/horizontal rotation
% (theta): 0 is toward right ear; 90 is toward nose, -90 toward occiput.
% Angles are in degrees. If labels are absent or weights are given in
% a last column, readlocs() adjusts for this. Default labels are E1, E2, ...
% Fields: Type label phi theta
% Sample: EEG Fp1 -92 -72
% EEG Fp2 92 72
% EEG C3 -46 0
% EEG C4 46 0
% ...
% '.xyz':
% Matlab/EEGLAB Cartesian coordinates. Here. x is towards the nose,
% y is towards the left ear, and z towards the vertex. Note that the first
% column (x) is -Y in a Matlab 3-D plot, the second column (y) is X in a
% matlab 3-D plot, and the third column (z) is Z.
% Fields: channum x y z label
% Sample: 1 .950 .308 -.035 Fp1
% 2 .950 -.308 -.035 Fp2
% 3 0 .719 .695 C3
% 4 0 -.719 .695 C4
% ...
% '.asc', '.dat':
% Neuroscan-.'asc' or '.dat' Cartesian polar coordinates text file.
% '.sfp':
% BESA/EGI-xyz Cartesian coordinates. Notes: For EGI, x is toward right ear,
% y is toward the nose, z is toward the vertex. EEGLAB converts EGI
% Cartesian coordinates to Matlab/EEGLAB xyz coordinates.
% Fields: label x y z
% Sample: Fp1 -.308 .950 -.035
% Fp2 .308 .950 -.035
% C3 -.719 0 .695
% C4 .719 0 .695
% ...
% '.ced':
% ASCII file saved by pop_chanedit(). Contains multiple MATLAB/EEGLAB formats.
% Cartesian coordinates are as in the 'xyz' format (above).
% Fields: channum label theta radius x y z sph_theta sph_phi ...
% Sample: 1 Fp1 -18 .511 .950 .308 -.035 18 -2 ...
% 2 Fp2 18 .511 .950 -.308 -.035 -18 -2 ...
% 3 C3 -90 .256 0 .719 .695 90 44 ...
% 4 C4 90 .256 0 -.719 .695 -90 44 ...
% ...
% The last columns of the file may contain any other defined fields (gain,
% calib, type, custom).
%
% Fieldtrip structure:
% If a Fieltrip structure is given as input, an EEGLAB
% chanlocs structure is returned
%
% Author: Arnaud Delorme, Salk Institute, 8 Dec 2002
%
% See also: readelp(), writelocs(), topo2sph(), sph2topo(), sph2cart()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 28 Feb 2002
%
% 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 [eloc, labels, theta, radius, indices] = readlocs( filename, varargin );
if nargin < 1
help readlocs;
return;
end;
% NOTE: To add a new channel format:
% ----------------------------------
% 1) Add a new element to the structure 'chanformat' (see 'ADD NEW FORMATS HERE' below):
% 2) Enter a format 'type' for the new file format,
% 3) Enter a (short) 'typestring' description of the format
% 4) Enter a longer format 'description' (possibly multiline, see ex. (1) below)
% 5) Enter format file column labels in the 'importformat' field (see ex. (2) below)
% 6) Enter the number of header lines to skip (if any) in the 'skipline' field
% 7) Document the new channel format in the help message above.
% 8) After testing, please send the new version of readloca.m to us
% at [email protected] with a sample locs file.
% The 'chanformat' structure is also used (automatically) by the writelocs()
% and pop_readlocs() functions. You do not need to edit these functions.
chanformat(1).type = 'polhemus';
chanformat(1).typestring = 'Polhemus native .elp file';
chanformat(1).description = [ 'Polhemus native coordinate file containing scanned electrode positions. ' ...
'User must select the direction ' ...
'for the nose after importing the data file.' ];
chanformat(1).importformat = 'readelp() function';
% ---------------------------------------------------------------------------------------------------
chanformat(2).type = 'besa';
chanformat(2).typestring = 'BESA spherical .elp file';
chanformat(2).description = [ 'BESA spherical coordinate file. Note that BESA spherical coordinates ' ...
'are different from Matlab spherical coordinates' ];
chanformat(2).skipline = 0; % some BESA files do not have headers
chanformat(2).importformat = { 'type' 'labels' 'sph_theta_besa' 'sph_phi_besa' 'sph_radius' };
% ---------------------------------------------------------------------------------------------------
chanformat(3).type = 'xyz';
chanformat(3).typestring = 'Matlab .xyz file';
chanformat(3).description = [ 'Standard 3-D cartesian coordinate files with electrode labels in ' ...
'the first column and X, Y, and Z coordinates in columns 2, 3, and 4' ];
chanformat(3).importformat = { 'channum' '-Y' 'X' 'Z' 'labels'};
% ---------------------------------------------------------------------------------------------------
chanformat(4).type = 'sfp';
chanformat(4).typestring = 'BESA or EGI 3-D cartesian .sfp file';
chanformat(4).description = [ 'Standard BESA 3-D cartesian coordinate files with electrode labels in ' ...
'the first column and X, Y, and Z coordinates in columns 2, 3, and 4.' ...
'Coordinates are re-oriented to fit the EEGLAB standard of having the ' ...
'nose along the +X axis.' ];
chanformat(4).importformat = { 'labels' '-Y' 'X' 'Z' };
chanformat(4).skipline = 0;
% ---------------------------------------------------------------------------------------------------
chanformat(5).type = 'loc';
chanformat(5).typestring = 'EEGLAB polar .loc file';
chanformat(5).description = [ 'EEGLAB polar .loc file' ];
chanformat(5).importformat = { 'channum' 'theta' 'radius' 'labels' };
% ---------------------------------------------------------------------------------------------------
chanformat(6).type = 'sph';
chanformat(6).typestring = 'Matlab .sph spherical file';
chanformat(6).description = [ 'Standard 3-D spherical coordinate files in Matlab format' ];
chanformat(6).importformat = { 'channum' 'sph_theta' 'sph_phi' 'labels' };
% ---------------------------------------------------------------------------------------------------
chanformat(7).type = 'asc';
chanformat(7).typestring = 'Neuroscan polar .asc file';
chanformat(7).description = [ 'Neuroscan polar .asc file, automatically recentered to fit EEGLAB standard' ...
'of having ''Cz'' at (0,0).' ];
chanformat(7).importformat = 'readneurolocs';
% ---------------------------------------------------------------------------------------------------
chanformat(8).type = 'dat';
chanformat(8).typestring = 'Neuroscan 3-D .dat file';
chanformat(8).description = [ 'Neuroscan 3-D cartesian .dat file. Coordinates are re-oriented to fit ' ...
'the EEGLAB standard of having the nose along the +X axis.' ];
chanformat(8).importformat = 'readneurolocs';
% ---------------------------------------------------------------------------------------------------
chanformat(9).type = 'elc';
chanformat(9).typestring = 'ASA .elc 3-D file';
chanformat(9).description = [ 'ASA .elc 3-D coordinate file containing scanned electrode positions. ' ...
'User must select the direction ' ...
'for the nose after importing the data file.' ];
chanformat(9).importformat = 'readeetraklocs';
% ---------------------------------------------------------------------------------------------------
chanformat(10).type = 'chanedit';
chanformat(10).typestring = 'EEGLAB complete 3-D file';
chanformat(10).description = [ 'EEGLAB file containing polar, cartesian 3-D, and spherical 3-D ' ...
'electrode locations.' ];
chanformat(10).importformat = { 'channum' 'labels' 'theta' 'radius' 'X' 'Y' 'Z' 'sph_theta' 'sph_phi' ...
'sph_radius' 'type' };
chanformat(10).skipline = 1;
% ---------------------------------------------------------------------------------------------------
chanformat(11).type = 'custom';
chanformat(11).typestring = 'Custom file format';
chanformat(11).description = 'Custom ASCII file format where user can define content for each file columns.';
chanformat(11).importformat = '';
% ---------------------------------------------------------------------------------------------------
% ----- ADD MORE FORMATS HERE -----------------------------------------------------------------------
% ---------------------------------------------------------------------------------------------------
listcolformat = { 'labels' 'channum' 'theta' 'radius' 'sph_theta' 'sph_phi' ...
'sph_radius' 'sph_theta_besa' 'sph_phi_besa' 'gain' 'calib' 'type' ...
'X' 'Y' 'Z' '-X' '-Y' '-Z' 'custom1' 'custom2' 'custom3' 'custom4' 'ignore' 'not def' };
% ----------------------------------
% special mode for getting the info
% ----------------------------------
if isstr(filename) & strcmp(filename, 'getinfos')
eloc = chanformat;
labels = listcolformat;
return;
end;
g = finputcheck( varargin, ...
{ 'filetype' 'string' {} '';
'importmode' 'string' { 'eeglab','native' } 'eeglab';
'defaultelp' 'string' { 'besa','polhemus' } 'polhemus';
'skiplines' 'integer' [0 Inf] [];
'elecind' 'integer' [1 Inf] [];
'format' 'cell' [] {} }, 'readlocs');
if isstr(g), error(g); end;
if ~isempty(g.format), g.filetype = 'custom'; end;
if isstr(filename)
% format auto detection
% --------------------
if strcmpi(g.filetype, 'autodetect'), g.filetype = ''; end;
g.filetype = strtok(g.filetype);
periods = find(filename == '.');
fileextension = filename(periods(end)+1:end);
g.filetype = lower(g.filetype);
if isempty(g.filetype)
switch lower(fileextension),
case {'loc' 'locs' 'eloc'}, g.filetype = 'loc'; % 5/27/2014 Ramon: 'eloc' option introduced.
case 'xyz', g.filetype = 'xyz';
fprintf( [ 'WARNING: Matlab Cartesian coord. file extension (".xyz") detected.\n' ...
'If importing EGI Cartesian coords, force type "sfp" instead.\n'] );
case 'sph', g.filetype = 'sph';
case 'ced', g.filetype = 'chanedit';
case 'elp', g.filetype = g.defaultelp;
case 'asc', g.filetype = 'asc';
case 'dat', g.filetype = 'dat';
case 'elc', g.filetype = 'elc';
case 'eps', g.filetype = 'besa';
case 'sfp', g.filetype = 'sfp';
otherwise, g.filetype = '';
end;
fprintf('readlocs(): ''%s'' format assumed from file extension\n', g.filetype);
else
if strcmpi(g.filetype, 'locs'), g.filetype = 'loc'; end
if strcmpi(g.filetype, 'eloc'), g.filetype = 'loc'; end
end;
% assign format from filetype
% ---------------------------
if ~isempty(g.filetype) & ~strcmpi(g.filetype, 'custom') ...
& ~strcmpi(g.filetype, 'asc') & ~strcmpi(g.filetype, 'elc') & ~strcmpi(g.filetype, 'dat')
indexformat = strmatch(lower(g.filetype), { chanformat.type }, 'exact');
g.format = chanformat(indexformat).importformat;
if isempty(g.skiplines)
g.skiplines = chanformat(indexformat).skipline;
end;
if isempty(g.filetype)
error( ['readlocs() error: The filetype cannot be detected from the \n' ...
' file extension, and custom format not specified']);
end;
end;
% import file
% -----------
if strcmp(g.filetype, 'asc') | strcmp(g.filetype, 'dat')
eloc = readneurolocs( filename );
eloc = rmfield(eloc, 'sph_theta'); % for the conversion below
eloc = rmfield(eloc, 'sph_theta_besa'); % for the conversion below
if isfield(eloc, 'type')
for index = 1:length(eloc)
type = eloc(index).type;
if type == 69, eloc(index).type = 'EEG';
elseif type == 88, eloc(index).type = 'REF';
elseif type >= 76 & type <= 82, eloc(index).type = 'FID';
else eloc(index).type = num2str(eloc(index).type);
end;
end;
end;
elseif strcmp(g.filetype, 'elc')
eloc = readeetraklocs( filename );
%eloc = read_asa_elc( filename ); % from fieldtrip
%eloc = struct('labels', eloc.label, 'X', mattocell(eloc.pnt(:,1)'), 'Y', ...
% mattocell(eloc.pnt(:,2)'), 'Z', mattocell(eloc.pnt(:,3)'));
eloc = convertlocs(eloc, 'cart2all');
eloc = rmfield(eloc, 'sph_theta'); % for the conversion below
eloc = rmfield(eloc, 'sph_theta_besa'); % for the conversion below
elseif strcmp(lower(g.filetype(1:end-1)), 'polhemus') | ...
strcmp(g.filetype, 'polhemus')
try,
[eloc labels X Y Z]= readelp( filename );
if strcmp(g.filetype, 'polhemusy')
tmp = X; X = Y; Y = tmp;
end;
for index = 1:length( eloc )
eloc(index).X = X(index);
eloc(index).Y = Y(index);
eloc(index).Z = Z(index);
end;
catch,
disp('readlocs(): Could not read Polhemus coords. Trying to read BESA .elp file.');
[eloc, labels, theta, radius, indices] = readlocs( filename, 'defaultelp', 'besa', varargin{:} );
end;
else
% importing file
% --------------
if isempty(g.skiplines), g.skiplines = 0; end;
if strcmpi(g.filetype, 'chanedit')
array = loadtxt( filename, 'delim', 9, 'skipline', g.skiplines, 'blankcell', 'off');
else
array = load_file_or_array( filename, g.skiplines);
end;
if size(array,2) < length(g.format)
fprintf(['readlocs() warning: Fewer columns in the input than expected.\n' ...
' See >> help readlocs\n']);
elseif size(array,2) > length(g.format)
fprintf(['readlocs() warning: More columns in the input than expected.\n' ...
' See >> help readlocs\n']);
end;
% removing lines BESA
% -------------------
if isempty(array{1,2})
disp('BESA header detected, skipping three lines...');
array = load_file_or_array( filename, g.skiplines-1);
if isempty(array{1,2})
array = load_file_or_array( filename, g.skiplines-1);
end;
end;
% xyz format, is the first col absent
% -----------------------------------
if strcmp(g.filetype, 'xyz')
if size(array, 2) == 4
array(:, 2:5) = array(:, 1:4);
end;
end;
% removing comments and empty lines
% ---------------------------------
indexbeg = 1;
while isempty(array{indexbeg,1}) | ...
(isstr(array{indexbeg,1}) & array{indexbeg,1}(1) == '%' )
indexbeg = indexbeg+1;
end;
array = array(indexbeg:end,:);
% converting file
% ---------------
for indexcol = 1:min(size(array,2), length(g.format))
[str mult] = checkformat(g.format{indexcol});
for indexrow = 1:size( array, 1)
if mult ~= 1
eval ( [ 'eloc(indexrow).' str '= -array{indexrow, indexcol};' ]);
else
eval ( [ 'eloc(indexrow).' str '= array{indexrow, indexcol};' ]);
end;
end;
end;
end;
% handling BESA coordinates
% -------------------------
if isfield(eloc, 'sph_theta_besa')
if isfield(eloc, 'type')
if isnumeric(eloc(1).type)
disp('BESA format detected ( Theta | Phi )');
for index = 1:length(eloc)
eloc(index).sph_phi_besa = eloc(index).labels;
eloc(index).sph_theta_besa = eloc(index).type;
eloc(index).labels = '';
eloc(index).type = '';
end;
eloc = rmfield(eloc, 'labels');
end;
end;
if isfield(eloc, 'labels')
if isnumeric(eloc(1).labels)
disp('BESA format detected ( Elec | Theta | Phi )');
for index = 1:length(eloc)
eloc(index).sph_phi_besa = eloc(index).sph_theta_besa;
eloc(index).sph_theta_besa = eloc(index).labels;
eloc(index).labels = eloc(index).type;
eloc(index).type = '';
eloc(index).radius = 1;
end;
end;
end;
try
eloc = convertlocs(eloc, 'sphbesa2all');
eloc = convertlocs(eloc, 'topo2all'); % problem with some EGI files (not BESA files)
catch, disp('Warning: coordinate conversion failed'); end;
fprintf('Readlocs: BESA spherical coords. converted, now deleting BESA fields\n');
fprintf(' to avoid confusion (these fields can be exported, though)\n');
eloc = rmfield(eloc, 'sph_phi_besa');
eloc = rmfield(eloc, 'sph_theta_besa');
% converting XYZ coordinates to polar
% -----------------------------------
elseif isfield(eloc, 'sph_theta')
try
eloc = convertlocs(eloc, 'sph2all');
catch, disp('Warning: coordinate conversion failed'); end;
elseif isfield(eloc, 'X')
try
eloc = convertlocs(eloc, 'cart2all');
catch, disp('Warning: coordinate conversion failed'); end;
else
try
eloc = convertlocs(eloc, 'topo2all');
catch, disp('Warning: coordinate conversion failed'); end;
end;
% inserting labels if no labels
% -----------------------------
if ~isfield(eloc, 'labels')
fprintf('readlocs(): Inserting electrode labels automatically.\n');
for index = 1:length(eloc)
eloc(index).labels = [ 'E' int2str(index) ];
end;
else
% remove trailing '.'
for index = 1:length(eloc)
if isstr(eloc(index).labels)
tmpdots = find( eloc(index).labels == '.' );
eloc(index).labels(tmpdots) = [];
end;
end;
end;
% resorting electrodes if number not-sorted
% -----------------------------------------
if isfield(eloc, 'channum')
if ~isnumeric(eloc(1).channum)
error('Channel numbers must be numeric');
end;
allchannum = [ eloc.channum ];
if any( sort(allchannum) ~= allchannum )
fprintf('readlocs(): Re-sorting channel numbers based on ''channum'' column indices\n');
[tmp newindices] = sort(allchannum);
eloc = eloc(newindices);
end;
eloc = rmfield(eloc, 'channum');
end;
else
if isstruct(filename)
% detect Fieldtrip structure and convert it
% -----------------------------------------
if isfield(filename, 'pnt')
neweloc = [];
for index = 1:length(filename.label)
neweloc(index).labels = filename.label{index};
neweloc(index).X = filename.pnt(index,1);
neweloc(index).Y = filename.pnt(index,2);
neweloc(index).Z = filename.pnt(index,3);
end;
eloc = neweloc;
eloc = convertlocs(eloc, 'cart2all');
else
eloc = filename;
end;
else
disp('readlocs(): input variable must be a string or a structure');
end;
end;
if ~isempty(g.elecind)
eloc = eloc(g.elecind);
end;
if nargout > 2
if isfield(eloc, 'theta')
tmptheta = { eloc.theta }; % check which channels have (polar) coordinates set
else tmptheta = cell(1,length(eloc));
end;
if isfield(eloc, 'theta')
tmpx = { eloc.X }; % check which channels have (polar) coordinates set
else tmpx = cell(1,length(eloc));
end;
indices = find(~cellfun('isempty', tmptheta));
indices = intersect_bc(find(~cellfun('isempty', tmpx)), indices);
indices = sort(indices);
indbad = setdiff_bc(1:length(eloc), indices);
tmptheta(indbad) = { NaN };
theta = [ tmptheta{:} ];
end;
if nargout > 3
if isfield(eloc, 'theta')
tmprad = { eloc.radius }; % check which channels have (polar) coordinates set
else tmprad = cell(1,length(eloc));
end;
tmprad(indbad) = { NaN };
radius = [ tmprad{:} ];
end;
%tmpnum = find(~cellfun('isclass', { eloc.labels }, 'char'));
%disp('Converting channel labels to string');
for index = 1:length(eloc)
if ~isstr(eloc(index).labels)
eloc(index).labels = int2str(eloc(index).labels);
end;
end;
labels = { eloc.labels };
if isfield(eloc, 'ignore')
eloc = rmfield(eloc, 'ignore');
end;
% process fiducials if any
% ------------------------
fidnames = { 'nz' 'lpa' 'rpa' 'nasion' 'left' 'right' 'nazion' 'fidnz' 'fidt9' 'fidt10' 'cms' 'drl' };
for index = 1:length(fidnames)
ind = strmatch(fidnames{index}, lower(labels), 'exact');
if ~isempty(ind), eloc(ind).type = 'FID'; end;
end;
return;
% interpret the variable name
% ---------------------------
function array = load_file_or_array( varname, skiplines );
if isempty(skiplines),
skiplines = 0;
end;
if exist( varname ) == 2
array = loadtxt(varname,'verbose','off','skipline',skiplines,'blankcell','off');
else % variable in the global workspace
% --------------------------
try, array = evalin('base', varname);
catch, error('readlocs(): cannot find the named file or variable, check syntax');
end;
end;
return;
% check field format
% ------------------
function [str, mult] = checkformat(str)
mult = 1;
if strcmpi(str, 'labels'), str = lower(str); return; end;
if strcmpi(str, 'channum'), str = lower(str); return; end;
if strcmpi(str, 'theta'), str = lower(str); return; end;
if strcmpi(str, 'radius'), str = lower(str); return; end;
if strcmpi(str, 'ignore'), str = lower(str); return; end;
if strcmpi(str, 'sph_theta'), str = lower(str); return; end;
if strcmpi(str, 'sph_phi'), str = lower(str); return; end;
if strcmpi(str, 'sph_radius'), str = lower(str); return; end;
if strcmpi(str, 'sph_theta_besa'), str = lower(str); return; end;
if strcmpi(str, 'sph_phi_besa'), str = lower(str); return; end;
if strcmpi(str, 'gain'), str = lower(str); return; end;
if strcmpi(str, 'calib'), str = lower(str); return; end;
if strcmpi(str, 'type') , str = lower(str); return; end;
if strcmpi(str, 'X'), str = upper(str); return; end;
if strcmpi(str, 'Y'), str = upper(str); return; end;
if strcmpi(str, 'Z'), str = upper(str); return; end;
if strcmpi(str, '-X'), str = upper(str(2:end)); mult = -1; return; end;
if strcmpi(str, '-Y'), str = upper(str(2:end)); mult = -1; return; end;
if strcmpi(str, '-Z'), str = upper(str(2:end)); mult = -1; return; end;
if strcmpi(str, 'custom1'), return; end;
if strcmpi(str, 'custom2'), return; end;
if strcmpi(str, 'custom3'), return; end;
if strcmpi(str, 'custom4'), return; end;
error(['readlocs(): undefined field ''' str '''']);
|
github
|
lcnhappe/happe-master
|
erpimage.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/erpimage.m
| 157,376 |
utf_8
|
deef1ab9cf000fdabbc8e026c72c4366
|
% erpimage() - Plot a colored image of a collection of single-trial data epochs, optionally
% sorted on and/or aligned to an input sorting variable and smoothed across
% trials with a Gaussian weighted moving-average. (To return event-aligned data
% without plotting, use eegalign()). Optionally sort trials on value, amplitude
% or phase within a specified latency window. Optionally plot the ERP mean
% and std. dev.and moving-window spectral amplitude and inter-trial coherence
% at aselected or peak frequency. Optionally 'time warp' the single trial
% time-domain (potential) or power data to align the plotted data to a series
% of events with varying latencies that occur in each trial. Click on
% individual figures parts to examine them separately and zoom (using axcopy()).
% Usage:
% >> figure; erpimage(data,[],times); % image trials as colored lines in input order
%
% >> figure; [outdata,outvar,outtrials,limits,axhndls, ...
% erp,amps,cohers,cohsig,ampsig,outamps,...
% phsangls,phsamp,sortidx,erpsig] ...
% = erpimage(data,sortvar,times,'title',avewidth,decimate,...
% 'key', 'val', ...); % use options
% Required input:
% data = [vector or matrix] Single-channel input data to image.
% Formats (1,frames*trials) or (frames,trials)
%
% Optional ordered inputs {with defaults}:
%
% sortvar = [vector | []] Variable to sort epochs on (length(sortvar) = nepochs)
% Example: sortvar may by subject response time in each epoch (in ms)
% {default|[]: plot in input order}
% times = [vector | []] vector of latencies (in ms) for each epoch time point.
% Else [startms ntimes srate] = [start latency (ms), time points
% (=frames) per epoch, sampling rate (Hz)]. Else [] -> 0:nframes-1
% {default: []}
% 'title' = ['string'] Plot title {default: none}
% avewidth = [positive scalar (may be non-integer)]. If avg_type is set to 'boxcar'
% (the default), this is the number of trials used to smooth
% (vertically) with a moving-average. If avg_type is set to
% 'Gaussian,' this is the standard deviation (in units of
% trials) of the Gaussian window used to smooth (vertically)
% with a moving-average. Gaussian window extends three
% standard deviations below and three standard deviations above window
% center (trials beyond window are not incorporated into average). {default: no
% smoothing}
% decimate = Factor to decimate|interpolate ntrials by (may be non-integer)
% Else, if this is large (> sqrt(ntrials)), output this many epochs.
% {default|0->1}
%
% Optional unordered 'keyword',argument pairs:
%
% Re-align data epochs:
% 'align' = [latency] Time-lock data to sortvar. Plot sortvar at given latency
% (in ms). Else Inf -> plot sortvar at median sortvar latency
% {default: do not align}
% 'timewarp' = {[events], [warpms], {colors}} Time warp ERP, amplitude and phase
% time-courses before smoothing. 'events' is a matrix whose columns
% specify the latencies (in ms) at which a series of successive events occur
% in each trial. 'warpms' is an optional vector of latencies (in ms) to which
% the series of events should be time locked. (Note: Epoch start and end
% should not be declared as events or warpms}. If 'warpms' is absent or [],
% the median of each 'events' column will be used. {colors} contains a
% list of Matlab linestyles to use for vertical lines marking the occurrence
% of the time warped events. If '', no line will be drawn for this event
% column. If fewer colors than event columns, cycles through the given color
% labels. Note: Not compatible with 'vert' (below).
% 'renorm' = ['yes'|'no'| formula] Normalize sorting variable to epoch
% latency range and plot. 'yes'= autoscale. formula must be a linear
% transformation in the format 'a*x+b'
% Example of formula: '3*x+2'. {default: 'no'}
% If sorting by string values like event type, suggested formulas for:
% letter string: '1000*x', number string: '30000*x-1500'
% 'noplot' = ['on'|'off'] Do not plot sortvar {default: Plot sortvar if in times range}
% 'NoShow' = ['on'|'off'] Do not plot erpimage, simply return outputs {default: 'off'}
%
% Sort data epochs:
% 'nosort' = ['on'|'off'] Do not sort data epochs. {default: Sort data epochs by
% sortvar (see sortvar input above)}
% 'replace_ties' = ['yes'|'no'] Replace trials with the same value of
% sortvar with the mean of those trials. Only works if sorting trials
% by sortvar. {default: 'no'}
% 'valsort' = [startms endms direction] Sort data on (mean) value
% between startms and (optional) endms. Direction is 1 or -1.
% If -1, plot max-value epoch at bottom {default: sort on sortvar}
% 'phasesort' = [ms_center prct freq maxfreq topphase] Sort epochs by phase in
% a 3-cycle window centered at latency ms_center (ms).
% Percentile (prct) in range [0,100] gives percent of trials
% to reject for (too) low amplitude. Else, if in range [-100,0],
% percent of trials to reject for (too) high amplitude;
% freq (Hz) is the phase-sorting frequency. With optional
% maxfreq, sort by phase at freq of max power in the data in
% the range [freq,maxfreq] (Note: 'phasesort' arg freq overrides
% the frequency specified in 'coher'). With optional topphase,
% sort by phase, putting topphase (degrees, in range [-180,180])
% at the top of the image. Note: 'phasesort' now uses circular
% smoothing. Use 'cycles' (below) for wavelet length.
% {default: [0 25 8 13 180]}
% 'ampsort' = [center_ms prcnt freq maxfreq] Sort epochs by amplitude.
% (See 'phasesort' above). If ms_center is 'Inf', then sorting
% is by mean power across the time window specified by 'sortwin'
% below. If third arg, freq, is < 0, sort by mean power in the range
% [ abs(freq) maxfreq ].
% 'sortwin' = [start_ms end_ms] If center_ms == Inf in 'ampsort' arg (above), sorts
% by mean amplitude across window centers shifted from start_ms
% to end_ms by 10 ms.
% 'showwin' = ['on'|'off'] Show sorting window behind ERP trace. {default: 'off'}
%
% Plot time-varying spectral amplitude instead of potential:
% 'plotamps' = ['on'|'off'] Image amplitudes at each trial and latency instead of
% potential values. Note: Currently requires 'coher' (below) with alpha signif.
% Use 'cycles' (see below) > (its default) 3 for better frequency specificity,
% {default: plot potential, not amplitudes, with no minimum}. The average power
% (in log space) before time 0 is automatically removed. Note that the
% 'baseline' parameter has no effect on 'plotamps'. Instead use
% change "baselinedb" or "basedB" in the 'limits' parameter. By default
% the baseline is removed before time 0.
%
% Specify plot parameters:
% 'limits' = [lotime hitime minerp maxerp lodB hidB locoher hicoher basedB]
% Plot axes limits. Can use NaN (or nan, but not Nan) for missing items
% and omit late items. Use last input, basedB, to set the
% baseline dB amplitude in 'plotamps' plots {default: from data}
% 'sortvar_limits' = [min max] minimum and maximum sorting variable
% values to image. This only affects visualization of
% ERPimage and ERPs (not smoothing). Cannot be used
% if sorting by any factor besides sortvar (e.g.,
% phase).
% 'signif' = [lo_dB, hi_dB, coher_signif_level] Use precomputed significance
% thresholds (as from outputs ampsig, cohsig) to save time. {default: none}
% 'caxis' = [lo hi] Set color axis limits. Else [fraction] Set caxis limits at
% (+/-)fraction*max(abs(data)) {default: symmetrical in dB, based on data limits}
%
% Add epoch-mean ERP to plot:
% 'erp' = ['on'|'off'|1|2|3|4] Plot ERP time average of the trials below the
% image. If 'on' or 1, a single ERP (the mean of all trials) is shown. If 2,
% two ERPs (super and sub median trials) are shown. If 3, the trials are split into
% tertiles and their three ERPs are shown. If 4, the trials are split into quartiles
% and four ERPs are shown. Note, if you want negative voltage plotted up, change YDIR
% to -1 in icadefs.m. If 'erpalpha' option is used, any values of 'erp' greater than
% 1 will be reset to 1. {default no ERP plotted}
% 'erpalpha' = [alpha] Visualizes two-sided significance threshold (i.e., a two-tailed test) for the
% null hypothesis of a zero mean, symmetric distribution (range: [.001 0.1]). Thresholds
% are determined via a permutation test. Requires 'erp' to be a value other than 'off'.
% If 'erp' is set to a value greater than 1, it is reset to 1 to increase plot readability.
% {default: no alpha significance thresholds plotted}
% 'erpstd' = ['on'|'off'] Plot ERP +/- stdev. Requires 'erp' {default: no std. dev. plotted}
% 'erp_grid' = If 'erp_grid' is added as an option voltage axis dashed grid lines will be
% added to the ERP plot to facilitate judging ERP amplitude
% 'rmerp' = ['on'|'off'] Subtract the average ERP from each trial before processing {default: no}
%
% Add time/frequency information:
% 'coher' = [freq] Plot ERP average plus mean amplitude & coherence at freq (Hz)
% Else [minfrq maxfrq] = same, but select frequency with max power in
% given range. (Note: the 'phasesort' freq (above) overwrites these
% parameters). Else [minfrq maxfrq alpha] = plot coher. signif. level line
% at probability alpha (range: [0,0.1]) {default: no coher, no alpha level}
% 'srate' = [freq] Specify the data sampling rate in Hz for amp/coher (if not
% implicit in third arg, times) {default: as defined in icadefs.m}
% 'cycles' = [float] Number of cycles in the wavelet time/frequency decomposition {default: 3}
%
% Add plot features:
% 'cbar' = ['on'|'off'] Plot color bar to right of ERP-image {default no}
% 'cbar_title' = [string] The title for the color bar (e.g., '\muV' for
% microvolts).
% 'topo' = {map,chan_locs,eloc_info} Plot a 2-D scalp map at upper left of image.
% map may be a single integer, representing the plotted data channel,
% or a vector of scalp map channel values. chan_locs may be a channel locations
% file or a chanlocs structure (EEG.chanlocs). See '>> topoplot example'
% eloc_info (EEG.chaninfo), if empty ([]) or absent, implies the 'X' direction
% points towards the nose and all channels are plotted {default: no scalp map}
% 'spec' = [loHz,hiHz] Plot the mean data spectrum at upper right of image.
% 'specaxis' = ['log'|'lin] Use 'lin' for linear spectrum frequency scaling,
% else 'log' for log scaling {default: 'log'}
% 'horz' = [epochs_vector] Plot horizontal lines at specified epoch numbers.
% 'vert' = [times_vector] Plot vertical dashed lines at specified latencies
% 'auxvar' = [size(nvars,ntrials) matrix] Plot auxiliary variable(s) for each trial
% as separate traces. Else, 'auxvar',{[matrix],{colorstrings}}
% to specify N trace colors. Ex: colorstrings = {'r','bo-','','k:'}
% (see also: 'vert' and 'timewarp' above). {default: none}
% 'sortvarpercent' = [float vector] Plot percentiles for the sorting variable
% for instance, [0.1 0.5 0.9] plots the 10th percentile, the median
% and the 90th percentile.
% Plot options:
% 'noxlabel' = ['on'|'off'] Do not plot "Time (ms)" on the bottom x-axis
% 'yerplabel' = ['string'] ERP ordinate axis label (default is ERP). Print uV with '\muV'
% 'avg_type' = ['boxcar'|'Gaussian'] The type of moving average used to smooth
% the data. 'Boxcar' smoothes the data by simply taking the mean of
% a certain number of trials above and below each trial.
% 'Gaussian' does the same but first weights the trials
% according to a Gaussian distribution (e.g., nearby trials
% receive greater weight). The Gaussian is better than the
% boxcar in that it rather evenly filters out high frequency
% vertical components in the ERPimage. See 'avewidth' argument
% description for more information. {default: boxcar}
% 'img_trialax_label' = ['string'] The label of the axis corresponding to trials in the ERPimage
% (e.g., 'Reaction Time'). Note, if img_trialax_label is set to something
% besides 'Trials' or [], the tick marks on this axis will be set in units
% of the sorting variable. This is a useful alternative to plotting the
% sorting variable when the sorting variable is not in milliseconds. This
% option is not effective if sorting by amplitude, phase, or EEG value. {default: 'Trials'}
% 'img_trialax_ticks' = Vector of sorting variable values at which tick marks (e.g., [300 350 400 450]
% for reaction time in msec) will appear on the trial axis of the erpimage. Tick mark
% values should be given in units img_trialax_label (e.g., 'Trials' or msec).
% This option is not effective if sorting by amplitude, phase, or EEG value.
% {default: automatic}
% 'baseline' = [low_boundary high_boundary] a time window (in msec) whose mean amplitude in
% each trial will be removed from each trial (e.g., [-100 0]) after filtering.
% Useful in conjunction with 'filt' option to re-basline trials after they have been
% filtered. Not necessary if data have already been baselined and erpimage
% processing does not affect baseline amplitude {default: no further baselining
% of data}.
% 'baselinedb' = [low_boundary high_boundary] a time window (in msec) whose mean amplitude in
% each trial will be removed from each trial (e.g., [-100 0]). Use basedB in limits
% to remove a fixed value. Default is time before 0. If you do not want to use a
% baseline for amplitude plotting, enter a NaN value.
% 'filt' = [low_boundary high_boundary] a two element vector indicating the frequency
% cut-offs for a 3rd order Butterworth filter that will be applied to each
% trial of data. If low_boundary=0, the filter is a low pass filter. If
% high_boundary=srate/2, then the filter is a high pass filter. If both
% boundaries are between 0 and srate/2, then the filter is a bandpass filter.
% If both boundaries are between 0 and -srate/2, then the filter is a bandstop
% filter (with boundaries equal to the absolute values of low_boundary and
% high_boundary). Note, using this option requires the 'srate' option to be
% specified and the signal processing toolbox function butter.m. You should
% probably use the 'baseline' option as well since the mean prestimulus baseline
% may no longer be 0 after the filter is applied {default: no filtering}
%
% Optional outputs:
% outdata = (times,epochsout) data matrix (after smoothing)
% outvar = (1,epochsout) actual values trials are sorted on (after smoothing).
% if 'sortvarpercent' is used, this variable contains a cell array with
% { sorted_values { sorted_percent1 ... sorted_percentN } }
% outtrials = (1,epochsout) smoothed trial numbers
% limits = (1,10) array, 1-9 as in 'limits' above, then analysis frequency (Hz)
% axhndls = vector of 1-7 plot axes handles (img,cbar,erp,amp,coh,topo,spec)
% erp = plotted ERP average
% amps = mean amplitude time course
% coher = mean inter-trial phase coherence time course
% cohsig = coherence significance level
% ampsig = amplitude significance levels [lo high]
% outamps = matrix of imaged amplitudes (from option 'plotamps')
% phsangls = vector of sorted trial phases at the phase-sorting frequency
% phsamp = vector of sorted trial amplitudes at the phase-sorting frequency
% sortidx = indices of input data epochs in the sorting order
% erpsig = trial average significance levels [2,frames]
%
% Example: >> figure;
% erpimage(data,RTs,[-400 256 256],'Test',1,1,...
% 'erp','cbar','vert',-350);
% Plots an ERP-image of 1-s data epochs sampled at 256 Hz, sorted by RTs, with
% title ('Test'), and sorted epochs not smoothed or decimated (1,1). Overplots
% the (unsmoothed) RT latencies on the colored ERP-image. Also plots the
% epoch-mean (ERP), a color bar, and a dashed vertical line at -350 ms.
%
% Authors: Scott Makeig, Tzyy-Ping Jung & Arnaud Delorme,
% CNL/Salk Institute, La Jolla, 3-2-1998 -
%
% See also: phasecoher, rmbase, cbar, movav
% Copyright (C) Scott Makeig & Tzyy-Ping Jung, CNL / Salk Institute, La Jolla 3-2-98
%
% 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
% Uses external toolbox functions: phasecoher(), rmbase(), cbar(), movav()
% Uses included functions: plot1trace(), phasedet()
% UNIMPLEMENTED - 'allcohers',[data2] -> image the coherences at each latency & epoch.
% Requires arg 'coher' with alpha significance.
% Shows projection on grand mean coherence vector at each latency
% and trial. {default: no}
%% LOG COMMENTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data,outsort,outtrials,limits,axhndls,erp,amps,cohers,cohsig,ampsig,allamps,phaseangles,phsamp,sortidx,erpsig] = erpimage(data,sortvar,times,titl,avewidth,decfactor,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11,arg12,arg13,arg14,arg15,arg16,arg17,arg18,arg19,arg20,arg21,arg22,arg23,arg24,arg25,arg26,arg27,arg28,arg29,arg30,arg31,arg32,arg33,arg34,arg35,arg36,arg37,arg38,arg39,arg40,arg41,arg42,arg43,arg44,arg45,arg46,arg47,arg48,arg49,arg50,arg51,arg52,arg53,arg54,arg55,arg56,arg57,arg58,arg59,arg60,arg61,arg62,arg63,arg64,arg65,arg66)
%
%% %%%%%%%%%%%%%%%%% Define defaults %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Initialize optional output variables:
warning off;
erp = []; amps = []; cohers = []; cohsig = []; ampsig = [];
allamps = []; phaseangles = []; phsamp = []; sortidx = [];
auxvar = []; erpsig = []; winloc = [];winlocs = [];
timeStretchColors = {};
YES = 1; % logical variables
NO = 0;
DEFAULT_BASELINE_END = 0; % ms
TIMEX = 1; % 1 -> plot time on x-axis;
% 0 -> plot trials on x-axis
BACKCOLOR = [0.8 0.8 0.8]; % grey background
try, icadefs; catch, end;
% read BACKCOLOR for plot from defs file (edit this)
% read DEFAULT_SRATE for coher,phase,allamps, etc.
% read YDIR for plotting ERP
% Fix plotting text and line style parameters
SORTWIDTH = 2.5; % Linewidth of plotted sortvar
ZEROWIDTH = 3.0; % Linewidth of vertical 0 line
VERTWIDTH = 2.5; % Linewidth of optional vertical lines
HORZWIDTH = 2.1; % Linewidth of optional vertical lines
SIGNIFWIDTH = 1.9; % Linewidth of red significance lines for amp, coher
DOTSTYLE = 'k--'; % line style to use for vetical dotted/dashed lines
LINESTYLE = '-'; % solid line
LABELFONT = 10; % font sizes for axis labels, tick labels
TICKFONT = 10;
PLOT_HEIGHT = 0.2; % fraction of y dim taken up by each time series axes
YGAP = 0.03; % fraction gap between time axes
YEXPAND = 1.3; % expansion factor for y-axis about erp, amp data limits
DEFAULT_SDEV = 1/7; % smooth trials with this window size by default if Gaussian window
DEFAULT_AVEWIDTH = 1; % smooth trials with this window size by default
DEFAULT_DECFACTOR = 1; % decimate by this factor by default
DEFAULT_CYCLES = 3; % use this many cycles in amp,coher computation window
cycles = DEFAULT_CYCLES;
DEFAULT_CBAR = NO;% do not plot color bar by default
DEFAULT_PHARGS = [0 25 8 13]; % Default arguments for phase sorting
DEFAULT_ALPHA = 0.01;
alpha = 0; % default alpha level for coherence significance
MIN_ERPALPHA = 0.001; % significance bounds for ERP
MAX_ERPALPHA = 0.1;
NoShowVar = NO; % show sortvar by default
Nosort = NO; % sort on sortvar by default
Caxflag = NO; % use default caxis by default
timestretchflag = NO; % Added -JH
mvavg_type='boxcar'; % use the original rectangular moving average -DG
erp_grid = NO; % add y-tick grids to ERP plot -DG
cbar_title = []; % title to add above ERPimage color bar (e.g., '\muV') -DG
img_ylab = 'Trials'; % make the ERPimage y-axis in units of the sorting variable -DG
img_ytick_lab = []; % the values at which tick marks will appear on the trial axis of the ERPimage (the y-axis by default).
%Note, this is in units of the sorting variable if img_ylab~='Trials', otherwise it is in units of trials -DG
baseline = []; %time window of each trial whose mean amp will be used to baseline the trial -DG
baselinedb = []; %time window of each trial whose mean power will be used to baseline the trial
flt=[]; %frequency domain filter parameters -DG
sortvar_limits=[]; %plotting limits for sorting variable/trials; limits only affect visualization, not smoothing -DG
replace_ties = NO; %if YES, trials with the exact same value of a sorting variable will be replaced by their average -DG
erp_vltg_ticks=[]; %if non-empty, these are the voltage axis ticks for the ERP plot
Caxis = [];
caxfraction = [];
Coherflag = NO; % don't compute or show amp,coher by default
Cohsigflag= NO; % default: do not compute coherence significance
Allampsflag=NO; % don't image the amplitudes by default
Allcohersflag=NO; % don't image the coherence amplitudes by default
Topoflag = NO; % don't plot a topoplot in upper left
Specflag = NO; % don't plot a spectrum in upper right
SpecAxisflag = NO; % don't change the default spectrum axis type from default
SpecAxis = 'log'; % default log frequency spectrum axis (if Specflag)
Erpflag = NO; % don't show erp average by default
Erpstdflag= NO;
Erpalphaflag= NO;
Alignflag = NO; % don't align data to sortvar by default
Colorbar = NO; % if YES, plot a colorbar to right of erp image
Limitflag = NO; % plot whole times range by default
Phaseflag = NO; % don't sort by phase
Ampflag = NO; % don't sort by amplitude
Sortwinflag = NO; % sort by amplitude over a window
Valflag = NO; % don't sort by value
Srateflag = NO; % srate not given
Vertflag = NO;
Horzflag = NO;
titleflag = NO;
NoShowflag = NO;
Renormflag = NO;
Showwin = NO;
yerplabel = 'ERP';
yerplabelflag = NO;
verttimes = [];
horzepochs = [];
NoTimeflag= NO; % by default DO print "Time (ms)" below bottom axis
Signifflag= NO; % compute significance instead of receiving it
Auxvarflag= NO;
plotmodeflag= NO;
plotmode = 'normal';
Cycleflag = NO;
signifs = NaN;
coherfreq = nan; % amp/coher-calculating frequency
freq = 0; % phase-sorting frequency
srate = DEFAULT_SRATE; % from icadefs.m
aligntime = nan;
timelimits= nan;
topomap = []; % topo map vector
lospecHz = []; % spec lo frequency
topphase = 180; % default top phase for 'phase' option
renorm = 'no';
NoShow = 'no';
Rmerp = 'no';
percentiles = [];
percentileflag = NO;
erp_ptiles = 1;
minerp = NaN; % default limits
maxerp = NaN;
minamp = NaN;
maxamp = NaN;
mincoh = NaN;
maxcoh = NaN;
baseamp =NaN;
allamps = []; % default return
ax1 = NaN; % default axes handles
axcb = NaN;
ax2 = NaN;
ax3 = NaN;
ax4 = NaN;
timeStretchRef = [];
timeStretchMarks = [];
tsurdata = []; % time-stretched data before smoothing (for timestretched-erp computation)
% If time-stretching is off, this variable remains empty
%
%% %%%%%%%%%%%%%%%%% Test, fill in commandline args %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if nargin < 1
help erpimage
return
end
data = squeeze(data);
if nargin < 3 | isempty(times)
if size(data,1)==1 || size(data,2)==1
fprintf('\nerpimage(): either input a times vector or make data size = (frames,trials).\n')
return
end
times = 1:size(data,1);
NoTimesPassed= 1;
end
if nargin < 2 | isempty(sortvar)
sortvar = 1:size(data,2);
NoShowVar = 1; % don't plot the dummy sortvar
end
framestot = size(data,1)*size(data,2);
ntrials = length(sortvar);
if ntrials < 2
help erpimage
fprintf('\nerpimage(): too few trials.\n');
return
end
frames = floor(framestot/ntrials);
if frames*ntrials ~= framestot
help erpimage
fprintf(...
'\nerpimage(); length of sortvar doesn''t divide number of data elements??\n')
return
end
if nargin < 6
decfactor = 0;
end
if nargin < 5
avewidth = DEFAULT_AVEWIDTH;
end
if nargin<4
titl = ''; % default no title
end
if nargin<3
times = NO;
end
if (length(times) == 1) | (times == NO), % make default times
times = 0:frames-1;
srate = 1000*(length(times)-1)/(times(length(times))-times(1));
fprintf('Using sampling rate %g Hz.\n',srate);
elseif length(times) == 3
mintime = times(1);
frames = times(2);
srate = times(3);
times = mintime:1000/srate:mintime+(frames-1)*1000/srate;
fprintf('Using sampling rate %g Hz.\n',srate);
else
% Note: might use default srate read from icadefs here...
srate = 1000*(length(times)-1)/(times(end)-times(1));
end
if length(times) ~= frames
fprintf(...
'\nerpimage(): length(data)(%d) ~= length(sortvar)(%d) * length(times)(%d).\n\n',...
framestot, length(sortvar), length(times));
return
end
if decfactor == 0,
decfactor = DEFAULT_DECFACTOR;
elseif decfactor > ntrials
fprintf('Setting variable decfactor to max %d.\n',ntrials)
decfactor = ntrials;
end
%
%% %%%%%%%%%%%%%%% Collect optional args %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if nargin > 6
flagargs = [];
a = 6;
while a < nargin % for each remaining Arg
a = a + 1;
Arg = eval(['arg' int2str(a-6)]);
if Caxflag == YES
if size(Arg,1) ~= 1 || size(Arg,2) > 2
help erpimage
fprintf('\nerpimage(): caxis arg must be a scalar or (1,2) vector.\n');
return
end
if size(Arg,2) == 2
Caxis = Arg;
else
caxfraction = Arg;
end
Caxflag = NO;
elseif timestretchflag == YES % Added -JH
timeStretchMarks = Arg{1};
timeStretchMarks = round(1+(timeStretchMarks-times(1))*srate/1000); % convert from ms to frames -sm
[smc smr] = find(diff(timeStretchMarks') < 0);
if ~isempty(smr)
fprintf('\nerpimage(): Timewarp event latencies not in ascending order in trial %d.\n',smr)
return
end
timeStretchMarks = [ ...
repmat(1, [size(timeStretchMarks,1), 1]), ...% Epoch begins
timeStretchMarks, ...
repmat(length(times), [size(timeStretchMarks,1), 1])]; % Epoch ends
if length(Arg) < 2 || isempty(Arg{2})
timeStretchRef = median(timeStretchMarks);
else
timeStretchRef = Arg{2};
timeStretchRef = round(1+(timeStretchRef-times(1))*srate/1000); % convert from ms to frames -sm
timeStretchRef = [1 timeStretchRef length(times)]; % add epoch beginning, end
end
if length(Arg) < 3 || isempty(Arg{3})
timeStretchColors = {};
else
timeStretchColors = Arg{3};
end
fprintf('The %d events specified in each trial will be time warped to latencies:',length(timeStretchRef)-2);
fprintf(' %.0f', times(1)+1000*(timeStretchRef(2:end-1)-1)/srate); % converted from frames to ms -sm
fprintf(' ms\n');
timestretchflag = NO;
elseif Coherflag == YES
if length(Arg) > 3 || length(Arg) < 1
help erpimage
fprintf('\nerpimage(): coher arg must be size <= 3.\n');
return
end
coherfreq = Arg(1);
if size(Arg,2) == 1
coherfreq = Arg(1);
else
coherfreq = Arg(1:2);
end;
if size(Arg,2) == 3
Cohsigflag = YES;
alpha = Arg(3);
if alpha < 0 || alpha > 0.1
fprintf('\nerpimage(): alpha value %g out of bounds.\n',alpha);
return
end
end
Coherflag = NO;
Erpflag = YES; % plot amp, coher below erp time series
elseif Topoflag == YES;
if length(Arg) < 2
help erpimage
fprintf('\nerpimage(): topo arg must be a list of length 2 or 3.\n');
return
end
topomap = Arg{1};
eloc_file = Arg{2};
if length(Arg) > 2, eloc_info = Arg{3};
else eloc_info = [];
end;
Topoflag = NO;
elseif Specflag == YES;
if length(Arg) ~= 2
error('\nerpimage(): ''spec'' flag argument must be a numeric array of length 2.\n');
return
end
lospecHz = Arg(1);
hispecHz = Arg(2);
Specflag = NO;
elseif SpecAxisflag == YES;
SpecAxis = Arg;
if ~strcmpi(SpecAxis,'lin') && ~strcmpi(SpecAxis,'log')
error('\nerpimage(): spectrum axis type must be ''lin'' or ''log''.\n');
return
end
if strcmpi(SpecAxis,'lin')
SpecAxis = 'linear'; % convert to MATLAB Xscale keyword
end
SpecAxisflag = NO;
elseif Renormflag == YES
renorm = Arg;
Renormflag = NO;
elseif NoShowflag == YES
NoShow = Arg;
if strcmpi(NoShow, 'off'), NoShow = 'no'; end;
NoShowflag = NO;
elseif Alignflag == YES
aligntime = Arg;
Alignflag = NO;
elseif percentileflag == YES
percentiles = Arg;
percentileflag = NO;
elseif Limitflag == YES
% [lotime hitime loerp hierp loamp hiamp locoher hicoher]
if size(Arg,1) ~= 1 || size(Arg,2) < 2 || size(Arg,2) > 9
help erpimage
fprintf('\nerpimage(): limits arg must be a vector sized (1,2<->9).\n');
return
end
if ~isnan(Arg(1)) & (Arg(2) <= Arg(1))
help erpimage
fprintf('\nerpimage(): time limits out of order or out of range.\n');
return
end
if Arg(1) < min(times)
Arg(1) = min(times);
fprintf('Adjusting mintime limit to first data value %g\n',min(times));
end
if Arg(2) > max(times)
Arg(2) = max(times);
fprintf('Adjusting maxtime limit to last data value %g\n',max(times));
end
timelimits = Arg(1:2);
if length(Arg)> 2
minerp = Arg(3);
end
if length(Arg)> 3
maxerp = Arg(4);
end
if ~isnan(maxerp) & maxerp <= minerp
help erpimage
fprintf('\nerpimage(): erp limits args out of order.\n');
return
end
if length(Arg)> 4
minamp = Arg(5);
end
if length(Arg)> 5
maxamp = Arg(6);
end
if maxamp <= minamp
help erpimage
fprintf('\nerpimage(): amp limits args out of order.\n');
return
end
if length(Arg)> 6
mincoh = Arg(7);
end
if length(Arg)> 7
maxcoh = Arg(8);
end
if maxcoh <= mincoh
help erpimage
fprintf('\nerpimage(): coh limits args out of order.\n');
return
end
if length(Arg)>8
baseamp = Arg(9); % for 'allamps'
end
Limitflag = NO;
elseif Srateflag == YES
srate = Arg(1);
Srateflag = NO;
elseif Cycleflag == YES
cycles = Arg;
Cycleflag = NO;
elseif Auxvarflag == YES;
if isa(Arg,'cell')==YES && length(Arg)==2
auxvar = Arg{1};
auxcolors = Arg{2};
elseif isa(Arg,'cell')==YES
fprintf('\nerpimage(): auxvars argument must be a matrix or length-2 cell array.\n');
return
else
auxvar = Arg; % no auxcolors specified
end
[xr,xc] = size(auxvar);
lns = length(sortvar);
if xr ~= lns && xc ~= lns
error('\nerpimage(): auxvar columns different from the number of epochs in data');
elseif xr == lns && xc ~= lns
auxvar = auxvar'; % exchange rows/cols
end
Auxvarflag = NO;
elseif Vertflag == YES
verttimes = Arg;
Vertflag = NO;
elseif Horzflag == YES
horzepochs = Arg;
Horzflag = NO;
elseif yerplabelflag == YES
yerplabel = Arg;
yerplabelflag = NO;
elseif Signifflag == YES
signifs = Arg; % [low_amp hi_amp coher]
if length(signifs) ~= 3
fprintf('\nerpimage(): signif arg [%g] must have 3 values\n',Arg);
return
end
Signifflag = NO;
elseif Allcohersflag == YES
data2=Arg;
if size(data2) ~= size(data)
fprintf('\nerpimage(): allcohers data matrix must be the same size as data.\n');
return
end
Allcohersflag = NO;
elseif Phaseflag == YES
n = length(Arg);
if n > 5
error('\nerpimage(): Too many arguments for keyword ''phasesort''');
end
phargs = Arg;
if phargs(3) < 0
error('\nerpimage(): Invalid negative frequency argument for keyword ''phasesort''');
end
if n>=4
if phargs(4) < 0
error('\nerpimage(): Invalid negative argument for keyword ''phasesort''');
end
end
if min(phargs(1)) < times(1) | max(phargs(1)) > times(end)
error('\nerpimage(): time for phase sorting filter out of bound.');
end
if phargs(2) >= 100 | phargs(2) < -100
error('\nerpimage(): %-argument for keyword ''phasesort'' must be (-100;100)');
end
if length(phargs) >= 4 & phargs(3) > phargs(4)
error('\nerpimage(): Phase sorting frequency range must be increasing.');
end
if length(phargs) == 5
topphase = phargs(5);
end
Phaseflag = NO;
elseif Sortwinflag == YES % 'ampsort' mean amplitude over a time window
n = length(Arg);
sortwinarg = Arg;
if n > 2
error('\nerpimage(): Too many arguments for keyword ''sortwin''');
end
if min(sortwinarg(1)) < times(1) | max(sortwinarg(1)) > times(end)
error('\nerpimage(): start time for value sorting out of bounds.');
end
if n > 1
if min(sortwinarg(2)) < times(1) | max(sortwinarg(2)) > times(end)
error('\nerpimage(): end time for value sorting out of bounds.');
end
end
if n > 1 & sortwinarg(1) > sortwinarg(2)
error('\nerpimage(): Value sorting time range must be increasing.');
end
Sortwinflag = NO;
elseif Ampflag == YES % 'ampsort',[center_time,prcnt_reject,minfreq,maxfreq]
n = length(Arg);
if n > 4
error('\nerpimage(): Too many arguments for keyword ''ampsort''');
end
ampargs = Arg;
% if ampargs(3) < 0
% error('\nerpimage(): Invalid negative argument for keyword ''ampsort''');
% end
if n>=4
if ampargs(4) < 0
error('\nerpimage(): Invalid negative argument for keyword ''ampsort''');
end
end
if ~isinf(ampargs(1))
if min(ampargs(1)) < times(1) | max(ampargs(1)) > times(end)
error('\nerpimage(): time for amplitude sorting filter out of bounds.');
end
end
if ampargs(2) >= 100 | ampargs(2) < -100
error('\nerpimage(): percentile argument for keyword ''ampsort'' must be (-100;100)');
end
if length(ampargs) == 4 & abs(ampargs(3)) > abs(ampargs(4))
error('\nerpimage(): Amplitude sorting frequency range must be increasing.');
end
Ampflag = NO;
elseif Valflag == YES % sort by potential value in a given window
% Usage: 'valsort',[mintime,maxtime,direction]
n = length(Arg);
if n > 3
error('\nerpimage(): Too many arguments for keyword ''valsort''');
end
valargs = Arg;
if min(valargs(1)) < times(1) | max(valargs(1)) > times(end)
error('\nerpimage(): start time for value sorting out of bounds.');
end
if n > 1
if min(valargs(2)) < times(1) | max(valargs(2)) > times(end)
error('\nerpimage(): end time for value sorting out of bounds.');
end
end
if n > 1 & valargs(1) > valargs(2)
error('\nerpimage(): Value sorting time range must be increasing.');
end
if n==3 & (~isnumeric(valargs(3)) | valargs(3)==0)
error('\nerpimage(): Value sorting direction must be +1 or -1.');
end
Valflag = NO;
elseif plotmodeflag == YES
plotmode = Arg; plotmodeflag = NO;
elseif titleflag == YES
titl = Arg; titleflag = NO;
elseif Erpalphaflag == YES
erpalpha = Arg(1);
if erpalpha < MIN_ERPALPHA | erpalpha > MAX_ERPALPHA
fprintf('\nerpimage(): erpalpha value is out of bounds [%g, %g]\n',...
MIN_ERPALPHA,MAX_ERPALPHA);
return
end
Erpalphaflag = NO;
% -----------------------------------------------------------------------
% -----------------------------------------------------------------------
% -----------------------------------------------------------------------
elseif strcmpi(Arg,'avg_type')
if a < nargin,
a=a+1;
Arg = eval(['arg' int2str(a-6)]);
if strcmpi(Arg, 'Gaussian'), mvavg_type='gaussian';
elseif strcmpi(Arg, 'Boxcar'), mvavg_type='boxcar';
else error('\nerpimage(): Invalid value for optional argument ''avg_type''.');
end;
else
error('\nerpimage(): Optional argument ''avg_type'' needs to be assigned a value.');
end
elseif strcmp(Arg,'nosort')
Nosort = YES;
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), Nosort = YES; a = a+1;
elseif strcmpi(Arg, 'off') Nosort = NO; a = a+1;
end;
end;
elseif strcmp(Arg,'showwin')
Showwin = YES;
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), Showwin = YES; a = a+1;
elseif strcmpi(Arg, 'off') Showwin = NO; a = a+1;
end;
end;
elseif strcmp(Arg,'noplot') % elseif strcmp(Arg,'NoShow') % by Luca & Ramon
NoShowVar = YES;
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), NoShowVar = YES; a = a+1;
elseif strcmpi(Arg, 'off'), NoShowVar = NO; a = a+1;
end;
end;
elseif strcmpi(Arg,'replace_ties')
if a < nargin,
a = a+1;
temp = eval(['arg' int2str(a-6)]);
if strcmpi(temp,'on'),
replace_ties = YES;
elseif strcmpi(temp,'off') replace_ties = NO;
else
error('\nerpimage(): Argument ''replace_ties'' needs to be followed by the string ''on'' or ''off''.');
end
else
error('\nerpimage(): Argument ''replace_ties'' needs to be followed by the string ''on'' or ''off''.');
end
elseif strcmpi(Arg,'sortvar_limits')
if a < nargin,
a = a+1;
sortvar_limits = eval(['arg' int2str(a-6)]);
if ischar(sortvar_limits) || length(sortvar_limits)~=2
error('\nerpimage(): Argument ''sortvar_limits'' needs to be followed by a two element vector.');
end
else
error('\nerpimage(): Argument ''sortvar_limits'' needs to be followed by a two element vector.');
end
elseif strcmpi(Arg,'erp')
Erpflag = YES;
erp_ptiles=1;
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), Erpflag = YES; erp_ptiles=1; a = a+1;
elseif strcmpi(Arg, 'off') Erpflag = NO; a = a+1;
elseif strcmpi(Arg,'1') | (Arg==1) Erplag = YES; erp_ptiles=1; a=a+1;
elseif strcmpi(Arg,'2') | (Arg==2) Erplag = YES; erp_ptiles=2; a=a+1;
elseif strcmpi(Arg,'3') | (Arg==3) Erplag = YES; erp_ptiles=3; a=a+1;
elseif strcmpi(Arg,'4') | (Arg==4) Erplag = YES; erp_ptiles=4; a=a+1;
end;
end;
elseif strcmpi(Arg,'rmerp')
Rmerp = 'yes';
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), Rmerp = 'yes'; a = a+1;
elseif strcmpi(Arg, 'off') Rmerp = 'no'; a = a+1;
end;
end;
elseif strcmp(Arg,'cbar') | strcmp(Arg,'colorbar')
Colorbar = YES;
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), Colorbar = YES; a = a+1;
elseif strcmpi(Arg, 'off') Colorbar = NO; a = a+1;
end;
end;
elseif (strcmp(Arg,'allamps') | strcmp(Arg,'plotamps'))
Allampsflag = YES;
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), Allampsflag = YES; a = a+1;
elseif strcmpi(Arg, 'off') Allampsflag = NO; a = a+1;
end;
end;
elseif strcmpi(Arg,'erpstd')
Erpstdflag = YES;
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), Erpstdflag = YES; a = a+1;
elseif strcmpi(Arg, 'off') Erpstdflag = NO; a = a+1;
end;
end;
elseif strcmp(Arg,'noxlabel') | strcmp(Arg,'noxlabels') | strcmp(Arg,'nox')
NoTimeflag = YES;
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), NoTimeflag = YES; a = a+1;
elseif strcmpi(Arg, 'off') NoTimeflag = NO; a = a+1;
end;
end;
elseif strcmp(Arg,'plotmode')
plotmodeflag = YES;
elseif strcmp(Arg,'sortvarpercent')
percentileflag = YES;
elseif strcmp(Arg,'renorm')
Renormflag = YES;
elseif strcmp(Arg,'NoShow')
NoShowflag = YES;
elseif strcmp(Arg,'caxis')
Caxflag = YES;
elseif strcmp(Arg,'title')
titleflag = YES;
elseif strcmp(Arg,'coher')
Coherflag = YES;
elseif strcmp(Arg,'timestretch') | strcmp(Arg,'timewarp') % Added -JH
timestretchflag = YES;
elseif strcmp(Arg,'allcohers')
Allcohersflag = YES;
elseif strcmp(Arg,'topo') | strcmp(Arg,'topoplot')
Topoflag = YES;
elseif strcmp(Arg,'spec') | strcmp(Arg,'spectrum')
Specflag = YES;
elseif strcmp(Arg,'Specaxis') || strcmp(Arg,'specaxis') || strcmp(Arg,'SpecAxis')
SpecAxisflag = YES;
elseif strcmpi(Arg,'erpalpha')
Erpalphaflag = YES;
elseif strcmp(Arg,'align')
Alignflag = YES;
elseif strcmp(Arg,'limits')
Limitflag = YES;
elseif (strcmp(Arg,'phase') | strcmp(Arg,'phasesort'))
Phaseflag = YES;
elseif strcmp(Arg,'ampsort')
Ampflag = YES;
elseif strcmp(Arg,'sortwin')
Sortwinflag = YES;
elseif strcmp(Arg,'valsort')
Valflag = YES;
elseif strcmp(Arg,'auxvar')
Auxvarflag = YES;
elseif strcmp(Arg,'cycles')
Cycleflag = YES;
elseif strcmpi(Arg,'yerplabel')
yerplabelflag = YES;
elseif strcmpi(Arg,'srate')
Srateflag = YES;
elseif strcmpi(Arg,'erp_grid')
erp_grid = YES;
elseif strcmpi(Arg,'baseline')
if a < nargin,
a = a+1;
baseline = eval(['arg' int2str(a-6)]);
else
error('\nerpimage(): Argument ''baseline'' needs to be followed by a two element vector.');
end
elseif strcmpi(Arg,'baselinedb')
if a < nargin,
a = a+1;
baselinedb = eval(['arg' int2str(a-6)]);
if length(baselinedb) > 2, error('''baselinedb'' need to be a 2 argument vector'); end;
else
error('\nerpimage(): Argument ''baselinedb'' needs to be followed by a two element vector.');
end
elseif strcmpi(Arg,'filt')
if a < nargin,
a = a+1;
flt = eval(['arg' int2str(a-6)]);
else
error('\nerpimage(): Argument ''filt'' needs to be followed by a two element vector.');
end
elseif strcmpi(Arg,'erp_vltg_ticks')
if a < nargin,
a = a+1;
erp_vltg_ticks=eval(['arg' int2str(a-6)]);
else
error('\nerpimage(): Argument ''erp_vltg_ticks'' needs to be followed by a vector.');
end
elseif strcmpi(Arg,'img_trialax_label')
if a < nargin,
a = a+1;
img_ylab = eval(['arg' int2str(a-6)]);
else
error('\nerpimage(): Argument ''img_trialax_label'' needs to be followed by a string.');
end;
elseif strcmpi(Arg,'img_trialax_ticks')
if a < nargin,
a = a+1;
img_ytick_lab = eval(['arg' int2str(a-6)]);
else
error('\nerpimage(): Argument ''img_trialax_ticks'' needs to be followed by a vector of values at which tick marks will appear.');
end;
elseif strcmpi(Arg,'cbar_title')
if a < nargin,
a = a+1;
cbar_title = eval(['arg' int2str(a-6)]);
else
error('\nerpimage(): Argument ''cbar_title'' needs to be followed by a string.');
end;
elseif strcmp(Arg,'vert') || strcmp(Arg,'verttimes')
Vertflag = YES;
elseif strcmp(Arg,'horz') || strcmp(Arg,'horiz') || strcmp(Arg,'horizontal')
Horzflag = YES;
elseif strcmp(Arg,'signif') || strcmp(Arg,'signifs') || strcmp(Arg,'sig') || strcmp(Arg,'sigs')
Signifflag = YES;
else
help erpimage
if isstr(Arg)
fprintf('\nerpimage(): unknown arg %s\n',Arg);
else
fprintf('\nerpimage(): unknown arg %d, size(%d,%d)\n',a,size(Arg,1),size(Arg,2));
end
return
end
end % Arg
end
if exist('img_ylab','var') || exist('img_ytick_lab','var'),
oops=0;
if exist('phargs','var'),
fprintf('********* Warning *********\n');
fprintf('Options ''img_ylab'' and ''img_ytick_lab'' have no effect when sorting by phase.\n');
oops=0;
elseif exist('valargs','var'),
fprintf('********* Warning *********\n');
fprintf('Options ''img_ylab'' and ''img_ytick_lab'' have no effect when sorting by EEG voltage.\n');
oops=0;
elseif exist('ampargs','var'),
fprintf('********* Warning *********\n');
fprintf('Options ''img_ylab'' and ''img_ytick_lab'' have no effect when sorting by frequency amplitude.\n');
oops=0;
end
if oops
img_ylab=[];
img_ytick_lab=[];
end
end
if Caxflag == YES ...
|Coherflag == YES ...
|Alignflag == YES ...
|Limitflag == YES
help erpimage
fprintf('\nerpimage(): missing option arg.\n')
return
end
if (Allampsflag | exist('data2')) & ( any(isnan(coherfreq)) | ~Cohsigflag )
fprintf('\nerpimage(): allamps and allcohers flags require coher freq, srate, and cohsig.\n');
return
end
if Allampsflag & exist('data2')
fprintf('\nerpimage(): cannot image both allamps and allcohers.\n');
return
end
if ~exist('srate') | srate <= 0
fprintf('\nerpimage(): Data srate must be specified and > 0.\n');
return
end
if ~isempty(auxvar)
% whos auxvar
if size(auxvar,1) ~= ntrials & size(auxvar,2) ~= ntrials
fprintf('\nerpimage(): auxvar size should be (N,ntrials), e.g., (N,%d)\n',...
ntrials);
return
end
if size(auxvar,1) == ntrials & size(auxvar,2) ~= ntrials % make (N,frames)
auxvar = auxvar';
end
if size(auxvar,2) ~= ntrials
fprintf('\nerpimage(): auxvar size should be (N,ntrials), e.g., (N,%d)\n',...
ntrials);
return
end
if exist('auxcolors')==YES % if specified
if isa(auxcolors,'cell')==NO % if auxcolors is not a cell array
fprintf(...
'\nerpimage(): auxcolors argument to auxvar flag must be a cell array.\n');
return
end
end
elseif exist('timeStretchRef') & ~isempty(timeStretchRef)
if ~isnan(aligntime)
fprintf(['\nerpimage(): options "align" and ' ...
'"timewarp" are not compatiable.\n']);
return;
end
if ~isempty(timeStretchColors)
if length(timeStretchColors) < length(timeStretchRef)
nColors = length(timeStretchColors);
for k=nColors+1:length(timeStretchRef)-2
timeStretchColors = { timeStretchColors{:} timeStretchColors{1+rem(k-1,nColors)}};
end
end
timeStretchColors = {'' timeStretchColors{:} ''};
else
timeStretchColors = { 'k--'};
for k=2:length(timeStretchRef)
timeStretchColors = { timeStretchColors{:} 'k--'};
end
end
auxvarInd = 1-strcmp('',timeStretchColors); % indicate which lines to draw
newauxvars = ((timeStretchRef(find(auxvarInd))-1)/srate+times(1)/1000) * 1000; % convert back to ms
fprintf('Overwriting vert with auxvar\n');
verttimes = [newauxvars'];
verttimesColors = {timeStretchColors{find(auxvarInd)}};
newauxvars = repmat(newauxvars, [1 ntrials]);
if isempty(auxvar) % Initialize auxvar & auxcolors
% auxvar = newauxvars;
auxcolors = {timeStretchColors{find(auxvarInd)}};
else % Append auxvar & auxcolors
if ~exist('auxcolors')
% Fill with default color (k-- for now)
auxcolors = {};
for j=1:size(auxvar,1)
auxcolors{end+1} = 'k--';
end
end
for j=find(auxvarInd)
auxcolors{end+1} = timeStretchColors{j};
end
auxvar = [auxvar; newauxvars];
end
end
% No need to turn off ERP anymore; we now time-stretch potentials
% separately (see tsurdata below) so the (warped) ERP is actually meaningful
if exist('phargs')
if phargs(3) > srate/2
fprintf(...
'\nerpimage(): Phase-sorting frequency (%g Hz) must be less than Nyquist rate (%g Hz).',...
phargs(3),srate/2);
end
if frames < cycles*srate/phargs(3)
fprintf('\nerpimage(): phase-sorting freq. (%g) too low: epoch length < %d cycles.\n',...
phargs(3),cycles);
return
end
if length(phargs)==4 & phargs(4) > srate/2
phargs(4) = srate/2;
end
if length(phargs)==5 & (phargs(5)>180 | phargs(5) < -180)
fprintf('\nerpimage(): coher topphase (%g) out of range.\n',topphase);
return
end
end
if exist('ampargs')
if abs(ampargs(3)) > srate/2
fprintf(...
'\nerpimage(): amplitude-sorting frequency (%g Hz) must be less than Nyquist rate (%g Hz).',...
abs(ampargs(3)),srate/2);
end
if frames < cycles*srate/abs(ampargs(3))
fprintf('\nerpimage(): amplitude-sorting freq. (%g) too low: epoch length < %d cycles.\n',...
abs(ampargs(3)),cycles);
return
end
if length(ampargs)==4 & abs(ampargs(4)) > srate/2
ampargs(4) = srate/2;
fprintf('> Reducing max ''ampsort'' frequency to Nyquist rate (%g Hz)\n',srate/2)
end
end
if ~any(isnan(coherfreq))
if coherfreq(1) <= 0 | srate <= 0
fprintf('\nerpimage(): coher frequency (%g) out of range.\n',coherfreq(1));
return
end
if coherfreq(end) > srate/2 | srate <= 0
fprintf('\nerpimage(): coher frequency (%g) out of range.\n',coherfreq(end));
return
end
if frames < cycles*srate/coherfreq(1)
fprintf('\nerpimage(): coher freq. (%g) too low: epoch length < %d cycles.\n',...
coherfreq(1),cycles);
return
end
end
if isnan(timelimits)
timelimits = [min(times) max(times)];
end
if ~isstr(aligntime) & ~isnan(aligntime)
if ~isinf(aligntime) ...
& (aligntime < timelimits(1) | aligntime > timelimits(2))
help erpimage
fprintf('\nerpimage(): requested align time outside of time limits.\n');
return
end
end
%
%% %%%%%%%%%%%%%% Replace nan's with 0s %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
nans = find(isnan(data));
if length(nans)
fprintf('Replaced %d nan in data with 0s.\n');
data(nans) = 0;
end
%
%% %%%%%%%%%%%% Reshape data to (frames,ntrials) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if size(data,2) ~= ntrials
if size(data,1)>1
% fprintf('frames %d, ntrials %d length(data) %d\n',frames,ntrials,length(data));
data=reshape(data,1,frames*ntrials);
end
data=reshape(data,frames,ntrials);
end
fprintf('Plotting input data as %d epochs of %d frames sampled at %3.1f Hz.\n',...
ntrials,frames,srate);
%
%% %%%%%%%%%%%% Reshape data2 to (frames,ntrials) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if exist('data2') == 1
if size(data2,2) ~= ntrials
if size(data2,1)>1
data2=reshape(data2,1,frames*ntrials);
end
data2=reshape(data2,frames,ntrials);
end
end
%
%% %%%%%%%%%%%%% if sortvar=NaN, remove lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -ad
%
if any(isnan(sortvar))
nanlocs = find(isnan(sortvar));
fprintf('Removing %d trials with NaN sortvar values.\n', length(nanlocs));
data(:,nanlocs) = [];
sortvar(nanlocs) = [];
if exist('data2') == 1
data2(:,nanlocs) = [];
end;
if ~isempty(auxvar)
auxvar(:,nanlocs) = [];
end
if ~isempty(verttimes)
if size(verttimes,1) == ntrials
verttimes(nanlocs,:) = [];
end;
end;
ntrials = size(data,2);
if ntrials <= 1, close(gcf); error('\nerpimage(): Too few trials'); end;
end;
%% Create moving average window %%
if strcmpi(mvavg_type,'Gaussian'),
%construct Gaussian window to weight trials
if avewidth == 0,
avewidth = DEFAULT_SDEV;
elseif avewidth < 1,
help erpimage
fprintf('\nerpimage(): Variable avewidth cannot be < 1.\n')
fprintf('\nerpimage(): avewidth needs to be a positive integer.\n')
return
end
wt_wind=exp(-0.5*([-3*avewidth:3*avewidth]/avewidth).^2)';
wt_wind=wt_wind/sum(wt_wind); %normalize to unit sum
avewidth=length(wt_wind);
if avewidth > ntrials
avewidth=floor((ntrials-1)/6);
if avewidth==0,
avewidth=DEFAULT_SDEV; %should be a window with one time point (smallest possible)
end
wt_wind=exp(-0.5*([-3*avewidth:3*avewidth]/avewidth).^2)';
wt_wind=wt_wind/sum(wt_wind);
fprintf('avewidth is too big for this number of trials.\n');
fprintf('Changing avewidth to maximum possible size: %d\n',avewidth);
avewidth=length(wt_wind);
end
else
%construct rectangular "boxcar" window to equally weight trials within
%window
if avewidth == 0,
avewidth = DEFAULT_AVEWIDTH;
elseif avewidth < 1
help erpimage
fprintf('\nerpimage(): Variable avewidth cannot be < 1.\n')
return
elseif avewidth > ntrials
fprintf('Setting variable avewidth to max %d.\n',ntrials)
avewidth = ntrials;
end
wt_wind=ones(1,avewidth)/avewidth;
end
%% Filter data with Butterworth filter (if requested) %%%%%%%%%%%%
%
if ~isempty(flt)
%error check
if length(flt)~=2,
error('\nerpimage(): ''filt'' parameter argument should be a two element vector.');
elseif max(flt)>(srate/2),
error('\nerpimage(): ''filt'' parameters need to be less than or equal to sampling rate/2 (i.e., %f).',srate/2);
elseif (flt(2)==(srate/2)) && (flt(1)==0),
error('\nerpimage(): If second element of ''filt'' parameter is srate/2, then the first element must be greater than 0.');
elseif abs(flt(2))<=abs(flt(1)),
error('\nerpimage(): Second element of ''filt'' parameters must be greater than first in absolute value.');
elseif (flt(1)<0) || (flt(2)<0),
if (flt(1)>=0) || (flt(2)>=0),
error('\nerpimage(): BOTH parameters of ''filt'' need to be greater than or equal to zero OR need to be negative.');
end
if min(flt)<=(-srate/2),
error('\nerpimage(): ''filt'' parameters need to be greater than sampling rate/2 (i.e., -%f) when creating a stop band.',srate/2);
end
end
fprintf('\nFiltering data with 3rd order Butterworth filter: ');
if (flt(1)==0),
%lowpass filter the data
[B A]=butter(3,flt(2)*2/srate,'low');
fprintf('lowpass at %.0f Hz\n',flt(2));
elseif (flt(2)==(srate/2)),
%highpass filter the data
[B A]=butter(3,flt(1)*2/srate,'high');
fprintf('highpass at %.0f Hz\n',flt(1));
elseif (flt(1)<0)
%bandstop filter the data
flt=-flt;
[B A]=butter(3,flt*2/srate,'stop');
fprintf('stopband from %.0f to %.0f Hz\n',flt(1),flt(2));
else
%bandpass filter the data
[B A]=butter(3,flt*2/srate);
fprintf('bandpass from %.0f to %.0f Hz\n',flt(1),flt(2));
end
s=size(data);
for trial=1:s(2),
data(:,trial)=filtfilt(B,A,double(data(:,trial)));
end
if isempty(baseline)
fprintf('Note, you might want to re-baseline the data using the erpimage ''baseline'' option.\n\n');
end
end
%% Mean Baseline Each Trial (if requested) %%
if ~isempty(baseline),
%check argument values for errors
if baseline(2)<baseline(1),
error('\nerpimage(): First element of ''baseline'' argument needs to be less than or equal to second argument.');
elseif baseline(2)<times(1),
error('\nerpimage(): Second element of ''baseline'' argument needs to be greater than or equal to epoch start time %.1f.',times(1));
elseif baseline(1)>times(end),
error('\nerpimage(): First element of ''baseline'' argument needs to be less than or equal to epoch end time %.1f.',times(end));
end
%convert msec into time points
if baseline(1)<times(1),
strt_pt=1;
else
strt_pt=find_crspnd_pt(baseline(1),times,1:length(times));
strt_pt=ceil(strt_pt);
end
if baseline(end)>times(end),
end_pt=length(times);
else
end_pt=find_crspnd_pt(baseline(2),times,1:length(times));
end_pt=floor(end_pt);
end
fprintf('\nRemoving pre-stimulus mean baseline from %.1f to %.1f msec.\n\n',times(strt_pt),times(end_pt));
bsln_mn=mean(data(strt_pt:end_pt,:),1);
data=data-repmat(bsln_mn,length(times),1);
end
%
%% %%%%%%%%%%%%%%%%% Renormalize sortvar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
switch lower(renorm)
case 'yes',
disp('\nerpimage warning: *** sorting variable renormalized ***');
sortvar = (sortvar-min(sortvar)) / (max(sortvar) - min(sortvar)) * ...
0.5 * (max(times) - min(times)) + min(times) + 0.4*(max(times) - min(times));
case 'no',;
otherwise,
if ~isempty(renorm)
locx = findstr('x', lower(renorm));
if length(locx) ~= 1, error('\nerpimage: unrecognized renormalizing formula'); end;
eval( [ 'sortvar =' renorm(1:locx-1) 'sortvar' renorm(locx+1:end) ';'] );
end;
end;
%
%% %%%%%%%%%%%%%%%%% Align data to sortvar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isstr(aligntime) | ~isnan(aligntime)
if ~isstr(aligntime) & isinf(aligntime)
aligntime= median(sortvar);
fprintf('Aligning data to median sortvar.\n');
% Alternative below: trimmed median - ignore top/bottom 5%
% ssv = sort(sortvar); % ssv = 'sorted sortvar'
% aligntime= median(ssv(ceil(ntrials/20)):floor(19*ntrials/20));
end
if ~isstr(aligntime)
fprintf('Realigned sortvar plotted at %g ms.\n',aligntime);
aligndata=zeros(frames,ntrials); % begin with matrix of zeros()
shifts = zeros(1,ntrials);
for t=1:ntrials, %%%%%%%%% foreach trial %%%%%%%%%
shft = round((aligntime-sortvar(t))*srate/1000);
shifts(t) = shft;
if shft>0, % shift right
if frames-shft > 0
aligndata(shft+1:frames,t)=data(1:frames-shft,t);
else
fprintf('No aligned data for epoch %d - shift (%d frames) too large.\n',t,shft);
end
elseif shft < 0 % shift left
if frames+shft > 0
aligndata(1:frames+shft,t)=data(1-shft:frames,t);
else
fprintf('No aligned data for epoch %d - shift (%d frames) too large.\n',t,shft);
end
else % shft == 0
aligndata(:,t) = data(:,t);
end
end % end trial
if ~isempty(auxvar)
auxvar = auxvar+shifts;
end;
fprintf('Shifted epochs by %d to %d frames.\n',min(shifts),max(shifts));
data = aligndata; % now data is aligned to sortvar
else
aligntime = str2num(aligntime);
if isinf(aligntime), aligntime= median(sortvar); end;
end;
end
%
%% %%%%%%%%%%%%%%%%%%%% Remove the ERP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(Rmerp, 'yes')
data = data - repmat(nan_mean(data')', [1 size(data,2)]);
end;
%
%% %%%%%%%%%%%%% Sort the data trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if exist('phargs') == 1 % if phase-sort the data trials
if length(phargs) >= 4 & phargs(3) ~= phargs(4) % find max frequency
% in specified band
if exist('psd') == 2 % requires Signal Processing Toolbox
fprintf('Computing data spectrum using psd().\n');
[pxx,freqs] = psd(data(:),max(1024, pow2(ceil(log2(frames)))),srate,frames,0);
else % EEGLAB native work-around
fprintf('Computing data spectrum using spec().\n');
[pxx,freqs] = spec(data(:),max(1024, pow2(ceil(log2(frames)))),srate,frames,0);
end;
% gf = gcf; % figure;plot(freqs,pxx); %xx=axis; %axis([phargs(3) phargs(4) xx(3) xx(4)]); %figure(gf);
pxx = 10*log10(pxx);
n = find(freqs >= phargs(3) & freqs <= phargs(4));
if ~length(n)
freq = (phargs(3)+phargs(4))/2;
end
[dummy maxx] = max(pxx(n));
freq = freqs(n(maxx));
else
freq = phargs(3); % else use specified frequency
end
fprintf('Sorting trials on phase at %.2g Hz.\n',freq);
[amps, cohers, cohsig, ampsig, allamps, allphs] = ...
phasecoher(data,length(times),srate,freq,cycles,0, ...
[], [], timeStretchRef, timeStretchMarks);
phwin = phargs(1);
[dummy minx] = min(abs(times-phwin)); % closest time to requested
winlen = floor(cycles*srate/freq);
winloc = minx-linspace(floor(winlen/2), floor(-winlen/2), winlen+1);
tmprange = find(winloc>0 & winloc<=frames);
winloc = winloc(tmprange); % sorting window times
winlocs = winloc;
%
%%%%%%%%%%%%%%%%%%%% Compute phsamp and phaseangles %%%%%%%%%%%%%%%%%%%%
%
% $$$ [phaseangles phsamp] = phasedet(data,frames,srate,winloc,freq);
phaseangles = allphs(minx,:);
phsamp = allamps(minx,:);
% $$$ % hist(phaseangles,50);
% $$$ % return
% $$$
% $$$ %
% $$$ % Print facts on commandline %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% $$$ %
% $$$ if length(tmprange) ~= winlen+1
% $$$ filtersize = cycles * length(tmprange) / (winlen+1);
% $$$ timecenter = median(winloc)/srate*1000+times(1); % center of window in ms
% $$$ phaseangles = phaseangles + 2*pi*(timecenter-phargs(1))*freq;
% $$$ fprintf('Sorting data epochs by phase at frequency %2.1f Hz: \n', freq);
% $$$ fprintf(...
% $$$ ' Data time limits reached -> now uses a %1.1f cycles (%1.0f ms) window centered at %1.0f ms\n', ...
% $$$ filtersize, 1000/freq*filtersize, timecenter);
% $$$ fprintf(...
% $$$ ' Filter length is %d; Phase has been linearly interpolated to latency at %1.0f ms.\n', ...
% $$$ length(winloc), phargs(1));
% $$$ else
% $$$ fprintf(...
% $$$ 'Sorting data epochs by phase at %2.1f Hz in a %1.1f-cycle (%1.0f ms) window centered at %1.0f ms.\n',...
% $$$ freq,cycles,1000/freq*cycles,times(minx));
% $$$ fprintf('Phase is computed using a wavelet of %d frames.\n',length(winloc));
% $$$ end;
%
% Reject small (or large) phsamp trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
phargs(2) = phargs(2)/100; % convert rejection rate from % to fraction
amprej = phargs(2);
[tmp ampsortidx] = sort(phsamp); % sort amplitudes
if amprej>=0
ampsortidx = ampsortidx(ceil(amprej*length(ampsortidx))+1:end); % if amprej==0, select all trials
fprintf('Retaining %d epochs (%g percent) with largest power at the analysis frequency,\n',...
length(ampsortidx),100*(1-amprej));
else % amprej < 0
amprej = 1+amprej; % subtract from end
ampsortidx = ampsortidx(1:floor(amprej*length(ampsortidx)));
fprintf('Retaining %d epochs (%g percent) with smallest power at the analysis frequency,\n',...
length(ampsortidx),amprej*100);
end
%
% Remove low|high-amplitude trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
data = data(:,ampsortidx); % amp-sort the data, removing rejected-amp trials
phsamp = phsamp(ampsortidx); % amp-sort the amps
phaseangles = phaseangles(ampsortidx); % amp-sort the phaseangles
sortvar = sortvar(ampsortidx); % amp-sort the trial indices
ntrials = length(ampsortidx); % number of trials retained
if ~isempty(auxvar)
auxvar = auxvar(:,ampsortidx);
end
if ~isempty(timeStretchMarks)
timeStretchMarks = timeStretchMarks(:,ampsortidx);
end
%
% Sort remaining data by phase angle %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
phaseangles = -phaseangles;
topphase = (topphase/360)*2*pi; % convert from degrees to radians
ip = find(phaseangles>topphase);
phaseangles(ip) = phaseangles(ip)-2*pi; % rotate so topphase at top of plot
[phaseangles sortidx] = sort(phaseangles); % sort trials on (rotated) phase
data = data(:,sortidx); % sort data by phase
phsamp = phsamp(sortidx); % sort amps by phase
sortvar = sortvar(sortidx); % sort input sortvar by phase
if ~isempty(auxvar)
auxvar = auxvar(:,sortidx);
end
if ~isempty(timeStretchMarks)
timeStretchMarks = timeStretchMarks(:,sortidx);
end
phaseangles = -phaseangles; % Note: phsangles now descend from pi
% TEST auxvar = 360 + (1000/256)*(256/5)*phaseangles/(2*pi); % plot phase+360 in ms for test
fprintf('Size of data = [%d,%d]\n',size(data,1),size(data,2));
sortidx = ampsortidx(sortidx); % return original trial indices in final sorted order
%
% %%%%%%%%%%%%%%% Sort data by amplitude %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif exist('ampargs') == 1 % if amplitude-sort
if length(ampargs) == 4 % find max frequency in specified band
if exist('psd') == 2
fprintf('Computing data spectrum using psd().\n');
[pxx,freqs] = psd(data(:),max(1024, pow2(ceil(log2(frames)))),srate,frames,0);
else
fprintf('Computing data spectrum using spec().\n');
[pxx,freqs] = spec(data(:),max(1024, pow2(ceil(log2(frames)))),srate,frames,0);
end;
pxx = 10*log10(pxx);
if ampargs(3) == ampargs(4)
[freq n] = min(abs(freqs - ampargs(3)));
else
n = find(freqs >= abs(ampargs(3)) & freqs <= abs(ampargs(4)));
end;
if ~length(n)
freq = mean([abs(ampargs(3)),abs(ampargs(4))]);
end
if ampargs(3)>=0
[dummy maxx] = max(pxx(n));
freq = freqs(n(maxx)); % use the highest-power frequency
else
freq = freqs(n); % use all frequencies in the specified range
end
else
freq = abs(ampargs(3)); % else use specified frequency
end
if length(freq) == 1
fprintf('Sorting data epochs by amplitude at frequency %2.1f Hz \n', freq);
else
fprintf('Sorting data epochs by amplitude at %d frequencies (%2.1f Hz to %.1f Hz) \n',...
length(freq),freq(1),freq(end));
end
SPECWININCR = 10; % make spectral sorting time windows increment by 10 ms
if isinf(ampargs(1))
ampwins = sortwinarg(1):SPECWININCR:sortwinarg(2);
else
ampwins = ampargs(1);
end
if ~isinf(ampargs(1)) % single time given
if length(freq) == 1
fprintf(' in a %1.1f-cycle (%1.0f ms) time window centered at %1.0f ms.\n',...
cycles,1000/freq(1)*cycles,ampargs(1));
else
fprintf(' in %1.1f-cycle (%1.0f-%1.0f ms) time windows centered at %1.0f ms.\n',...
cycles,1000/freq(1)*cycles,1000/freq(end)*cycles,ampargs(1));
end
else % range of times
[dummy sortwin_st ] = min(abs(times-ampwins(1)));
[dummy sortwin_end] = min(abs(times-ampwins(end)));
if length(freq) == 1
fprintf(' in %d %1.1f-cycle (%1.0f ms) time windows centered from %1.0f to %1.0f ms.\n',...
length(ampwins),cycles,1000/freq(1)*cycles,times(sortwin_st),times(sortwin_end));
else
fprintf(' in %d %1.1f-cycle (%1.0f-%1.0f ms) time windows centered from %1.0f to %1.0f ms.\n',...
length(ampwins),cycles,1000/freq(1)*cycles,1000/freq(end)*cycles,times(sortwin_st),times(sortwin_end));
end
end
phsamps = 0; %%%%%%%%%%%%%%%%%%%%%%%%%% sort by (mean) amplitude %%%%%%%%%%%%%%%%%%%%%%%%%%
minxs = [];
for f = 1:length(freq) % use one or range of frequencies
frq = freq(f);
[amps, cohers, cohsig, ampsig, allamps, allphs] = ...
phasecoher(data,length(times),srate,frq,cycles,0, ...
[], [], timeStretchRef, timeStretchMarks);
for ampwin = ampwins
[dummy minx] = min(abs(times-ampwin)); % find nearest time point to requested
minxs = [minxs minx];
winlen = floor(cycles*srate/frq);
% winloc = minx-[winlen:-1:0]; % ending time version
winloc = minx-linspace(floor(winlen/2), floor(-winlen/2), winlen+1);
tmprange = find(winloc>0 & winloc<=frames);
winloc = winloc(tmprange); % sorting window frames
if f==1
winlocs = [winlocs;winloc]; % store tme windows
end
% $$$ [phaseangles phsamp] = phasedet(data,frames,srate,winloc,frq);
% $$$ phsamps = phsamps+phsamps; % accumulate amplitudes across 'sortwin'
phaseangles = allphs(minx,:);
phsamps = phsamps+allamps(minx,:); % accumulate amplitudes across 'sortwin'
end
end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if length(tmprange) ~= winlen+1 % ?????????
filtersize = cycles * length(tmprange) / (winlen+1);
timecenter = median(winloc)/srate*1000+times(1); % center of window in ms
phaseangles = phaseangles + 2*pi*(timecenter-ampargs(1))*freq(end);
fprintf(...
' Data time limits reached -> now uses a %1.1f cycles (%1.0f ms) window centered at %1.0f ms\n', ...
filtersize, 1000/freq(1)*filtersize, timecenter);
fprintf(...
' Wavelet length is %d; Phase has been linearly interpolated to latency et %1.0f ms.\n', ...
length(winloc(1,:)), ampargs(1));
end
if length(freq) == 1
fprintf('Amplitudes are computed using a wavelet of %d frames.\n',length(winloc(1,:)));
end
%
% Reject small (or large) phsamp trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
ampargs(2) = ampargs(2)/100; % convert rejection rate from % to fraction
[tmp n] = sort(phsamps); % sort amplitudes
if ampargs(2)>=0
n = n(ceil(ampargs(2)*length(n))+1:end); % if rej 0, select all trials
fprintf('Retaining %d epochs (%g percent) with largest power at the analysis frequency,\n',...
length(n),100*(1-ampargs(2)));
else % ampargs(2) < 0
ampargs(2) = 1+ampargs(2); % subtract from end
n = n(1:floor(ampargs(2)*length(n)));
fprintf(...
'Retaining %d epochs (%g percent) with smallest power at the analysis frequency,\n',...
length(n),ampargs(2)*100);
end
%
% Remove low|high-amplitude trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
data = data(:,n); % amp-sort the data, removing rejected-amp trials
phsamps = phsamps(n); % amp-sort the amps
phaseangles = phaseangles(n); % amp-sort the phaseangles
sortvar = sortvar(n); % amp-sort the trial indices
ntrials = length(n); % number of trials retained
if ~isempty(auxvar)
auxvar = auxvar(:,n);
end
%
% Sort remaining data by amplitude %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
[phsamps sortidx] = sort(phsamps); % sort trials on amplitude
data = data(:,sortidx); % sort data by amp
phaseangles = phaseangles(sortidx); % sort angles by amp
sortvar = sortvar(sortidx); % sort input sortvar by amp
if ~isempty(auxvar)
auxvar = auxvar(:,sortidx);
end
fprintf('Size of data = [%d,%d]\n',size(data,1),size(data,2));
sortidx = n(sortidx); % return original trial indices in final sorted order
%
%%%%%%%%%%%%%%%%%%%%%% Don't Sort trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif Nosort == YES
fprintf('Not sorting data on input sortvar.\n');
sortidx = 1:ntrials;
%
%%%%%%%%%%%%%%%%%%%%%% Sort trials on (mean) value %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif exist('valargs')
[sttime stframe] = min(abs(times-valargs(1)));
sttime = times(stframe);
if length(valargs)>1
[endtime endframe] = min(abs(times-valargs(2)));
endtime = times(endframe);
else
endframe = stframe;
endtime = times(endframe);
end
if length(valargs)==1 || sttime == endtime
fprintf('Sorting data on value at time %4.0f ms.\n',sttime);
elseif length(valargs)>1
fprintf('Sorting data on mean value between %4.0f and %4.0f ms.\n',...
sttime,endtime);
end
if endframe>stframe
sortval = mean(data(stframe:endframe,:));
else
sortval = data(stframe,:);
end
[sortval,sortidx] = sort(sortval);
if length(valargs)>2
if valargs(3) <0
sortidx = sortidx(end:-1:1); % plot largest values on top
% if direction < 0
end
end
data = data(:,sortidx);
sortvar = sortvar(sortidx); % sort input sortvar by amp
if ~isempty(auxvar)
auxvar = auxvar(:,sortidx);
end
if ~isempty(phaseangles)
phaseangles = phaseangles(sortidx); % sort angles by amp
end
winloc = [stframe,endframe];
winlocs = winloc;
%
%%%%%%%%%%%%%%%%%%%%%% Sort trials on sortvar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
else
fprintf('Sorting data on input sortvar.\n');
[sortvar,sortidx] = sort(sortvar);
data = data(:,sortidx);
if ~isempty(auxvar)
auxvar = auxvar(:,sortidx);
end
uni_svar=unique_bc(sortvar);
n_ties=0;
tie_dist=zeros(1,length(uni_svar));
loop_ct=0;
for tie_loop=uni_svar,
ids=find(sortvar==tie_loop);
n_ids=length(ids);
if n_ids>1,
if replace_ties==YES,
mn=mean(data(:,ids),2);
data(:,ids)=repmat(mn,1,n_ids);
if ~isempty(auxvar)
mn=mean(auxvar(:,ids),2);
auxvar(:,ids) = repmat(mn,1,n_ids);
end
end
n_ties=n_ties+n_ids;
loop_ct=loop_ct+1;
tie_dist(loop_ct)=n_ids;
end
end
fprintf('%.2f%c of the trials (i.e., %d out of %d) have the same sortvar value as at least one other trial.\n', ...
100*n_ties/length(sortvar),37,n_ties,length(sortvar));
fprintf('Distribution of number ties per unique value of sortvar:\n');
if exist('prctile')
try
fprintf('Min: %d, 25th ptile: %d, Median: %d, 75th ptile: %d, Max: %d\n',min(tie_dist),round(prctile(tie_dist,25)), ...
round(median(tie_dist)),round(prctile(tie_dist,75)),max(tie_dist));
catch
end;
end;
if replace_ties==YES,
fprintf('Trials with tied sorting values will be replaced by their mean.\n');
end
fprintf('\n');
end
%if max(sortvar)<0
% fprintf('Changing the sign of sortvar: making it positive.\n');
% sortvar = -sortvar;
%end
%
%% %%%%%%%%%%%%%%%%% Adjust decfactor if phargs or ampargs %%%%%%%%%%%%%%%%%%%%%
%
if decfactor < 0
decfactor = -decfactor;
invdec = 1;
else
invdec = 0;
end;
if decfactor > sqrt(ntrials) % if large, output this many trials
n = 1:ntrials;
if exist('phargs') & length(phargs)>1
if phargs(2)>0
n = n(ceil(phargs(2)*ntrials)+1:end); % trials after rejection
elseif phargs(2)<0
n = n(1:floor(phargs(2)*length(n))); % trials after rejection
end
elseif exist('ampargs') & length(ampargs)>1
if ampargs(2)>0
n = n(ceil(ampargs(2)*ntrials)+1:end); % trials after rejection
elseif ampargs(2)<0
n = n(1:floor(ampargs(2)*length(n))); % trials after rejection
end
end
if invdec
decfactor = (length(n)-avewidth)/decfactor;
else
decfactor = length(n)/decfactor;
end;
end
if ~isreal(decfactor), decfactor = imag(decfactor); end;
%
%% %%%%%%%%%%%%%%%% Smooth data using moving average %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
urdata = data; % save data to compute amp, coher on unsmoothed data
if ~Allampsflag & ~exist('data2') % if imaging potential,
if length(timeStretchRef) > 0 & length(timeStretchMarks) > 0
%
% Perform time-stretching here -JH %%%%%%%%%%%%%%%%
%
for t=1:size(data,2)
M = timewarp(timeStretchMarks(t,:)', timeStretchRef');
data(:,t) = M*data(:,t);
end
end
tsurdata = data;
% Time-stretching ends here %%%%%%%%%%%%%%
if avewidth > 1 || decfactor > 1
if Nosort == YES
fprintf('Smoothing the data using a window width of %g epochs ',avewidth);
else
fprintf('Smoothing the sorted epochs with a %g-epoch moving window.',...
avewidth);
end
fprintf('\n');
fprintf(' and a decimation factor of %g\n',decfactor);
if ~exist('phargs') % if not phase-sorted trials
[data,outtrials] = movav(data,1:ntrials,avewidth,decfactor,[],[],wt_wind);
% Note: movav() here sorts using square window
[outsort,outtrials] = movav(sortvar,1:ntrials,avewidth,decfactor,[],[],wt_wind);
else % if phase-sorted trials, use circular / wrap-around smoothing
backhalf = floor(avewidth/2);
fronthalf = floor((avewidth-1)/2);
if avewidth > 2
[data,outtrials] = movav([data(:,[(end-backhalf+1):end]),...
data,...
data(:,[1:fronthalf])],...
[1:(ntrials+backhalf+fronthalf)],avewidth,decfactor,[],[],wt_wind);
[outsort,outtrials] = movav([sortvar((end-backhalf+1):end),...
sortvar,...
sortvar(1:fronthalf)],...
1:(ntrials+backhalf+fronthalf),avewidth,decfactor,[],[],wt_wind);
% Shift elements of outtrials so the first element is 1
outtrials = outtrials - outtrials(1) + 1;
else % avewidth==2
[data,outtrials] = movav([data(:,end),data],...
[1:(ntrials+1)],avewidth,decfactor,[],[],wt_wind);
% Note: movav() here sorts using square window
[outsort,outtrials] = movav([sortvar(end) sortvar],...
1:(ntrials+1),avewidth,decfactor,[],[],wt_wind);
% Shift elements of outtrials so the first element is 1
outtrials = outtrials - outtrials(1) + 1;
end
end
for index=1:length(percentiles)
outpercent{index} = compute_percentile( sortvar, percentiles(index), outtrials, avewidth);
end;
if ~isempty(auxvar)
if ~exist('phargs') % if not phase-sorted trials
[auxvar,tmp] = movav(auxvar,1:ntrials,avewidth,decfactor,[],[],wt_wind);
else % if phase-sorted trials
if avewidth>2
[auxvar,tmp] = movav([auxvar(:,[(end-backhalf+1):end]),...
auxvar,...
auxvar(:,[1:fronthalf])],...
[1:(ntrials+backhalf+fronthalf)],avewidth,decfactor,[],[],wt_wind);
% Shift elements of tmp so the first element is 1
tmp = tmp - tmp(1) + 1;
else % avewidth==2
[auxvar,tmp] = movav([auxvar(:,end),auxvar],[1:(ntrials+1)],avewidth,decfactor,[],[],wt_wind);
% Shift elements of tmp so the first element is 1
tmp = tmp - tmp(1) + 1;
end
end
end
% if ~isempty(sortvar_limits),
% fprintf('Output data will be %d frames by %d smoothed trials.\n',...
% frames,length(outtrials));
% fprintf('Outtrials: %3.2f to %4.2f\n',min(outtrials),max(outtrials));
% end
else % don't smooth
outtrials = 1:ntrials;
outsort = sortvar;
end
%
%%%%%%%%%%%%%%%%%%%%%%%%% Find color axis limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(Caxis)
mindat = Caxis(1);
maxdat = Caxis(2);
fprintf('Using the specified caxis range of [%g,%g].\n', mindat, maxdat);
else
mindat = min(min(data));
maxdat = max(max(data));
maxdat = max(abs([mindat maxdat])); % make symmetrical about 0
mindat = -maxdat;
if ~isempty(caxfraction)
adjmax = (1-caxfraction)/2*(maxdat-mindat);
mindat = mindat+adjmax;
maxdat = maxdat-adjmax;
fprintf(...
'The caxis range will be %g times the sym. abs. data range -> [%g,%g].\n',...
caxfraction,mindat,maxdat);
else
fprintf(...
'The caxis range will be the sym. abs. data range -> [%g,%g].\n',...
mindat,maxdat);
end
end
end % if ~Allampsflag & ~exist('data2')
%
%% %%%%%%%%%%%%%%%%%%%%%%%% Set time limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isnan(timelimits(1))
timelimits = [min(times) max(times)];
end
fprintf('Data will be plotted between %g and %g ms.\n',timelimits(1),timelimits(2));
%
%% %%%%%%%%%%% Image the aligned/sorted/smoothed data %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
if ~any(isnan(coherfreq)) % if plot three time axes
image_loy = 3*PLOT_HEIGHT;
elseif Erpflag == YES % elseif if plot only one time axes
image_loy = 1*PLOT_HEIGHT;
else % else plot erp-image only
image_loy = 0*PLOT_HEIGHT;
end
gcapos=get(gca,'Position');
delete(gca)
if isempty(topomap)
image_top = 1;
else
image_top = 0.9;
end
ax1=axes('Position',...
[gcapos(1) gcapos(2)+image_loy*gcapos(4) ...
gcapos(3) (image_top-image_loy)*gcapos(4)]);
end;
ind = isnan(data); % find nan's in data
[i j]=find(ind==1);
if ~isempty(i)
data(i,j) = 0; % plot shifted nan data as 0 (=green)
end
%
%% %%%%%%%%%%% Determine coherence freqeuncy %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if length(coherfreq) == 2 & coherfreq(1) ~= coherfreq(2) & freq <= 0
% find max frequency in specified band - should use Matlab pwelch()?
if exist('psd') == 2 % from Signal Processing Toolbox
[pxx,tmpfreq] = psd(urdata(:),max(1024,pow2(ceil(log2(frames)))),srate,frames,0);
else % substitute from EEGLAB
[pxx,tmpfreq] = spec(urdata(:),max(1024,pow2(ceil(log2(frames)))),srate,frames,0);
end;
pxx = 10*log10(pxx);
n = find(tmpfreq >= coherfreq(1) & tmpfreq <= coherfreq(2));
% [tmpfreq(n) pxx(n)]
% coherfreqs = coherfreq; % save for debugging spectrum plotting
if ~length(n)
coherfreq = coherfreq(1);
end
[dummy maxx] = max(pxx(n));
coherfreq = tmpfreq(n(maxx));
else
coherfreq = coherfreq(1);
end
if ~Allampsflag & ~exist('data2') %%%%%%%% Plot ERP image %%%%%%%%%%
%Stretch the data array
% $$$ keyboard;
if strcmpi(NoShow, 'no')
if TIMEX
h_eim=imagesc(times,outtrials,data',[mindat,maxdat]);% plot time on x-axis
set(gca,'Ydir','normal');
axis([timelimits(1) timelimits(2) ...
min(outtrials) max(outtrials)]);
else
h_eim=imagesc(outtrials,times,data,[mindat,maxdat]); % plot trials on x-axis
axis([min(outtrials) max(outtrials)...
timelimits(1) timelimits(2)]);
end
try colormap(DEFAULT_COLORMAP); catch, end;
hold on
drawnow
end;
elseif Allampsflag %%%%%%%%%%%%%%%% Plot allamps instead of data %%%%%%%%%%%%%%
if freq > 0
coherfreq = mean(freq); % use phase-sort frequency
end
if ~isnan(signifs) % plot received significance levels
fprintf(['Computing and plotting received ERSP and ITC signif. ' ...
'levels...\n']);
[amps,cohers,cohsig,ampsig,allamps] = ...
phasecoher(urdata,length(times),srate,coherfreq,cycles,0, ...
[], [], timeStretchRef, timeStretchMarks);
% Note: need to receive cohsig and ampsig to get allamps <---
ampsig = signifs([1 2]); % assume these already in dB
cohsig = signifs(3);
elseif alpha>0 % compute significance levels
fprintf('Computing and plotting %g ERSP and ITC signif. level...\n',alpha);
[amps,cohers,cohsig,ampsig,allamps] = ...
phasecoher(urdata,length(times),srate,coherfreq, ...
cycles, alpha, [], [], ...
timeStretchRef, timeStretchMarks');
% Note: need to receive cohsig and ampsig to get allamps
fprintf('Coherence significance level: %g\n',cohsig);
else % no plotting of significance
[amps,cohers,cohsig,ampsig,allamps] = ...
phasecoher(urdata,length(times),srate,coherfreq, ...
cycles,0,[], [], timeStretchRef, timeStretchMarks);
% Note: need to receive cohsig and ampsig to get allamps
end
% fprintf('#1 Size of allamps = [%d %d]\n',size(allamps,1),size(allamps,2));
base = find(times<=DEFAULT_BASELINE_END);
if length(base)<2
base = 1:floor(length(times)/4); % default first quarter-epoch
end
fprintf('Using %g to %g ms as amplitude baseline.\n',...
times(1),times(base(end)));
% fprintf('#2 Size of allamps = [%d %d]\n',size(allamps,1),size(allamps,2));
% fprintf('Subtracting the mean baseline log amplitude \n');
%fprintf('Subtracting the mean baseline log amplitude %g\n',baseall);
% allamps = allamps./baseall;
% fprintf('#3 Size of allamps = [%d %d]\n',size(allamps,1),size(allamps,2));
if avewidth > 1 || decfactor > 1
if Nosort == YES
fprintf(...
'Smoothing the amplitude epochs using a window width of %g epochs ',...
avewidth);
else % sort trials
fprintf(...
'Smoothing the sorted amplitude epochs with a %g-epoch moving window.',...
avewidth);
end
fprintf('\n');
fprintf(' and a decimation factor of %g\n',decfactor);
%fprintf('4 Size of allamps = [%d %d]\n',size(allamps,1),size(allamps,2));
if exist('phargs') % if phase-sorted trials, use circular/wrap-around smoothing
backhalf = floor(avewidth/2);
fronthalf = floor((avewidth-1)/2);
if avewidth > 2
[allamps,outtrials] = movav([allamps(:,[(end-backhalf+1):end]),...
allamps,...
allamps(:,[1:fronthalf])],...
[1:(ntrials+backhalf+fronthalf)],avewidth,decfactor,[],[],wt_wind);
% Note: sort using square window
[outsort,outtrials] = movav([sortvar((end-backhalf+1):end),...
sortvar,...
sortvar(1:fronthalf)],...
1:(ntrials+backhalf+fronthalf),avewidth,decfactor,[],[],wt_wind);
% Shift elements of outtrials so the first element is 1
outtrials = outtrials - outtrials(1) + 1;
if ~isempty(auxvar)
[auxvar,tmp] = movav([auxvar(:,[(end-backhalf+1):end]),...
auxvar,...
auxvar(:,[1:fronthalf])],...
[1:(ntrials+backhalf+fronthalf)],avewidth,decfactor,[],[],wt_wind);
% Shift elements of outtrials so the first element is 1
outtrials = outtrials - outtrials(1) + 1;
end
else % avewidth==2
[allamps,outtrials] = movav([allamps(:,end),allamps],...
[1:(ntrials+1)],avewidth,decfactor,[],[],wt_wind);
% Note: sort using square window
[outsort,outtrials] = movav([sortvar(end) sortvar],...
1:(ntrials+1),avewidth,decfactor,[],[],wt_wind);
% Shift elements of outtrials so the first element is 1
outtrials = outtrials - outtrials(1) + 1;
[auxvar,tmp] = movav([auxvar(:,end),auxvar],[1:(ntrials+1)],avewidth,decfactor,[],[],wt_wind);
% Shift elements of tmp so the first element is 1
tmp = tmp - tmp(1) + 1;
end
else % if trials not phase sorted, no wrap-around
[allamps,outtrials] = movav(allamps,1:ntrials,avewidth,decfactor,[],[],wt_wind);
%fprintf('5 Size of allamps = [%d %d]\n',size(allamps,1),size(allamps,2));
[outsort,outtrials] = movav(sortvar,1:ntrials,avewidth,decfactor,[],[],wt_wind);
if ~isempty(auxvar)
[auxvar,tmp] = movav(auxvar,1:ntrials,avewidth,decfactor,[],[],wt_wind);
end
end
for index=1:length(percentiles)
outpercent{index} = compute_percentile( sortvar, percentiles(index), outtrials, avewidth);
end;
fprintf('Output allamps data will be %d frames by %d smoothed trials.\n',...
frames,length(outtrials));
else % if no smoothing
outtrials = 1:ntrials;
outsort = sortvar;
end
allamps = 20*log10(allamps); % convert allamps to dB
amps = 20*log10(amps); % convert latency mean amps to dB
ampsig = 20*log10(ampsig); % convert amplitude signif thresholds to dB
if alpha>0
fprintf('Amplitude significance levels: [%g %g] dB\n',ampsig(1),ampsig(2));
end
if isnan(baseamp) % if not specified in 'limits'
[amps,baseamp] = rmbase(amps,length(times),base); % subtract the dB baseline (baseamp)
% amps are the means at each latency
allamps = allamps - baseamp; % subtract dB baseline from allamps
% amplitude
ampsig = ampsig - baseamp; % subtract dB baseline from ampsig
else % if baseamp specified in 'limits' (as last argument 'basedB', see help)
amps = amps-baseamp; % use specified (log) baseamp
allamps = allamps - baseamp; % subtract dB baseline
if isnan(signifs);
ampsig = ampsig-baseamp; % subtract dB baseline
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%%% Find color axis limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(Caxis)
mindat = Caxis(1);
maxdat = Caxis(2);
fprintf('Using the specified caxis range of [%g,%g].\n',...
mindat,maxdat);
else
% Changed -JH
% 0.8 is Scott's suggestion to make the erp image show small
% variations better
maxdat = 0.8 * max(max(abs(allamps)));
mindat = -maxdat;
% $$$ mindat = min(min(allamps));
% $$$ maxdat = max(max(allamps));
% $$$ maxdat = max(abs([mindat maxdat])); % make symmetrical about 0
% $$$ mindat = -maxdat;
if ~isempty(caxfraction)
adjmax = (1-caxfraction)/2*(maxdat-mindat);
mindat = mindat+adjmax;
maxdat = maxdat-adjmax;
fprintf(...
'The caxis range will be %g times the sym. abs. data range -> [%g,%g].\n',...
caxfraction,mindat,maxdat);
else
fprintf(...
'The caxis range will be the sym. abs. data range -> [%g,%g].\n',...
mindat,maxdat);
end
end
%
%%%%%%%%%%%%%%%%%%%%% Image amplitudes at coherfreq %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
fprintf('Plotting amplitudes at freq %g Hz instead of potentials.\n',coherfreq);
if TIMEX
imagesc(times,outtrials,allamps',[mindat,maxdat]);% plot time on x-axis
set(gca,'Ydir','normal');
axis([timelimits(1) timelimits(2) ...
min(outtrials) max(outtrials)]);
else
imagesc(outtrials,times,allamps,[mindat,maxdat]); % plot trials on x-axis
axis([min(outtrials) max(outtrials)...
timelimits(1) timelimits(2)]);
end
try colormap(DEFAULT_COLORMAP); catch, end;
drawnow
hold on
end;
data = allamps;
elseif exist('data2') %%%%%% Plot allcohers instead of data %%%%%%%%%%%%%%%%%%%
%%%%%%%%% UNDOCUMENTED AND DEPRECATED OPTION %%%%%%%%%%%%
if freq > 0
coherfreq = mean(freq); % use phase-sort frequency
end
if alpha>0
fprintf('Computing and plotting %g coherence significance level...\n',alpha);
% [amps,cohers,cohsig,ampsig,allcohers] = ...
% crosscoher(urdata,data2,length(times),srate,coherfreq,cycles,alpha);
fprintf('Inter-Trial Coherence significance level: %g\n',cohsig);
fprintf('Amplitude significance levels: [%g %g]\n',ampsig(1),ampsig(2));
else
% [amps,cohers,cohsig,ampsig,allcohers] = ...
% crosscoher(urdata,data2,length(times),srate,coherfreq,cycles,0);
end
if ~exist('allcohers')
fprintf('\nerpimage(): allcohers not returned....\n')
return
end
allamps = allcohers; % output variable
% fprintf('Size allcohers = (%d, %d)\n',size(allcohers,1),size(allcohers,2));
% fprintf('#1 Size of allcohers = [%d %d]\n',size(allcohers,1),size(allcohers,2));
base = find(times<=0);
if length(base)<2
base = 1:floor(length(times)/4); % default first quarter-epoch
end
amps = 20*(log10(amps) - log10(mean(amps))); % convert to dB
%amps = 20*log10(amps); % convert to dB
ampsig = 20*(log10(ampsig) - log10(mean(amps))); % convert to dB
%ampsig = 20*log10(ampsig); % convert to dB
if isnan(baseamp)
[amps,baseamp] = rmbase(amps,length(times),base); % remove baseline
else
amps = amps - baseamp;
end
% fprintf('#2 Size of allcohers = [%d %d]\n',size(allcohers,1),size(allcohers,2));
if avewidth > 1 || decfactor > 1
if Nosort == YES
fprintf(...
'Smoothing the amplitude epochs using a window width of %g epochs '...
,avewidth);
else
fprintf(...
'Smoothing the sorted amplitude epochs with a %g-epoch moving window.'...
,avewidth);
end
fprintf('\n');
fprintf(' and a decimation factor of %g\n',decfactor);
% fprintf('4 Size of allcohers = [%d %d]\n',size(allcohers,1),size(allcohers,2));
[allcohers,outtrials] = movav(allcohers,1:ntrials,avewidth,decfactor,[],[],wt_wind);
% fprintf('5 Size of allcohers = [%d %d]\n',size(allcohers,1),size(allcohers,2));
[outsort,outtrials] = movav(sortvar,1:ntrials,avewidth,decfactor,[],[],wt_wind);
% fprintf('Output data will be %d frames by %d smoothed trials.\n',...
% frames,length(outtrials));
else
outtrials = 1:ntrials;
outsort = sortvar;
end
%
%%%%%%%%%%%%%%%%%%%%%%%%% Find color axis limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(Caxis)
mindat = Caxis(1);
maxdat = Caxis(2);
fprintf('Using the specified caxis range of [%g,%g].\n',...
mindat,maxdat);
else
mindat = -1;
maxdat = 1
fprintf(...
'The caxis range will be the sym. abs. data range [%g,%g].\n',...
mindat,maxdat);
end
%
%%%%%%%%%%%%%%%%%%%%% Image coherences at coherfreq %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
fprintf('Plotting coherences at freq %g Hz instead of potentials.\n',coherfreq);
if TIMEX
imagesc(times,outtrials,allcohers',[mindat,maxdat]);% plot time on x-axis
set(gca,'Ydir','normal');
axis([timelimits(1) timelimits(2) ...
min(outtrials) max(outtrials)]);
else
imagesc(outtrials,times,allcohers,[mindat,maxdat]); % plot trials on x-axis
axis([min(outtrials) max(outtrials)...
timelimits(1) timelimits(2)]);
end
try colormap(DEFAULT_COLORMAP); catch, end;
drawnow
hold on
end;
end
%Change limits on ERPimage y-axis if requested
if ~isempty(sortvar_limits)
if exist('phargs','var'),
fprintf('********* Warning *********\n');
fprintf('Specifying sorting variable limits has no effect when sorting by phase.\n');
elseif exist('valargs','var'),
fprintf('********* Warning *********\n');
fprintf('Specifying sorting variable limits has no effect when sorting by mean EEG voltage.\n');
elseif exist('ampargs','var'),
fprintf('********* Warning *********\n');
fprintf('Specifying sorting variable limits has no effect when sorting by frequency amp.\n');
else
v=axis;
img_mn=find_crspnd_pt(sortvar_limits(1),outsort,outtrials);
if isempty(img_mn),
img_mn=1;
sortvar_limits(1)=outsort(1);
end
img_mx=find_crspnd_pt(sortvar_limits(2),outsort,outtrials);
if isempty(img_mx),
img_mx=length(outsort);
sortvar_limits(2)=outsort(img_mx);
end
axis([v(1:2) img_mn img_mx]);
id1=find(sortvar>=sortvar_limits(1));
id2=find(sortvar<=sortvar_limits(2));
id=intersect_bc(id1,id2);
fprintf('%d epochs fall within sortvar limits.\n',length(id));
urdata=urdata(:,id);
if ~isempty(tsurdata),
tsurdata=tsurdata(:,id);
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%% End plot image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmpi(NoShow, 'no')
v=axis;
fprintf('Output data will be %d frames by %d smoothed trials.\n',...
frames,v(4)-v(3)+1);
fprintf('Outtrials: %3.2f to %4.2f\n',v(3),v(4));
end;
%
%%%%%%%%%%%%%%%%%%%%% Compute y-axis tick values and labels (if requested) %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
if ~isempty(img_ylab) && ~strcmpi(img_ylab,'Trials')
%make ERPimage y-tick labels in units of sorting variable
if isempty(sortvar_limits),
mn=min(outsort);
mx=max(outsort);
else
mn=sortvar_limits(1);
mx=sortvar_limits(2);
end
ord=orderofmag(mx-mn);
rng_rnd=round([mn mx]/ord)*ord;
if isempty(img_ytick_lab)
img_ytick_lab=[rng_rnd(1):ord:rng_rnd(2)];
in_range=find((img_ytick_lab>=mn) & (img_ytick_lab<=mx));
img_ytick_lab=img_ytick_lab(in_range);
else
img_ytick_lab=unique_bc(img_ytick_lab); %make sure it is sorted
in_range=find((img_ytick_lab>=mn) & (img_ytick_lab<=mx));
if length(img_ytick_lab)~=length(in_range),
fprintf('\n***Warning***\n');
fprintf('''img_trialax_ticks'' exceed smoothed sorting variable values. Max/min values are %f/%f.\n\n',mn,mx);
img_ytick_lab=img_ytick_lab(in_range);
end
end
n_tick=length(img_ytick_lab);
img_ytick=zeros(1,n_tick);
for tickloop=1:n_tick,
img_ytick(tickloop)=find_crspnd_pt(img_ytick_lab(tickloop),outsort,outtrials);
end
elseif ~isempty(img_ylab), %make ERPimage y-tick labels in units of Trials
if isempty(img_ytick_lab)
v=axis; %note: sorting variable limits have already been used to determine range of ERPimage y-axis
mn=v(3);
mx=v(4);
ord=orderofmag(mx-mn);
rng_rnd=round([mn mx]/ord)*ord;
img_ytick=[rng_rnd(1):ord:rng_rnd(2)];
in_range=find((img_ytick>=mn) & (img_ytick<=mx));
img_ytick=img_ytick(in_range);
else
img_ytick=img_ytick_lab;
end
end
end;
%% %%%%%%%%%%%%%%%%%%%%%%%%% plot vert lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(verttimes)
if size(verttimes,1) ~= 1 & size(verttimes,2) == 1 & size(verttimes,1) ~= ntrials
verttimes = verttimes';
end
if size(verttimes,1) ~= 1 & size(verttimes,1) ~= ntrials
fprintf('\nerpimage(): vert arg matrix must have 1 or %d rows\n',ntrials);
return
end;
if strcmpi(NoShow, 'no')
if size(verttimes,1) == 1
fprintf('Plotting %d lines at times: ',size(verttimes,2));
else
fprintf('Plotting %d traces starting at times: ',size(verttimes,2));
end
for vt = verttimes % for each column
fprintf('%g ',vt(1));
if isnan(aligntime) % if NOT re-aligned data
if TIMEX % overplot vt on image
if length(vt)==1
mydotstyle = DOTSTYLE;
if exist('auxcolors') & ...
length(verttimes) == length(auxcolors)
mydotstyle = auxcolors{find(verttimes == vt)};
end
plot([vt vt],[0 max(outtrials)],mydotstyle,'Linewidth',VERTWIDTH);
elseif length(vt)==ntrials
[outvt,ix] = movav(vt,1:ntrials,avewidth,decfactor,[],[],wt_wind);
plot(outvt,outtrials,DOTSTYLE,'Linewidth',VERTWIDTH);
end
else
if length(vt)==1
plot([0 max(outtrials)],[vt vt],DOTSTYLE,'Linewidth',VERTWIDTH);
elseif length(vt)==ntrials
[outvt,ix] = movav(vt,1:ntrials,avewidth,decfactor,[],[],wt_wind);
plot(outtrials,outvt,DOTSTYLE,'Linewidth',VERTWIDTH);
end
end
else % re-aligned data
if TIMEX % overplot vt on image
if length(vt)==ntrials
[outvt,ix] = movav(vt,1:ntrials,avewidth,decfactor,[],[],wt_wind);
plot(aligntime+outvt-outsort,outtrials,DOTSTYLE,'LineWidth',VERTWIDTH);
elseif length(vt)==1
plot(aligntime+vt-outsort,outtrials,DOTSTYLE,'LineWidth',VERTWIDTH);
end
else
if length(vt)==ntrials
[outvt,ix] = movav(vt,1:ntrials,avewidth,decfactor,[],[],wt_wind);
plot(outtrials,aligntime+outvt-outsort,DOTSTYLE,'LineWidth',VERTWIDTH);
elseif length(vt)==1
plot(outtrials,aligntime+vt-outsort,DOTSTYLE,'LineWidth',VERTWIDTH);
end
end
end
end
%end
fprintf('\n');
end;
end
%
%% %%%%%%%%%%%%%%%%%%%%%%%%% plot horizontal ('horz') lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(horzepochs)
if size(horzepochs,1) > 1 & size(horzepochs,1) > 1
fprintf('\nerpimage(): horz arg must be a vector\n');
return
end;
if strcmpi(NoShow, 'no')
if ~isempty(img_ylab) && ~strcmpi(img_ylab,'Trials'),
%trial axis in units of sorting variable
mx=max(outsort);
mn=min(outsort);
fprintf('Plotting %d lines at epochs corresponding to sorting variable values: ',length(horzepochs));
for he = horzepochs % for each horizontal line
fprintf('%g ',he);
%find trial number corresponding to this value of sorting
%variable:
if (he>mn) && (he<mx)
he_ep=find_crspnd_pt(he,outsort,outtrials);
if TIMEX % overplot he_ep on image
plot([timelimits(1) timelimits(2)],[he_ep he_ep],LINESTYLE,'Linewidth',HORZWIDTH);
else
plot([he_ep he_ep], [timelimits(1) timelimits(2)],LINESTYLE,'Linewidth',HORZWIDTH);
end
end
end
else %trial axis in units of trials
fprintf('Plotting %d lines at epochs: ',length(horzepochs));
for he = horzepochs % for each horizontal line
fprintf('%g ',he);
if TIMEX % overplot he on image
plot([timelimits(1) timelimits(2)],[he he],LINESTYLE,'Linewidth',HORZWIDTH);
else
plot([he he], [timelimits(1) timelimits(2)],LINESTYLE,'Linewidth',HORZWIDTH);
end
end
end
fprintf('\n');
end;
end
if strcmpi(NoShow, 'no')
set(gca,'FontSize',TICKFONT)
hold on;
end;
%
%% %%%%%%%%% plot vertical line at 0 or align time %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
if ~isnan(aligntime) % if trials time-aligned
if times(1) <= aligntime & times(frames) >= aligntime
plot([aligntime aligntime],[min(outtrials) max(outtrials)],...
'k','Linewidth',ZEROWIDTH); % plot vertical line at time 0
% plot vertical line at aligntime
end
else % trials not time-aligned
if times(1) <= 0 & times(frames) >= 0
plot([0 0],[min(outtrials) max(outtrials)],...
'k','Linewidth',ZEROWIDTH); % plot smoothed sortwvar
end
end
end;
if strcmpi(NoShow, 'no') & ( min(outsort) < timelimits(1) ...
|max(outsort) > timelimits(2))
ur_outsort = outsort; % store the pre-adjusted values
fprintf('Not all sortvar values within time vector limits: \n')
fprintf(' outliers will be shown at nearest limit.\n');
i = find(outsort< timelimits(1));
outsort(i) = timelimits(1);
i = find(outsort> timelimits(2));
outsort(i) = timelimits(2);
end
if strcmpi(NoShow, 'no')
if TIMEX
if Nosort == YES
l=ylabel(img_ylab);
if ~isempty(img_ylab) && ~strcmpi(img_ylab,'Trials')
set(gca,'ytick',img_ytick,'yticklabel',img_ytick_lab);
end
else
if exist('phargs','var')
l=ylabel('Phase-sorted Trials');
elseif exist('ampargs','var')
l=ylabel('Amplitude-sorted Trials');
elseif exist('valargs','var')
l=ylabel('Voltage-sorted Trials');
else
l=ylabel(img_ylab);
if ~isempty(img_ylab)
set(gca,'ytick',img_ytick);
end
if ~strcmpi(img_ylab,'Trials')
set(gca,'yticklabel',img_ytick_lab);
end
end
end
else % if switch x<->y axes
if Nosort == YES & NoTimeflag==NO
l=xlabel(img_ylab);
if ~isempty(img_ylab) && ~strcmpi(img_ylab,'Trials')
set(gca,'xtick',img_ytick,'xticklabel',img_ytick_lab);
end
else
if exist('phargs')
l=ylabel('Phase-sorted Trials');
elseif NoTimeflag == NO
l=xlabel('Sorted Trials');
else
l=xlabel(img_ylab);
if ~isempty(img_ylab) && ~strcmpi(img_ylab,'Trials')
set(gca,'xtick',img_ytick,'xticklabel',img_ytick_lab);
end
end
end
end
set(l,'FontSize',LABELFONT);
if ~strcmpi(plotmode, 'topo')
t=title(titl);
set(t,'FontSize',LABELFONT);
else
NAME_OFFSETX = 0.1;
NAME_OFFSETY = 0.2;
xx = xlim; xmin = xx(1); xdiff = xx(2)-xx(1); xpos = double(xmin+NAME_OFFSETX*xdiff);
yy = ylim; ymax = yy(2); ydiff = yy(2)-yy(1); ypos = double(ymax-NAME_OFFSETY*ydiff);
t=text(xpos, ypos,titl);
axis off;
end;
set(gca,'Box','off');
set(gca,'Fontsize',TICKFONT);
set(gca,'color',BACKCOLOR);
if Erpflag == NO & NoTimeflag == NO
if exist('NoTimesPassed')~=1
l=xlabel('Time (ms)');
else
l=xlabel('Frames');
end
set(l,'Fontsize',LABELFONT);
end
end;
%
%% %%%%%%%%%%%%%%%%%% Overplot sortvar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
if NoShowVar == YES
fprintf('Not overplotting sorted sortvar on data.\n');
elseif isnan(aligntime) % plot sortvar on un-aligned data
if Nosort == NO;
fprintf('Overplotting sorted sortvar on data.\n');
end
hold on;
if TIMEX % overplot sortvar
plot(outsort,outtrials,'k','LineWidth',SORTWIDTH);
else
plot(outtrials,outsort,'k','LineWidth',SORTWIDTH);
end
drawnow
else % plot re-aligned zeros on sortvar-aligned data
if Nosort == NO;
fprintf('Overplotting sorted sortvar on data.\n');
end
hold on;
if TIMEX % overplot re-aligned 0 time on image
plot([aligntime aligntime],[min(outtrials) max(outtrials)],...
'k','LineWidth',SORTWIDTH);
else
plot([[min(outtrials) max(outtrials)],aligntime aligntime],...
'k','LineWidth',SORTWIDTH);
end
fprintf('Overplotting realigned times-zero on data.\n');
hold on;
if TIMEX % overplot realigned sortvar on image
plot(0+aligntime-outsort,outtrials,'k','LineWidth',ZEROWIDTH);
else
plot(0+outtrials,aligntime-outsort,'k','LineWidth',ZEROWIDTH);
end
drawnow
end
end;
%
%% %%%%%%%%%%%%%%%%%% Overplot auxvar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
if ~isempty(auxvar)
fprintf('Overplotting auxvar(s) on data.\n');
hold on;
auxtrials = outtrials(:)' ; % make row vector
if exist('auxcolors')~=1 % If no auxcolors specified
auxcolors = cell(1,size(auxvar,1));
for c=1:size(auxvar,1)
auxcolors(c) = {'k'}; % plot auxvars as black trace(s)
end
end
if length(auxcolors) < size(auxvar,1)
nauxColors = length(auxcolors);
for k=nauxColors+1:size(auxvar,1)
auxcolors = { auxcolors{:} auxcolors{1+rem(k-1,nauxColors)}};
end
end
for c=1:size(auxvar,1)
auxcolor = auxcolors{c};
if ~isempty(auxcolor)
if isnan(aligntime) % plot auxvar on un-aligned data
if TIMEX % overplot auxvar
plot(auxvar(c,:)',auxtrials',auxcolor,'LineWidth',SORTWIDTH);
else
plot(auxtrials',auxvar(c,:)',auxcolor,'LineWidth',SORTWIDTH);
end
drawnow
else % plot re-aligned zeros on sortvar-aligned data
if TIMEX % overplot realigned 0-time on image
plot(auxvar(c,:)',auxtrials',auxcolor,'LineWidth',ZEROWIDTH);
else
plot(0+auxtrials',aligntime-auxvar(c,:)',auxcolor,'LineWidth',ZEROWIDTH);
end
drawnow
end % aligntime
end % if auxcolor
end % c
end % auxvar
if exist('outpercent')
for index = 1:length(outpercent)
if isnan(aligntime) % plot auxvar on un-aligned data
plot(outpercent{index},outtrials,'k','LineWidth',SORTWIDTH);
else
plot(aligntime-outpercent{index},outtrials,'k','LineWidth',SORTWIDTH);
end;
end;
end;
end;
%
%% %%%%%%%%%%%%%%%%%%%%%% Plot colorbar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
if Colorbar == YES
pos=get(ax1,'Position');
axcb=axes('Position',...
[pos(1)+pos(3)+0.02 pos(2) ...
0.03 pos(4)]);
cbar(axcb,0,[mindat,maxdat]); % plot colorbar to right of image
title(cbar_title);
set(axcb,'fontsize',TICKFONT,'xtick',[]);
% drawnow
axes(ax1); % reset current axes to the erpimage
end
end;
%
%% %%%%%%%%%%%%%%%%%%%%% Compute ERP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
erp = [];
if Erpflag == YES
if exist('erpalpha')
if erp_ptiles>1,
fprintf(['\nOnly plotting one ERP (i.e., not plotting ERPs from %d percentile splits) ' ...
'because ''erpalpha'' option was chosen. You can''t plot both.\n\n'],erp_ptiles)
end
[erp erpsig] = nan_mean(fastif(length(tsurdata) > 0, tsurdata',urdata'), ...
erpalpha);
fprintf(' Mean ERP (p<%g) significance threshold: +/-%g\n', ...
erpalpha,mean(erpsig));
else
%potentially make ERPs of 50%, 33%, or 25% split of trials
n_trials=size(urdata,2);
trials_step=round(n_trials/erp_ptiles);
erp=zeros(erp_ptiles,size(urdata,1));
for ploop=1:erp_ptiles,
ptile_trials=[1:trials_step]+(ploop-1)*trials_step;
if max(ptile_trials)>n_trials,
ptile_trials=ptile_trials(1):n_trials;
end
if length(tsurdata) > 0
erp(ploop,:) = nan_mean(tsurdata(:,ptile_trials)');
else
erp(ploop,:) = nan_mean(urdata(:,ptile_trials)');
end;
end
% else
%orig line
%[erp] = nan_mean(fastif(length(tsurdata) > 0, tsurdata', urdata'));
%end
end % compute average ERP, ignoring nan's
end;
if Erpflag == YES & strcmpi(NoShow, 'no')
axes(ax1); % reset current axes to the erpimage
xtick = get(ax1,'Xtick'); % remember x-axis tick locations
xticklabel = get(ax1,'Xticklabel'); % remember x-axis tick locations
set(ax1, 'xticklabel', []);
widthxticklabel = size(xticklabel,2);
xticklabel = cellstr(xticklabel);
for tmpindex = 1:length(xticklabel)
if length(xticklabel{tmpindex}) < widthxticklabel
spaces = char(ones(1,ceil((widthxticklabel-length(xticklabel{tmpindex}))/2) )*32);
xticklabel{tmpindex} = [spaces xticklabel{tmpindex}];
end;
end;
xticklabel = strvcat(xticklabel);
if Erpstdflag == YES
stdev = nan_std(urdata');
end;
%
%%%%%% Plot ERP time series below image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isnan(maxerp)
fac = 10;
maxerp = 0;
while maxerp == 0
maxerp = round(fac*YEXPAND*max(erp))/fac; % minimal decimal places
fac = 10*fac;
end
if Erpstdflag == YES
fac = fac/10;
maxerp = max(maxerp, round(fac*YEXPAND*max(erp+stdev))/fac);
end;
if ~isempty(erpsig)
erpsig = [erpsig;-1*erpsig];
maxerp = max(maxerp, round(fac*YEXPAND*max(erpsig))/fac);
end
maxerp=max(maxerp);
end
if isnan(minerp)
fac = 1;
minerp = 0;
while minerp == 0
minerp = round(fac*YEXPAND*min(erp))/fac; % minimal decimal places
fac = 10*fac;
end
if Erpstdflag == YES
fac = fac/10;
minerp = min(minerp, round(fac*YEXPAND*min(erp-stdev))/fac);
end;
if ~isempty(erpsig)
minerp = min(minerp, round(fac*YEXPAND*min(erpsig))/fac);
end
minerp=min(minerp);
end
limit = [timelimits(1:2) minerp maxerp];
if ~isnan(coherfreq)
set(ax1,'Xticklabel',[]); % remove tick labels from bottom of image
ax2=axes('Position',...
[gcapos(1) gcapos(2)+2/3*image_loy*gcapos(4) ...
gcapos(3) (image_loy/3-YGAP)*gcapos(4)]);
else
ax2=axes('Position',...
[gcapos(1) gcapos(2) ...
gcapos(3) image_loy*gcapos(4)]);
end
fprintf('Plotting the ERP trace below the ERP image\n');
if Erpstdflag == YES
if Showwin
tmph = plot1trace(ax2,times,erp,limit,[],stdev,times(winlocs),erp_grid,erp_vltg_ticks); % plot ERP +/-stdev
else
tmph = plot1trace(ax2,times,erp,limit, [], stdev,[],erp_grid,erp_vltg_ticks); % plot ERP +/-stdev
end
elseif ~isempty('erpsig')
if Showwin
tmph = plot1trace(ax2,times,erp,limit,erpsig,[],times(winlocs),erp_grid,erp_vltg_ticks); % plot ERP and 0+/-alpha threshold
else
tmph = plot1trace(ax2,times,erp,limit,erpsig,[],[],erp_grid,erp_vltg_ticks); % plot ERP and 0+/-alpha threshold
end
else % plot ERP alone - no significance or std dev plotted
if Showwin
tmph = plot1trace(ax2,times,erp,limit,[],[],times(winlocs),erp_grid,erp_vltg_ticks); % plot ERP alone
else
tmph = plot1trace(ax2,times,erp,limit,[],[],[],erp_grid,erp_vltg_ticks); % plot ERP alone
end
end;
if ~isnan(aligntime)
line([aligntime aligntime],[limit(3:4)*1.1],'Color','k','LineWidth',ZEROWIDTH); % x=median sort value
line([0 0],[limit(3:4)*1.1],'Color','k','LineWidth',ZEROWIDTH); % x=median sort value
% remove y axis
if length(tmph) > 1
delete(tmph(end));
end;
end
set(ax2,'Xtick',xtick); % use same Xticks as erpimage above
if ~isnan(coherfreq)
set(ax2,'Xticklabel',[]); % remove tick labels from ERP x-axis
else % bottom axis
set(ax2,'Xticklabel',xticklabel); % add ticklabels to ERP x-axis
end
if isnan(coherfreq) % if no amp and coher plots below . . .
if TIMEX & NoTimeflag == NO
if exist('NoTimesPassed')~=1
l=xlabel('Time (ms)');
else
l=xlabel('Frames');
end
set(l,'FontSize',LABELFONT);
% $$$ else
% $$$ if exist('NoTimesPassed')~=1
% $$$ l=ylabel('Time (ms)');
% $$$ else
% $$$ l=ylabel('Frames');
% $$$ end
% $$$ set(l,'FontSize',LABELFONT);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% plot vert lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(verttimes)
if size(verttimes,1) == ntrials
vts=sort(verttimes);
vts = vts(ceil(ntrials/2),:); % plot median verttimes values if a matrix
else
vts = verttimes(:)'; % make verttimes a row vector
end
for vt = vts
if isnan(aligntime)
if TIMEX % overplot vt on ERP
mydotstyle = DOTSTYLE;
if exist('auxcolors') & ...
length(verttimes) == length(verttimesColors)
mydotstyle = verttimesColors{find(verttimes == vt)};
end
plot([vt vt],[limit(3:4)],mydotstyle,'Linewidth',VERTWIDTH);
else
plot([min(outtrials) max(outtrials)],[limit(3:4)],DOTSTYLE,...
'Linewidth',VERTWIDTH);
end
else
if TIMEX % overplot realigned vt on ERP
plot(repmat(median(aligntime+vt-outsort),1,2),[limit(3),limit(4)],...
DOTSTYLE,'LineWidth',VERTWIDTH);
else
plot([limit(3),limit(4)],repmat(median(aligntime+vt-outsort),1,2),...
DOTSTYLE,'LineWidth',VERTWIDTH);
end
end
end
end
limit = double(limit);
ydelta = double(1/10*(limit(2)-limit(1)));
ytextoffset = double(limit(1)-1.1*ydelta);
ynumoffset = double(limit(1)-0.3*ydelta); % double for Matlab 7
%Far left axis max and min labels not needed now that there are tick
%marks
%t=text(ynumoffset,0.7*limit(3), num2str(limit(3)));
%set(t,'HorizontalAlignment','right','FontSize',TICKFONT)
%t=text(ynumoffset,0.7*limit(4), num2str(limit(4)));
%set(t,'HorizontalAlignment','right','FontSize',TICKFONT)
ynum = 0.7*(limit(3)+limit(4))/2;
t=text(ytextoffset,ynum,yerplabel,'Rotation',90);
set(t,'HorizontalAlignment','center','FontSize',LABELFONT)
if ~exist('YDIR')
error('\nerpimage(): Default YDIR not read from ''icadefs.m''');
end
if YDIR == 1
set(ax2,'ydir','normal')
else
set(ax2,'ydir','reverse')
end
set(ax2,'Fontsize',TICKFONT);
set(ax2,'Box','off','color',BACKCOLOR);
drawnow
end
%
%% %%%%%%%%%%%%%%%%%%% Plot amp, coher time series %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isnan(coherfreq)
if freq > 0
coherfreq = mean(freq); % use phase-sort frequency
end
%
%%%%%% Plot amp axis below ERP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~Allampsflag %%%% don't repeat computation if already done for 'allamps'
fprintf('Computing and plotting amplitude at %g Hz.\n',coherfreq);
if ~isnan(signifs) | Cohsigflag==NO % don't compute or plot signif. levels
[amps,cohers] = phasecoher(urdata,size(times,2),srate,coherfreq,cycles);
if ~isnan(signifs)
ampsig = signifs([1 2]);
fprintf('Using supplied amplitude significance levels: [%g,%g]\n',...
ampsig(1),ampsig(2));
cohsig = signifs(3);
fprintf('Using supplied coherence significance level: %g\n',cohsig);
end
else % compute amps, cohers with significance
fprintf(...
'Computing and plotting %g coherence significance level at %g Hz...\n',...
alpha, coherfreq);
[amps,cohers,cohsig,ampsig] = ...
phasecoher(urdata,size(times,2),srate,coherfreq,cycles,alpha);
fprintf('Coherence significance level: %g\n',cohsig);
ampsig = 20*log10(ampsig); % convert to dB
end
amps = 20*log10(amps); % convert to dB
if isnan(baseamp) % if baseamp not specified in 'limits'
if ~isempty(baselinedb) && isnan(baselinedb(1))
disp('Not removing amplitude baseline');
else
if isempty(baselinedb)
baselinedb = [times(1) DEFAULT_BASELINE_END];
end;
base = find(times >= baselinedb(1) & times<=baselinedb(end)); % use default baseline end point (ms)
if length(base)<2
base = 1:floor(length(times)/4); % default first quarter-epoch
fprintf('Using %g to %g ms as amplitude baseline.\n',...
times(1),times(base(end)));
end
[amps,baseamp] = rmbase(amps,length(times),base); % remove dB baseline
fprintf('Removed baseline amplitude of %d dB for plotting.\n',baseamp);
end;
else % if 'basedB' specified in 'limits' (in dB)
fprintf('Removing specified baseline amplitude of %d dB for plotting.\n',...
baseamp);
amps = amps-baseamp; % remove specified dB baseline
end
fprintf('Data amplitude levels: [%g %g] dB\n',min(amps),max(amps));
if alpha>0 % if computed significance levels
ampsig = ampsig - baseamp;
fprintf('Data amplitude significance levels: [%g %g] dB\n',ampsig(1),ampsig(2));
end
end % ~Allampsflag
if strcmpi(NoShow, 'no')
axis('off') % rm ERP axes axis and labels
v=axis;
minampERP=v(3);
maxampERP=v(4);
if ~exist('ynumoffset')
limit = [timelimits(1:2) -max(abs([minampERP maxampERP])) max(abs([minampERP maxampERP]))];
limit = double(limit);
ydelta = double(1/10*(limit(2)-limit(1)));
ytextoffset = double(limit(1)-1.1*ydelta);
ynumoffset = double(limit(1)-0.3*ydelta); % double for Matlab 7
end
t=text(double(ynumoffset),double(maxampERP),num2str(maxampERP,3));
set(t,'HorizontalAlignment','right','FontSize',TICKFONT);
t=text(double(ynumoffset),double(minampERP), num2str(minampERP,3));
set(t,'HorizontalAlignment','right','FontSize',TICKFONT);
ax3=axes('Position',...
[gcapos(1) gcapos(2)+1/3*image_loy*gcapos(4) ...
gcapos(3) (image_loy/3-YGAP)*gcapos(4)]);
if isnan(maxamp) % if not specified
fac = 1;
maxamp = 0;
while maxamp == 0
maxamp = floor(YEXPAND*fac*max(amps))/fac; % minimal decimal place
fac = 10*fac;
end
maxamp = maxamp + 10/fac;
if Cohsigflag
if ampsig(2)>maxamp
if ampsig(2)>0
maxamp = 1.01*(ampsig(2));
else
maxamp = 0.99*(ampsig(2));
end
end
end
end
if isnan(maxamp), maxamp = 0; end % In case the above iteration went on
% until fac = Inf and maxamp = NaN again.
if isnan(minamp) % if not specified
fac = 1;
minamp = 0;
while minamp == 0
minamp = floor(YEXPAND*fac*max(-amps))/fac; % minimal decimal place
fac = 10*fac;
end
minamp = minamp + 10/fac;
minamp = -minamp;
if Cohsigflag
if ampsig(1)< minamp
if ampsig(1)<0
minamp = 1.01*(ampsig(1));
else
minamp = 0.99*(ampsig(1));
end
end
end
end
if isnan(minamp), minamp = 0; end % In case the above iteration went on
% until fac = Inf and minamp = NaN again.
fprintf('Plotting the ERSP amplitude trace below the ERP\n');
fprintf('Min, max plotting amplitudes: [%g, %g] dB\n',minamp,maxamp);
fprintf(' relative to baseamp: %g dB\n',baseamp);
if Cohsigflag
ampsiglims = [repmat(ampsig(1)-mean(ampsig),1,length(times))];
ampsiglims = [ampsiglims;-1*ampsiglims];
plot1trace(ax3,times,amps,[timelimits minamp(1) maxamp(1)],ampsiglims,[],[],0); % plot AMP
else
plot1trace(ax3,times,amps,[timelimits minamp(1) maxamp(1)],[],[],[],0); % plot AMP
end
if ~isnan(aligntime)
line([aligntime aligntime],[minamp(1) maxamp(1)]*1.1,'Color','k');
% x=median sort value
end
if exist('xtick') % Added -JH
set(ax3,'Xtick',xtick);
end
set(ax3,'Xticklabel',[]); % remove tick labels from bottom of image
set(ax3,'Yticklabel',[]); % remove tick labels from left of image
set(ax3,'YColor',BACKCOLOR);
axis('off');
set(ax3,'Box','off','color',BACKCOLOR);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% plot vert marks %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(verttimes)
if size(verttimes,1) == ntrials
vts=sort(verttimes);
vts = vts(ceil(ntrials/2),:); % plot median values if a matrix
else
vts=verttimes(:)';
end
for vt = vts
if isnan(aligntime)
if TIMEX % overplot vt on amp
mydotstyle = DOTSTYLE;
if exist('auxcolors') & ...
length(verttimes) == length(verttimesColors)
mydotstyle = verttimesColors{find(verttimes == vt)};
end
plot([vt vt],[minamp(1) maxamp(1)],mydotstyle,...
'Linewidth',VERTWIDTH);
else
plot([min(outtrials) max(outtrials)],[minamp(1) maxamp(1)], ...
DOTSTYLE,...
'Linewidth',VERTWIDTH);
end
else
if TIMEX % overplot realigned vt on amp
plot(repmat(median(aligntime+vt-outsort),1,2), ...
[minamp(1),maxamp(1)],DOTSTYLE,...
'LineWidth',VERTWIDTH);
else
plot([minamp,maxamp],repmat(median(aligntime+vt-outsort),1,2), ...
DOTSTYLE,...
'LineWidth',VERTWIDTH);
end
end
end
end
if 0 % Cohsigflag % plot amplitude significance levels
hold on
plot([timelimits(1) timelimits(2)],[ampsig(1) ampsig(1)] - mean(ampsig),'r',...
'linewidth',SIGNIFWIDTH);
plot([timelimits(1) timelimits(2)],[ampsig(2) ampsig(2)] - mean(ampsig),'r',...
'linewidth',SIGNIFWIDTH);
end
if ~exist('ynumoffset')
limit = [timelimits(1:2) -max(abs([minamp maxamp])) max(abs([minamp maxamp]))];
limit = double(limit);
ydelta = double(1/10*(limit(2)-limit(1)));
ytextoffset = double(limit(1)-1.1*ydelta);
ynumoffset = double(limit(1)-0.3*ydelta); % double for Matlab 7
end
t=text(ynumoffset,maxamp, num2str(maxamp,3));
set(t,'HorizontalAlignment','right','FontSize',TICKFONT);
t=text(ynumoffset,0, num2str(0));
set(t,'HorizontalAlignment','right','FontSize',TICKFONT);
t=text(ynumoffset,minamp, num2str(minamp,3));
set(t,'HorizontalAlignment','right','FontSize',TICKFONT);
t=text(ytextoffset,(maxamp+minamp)/2,'ERSP','Rotation',90);
set(t,'HorizontalAlignment','center','FontSize',LABELFONT);
axtmp = axis;
dbtxt= text(1/13*(axtmp(2)-axtmp(1))+axtmp(1), ...
11/13*(axtmp(4)-axtmp(3))+axtmp(3), ...
[num2str(baseamp,4) ' dB']);
set(dbtxt,'fontsize',TICKFONT);
drawnow;
set(ax3, 'xlim', timelimits);
set(ax3, 'ylim', [minamp(1) maxamp(1)]);
%
%%%%%% Make coher axis below amp %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
ax4=axes('Position',...
[gcapos(1) gcapos(2) ...
gcapos(3) (image_loy/3-YGAP)*gcapos(4)]);
if isnan(maxcoh)
fac = 1;
maxcoh = 0;
while maxcoh == 0
maxcoh = floor(YEXPAND*fac*max(cohers))/fac; % minimal decimal place
fac = 10*fac;
end
maxcoh = maxcoh + 10/fac;
if maxcoh>1
maxcoh=1; % absolute limit
end
end
if isnan(mincoh)
mincoh = 0;
end
fprintf('Plotting the ITC trace below the ERSP\n');
if Cohsigflag % plot coherence significance level
cohsiglims = [repmat(cohsig,1,length(times));zeros(1,length(times))];
coh_handle = plot1trace(ax4,times,cohers,[timelimits mincoh maxcoh],cohsiglims,[],[],0);
% plot COHER, fill sorting window
else
coh_handle = plot1trace(ax4,times,cohers,[timelimits mincoh maxcoh],[],[],[],0); % plot COHER
end
if ~isnan(aligntime)
line([aligntime aligntime],[[mincoh maxcoh]*1.1],'Color','k');
% x=median sort value
end
% set(ax4,'Xticklabel',[]); % remove tick labels from bottom of
% image
if exist('xtick')
set(ax4,'Xtick',xtick);
set(ax4,'Xticklabel',xticklabel);
end
set(ax4,'Ytick',[]);
set(ax4,'Yticklabel',[]); % remove tick labels from left of image
set(ax4,'YColor',BACKCOLOR);
if ~isempty(verttimes)
if size(verttimes,1) == ntrials
vts=sort(verttimes);
vts = vts(ceil(ntrials/2),:); % plot median values if a matrix
else
vts = verttimes(:)'; % make verttimes a row vector
end
for vt = vts
if isnan(aligntime)
if TIMEX % overplot vt on coher
mydotstyle = DOTSTYLE;
if exist('auxcolors') & ...
length(verttimes) == length(verttimesColors)
mydotstyle = verttimesColors{find(verttimes == vt)};
end
plot([vt vt],[mincoh maxcoh],mydotstyle,'Linewidth',VERTWIDTH);
else
plot([min(outtrials) max(outtrials)],...
[mincoh maxcoh],DOTSTYLE,'Linewidth',VERTWIDTH);
end
else
if TIMEX % overplot realigned vt on coher
plot(repmat(median(aligntime+vt-outsort),1,2),...
[mincoh,maxcoh],DOTSTYLE,'LineWidth',VERTWIDTH);
else
plot([mincoh,maxcoh],repmat(median(aligntime+vt-outsort),1,2),...
DOTSTYLE,'LineWidth',VERTWIDTH);
end
end
end
end
t=text(ynumoffset,0, num2str(0));
set(t,'HorizontalAlignment','right','FontSize',TICKFONT);
t=text(ynumoffset,maxcoh, num2str(maxcoh));
set(t,'HorizontalAlignment','right','FontSize',TICKFONT);
t=text(ytextoffset,maxcoh/2,'ITC','Rotation',90);
set(t,'HorizontalAlignment','center','FontSize',LABELFONT);
drawnow
%if Cohsigflag % plot coherence significance level
%hold on
%plot([timelimits(1) timelimits(2)],[cohsig cohsig],'r',...
%'linewidth',SIGNIFWIDTH);
%end
set(ax4,'Box','off','color',BACKCOLOR);
set(ax4,'Fontsize',TICKFONT);
if NoTimeflag==NO
if exist('NoTimesPassed')~=1
l=xlabel('Time (ms)');
else
l=xlabel('Frames');
end
set(l,'Fontsize',LABELFONT);
end
axtmp = axis;
hztxt=text(10/13*(axtmp(2)-axtmp(1))+axtmp(1), ...
8/13*(axtmp(4)-axtmp(3))+axtmp(3), ...
[num2str(coherfreq,4) ' Hz']);
set(hztxt,'fontsize',TICKFONT);
end;% NoShow
else
amps = []; % null outputs unless coherfreq specified
cohers = [];
end
if VERS >= 8.04
axhndls = {ax1 axcb ax2 ax3 ax4};
else
axhndls = [ax1 axcb ax2 ax3 ax4];
end
if exist('ur_outsort')
outsort = ur_outsort; % restore outsort clipped values, if any
end
if nargout<1
data = []; % don't spew out data if no args out and no ;
end
%
%% %%%%%%%%%%%%% Plot a topoplot() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if (~isempty(topomap)) & strcmpi(NoShow, 'no')
h(12)=axes('Position',...
[gcapos(1)+0.10*gcapos(3) gcapos(2)+0.92*gcapos(4),...
0.20*gcapos(3) 0.14*gcapos(4)]);
% h(12) = subplot('Position',[.10 .86 .20 .14]);
fprintf('Plotting a topo map in upper left.\n');
eloc_info.plotrad = [];
if length(topomap) == 1
try
topoplot(topomap,eloc_file,'electrodes','off', ...
'style', 'blank', 'emarkersize1chan', 10, 'chaninfo', eloc_info);
catch
fprintf('topoplot() plotting failed.\n');
end;
else
try
topoplot(topomap,eloc_file,'electrodes','off', 'chaninfo', eloc_info);
catch
fprintf('topoplot() plotting failed.\n');
end;
end;
axis('square')
if VERS >= 8.04
axhndls = {axhndls h(12)};
else
axhndls = [axhndls h(12)];
end
end
%
%% %%%%%%%%%%%%% Plot a spectrum %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
SPECFONT = 10;
if (~isempty(lospecHz)) && strcmpi(NoShow, 'no')
h(13)=axes('Position',...
[gcapos(1)+0.82*gcapos(3) ...
gcapos(2)+0.96*gcapos(4),...
0.15*gcapos(3)*(0.8/gcapos(3))^0.5 ...
0.10*gcapos(4)*(0.8/gcapos(4))^0.5]);
% h(13) = subplot('Position',[.75 .88 .15 .10]);
fprintf('Plotting the data spectrum in upper right.\n');
winlength = frames;
if winlength > 512
for k=2:5
if rem(winlength,k) == 0
break
end
end
winlength = winlength/k;
end
% [Pxx, Pxxc, F] = PSD(X,NFFT,Fs,WINDOW,NOVERLAP,P)
if exist('psd') == 2
[Pxx,F] = psd(reshape(urdata,1,size(urdata,1)*size(urdata,2)),...
max(1024,pow2(ceil(log2(frames)))),srate,frames,0,0.05);
% [Pxx,F] = psd(reshape(urdata,1,size(urdata,1)*size(urdata,2)),512,srate,winlength,0,0.05);
else
[Pxx,F] = spec(reshape(urdata,1,size(urdata,1)*size(urdata,2)),...
max(1024,pow2(ceil(log2(frames)))),srate,frames,0);
% [Pxx,F] = spec(reshape(urdata,1,size(urdata,1)*size(urdata,2)),512,srate,winlength,0);
end;
plot(F,10*log10(Pxx));
goodfs = find(F>= lospecHz & F <= hispecHz);
maxgfs = max(10*log10(Pxx(goodfs)));
mingfs = min(10*log10(Pxx(goodfs)));
axis('square')
axis([lospecHz hispecHz mingfs-1 maxgfs+1]);
set(h(13),'Box','off','color',BACKCOLOR);
set(h(13),'Fontsize',SPECFONT);
set(h(13),'Xscale',SpecAxis); % added 'log' or 'linear' freq axis scaling -SM 5/31/12
l=ylabel('dB');
set(l,'Fontsize',SPECFONT);
if ~isnan(coherfreq)
hold on; plot([coherfreq,coherfreq],[mingfs maxgfs],'r');
end
if VERS >= 8.04
axhndls = {axhndls h(13)};
else
axhndls = [axhndls h(13)];
end
end
%
%% %%%%%%%%%%%%% save plotting limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
limits = [min(times) max(times) minerp maxerp minamp maxamp mincoh maxcoh];
limits = [limits baseamp coherfreq]; % add coherfreq to output limits array
%
%% %%%%%%%%%%%%% turn on axcopy() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
axcopy(gcf);
% eegstr = 'img=get(gca,''''children''''); if (strcmp(img(end),''''type''''),''''image''''), img=get(img(end),''''CData''''); times=get(img(end),''''Xdata''''); clf; args = [''''limits'''' '''','''' times(1) '''','''' times(end)]; if exist(''''EEG'''')==1, args = [args '''','''' ''''srate'''' '''','''' EEG.srate]; end eegplot(img,args); end';
% axcopy(gcf,eegstr);
end;
% returning outsort
if exist('outpercent')
outsort = { outsort outpercent };
end;
fprintf('Done.\n\n');
%
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%% End erpimage() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
axes('position',gcapos);
axis off
end;
warning on;
return
%
%% %%%%%%%%%%%%%%%%% function plot1trace() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
function [plot_handle] = plot1trace(ax,times,trace,axlimits,signif,stdev,winlocs,erp_grid,erp_vltg_ticks)
%function [plot_handle] = plot1trace(ax,times,trace,axlimits,signif,stdev,winlocs,erp_grid,erp_vltg_ticks)
% If signif is [], plot trace +/- stdev
% Else if signif, plot trace and signif(1,:)&signif(2,:) fill.
% Else, plot trace alone.
% If winlocs not [], plot grey back image(s) in sort window
% winlocs(1,1)-> winlocs(1,end) (ms)
% ...
% winlocs(end,1)-> winlocs(end,end) (ms)
FILLCOLOR = [.66 .76 1];
WINFILLCOLOR = [.88 .92 1];
ERPDATAWIDTH = 2;
ERPZEROWIDTH = 2;
axes(ax);
if nargin<9,
erp_vltg_ticks=[]; %if erp_vltg_ticks is not empty, those will be the ticks used on the y-axis (voltage axis for ERPs)
end
if ~isempty(winlocs)
for k=1:size(winlocs,1)
winloc = winlocs(k,:);
fillwinx = [winloc winloc(end:-1:1)];
hannwin = makehanning(length(winloc));
hannwin = hannwin./max(hannwin); % make max = 1
hannwin = hannwin(:)'; % make row vector
if ~isempty(axlimits) & sum(isnan(axlimits))==0
% fillwiny = [repmat(axlimits(3),1,length(winloc)) repmat(axlimits(4),1,length(winloc))];
fillwiny = [hannwin*axlimits(3) hannwin*axlimits(4)];
else
% fillwiny = [repmat(min(trace)*1.1,1,length(winloc)) repmat(max(trace)*1.1,1,length(winloc))];
fillwiny = [hannwin*2*min(trace) hannwin*2*max(trace)];
end
fillwh = fill(fillwinx,fillwiny, WINFILLCOLOR); hold on % plot 0+alpha
set(fillwh,'edgecolor',WINFILLCOLOR-[.00 .00 0]); % make edges NOT highlighted
end
end
if ~isempty(signif);% (2,times) array giving upper and lower signif limits
filltimes = [times times(end:-1:1)];
if size(signif,1) ~=2 | size(signif,2) ~= length(times)
fprintf('plot1trace(): signif array must be size (2,frames)\n')
return
end
fillsignif = [signif(1,:) signif(2,end:-1:1)];
fillh = fill(filltimes,fillsignif, FILLCOLOR); hold on % plot 0+alpha
set(fillh,'edgecolor',FILLCOLOR-[.02 .02 0]); % make edges slightly highlighted
% [plot_handle] = plot(times,signif, 'r','LineWidth',1); hold on % plot 0+alpha
% [plot_handle] = plot(times,-1*signif, 'r','LineWidth',1); hold on % plot 0-alpha
end
if ~isempty(stdev)
[st1] = plot(times,trace+stdev, 'r--','LineWidth',1); hold on % plot trace+stdev
[st2] = plot(times,trace-stdev, 'r--','LineWidth',1); hold on % plot trace-stdev
end
%linestyles={'r','m','c','b'};
% 'LineStyle',linestyles{traceloop}); hold on
linecolor={[0 0 1],[.25 0 .75],[.75 0 .25],[1 0 0]};
plot_handle=zeros(1,size(trace,1));
for traceloop=1:size(trace,1),
[plot_handle(traceloop)] = plot(times,trace(traceloop,:),'LineWidth',ERPDATAWIDTH, ...
'color',linecolor{traceloop}); hold on
end
%Assume that multiple traces are equally sized divisions of data
switch size(trace,1),
case 2
legend('Lower 50%','Higher 50%');
case 3
legend('Lowest 33%','Middle 33%','Highest 33%');
case 4
legend('Lowest 25%','2nd Lowest 25%','3rd Lowest 25%','Highest 25%');
end
if ~isempty(axlimits) && sum(isnan(axlimits))==0
if axlimits(2)>axlimits(1) && axlimits(4)>axlimits(3)
axis([axlimits(1:2) 1.1*axlimits(3:4)])
end
l1=line([axlimits(1:2)],[0 0], 'Color','k',...
'linewidth',ERPZEROWIDTH); % y=zero-line
timebar=0;
l2=line([1 1]*timebar,axlimits(3:4)*1.1,'Color','k',...
'linewidth',ERPZEROWIDTH); % x=zero-line
%y-ticks
if isempty(erp_vltg_ticks),
shrunk_ylimits=axlimits(3:4)*.8;
ystep=(shrunk_ylimits(2)-shrunk_ylimits(1))/4;
if ystep>1,
ystep=round(ystep);
else
ord=orderofmag(ystep);
ystep=round(ystep/ord)*ord;
end
if (sign(shrunk_ylimits(2))*sign(shrunk_ylimits(1)))==1, %y shrunk_ylimits don't include 0
erp_yticks=shrunk_ylimits(1):ystep:shrunk_ylimits(2);
else %y limits include 0
% erp_yticks=0:ystep:shrunk_ylimits(2); %ensures 0 is a tick point
% erp_yticks=[erp_yticks [0:-ystep:shrunk_ylimits(1)]];
erp_yticks=0:ystep:axlimits(4); %ensures 0 is a tick point
erp_yticks=[erp_yticks [0:-ystep:axlimits(3)]];
end
if erp_grid,
set(gca,'ytick',unique(erp_yticks),'ygrid','on');
else
set(gca,'ytick',unique(erp_yticks));
end
else
set(gca,'ytick',erp_vltg_ticks);
end
end
%make ERP traces on top
kids=get(gca,'children')';
for hndl_loop=plot_handle,
id=find(kids==hndl_loop);
kids(id)=[];
kids=[hndl_loop kids];
end
set(gca,'children',kids');
plot_handle=[plot_handle l1 l2];
%
%% %%%%%%%%%%%%%%%%% function phasedet() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% phasedet() - function used in erpimage.m
% Constructs a complex filter at frequency freq
%
function [ang,amp,win] = phasedet(data,frames,srate,nwin,freq)
% Typical values:
% frames = 768;
% srate = 256; % Hz
% nwin = [200:300];
% freq = 10; % Hz
data = reshape(data,[frames prod(size(data))/frames]);
% number of cycles depends on window size
% number of cycles automatically reduced if smaller window
% Note: as the number of cycles changes, the frequency shifts
% a little -- this should be fixed
win = exp(2i*pi*freq(:)*[1:length(nwin)]/srate);
win = win .* repmat(makehanning(length(nwin))',length(freq),1);
%tmp =gcf; figure; plot(real(win)); figure(tmp);
%fprintf('ANY NAN ************************* %d\n', any(any(isnan( data(nwin,:)))));
tmpdata = data(nwin,:) - repmat(mean(data(nwin,:), 1), [size(data,1) 1]);
resp = win * tmpdata;
ang = angle(resp);
amp = abs(resp);
%
%% %%%%%%%%%%%% function prctle() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
function prctl = prctle(data,pc); % return percentile of a distribution
[prows pcols] = size(pc);
if prows ~= 1 & pcols ~= 1
error('\nerpimage(): pc must be a scalar or a vector.');
end
if any(pc > 100) | any(pc < 0)
error('\nerpimage(): pc must be between 0 and 100');
end
[i,j] = size(data);
sortdata = sort(data);
if i==1 | j==1 % if data is a vector
i = max(i,j); j = 1;
if i == 1,
fprintf(' prctle() note: input data is a single scalar!\n')
y = data*ones(length(pc),1); % if data is scalar, return it
return;
end
sortdata = sortdata(:);
end
pt = [0 100*((1:i)-0.5)./i 100];
sortdata = [min(data); sortdata; max(data)];
prctl = interp1(pt,sortdata,pc);
%
%% %%%%%%%%%%%%%%%%%%%%% function nan_mean() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% nan_mean() - Take the column means of a matrix, ignoring NaN values.
% Return significance bounds if alpha (0 < alpha< <1) is given.
%
function [out, outalpha] = nan_mean(in,alpha)
NPERM = 500;
intrials = size(in,1);
inframes = size(in,2);
nans = find(isnan(in));
in(nans) = 0;
sums = sum(in);
nonnans = ones(size(in));
nonnans(nans) = 0;
nonnans = sum(nonnans);
nononnans = find(nonnans==0);
nonnans(nononnans) = 1;
out = sum(in)./nonnans;
outalpha = [];
if nargin>1
if NPERM < round(3/alpha)
NPERM = round(3/alpha);
end
fprintf('Performing a permuration test using %d permutations to determine ERP significance thresholds... ',NPERM);
permerps = zeros(NPERM,inframes);
for n=1:NPERM
signs = sign(randn(1,intrials)'-0.5);
permerps(n,:) = sum(repmat(signs,1,inframes).*in)./nonnans;
if ~rem(n,50)
fprintf('%d ',n);
end
end
fprintf('\n');
permerps = sort(abs(permerps));
alpha_bnd = floor(2*alpha*NPERM); % two-sided probability threshold
outalpha = permerps(end-alpha_bnd,:);
end
out(nononnans) = NaN;
%
%% %%%%%%%%%%%%%%%%%%%%% function nan_std() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
function out = nan_std(in)
nans = find(isnan(in));
in(nans) = 0;
nonnans = ones(size(in));
nonnans(nans) = 0;
nonnans = sum(nonnans);
nononnans = find(nonnans==0);
nonnans(nononnans) = 1;
out = sqrt((sum(in.^2)-sum(in).^2./nonnans)./(nonnans-1));
out(nononnans) = NaN;
% symmetric hanning function
function w = makehanning(n)
if ~rem(n,2)
w = 0.5*(1 - cos(2*pi*(1:n/2)'/(n+1)));
w = [w; w(end:-1:1)];
else
w = 0.5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1)));
w = [w; w(end-1:-1:1)];
end
%
%% %%%%%%%%%%%%%%%%%%%%% function compute_percentile() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
function outpercent = compute_percentile(sortvar, percent, outtrials, winsize);
ntrials = length(sortvar);
outtrials=round(outtrials);
sortvar = [ sortvar sortvar sortvar ];
winvals = [round(-winsize/2):round(winsize/2)];
outpercent = zeros(size(outtrials));
for index = 1:length(outtrials)
sortvarval = sortvar(outtrials(index)+ntrials+winvals);
sortvarval = sort(sortvarval);
outpercent(index) = sortvarval(round((length(winvals)-1)*percent)+1);
end;
%
%% %%%%%%%%%%%%%%%%%%%%% function orderofmag() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
function ord=orderofmag(val)
%function ord=orderofmag(val)
%
% Returns the order of magnitude of the value of 'val' in multiples of 10
% (e.g., 10^-1, 10^0, 10^1, 10^2, etc ...)
% used for computing erpimage trial axis tick labels as an alternative for
% plotting sorting variable
val=abs(val);
if val>=1
ord=1;
val=floor(val/10);
while val>=1,
ord=ord*10;
val=floor(val/10);
end
return;
else
ord=1/10;
val=val*10;
while val<1,
ord=ord/10;
val=val*10;
end
return;
end
%
%% %%%%%%%%%%%%%%%%%%%%% function find_crspnd_pt() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
function y_pt=find_crspnd_pt(targ,vals,outtrials)
%function id=find_crspnd_pt(targ,vals,outtrials)
%
% Inputs:
% targ - desired value of sorting variable
% vals - a vector of observed sorting variables (possibly smoothed)
% outtrials - a vector of y-axis values corresponding to trials in the
% ERPimage (this will just be 1:n_trials if there's no
% smoothing)
%
% Output:
% y_pt - y-axis value (in units of trials) corresponding to "targ".
% If "targ" matches more than one y-axis pt, the median point is
% returned. If "targ" falls between two points, y_pt is linearly
% interpolated.
%
% Note: targ and vals should be in the same units (e.g., milliseconds)
%find closest point above
abv=find(vals>=targ);
if isempty(abv),
%point lies outside of vals range, can't interpolate
y_pt=[];
return
end
abv=abv(1);
%find closest point below
blw=find(vals<=targ);
if isempty(blw),
%point lies outside of vals range, can't interpolate
y_pt=[];
return
end
blw=blw(end);
if (vals(abv)==vals(blw)),
%exact match
ids=find(vals==targ);
y_pt=median(outtrials(ids));
else
%interpolate point
%lst squares inear regression
B=regress([outtrials(abv) outtrials(blw)]',[ones(2,1) [vals(abv) vals(blw)]']);
%predict outtrial point from target value
y_pt=[1 targ]*B;
end
|
github
|
lcnhappe/happe-master
|
readegi.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/readegi.m
| 5,517 |
utf_8
|
de08c5adb26f9e5f5987d0b8a286debe
|
% readegi() - read EGI Simple Binary datafile (versions 2,3,4,5,6,7).
% Return header info, EEG data, and any event data.
% Usage:
% >> [head, TrialData, EventData, CatIndex] = readegi(filename, dataChunks, forceversion)
%
% Required Input:
% filename = EGI data filename
%
% Optional Input:
% dataChunks = vector containing desired frame numbers(for unsegmented
% datafiles) or segments (for segmented files). If this
% input is empty or is not provided then all data will be
% returned.
% forceversion = integer from 2 to 7 which overrides the EGI version read from the
% file header. This has been occasionally necessary in cases where
% the file format was incorrectly indicated in the header.
% Outputs:
% head = struct containing header info (see readegihdr() )
% TrialData = EEG channel data
% EventData = event codes
% CatIndex = segment category indices
%
% Author: Cooper Roddey, SCCN, 13 Nov 2002
%
% Note: code derived from C source code written by
% Tom Renner at EGI, Inc.
%
% See also: readegihdr()
% Copyright (C) 2002 , 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 [head, TrialData, EventData, SegmentCatIndex] = readegi(filename, dataChunks,forceversion)
if nargin <1 | nargin > 3,
help readegi;
return;
end
if nargout < 2 | nargout > 4,
error('2 to 4 output args required');
end
if ~exist('dataChunks','var')
dataChunks = [];
end
if ~isvector(dataChunks)
error('dataChunks must either be empty or a vector');
end
[fid,message] = fopen(filename,'rb','b');
if (fid < 0),
error(message);
end
% get our header structure
fprintf('Importing binary EGI data file ...\n');
if exist('forceversion')
head = readegihdr(fid,forceversion);
else
head = readegihdr(fid);
end
% do we have segmented data?
segmented = 0;
switch(head.version),
case {2,4,6}
segmented = 0;
case {3,5,7}
segmented = 1;
end
% each type of event has a dedicated "channel"
FrameVals = head.nchan + head.eventtypes;
if (segmented)
desiredSegments = dataChunks;
if isempty(desiredSegments),
desiredSegments = [1:head.segments];
end
nsegs = length(desiredSegments);
TrialData = zeros(FrameVals,head.segsamps*nsegs);
readexpected = FrameVals*head.segsamps*nsegs;
else
desiredFrames = dataChunks;
if isempty(desiredFrames),
desiredFrames = [1:head.samples];
end
nframes = length(desiredFrames);
TrialData = zeros(FrameVals,nframes);
readexpected = FrameVals*nframes;
end
% get datatype from version number
switch(head.version)
case {2,3}
datatype = 'integer*2';
case {4,5}
datatype = 'float32';
case {6,7}
datatype = 'float64';
otherwise,
error('Unknown data format');
end
% read in epoch data
readtotal = 0;
j=0;
SegmentCatIndex = [];
if (segmented),
for i=1:head.segments,
segcatind = fread(fid,1,'integer*2');
segtime = fread(fid,1,'integer*4');
[tdata, count] = ...
fread(fid,[FrameVals,head.segsamps],datatype);
% check if this segment is one of our desired ones
if ismember(i,desiredSegments)
j=j+1;
SegmentCatIndex(j) = segcatind;
SegmentStartTime(j) = segtime;
TrialData(:,[1+(j-1)*head.segsamps:j*head.segsamps]) = tdata;
readtotal = readtotal + count;
end
if (j >= nsegs), break; end;
end;
else
% read unsegmented data
% if dataChunks is empty, read all frames
if isempty(dataChunks)
[TrialData, readtotal] = fread(fid, [FrameVals,head.samples],datatype);
else % grab only the desiredFrames
% This could take a while...
for i=1:head.samples,
[tdata, count] = fread(fid, [FrameVals,1],datatype);
% check if this segment is a keeper
if ismember(i,desiredFrames),
j=j+1;
TrialData(:,j) = tdata;
readtotal = readtotal + count;
end
if (j >= nframes), break; end;
end
end
end
fclose(fid);
if ~isequal(readtotal, readexpected)
error('Number of values read not equal to the number expected.');
end
EventData = [];
if (head.eventtypes > 0),
EventData = TrialData(head.nchan+1:end,:);
TrialData = TrialData(1:head.nchan,:);
end
% convert from A/D units to microvolts
if ( head.bits ~= 0 & head.range ~= 0 )
TrialData = (head.range/(2^head.bits))*TrialData;
end
% convert event codes to char
% ---------------------------
head.eventcode = char(head.eventcode);
%--------------------------- isvector() ---------------
function retval = isvector(V)
s = size(V);
retval = ( length(s) < 3 ) & ( min(s) <= 1 );
%------------------------------------------------------
|
github
|
lcnhappe/happe-master
|
compvar.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/compvar.m
| 2,725 |
utf_8
|
7116923a815fb34f3c3c092817999c9e
|
% compvar() - project selected components and compute the variance of
% the original data they account for.
%
% Usage:
% >> [proj, variance] = compvar( data, wts_or_act, winv, components);
%
% Required Inputs:
% data - 2-D (channels, points) or 3-D (channels, frames, trials)
% data array.
% wts_or_act - {sphere weights} cell array containing the ICA sphere
% and weights matrices. May also be a 2-D (channels, points)
% or 3-D (channels, frames, trials) array of component
% activations.
% winv - inverse or pseudo-inverse of the product of the weights
% and sphere matrices returned by the ICA decompnumsition,
% i.e., inv(weights*sphere) or pinv(weights*sphere).
% components - array of component indices to back-project
%
% Outputs:
% proj - summed back-projections of the specified components
% pvaf - percent variance of the data that the selected
% components account for (range: 100% to -Inf%).
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
% 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 [ compproj, varegg ] = compvar( data, act, winv, compnums)
if nargin < 4
help compvar;
return;
end;
if iscell(act) && length(act) == 1
act = act{1};
end;
data = reshape(data, size(data,1), size(data,2)*size(data,3));
act = reshape(act , size(act ,1), size(act ,2)*size( act,3));
squaredata = sum(sum(data.^2)); % compute the grand sum-squared data
if iscell(act)
sphere = act{1};
weight = act{2};
act = (weight*sphere)*data;
end;
compproj = winv(:,compnums)*act(compnums,:)-data; % difference between data and back-projection
squarecomp = sum(sum(compproj.^2)); % the summed-square difference
varegg = 100*(1- squarecomp/squaredata); % compute pvaf of components in data
compproj = compproj+data; % restore back-projected data
return;
|
github
|
lcnhappe/happe-master
|
plotsphere.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/plotsphere.m
| 4,822 |
utf_8
|
5a1e3b5a681d7d5be1d6ad3d5a0d3f0e
|
% plotsphere() - This function is used to plot a sphere and
% project them onto specific surfaces. This may
% be used for plotting dipoles for instance.
%
% Usage:
% >> handle = plotsphere(pos, rad, 'key', 'val')
%
% Inputs:
% pos - [x y z] 3-D position of the sphere center
% rad - [real] sphere radius
%
% Optional inputs:
% 'nvert' - number of vertices. Default is 15.
% 'color' - sphere color. Default is red.
% 'proj' - [x y z] project sphere to 3-D axes. Enter NaN for not
% projecting. For instance [-40 NaN -80] will project
% the sphere on the y/z plane axis at position x=-40 and on
% the x/y plane at position z=-80.
% 'projcol' - color of projected spheres
% 'colormap' - [real] sphere colormap { default: jet }
%
% Output:
% handle - sphere graphic handle(s). If projected sphere are ploted
% handles of plotted projected spheres are also returned.
%
% Example:
% figure; plotsphere([3 2 2], 1, 'proj', [0 0 -1]);
% axis off; axis equal; lighting phong; camlight left; view([142 48])
%
% Authors: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2004
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright (C) Arnaud Delorme, 2004
%
% 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 [handles] = plotsphere(pos, rad, varargin);
if nargin < 2
help plotsphere;
return;
end;
g = finputcheck(varargin, { 'color' { 'real','string' } [] [1 0 0];
'nvert' 'integer' [2 Inf] 15;
'proj' 'real' [] [];
'colormap' 'real' [] jet(64);
'projcol' { 'real','string' } [] [0 0 0] }, 'plotsphere');
if isstr(g), error(g); end;
% decode color if necessary
% -------------------------
if ~isstr(g.color) & length(g.color) == 1
g.color = g.colormap(g.color,:);
elseif isstr(g.color)
g.color = strcol2real(g.color);
end;
if ~isstr(g.projcol) & length(g.projcol) == 1
g.projcol = g.colormap(g.projcol,:);
elseif isstr(g.projcol)
g.projcol = strcol2real(g.projcol);
end;
% ploting sphere
% ==============
[xstmp ystmp zs] = sphere(g.nvert);
l=sqrt(xstmp.*xstmp+ystmp.*ystmp+zs.*zs);
normals = reshape([xstmp./l ystmp./l zs./l],[g.nvert+1 g.nvert+1 3]);
xs = pos(1) + rad*ystmp;
ys = pos(2) + rad*xstmp;
zs = pos(3) + rad*zs;
colorarray = repmat(reshape(g.color , 1,1,3), [size(zs,1) size(zs,2) 1]);
hold on;
handles = surf(xs, ys, zs, colorarray, 'tag', 'tmpmov', 'EdgeColor','none', 'VertexNormals', normals, ...
'backfacelighting', 'lit', 'facelighting', 'phong', 'facecolor', 'interp', 'ambientstrength', 0.3);
%axis off; axis equal; lighting phong; camlight left; rotate3d
% plot projections
% ================
if ~isempty(g.proj)
colorarray = repmat(reshape(g.projcol, 1,1,3), [size(zs,1) size(zs,2) 1]);
if ~isnan(g.proj(1)), handles(end+1) = surf(g.proj(1)*ones(size(xs)), ys, zs, colorarray, ...
'edgecolor', 'none', 'facelighting', 'none'); end;
if ~isnan(g.proj(2)), handles(end+1) = surf(xs, g.proj(2)*ones(size(ys)), zs, colorarray, ...
'edgecolor', 'none', 'facelighting', 'none'); end;
if ~isnan(g.proj(3)), handles(end+1) = surf(xs, ys, g.proj(3)*ones(size(zs)), colorarray, ...
'edgecolor', 'none', 'facelighting', 'none'); end;
end;
function color = strcol2real(color)
switch color
case 'r', color = [1 0 0];
case 'g', color = [0 1 0];
case 'b', color = [0 0 1];
case 'c', color = [0 1 1];
case 'm', color = [1 0 1];
case 'y', color = [1 1 0];
case 'k', color = [0 0 0];
case 'w', color = [1 1 1];
otherwise, error('Unknown color');
end;
|
github
|
lcnhappe/happe-master
|
projtopo.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/projtopo.m
| 4,459 |
utf_8
|
dd1586daff2737f20be375d9f4e19666
|
% projtopo() - plot projections of one or more ICA components along with
% the original data in a 2-d topographic array. Returns
% the data plotted. Click on subplot to examine separately.
% Usage:
% >> [projdata] = projtopo(data,weights,[compnums],'chan_locs',...
% 'title',[limits],colors,chans);
% Inputs:
% data = single epoch of runica() input data (chans,frames)
% weights = unimxing weight matrix (runica() weights*sphere)
% [compnums] = vector of component numbers to project and plot
% 'chan_locs' = channel locations file. Example: >> topoplot example
% Else [rows cols] for rectangular grid array
% Optional:
% 'title' = (short) plot title {default|0 -> none}
% [limits] = [xmin xmax ymin ymax] (x's in msec)
% {default|0|both y's 0 -> use data limits}
% colors = file of color codes, 3 chars per line ('.' = space)
% {default|0 -> default color order (black/white first)}
% chans = vector of channel numbers to plot {default|0: all}
%
% Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 04-02-98
%
% See also: plotproj(), topoplot()
% Copyright (C) 04-02-98 from plotproj() Scott Makeig, SCCN/INC/UCSD,
% [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
% Without color arg, reads filename for PROJCOLORS from icadefs.m
% 03-15-00 added plotchans arg -sm
% 03-16-00 added axcopy() feature -sm & tpj
% 12-19-00 adjusted new icaproj() args -sm
% 12-20-00 removed argument "sphere" -sm
% 07-12-01 fixed nargin test to allow 8 args -sm & cmk
% 01-25-02 reformated help & license, added links -ad
function [projdata] = projtopo(data,weights,compnums,chan_locs,titl,limits,colors,plotchans)
icadefs % read default PROJCOLORS & MAXPLOTDATACHANS variables from icadefs.m
axsize = 0; % use plottopo() default
DEFAULT_TITLE = '';
%
% Substitute for missing arguments
%
if nargin < 7,
colors = 'white1st.col';
elseif colors==0 | isempty(colors)
colors = 'white1st.col';
end
if nargin < 6,
limits = 0;
end
if nargin < 5,
titl = 0;
end
if titl==0,
titl = DEFAULT_TITLE;
end
if nargin < 4 | nargin > 8
help projtopo
fprintf('projtopo(): requires 4-8 arguments.\n\n');
return
end
%
% Test data size
%
[chans,framestot] = size(data);
if ~exist('plotchans') | isempty(plotchans) | plotchans==0
plotchans = 1:chans; % default
end
frames = framestot; % assume one epoch
[wr,wc] = size(weights);
%
% Substitute for 0 arguments
%
if compnums == 0,
compnums = [1:wr];
end;
if size(compnums,1)>1, % handle column of compnums !
compnums = compnums';
end;
if length(compnums) > MAXPLOTDATACHANS,
fprintf(...
'projtopo(): cannot plot more than %d channels of data at once.\n',...
MAXPLOTDATACHANS);
return
end;
if max(compnums)>wr,
fprintf(...
'\n projtopo(): Component index (%d) > number of components (%d).\n', ...
max(compnums),wr);
return
end
fprintf('Reconstructing (%d chan, %d frame) data summing %d components.\n', ...
chans,frames,length(compnums));
%
% Compute projected data for single components
%
projdata = data;
fprintf('projtopo(): Projecting component(s) ');
for s=compnums, % for each component
fprintf('%d ',s);
proj = icaproj(data,weights,s); % let offsets distribute
projdata = [projdata proj]; % append projected data onto projdata
end;
fprintf('\n');
%
% Make the plot
%
% >> plottopo(data,'chan_locs',frames,limits,title,channels,axsize,colors,ydir)
plottopo(projdata,chan_locs,size(data,2),limits,titl,plotchans,axsize,colors);
% make the plottopo() plot
axcopy(gcf);
|
github
|
lcnhappe/happe-master
|
voltype.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/voltype.m
| 677 |
utf_8
|
28455ecff10043767463871fdedc4413
|
% VOLTYPE determines the type of volume conduction model
%
% Use as
% [type] = voltype(vol)
% to get a string describing the type, or
% [flag] = voltype(vol, desired)
% to get a boolean value.
%
% See also COMPUTE_LEADFIELD
% Copyright (C) 2007, Robert Oostenveld
%
function [type] = voltype(vol, desired)
if isfield(vol, 'type')
type = vol.type;
elseif isfield(vol, 'r') && prod(size(vol.r))==1
type = 'singlesphere';
elseif isfield(vol, 'r') && isfield(vol, 'o') && all(size(vol.r)==size(vol.o))
type = 'multisphere';
elseif isfield(vol, 'r')
type = 'concentric';
elseif isfield(vol, 'bnd')
type = 'bem';
end
if nargin>1
type = strcmp(type, desired);
end
|
github
|
lcnhappe/happe-master
|
strmultiline.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/strmultiline.m
| 3,151 |
utf_8
|
c1a6c98b7691f0623c7938d5cb68ae93
|
% strmultiline() - format a long string as a multi-line string.
%
% Usage:
% >> strout = strmultiline( strin, maxlen, delimiter);
%
% Inputs:
% strin - one-line or several-line string
% maxlen - maximum line length
% delimiter - enter 10 here to separate lines with character 10. Default is
% empty: lines are on different rows of the returned array.
% Outputs:
% strout - string with multiple line
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2005
%
% See also: eegfilt(), eegfiltfft(), 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 strout = strmultiline( strinori, maxlen, delimiter);
if nargin < 1
help strmultiline;
return;
end;
if nargin < 3
delimiter = [];
end;
% first format input string
% -------------------------
if ~isempty(find(strinori == 10))
tmpinds = [1 find(strinori == 10)+1 length(strinori)];
strinori = [ ' ' strinori ' ' ];
for ind = 2:length(tmpinds)
allstrs{ind} = strinori(tmpinds(ind-1)+1:tmpinds(ind)-1);
if isempty(allstrs{ind}), allstrs{ind} = ' '; end;
end;
strinori = strvcat(allstrs{:});
end;
if size(strinori,2) < maxlen, strout = strinori; return; end;
strout = [];
for index = 1:size(strinori,1) % scan lines
strin = deblank(strinori(index, :));
lines = {};
count = 1;
curline = '';
while ~isempty( strin )
[tok strin] = strtok(strin);
if length(curline) + length(tok) +1 > maxlen
lines{count} = curline;
curline = '';
count = count + 1;
end;
if isempty(curline) curline = tok;
else curline = [ curline ' ' tok ];
end;
end;
if ~isempty(curline), lines{count} = curline; end;
% type of delimiter
% -----------------
if isempty(delimiter)
if ~isempty(lines)
strouttmp = strvcat(lines{:});
else strouttmp = '';
end;
if isempty(strouttmp)
strouttmp = ones(1,maxlen)*' ';
elseif size(strouttmp, 2) < maxlen
strouttmp(:,end+1:maxlen) = ' ';
end;
strout = strvcat(strout, strouttmp);
else
strouttmp = lines{1};
for index = 2:length(lines)
strouttmp = [ strouttmp 10 lines{index} ];
end;
if index == 1, strout = strouttmp;
else strout = [ strout 10 strouttmp ];
end;
end;
end;
|
github
|
lcnhappe/happe-master
|
floatread.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/floatread.m
| 5,572 |
utf_8
|
942a49968bcce849dfc9d359ac7d2651
|
% floatread() - Read matrix from float file ssuming four byte floating point number
% Can use fseek() to read an arbitary (continguous) submatrix.
%
% Usage: >> a = floatread(filename,size,'format',offset)
%
% Inputs:
% filename - name of the file
% size - determine the number of float elements to be read and
% the dimensions of the resulting matrix. If the last element
% of 'size' is Inf, the size of the last dimension is determined
% by the file length. If size is 'square,' floatread() attempts
% to read a square 2-D matrix.
%
% Optional inputs:
% 'format' - the option FORMAT argument specifies the storage format as
% defined by fopen(). Default format ([]) is 'native'.
% offset - either the number of first floats to skip from the beginning of the
% float file, OR a cell array containing the dimensions of the original
% data matrix and a starting position vector in that data matrix.
%
% Example: % Read a [3 10] submatrix of a four-dimensional float matrix
% >> a = floatread('mydata.fdt',[3 10],'native',{[[3 10 4 5],[1,1,3,4]});
% % Note: The 'size' and 'offset' arguments must be compatible both
% % with each other and with the size and ordering of the float file.
%
% Author: Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998
%
% See also: floatwrite(), fopen()
% Copyright (C) Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998
%
% 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
% 04-26-99 modified by Sigurd Enghoff to handle variable-sized and
% multi-dimensional data.
% 07-08-99 modified by Sigurd Enghoff, FORMAT argument added.
% 02-08-00 help updated for toolbox inclusion -sm
% 02-14-00 added segment arg -sm
% 08-14-00 added size 'square' option -sm
% 01-25-02 reformated help & license, added links -ad
function A = floatread(fname,Asize,fform,offset)
if nargin<2
help floatread
return
end
if ~exist('fform') | isempty(fform)|fform==0
fform = 'native';
end
if ~exist('offset')
offset = 0;
end
fid = fopen(fname,'rb',fform);
if fid>0
if exist('offset')
if iscell(offset)
if length(offset) ~= 2
error('offset must be a positive integer or a 2-item cell array');
end
datasize = offset{1};
startpos = offset{2};
if length(datasize) ~= length(startpos)
error('offset must be a positive integer or a 2-item cell array');
end
for k=1:length(datasize)
if startpos(k) < 1 | startpos(k) > datasize(k)
error('offset must be a positive integer or a 2-item cell array');
end
end
if length(Asize)> length(datasize)
error('offset must be a positive integer or a 2-item cell array');
end
for k=1:length(Asize)-1
if startpos(k) ~= 1
error('offset must be a positive integer or a 2-item cell array');
end
end
sizedim = length(Asize);
if Asize(sizedim) + startpos(sizedim) - 1 > datasize(sizedim)
error('offset must be a positive integer or a 2-item cell array');
end
for k=1:length(Asize)-1
if Asize(k) ~= datasize(k)
error('offset must be a positive integer or a 2-item cell array');
end
end
offset = 0;
jumpfac = 1;
for k=1:length(startpos)
offset = offset + jumpfac * (startpos(k)-1);
jumpfac = jumpfac * datasize(k);
end
elseif length(offset) > 1
error('offset must be a positive integer or a 2-item cell array');
end
% perform the fseek() operation
% -----------------------------
stts = fseek(fid,4*offset,'bof');
if stts ~= 0
error('floatread(): fseek() error.');
return
end
end
% determine what 'square' means
% -----------------------------
if ischar('Asize')
if iscell(offset)
if length(datasize) ~= 2 | datasize(1) ~= datasize(2)
error('size ''square'' must refer to a square 2-D matrix');
end
Asize = [datsize(1) datasize(2)];
elseif strcmp(Asize,'square')
fseek(fid,0,'eof'); % go to end of file
bytes = ftell(fid); % get byte position
fseek(fid,0,'bof'); % rewind
bytes = bytes/4; % nfloats
froot = sqrt(bytes);
if round(froot)*round(froot) ~= bytes
error('floatread(): filelength is not square.')
else
Asize = [round(froot) round(froot)];
end
end
end
A = fread(fid,prod(Asize),'float');
else
error('floatread() fopen() error.');
return
end
% fprintf(' %d floats read\n',prod(size(A)));
% interpret last element of Asize if 'Inf'
% ----------------------------------------
if Asize(end) == Inf
Asize = Asize(1:end-1);
A = reshape(A,[Asize length(A)/prod(Asize)]);
else
A = reshape(A,Asize);
end
fclose(fid);
|
github
|
lcnhappe/happe-master
|
writeeeg.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/writeeeg.m
| 9,957 |
utf_8
|
b80ba013a795acbaa4122e842203239c
|
% writeeeg - Generating CNT/EDF/BDF/GDF-files using BIOSIG toolbox. Note
% that the CNT file format is not fully functional. See also the
% writecnt.m Matlab function (there is no fully working
% Neuroscan writing function to our knowledge).
%
% writeeeg( filename, data, srate, 'key', 'val')
%
% Inputs:
% filename - [string] filename
% data - [float] continuous or epoched data (channels x times x
% epochs)
% srate - [float] sampling rate in Hz
%
% Optional keys:
% 'TYPE' - ['GDF'|'EDF'|'BDF'|'CFWB'|'CNT'] file format for writing
% default is 'EDF'.
% 'EVENT' - event structure (BIOSIG or EEGLAB format)
% 'Label' - cell array of channel labels. Warning, this input is
% case sensitive.
% 'SPR' - [integer] sample per block, default is 1000
%
% Other optional keys:
% 'Patient.id' - [string] person identification, max 80 char
% 'Patient.Sex' - [0|1|2] 0: undefined (default), 1: male, 2: female
% 'Patient.Birthday' - Default [1951 05 13 0 0 0];
% 'Patient.Name' - [string] default 'anonymous' for privacy protection
% 'Patient.Handedness' - [0|1|2|3] 0: unknown (default), 1:left, 2:right,
% 3: equal
% 'Patient.Weight' - [integer] default 0, undefined
% 'Patient.Height' - [integer] default 0, undefined
% 'Patient.Impairment.Heart' - [integer] 0: unknown 1: NO 2: YES 3: pacemaker
% 'Patient.Impairment.Visual' - [integer] 0: unknown 1: NO 2: YES
% 3: corrected (with visual aid)
% 'Patient.Smoking' - [integer] 0: unknown 1: NO 2: YES
% 'Patient.AlcoholAbuse' - [integer] 0: unknown 1: NO 2: YES
% 'Patient.DrugAbuse' - [integer] 0: unknown 1: NO 2: YES
%
% 'Manufacturer.Name - [string] default is 'BioSig/EEGLAB'
% 'Manufacturer.Model - [string] default is 'writeeeg.m'
% 'Manufacturer.Version - [string] default is current version in CVS repository
% 'Manufacturer.SerialNumber - [string] default is '00000000'
%
% 'T0' - recording time [YYYY MM DD hh mm ss.ccc]
% 'RID' - [string] StudyID/Investigation, default is empty
% 'REC.Hospital - [string] default is empty
% 'REC.Techician - [string] default is empty
% 'REC.Equipment - [string] default is empty
% 'REC.IPaddr - [integer array] IP address of recording system. Default is
% [127,0,0,1]
%
% Author: Arnaud Delorme, SCCN, UCSD/CERCO, 2009
% Based on BIOSIG, sopen and swrite
% Copyright (C) 22 March 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 HDR = writeeeg(filename, x, srate, varargin)
% decode structures
HDR = [];
for i=1:2:length( varargin )
str = varargin{i};
val = varargin{i+1};
ind = strfind(str, '.');
if length(ind) == 2
HDR = setfield(HDR, varargin{i}(1:ind(1)-1), {1}, varargin{i}(ind(1)+1:ind(2)-1), ...
{1}, varargin{i}(ind(2)+1:end), val);
elseif length(ind) == 1
HDR = setfield(HDR, varargin{i}(1:ind-1), {1}, varargin{i}(ind+1:end), val);
else
HDR = setfield(HDR, varargin{i}, varargin{i+1});
end;
end;
HDR.FileName = filename;
HDR.FLAG.UCAL = 0;
% select file format
if ~isfield(HDR, 'EVENT'), HDR.EVENT = []; end;
if ~isfield(HDR, 'TYPE'), HDR.TYPE ='GDF'; end;
if ~isfield(HDR, 'Patient') HDR.Patient = []; end;
if ~isfield(HDR.Patient, 'ID') HDR.Patient.ID = 'P0000'; end;
if ~isfield(HDR.Patient, 'Sex') HDR.Patient.Sex = 0; end;
if ~isfield(HDR.Patient, 'Name') HDR.Patient.Name = 'Anonymous'; end;
if ~isfield(HDR.Patient, 'Handedness') HDR.Patient.Handedness = 0; end;% unknown, 1:left, 2:right, 3: equal
% description of recording device
if ~isfield(HDR,'Manufacturer') HDR.Manufacturer = []; end;
if ~isfield(HDR.Manufacturer, 'Name'), HDR.Manufacturer.Name = 'BioSig/EEGLAB'; end;
if ~isfield(HDR.Manufacturer, 'Model'), HDR.Manufacturer.Model = 'writeeeg.m'; end;
if ~isfield(HDR.Manufacturer, 'Version'), HDR.Manufacturer.Version = '$Revision'; end;
if ~isfield(HDR.Manufacturer, 'SerialNumber'), HDR.Manufacturer.SerialNumber = '00000000'; end;
% recording identification, max 80 char.
if ~isfield(HDR,'RID') HDR.RID = ''; end; %StudyID/Investigation [consecutive number];
if ~isfield(HDR,'REC') HDR.REC = []; end;
if ~isfield(HDR.REC, 'Hospital') HDR.REC.Hospital = ''; end;
if ~isfield(HDR.REC, 'Techician') HDR.REC.Techician = ''; end;
if ~isfield(HDR.REC, 'Equipment') HDR.REC.Equipment = ''; end;
if ~isfield(HDR.REC, 'IPaddr') HDR.REC.IPaddr = [127,0,0,1]; end; % IP address of recording system
if ~isfield(HDR.Patient, 'Weight') HDR.Patient.Weight = 0; end; % undefined
if ~isfield(HDR.Patient, 'Height') HDR.Patient.Height = 0; end; % undefined
if ~isfield(HDR.Patient, 'Birthday') HDR.Patient.Birthday = [1951 05 13 0 0 0]; end; % undefined
if ~isfield(HDR.Patient, 'Impairment') HDR.Patient.Impairment = []; end;
if ~isfield(HDR.Patient.Impairment, 'Heart') HDR.Patient.Impairment.Heart = 0; end; % 0: unknown 1: NO 2: YES 3: pacemaker
if ~isfield(HDR.Patient.Impairment, 'Visual') HDR.Patient.Impairment.Visual = 0; end; % 0: unknown 1: NO 2: YES 3: corrected (with visual aid)
if ~isfield(HDR.Patient,'Smoking') HDR.Patient.Smoking = 0; end; % 0: unknown 1: NO 2: YES
if ~isfield(HDR.Patient,'AlcoholAbuse') HDR.Patient.AlcoholAbuse = 0; end; % 0: unknown 1: NO 2: YES
if ~isfield(HDR.Patient,'DrugAbuse') HDR.Patient.DrugAbuse = 0; end; % 0: unknown 1: NO 2: YES
% recording time [YYYY MM DD hh mm ss.ccc]
if ~isfield(HDR,'T0') HDR.T0 = clock; end;
if ~isfield(HDR,'SPR') HDR.SPR = size(x,2); end;
if isfield(HDR,'label') HDR.Label = HDR.label; HDR = rmfield(HDR, 'label'); end;
if HDR.SPR > 1000, HDR.SPR = round(srate); end;
% channel identification, max 80 char. per channel
if ~isfield(HDR,'Label')
for i = 1:size(x,1)
chans{i} = sprintf('Chan %d', i);
end;
HDR.Label = chans;
end;
if iscell(HDR.Label), HDR.Label = char(HDR.Label{:}); end;
if ~isempty(HDR.EVENT)
if ~isfield(HDR.EVENT, 'TYP')
EVENT = [];
EVENT.CHN = zeros(length(HDR.EVENT),1);
EVENT.TYP = zeros(length(HDR.EVENT),1);
EVENT.POS = zeros(length(HDR.EVENT),1);
EVENT.DUR = ones( length(HDR.EVENT),1);
EVENT.VAL = zeros(length(HDR.EVENT),1)*NaN;
if isfield(HDR.EVENT, 'type')
for index = 1:length(HDR.EVENT)
HDR.EVENT(index).type = num2str(HDR.EVENT(index).type);
end;
alltypes = unique_bc( { HDR.EVENT.type } );
end;
for i = 1:length(HDR.EVENT)
if isfield(HDR.EVENT, 'type')
ind = str2num(HDR.EVENT(i).type);
if isempty(ind)
ind = strmatch(HDR.EVENT(i).type, alltypes, 'exact');
end;
EVENT.TYP(i) = ind;
end;
if isfield(HDR.EVENT, 'latency')
EVENT.POS(i) = HDR.EVENT(i).latency;
end;
if isfield(HDR.EVENT, 'duration')
EVENT.DUR(i) = HDR.EVENT(i).duration;
end;
end;
HDR.EVENT = EVENT;
HDR.EVENT.SampleRate = srate;
end;
end;
% reformat data
HDR.NRec = size(x,3);
x = double(x);
x = reshape(x, [size(x,1) size(x,2)*size(x,3) ]);
% recreate event channel
if isempty(HDR.EVENT)
HDR.EVENT.POS = [];
HDR.EVENT.TYP = [];
HDR.EVENT.POS = [];
HDR.EVENT.DUR = [];
HDR.EVENT.VAL = [];
HDR.EVENT.CHN = [];
elseif ~strcmpi(HDR.TYPE, 'GDF') % GDF can save events
disp('Recreating event channel');
x(end+1,:) = 0;
x(end,round(HDR.EVENT.POS')) = HDR.EVENT.TYP';
HDR.Label = char(HDR.Label, 'Status');
HDR.EVENT.POS = [];
end;
% number of channels
HDR.NS = size(x,1);
if ~isfield(HDR,'Transducer')
HDR.Transducer = cell(1,HDR.NS);
HDR.Transducer(:) = { '' };
end;
if ~isfield(HDR,'PhysDim')
HDR.PhysDim = cell(1,HDR.NS);
HDR.PhysDim(:) = { 'uV' };
end;
% Duration of one block in seconds
HDR.SampleRate = srate;
HDR.Dur = HDR.SPR/HDR.SampleRate;
% define datatypes and scaling factors
HDR.PhysMax = max(x, [], 2);
HDR.PhysMin = min(x, [], 2);
if strcmp(HDR.TYPE, 'GDF')
HDR.GDFTYP = 16*ones(1,HDR.NS); % float32
HDR.DigMax = ones(HDR.NS,1)*100; % FIXME: What are the correct values for float32?
HDR.DigMin = zeros(HDR.NS,1);
else
HDR.GDFTYP = 3*ones(1,HDR.NS); % int16
HDR.DigMin = repmat(-2^15, size(HDR.PhysMin));
HDR.DigMax = repmat(2^15-1, size(HDR.PhysMax));
end
HDR.Filter.Lowpass = zeros(1,HDR.NS)*NaN;
HDR.Filter.Highpass = zeros(1,HDR.NS)*NaN;
HDR.Filter.Notch = zeros(1,HDR.NS)*NaN;
HDR.VERSION = 2.11;
HDR = sopen(HDR,'w');
HDR = swrite(HDR, x');
HDR = sclose(HDR);
|
github
|
lcnhappe/happe-master
|
convertlocs.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/convertlocs.m
| 9,621 |
utf_8
|
9455542daae2061f96f576b6dc3d46da
|
% convertlocs() - Convert electrode locations between coordinate systems
% using the EEG.chanlocs structure.
%
% Usage: >> newchans = convertlocs( EEG, 'command');
%
% Input:
% chanlocs - An EEGLAB EEG dataset OR a EEG.chanlocs channel locations structure
% 'command' - ['cart2topo'|'sph2topo'|'sphbesa2topo'| 'sph2cart'|'topo2cart'|'sphbesa2cart'|
% 'cart2sph'|'sphbesa2sph'|'topo2sph'| 'cart2sphbesa'|'sph2sphbesa'|'topo2sphbesa'|
% 'cart2all'|'sph2all'|'sphbesa2all'|'topo2all']
% These command modes convert between four coordinate frames: 3-D Cartesian
% (cart), Matlab spherical (sph), Besa spherical (sphbesa), and 2-D polar (topo)
% 'auto' -- Here, the function finds the most complex coordinate frame
% and constrains all the others to this one. It searches first for Cartesian
% coordinates, then for spherical and finally for polar. Default is 'auto'.
%
% Optional input
% 'verbose' - ['on'|'off'] default is 'off'.
%
% Outputs:
% newchans - new EEGLAB channel locations structure
%
% Ex: CHANSTRUCT = convertlocs( CHANSTRUCT, 'cart2topo');
% % Convert Cartesian coordinates to 2-D polar (topographic).
%
% Author: Arnaud Delorme, CNL / Salk Institute, 22 Dec 2002
%
% See also: readlocs()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 22 Dec 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 chans = convertlocs(chans, command, varargin);
if nargin < 1
help convertlocs;
return;
end;
if nargin < 2
command = 'auto';
end;
if nargin == 4 && strcmpi(varargin{2}, 'on')
verbose = 1;
else
verbose = 0; % off
end;
% test if value exists for default
% --------------------------------
if strcmp(command, 'auto')
if isfield(chans, 'X') && ~isempty(chans(1).X)
command = 'cart2all';
if verbose
disp('Make all coordinate frames uniform using Cartesian coords');
end;
else
if isfield(chans, 'sph_theta') && ~isempty(chans(1).sph_theta)
command = 'sph2all';
if verbose
disp('Make all coordinate frames uniform using spherical coords');
end;
else
if isfield(chans, 'sph_theta_besa') && ~isempty(chans(1).sph_theta_besa)
command = 'sphbesa2all';
if verbose
disp('Make all coordinate frames uniform using BESA spherical coords');
end;
else
command = 'topo2all';
if verbose
disp('Make all coordinate frames uniform using polar coords');
end;
end;
end;
end;
end;
% convert
% -------
switch command
case 'topo2sph',
theta = {chans.theta};
radius = {chans.radius};
indices = find(~cellfun('isempty', theta));
[sph_phi sph_theta] = topo2sph( [ [ theta{indices} ]' [ radius{indices}]' ] );
if verbose
disp('Warning: electrodes forced to lie on a sphere for polar to 3-D conversion');
end;
for index = 1:length(indices)
chans(indices(index)).sph_theta = sph_theta(index);
chans(indices(index)).sph_phi = sph_phi (index);
end;
if isfield(chans, 'sph_radius'),
meanrad = mean([ chans(indices).sph_radius ]);
if isempty(meanrad), meanrad = 1; end;
else
meanrad = 1;
end;
sph_radius(1:length(indices)) = {meanrad};
case 'topo2sphbesa',
chans = convertlocs(chans, 'topo2sph', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2sphbesa', varargin{:}); % search for spherical coords
case 'topo2cart'
chans = convertlocs(chans, 'topo2sph', varargin{:}); % search for spherical coords
if verbose
disp('Warning: spherical coordinates automatically updated');
end;
chans = convertlocs(chans, 'sph2cart', varargin{:}); % search for spherical coords
case 'topo2all',
chans = convertlocs(chans, 'topo2sph', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2sphbesa', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2cart', varargin{:}); % search for spherical coords
case 'sph2cart',
sph_theta = {chans.sph_theta};
sph_phi = {chans.sph_phi};
indices = find(~cellfun('isempty', sph_theta));
if ~isfield(chans, 'sph_radius'), sph_radius(1:length(indices)) = {1};
else sph_radius = {chans.sph_radius};
end;
inde = find(cellfun('isempty', sph_radius));
if ~isempty(inde)
meanrad = mean( [ sph_radius{:} ]);
sph_radius(inde) = { meanrad };
end;
[x y z] = sph2cart([ sph_theta{indices} ]'/180*pi, [ sph_phi{indices} ]'/180*pi, [ sph_radius{indices} ]');
for index = 1:length(indices)
chans(indices(index)).X = x(index);
chans(indices(index)).Y = y(index);
chans(indices(index)).Z = z(index);
end;
case 'sph2topo',
if verbose
% disp('Warning: all radii constrained to one for spherical to topo transformation');
end;
sph_theta = {chans.sph_theta};
sph_phi = {chans.sph_phi};
indices = find(~cellfun('isempty', sph_theta));
[chan_num,angle,radius] = sph2topo([ ones(length(indices),1) [ sph_phi{indices} ]' [ sph_theta{indices} ]' ], 1, 2); % using method 2
for index = 1:length(indices)
chans(indices(index)).theta = angle(index);
chans(indices(index)).radius = radius(index);
if ~isfield(chans, 'sph_radius') || isempty(chans(indices(index)).sph_radius)
chans(indices(index)).sph_radius = 1;
end;
end;
case 'sph2sphbesa',
% using polar coordinates
sph_theta = {chans.sph_theta};
sph_phi = {chans.sph_phi};
indices = find(~cellfun('isempty', sph_theta));
[chan_num,angle,radius] = sph2topo([ones(length(indices),1) [ sph_phi{indices} ]' [ sph_theta{indices} ]' ], 1, 2);
[sph_theta_besa sph_phi_besa] = topo2sph([angle radius], 1, 1);
for index = 1:length(indices)
chans(indices(index)).sph_theta_besa = sph_theta_besa(index);
chans(indices(index)).sph_phi_besa = sph_phi_besa(index);
end;
case 'sph2all',
chans = convertlocs(chans, 'sph2topo', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2sphbesa', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2cart', varargin{:}); % search for spherical coords
case 'sphbesa2sph',
% using polar coordinates
sph_theta_besa = {chans.sph_theta_besa};
sph_phi_besa = {chans.sph_phi_besa};
indices = find(~cellfun('isempty', sph_theta_besa));
[chan_num,angle,radius] = sph2topo([ones(length(indices),1) [ sph_theta_besa{indices} ]' [ sph_phi_besa{indices} ]' ], 1, 1);
%for index = 1:length(chans)
% chans(indices(index)).theta = angle(index);
% chans(indices(index)).radius = radius(index);
% chans(indices(index)).labels = int2str(index);
%end;
%figure; topoplot([],chans, 'style', 'blank', 'electrodes', 'labelpoint');
[sph_phi sph_theta] = topo2sph([angle radius], 2);
for index = 1:length(indices)
chans(indices(index)).sph_theta = sph_theta(index);
chans(indices(index)).sph_phi = sph_phi (index);
end;
case 'sphbesa2topo',
chans = convertlocs(chans, 'sphbesa2sph', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2topo', varargin{:}); % search for spherical coords
case 'sphbesa2cart',
chans = convertlocs(chans, 'sphbesa2sph', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2cart', varargin{:}); % search for spherical coords
case 'sphbesa2all',
chans = convertlocs(chans, 'sphbesa2sph', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2all', varargin{:}); % search for spherical coords
case 'cart2topo',
chans = convertlocs(chans, 'cart2sph', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2topo', varargin{:}); % search for spherical coords
case 'cart2sphbesa',
chans = convertlocs(chans, 'cart2sph', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2sphbesa', varargin{:}); % search for spherical coords
case 'cart2sph',
if verbose
disp('WARNING: If XYZ center has not been optimized, optimize it using Edit > Channel Locations');
end;
X = {chans.X};
Y = {chans.Y};
Z = {chans.Z};
indices = find(~cellfun('isempty', X));
[th phi radius] = cart2sph( [ X{indices} ], [ Y{indices} ], [ Z{indices} ]);
for index = 1:length(indices)
chans(indices(index)).sph_theta = th(index)/pi*180;
chans(indices(index)).sph_phi = phi(index)/pi*180;
chans(indices(index)).sph_radius = radius(index);
end;
case 'cart2all',
chans = convertlocs(chans, 'cart2sph', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2all', varargin{:}); % search for spherical coords
end;
|
github
|
lcnhappe/happe-master
|
isscript.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/isscript.m
| 385 |
utf_8
|
5e35a8cefee4828cc65eeb2abb2502a7
|
% function checking if a specific file is a script%
function bool = isscript(fileName);
fid = fopen(fileName, 'r');
cont = true;
while cont && ~feof(fid)
l = strtok(fgetl(fid));
if ~isempty(l) && l(1) ~= '%'
if strcmpi(l, 'function')
bool = false; return;
else
bool = true; return;
end;
end;
end;
bool = true; return;
|
github
|
lcnhappe/happe-master
|
floatwrite.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/floatwrite.m
| 3,169 |
utf_8
|
8472e61c3208f7a445ec052e9cc52b4b
|
% floatwrite() - Write data matrix to float file.
%
% Usage: >> floatwrite(data,filename, 'format')
%
% Inputs:
% data - write matrix data to specified file as four-byte floating point numbers.
% filename - name of the file
% 'format' - The option FORMAT argument specifies the storage format as
% defined by fopen. Default format is 'native'.
% 'transp|normal' - save the data transposed (.dat files) or not.
%
% Author: Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998
%
% See also: floatread(), fopen()
% Copyright (C) Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998
%
% 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
% 07-08-99 FORMAT argument added -se
% 02-08-00 new version included in toolbox -sm
% 01-25-02 reformated help & license, added links -ad
function A = floatwrite(A, fname, fform, transp)
if ~exist('fform')
fform = 'native';
end
if nargin < 4
transp = 'normal';
end;
if strcmpi(transp,'normal')
if strcmpi(class(A), 'mmo')
A = changefile(A, fname);
return;
elseif strcmpi(class(A), 'memmapdata')
% check file to overwrite
% -----------------------
[fpath1 fname1 ext1] = fileparts(fname);
[fpath2 fname2 ext2] = fileparts(A.data.Filename);
if isempty(fpath1), fpath1 = pwd; end;
fname1 = fullfile(fpath1, [fname1 ext1]);
fname2 = fullfile(fpath2, [fname2 ext2]);
if ~isempty(findstr(fname1, fname2))
disp('Warning: raw data already saved in memory mapped file (no need to resave it)');
return;
end;
fid = fopen(fname,'wb',fform);
if fid == -1, error('Cannot write output file, check permission and space'); end;
if size(A,3) > 1
for ind = 1:size(A,3)
tmpdata = A(:,:,ind);
fwrite(fid,tmpdata,'float');
end;
else
blocks = [ 1:round(size(A,2)/10):size(A,2)];
if blocks(end) ~= size(A,2), blocks = [blocks size(A,2)]; end;
for ind = 1:length(blocks)-1
tmpdata = A(:, blocks(ind):blocks(ind+1));
fwrite(fid,tmpdata,'float');
end;
end;
else
fid = fopen(fname,'wb',fform);
if fid == -1, error('Cannot write output file, check permission and space'); end;
fwrite(fid,A,'float');
end;
else
% save transposed
for ind = 1:size(A,1)
fwrite(fid,A(ind,:),'float');
end;
end;
fclose(fid);
|
github
|
lcnhappe/happe-master
|
kurt.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/kurt.m
| 1,697 |
utf_8
|
649871ee149fc000974e3081ac13ff98
|
% kurt() - return kurtosis of input data distribution
%
% Usage:
% >> k=kurt(data)
%
% Algorithm:
% Calculates kurtosis or normalized 4th moment of an input data vector
% Given a matrix, returns a row vector giving the kurtosis' of the columns
% (Ref: "Numerical Recipes," p. 612)
%
% Author: Martin Mckeown, CNL / Salk Institute, La Jolla, 10/2/96
% Copyright (C) Martin Mckeown, CNL / Salk Institute, La Jolla, 7/1996
%
% 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
% 2/28/97 - made to return separate kurtosis estimates of columns -Scott Makeig
% 01-25-02 reformated help & license, added links -ad
function [k] = kurt(data)
[r,c]=size(data);
if r==1,
kdata = data'; % if a row vector, make into a column vector
r = c;
else
kdata = data;
end
%fprintf('size of kdata = [%d,%d]\n',size(kdata,1),size(kdata,2));
mn = mean(kdata); % find the column means
diff = kdata-ones(r,1)*mn; % remove the column means
dsq = diff.*diff; % square the data
k = (sum(dsq.*dsq)./std(kdata).^4)./r - 3;
|
github
|
lcnhappe/happe-master
|
jointprob.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/jointprob.m
| 4,100 |
utf_8
|
6f1300fd6123684425efaaa56c1e95c1
|
% jointprob() - rejection of odd columns of a data array using
% joint probability of the values in that column (and
% using the probability distribution of all columns).
%
% Usage:
% >> [jp rej] = jointprob( signal );
% >> [jp rej] = jointprob( signal, threshold, jp, normalize, discret);
%
%
% Inputs:
% signal - one dimensional column vector of data values, two
% dimensional column vector of values of size
% sweeps x frames or three dimensional array of size
% component x sweeps x frames. If three dimensional,
% all components are treated independently.
% threshold - Absolute threshold. If normalization is used then the
% threshold is expressed in standard deviation of the
% mean. 0 means no threshold.
% jp - pre-computed joint probability (only perform thresholding).
% Default is the empty array [].
% normalize - 0 = do not not normalize entropy. 1 = normalize entropy.
% 2 is 20% trimming (10% low and 10% high) proba. before
% normalizing. Default is 0.
% discret - discretization variable for calculation of the
% discrete probability density. Default is 1000 points.
%
% Outputs:
% jp - normalized joint probability of the single trials
% (size component x sweeps)
% rej - rejected matrix (0 and 1, size comp x sweeps)
%
% Remark:
% The exact values of joint-probability depend on the size of a time
% step and thus cannot be considered as absolute.
%
% See also: realproba()
% 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 [jp, rej] = jointprob( signal, threshold, oldjp, normalize, discret );
if nargin < 1
help jointprob;
return;
end;
if nargin < 2
threshold = 0;
end;
if nargin < 3
oldjp = [];
end;
if nargin < 4
normalize = 0;
end;
if nargin < 5
discret = 1000;
end;
if size(signal,2) == 1 % transpose if necessary
signal = signal';
end;
[nbchan pnts sweeps] = size(signal);
jp = zeros(nbchan,sweeps);
if exist('oldjp') & ~isempty( oldjp ) % speed up the computation
jp = oldjp;
else
for rc = 1:nbchan
% COMPUTE THE DENSITY FUNCTION
% ----------------------------
[ dataProba sortbox ] = realproba( signal(rc, :), discret );
% compute all entropy
% -------------------
for index=1:sweeps
datatmp = dataProba((index-1)*pnts+1:index*pnts);
jp(rc, index) = - sum( log( datatmp ) );
% - sum( datatmp .* log( datatmp ) ); would be the entropy
end;
end;
% normalize the last dimension
% ----------------------------
if normalize
tmpjp = jp;
if normalize == 2,
tmpjp = sort(jp);
tmpjp = tmpjp(round(length(tmpjp)*0.1):end-round(length(tmpjp)*0.1));
end;
try,
switch ndims( signal )
case 2, jp = (jp-mean(tmpjp)) / std(tmpjp);
case 3, jp = (jp-mean(tmpjp,2)*ones(1,size(jp,2)))./ ...
(std(tmpjp,0,2)*ones(1,size(jp,2)));
end;
catch, error('Error while normalizing'); end;
end;
end
% reject
% ------
if threshold ~= 0
if length(threshold) > 1
rej = (threshold(1) > jp) | (jp > threshold(2));
else
rej = abs(jp) > threshold;
end;
else
rej = zeros(size(jp));
end;
return;
|
github
|
lcnhappe/happe-master
|
readneurodat.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/readneurodat.m
| 3,182 |
utf_8
|
2658232f1fb962a2bad82932ad309164
|
% readneurodat() - read neuroscan location file (.dat)
%
% Usage:
% >> [ CHANLOCS labels theta theta ] = readneurodat( filename );
%
% Inputs:
% filename - file name or matlab cell array { names x_coord y_coord }
%
% Outputs:
% CHANLOCS - [structure] EEGLAB channel location data structure. See
% help readlocs()
% labels - [cell arrya] channel labels
% theta - [float array]array containing 3-D theta angle electrode
% position (in degree)
% phi - [float array]array containing 3-D phi angle electrode
% position (in degree)
%
% Author: Arnaud Delorme, CNL / Salk Institute, 28 Nov 2003
%
% See also: readlocs(), readneurolocs()
% Copyright (C) 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 [chanlocs, labels, theta, phi] = readneurodat(filename);
if nargin < 1
help readneurodat;
return;
end;
% enter file name here
% --------------------
%tmp = loadtxt('/home/ftp/pub/locfiles/neuroscan/cap128.dat');
%tmp = loadtxt('/home/arno/temp/quik128.DAT');
tmp = loadtxt(filename);
% resort electrodes
% -----------------
[tmp2 tmpind] = sort(celltomat(tmp(:,1))');
tmp = tmp(tmpind,:);
% convert to polar coordinates
% ----------------------------
%figure; plot(celltomat(tmp(:,2)), celltomat(tmp(:,3)), '.');
[phi,theta] = cart2pol(celltomat(tmp(:,end-1)), celltomat(tmp(:,end)));
theta = theta/513.1617*44;
phi = phi/pi*180;
% convert to other types of coordinates
% -------------------------------------
labels = tmp(:,end-2)';
chanlocs = struct('labels', labels, 'sph_theta_besa', mattocell(theta)', 'sph_phi_besa', mattocell(phi)');
chanlocs = convertlocs( chanlocs, 'sphbesa2all');
for index = 1:length(chanlocs)
chanlocs(index).labels = num2str(chanlocs(index).labels);
end;
theta = theta/pi*180;
fprintf('Note: .dat file contain polar 2-D coordinates. EEGLAB will use these coordinates\n');
fprintf(' to recreated 3-D coordinates.\n');
fprintf('\n');
fprintf('Warning: if the channels are clustered in the middle or oddly spaced removed\n');
fprintf(' the peripheral channels and then used the optimize head function\n');
fprintf(' in the Channel Locations GUI. It seems that sometimes the peripherals\n');
fprintf(' are throwing off the spacing.\n');
|
github
|
lcnhappe/happe-master
|
shuffle.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/shuffle.m
| 1,610 |
utf_8
|
aef9a1bc7914b99d6e312694b0522085
|
% shuffle() - shuffle a given dimension in an array
%
% Usage: >> Y = shuffle(X)
% >> [Y = shuffle(X, DIM)
%
% Inputs:
% X - input array
% DIM - dimension index (default is firt non-singleton dimention)
%
% Outputs:
% Y - shuffled array
% I - forward indices (Y = X(I) if 1D)
% J - reverse indices (X(J) = Y if 1D)
%
% Author: Arnaud Delorme, SCCN/INC/UCSD USA, Dec 2000
% Copyright (C) Arnaud Delorme, SCCN/INC/UCSD USA, Dec 2000
%
% 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 [x, i, j]=shuffle( y, dim)
if nargin < 1
help shuffle;
return;
end;
if nargin < 2
if size(y,1) ~= 1
dim = 1;
else
if size(y,2) ~= 1
dim = 2;
else
dim = 3;
end;
end;
end;
r =size(y, dim);
a = rand(1,r);
[tmp i] = sort(a);
switch dim
case 1
x = y(i,:,:,:,:);
case 2
x = y(:,i,:,:,:);
case 3
x = y(:,:,i,:,:);
case 4
x = y(:,:,:,i,:);
case 5
x = y(:,:,:,:,i);
end;
[tmp j] = sort(i); % unshuffle
return;
|
github
|
lcnhappe/happe-master
|
fastif.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/fastif.m
| 1,159 |
utf_8
|
ac76d723f5de7649f75655cbdb653c1a
|
% fastif() - fast if function.
%
% Usage:
% >> res = fastif(test, s1, s2);
%
% Input:
% test - logical test with result 0 or 1
% s1 - result if 1
% s2 - result if 0
%
% Output:
% res - s1 or s2 depending on the value of the test
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
% 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 res = fastif(s1, s2, s3);
if s1
res = s2;
else
res = s3;
end;
return;
|
github
|
lcnhappe/happe-master
|
chancenter.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/chancenter.m
| 3,703 |
utf_8
|
27a231ace0a066d6e9ad7c3da227bbb7
|
% chancenter() - recenter cartesian X,Y,Z channel coordinates
%
% Usage: >> [x y z newcenter] = chancenter(x,y,z,center);
%
% Optional inputs:
% x,y,z = 3D coordintates of the channels
% center = [X Y Z] known center different from [0 0 0]
% [] will optimize the center location according
% to the best sphere. Default is [0 0 0].
%
% Note: 4th input gui is obsolete. Use pop_chancenter instead.
%
% Authors: Arnaud Delorme, Luca Finelli & Scott Makeig SCCN/INC/UCSD,
% La Jolla, 11/1999-03/2002
%
% See also: spherror(), cart2topo()
% Copyright (C) 11/1999 Scott Makeig, SCCN/INC/UCSD, [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
% 3-16-00 improved help message -sm
% 1-25-02 put spherror subfunction inside chancenter -ad
% 1-25-02 help pops-up if no arguments -ad
% 01-25-02 reformated help & license -ad
% 02-13-02 now center fitting works, need spherror outside chancenter -lf
% 02-14-02 radii are squeezed of squeeze in to fit topoplot circle -lf
% 03-31-02 center fitting is optional
% 04-01-02 automatic squeeze calculation -ad & sm
function [ x, y, z, newcenter, optim] = chancenter( x, y, z, center, gui)
optim = 0;
if nargin<4
help chancenter
return;
end;
if nargin > 4 & gui
error('Chancenter: 4th input'' gui'' is obsolete. Use pop_chancenter instead');
else
if isempty(center)
optim = 1;
center = [0 0 0];
end;
end;
options = {'MaxFunEvals',1000*length(center)};
x = x - center(1); % center the data
y = y - center(2);
z = z - center(3);
radius = (sqrt(x.^2+y.^2+z.^2)); % assume xyz values are on a sphere
if ~isempty(radius)
wobble = std(radius); % test if xyz values are on a sphere
else wobble = [];
end;
fprintf('Radius values: %g (mean) +/- %g (std)\n',mean(radius),wobble);
newcenter = center;
if wobble/mean(radius) > 0.01 & optim==1
% Find center
% ----------------------------------------------
fprintf('Optimizing center position...\n');
kk=0;
while wobble/mean(radius) > 0.01 & kk<5
try
newcenter = fminsearch('spherror',center,options,x,y,z);
catch
newcenter = fminsearch('spherror',center,[], [], x,y,z);
end;
nx = x - newcenter(1); % re-center the data
ny = y - newcenter(2);
nz = z - newcenter(3);
nradius = (sqrt(nx.^2+ny.^2+nz.^2)); % assume xyz values are on a sphere
newobble = std(nradius);
if newobble<wobble
center=newcenter;
fprintf('Wobble too strong (%3.2g%%)! Re-centering data on (%g,%g,%g)\n',...
100*wobble/mean(radius),newcenter(1),newcenter(2),newcenter(3))
x = nx; % re-center the data
y = ny;
z = nz;
radius=nradius;
wobble=newobble;
kk=kk+1;
else
newcenter = center;
kk=5;
end
end
fprintf('Wobble (%3.2g%%) after centering data on (%g,%g,%g)\n',...
100*wobble/mean(radius),center(1),center(2), ...
center(3))
%else
% fprintf('Wobble (%3.2g%%) after centering data on (%g,%g,%g)\n',...
% 100*wobble/mean(radius),center(1),center(2),center(3))
end
|
github
|
lcnhappe/happe-master
|
eegplot2trial.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/eegplot2trial.m
| 3,493 |
utf_8
|
070a4620dcbcefa6063fde095d9ae592
|
% eegplot2trial() - convert EEGPLOT rejections into trial and electrode
% rejections compatible with EEGLAB format.
%
% Usage:
% >> [trialrej elecrej] = eegplot2trial( eegplotrej, frames, ...
% sweeps, colorin, colorout );
%
% Inputs:
% eegplotrej - EEGPLOT output (TMPREJ; see eegplot for more details)
% frames - number of points per epoch
% sweeps - number of trials
% colorin - only extract rejection of specific colors (here a n x 3
% array must be given). Default: extract all rejections.
% colorout - do not extract rejection of specified colors.
%
% Outputs:
% trialrej - array of 0 and 1 depicting rejected trials (size sweeps)
% elecrej - array of 0 and 1 depicting rejected electrodes in
% all trials (size nbelectrodes x sweeps )
%
% Note: if colorin is used, colorout is ignored
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eegplot(), eeg_multieegplot(), eegplot2event(), 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 [tmpsig, tmprejelec] = eegplot2trial( TMPREJINIT, pnts, sweeps, color, colorout );
if nargin < 3
help eegplot2trial;
return;
end;
% only take into account specific colors
% --------------------------------------
TMPREJINIT(:,3:5) = round(TMPREJINIT(:,3:5)*100)/100;
TMPREJ = [];
if exist('color') == 1 && ~isempty(color)
color = round(color*100)/100;
for index = 1:size(color,1)
tmpcol1 = TMPREJINIT(:,3) + 255*TMPREJINIT(:,4) + 255*255*TMPREJINIT(:,5);
tmpcol2 = color(index,1)+255*color(index,2)+255*255*color(index,3);
I = find( tmpcol1 == tmpcol2);
%if isempty(I)
% fprintf('Warning: color [%d %d %d] not found\n', ...
% color(index,1), color(index,2), color(index,3));
%end;
TMPREJ = [ TMPREJ; TMPREJINIT(I,:)];
end;
else
TMPREJ = TMPREJINIT;
% remove other specific colors
% ----------------------------
if exist('colorout') == 1
colorout = round(colorout*100)/100;
for index = 1:size(colorout,1)
tmpcol1 = TMPREJ(:,3) + 255*TMPREJ(:,4) + 255*255*TMPREJ(:,5);
tmpcol2 = colorout(index,1)+255*colorout(index,2)+255*255*colorout(index,3);
I = find( tmpcol1 == tmpcol2);
TMPREJ(I,:) = [];
end;
end;
end;
% perform the conversion
% ----------------------
tmprejelec = [];
tmpsig = zeros(1,sweeps);
if ~isempty(TMPREJ)
nbchan = size(TMPREJ,2)-5;
TMPREJ = sortrows(TMPREJ,1);
TMPREJ(find(TMPREJ(:,1) == 1),1) = 0;
tmpsig = TMPREJ(:,1)''/pnts+1;
I = find(tmpsig == round(tmpsig));
tmp = tmpsig(I);
tmpsig = zeros(1,sweeps);
tmpsig(tmp) = 1;
I = find(tmpsig);
tmprejelec = zeros( nbchan, sweeps);
tmprejelec(:,I) = TMPREJ(:,6:nbchan+5)';
end;
return;
|
github
|
lcnhappe/happe-master
|
reref.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/reref.m
| 9,588 |
utf_8
|
d1a7ce88ac95a65fc25d21b6f9b28713
|
% reref() - convert common reference EEG data to some other common reference
% or to average reference
% Usage:
% >> Dataout = reref(data); % convert all channels to average reference
% >> [Dataout Chanlocs] = reref(data, refchan, 'key', 'val');
% % convert data to new reference with options
% Inputs:
% data - 2-D or 3-D data matrix (chans,frames*epochs)
% refchan - reference channel number(s). There are three possibilities:
% 1) [] - compute average reference
% 2) [X]: re-reference to channel X
% 2) [X Y Z ...]: re-reference to the average of channel X Y Z ...
%
% Optional inputs:
% 'exclude' - [integer array] channel indices to exclude from re-referencing
% (e.g., event marker channels, etc.)
% 'keepref' - ['on'|'off'] keep reference channel in output (only usable
% when there are several references).
% 'elocs' - Current data electrode location structure (e.g., EEG.chanlocs).
% 'refloc' - Reference channel location single element structure or cell array
% {'label' theta radius} containing the name and polar coordinates
% of the current channel. Including this entry means that
% this channel will be included (reconstructed) in the
% output.
%
% Outputs:
% Dataout - Input data converted to the new reference
% Chanlocs - Updated channel locations structure
%
% Notes: 1) The average reference calculation implements two methods
% (see www.egi.com/Technotes/AverageReference.pdf)
% V'i = (Vi-Vref) - sum(Vi-Vref)/number_of_electrodes
%
% Authors: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2009-
% previous version: Arnaud Delorme & Scott Makeig, 1999-2002
% Deprecated inputs:
% These inputs are still accepted but not processed. The function returns
% accurate results irrespective of the entry of these options.
% 'refstate ' - ['common'|'averef'|[indices]] Current reference condition,
% ('averef') = average reference; ('common' or 0) = common
% reference. [indices] designate the current reference channel
% or channels if present in the data {default: 'common'}
% 'method' - ['standard'|'withref'] Do not ('standard') or do ('withref')
% include reference channel data in output {def: 'standard'}.
% Note: Option 'withref' not possible when multiple ref channel
% indices are given as argument to 'refstate' (below).
%
% ICA inputs:
% These inputs are still accepted but not the ICA conversion is now
% performed from within pop_reref()
% 'icaweights' - ICA weight matrix. Note: If this is ICA weights*sphere,
% then the 'icasphere' input below should be [] or identity.
% 'icasphere' - ICA sphere matrix (if any)
% 'icachansind' - Indices of the channels used in ICA decomposition
%
% Outputs:
% Wout - ICA weight matrix (former icaweights*icasphere)
% converted to new data reference
% Sout - ICA sphere matrix converted to an identity matrix
% ICAinds - New indices of channels used in ICA decomposition
% meandata - (1,dataframes) means removed from each data point
%
% 2) In conversion of the weight matrix to a new reference
% where WS = Wts*Sph and ica_act = WS*data, then
% data = inv(WS)*ica_act;
% If R*data are the re-referenced data,
% R*data= R*inv(WS)*ica_act;
% And Wout = inv(R*inv(WS));
% Now, Sout = eye(length(ICAinds));
% The re-referenced ICA component maps are now the
% columns of inv(Wout), and the icasphere matrix, Sout,
% is an identity matrix. Note: inv() -> pinv() when
% PCA dimension reduction is used during ICA decomposition.
% Copyright (C) 1999 Scott Makeig, SCCN/INC/UCSD, [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
% 12/16/99 Corrected denomiator on the suggestion of Ian Nimmo-Smith, Cambridge UK
% 01-25-02 reformated help & license -ad
function [data, Elocs, morechans, W, S, icachansind, meandata] = reref(data, ref, varargin)
if nargin<1
help reref
return
end
if nargin < 2
ref = [];
end;
% check inputs
% ------------
g = finputcheck(varargin, { 'icaweight' 'real' [] [];
'icaweights' 'real' [] [];
'icasphere' 'real' [] [];
'icachansind' 'integer' [] [];
'method' 'string' { 'standard','withref' } 'standard';
'refstate' { 'string','integer' } { { 'common','averef' } [1 size(data,1)] } 'common'; % ot used but kept for backward compatib.
'exclude' 'integer' [1 size(data,1)] [];
'refloc' { 'cell','struct' } { [] [] } {};
'keepref' 'string' {'on','off' } 'off';
'elocs' {'integer','struct'} [] [] });
if isstr(g), error(g); end;
if ~isempty(g.icaweight)
g.icaweights = g.icaweight;
end;
if ~isempty(g.icaweights)
if isempty(g.icachansind),
g.icachansind = [1:size(g.icaweights,2)];
disp('Warning: reref() output has changed slightly since EEGLAB 5.02');
disp(' the 4th output argument is the indices of channels used for ICA instead');
disp(' of the mean reference value (which is now output argument 5)');
end;
end;
if ~isempty(ref)
if ref > size(data,1)
error('reference channel index out of range');
end;
end;
[dim1 dim2 dim3] = size(data);
data = reshape(data, dim1, dim2*dim3);
% single reference not present in the data
% add it as blank data channel at the end
% ----------------------------------------
if ~isempty(g.refloc) == 1
if ~isempty(g.elocs)
if iscell(g.refloc)
data(end+1,:) = 0;
g.elocs(end+1).labels = g.refloc{1};
g.elocs(end ).theta = g.refloc{2};
g.elocs(end ).radius = g.refloc{3};
else
data(end+length(g.refloc),:) = 0;
for iLocs = 1:length(g.refloc)
g.elocs(end+1).labels = g.refloc(iLocs).labels;
fieldloc = fieldnames(g.elocs);
for ind = 1:length(fieldloc)
g.elocs(end) = setfield(g.elocs(end), fieldloc{ind}, getfield(g.refloc(iLocs), fieldloc{ind}));
end;
end;
end;
end;
[dim1 dim2 dim3] = size(data);
end;
% exclude some channels
% ---------------------
chansin = setdiff_bc([1:dim1], g.exclude);
nchansin = length(chansin);
% return mean data
% ----------------
if nargout > 4
meandata = sum(data(chansin,2))/nchansin;
end;
% generate rereferencing matrix
% -----------------------------
if 0 % alternate code - should work exactly the same
if isempty(ref)
ref=chansin; % average reference
end % if
chansout=chansin;
data(chansout,:)=data(chansout,:)-ones(nchansin,1)*mean(data(ref,:),1);
else
if ~isempty(ref) % not average reference
refmatrix = eye(nchansin); % begin with identity matrix
tmpref = ref;
for index = length(g.exclude):-1:1
tmpref(find(g.exclude(index) < tmpref)) = tmpref(find(g.exclude(index) < tmpref))-1;
end;
for index = 1:length(tmpref)
refmatrix(:,tmpref(index)) = refmatrix(:,tmpref(index))-1/length(tmpref);
end;
else % compute average reference
refmatrix = eye(nchansin)-ones(nchansin)*1/nchansin;
end;
chansout = chansin;
data(chansout,:) = refmatrix*data(chansin,:);
end;
% change reference in elocs structure
% -----------------------------------
if ~isempty(g.elocs)
if isempty(ref)
for ind = chansin
g.elocs(ind).ref = 'average';
end;
else
reftxt = { g.elocs(ref).labels };
if length(reftxt) == 1, reftxt = reftxt{1};
else
reftxt = cellfun(@(x)([x ' ']), reftxt, 'uniformoutput', false);
reftxt = [ reftxt{:} ];
end;
for ind = chansin
g.elocs(ind).ref = reftxt;
end;
end;
end;
% remove reference
% ----------------
morechans = [];
if strcmpi(g.keepref, 'off')
data(ref,:) = [];
if ~isempty(g.elocs)
morechans = g.elocs(ref);
g.elocs(ref) = [];
end;
end;
data = reshape(data, size(data,1), dim2, dim3);
% treat optional ica parameters
% -----------------------------
W = []; S = []; icachansind = [];
if ~isempty(g.icaweights)
disp('Warning: This function does not process ICA array anymore, use the pop_reref function instead');
end;
Elocs = g.elocs;
|
github
|
lcnhappe/happe-master
|
plotdata.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/plotdata.m
| 20,127 |
utf_8
|
dc7d1faf9633b845ff3de9c423067fc0
|
% plotdata() - plot concatenated multichannel data epochs in two-column format
%
% Usage: >> plotdata(data)
% >> plotdata(data,frames)
% >> plotdata(data,frames,limits,title,channames,colors,rtitle,ydir)
%
% Necessary input:
% data = data consisting of consecutive epochs of (chans,frames)
%
% Optional inputs:
% frames = time frames/points per epoch {default: 0 -> data length}
% [limits] = [xmin xmax ymin ymax] (x's in ms)
% {default|0 (or both y's 0) -> use data limits)
% 'title' = plot title {default|0 -> none}
% 'channames' = channel location file or structure (see readlocs())
% {default|0 -> channel numbers}
% 'colors' = file of color codes, 3 chars per line
% ( '.' = space) {default|0 -> default color order}
% 'rtitle' = right-side plot title {default|0 -> none}
% ydir = y-axis polarity (1 -> pos-up; -1 -> neg-up)
% {default|0 -> set from default YDIR in 'icadefs.m'}
%
% Authors: Scott Makeig, Arnaud Delorme, Tzyy-Ping Jung,
% SCCN/INC/UCSD, La Jolla, 05-01-96
%
% See also: plottopo(), timtopo(), envtopo(), headplot(), compmap(), eegmovie()
% Copyright (C) 05-01-96 Scott Makeig, Arnaud Delorme & Tzyy-Ping Jung,
% SCCN/INC/UCSD, [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
% 5-1-96 from showerps.m -sm from showerp.m -tpj
% 5-3-96 added default channel numbering, frames & title -sm
% 5-17-96 added nargin tests below -sm
% 5-21-96 added right titles -sm
% 6-29-96 removed Postscript file query -sm
% 7-22-96 restored lines to fill printed page with figure -sm
% 7-29-96 added [channumbers] option for channames argument. -sm
% changed "channels" argument to "channames" in help statement above -sm
% 1-6-97 debugged min/max time and +/- printing -tpj & sm
% 3-3-97 restored previous Default axis parameters at end -sm
% 4-2-97 debugged 32-epoch plotting -sm
% 5-10-97 added no-args check -sm
% 5-20-97 read icadefs.m for MAXPLOTDATACHANS and MAXPLOTDATAEPOCHS -sm
% 6-23-97 use returns instead of errorcodes -sm
% 10-31-97 use normalized PaperUnits for US/A4 compatibility,
% fixed [xy]{min,max} printing, added clf, adding Clipping off,
% fixed scaling, added limits tests -sm & ch
% 11-19-97 removed an 'orient' command that caused problems printing -sm
% 07-15-98 added 'ydir' arg, made pos-up the default -sm
% 07-24-98 fixed 'ydir' arg, and pos-up default -sm
% 01-02-99 added warning about frames not dividing data length -sm
% 02-19-99 debugged axis limits -sm
% 11-21-01 add compatibility to load .loc files for channames -ad
% 01-25-02 reformated help & license, added links -ad
% 02-16-02 added axcopy -ad & sm
% 03-15-02 added readlocs and the use of eloc input structure -ad
% 03-15-02 added smart axcopy -ad
function plotdata(data,frames,limits,plottitle,channels,colors,righttitle,ydr)
if nargin < 1,
help plotdata
return
end
%
% Set defaults
%
FONTSIZE = 12; % font size to use for labels
TICKFONTSIZE=12; % font size to use for axis labels
icadefs; % read MAXPLOTDATACHANS constant from icadefs.m
% read YDIR
if ~exist('YDIR')
fprintf('YDIR not read from ''icadefs.m'' - plotting positive-up.\n');
YDIR = 1;
end
DEFAULT_SIGN = YDIR; % default to plotting positive-up (1) or negative-up (-1)
% Now, read sign from YDIR in icadefs.m
ISSPEC = 0; % default - 0 = not spectral data, 1 = pos-only spectra
axcolor= get(0,'DefaultAxesXcolor'); % find what the default x-axis color is
plotfile = 'plotdata.ps';
ls_plotfile = 'ls -l plotdata.ps';
%
%%%%%%%%%%%%%%%%%%%%%%%%%% Substitute defaults for missing parameters %%%%%
%
SIGN = DEFAULT_SIGN; % set default ydir from YDIR in icadefs.m
if nargin < 8
ydr = [];
end
if ~isempty(ydr)& ydr ~=0 % override default from commandline
if ydr == 1
SIGN = 1;
else
SIGN = -1;
end
end
if nargin < 7,
righttitle = 0;
end;
if nargin < 6
colors = 0;
end
if nargin < 5
channels = [1:size(data,1)]; % default channames = 1:chans
end
if nargin < 4
plottitle = 0; %CJH
end
limitset = 0;
if nargin < 3,
limits = 0;
elseif length(limits)>1
limitset = 1;
end
if nargin < 2,
frames = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%% Test parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
[chans,framestotal]=size(data); % data size
if frames <=0,
frames = framestotal; % default
datasets=1;
elseif frames==1,
fprintf('plotdata: cannot plot less than 2 frames per trace.\n');
return
datasets=1;
else
datasets = fix(framestotal/frames); % number of traces to overplot
if datasets*frames < framestotal
fprintf('\nWARNING: %d points at end of data will not be plotted.\n',...
framestotal-datasets*frames);
end
end;
if chans>MAXPLOTDATACHANS,
fprintf('plotdata: not set up to plot more than %d channels.\n',...
MAXPLOTDATACHANS);
return
end;
if datasets>MAXPLOTDATAEPOCHS
fprintf('plotdata: not set up to plot more than %d epochs.\n',...
MAXPLOTDATAEPOCHS);
return
end;
if datasets<1
fprintf('plotdata: cannot plot less than 1 epoch!\n');
return
end;
%
%%%%%%%%%%%%% Extend the size of the plotting area in the window %%%%%%%%%%%%
%
curfig = gcf;
h=figure(curfig);
set(h,'Color',BACKCOLOR); % set the background color
set(h,'PaperUnits','normalized'); % use percentages to avoid US/A4 difference
set(h,'PaperPosition',[0.0235308 0.0272775 0.894169 0.909249]); % equivalent
% orient portrait
axis('normal');
%
%%%%%%%%%%%%%%%%%%%% Read the channel names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isnumeric(channels) & channels(1)==0,
channels = [1:size(data,1)];
end;
if isnumeric(channels),
channames = num2str(channels(:)); %%CJH
else
[tmp channames] = readlocs(channels);
channames = strvcat(channames{:});
end;
% chid = fopen(channels,'r');
% if chid <3,
% fprintf('plotdata(): cannot open file %s.\n',channels);
% return
% end;
% if isempty( findstr( lower(channels), '.loc') )
% channames = fscanf(chid,'%s',[4 Inf]);
% channames = channames';
% else
% channames = fscanf(chid,'%d %f %f %s',[7 128]);
% channames = char(channames(4:7,:)');
% end;
% ii = find(channames == '.');
% channames(ii) = ' ';
%channames = channames';
% [r c] = size(channames);
%for i=1:r
% for j=1:c
% if channames(i,j)=='.',
% channames(i,j)=' ';
% end;
% end;
%end;
% end; % setting channames
%
%%%%%%%%%%%%%%%%%%%%%%%%% Read the color names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if colors ~=0,
if ~isstr(colors)
fprintf('plotdata(): color file name must be a string.\n');
return
end
cid = fopen(colors,'r');
% fprintf('cid = %d\n',cid);
if cid <3,
fprintf('plotdata: cannot open file %s.\n',colors);
return
end;
colors = fscanf(cid,'%s',[3 Inf]);
colors = colors';
[r c] = size(colors);
for i=1:r
for j=1:c
if colors(i,j)=='.',
colors(i,j)=' ';
end;
end;
end;
else % use default color order (no yellow!)
colors =['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 ';'r ';'b ';'g ';'c ';'m '];
colors = [colors; colors]; % make > 64 available
end;
for c=1:size(colors,1) % make white traces black unless axis color is white
if colors(c,1)=='w' & axcolor~=[1 1 1]
colors(c,1)='k';
end
end
%
%%%%%%%%%%%%%%%%%%%%%%% Read and adjust limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if limits==0, % == 0 or [0 0 0 0]
xmin=0;
xmax=frames-1;
ymin=min(min(data));
ymax=max(max(data));
yrange = ymax-ymin;
ymin = ymin - 0.00*yrange;
ymax = ymax + 0.00*yrange;
else
if length(limits)~=4,
fprintf( ...
'plotdata: limits should be 0 or an array [xmin xmax ymin ymax].\n');
return
end;
xmin = limits(1);
xmax = limits(2);
ymin = limits(3);
ymax = limits(4);
end;
if xmax == 0 & xmin == 0,
x = (0:1:frames-1);
xmin = 0;
xmax = frames-1;
else
dx = (xmax-xmin)/(frames-1);
x=xmin*ones(1,frames)+dx*(0:frames-1); % compute x-values
end;
if xmax<=xmin,
fprintf('plotdata() - xmax must be > xmin.\n')
return
end
if ymax == 0 & ymin == 0,
ymax=double(max(max(data)));
ymin=double(min(min(data)));
yrange = ymax-ymin;
% ymin = ymin - 0.00*yrange;
% ymax = ymax + 0.00*yrange;
end
if ymax<=ymin,
fprintf('plotdata() - ymax must be > ymin.\n')
return
end
xlabel = 'Time (ms)';
if ymin >= 0 & xmin >= 0, % For all-positive (spectral) data
ISSPEC = 1;
SIGN = 1;
fprintf('\nPlotting positive up. Assuming data are spectra.\n');
xlabel = 'Freq (Hz)';
ymin = 0; % plot positive-up
end;
%
%%%%%%%%%%%%%%%%%%%%%%%% Set up plotting environment %%%%%%%%%%%%%%%%%%%%%%%%%
%
h = gcf;
% set(h,'YLim',[ymin ymax]); % set default plotting parameters
% set(h,'XLim',[xmin xmax]);
% set(h,'FontSize',18);
% set(h,'DefaultLineLineWidth',1); % for thinner postscript lines
%
%%%%%%%%%%%%%%%%%%%%%%%%%% Print plot info %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
clf; % clear the current figure
% print plottitle over (left) sbplot 1
if plottitle==0,
plottitle = '';
end
if righttitle==0,
righttitle = '';
end
if ~isempty(righttitle)
sbplot(ceil(chans/2),2,2), h=gca;%title([righttitle], 'FontSize',FONTSIZE); % title plot and
set(h,'FontSize',FONTSIZE); % choose font size
set(h,'YLim',[ymin ymax]); % set default plotting parameters
set(h,'XLim',[xmin xmax]);
end;
msg = ['\nPlotting %d traces of %d frames with colors: '];
for c=1:datasets
msg = [msg colors(mod(c-1,length(colors))+1,:)];
end
msg = [msg ' -> \n']; % print starting info on screen . . .
fprintf(...
'\n limits: [xmin,xmax,ymin,ymax] = [%4.1f %4.1f %4.2f %4.2f]\n',...
xmin,xmax,ymin,ymax);
fprintf(msg,datasets,frames);
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Plot traces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
xdiff=xmax-xmin;
ydiff=ymax-ymin;
for P=0:datasets-1, % for each data epoch
fprintf('\ntrace %d: ',P+1);
for I=1:chans, % for each data channel
index=(2*((rem(I-1,ceil(chans/2))+1)))-1+floor(2*(I-1)/chans);
% = 1 3 5 .. 2 4 6 ..
% plot down left side of page first
h=sbplot(ceil(chans/2),2,index); h=gca;
pos = get(h,'position');
set(h,'position',[pos(1)-pos(4)*0.5 pos(2), pos(3),pos(4)*2]); % increase sbplot-height
hold on;
set(h,'YLim',[ymin ymax]); % set default plotting parameters
set(h,'XLim',[xmin xmax]);
axislcolor = get(gca,'Xcolor'); %%CJH
%
%%%%%%%%%%%%%%%%%%%%% Plot two-sided time-series data %%%%%%%%%%%%%%%%%%%
%
if ~ISSPEC % not spectral data
ymin = double(ymin);
ymax = double(ymax);
if ymin == ymax, ymin = ymin-1; ymax = ymax+1; end;
plot(x,SIGN*data(I,1+P*frames:1+P*frames+frames-1),colors(mod(P,length(colors))+1));
if SIGN > 0
axis([xmin xmax ymin ymax]); % set axis bounds (pos up)
else
axis([xmin xmax -1*ymax -1*ymin]); % set axis bounds (neg up)
end
if P==datasets-1, % on last traces
if I==floor((chans+1)/2), % draw +/0 on lowest left plot
signx = double(xmin-0.04*xdiff);
if SIGN > 0 % pos up
axis('off');hl=text(signx,ymin,num2str(ymin,3)); % text ymin
axis('off');hi=text(signx,ymax,['+' num2str(ymax,3)]); % text +ymax
else % neg up
axis('off');hl=text(signx,-1*ymin,num2str(ymin,3)); % text ymin
axis('off');hi=text(signx,-1*ymax,['+' num2str(ymax,3)]); % text +ymax
end
set(hl,'FontSize',TICKFONTSIZE); % choose font size
set(hl,'HorizontalAlignment','right','Clipping','off');
set(hi,'FontSize',TICKFONTSIZE); % choose font size
set(hi,'HorizontalAlignment','right','Clipping','off');
end
if I==chans & limitset, % draw timescale on lowest right plot
ytick = double(-ymax-0.25*ydiff);
tick = [int2str(xmin)]; h=text(xmin,ytick,tick); % min time
set(h,'FontSize',TICKFONTSIZE); % choose font size
set(h,'HorizontalAlignment','center',...
'Clipping','off'); % center text
tick = [xlabel]; h=text(xmin+xdiff/2,ytick,tick); % xlabel
set(h,'FontSize',TICKFONTSIZE); % choose font size
set(h,'HorizontalAlignment','center',...
'Clipping','off'); % center text
tick = [int2str(xmax)]; h=text(xmax,ytick,tick); % max time
set(h,'FontSize',TICKFONTSIZE); % choose font size
set(h,'HorizontalAlignment','center',...
'Clipping','off'); % center text
end;
end;
%
%%%%%%%%%%%%%%%%%%%%% Plot spectral data positive-up [0,ymax] %%%%%%%%%%%%%%%%%%%%%%%%
%
else % ISSPEC
ymin=0;
plot(x,SIGN*data(I,1+P*frames:1+P*frames+frames-1),colors(mod(P,length(colors))+1));
ymaxm = ymax;
% ymin = 0.01;
% ymaxm = 10.^ceil(log(ymax)/log(10.));
% if ymaxm/2. > ymax,
% ymaxm = ymaxm/2.;
% end;
axis([xmin xmax ymin ymaxm]); % set axis values
if P==datasets-1, % on last trace
if I==floor((chans+1)/2), % draw +/0 on lowest left plot
signx = xmin-0.04*xdiff;
axis('off');h=text(signx,ymax,['+' num2str(ymax,3)]);
set(h,'FontSize',TICKFONTSIZE);
set(h,'HorizontalAlignment','right','Clipping','off');
axis('off');h=text(signx,0,'0');
set(h,'FontSize',TICKFONTSIZE);
set(h,'HorizontalAlignment','right','Clipping','off');
end;
if I==chans, % draw freq scale on lowest right plot
ytick = -0.25*ymax;
tick = [num2str(round(10*xmin)/10) ]; h=text(xmin,ytick,tick);
set(h,'FontSize',TICKFONTSIZE);
set(h,'HorizontalAlignment','center','Clipping','off');
tick = [xlabel]; h=text(xmin+xdiff/2,ytick,tick);
set(h,'FontSize',TICKFONTSIZE);
set(h,'HorizontalAlignment','center','Clipping','off');
tick = [num2str(round(10*xmax)/10) ]; h=text(xmax,ytick,tick);
set(h,'FontSize',TICKFONTSIZE);
set(h,'HorizontalAlignment','center','Clipping','off');
end; % if last chan
end % if last data
end; % if ~ISSPEC
%%%%%%%%%%%%%%%%%%%%%%% Print channel names and lines %%%%%%%%%%%%%%%%%%%%%%%%%%
if P==datasets-1
if ~ISSPEC
axis('off');
plot([0 0],[ymin ymax],'color',axislcolor); % draw vert %%CJH
% axis at time 0
else % ISSPEC
axis('off');plot([xmin xmin],[0 ymax],'color',axislcolor);
end
% secondx = 200; % draw second vert axis
% axis('off');plot([secondx secondx],[ymin ymax],'color',axislcolor);
axis('off');
plot([xmin xmax],[0 0],'color',axislcolor); % draw horizontal axis
if ~isempty(channels), % print channames
if ~ISSPEC
if ymin <= 0 & ymax >= 0,
yht = 0;
else
yht = nan_mean(SIGN*data(I,1+P*frames:1+P*frames+frames-1));
end
axis('off'),h=text(xmin-0.04*xdiff,double(yht),[channames(I,:)]);
set(h,'HorizontalAlignment','right'); % print before traces
set(h,'FontSize',FONTSIZE); % choose font size
% axis('off'),h=text(xmax+0.10*xdiff,yht,[channames(I,:)]);
% set(h,'HorizontalAlignment','left'); % print after traces
else % ISSPEC
axis('off'),h=text(xmin-0.04*xdiff,ymax/2,[channames(I,:)]);
set(h,'HorizontalAlignment','right'); % print before traces
set(h,'FontSize',FONTSIZE); % choose font size
% axis('off'),h=text(xmax+0.10*xdiff,ymax/2,[channames(I,:)]);
% set(h,'HorizontalAlignment','left'); % print after traces
end;
end;
end;
fprintf(' %d',I);
end; % subplot
end; % dataset
fprintf('\n');
%
%%%%%%%%%%%%%%%%%% Make printed figure fill page %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
curfig = gcf;
h=figure(curfig);
% set(h,'PaperPosition',[0.2 0.3 7.6 10]); % stretch out the plot on the page
%
%%%%%%%%%%%%%%%%%% Restore plot environment %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% set(h,'DefaultAxesYLim',aylim); % restore previous plotting parameters
% set(h,'DefaultAxesXLim',axlim);
% set(h,'DefaultAxesFontSize',axfont);
%%%%%%%%%%%%%%%%%% Add axcopy %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if plottitle
h = textsc(plottitle, 'title');
set(h, 'fontsize', FONTSIZE);
end;
axcopy(gcf, 'axis on');
if 0, % START DETOUR XXXXXXXXXXXXX
%
%%%%%%%%%%%%%%%%%% Save plot to disk if asked %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if plotfile ~= '', %
n=0; y=1;
answer = input('plotdata: Save plot as Postscript file? (y/n) ');
if answer==1,
fprintf('\nSaving figure as %s ... ',plotfile);
curfig = gcf;
h=figure(curfig);
% set(h,'PaperPosition',[0.2 0.3 7.6 10]);
% stretch out the plot on the page
eval (['print -dpsc ' plotfile]);
fprintf('saved. Move or remove file!\n');
unix(ls_plotfile);
end
end
end % END DETOUR XXXXXXXXXXXXX
function out = nan_mean(in)
nans = find(isnan(in));
in(nans) = 0;
sums = sum(in);
nonnans = ones(size(in));
nonnans(nans) = 0;
nonnans = sum(nonnans);
nononnans = find(nonnans==0);
nonnans(nononnans) = 1;
out = sum(in)./nonnans;
out(nononnans) = NaN;
|
github
|
lcnhappe/happe-master
|
snapread.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/snapread.m
| 5,372 |
utf_8
|
acab56fb5681e5c05feaebf418734cad
|
% snapread() - Read data in Snap-Master Standard Binary Data File Format
% Reads Snap-Master header and data matrix (nchans,nframes).
% Ref: Users Guide, Snap-Master for Windows (1997) p. 4-19
% Usage:
% >> data = snapread(filename); % read .SMA file data
% >> [data,params,events,head] = snapread(filename,seekframes);
% % save parameters, event list
% Inputs:
% filename = string containing whole filename of .SMA file to read
% seekframes = skip this many initial time points {default 0}
% Output:
% data = data matrix, size(nchans,nframes)
% params = [nchannels, nframes, srate]
% events = vector of event frames (lo->hi transitions on event channel);
% See source to set EVENT_CHANNEL and EVENT_THRESH.
% head = complete char file header
%
% Authors: Scott Makeig & Tzyy-Ping Jung, SCCN/INC/UCSD, La Jolla, January 31, 2000
% Copyright (C) January 31, 2000 from plotdata() Scott Makeig & Tzyy-Ping Jung, SCCN/INC/UCSD,
% [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
% Scott Makeig & Tzyy-Ping Jung, CNL / Salk Institute / January 31, 2000
% 7-13-00 fixed fprintf count print bug -sm
% 7-13-00 added arg seekframes -sm & ss
% 7-13-00 added test for file length -sm & ss
% 2-15-02 change close('all') to fclose('all') -ad
% 2-15-02 reformated help & license -ad
function [data,params,events,head] = snapread(file,seekframes)
EVENT_CHANNEL = 1; % This channel assumed to store event pulses only!
EVENT_THRESH = 2.3; % Default event threshold (may need to adjust!!!!)
if nargin < 2
seekframes = 0;
end
data = [];
events = [];
params = [];
head = [];
%
%%%%%%%%%%%%%%%%%%%%%%%%%% Open file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
fid = fopen(file,'r', 'ieee-le');
if fid<1
fprintf('\nsnapread(): Could not open file %s.\n\n',file)
return
else
fprintf('\n Opened file %s for reading...\n',file);
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%% Read header %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Read header and extract info
numbegin=0;
head = [];
while ~numbegin,
line =fgets(fid);
head = [head line];
if (length(line)>=8 & line(1:8)=='"NCHAN%"')
nchans=str2num(line(findstr(line,'=')+1:end-1));
end
if (length(line)>= 12 & line(1:12)=='"NUM.POINTS"')
nframes=str2num(line(findstr(line,'=')+1:end-1));
end
if (length(line)>= 10 & line(1:10)=='"ACT.FREQ"')
srate=str2num(line(findstr(line,'=')+1:end-1));
end
if (length(line)>= 4 & line(1:4)=='"TR"')
head = head(1:length(head)-length(line));
line =fgets(fid); % get the time and date stamp line
numbegin=1;
end
end
params = [nchans, nframes, srate];
fprintf(' Number of channels: %d\n',nchans);
fprintf(' Number of data points: %d\n',nframes);
fprintf(' Sampling rate: %3.1f Hz\n',srate);
fseek(fid,1,0); % skip final hex-AA char
%
%%%%%%%%%%%%%%%%%%% Test for correct file length %%%%%%%%%%%%%%%%%%%%
%
datstart = ftell(fid); % save current position in file
fseek(fid,0,'eof'); % go to file end
datend = ftell(fid); % report position
discrep = (datend-datstart) - nchans*nframes*4;
if discrep ~= 0
fprintf(' ***> Note: File length does not match header information!\n')
fprintf(' Difference: %g frames\n',discrep/(4*nchans));
end
fseek(fid,datstart,'bof'); % seek back to data start
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Read data %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if seekframes > 0
fprintf(' Omitting first %d frames of data.\n',seekframes)
fprintf('moving %d bytes\n',seekframes*nchans*4);
fsq = fseek(fid,seekframes*nchans*4,'cof')
if fsq<0
fsqerr = ferror(fid);
fprintf('fseek() error: %s\n',fsqerr);
return
end
end
[data count] = fread(fid,[nchans,nframes],'float'); % read data frame
if count<nchans*(nframes-seekframes)
fprintf('\nsnapread(): Could not read %d data frames.\n Only %g read.\n\n',...
nframes,count/nchans);
return
else
fprintf('\n Read %d frames, each one sync channel(%d) and %d data channels.\n',...
nframes,EVENT_CHANNEL,nchans-1);
end
if nargout>2
fprintf(' Finding event transitions (>%g) on channel %d ...\n',...
EVENT_THRESH,EVENT_CHANNEL);
events = zeros(EVENT_CHANNEL,nframes);
for n=2:nframes
if abs(data(EVENT_CHANNEL,n-1)) < EVENT_THRESH ...
& abs(data(EVENT_CHANNEL,n)) > EVENT_THRESH
events(n) = 1;
end
end
fprintf(' Total of %d events found.\n',sum(events));
data = data(2:nchans,:); % eliminate channel 1
fprintf(' Event channel %d removed from output.\n',EVENT_CHANNEL);
params(1) = nchans-1;
end
fprintf('\n');
fclose('all');
|
github
|
lcnhappe/happe-master
|
cart2topo.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/cart2topo.m
| 5,225 |
utf_8
|
7ae7263796eecb060729861c9dd9b2fd
|
% cart2topo() - convert xyz-cartesian channel coordinates
% to polar topoplot() coordinates. Input data
% are points on a sphere centered at (0,0,0)
% or at optional input 'center'. This function
% is now DEPRECATED! See Important warning below.
%
% Usage: >> [th r] = cart2topo(xyz); % 3-column [x y z] position data
% >> [th r] = cart2topo(x,y,z); % separate x,y,z vectors
% >> [th r x y z] = cart2topo(xyz,'key', 'val', ...);
% >> [th r x y z] = cart2topo(x,y,z,'key', 'val', ...);
%
% Optional inputs:
% 'center' = [X Y Z] use a known sphere center {Default: [0 0 0]}
% 'squeeze' = plotting squeeze factor (0[default]->1). -1 -> optimize
% the squeeze factor automatically so that maximum radius is 0.5.
% 'optim' = [0|1] find the best-fitting sphere center minimizing the
% standard deviation of the radius values.
% 'gui' = ['on'|'off'] pops up a gui for optional arguments.
% Default is off.
%
% Example: >> [th r] = cart2topo(xyz,[1 0 4]);
%
% Notes: topoplot() does not plot channels with radius>0.5
% Shrink radii to within this range to plot all channels.
% [x y z] are returned after the optimization of the center
% and optionally squeezing r towards it by factor 'squeeze'
%
% Important:
% DEPRECATED: cart2topo() should NOT be used if elevation angle is less than 0
% (for electrodes below zero plane) since then it returns INNACURATE results.
% SUBSTITUTE: Use cart2topo = cart2sph() -> sph2topo().
%
% Authors: Scott Makeig, Luca Finelli & Arnaud Delorme SCCN/INC/UCSD,
% La Jolla, 11/1999-03/2002
%
% See also: topo2sph(), sph2topo(), chancenter()
% Copyright (C) 11/1999 Scott Makeig, SCCN/INC/UCSD, [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
% 3-16-00 improved help message -sm
% 1-25-02 put spherror subfunction inside cart2topo -ad
% 1-25-02 help pops-up if no arguments -ad
% 01-25-02 reformated help & license -ad
% 02-13-02 now center fitting works, need spherror outside cart2topo -lf
% 02-14-02 radii are squeezed of squeeze in to fit topoplot circle -lf
% 03-31-02 center fitting is optional
% 04-01-02 automatic squeeze calculation -ad & sm
function [th,r,xx,yy,zz] = cart2topo(x,varargin)
if nargin<1
help cart2topo
return;
end;
if nargin >= 2
if ~ischar(varargin{1})
y = varargin{1};
z = varargin{2};
varargin = varargin(3:end);
end;
end;
if exist('y') ~= 1
if size(x,2)==3 % separate 3-column data
z = x(:,3);
y = x(:,2);
x = x(:,1);
else
error('Insufficient data in first argument');
end
end;
g = [];
if ~isempty(varargin)
try, g = struct(varargin{:});
catch, error('Argument error in the {''param'', value} sequence'); end;
end;
try, g.optim; catch, g.optim = 0; end;
try, g.squeeze; catch, g.squeeze = 0; end;
try, g.center; catch, g.center = [0 0 0]; end;
try, g.gui; catch, g.gui = 'off'; end;
if g.squeeze>1
fprintf('Warning: Squeeze must be less than 1.\n');
return
end
if ~isempty(g.center) & size(g.center,2) ~= 3
fprintf('Warning: Center must be [x y z].\n');
return
end
% convert to columns
x = -x(:); % minus os for consistency between measures
y = -y(:);
z = z(:);
if any(z < 0)
disp('WARNING: some electrodes lie below the z=0 plane, result may be innacurate')
disp(' Instead use cart2sph() then sph2topo().')
end;
if strcmp(g.gui, 'on')
[x y z newcenter] = chancenter(x, y, z, [], 1);
else
if g.optim == 1
[x y z newcenter] = chancenter(x, y, z, []);
else
[x y z newcenter] = chancenter(x, y, z, g.center);
end;
end;
radius = (sqrt(x.^2+y.^2+z.^2)); % assume xyz values are on a sphere
xx=-x; yy=-y; zz=z;
x = x./radius; % make radius 1
y = y./radius;
z = z./radius;
r = x; th=x;
for n=1:size(x,1)
if x(n)==0 & y(n)==0
r(n) = 0;
else
r(n) = pi/2-atan(z(n)./sqrt(x(n).^2+y(n).^2));
end
end
r = r/pi; % scale r to max 0.500
if g.squeeze < 0
g.squeeze = 1 - 0.5/max(r); %(2*max(r)-1)/(2*rmax);
fprintf('Electrodes will be squeezed together by %2.3g to show all\n', g.squeeze);
end;
r = r-g.squeeze*r; % squeeze electrodes in squeeze*100% to have all inside
for n=1:size(x,1)
if abs(y(n))<1e-6
if x(n)>0
th(n) = -90;
else % x(n) <= 0
th(n) = 90;
end
else
th(n) = atan(x(n)./y(n))*180/pi+90;
if y(n)<0
th(n) = th(n)+180;
end
end
if th(n)>180
th(n) = th(n)-360;
end
if th(n)<-180
th(n) = th(n)+360;
end
end
|
github
|
lcnhappe/happe-master
|
spec.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/spec.m
| 3,687 |
utf_8
|
02cf60598edf850b8ac8f112277a5be7
|
% spec() - power spectrum. This function replaces psd() function if the signal
% processing toolbox is not present. It uses the timef() function.
%
% Usage:
% >> [power freqs] = spec(X);
% >> [power freqs] = spec(X, nfft, fs, win, overlap);
%
% Inputs:
% X - data
% nfft - zero padding to length nfft
% fs - sampling frequency
% win - window size
% overlap - window overlap
%
% Outputs:
% power - spectral estimate (amplitude not dB)
% freqs - frequency array
%
% Note: this function is just an approximation of the psd() (not pwelch)
% method. We strongly recommend to use the psd function if you have
% access to it.
%
% Known problems:
% 1) normalization formula was determined manually by comparing
% with the output of the psd function on about 100 examples.
% 2) In case only one time window is necessary, the overlapping factor
% will be increased so that at least 2 windows are presents (the
% timef function cannot use a single time window).
% 3) FOR FILTERED DATA, THE POWER OVER THE FILTERED REGION IS WRONG
% (TOO HIGH)
% 4) the result of this function differs (in scale) from the pwelch
% function since the normalization is different for pwelch.
%
% Author: Arnaud Delorme, SCCN, Dec 2, 2003
% Copyright (C) 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 [power, freqs] = spec(X, nfft, fs, win, overlap);
if nargin < 1
help spec;
return;
end;
% default parameters
% ------------------
if nargin < 2
nfft = 256;
else
nfft = pow2(nextpow2(nfft));
end;
nfft = min(length(X), nfft);
if nargin < 3
fs = 2;
end;
if nargin < 4
win = nfft;
else
win = pow2(nextpow2(win));
end;
if win > length(X)
win = length(X);
end;
if log2(win) ~= round(log2(win))
win = pow2(floor(log2(win)));
end;
if nargin < 5
overlap = 0;
end;
% compute corresponding parameters for timef
% ------------------------------------------
padratio = pow2(nextpow2(nfft/win));
timesout = floor(length(X)/(win-overlap));
if timesout <= 1, timesout = 2; end;
[ersp itc mbase times freqs] = timef(X(:)', length(X), [0 length(X)]/fs*1000, fs, ...
0, 'padratio', padratio, 'timesout', timesout, 'winsize', win, 'maxfreq', fs/2, ...
'plotersp', 'off', 'plotitc', 'off', 'baseline', NaN, 'verbose', 'off');
ersp = 10.^(ersp/10); % back to amplitude
power = mean(ersp,2)*2.7/win; % this formula is a best approximation (I couldn't find the actual one)
% in practice the difference with psd is less than 0.1 dB
%power = 10*log10(power);
if nargout < 1
hold on;
h = plot(freqs, 10*log10(power));
set(h, 'linewidth', 2);
end;
return;
figure;
stdv = std(ersp, [], 2);
h = plot(freqs, power+stdv, 'r:');
set(h, 'linewidth', 2);
h = plot(freqs, power-stdv, 'r:');
set(h, 'linewidth', 2);
xlabel('Frequency (Hz)');
ylabel('Power (log)');
|
github
|
lcnhappe/happe-master
|
icavar.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/icavar.m
| 3,287 |
utf_8
|
20340418c38178274dabeb7cfd17572d
|
% icavar() - project ICA component activations through the ICA weight matrices
% to reconstitute the observed data using selected ICA components.
% Returns time course of variance on scalp for each component.
%
% Usage: >> [srcvar] = icavar(data,weights,sphere,compnums);
%
% Inputs:
% data - data matrix returned by runica()
% weights - weight matrix returned by runica()
% sphere - sphere matrix returned by runica() (default|0 -> eye(ncomps))
% compnums - list of component numbers (default|0 -> all)
%
% Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 11-30-1996
%
% See also: runica()
% Copyright (C) 11-30-1996 Scott Makeig, SCCN/INC/UCSD, [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
% 04-03-97 made more efficient -sm
% 05-20-97 debugged variance calculation and made it more efficient -sm
% 06-07-97 changed order of args to conform to runica -sm
% 07-23-97 do not add back datamean to projections -sm
% 12-23-97 added compnums -sm
% 02-25-98 changed activations input to data -sm
% 07-20-98 use pinv() for inverting non-square weights -sm
% 01-25-02 reformated help & license, added links -ad
function [srcvar] = icavar(data,weights,sphere,compnums)
if nargin<2
help icavar
return
end
if size(weights,2) ~= size(sphere,1) | size(sphere,2) ~= size(data,1)
fprintf('icavar() - sizes of weights, sphere, and data incompatible.\n')
whos data weights sphere
return
end
activations = weights*sphere*data;
[ncomps,frames] = size(activations);
[wr,chans] = size(weights); % Note: ncomps may < data chans
if nargin<4
compnums = 0;
end
if compnums == 0,
compnums = 1:ncomps;
end
srcvar = zeros(length(compnums),frames);
if nargin < 3
sphere = 0;
end
if sphere == 0,
sphere = eye(ncomps);
end
project = weights*sphere;
if wr~=ncomps,
fprintf('icavar: Number of rows in activations and weights must be equal.\n');
return
end
% if wr<chans,
% fprintf('Filling out a square projection matrix with small noise.\n');
% for r=1:chans-wr,
% project = [project;0.00001*randn(1,chans)];
% end
% end
% project = inv(project); % invert projection matrix
if wr<chans
project = pinv(project);
else
project = inv(project);
end
fprintf('Projecting ICA component ');
nout = length(compnums);
for i=1:nout % for each component
comp = compnums(i);
fprintf('%d ',comp);
projdata = project(:,comp)*activations(comp,:); % reproject eeg data
srcvar(i,:) = sum(projdata.*projdata)/(chans-1);% compute variance at each time point
end
fprintf('\n');
|
github
|
lcnhappe/happe-master
|
eegrej.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/eegrej.m
| 6,611 |
utf_8
|
b882f67c5f4cfe3c0fbce6704b4faa70
|
% eegrej() - reject/excise arbitrary periods from continuous EEG data
% (e.g., EEG.data).
%
% Usage:
% >> [outdata newt newevents boundevents] = ...
% eegrej( indata, regions, timelength, eventlatencies);
%
% Inputs:
% indata - input data (channels, frames). If indata is a string,
% the function use the disk to perform the rejection
% regions - array of regions to suppress. [beg end] x number of
% regions. 'beg' and 'end' are expressed in term of points
% in the input dataset. The size() of the array should be
% (2, number of regions).
% timelength - length in time (s) of the input data. Only used to compute
% new total data length after rejections (newt).
% eventlatencies - vector of event latencies in data points.
% Default []=none.
%
% Outputs:
% outdata - output dataset
% newt - new total data length
% newevents - new event latencies. If the event was in a removed
% region, NaN is returned.
% boundevents - boundary events latencies
%
% Exemple:
% [outdat t] = eegrej( 'EEG.data', [1 100; 200 300]', [0 10]);
% this command pick up two regions in EEG.data (from point 1 to
% point 100, and point 200 to point 300) and put the result in
% the EEG.data variable in the global workspace (thus allowing
% to perform the operation even if EEG.data takes all the memory)
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
% 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 [indata, times, events, boundevents] = eegrej( indata, regions, times, events )
if nargin < 2
help eegrej;
return;
end;
if nargin < 4
events = [];
end;
if isstr(indata)
datlen = evalin('base', [ 'size(' indata ',2)' ]);
else
datlen = size(indata, 2);
end;
reject = zeros(1,datlen);
% Checking for extreme values in regions (correcting round) RMC
regions = round(regions);
regions(regions > size(indata, 2)) = size(indata, 2);
regions(regions < 1) = 1;
regions = sortrows(sort(regions,2)); % Sorting regions %regions = sort(regions,1); RMC
for i=2:size(regions,1)
if regions(i-1,2) >= regions(i,1)
regions(i,1) = regions(i-1,2)+1;
end;
end;
for i=1:size(regions,1)
reject(regions(i,1):regions(i,2)) = 1;
end;
% recompute event times
% ---------------------
rmEvent = [];
rejectedEvents = {};
oriEvents = events;
if ~isempty(events)
eventLatencies = [ events.latency ];
oriEventLatencies = eventLatencies;
for i=1:size(regions,1)
% indices of removed events
rejectedEvents{i} = find( oriEventLatencies > regions(i,1) & oriEventLatencies < regions(i,2) );
rmEvent = [ rmEvent rejectedEvents{i} ];
% remove events within the selected regions
eventLatencies( oriEventLatencies > regions(i,1) ) = eventLatencies( oriEventLatencies > regions(i,1) )-(regions(i,2)-regions(i,1)+1);
%if i == 24, dsafds; end;
end;
for iEvent = 1:length(events)
events(iEvent).latency = eventLatencies(iEvent);
end;
events(rmEvent) = [];
end;
% generate boundaries latencies
% -----------------------------
boundevents = regions(:,1)-1;
for iRegion1=1:size(regions,1)
duration(iRegion1) = regions(iRegion1,2)-regions(iRegion1,1)+1;
% add nested boundary events
if ~isempty(events) && isstr(events(1).type) && isfield(events, 'duration')
selectedEvent = oriEvents(rejectedEvents{iRegion1});
indBound = strmatch('boundary', { selectedEvent.type });
duration(iRegion1) = duration(iRegion1) + sum([selectedEvent(indBound).duration]);
end;
for iRegion2=iRegion1+1:size(regions)
boundevents(iRegion2) = boundevents(iRegion2) - (regions(iRegion1,2)-regions(iRegion1,1)+1);
end;
end;
boundevents = boundevents+0.5;
boundevents(boundevents < 0) = [];
% reject data
% -----------
if isstr(indata)
disp('Using disk to reject data');
increment = 10000;
global elecIndices;
evalin('base', 'global elecIndices');
elecIndices = find(reject == 0);
evalin('base', 'fid = fopen(''tmpeegrej.fdt'', ''w'')');
evalin('base', ['numberrow = size(' indata ',1)']);
evalin('base', ['for indextmp=1:10000:length(elecIndices),', ...
' endtmp = min(indextmp+9999, length(elecIndices));' ...
' fwrite(fid,' indata '(:,elecIndices(indextmp:endtmp)), ''float'');'...
'end']);
evalin('base', 'fclose(fid)');
evalin('base', 'clear global elecIndices');
evalin('base', [ indata '=[]; clear ' indata '']);
evalin('base', 'fid = fopen(''tmpeegrej.fdt'', ''r'')');
evalin('base', [ indata '= fread(fid, [numberrow ' int2str(datlen) '], ''float'')']);
evalin('base', 'fclose(fid)');
evalin('base', 'clear numberrow indextmp endtmp fid');
evalin('base', 'delete(''tmpeegrej.fdt'')');
else
indata(:,reject == 1) = [];
end;
times = times * size(indata,2) / length(reject);
% merge boundary events
% ---------------------
for iBound = length(boundevents):-1:2
if boundevents(iBound) == boundevents(iBound-1)
duration(iBound-1) = duration(iBound-1)+duration(iBound);
boundevents(iBound) = [];
duration(iBound) = [];
end;
end;
if ~isempty(boundevents) && boundevents(end) > size(indata,2)
boundevents(end) = [];
end;
% insert boundary events
% ----------------------
for iRegion1=1:length(boundevents)
if boundevents(iRegion1) > 1 && boundevents(iRegion1) < size(indata,2)
events(end+1).type = 'boundary';
events(end).latency = boundevents(iRegion1);
events(end).duration = duration(iRegion1);
end;
end;
if ~isempty(events) && isfield(events, 'latency')
events([ events.latency ] < 1) = [];
alllatencies = [ events.latency ];
[tmp, sortind] = sort(alllatencies);
events = events(sortind);
end;
return;
|
github
|
lcnhappe/happe-master
|
sbplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/sbplot.m
| 4,612 |
utf_8
|
aac99a4963fad7c8aa7f4010998bc965
|
% sbplot() - create axes in arbitrary subplot grid positions and sizes
%
% Usage: >> axis_handle = sbplot(v,h,index)
% >> axis_handle = sbplot(v,h,[index1 index2])
% >> axis_handle = sbplot(v,h,[index1 index2],axprop,..)
% >> axis_handle = sbplot(v,h,[index1 index2],'ax',handle,axprop,..)
%
% Inputs:
% v,h - Integers giving the vertical and horizontal ranks of the tiling.
% index - Either a single subplot index, in which case the command
% is equivalent to subplot, or a two-element vector giving
% the indices of two corners of the sbplot() area according
% to subplot() convention (e.g., left-to-right, top-to-bottom).
% axprop - Any axes property(s), e.g., >> sbplot(3,3,3,'color','w')
% handle - Following keyword 'ax', sbplot tiles the given axes handle
% instead of the whole figure
%
% Output:
% axis_handle - matlab axis handle
%
% Note:
% sbplot is essentially the same as the subplot command except that
% sbplot axes may span multiple tiles. Also, sbplot() will not erase
% underlying axes.
%
% Examples: >> sbplot(3,3,6);plot(rand(1,10),'g');
% >> sbplot(3,3,[7 2]);plot(rand(1,10),'r');
% >> sbplot(8,7,47);plot(rand(1,10),'b');
%
% Authors: Colin Humphries, Arnaud Delorme & Scott Makeig, SCCN/INC/UCSD, La Jolla, June, 1998
% Copyright (C) June 1998, Colin Humphries & Scott Makeig, SCCN/INC/UCSD,
% [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
% reformatted by Scott Makeig, 6/10/98
% 12/22/00 test nargin<3 -sm
% 01/21/01 added (recursive) axes option 'ax' -sm
% 01-25-02 reformated help & licence -ad
function [out] = sbplot(m,n,gridpos,varargin) % varargin is std. matlab arg list
if nargin<3
error(' requires >=3 arguments');
end
if nargin>3 & strcmp(varargin{1},'ax')
pos = get(varargin{2},'Position'); % sbplot(3,1,[2 3]) -> 0.4111 0.1100 0.4939 0.815
varargin = {varargin{3:end}};
else
pos = get(gcf,'DefaultAxesPosition'); % [0.1300 0.1100 0.7750 0.815]
end
Xpad = pos(1); % lower-left distance from left side of figure
Ypad = pos(2); % lower-left distance from bottom of figure
Xlen = pos(3); % axes width
Ylen = pos(4); % axes height
if n == 2
xspace = Xlen*0.27/(n-0.27); % xspace between axes as per subplot
else
xspace = (0.9*Xlen)*0.27/(n-0.9*0.27);
end
if m == 2
yspace = Ylen*0.27/(m-0.27); % yspace between axes as per subplot
else % WHY Xlen (.775) instead of Ylen (.815) ??
yspace = (0.9*Ylen)*0.27/(m-0.9*0.27);
end
xlength = (Xlen-xspace*(n-1))/n; % axes width
ylength = (Ylen-yspace*(m-1))/m; % axes height
% Convert tile indices to grid positions
if length(gridpos) == 1
xgridpos(1) = mod(gridpos,n); % grid position
if xgridpos(1) == 0
xgridpos(1) = n;
end
xgridpos(2) = 1; % grid length
ygridpos(1) = m-ceil(gridpos/n)+1; % grid position
ygridpos(2) = 1; % grid length
else
xgridpos(1) = mod(gridpos(1),n);
if xgridpos(1) == 0
xgridpos(1) = n;
end
tmp = mod(gridpos(2),n);
if tmp == 0
tmp = n;
end
if tmp > xgridpos(1)
xgridpos(2) = tmp-xgridpos(1)+1;
else
xgridpos(2) = xgridpos(1)-tmp+1;
xgridpos(1) = tmp;
end
ygridpos(1) = m-ceil(gridpos(1)/n)+1;
tmp = m-ceil(gridpos(2)/n)+1;
if tmp > ygridpos(1)
ygridpos(2) = tmp-ygridpos(1)+1;
else
ygridpos(2) = ygridpos(1)-tmp+1;
ygridpos(1) = tmp;
end
end
% Calculate axes coordinates
position(1) = Xpad+xspace*(xgridpos(1)-1)+xlength*(xgridpos(1)-1);
position(2) = Ypad+yspace*(ygridpos(1)-1)+ylength*(ygridpos(1)-1)-0.03;
position(3) = xspace*(xgridpos(2)-1)+xlength*xgridpos(2);
position(4) = yspace*(ygridpos(2)-1)+ylength*ygridpos(2);
% Create new axes
ax = axes('Position',position,varargin{:});
% Output axes handle
if nargout > 0
out = ax;
end
|
github
|
lcnhappe/happe-master
|
adjustlocs.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/adjustlocs.m
| 17,345 |
utf_8
|
540be08faa1b5d805504242c6d023cbb
|
% adjustlocs() - read neuroscan polar location file (.asc)
%
% Usage:
% >> chanlocs = adjustlocs( chanlocs );
% >> chanlocs = adjustlocs( chanlocs, 'key1', val1, 'key2', val2, ...);
%
% Inputs:
% chanlocs - EEGLAB channel location data structure. See
% help readlocs()
%
% Optional inputs:
% 'center' - [cell array] one or several electrode names to compute
% center location (if several electrodes are provided, the
% function use their iso-barycenter). Ex: { 'cz' } or
% { 'fz' 'pz' }.
% 'autocenter' - ['on'|'off'] attempt to automatically detect all symetrical
% electrode in the 10-20 system to compute the center.
% Default: 'on'.
% 'rotate' - [cell array] name and planar angle of landmark electrodes
% to use as template planar rotation. Ex: { 'c3', 90 }.
% 'autorotate' - ['on'|'off'] attempt to automatically detect
% electrode in the 10-20 system to compute the average
% planar rotation. Default 'on'.
% 'scale' - [cell array] name and phi angle of electrodes along
% horizontal central line. Ex: { 'c3' 44 }. Scale uniformly
% all direction. Use 'hscale' and 'vscale' for scaling x and
% y axis independently.
% 'hscale' - [cell array] name and phi angle of electrodes along
% honrizontal central line. Ex: { 'c3' 44 }.
% 'vscale' - [cell array] name and phi angle of one electrodes along
% central vertical axis. Ex: { 'fz' 44 }.
% 'autoscale' - ['on'|'off'] automatic scaling with 10-20 system used as
% reference. Default is 'on'.
% 'uniform' - ['on'|'off'] force the scaling to be uniform along the X
% and the Y axis. Default is 'on'.
% 'coordinates' - ['pol'|'sph'|'cart'] use polar coordinates ('pol'), sperical
% coordinates ('sph') or cartesian ('cart'). Default is 'sph'.
% (Note that using polar and spherical coordinates have the
% same effect, except that units are different).
% Default is 'sph'.
%
% Outputs:
% chanlocs - EEGLAB channel location data structure. See
% help readlocs()
%
% Note: operations are performed in the following order, first re-centering
% then planar rotation and finally sperical re-scaling.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 1 Dec 2003
%
% See also: readlocs()
% Copyright (C) 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 chanlocs = adjustlocs( chanlocs, varargin)
if nargin < 1
help adjustlocs;
return;
end;
% check input parameters
% ----------------------
g = finputcheck( varargin, { 'hscale' 'cell' [] {};
'vscale' 'cell' [] {};
'scale' 'cell' [] {};
'center' 'cell' [] {};
'rotate' 'cell' [] {};
'autoscale' 'string' { 'on','off' } 'off';
'autocenter' 'string' { 'on','off' } 'on';
'autorotate' 'string' { 'on','off' } 'on';
'uniform' 'string' { 'on','off' } 'on';
'coordinates' 'string' { 'pol','sph','cart' } 'sph' });
if ischar(g), error(g); end;
names = { chanlocs.labels };
% auto center
% -----------
if strcmpi(g.autocenter, 'on') & isempty(g.center)
disp('Reading template 10-20 file');
locs1020 = readlocs('eeglab1020.ced');
% scan electrodes for horiz pos
% -----------------------------
tmpnames = lower(names);
tmpnames1020 = lower({ locs1020.labels });
[tmp indelec] = intersect_bc(tmpnames1020, tmpnames);
% remove non-symetrical electrodes
% --------------------------------
if ~isempty(indelec)
if find(indelec == 79), indelec(end+1) = 80; end; % for Cz
ind2remove = [];
for index = 1:length(indelec)
if mod(indelec(index),2)
if ~ismember(indelec(index)+1, indelec)
ind2remove = [ ind2remove index ];
end;
else
if ~ismember(indelec(index)-1, indelec)
ind2remove = [ ind2remove index ];
end;
end;
end;
indelec(ind2remove) = [];
if find(indelec == 80), indelec(end) = []; end; % for Cz
g.center = tmpnames1020(indelec);
end;
if isempty(g.center)
disp('No electrodes found for auto-centering')
else
disp([ num2str(length(g.center)) ' landmark electrodes found for position auto-centering' ])
end;
end;
% auto rotate
% -----------
if strcmpi(g.autorotate, 'on') & isempty(g.rotate)
if exist('locs1020') ~= 1
disp('Reading template 10-20 file');
locs1020 = readlocs('eeglab1020.ced');
end;
% scan electrodes for horiz pos
% -----------------------------
tmpnames = lower(names);
tmpnames1020 = lower({ locs1020.labels });
tmptheta1020 = { locs1020.theta };
[tmp indelec] = intersect_bc(tmpnames1020(1:end-1), tmpnames); % do not use cz
g.rotate(1:2:2*length(indelec)) = tmpnames1020 (indelec);
g.rotate(2:2:2*length(indelec)+1) = tmptheta1020(indelec);
if isempty(g.rotate)
disp('No electrodes found for auto planar rotation')
else
disp([ num2str(length(g.rotate)/2) ' landmark electrodes found for auto planar rotation' ])
end;
end;
% auto scale
% ----------
if strcmpi(g.autoscale, 'on') & isempty(g.hscale) & isempty(g.vscale)
if exist('locs1020') ~= 1
disp('Reading template 10-20 file');
locs1020 = readlocs('eeglab1020.ced');
end;
if strcmpi(g.uniform, 'off')
% remove all vertical electrodes for horizontal scaling
% -----------------------------------------------------
theta = [ locs1020.theta ];
indxh = find(abs(theta) == 90);
indxv = union_bc(find(theta == 0) , find(theta == 180));
locs1020horiz = locs1020(indxh);
locs1020vert = locs1020(indxv);
% scan electrodes for horiz pos
% -----------------------------
tmpnames = lower(names);
tmpnames1020 = lower({ locs1020horiz.labels });
tmpradius1020 = { locs1020horiz.radius };
[tmp indelec] = intersect_bc(tmpnames1020, tmpnames);
if isempty(indelec)
disp('No electrodes found for horiz. position spherical re-scaling')
else
disp([ num2str(length(indelec)) ' landmark electrodes found for horiz. position spherical re-scaling' ]);
if strcmpi(g.coordinates, 'cart')
g.hscale(2:2:2*length(indelec)+1) = [ locs1020horiz.Y ];
else
g.hscale(2:2:2*length(indelec)+1) = tmpradius1020(indelec);
end;
end;
% scan electrodes for vert. pos
% -----------------------------
tmpnames1020 = lower({ locs1020vert.labels });
tmpradius1020 = { locs1020vert.radius };
[tmp indelec] = intersect_bc(tmpnames1020, tmpnames);
if isempty(indelec)
disp('No electrodes found for vertical position spherical re-scaling')
else
disp([ num2str(length(indelec)) ' landmark electrodes found for vertical spherical re-scaling' ]);
g.vscale(1:2:2*length(indelec)) = tmpnames1020 (indelec);
if strcmpi(g.coordinates, 'cart')
g.vscale(2:2:2*length(indelec)+1) = [ locs1020vert.X ];
else
g.vscale(2:2:2*length(indelec)+1) = tmpradius1020(indelec);
end;
end;
else
% uniform scaling
% ---------------
tmpnames = lower(names);
tmpnames1020 = lower({ locs1020.labels });
tmpradius1020 = { locs1020.radius };
[tmp indelec] = intersect_bc(tmpnames1020, tmpnames);
if isempty(indelec)
disp('No electrodes found for uniform spherical re-scaling')
else
disp([ num2str(length(indelec)) ' landmark electrodes found for uniform spherical re-scaling' ]);
g.scale(1:2:2*length(indelec)) = tmpnames1020 (indelec);
if strcmpi(g.coordinates, 'cart')
tmpabsxyz = mattocell(abs([ locs1020.X ]+j*[ locs1020.Y ]));
g.scale(2:2:2*length(indelec)+1) = tmpabsxyz(indelec);
else
g.scale(2:2:2*length(indelec)+1) = tmpradius1020(indelec);
end;
end;
end;
if strcmpi(g.coordinates, 'sph')
g.coordinates = 'pol'; % use polar coordinates for scaling
end;
end;
% get X and Y coordinates
% -----------------------
if strcmpi(g.coordinates, 'sph') | strcmpi(g.coordinates, 'pol')
[X Y] = pol2cart( [ chanlocs.theta ]/180*pi, [ chanlocs.radius ]); Z = 1;
if strcmpi(g.coordinates, 'sph')
X = X/0.25*46;
Y = Y/0.25*46;
end;
else
X = [ chanlocs.X ];
Y = [ chanlocs.Y ];
Z = [ chanlocs.Z ];
end;
% recenter
% --------
if ~isempty(g.center)
for index = 1:length(g.center)
tmpindex = strmatch( lower(g.center{index}), lower(names), 'exact' );
if isempty(tmpindex)
error(['Electrode ''' g.center{index} ''' not found for re-centering']);
end;
indexelec(index) = tmpindex;
end;
showmsg('Using electrode', 'for re-centering', g.center);
centerx = mean(X(indexelec));
centery = mean(Y(indexelec));
X = X - centerx;
Y = Y - centery;
end;
% planar rotation
% ---------------
if ~isempty(g.rotate)
% find electrodes
% ---------------
clear elec;
for index = 1:2:length(g.rotate)
tmpindex = strmatch( lower(g.rotate{index}), lower(names), 'exact' );
if isempty(tmpindex)
error(['Electrode ''' g.rotate{index} ''' not found for left-right scaling']);
end;
elec((index+1)/2) = tmpindex;
end;
vals = [ g.rotate{2:2:end} ];
% compute average scaling factor
% ------------------------------
[ allangles tmp ] = cart2pol(X(elec), Y(elec));
allangles = allangles/pi*180;
diffangle = allangles - vals;
%diffangle2 = allangles + vals;
%if abs(diffangle1) > abs(diffangle2), diffangle = diffangle2;
%else diffangle = diffangle1;
%end;
tmpind = find(diffangle > 180); diffangle(tmpind) = diffangle(tmpind)-360;
tmpind = find(diffangle < -180); diffangle(tmpind) = diffangle(tmpind)+360;
anglerot = mean(diffangle);
tmpcplx = (X+j*Y)*exp(-j*anglerot/180*pi);
X = real(tmpcplx);
Y = imag(tmpcplx);
showmsg('Using electrode', ['for planar rotation (' num2str(anglerot,2) ' degrees)'], g.rotate(1:2:end));
end;
% computing scaling factors
% -------------------------
if ~isempty(g.scale)
% find electrodes
% ---------------
clear elec;
for index = 1:2:length(g.scale)
tmpindex = strmatch( lower(g.scale{index}), lower(names), 'exact' );
if isempty(tmpindex)
error(['Electrode ''' g.scale{index} ''' not found for left-right scaling']);
end;
elec((index+1)/2) = tmpindex;
end;
vals = [ g.scale{2:2:end} ];
% compute average scaling factor
% ------------------------------
nonzero = find(vals > 0);
hscalefact = mean(abs(Y(elec(nonzero))+j*X(elec(nonzero)))./vals(nonzero)); % *46/0.25; %/44/0.25;
vscalefact = hscalefact;
showmsg('Using electrode', ['for uniform spherical re-scaling (x' num2str(1/hscalefact,4) ')'], g.scale(1:2:end));
else
if ~isempty(g.hscale)
% find electrodes
% ---------------
clear elec;
for index = 1:2:length(g.hscale)
tmpindex = strmatch( lower(g.hscale{index}), lower(names), 'exact' );
if isempty(tmpindex)
error(['Electrode ''' g.hscale{index} ''' not found for left-right scaling']);
end;
elec((index+1)/2) = tmpindex;
end;
vals = [ g.hscale{2:2:end} ];
showmsg('Using electrode', [ 'for left-right spherical re-scaling (x' num2str(1/hscalefact,4) ')'], g.hscale(1:2:end));
% compute average scaling factor
% ------------------------------
hscalefact = mean(abs(Y(elec))./vals); % *46/0.25; %/44/0.25;
if isempty(g.vscale)
vscalefact = hscalefact;
end;
end;
if ~isempty(g.vscale)
% find electrodes
% ---------------
clear elec;
for index = 1:2:length(g.vscale)
tmpindex = strmatch( lower(g.vscale{index}), lower(names), 'exact' );
if isempty(tmpindex)
error(['Electrode ''' g.vscale{index} ''' not found for rear-front scaling']);
end;
elec((index+1)/2) = tmpindex;
end;
vals = [ g.vscale{2:2:end} ];
showmsg('Using electrode', ['for rear-front spherical re-scaling (x' num2str(1/vscalefact,4) ')'], g.vscale(1:2:end));
% compute average scaling factor
% ------------------------------
vscalefact = mean(abs(X(elec))./vals); % *46/0.25; %/44/0.25;
if isempty(g.vscale)
hscalefact = vscalefact;
end;
end;
end;
% uniform?
% --------
if strcmpi(g.uniform, 'on') & ( ~isempty(g.vscale) | ~isempty(g.hscale))
disp('uniform scaling: averaging left-right and rear-front scaling factor');
hscalefact = mean([hscalefact vscalefact]);
vscalefact = hscalefact;
end;
% scaling data
% ------------
if ~isempty(g.vscale) | ~isempty(g.hscale) | ~isempty(g.scale)
Y = Y/hscalefact;
X = X/vscalefact;
Z = Z/((hscalefact+vscalefact)/2);
end;
% updating structure
% ------------------
if strcmpi(g.coordinates, 'sph') | strcmpi(g.coordinates, 'pol')
[phi,theta] = cart2pol(Y, X);
phi = phi/pi*180;
if strcmpi(g.coordinates, 'pol')
theta = theta/0.25*46;
end;
% convert to other types of coordinates
% -------------------------------------
labels = names';
chanlocs = struct('labels', names, 'sph_theta_besa', mattocell(theta), ...
'sph_phi_besa', mattocell(phi), 'sph_radius', { chanlocs.sph_radius });
chanlocs = convertlocs( chanlocs, 'sphbesa2all');
else
for index = 1:length(chanlocs)
chanlocs(index).X = X(index);
chanlocs(index).Y = Y(index);
chanlocs(index).Z = Z(index);
end;
chanlocs = convertlocs(chanlocs, 'cart2all');
end;
function showmsg(begmsg, endmsg, struct);
if length(struct) <= 1
disp([ begmsg ' ''' struct{1} ''' ' endmsg]);
elseif length(struct) <= 2
disp([ begmsg ' ''' struct{1} ''' and ''' struct{2} ''' ' endmsg]);
elseif length(struct) <= 3
disp([ begmsg ' ''' struct{1} ''', ''' struct{2} ''' and ''' struct{3} ''' ' endmsg]);
else
disp([ begmsg ' ''' struct{1} ''', ''' struct{2} ''', ''' struct{3} ''' ... ' endmsg]);
end;
|
github
|
lcnhappe/happe-master
|
sph2topo.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/sph2topo.m
| 3,339 |
utf_8
|
44852faa1bc45208398680f08a50db29
|
% sph2topo() - Convert from a 3-column headplot file in spherical coordinates
% to 3-column topoplot() locs file in polar (not cylindrical) coords.
% Used for topoplot() and other 2-D topographic plotting programs.
% Assumes a spherical coordinate system in which horizontal angles
% have a range [-180,180] deg, with zero pointing to the right ear.
% In the output polar coordinate system, zero points to the nose.
% See >> help readlocs
% Usage:
% >> [chan_num,angle,radius] = sph2topo(input,shrink_factor,method);
%
% Inputs:
% input = [channo,az,horiz] = chan_number, azumith (deg), horiz. angle (deg)
% When az>0, horiz=0 -> right ear, 90 -> nose
% When az<0, horiz=0 -> left ear, -90 -> nose
% shrink_factor = arc_length shrinking factor>=1 (deprecated).
% 1 -> plot edge is 90 deg azimuth {default};
% 1.5 -> plot edge is +/-135 deg azimuth See
% >> help topoplot().
% method = [1|2], optional. 1 is for Besa compatibility, 2 is for
% compatibility with Matlab function cart2sph(). Default is 2
%
% Outputs:
% channo = channel number (as in input)
% angle = horizontal angle (0 -> nose; 90 -> right ear; -90 -> left ear)
% radius = arc_lengrh from vertex (Note: 90 deg az -> 0.5/shrink_factor);
% By topoplot() convention, radius=0.5 is the nasion-ear_canal plane.
% Use topoplot() 'plotrad' to plot chans with abs(az) > 90 deg.
%
% Author: Scott Makeig & Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 6/12/98
%
% See also: cart2topo(), topo2sph()
% Copyright (C) 6/12/98 Scott Makeig, SCCN/INC/UCSD, [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
% corrected left/right orientation mismatch, Blair Hicks 6/20/98
% changed name sph2pol() -> sph2topo() for compatibility -sm
% 01-25-02 reformated help & license -ad
% 01-25-02 changed computation so that it works with sph2topo -ad
function [channo,angle,radius] = sph2topo(input,factor, method)
chans = size(input,1);
angle = zeros(chans,1);
radius = zeros(chans,1);
if nargin < 1
help sph2topo
return
end
if nargin< 2
factor = 0;
end
if factor==0
factor = 1;
end
if factor < 1
help sph2topo
return
end
if size(input,2) ~= 3
help sph2topo
return
end
channo = input(:,1);
az = input(:,2);
horiz = input(:,3);
if exist('method')== 1 & method == 1
radius = abs(az/180)/factor;
i = find(az>=0);
angle(i) = 90-horiz(i);
i = find(az<0);
angle(i) = -90-horiz(i);
else
angle = -horiz;
radius = 0.5 - az/180;
end;
|
github
|
lcnhappe/happe-master
|
sobi.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/sobi.m
| 5,094 |
utf_8
|
ce6035ad7a3d7312fee7cf1a37d8e04e
|
% sobi() - Second Order Blind Identification (SOBI) by joint diagonalization of
% correlation matrices. THIS CODE ASSUMES TEMPORALLY CORRELATED SIGNALS,
% and uses correlations across times in performing the signal separation.
% Thus, estimated time delayed covariance matrices must be nonsingular
% for at least some time delays.
% Usage:
% >> winv = sobi(data);
% >> [winv,act] = sobi(data,n,p);
% Inputs:
% data - data matrix of size [m,N] ELSE of size [m,N,t] where
% m is the number of sensors,
% N is the number of samples,
% t is the number of trials (avoid epoch boundaries)
% n - number of sources {Default: n=m}
% p - number of correlation matrices to be diagonalized
% {Default: min(100, N/3)} Note that for non-ideal data,
% the authors strongly recommend using at least 100 time delays.
%
% Outputs:
% winv - Matrix of size [m,n], an estimate of the *mixing* matrix. Its
% columns are the component scalp maps. NOTE: This is the inverse
% of the usual ICA unmixing weight matrix. Sphering (pre-whitening),
% used in the algorithm, is incorporated into winv. i.e.,
%
% >> icaweights = pinv(winv); icasphere = eye(m);
%
% act - matrix of dimension [n,N] an estimate of the source activities
%
% >> data = winv * act;
% [size m,N] [size m,n] [size n,N]
% >> act = pinv(winv) * data;
%
% Authors: A. Belouchrani and A. Cichocki (references: See function body)
% Note: Adapted by Arnaud Delorme and Scott Makeig to process data epochs by
% computing covariances while respecting epoch boundaries.
% REFERENCES:
% A. Belouchrani, K. Abed-Meraim, J.-F. Cardoso, and E. Moulines, ``Second-order
% blind separation of temporally correlated sources,'' in Proc. Int. Conf. on
% Digital Sig. Proc., (Cyprus), pp. 346--351, 1993.
%
% A. Belouchrani and K. Abed-Meraim, ``Separation aveugle au second ordre de
% sources correlees,'' in Proc. Gretsi, (Juan-les-pins),
% pp. 309--312, 1993.
%
% A. Belouchrani, and A. Cichocki,
% Robust whitening procedure in blind source separation context,
% Electronics Letters, Vol. 36, No. 24, 2000, pp. 2050-2053.
%
% A. Cichocki and S. Amari,
% Adaptive Blind Signal and Image Processing, Wiley, 2003.
function [H,S,D]=sobi(X,n,p),
% Authors note: For non-ideal data, use at least p=100 the time-delayed covariance matrices.
DEFAULT_LAGS = 100;
[m,N,ntrials]=size(X);
if nargin<1 | nargin > 3
help sobi
elseif nargin==1,
n=m; % Source detection (hum...)
p=min(DEFAULT_LAGS,ceil(N/3)); % Number of time delayed correlation matrices to be diagonalized
elseif nargin==2,
p=min(DEFAULT_LAGS,ceil(N/3)); % Default number of correlation matrices to be diagonalized
% Use < DEFAULT_LAGS delays if necessary for short data epochs
end;
%
% Make the data zero mean
%
X(:,:)=X(:,:)-kron(mean(X(:,:)')',ones(1,N*ntrials));
%
% Pre-whiten the data based directly on SVD
%
[UU,S,VV]=svd(X(:,:)',0);
Q= pinv(S)*VV';
X(:,:)=Q*X(:,:);
% Alternate whitening code
% Rx=(X*X')/T;
% if m<n, % assumes white noise
% [U,D]=eig(Rx);
% [puiss,k]=sort(diag(D));
% ibl= sqrt(puiss(n-m+1:n)-mean(puiss(1:n-m)));
% bl = ones(m,1) ./ ibl ;
% BL=diag(bl)*U(1:n,k(n-m+1:n))';
% IBL=U(1:n,k(n-m+1:n))*diag(ibl);
% else % assumes no noise
% IBL=sqrtm(Rx);
% Q=inv(IBL);
% end;
% X=Q*X;
%
% Estimate the correlation matrices
%
k=1;
pm=p*m; % for convenience
for u=1:m:pm,
k=k+1;
for t = 1:ntrials
if t == 1
Rxp=X(:,k:N,t)*X(:,1:N-k+1,t)'/(N-k+1)/ntrials;
else
Rxp=Rxp+X(:,k:N,t)*X(:,1:N-k+1,t)'/(N-k+1)/ntrials;
end;
end;
M(:,u:u+m-1)=norm(Rxp,'fro')*Rxp; % Frobenius norm =
end; % sqrt(sum(diag(Rxp'*Rxp)))
%
% Perform joint diagonalization
%
epsil=1/sqrt(N)/100;
encore=1;
V=eye(m);
step_n=0;
while encore,
encore=0;
for p=1:m-1,
for q=p+1:m,
% Perform Givens rotation
g=[ M(p,p:m:pm)-M(q,q:m:pm) ;
M(p,q:m:pm)+M(q,p:m:pm) ;
i*(M(q,p:m:pm)-M(p,q:m:pm)) ];
[vcp,D] = eig(real(g*g'));
[la,K]=sort(diag(D));
angles=vcp(:,K(3));
angles=sign(angles(1))*angles;
c=sqrt(0.5+angles(1)/2);
sr=0.5*(angles(2)-j*angles(3))/c;
sc=conj(sr);
oui = abs(sr)>epsil ;
encore=encore | oui ;
if oui , % Update the M and V matrices
colp=M(:,p:m:pm);
colq=M(:,q:m:pm);
M(:,p:m:pm)=c*colp+sr*colq;
M(:,q:m:pm)=c*colq-sc*colp;
rowp=M(p,:);
rowq=M(q,:);
M(p,:)=c*rowp+sc*rowq;
M(q,:)=c*rowq-sr*rowp;
temp=V(:,p);
V(:,p)=c*V(:,p)+sr*V(:,q);
V(:,q)=c*V(:,q)-sc*temp;
end%% if
end%% q loop
end%% p loop
step_n=step_n+1;
fprintf('%d step\n',step_n);
end%% while
%
% Estimate the mixing matrix
%
H = pinv(Q)*V;
%
% Estimate the source activities
%
if nargout>1
S=V'*X(:,:); % estimated source activities
end
|
github
|
lcnhappe/happe-master
|
runica_ml.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/runica_ml.m
| 43,480 |
utf_8
|
62bb523264cef06666a2d818dea42918
|
% runica() - Perform Independent Component Analysis (ICA) decomposition
% of input data using the logistic infomax ICA algorithm of
% Bell & Sejnowski (1995) with the natural gradient feature
% of Amari, Cichocki & Yang, or optionally the extended-ICA
% algorithm of Lee, Girolami & Sejnowski, with optional PCA
% dimension reduction. Annealing based on weight changes is
% used to automate the separation process.
% Usage:
% >> [weights,sphere] = runica(data); % train using defaults
% else
% >> [weights,sphere,compvars,bias,signs,lrates,activations] ...
% = runica(data,'Key1',Value1',...);
% Input:
% data = input data (chans,frames*epochs).
% Note that if data consists of multiple discontinuous epochs,
% each epoch should be separately baseline-zero'd using
% >> data = rmbase(data,frames,basevector);
%
% Optional keywords [argument]:
% 'extended' = [N] perform tanh() "extended-ICA" with sign estimation
% N training blocks. If N > 0, automatically estimate the
% number of sub-Gaussian sources. If N < 0, fix number of
% sub-Gaussian comps to -N [faster than N>0] (default|0 -> off)
% 'pca' = [N] decompose a principal component (default -> 0=off)
% subspace of the data. Value is the number of PCs to retain.
% 'ncomps' = [N] number of ICA components to compute (default -> chans or 'pca' arg)
% using rectangular ICA decomposition
% 'sphering' = ['on'/'off'] flag sphering of data (default -> 'on')
% 'weights' = [W] initial weight matrix (default -> eye())
% (Note: if 'sphering' 'off', default -> spher())
% 'lrate' = [rate] initial ICA learning rate (<< 1) (default -> heuristic)
% 'block' = [N] ICA block size (<< datalength) (default -> heuristic)
% 'anneal' = annealing constant (0,1] (defaults -> 0.90, or 0.98, extended)
% controls speed of convergence
% 'annealdeg' = [N] degrees weight change for annealing (default -> 70)
% 'stop' = [f] stop training when weight-change < this (default -> 1e-6
% if less than 33 channel and 1E-7 otherwise)
% 'maxsteps' = [N] max number of ICA training steps (default -> 512)
% 'bias' = ['on'/'off'] perform bias adjustment (default -> 'on')
% 'momentum' = [0<f<1] training momentum (default -> 0)
% 'specgram' = [srate loHz hiHz frames winframes] decompose a complex time/frequency
% transform of the data (Note: winframes must divide frames)
% (defaults [srate 0 srate/2 size(data,2) size(data,2)])
% 'posact' = make all component activations net-positive(default 'on'}
% 'verbose' = give ascii messages ('on'/'off') (default -> 'on')
%
% Outputs: [Note: RO means output in reverse order of projected mean variance
% unless starting weight matrix passed ('weights' above)]
% weights = ICA weight matrix (comps,chans) [RO]
% sphere = data sphering matrix (chans,chans) = spher(data)
% Note that unmixing_matrix = weights*sphere {if sphering off -> eye(chans)}
% compvars = back-projected component variances [RO]
% bias = vector of final (ncomps) online bias [RO] (default = zeros())
% signs = extended-ICA signs for components [RO] (default = ones())
% [ -1 = sub-Gaussian; 1 = super-Gaussian]
% lrates = vector of learning rates used at each training step [RO]
% activations = activation time courses of the output components (ncomps,frames*epochs)
%
% Authors: Scott Makeig with contributions from Tony Bell, Te-Won Lee,
% Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky, Delorme Arnaud,
% CNL/The Salk Institute, La Jolla, 1996-
% Uses: posact()
% Reference (please cite):
%
% Makeig, S., Bell, A.J., Jung, T-P and Sejnowski, T.J.,
% "Independent component analysis of electroencephalographic data,"
% In: D. Touretzky, M. Mozer and M. Hasselmo (Eds). Advances in Neural
% Information Processing Systems 8:145-151, MIT Press, Cambridge, MA (1996).
%
% Toolbox Citation:
%
% Makeig, Scott et al. "EEGLAB: ICA Toolbox for Psychophysiological Research".
% WWW Site, Swartz Center for Computational Neuroscience, Institute of Neural
% Computation, University of San Diego California
% <www.sccn.ucsd.edu/eeglab/>, 2000. [World Wide Web Publication].
%
% For more information:
% http://www.sccn.ucsd.edu/eeglab/icafaq.html - FAQ on ICA/EEG
% http://www.sccn.ucsd.edu/eeglab/icabib.html - mss. on ICA & biosignals
% http://www.cnl.salk.edu/~tony/ica.html - math. mss. on ICA
% Copyright (C) 1996 Scott Makeig et al, SCCN/INC/UCSD, [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
%%%%%%%%%%%%%%%%%%%%%%%%%%% Edit history %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% runica() - by Scott Makeig with contributions from Tony Bell, Te-Won Lee
% Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky et al.
% CNL / Salk Institute 1996-00
% 04-30-96 built from icatest.m and ~jung/.../wtwpwica.m -sm
% 07-28-97 new runica(), adds bias (default on), momentum (default off),
% extended-ICA (Lee & Sejnowski, 1997), cumulative angledelta
% (until lrate drops), keywords, signcount for speeding extended-ICA
% 10-07-97 put acos() outside verbose loop; verbose 'off' wasn't stopping -sm
% 11-11-97 adjusted help msg -sm
% 11-30-97 return eye(chans) if sphering 'off' or 'none' (undocumented option) -sm
% 02-27-98 use pinv() instead of inv() to rank order comps if ncomps < chans -sm
% 04-28-98 added 'posact' and 'pca' flags -sm
% 07-16-98 reduced length of randperm() for kurtosis subset calc. -se & sm
% 07-19-98 fixed typo in weights def. above -tl & sm
% 12-21-99 added 'specgram' option suggested by Michael Zibulevsky, UNM -sm
% 12-22-99 fixed rand() sizing inefficiency on suggestion of Mike Spratling, UK -sm
% 01-11-00 fixed rand() sizing bug on suggestion of Jack Foucher, Strasbourg -sm
% 12-18-00 test for existence of Sig Proc Tlbx function 'specgram'; improve
% 'specgram' option arguments -sm
% 01-25-02 reformated help & license -ad
% 01-25-02 lowered default lrate and block -ad
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [weights,sphere,meanvar,bias,signs,lrates,activations,y,loglik,wsave] = runica(data,p1,v1,p2,v2,p3,v3,p4,v4,p5,v5,p6,v6,p7,v7,p8,v8,p9,v9,p10,v10,p11,v11,p12,v12,p13,v13,p14,v14)
if nargin < 1
help runica
return
end
[chans frames] = size(data); % determine the data size
urchans = chans; % remember original data channels
datalength = frames;
if chans<2
fprintf('\nrunica() - data size (%d,%d) too small.\n\n', chans,frames);
return
end
%
%%%%%%%%%%%%%%%%%%%%%% Declare defaults used below %%%%%%%%%%%%%%%%%%%%%%%%
%
MAX_WEIGHT = 1e8; % guess that weights larger than this have blown up
DEFAULT_STOP = 1e-6; % stop training if weight changes below this
DEFAULT_ANNEALDEG = 60; % when angle change reaches this value,
DEFAULT_ANNEALSTEP = 0.95; % anneal by multiplying lrate by this
DEFAULT_EXTANNEAL = 0.95; % or this if extended-ICA
DEFAULT_MAXSTEPS = 500; % stop training after this many steps
DEFAULT_MOMENTUM = 0.0; % default momentum weight
DEFAULT_BLOWUP = 1000000000.0; % = learning rate has 'blown up'
DEFAULT_BLOWUP_FAC = 0.8; % when lrate 'blows up,' anneal by this fac
DEFAULT_RESTART_FAC = 0.9; % if weights blowup, restart with lrate
% lower by this factor
MIN_LRATE = 0.0001; % if weight blowups make lrate < this, quit
MAX_LRATE = 0.1; % guard against uselessly high learning rate
DEFAULT_LRATE = 0.00065/log(chans);
% heuristic default - may need adjustment
% for large or tiny data sets!
% DEFAULT_BLOCK = floor(sqrt(frames/4)); % heuristic default
DEFAULT_BLOCK = ceil(min(5*log(frames),0.3*frames)); % heuristic
%DEFAULT_BLOCK = 10000; % heuristic
% - may need adjustment!
% Extended-ICA option:
DEFAULT_EXTENDED = 1; % default off
DEFAULT_EXTBLOCKS = 1; % number of blocks per kurtosis calculation
DEFAULT_NSUB = 0; % initial default number of assumed sub-Gaussians
% for extended-ICA
DEFAULT_EXTMOMENTUM = 0.5; % momentum term for computing extended-ICA kurtosis
MAX_KURTSIZE = 6000; % max points to use in kurtosis calculation
MIN_KURTSIZE = 2000; % minimum good kurtosis size (flag warning)
SIGNCOUNT_THRESHOLD = 25; % raise extblocks when sign vector unchanged
% after this many steps
SIGNCOUNT_STEP = 2; % extblocks increment factor
DEFAULT_SPHEREFLAG = 'on'; % use the sphere matrix as the default
% starting weight matrix
DEFAULT_PCAFLAG = 'off'; % don't use PCA reduction
DEFAULT_POSACTFLAG = 'on'; % use posact()
DEFAULT_VERBOSE = 1; % write ascii info to calling screen
DEFAULT_BIASFLAG = 0; % default to using bias in the ICA update rule
%
%%%%%%%%%%%%%%%%%%%%%%% Set up keyword default values %%%%%%%%%%%%%%%%%%%%%%%%%
%
if nargout < 2,
fprintf('runica() - needs at least two output arguments.\n');
return
end
epochs = 1; % do not care how many epochs in data
pcaflag = DEFAULT_PCAFLAG;
sphering = DEFAULT_SPHEREFLAG; % default flags
posactflag = DEFAULT_POSACTFLAG;
verbose = DEFAULT_VERBOSE;
block = DEFAULT_BLOCK; % heuristic default - may need adjustment!
lrate = DEFAULT_LRATE;
annealdeg = DEFAULT_ANNEALDEG;
annealstep = 0; % defaults declared below
nochange = NaN;
momentum = DEFAULT_MOMENTUM;
maxsteps = DEFAULT_MAXSTEPS;
weights = 0; % defaults defined below
ncomps = chans;
biasflag = DEFAULT_BIASFLAG;
extended = DEFAULT_EXTENDED;
extblocks = DEFAULT_EXTBLOCKS;
kurtsize = MAX_KURTSIZE;
signsbias = 0.02; % bias towards super-Gaussian components
extmomentum= DEFAULT_EXTMOMENTUM; % exp. average the kurtosis estimates
nsub = DEFAULT_NSUB;
wts_blowup = 0; % flag =1 when weights too large
wts_passed = 0; % flag weights passed as argument
%
%%%%%%%%%% Collect keywords and values from argument list %%%%%%%%%%%%%%%
%
if (nargin> 1 & rem(nargin,2) == 0)
fprintf('runica(): Even number of input arguments???')
return
end
for i = 3:2:nargin % for each Keyword
Keyword = eval(['p',int2str((i-3)/2 +1)]);
Value = eval(['v',int2str((i-3)/2 +1)]);
if ~isstr(Keyword)
fprintf('runica(): keywords must be strings')
return
end
Keyword = lower(Keyword); % convert upper or mixed case to lower
if strcmp(Keyword,'weights') | strcmp(Keyword,'weight')
if isstr(Value)
fprintf(...
'runica(): weights value must be a weight matrix or sphere')
return
else
weights = Value;
wts_passed =1;
end
elseif strcmp(Keyword,'ncomps')
if isstr(Value)
fprintf('runica(): ncomps value must be an integer')
return
end
if ncomps < urchans & ncomps ~= Value
fprintf('runica(): Use either PCA or ICA dimension reduction');
return
end
ncomps = Value;
if ~ncomps,
ncomps = chans;
end
elseif strcmp(Keyword,'pca')
if ncomps < urchans & ncomps ~= Value
fprintf('runica(): Use either PCA or ICA dimension reduction');
return
end
if isstr(Value)
fprintf(...
'runica(): pca value should be the number of principal components to retain')
return
end
pcaflag = 'on';
ncomps = Value;
if ncomps > chans | ncomps < 1,
fprintf('runica(): pca value must be in range [1,%d]\n',chans)
return
end
chans = ncomps;
elseif strcmp(Keyword,'posact')
if ~isstr(Value)
fprintf('runica(): posact value must be on or off')
return
else
Value = lower(Value);
if ~strcmp(Value,'on') & ~strcmp(Value,'off'),
fprintf('runica(): posact value must be on or off')
return
end
posactflag = Value;
end
elseif strcmp(Keyword,'lrate')
if isstr(Value)
fprintf('runica(): lrate value must be a number')
return
end
lrate = Value;
if lrate>MAX_LRATE | lrate <0,
fprintf('runica(): lrate value is out of bounds');
return
end
if ~lrate,
lrate = DEFAULT_LRATE;
end
elseif strcmp(Keyword,'block') | strcmp(Keyword,'blocksize')
if isstr(Value)
fprintf('runica(): block size value must be a number')
return
end
block = floor(Value);
if ~block,
block = DEFAULT_BLOCK;
end
elseif strcmp(Keyword,'stop') | strcmp(Keyword,'nochange') ...
| strcmp(Keyword,'stopping')
if isstr(Value)
fprintf('runica(): stop wchange value must be a number')
return
end
nochange = Value;
elseif strcmp(Keyword,'maxsteps') | strcmp(Keyword,'steps')
if isstr(Value)
fprintf('runica(): maxsteps value must be an integer')
return
end
maxsteps = Value;
if ~maxsteps,
maxsteps = DEFAULT_MAXSTEPS;
end
if maxsteps < 0
fprintf('runica(): maxsteps value (%d) must be a positive integer',maxsteps)
return
end
elseif strcmp(Keyword,'anneal') | strcmp(Keyword,'annealstep')
if isstr(Value)
fprintf('runica(): anneal step value (%2.4f) must be a number (0,1)',Value)
return
end
annealstep = Value;
if annealstep <=0 | annealstep > 1,
fprintf('runica(): anneal step value (%2.4f) must be (0,1]',annealstep)
return
end
elseif strcmp(Keyword,'annealdeg') | strcmp(Keyword,'degrees')
if isstr(Value)
fprintf('runica(): annealdeg value must be a number')
return
end
annealdeg = Value;
if ~annealdeg,
annealdeg = DEFAULT_ANNEALDEG;
elseif annealdeg > 180 | annealdeg < 0
fprintf('runica(): annealdeg (%3.1f) is out of bounds [0,180]',...
annealdeg);
return
end
elseif strcmp(Keyword,'momentum')
if isstr(Value)
fprintf('runica(): momentum value must be a number')
return
end
momentum = Value;
if momentum > 1.0 | momentum < 0
fprintf('runica(): momentum value is out of bounds [0,1]')
return
end
elseif strcmp(Keyword,'sphering') | strcmp(Keyword,'sphereing') ...
| strcmp(Keyword,'sphere')
if ~isstr(Value)
fprintf('runica(): sphering value must be on, off, or none')
return
else
Value = lower(Value);
if ~strcmp(Value,'on') & ~strcmp(Value,'off') & ~strcmp(Value,'none'),
fprintf('runica(): sphering value must be on or off')
return
end
sphering = Value;
end
elseif strcmp(Keyword,'bias')
if ~isstr(Value)
fprintf('runica(): bias value must be on or off')
return
else
Value = lower(Value);
if strcmp(Value,'on')
biasflag = 1;
elseif strcmp(Value,'off'),
biasflag = 0;
else
fprintf('runica(): bias value must be on or off')
return
end
end
elseif strcmp(Keyword,'specgram') | strcmp(Keyword,'spec')
if ~exist('specgram') < 2 % if ~exist or defined workspace variable
fprintf(...
'runica(): MATLAB Sig. Proc. Toolbox function "specgram" not found.\n')
return
end
if isstr(Value)
fprintf('runica(): specgram argument must be a vector')
return
end
srate = Value(1);
if (srate < 0)
fprintf('runica(): specgram srate (%4.1f) must be >=0',srate)
return
end
if length(Value)>1
loHz = Value(2);
if (loHz < 0 | loHz > srate/2)
fprintf('runica(): specgram loHz must be >=0 and <= srate/2 (%4.1f)',srate/2)
return
end
else
loHz = 0; % default
end
if length(Value)>2
hiHz = Value(3);
if (hiHz < loHz | hiHz > srate/2)
fprintf('runica(): specgram hiHz must be >=loHz (%4.1f) and <= srate/2 (%4.1f)',loHz,srate/2)
return
end
else
hiHz = srate/2; % default
end
if length(Value)>3
Hzframes = Value(5);
if (Hzframes<0 | Hzframes > size(data,2))
fprintf('runica(): specgram frames must be >=0 and <= data length (%d)',size(data,2))
return
end
else
Hzframes = size(data,2); % default
end
if length(Value)>4
Hzwinlen = Value(4);
if rem(Hzframes,Hzwinlen) % if winlen doesn't divide frames
fprintf('runica(): specgram Hzinc must divide frames (%d)',Hzframes)
return
end
else
Hzwinlen = Hzframes; % default
end
Specgramflag = 1; % set flag to perform specgram()
elseif strcmp(Keyword,'extended') | strcmp(Keyword,'extend')
if isstr(Value)
fprintf('runica(): extended value must be an integer (+/-)')
return
else
extended = 1; % turn on extended-ICA
extblocks = fix(Value); % number of blocks per kurt() compute
if extblocks < 0
nsub = -1*fix(extblocks); % fix this many sub-Gauss comps
elseif ~extblocks,
extended = 0; % turn extended-ICA off
elseif kurtsize>frames, % length of kurtosis calculation
kurtsize = frames;
if kurtsize < MIN_KURTSIZE
fprintf(...
'runica() warning: kurtosis values inexact for << %d points.\n',...
MIN_KURTSIZE);
end
end
end
elseif strcmp(Keyword,'verbose')
if ~isstr(Value)
fprintf('runica(): verbose flag value must be on or off')
return
elseif strcmp(Value,'on'),
verbose = 1;
elseif strcmp(Value,'off'),
verbose = 0;
else
fprintf('runica(): verbose flag value must be on or off')
return
end
else
fprintf('runica(): unknown flag')
return
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Initialize weights, etc. %%%%%%%%%%%%%%%%%%%%%%%%
%
if ~annealstep,
if ~extended,
annealstep = DEFAULT_ANNEALSTEP; % defaults defined above
else
annealstep = DEFAULT_EXTANNEAL; % defaults defined above
end
end % else use annealstep from commandline
if ~annealdeg,
annealdeg = DEFAULT_ANNEALDEG - momentum*90; % heuristic
if annealdeg < 0,
annealdeg = 0;
end
end
if ncomps > chans | ncomps < 1
fprintf('runica(): number of components must be 1 to %d.\n',chans);
return
end
if weights ~= 0, % initialize weights
% starting weights are being passed to runica() from the commandline
if verbose,
fprintf('Using starting weight matrix named in argument list ...\n')
end
if chans>ncomps & weights ~=0,
[r,c]=size(weights);
if r~=ncomps | c~=chans,
fprintf(...
'runica(): weight matrix must have %d rows, %d columns.\n', ...
chans,ncomps);
return;
end
end
end;
%
%%%%%%%%%%%%%%%%%%%%% Check keyword values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if frames<chans,
fprintf('runica(): data length (%d) < data channels (%d)!\n',frames,chans)
return
elseif block < 1,
fprintf('runica(): block size %d too small!\n',block)
return
elseif block > frames,
fprintf('runica(): block size exceeds data length!\n');
return
elseif floor(epochs) ~= epochs,
fprintf('runica(): data length is not a multiple of the epoch length!\n');
return
elseif nsub > ncomps
fprintf('runica(): there can be at most %d sub-Gaussian components!\n',ncomps);
return
end;
%
% adjust nochange if necessary
%
if isnan(nochange)
if ncomps > 32
nochange = 1E-7;
nochangeupdated = 1; % for fprinting purposes
else
nochangeupdated = 1; % for fprinting purposes
nochange = DEFAULT_STOP;
end;
else
nochangeupdated = 0;
end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Process the data %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if verbose,
fprintf( ...
'\nInput data size [%d,%d] = %d channels, %d frames/n', ...
chans,frames,chans,frames);
if strcmp(pcaflag,'on')
fprintf('After PCA dimension reduction,\n finding ');
else
fprintf('Finding ');
end
if ~extended
fprintf('%d ICA components using logistic ICA.\n',ncomps);
else % if extended
fprintf('%d ICA components using extended ICA.\n',ncomps);
if extblocks > 0
fprintf(...
'Kurtosis will be calculated initially every %d blocks using %d data points.\n',...
extblocks, kurtsize);
else
fprintf(...
'Kurtosis will not be calculated. Exactly %d sub-Gaussian components assumed.\n',...
nsub);
end
end
fprintf('Decomposing %d frames per ICA weight ((%d)^2 = %d weights, %d frames)\n',...
floor(frames/ncomps.^2),ncomps.^2,frames);
fprintf('Initial learning rate will be %g, block size %d.\n',...
lrate,block);
if momentum>0,
fprintf('Momentum will be %g.\n',momentum);
end
fprintf( ...
'Learning rate will be multiplied by %g whenever angledelta >= %g deg.\n', ...
annealstep,annealdeg);
if nochangeupdated
fprintf('More than 32 channels: default stopping weight change 1E-7\n');
end;
fprintf('Training will end when wchange < %g or after %d steps.\n', ...
nochange,maxsteps);
if biasflag,
fprintf('Online bias adjustment will be used.\n');
else
fprintf('Online bias adjustment will not be used.\n');
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%%% Remove overall row means %%%%%%%%%%%%%%%%%%%%%%%%
%
if verbose,
fprintf('Removing mean of each channel ...\n');
end
data = data - mean(data')'*ones(1,frames); % subtract row means
if verbose,
fprintf('Final training data range: %g to %g\n', ...
min(min(data)),max(max(data)));
end
%
%%%%%%%%%%%%%%%%%%% Perform PCA reduction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmp(pcaflag,'on')
fprintf('Reducing the data to %d principal dimensions...\n',ncomps);
[eigenvectors,eigenvalues,data] = pcsquash(data,ncomps);
% make data its projection onto the ncomps-dim principal subspace
end
%
%%%%%%%%%%%%%%%%%%% Perform specgram transformation %%%%%%%%%%%%%%%%%%%%%%%
%
if exist('Specgramflag') == 1
% [P F T] = SPECGRAM(A,NFFT,Fs,WINDOW,NOVERLAP) % MATLAB Sig Proc Toolbox
% Hzwinlen = fix(srate/Hzinc); % CHANGED FROM THIS 12/18/00 -sm
Hzfftlen = 2^(ceil(log(Hzwinlen)/log(2))); % make FFT length next higher 2^k
Hzoverlap = 0; % use sequential windows
%
% Get freqs and times from 1st channel analysis
%
[tmp,freqs,tms] = specgram(data(1,:),Hzfftlen,srate,Hzwinlen,Hzoverlap);
fs = find(freqs>=loHz & freqs <= hiHz);
if isempty(fs)
fprintf('runica(): specified frequency range too narrow!\n');
return
end;
specdata = reshape(tmp(fs,:),1,length(fs)*size(tmp,2));
specdata = [real(specdata) imag(specdata)];
% fprintf(' size(fs) = %d,%d\n',size(fs,1),size(fs,2));
% fprintf(' size(tmp) = %d,%d\n',size(tmp,1),size(tmp,2));
%
% Loop through remaining channels
%
for ch=2:chans
[tmp] = specgram(data(ch,:),Hzwinlen,srate,Hzwinlen,Hzoverlap);
tmp = reshape((tmp(fs,:)),1,length(fs)*size(tmp,2));
specdata = [specdata;[real(tmp) imag(tmp)]]; % channels are rows
end
%
% Print specgram confirmation and details
%
fprintf(...
'Converted data to %d channels by %d=2*%dx%d points spectrogram data.\n',...
chans,2*length(fs)*length(tms),length(fs),length(tms));
if length(fs) > 1
fprintf(...
' Low Hz %g, high Hz %g, Hz incr %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),freqs(fs(2))-freqs(fs(1)),Hzwinlen);
else
fprintf(...
' Low Hz %g, high Hz %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),Hzwinlen);
end
%
% Replace data with specdata
%
data = specdata;
datalength=size(data,2);
end
%
%%%%%%%%%%%%%%%%%%% Perform sphering %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmp(sphering,'on'), %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if verbose,
fprintf('Computing the sphering matrix...\n');
end
sphere = 2.0*inv(sqrtm(cov(data'))); % find the "sphering" matrix = spher()
if ~weights,
if verbose,
fprintf('Starting weights are the identity matrix ...\n');
end
weights = eye(ncomps,chans); % begin with the identity matrix
else % weights given on commandline
if verbose,
fprintf('Using starting weights named on commandline ...\n');
end
end
if verbose,
fprintf('Sphering the data ...\n');
end
data = sphere*data; % actually decorrelate the electrode signals
elseif strcmp(sphering,'off') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~weights
if verbose,
fprintf('Using the sphering matrix as the starting weight matrix ...\n');
fprintf('Returning the identity matrix in variable "sphere" ...\n');
end
sphere = 2.0*inv(sqrtm(cov(data'))); % find the "sphering" matrix = spher()
weights = eye(ncomps,chans)*sphere; % begin with the identity matrix
sphere = eye(chans); % return the identity matrix
else % weights ~= 0
if verbose,
fprintf('Using starting weights named on commandline ...\n');
fprintf('Returning the identity matrix in variable "sphere" ...\n');
end
sphere = eye(chans); % return the identity matrix
end
elseif strcmp(sphering,'none')
sphere = eye(chans); % return the identity matrix
if ~weights
if verbose,
fprintf('Starting weights are the identity matrix ...\n');
fprintf('Returning the identity matrix in variable "sphere" ...\n');
end
weights = eye(ncomps,chans); % begin with the identity matrix
else % weights ~= 0
if verbose,
fprintf('Using starting weights named on commandline ...\n');
fprintf('Returning the identity matrix in variable "sphere" ...\n');
end
end
sphere = eye(chans,chans);
if verbose,
fprintf('Returned variable "sphere" will be the identity matrix.\n');
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Initialize ICA training %%%%%%%%%%%%%%%%%%%%%%%%%
%
lastt=fix((datalength/block-1)*block+1);
BI=block*eye(ncomps,ncomps);
delta=zeros(1,chans*ncomps);
changes = [];
degconst = 180./pi;
startweights = weights;
prevweights = startweights;
oldweights = startweights;
prevwtchange = zeros(chans,ncomps);
oldwtchange = zeros(chans,ncomps);
lrates = zeros(1,maxsteps);
onesrow = ones(1,block);
bias = zeros(ncomps,1);
signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1
for k=1:nsub
signs(k) = -1;
end
if extended & extblocks < 0 & verbose,
fprintf('Fixed extended-ICA sign assignments: ');
for k=1:ncomps
fprintf('%d ',signs(k));
end; fprintf('\n');
end
signs = diag(signs); % make a diagonal matrix
oldsigns = zeros(size(signs));;
signcount = 0; % counter for same-signs
signcounts = [];
urextblocks = extblocks; % original value, for resets
old_kk = zeros(1,ncomps); % for kurtosis momemtum
%
%%%%%%%% ICA training loop using the logistic sigmoid %%%%%%%%%%%%%%%%%%%
%
if verbose,
fprintf('Beginning ICA training ...');
if extended,
fprintf(' first training step may be slow ...\n');
else
fprintf('\n');
end
end
step=0;
laststep=0;
blockno = 1; % running block counter for kurtosis interrupts
logstep = 1; % iterator over log likelihood record
rand('state',sum(100*clock)); % set the random number generator state to
cost_step = 1; % record cost every cost_step iterations
% a position dependent on the system clock
while step < maxsteps, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
permute=randperm(datalength); % shuffle data order at each step
if mod(step,cost_step) == 0 & extended
loglik(logstep) = 0;
end
for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%%
pause(0);
if ~isempty(get(0, 'currentfigure')) & strcmp(get(gcf, 'tag'), 'stop')
close; error('USER ABORT');
end;
if biasflag
u=weights*data(:,permute(t:t+block-1)) + bias*onesrow;
else
u=weights*data(:,permute(t:t+block-1));
end
if ~extended
%%%%%%%%%%%%%%%%%%% Logistic ICA weight update %%%%%%%%%%%%%%%%%%%
y=1./(1+exp(-u)); %
weights = weights + lrate*(BI+(1-2*y)*u')*weights; %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
else % Tanh extended-ICA weight update
%%%%%%%%%%%%%%%%%%% Extended-ICA weight update %%%%%%%%%%%%%%%%%%%
y=tanh(u); %
weights = weights + lrate*(BI-signs*y*u'-u*u')*weights; %
%%%%%%%%% Calculate log likelihood given our model %%%%%%%%%
if mod(step,cost_step) == 0
subgcomp = find(diag(signs) == -1);
supergcomp = find(diag(signs) == 1);
if length(subgcomp) > 0
if biasflag
loglik(logstep) = loglik(logstep) + (1/frames)*sum(sum(log(exp(-(1/2)*(u(subgcomp,:)-bias*ones(1,length(subgcomp))-1).^2) + exp(-(1/2)*(u(subgcomp,:)-bias*ones(1,length(subgcomp))+1).^2))));
else
loglik(logstep) = loglik(logstep) + (1/frames)*sum(sum(log(exp(-(1/2)*(u(subgcomp,:)-1).^2) + exp(-(1/2)*(u(subgcomp,:)+1).^2))));
end
end
if length(supergcomp) > 0
if biasflag
loglik(logstep) = loglik(logstep) + (1/frames)*sum(sum(-0.5*(u(supergcomp,:)-bias*ones(1,length(supergcomp))).^2 - 2*log(cosh(u(supergcomp,:)-bias*ones(1,length(supergcomp))))));
else
loglik(logstep) = loglik(logstep) + (1/frames)*sum(sum(-0.5*u(supergcomp,:).^2 - 2*log(cosh(u(supergcomp,:)))));
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
wsave{step+1} = weights;
if biasflag
if ~extended
%%%%%%%%%%%%%%%%%%%%%%%% Logistic ICA bias %%%%%%%%%%%%%%%%%%%%%%%
bias = bias + lrate*sum((1-2*y)')'; % for logistic nonlin. %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
else % extended
%%%%%%%%%%%%%%%%%%% Extended-ICA bias %%%%%%%%%%%%%%%%%%%%%%%%%%%%
bias = bias + lrate*sum((-2*y)')'; % for tanh() nonlin. %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
end
if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%%
weights = weights + momentum*prevwtchange;
prevwtchange = weights-prevweights;
prevweights = weights;
end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if max(max(abs(weights))) > MAX_WEIGHT
wts_blowup = 1;
change = nochange;
end
if extended & ~wts_blowup
%
%%%%%%%%%%% Extended-ICA kurtosis estimation %%%%%%%%%%%%%%%%%%%%%
%
if extblocks > 0 & rem(blockno,extblocks) == 0,
% recompute signs vector using kurtosis
if kurtsize < frames % 12-22-99 rand() size suggestion by M. Spratling
rp = fix(rand(1,kurtsize)*datalength); % pick random subset
% Accout for the possibility of a 0 generation by rand
ou = find(rp == 0);
while ~isempty(ou) % 1-11-00 suggestion by J. Foucher
rp(ou) = fix(rand(1,length(ou))*datalength);
ou = find(rp == 0);
end
partact=weights*data(:,rp(1:kurtsize));
else % for small data sets,
partact=weights*data; % use whole data
end
m2=mean(partact'.^2).^2;
m4= mean(partact'.^4);
kk= (m4./m2)-3.0; % kurtosis estimates
if extmomentum
kk = extmomentum*old_kk + (1.0-extmomentum)*kk; % use momentum
old_kk = kk;
end
signs=diag(sign(kk+signsbias)); % pick component signs
if signs == oldsigns,
signcount = signcount+1;
else
signcount = 0;
end
oldsigns = signs;
signcounts = [signcounts signcount];
if signcount >= SIGNCOUNT_THRESHOLD,
extblocks = fix(extblocks * SIGNCOUNT_STEP);% make kurt() estimation
signcount = 0; % less frequent if sign
end % is not changing
end % extblocks > 0 & . . .
end % if extended %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
blockno = blockno + 1;
if wts_blowup
break
end
end % training block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if mod(step,cost_step) == 0 & extended
loglik(logstep) = loglik(logstep) + log(abs(det(weights)));
logstep = logstep + 1;
end
if ~wts_blowup
oldwtchange = weights-oldweights;
step=step+1;
%
%%%%%%% Compute and print weight and update angle changes %%%%%%%%%
%
lrates(1,step) = lrate;
angledelta=0.;
delta=reshape(oldwtchange,1,chans*ncomps);
change=delta*delta';
end
%
%%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%%
%
if wts_blowup | isnan(change)|isinf(change), % if weights blow up,
fprintf('');
step = 0; % start again
change = nochange;
wts_blowup = 0; % re-initialize variables
blockno = 1;
lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate
weights = startweights; % and original weight matrix
oldweights = startweights;
change = nochange;
oldwtchange = zeros(chans,ncomps);
delta=zeros(1,chans*ncomps);
olddelta = delta;
extblocks = urextblocks;
prevweights = startweights;
prevwtchange = zeros(chans,ncomps);
lrates = zeros(1,maxsteps);
bias = zeros(ncomps,1);
if extended
signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1
for k=1:nsub
signs(k) = -1;
end
signs = diag(signs); % make a diagonal matrix
oldsigns = zeros(size(signs));;
end
if lrate> MIN_LRATE
r = rank(data);
if r<ncomps
fprintf('Data has rank %d. Cannot compute %d components.\n',...
r,ncomps);
return
else
fprintf(...
'Lowering learning rate to %g and starting again.\n',lrate);
end
else
fprintf( ...
'runica(): QUITTING - weight matrix may not be invertible!\n');
return;
end
else % if weights in bounds
%
%%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%%
%
if step> 2
angledelta=acos((delta*olddelta')/sqrt(change*oldchange));
end
if verbose,
places = -floor(log10(nochange));
if step > 2,
if ~extended,
ps = sprintf('step %d - lrate %5f, wchange %%%d.%df, angledelta %4.1f deg\n', ...
step, lrate, places+1,places, degconst*angledelta);
else
ps = sprintf('step %d - lrate %5f, wchange %%%d.%df, angledelta %4.1f deg, %d subgauss\n',...
step, lrate, degconst*angledelta,...
places+1,places, (ncomps-sum(diag(signs)))/2);
end
elseif ~extended
ps = sprintf('step %d - lrate %5f, wchange %%%d.%df\n',...
step, lrate, places+1,places );
else
ps = sprintf('step %5d - lrate %5f, wchange %%%d.%df, %d subgauss\n',...
step, lrate, places+1,places, (ncomps-sum(diag(signs)))/2);
end % step > 2
fprintf('step %d - lrate %5f, wchange %8.8f, angledelta %5.1f deg, loglik %6.2f, nsub = %d\n', ...
step, lrate, change, degconst*angledelta, loglik(step), sum(diag(signs)==-1));
% fprintf(ps,change); % <---- BUG !!!!
end; % if verbose
%
%%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
changes = [changes change];
oldweights = weights;
%
%%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if degconst*angledelta > annealdeg,
lrate = lrate*annealstep; % anneal learning rate
olddelta = delta; % accumulate angledelta until
oldchange = change; % annealdeg is reached
elseif step == 1 % on first step only
olddelta = delta; % initialize
oldchange = change;
end
%
%%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if step >2 & change < nochange, % apply stopping rule
laststep=step;
step=maxsteps; % stop when weights stabilize
elseif change > DEFAULT_BLOWUP, % if weights blow up,
lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying
end; % with a smaller learning rate
end; % end if weights in bounds
end; % end training %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~laststep
laststep = step;
end;
lrates = lrates(1,1:laststep); % truncate lrate history vector
%
%%%%%%%%%%%%%% Orient components towards max positive activation %%%%%%
%
if strcmp(posactflag,'on')
[activations,winvout,weights] = posact(data,weights);
% changes signs of activations and weights to make activations
% net rms-positive
else
activations = weights*data;
end
%
%%%%%%%%%%%%%% If pcaflag, compose PCA and ICA matrices %%%%%%%%%%%%%%%
%
if strcmp(pcaflag,'on')
fprintf('Composing the eigenvector, weights, and sphere matrices\n');
fprintf(' into a single rectangular weights matrix; sphere=eye(%d)\n'...
,chans);
weights= weights*sphere*eigenvectors(:,1:ncomps)';
sphere = eye(urchans);
end
%
%%%%%% Sort components in descending order of max projected variance %%%%
%
if verbose,
fprintf(...
'Sorting components in descending order of mean projected variance ...\n');
end
%
%%%%%%%%%%%%%%%%%%%% Find mean variances %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
meanvar = zeros(ncomps,1); % size of the projections
if ncomps == urchans % if weights are square . . .
winv = inv(weights*sphere);
else
fprintf('Using pseudo-inverse of weight matrix to rank order component projections.\n');
winv = pinv(weights*sphere);
end
for s=1:ncomps
if verbose,
fprintf('%d ',s); % construct single-component data matrix
end
% project to scalp, then add row means
compproj = winv(:,s)*activations(s,:);
meanvar(s) = mean(sum(compproj.*compproj)/(size(compproj,1)-1));
% compute mean variance
end % at all scalp channels
if verbose,
fprintf('\n');
end
%
%%%%%%%%%%%%%% Sort components by mean variance %%%%%%%%%%%%%%%%%%%%%%%%
%
[sortvar, windex] = sort(meanvar);
windex = windex(ncomps:-1:1); % order large to small
meanvar = meanvar(windex);
%
%%%%%%%%%%%%%%%%%%%%% Filter data using final weights %%%%%%%%%%%%%%%%%%
%
if nargout>6, % if activations are to be returned
if verbose,
fprintf('Permuting the activation wave forms ...\n');
end
activations = activations(windex,:);
else
clear activations
end
weights = weights(windex,:);% reorder the weight matrix
bias = bias(windex); % reorder them
signs = diag(signs); % vectorize the signs matrix
signs = signs(windex); % reorder them
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
return
if nargout > 7
u=weights*data + bias*ones(1,frames);
y = zeros(size(u));
for c=1:chans
for f=1:frames
y(c,f) = 1/(1+exp(-u(c,f)));
end
end
end
|
github
|
lcnhappe/happe-master
|
runica_ml2.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/runica_ml2.m
| 43,331 |
utf_8
|
d9f5448e45ce40d04ca05b45c6a092c4
|
% runica() - Perform Independent Component Analysis (ICA) decomposition
% of input data using the logistic infomax ICA algorithm of
% Bell & Sejnowski (1995) with the natural gradient feature
% of Amari, Cichocki & Yang, or optionally the extended-ICA
% algorithm of Lee, Girolami & Sejnowski, with optional PCA
% dimension reduction. Annealing based on weight changes is
% used to automate the separation process.
% Usage:
% >> [weights,sphere] = runica(data); % train using defaults
% else
% >> [weights,sphere,compvars,bias,signs,lrates,activations] ...
% = runica(data,'Key1',Value1',...);
% Input:
% data = input data (chans,frames*epochs).
% Note that if data consists of multiple discontinuous epochs,
% each epoch should be separately baseline-zero'd using
% >> data = rmbase(data,frames,basevector);
%
% Optional keywords [argument]:
% 'extended' = [N] perform tanh() "extended-ICA" with sign estimation
% N training blocks. If N > 0, automatically estimate the
% number of sub-Gaussian sources. If N < 0, fix number of
% sub-Gaussian comps to -N [faster than N>0] (default|0 -> off)
% 'pca' = [N] decompose a principal component (default -> 0=off)
% subspace of the data. Value is the number of PCs to retain.
% 'ncomps' = [N] number of ICA components to compute (default -> chans or 'pca' arg)
% using rectangular ICA decomposition
% 'sphering' = ['on'/'off'] flag sphering of data (default -> 'on')
% 'weights' = [W] initial weight matrix (default -> eye())
% (Note: if 'sphering' 'off', default -> spher())
% 'lrate' = [rate] initial ICA learning rate (<< 1) (default -> heuristic)
% 'block' = [N] ICA block size (<< datalength) (default -> heuristic)
% 'anneal' = annealing constant (0,1] (defaults -> 0.90, or 0.98, extended)
% controls speed of convergence
% 'annealdeg' = [N] degrees weight change for annealing (default -> 70)
% 'stop' = [f] stop training when weight-change < this (default -> 1e-6
% if less than 33 channel and 1E-7 otherwise)
% 'maxsteps' = [N] max number of ICA training steps (default -> 512)
% 'bias' = ['on'/'off'] perform bias adjustment (default -> 'on')
% 'momentum' = [0<f<1] training momentum (default -> 0)
% 'specgram' = [srate loHz hiHz frames winframes] decompose a complex time/frequency
% transform of the data (Note: winframes must divide frames)
% (defaults [srate 0 srate/2 size(data,2) size(data,2)])
% 'posact' = make all component activations net-positive(default 'on'}
% 'verbose' = give ascii messages ('on'/'off') (default -> 'on')
%
% Outputs: [Note: RO means output in reverse order of projected mean variance
% unless starting weight matrix passed ('weights' above)]
% weights = ICA weight matrix (comps,chans) [RO]
% sphere = data sphering matrix (chans,chans) = spher(data)
% Note that unmixing_matrix = weights*sphere {if sphering off -> eye(chans)}
% compvars = back-projected component variances [RO]
% bias = vector of final (ncomps) online bias [RO] (default = zeros())
% signs = extended-ICA signs for components [RO] (default = ones())
% [ -1 = sub-Gaussian; 1 = super-Gaussian]
% lrates = vector of learning rates used at each training step [RO]
% activations = activation time courses of the output components (ncomps,frames*epochs)
%
% Authors: Scott Makeig with contributions from Tony Bell, Te-Won Lee,
% Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky, Delorme Arnaud,
% CNL/The Salk Institute, La Jolla, 1996-
% Uses: posact()
% Reference (please cite):
%
% Makeig, S., Bell, A.J., Jung, T-P and Sejnowski, T.J.,
% "Independent component analysis of electroencephalographic data,"
% In: D. Touretzky, M. Mozer and M. Hasselmo (Eds). Advances in Neural
% Information Processing Systems 8:145-151, MIT Press, Cambridge, MA (1996).
%
% Toolbox Citation:
%
% Makeig, Scott et al. "EEGLAB: ICA Toolbox for Psychophysiological Research".
% WWW Site, Swartz Center for Computational Neuroscience, Institute of Neural
% Computation, University of San Diego California
% <www.sccn.ucsd.edu/eeglab/>, 2000. [World Wide Web Publication].
%
% For more information:
% http://www.sccn.ucsd.edu/eeglab/icafaq.html - FAQ on ICA/EEG
% http://www.sccn.ucsd.edu/eeglab/icabib.html - mss. on ICA & biosignals
% http://www.cnl.salk.edu/~tony/ica.html - math. mss. on ICA
% Copyright (C) 1996 Scott Makeig et al, SCCN/INC/UCSD, [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
%%%%%%%%%%%%%%%%%%%%%%%%%%% Edit history %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% runica() - by Scott Makeig with contributions from Tony Bell, Te-Won Lee
% Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky et al.
% CNL / Salk Institute 1996-00
% 04-30-96 built from icatest.m and ~jung/.../wtwpwica.m -sm
% 07-28-97 new runica(), adds bias (default on), momentum (default off),
% extended-ICA (Lee & Sejnowski, 1997), cumulative angledelta
% (until lrate drops), keywords, signcount for speeding extended-ICA
% 10-07-97 put acos() outside verbose loop; verbose 'off' wasn't stopping -sm
% 11-11-97 adjusted help msg -sm
% 11-30-97 return eye(chans) if sphering 'off' or 'none' (undocumented option) -sm
% 02-27-98 use pinv() instead of inv() to rank order comps if ncomps < chans -sm
% 04-28-98 added 'posact' and 'pca' flags -sm
% 07-16-98 reduced length of randperm() for kurtosis subset calc. -se & sm
% 07-19-98 fixed typo in weights def. above -tl & sm
% 12-21-99 added 'specgram' option suggested by Michael Zibulevsky, UNM -sm
% 12-22-99 fixed rand() sizing inefficiency on suggestion of Mike Spratling, UK -sm
% 01-11-00 fixed rand() sizing bug on suggestion of Jack Foucher, Strasbourg -sm
% 12-18-00 test for existence of Sig Proc Tlbx function 'specgram'; improve
% 'specgram' option arguments -sm
% 01-25-02 reformated help & license -ad
% 01-25-02 lowered default lrate and block -ad
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [weights,sphere,meanvar,bias,signs,lrates,activations,y,loglik,wsave] = runica(data,p1,v1,p2,v2,p3,v3,p4,v4,p5,v5,p6,v6,p7,v7,p8,v8,p9,v9,p10,v10,p11,v11,p12,v12,p13,v13,p14,v14)
if nargin < 1
help runica
return
end
[chans frames] = size(data); % determine the data size
urchans = chans; % remember original data channels
datalength = frames;
if chans<2
fprintf('\nrunica() - data size (%d,%d) too small.\n\n', chans,frames);
return
end
%
%%%%%%%%%%%%%%%%%%%%%% Declare defaults used below %%%%%%%%%%%%%%%%%%%%%%%%
%
MAX_WEIGHT = 1e8; % guess that weights larger than this have blown up
DEFAULT_STOP = 1e-6; % stop training if weight changes below this
DEFAULT_ANNEALDEG = 60; % when angle change reaches this value,
DEFAULT_ANNEALSTEP = 0.95; % anneal by multiplying lrate by this
DEFAULT_EXTANNEAL = 0.95; % or this if extended-ICA
DEFAULT_MAXSTEPS = 500; % stop training after this many steps
DEFAULT_MOMENTUM = 0.0; % default momentum weight
DEFAULT_BLOWUP = 1000000000.0; % = learning rate has 'blown up'
DEFAULT_BLOWUP_FAC = 0.8; % when lrate 'blows up,' anneal by this fac
DEFAULT_RESTART_FAC = 0.9; % if weights blowup, restart with lrate
% lower by this factor
MIN_LRATE = 0.0001; % if weight blowups make lrate < this, quit
MAX_LRATE = 0.1; % guard against uselessly high learning rate
DEFAULT_LRATE = 0.00065/log(chans);
% heuristic default - may need adjustment
% for large or tiny data sets!
% DEFAULT_BLOCK = floor(sqrt(frames/4)); % heuristic default
DEFAULT_BLOCK = ceil(min(5*log(frames),0.3*frames)); % heuristic
%DEFAULT_BLOCK = 10000; % heuristic
% - may need adjustment!
% Extended-ICA option:
DEFAULT_EXTENDED = 1; % default off
DEFAULT_EXTBLOCKS = 1; % number of blocks per kurtosis calculation
DEFAULT_NSUB = 0; % initial default number of assumed sub-Gaussians
% for extended-ICA
DEFAULT_EXTMOMENTUM = 0.5; % momentum term for computing extended-ICA kurtosis
MAX_KURTSIZE = 6000; % max points to use in kurtosis calculation
MIN_KURTSIZE = 2000; % minimum good kurtosis size (flag warning)
SIGNCOUNT_THRESHOLD = 25; % raise extblocks when sign vector unchanged
% after this many steps
SIGNCOUNT_STEP = 2; % extblocks increment factor
DEFAULT_SPHEREFLAG = 'on'; % use the sphere matrix as the default
% starting weight matrix
DEFAULT_PCAFLAG = 'off'; % don't use PCA reduction
DEFAULT_POSACTFLAG = 'on'; % use posact()
DEFAULT_VERBOSE = 1; % write ascii info to calling screen
DEFAULT_BIASFLAG = 0; % default to using bias in the ICA update rule
%
%%%%%%%%%%%%%%%%%%%%%%% Set up keyword default values %%%%%%%%%%%%%%%%%%%%%%%%%
%
if nargout < 2,
fprintf('runica() - needs at least two output arguments.\n');
return
end
epochs = 1; % do not care how many epochs in data
pcaflag = DEFAULT_PCAFLAG;
sphering = DEFAULT_SPHEREFLAG; % default flags
posactflag = DEFAULT_POSACTFLAG;
verbose = DEFAULT_VERBOSE;
block = DEFAULT_BLOCK; % heuristic default - may need adjustment!
lrate = DEFAULT_LRATE;
annealdeg = DEFAULT_ANNEALDEG;
annealstep = 0; % defaults declared below
nochange = NaN;
momentum = DEFAULT_MOMENTUM;
maxsteps = DEFAULT_MAXSTEPS;
weights = 0; % defaults defined below
ncomps = chans;
biasflag = DEFAULT_BIASFLAG;
extended = DEFAULT_EXTENDED;
extblocks = DEFAULT_EXTBLOCKS;
kurtsize = MAX_KURTSIZE;
signsbias = 0.02; % bias towards super-Gaussian components
extmomentum= DEFAULT_EXTMOMENTUM; % exp. average the kurtosis estimates
nsub = DEFAULT_NSUB;
wts_blowup = 0; % flag =1 when weights too large
wts_passed = 0; % flag weights passed as argument
%
%%%%%%%%%% Collect keywords and values from argument list %%%%%%%%%%%%%%%
%
if (nargin> 1 & rem(nargin,2) == 0)
fprintf('runica(): Even number of input arguments???')
return
end
for i = 3:2:nargin % for each Keyword
Keyword = eval(['p',int2str((i-3)/2 +1)]);
Value = eval(['v',int2str((i-3)/2 +1)]);
if ~isstr(Keyword)
fprintf('runica(): keywords must be strings')
return
end
Keyword = lower(Keyword); % convert upper or mixed case to lower
if strcmp(Keyword,'weights') | strcmp(Keyword,'weight')
if isstr(Value)
fprintf(...
'runica(): weights value must be a weight matrix or sphere')
return
else
weights = Value;
wts_passed =1;
end
elseif strcmp(Keyword,'ncomps')
if isstr(Value)
fprintf('runica(): ncomps value must be an integer')
return
end
if ncomps < urchans & ncomps ~= Value
fprintf('runica(): Use either PCA or ICA dimension reduction');
return
end
ncomps = Value;
if ~ncomps,
ncomps = chans;
end
elseif strcmp(Keyword,'pca')
if ncomps < urchans & ncomps ~= Value
fprintf('runica(): Use either PCA or ICA dimension reduction');
return
end
if isstr(Value)
fprintf(...
'runica(): pca value should be the number of principal components to retain')
return
end
pcaflag = 'on';
ncomps = Value;
if ncomps > chans | ncomps < 1,
fprintf('runica(): pca value must be in range [1,%d]\n',chans)
return
end
chans = ncomps;
elseif strcmp(Keyword,'posact')
if ~isstr(Value)
fprintf('runica(): posact value must be on or off')
return
else
Value = lower(Value);
if ~strcmp(Value,'on') & ~strcmp(Value,'off'),
fprintf('runica(): posact value must be on or off')
return
end
posactflag = Value;
end
elseif strcmp(Keyword,'lrate')
if isstr(Value)
fprintf('runica(): lrate value must be a number')
return
end
lrate = Value;
if lrate>MAX_LRATE | lrate <0,
fprintf('runica(): lrate value is out of bounds');
return
end
if ~lrate,
lrate = DEFAULT_LRATE;
end
elseif strcmp(Keyword,'block') | strcmp(Keyword,'blocksize')
if isstr(Value)
fprintf('runica(): block size value must be a number')
return
end
block = floor(Value);
if ~block,
block = DEFAULT_BLOCK;
end
elseif strcmp(Keyword,'stop') | strcmp(Keyword,'nochange') ...
| strcmp(Keyword,'stopping')
if isstr(Value)
fprintf('runica(): stop wchange value must be a number')
return
end
nochange = Value;
elseif strcmp(Keyword,'maxsteps') | strcmp(Keyword,'steps')
if isstr(Value)
fprintf('runica(): maxsteps value must be an integer')
return
end
maxsteps = Value;
if ~maxsteps,
maxsteps = DEFAULT_MAXSTEPS;
end
if maxsteps < 0
fprintf('runica(): maxsteps value (%d) must be a positive integer',maxsteps)
return
end
elseif strcmp(Keyword,'anneal') | strcmp(Keyword,'annealstep')
if isstr(Value)
fprintf('runica(): anneal step value (%2.4f) must be a number (0,1)',Value)
return
end
annealstep = Value;
if annealstep <=0 | annealstep > 1,
fprintf('runica(): anneal step value (%2.4f) must be (0,1]',annealstep)
return
end
elseif strcmp(Keyword,'annealdeg') | strcmp(Keyword,'degrees')
if isstr(Value)
fprintf('runica(): annealdeg value must be a number')
return
end
annealdeg = Value;
if ~annealdeg,
annealdeg = DEFAULT_ANNEALDEG;
elseif annealdeg > 180 | annealdeg < 0
fprintf('runica(): annealdeg (%3.1f) is out of bounds [0,180]',...
annealdeg);
return
end
elseif strcmp(Keyword,'momentum')
if isstr(Value)
fprintf('runica(): momentum value must be a number')
return
end
momentum = Value;
if momentum > 1.0 | momentum < 0
fprintf('runica(): momentum value is out of bounds [0,1]')
return
end
elseif strcmp(Keyword,'sphering') | strcmp(Keyword,'sphereing') ...
| strcmp(Keyword,'sphere')
if ~isstr(Value)
fprintf('runica(): sphering value must be on, off, or none')
return
else
Value = lower(Value);
if ~strcmp(Value,'on') & ~strcmp(Value,'off') & ~strcmp(Value,'none'),
fprintf('runica(): sphering value must be on or off')
return
end
sphering = Value;
end
elseif strcmp(Keyword,'bias')
if ~isstr(Value)
fprintf('runica(): bias value must be on or off')
return
else
Value = lower(Value);
if strcmp(Value,'on')
biasflag = 1;
elseif strcmp(Value,'off'),
biasflag = 0;
else
fprintf('runica(): bias value must be on or off')
return
end
end
elseif strcmp(Keyword,'specgram') | strcmp(Keyword,'spec')
if ~exist('specgram') < 2 % if ~exist or defined workspace variable
fprintf(...
'runica(): MATLAB Sig. Proc. Toolbox function "specgram" not found.\n')
return
end
if isstr(Value)
fprintf('runica(): specgram argument must be a vector')
return
end
srate = Value(1);
if (srate < 0)
fprintf('runica(): specgram srate (%4.1f) must be >=0',srate)
return
end
if length(Value)>1
loHz = Value(2);
if (loHz < 0 | loHz > srate/2)
fprintf('runica(): specgram loHz must be >=0 and <= srate/2 (%4.1f)',srate/2)
return
end
else
loHz = 0; % default
end
if length(Value)>2
hiHz = Value(3);
if (hiHz < loHz | hiHz > srate/2)
fprintf('runica(): specgram hiHz must be >=loHz (%4.1f) and <= srate/2 (%4.1f)',loHz,srate/2)
return
end
else
hiHz = srate/2; % default
end
if length(Value)>3
Hzframes = Value(5);
if (Hzframes<0 | Hzframes > size(data,2))
fprintf('runica(): specgram frames must be >=0 and <= data length (%d)',size(data,2))
return
end
else
Hzframes = size(data,2); % default
end
if length(Value)>4
Hzwinlen = Value(4);
if rem(Hzframes,Hzwinlen) % if winlen doesn't divide frames
fprintf('runica(): specgram Hzinc must divide frames (%d)',Hzframes)
return
end
else
Hzwinlen = Hzframes; % default
end
Specgramflag = 1; % set flag to perform specgram()
elseif strcmp(Keyword,'extended') | strcmp(Keyword,'extend')
if isstr(Value)
fprintf('runica(): extended value must be an integer (+/-)')
return
else
extended = 1; % turn on extended-ICA
extblocks = fix(Value); % number of blocks per kurt() compute
if extblocks < 0
nsub = -1*fix(extblocks); % fix this many sub-Gauss comps
elseif ~extblocks,
extended = 0; % turn extended-ICA off
elseif kurtsize>frames, % length of kurtosis calculation
kurtsize = frames;
if kurtsize < MIN_KURTSIZE
fprintf(...
'runica() warning: kurtosis values inexact for << %d points.\n',...
MIN_KURTSIZE);
end
end
end
elseif strcmp(Keyword,'verbose')
if ~isstr(Value)
fprintf('runica(): verbose flag value must be on or off')
return
elseif strcmp(Value,'on'),
verbose = 1;
elseif strcmp(Value,'off'),
verbose = 0;
else
fprintf('runica(): verbose flag value must be on or off')
return
end
else
fprintf('runica(): unknown flag')
return
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Initialize weights, etc. %%%%%%%%%%%%%%%%%%%%%%%%
%
if ~annealstep,
if ~extended,
annealstep = DEFAULT_ANNEALSTEP; % defaults defined above
else
annealstep = DEFAULT_EXTANNEAL; % defaults defined above
end
end % else use annealstep from commandline
if ~annealdeg,
annealdeg = DEFAULT_ANNEALDEG - momentum*90; % heuristic
if annealdeg < 0,
annealdeg = 0;
end
end
if ncomps > chans | ncomps < 1
fprintf('runica(): number of components must be 1 to %d.\n',chans);
return
end
if weights ~= 0, % initialize weights
% starting weights are being passed to runica() from the commandline
if verbose,
fprintf('Using starting weight matrix named in argument list ...\n')
end
if chans>ncomps & weights ~=0,
[r,c]=size(weights);
if r~=ncomps | c~=chans,
fprintf(...
'runica(): weight matrix must have %d rows, %d columns.\n', ...
chans,ncomps);
return;
end
end
end;
%
%%%%%%%%%%%%%%%%%%%%% Check keyword values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if frames<chans,
fprintf('runica(): data length (%d) < data channels (%d)!\n',frames,chans)
return
elseif block < 1,
fprintf('runica(): block size %d too small!\n',block)
return
elseif block > frames,
fprintf('runica(): block size exceeds data length!\n');
return
elseif floor(epochs) ~= epochs,
fprintf('runica(): data length is not a multiple of the epoch length!\n');
return
elseif nsub > ncomps
fprintf('runica(): there can be at most %d sub-Gaussian components!\n',ncomps);
return
end;
%
% adjust nochange if necessary
%
if isnan(nochange)
if ncomps > 32
nochange = 1E-7;
nochangeupdated = 1; % for fprinting purposes
else
nochangeupdated = 1; % for fprinting purposes
nochange = DEFAULT_STOP;
end;
else
nochangeupdated = 0;
end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Process the data %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if verbose,
fprintf( ...
'\nInput data size [%d,%d] = %d channels, %d frames/n', ...
chans,frames,chans,frames);
if strcmp(pcaflag,'on')
fprintf('After PCA dimension reduction,\n finding ');
else
fprintf('Finding ');
end
if ~extended
fprintf('%d ICA components using logistic ICA.\n',ncomps);
else % if extended
fprintf('%d ICA components using extended ICA.\n',ncomps);
if extblocks > 0
fprintf(...
'Kurtosis will be calculated initially every %d blocks using %d data points.\n',...
extblocks, kurtsize);
else
fprintf(...
'Kurtosis will not be calculated. Exactly %d sub-Gaussian components assumed.\n',...
nsub);
end
end
fprintf('Decomposing %d frames per ICA weight ((%d)^2 = %d weights, %d frames)\n',...
floor(frames/ncomps.^2),ncomps.^2,frames);
fprintf('Initial learning rate will be %g, block size %d.\n',...
lrate,block);
if momentum>0,
fprintf('Momentum will be %g.\n',momentum);
end
fprintf( ...
'Learning rate will be multiplied by %g whenever angledelta >= %g deg.\n', ...
annealstep,annealdeg);
if nochangeupdated
fprintf('More than 32 channels: default stopping weight change 1E-7\n');
end;
fprintf('Training will end when wchange < %g or after %d steps.\n', ...
nochange,maxsteps);
if biasflag,
fprintf('Online bias adjustment will be used.\n');
else
fprintf('Online bias adjustment will not be used.\n');
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%%% Remove overall row means %%%%%%%%%%%%%%%%%%%%%%%%
%
if verbose,
fprintf('Removing mean of each channel ...\n');
end
data = data - mean(data')'*ones(1,frames); % subtract row means
if verbose,
fprintf('Final training data range: %g to %g\n', ...
min(min(data)),max(max(data)));
end
%
%%%%%%%%%%%%%%%%%%% Perform PCA reduction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmp(pcaflag,'on')
fprintf('Reducing the data to %d principal dimensions...\n',ncomps);
[eigenvectors,eigenvalues,data] = pcsquash(data,ncomps);
% make data its projection onto the ncomps-dim principal subspace
end
%
%%%%%%%%%%%%%%%%%%% Perform specgram transformation %%%%%%%%%%%%%%%%%%%%%%%
%
if exist('Specgramflag') == 1
% [P F T] = SPECGRAM(A,NFFT,Fs,WINDOW,NOVERLAP) % MATLAB Sig Proc Toolbox
% Hzwinlen = fix(srate/Hzinc); % CHANGED FROM THIS 12/18/00 -sm
Hzfftlen = 2^(ceil(log(Hzwinlen)/log(2))); % make FFT length next higher 2^k
Hzoverlap = 0; % use sequential windows
%
% Get freqs and times from 1st channel analysis
%
[tmp,freqs,tms] = specgram(data(1,:),Hzfftlen,srate,Hzwinlen,Hzoverlap);
fs = find(freqs>=loHz & freqs <= hiHz);
if isempty(fs)
fprintf('runica(): specified frequency range too narrow!\n');
return
end;
specdata = reshape(tmp(fs,:),1,length(fs)*size(tmp,2));
specdata = [real(specdata) imag(specdata)];
% fprintf(' size(fs) = %d,%d\n',size(fs,1),size(fs,2));
% fprintf(' size(tmp) = %d,%d\n',size(tmp,1),size(tmp,2));
%
% Loop through remaining channels
%
for ch=2:chans
[tmp] = specgram(data(ch,:),Hzwinlen,srate,Hzwinlen,Hzoverlap);
tmp = reshape((tmp(fs,:)),1,length(fs)*size(tmp,2));
specdata = [specdata;[real(tmp) imag(tmp)]]; % channels are rows
end
%
% Print specgram confirmation and details
%
fprintf(...
'Converted data to %d channels by %d=2*%dx%d points spectrogram data.\n',...
chans,2*length(fs)*length(tms),length(fs),length(tms));
if length(fs) > 1
fprintf(...
' Low Hz %g, high Hz %g, Hz incr %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),freqs(fs(2))-freqs(fs(1)),Hzwinlen);
else
fprintf(...
' Low Hz %g, high Hz %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),Hzwinlen);
end
%
% Replace data with specdata
%
data = specdata;
datalength=size(data,2);
end
%
%%%%%%%%%%%%%%%%%%% Perform sphering %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmp(sphering,'on'), %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if verbose,
fprintf('Computing the sphering matrix...\n');
end
sphere = 2.0*inv(sqrtm(cov(data'))); % find the "sphering" matrix = spher()
if ~weights,
if verbose,
fprintf('Starting weights are the identity matrix ...\n');
end
weights = eye(ncomps,chans); % begin with the identity matrix
else % weights given on commandline
if verbose,
fprintf('Using starting weights named on commandline ...\n');
end
end
if verbose,
fprintf('Sphering the data ...\n');
end
data = sphere*data; % actually decorrelate the electrode signals
elseif strcmp(sphering,'off') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~weights
if verbose,
fprintf('Using the sphering matrix as the starting weight matrix ...\n');
fprintf('Returning the identity matrix in variable "sphere" ...\n');
end
sphere = 2.0*inv(sqrtm(cov(data'))); % find the "sphering" matrix = spher()
weights = eye(ncomps,chans)*sphere; % begin with the identity matrix
sphere = eye(chans); % return the identity matrix
else % weights ~= 0
if verbose,
fprintf('Using starting weights named on commandline ...\n');
fprintf('Returning the identity matrix in variable "sphere" ...\n');
end
sphere = eye(chans); % return the identity matrix
end
elseif strcmp(sphering,'none')
sphere = eye(chans); % return the identity matrix
if ~weights
if verbose,
fprintf('Starting weights are the identity matrix ...\n');
fprintf('Returning the identity matrix in variable "sphere" ...\n');
end
weights = eye(ncomps,chans); % begin with the identity matrix
else % weights ~= 0
if verbose,
fprintf('Using starting weights named on commandline ...\n');
fprintf('Returning the identity matrix in variable "sphere" ...\n');
end
end
sphere = eye(chans,chans);
if verbose,
fprintf('Returned variable "sphere" will be the identity matrix.\n');
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Initialize ICA training %%%%%%%%%%%%%%%%%%%%%%%%%
%
lastt=fix((datalength/block-1)*block+1);
BI=block*eye(ncomps,ncomps);
delta=zeros(1,chans*ncomps);
changes = [];
degconst = 180./pi;
startweights = weights;
prevweights = startweights;
oldweights = startweights;
prevwtchange = zeros(chans,ncomps);
oldwtchange = zeros(chans,ncomps);
lrates = zeros(1,maxsteps);
onesrow = ones(1,block);
bias = zeros(ncomps,1);
signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1
for k=1:nsub
signs(k) = -1;
end
if extended & extblocks < 0 & verbose,
fprintf('Fixed extended-ICA sign assignments: ');
for k=1:ncomps
fprintf('%d ',signs(k));
end; fprintf('\n');
end
signs = diag(signs); % make a diagonal matrix
oldsigns = zeros(size(signs));;
signcount = 0; % counter for same-signs
signcounts = [];
urextblocks = extblocks; % original value, for resets
old_kk = zeros(1,ncomps); % for kurtosis momemtum
%
%%%%%%%% ICA training loop using the logistic sigmoid %%%%%%%%%%%%%%%%%%%
%
if verbose,
fprintf('Beginning ICA training ...');
if extended,
fprintf(' first training step may be slow ...\n');
else
fprintf('\n');
end
end
step=0;
laststep=0;
blockno = 1; % running block counter for kurtosis interrupts
logstep = 1; % iterator over log likelihood record
rand('state',sum(100*clock)); % set the random number generator state to
cost_step = 10; % record cost every cost_step iterations
block = 10000;
% a position dependent on the system clock
while step < maxsteps, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
permute=randperm(datalength); % shuffle data order at each step
if mod(step,cost_step) == 0
loglik(logstep) = 0;
end
for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%%
pause(0);
if ~isempty(get(0, 'currentfigure')) & strcmp(get(gcf, 'tag'), 'stop')
close; error('USER ABORT');
end;
if biasflag
u=weights*data(:,permute(t:t+block-1)) + bias*onesrow;
else
u=weights*data(:,permute(t:t+block-1));
end
if ~extended
%%%%%%%%%%%%%%%%%%% Logistic ICA weight update %%%%%%%%%%%%%%%%%%%
y=1./(1+exp(-u)); %
weights = weights + lrate*(BI+(1-2*y)*u')*weights; %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
else % Tanh extended-ICA weight update
%%%%%%%%%%%%%%%%%%% Extended-ICA weight update %%%%%%%%%%%%%%%%%%%
y=tanh(u); %
weights = weights + lrate*(BI-signs*y*u'-u*u')*weights; %
end
wsave{step+1} = weights;
if biasflag
if ~extended
%%%%%%%%%%%%%%%%%%%%%%%% Logistic ICA bias %%%%%%%%%%%%%%%%%%%%%%%
bias = bias + lrate*sum((1-2*y)')'; % for logistic nonlin. %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
else % extended
%%%%%%%%%%%%%%%%%%% Extended-ICA bias %%%%%%%%%%%%%%%%%%%%%%%%%%%%
bias = bias + lrate*sum((-2*y)')'; % for tanh() nonlin. %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
end
if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%%
weights = weights + momentum*prevwtchange;
prevwtchange = weights-prevweights;
prevweights = weights;
end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if max(max(abs(weights))) > MAX_WEIGHT
wts_blowup = 1;
change = nochange;
end
if extended & ~wts_blowup
%
%%%%%%%%%%% Extended-ICA kurtosis estimation %%%%%%%%%%%%%%%%%%%%%
%
if extblocks > 0 & rem(blockno,extblocks) == 0,
% recompute signs vector using kurtosis
if kurtsize < frames % 12-22-99 rand() size suggestion by M. Spratling
rp = fix(rand(1,kurtsize)*datalength); % pick random subset
% Accout for the possibility of a 0 generation by rand
ou = find(rp == 0);
while ~isempty(ou) % 1-11-00 suggestion by J. Foucher
rp(ou) = fix(rand(1,length(ou))*datalength);
ou = find(rp == 0);
end
partact=weights*data(:,rp(1:kurtsize));
else % for small data sets,
partact=weights*data; % use whole data
end
m2=mean(partact'.^2).^2;
m4= mean(partact'.^4);
kk= (m4./m2)-3.0; % kurtosis estimates
if extmomentum
kk = extmomentum*old_kk + (1.0-extmomentum)*kk; % use momentum
old_kk = kk;
end
signs=diag(sign(kk+signsbias)); % pick component signs
if signs == oldsigns,
signcount = signcount+1;
else
signcount = 0;
end
oldsigns = signs;
signcounts = [signcounts signcount];
if signcount >= SIGNCOUNT_THRESHOLD,
extblocks = fix(extblocks * SIGNCOUNT_STEP);% make kurt() estimation
signcount = 0; % less frequent if sign
end % is not changing
end % extblocks > 0 & . . .
end % if extended %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
blockno = blockno + 1;
if wts_blowup
break
end
end % training block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if mod(step,cost_step) == 0
%%%%%%%%% Calculate log likelihood given our model %%%%%%%%%
loglik(logstep) = log(abs(det(weights)));
if extended
subgcomp = find(diag(signs) == -1);
supergcomp = find(diag(signs) == 1);
acts = weights*data;
if length(subgcomp) > 0
if biasflag
loglik(logstep) = loglik(logstep) + (1/frames)*sum(sum(log(exp(-(1/2)*(acts(subgcomp,:)-bias*ones(1,length(subgcomp))-1).^2) + exp(-(1/2)*(acts(subgcomp,:)-bias*ones(1,length(subgcomp))+1).^2))));
else
loglik(logstep) = loglik(logstep) + (1/frames)*sum(sum(log(exp(-(1/2)*(acts(subgcomp,:)-1).^2) + exp(-(1/2)*(acts(subgcomp,:)+1).^2))));
end
end
if length(supergcomp) > 0
if biasflag
loglik(logstep) = loglik(logstep) + (1/frames)*sum(sum(-0.5*(acts(supergcomp,:)-bias*ones(1,length(supergcomp))).^2 - 2*log(cosh(acts(supergcomp,:)-bias*ones(1,length(supergcomp))))));
else
loglik(logstep) = loglik(logstep) + (1/frames)*sum(sum(-0.5*acts(supergcomp,:).^2 - 2*log(cosh(acts(supergcomp,:)))));
end
end
end
logstep = logstep + 1;
end
if ~wts_blowup
oldwtchange = weights-oldweights;
step=step+1;
%
%%%%%%% Compute and print weight and update angle changes %%%%%%%%%
%
lrates(1,step) = lrate;
angledelta=0.;
delta=reshape(oldwtchange,1,chans*ncomps);
change=delta*delta';
end
%
%%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%%
%
if wts_blowup | isnan(change)|isinf(change), % if weights blow up,
fprintf('');
step = 0; % start again
change = nochange;
wts_blowup = 0; % re-initialize variables
blockno = 1;
lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate
weights = startweights; % and original weight matrix
oldweights = startweights;
change = nochange;
oldwtchange = zeros(chans,ncomps);
delta=zeros(1,chans*ncomps);
olddelta = delta;
extblocks = urextblocks;
prevweights = startweights;
prevwtchange = zeros(chans,ncomps);
lrates = zeros(1,maxsteps);
bias = zeros(ncomps,1);
if extended
signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1
for k=1:nsub
signs(k) = -1;
end
signs = diag(signs); % make a diagonal matrix
oldsigns = zeros(size(signs));;
end
if lrate> MIN_LRATE
r = rank(data);
if r<ncomps
fprintf('Data has rank %d. Cannot compute %d components.\n',...
r,ncomps);
return
else
fprintf(...
'Lowering learning rate to %g and starting again.\n',lrate);
end
else
fprintf( ...
'runica(): QUITTING - weight matrix may not be invertible!\n');
return;
end
else % if weights in bounds
%
%%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%%
%
if step> 2
angledelta=acos((delta*olddelta')/sqrt(change*oldchange));
end
if verbose,
places = -floor(log10(nochange));
if step > 2,
if ~extended,
ps = sprintf('step %d - lrate %5f, wchange %%%d.%df, angledelta %4.1f deg\n', ...
step, lrate, places+1,places, degconst*angledelta);
else
ps = sprintf('step %d - lrate %5f, wchange %%%d.%df, angledelta %4.1f deg, %d subgauss\n',...
step, lrate, degconst*angledelta,...
places+1,places, (ncomps-sum(diag(signs)))/2);
end
elseif ~extended
ps = sprintf('step %d - lrate %5f, wchange %%%d.%df\n',...
step, lrate, places+1,places );
else
ps = sprintf('step %5d - lrate %5f, wchange %%%d.%df, %d subgauss\n',...
step, lrate, places+1,places, (ncomps-sum(diag(signs)))/2);
end % step > 2
fprintf('step %d - lrate %8.8f, wchange %8.8f, angledelta %3.1f deg, loglik %6.4f, nsub = %d\n', ...
step, lrate, change, degconst*angledelta, loglik(step), sum(diag(signs)==-1));
% fprintf(ps,change); % <---- BUG !!!!
end; % if verbose
%
%%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
changes = [changes change];
oldweights = weights;
%
%%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if degconst*angledelta > annealdeg,
lrate = lrate*annealstep; % anneal learning rate
olddelta = delta; % accumulate angledelta until
oldchange = change; % annealdeg is reached
elseif step == 1 % on first step only
olddelta = delta; % initialize
oldchange = change;
end
%
%%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if step >2 & change < nochange, % apply stopping rule
laststep=step;
step=maxsteps; % stop when weights stabilize
elseif change > DEFAULT_BLOWUP, % if weights blow up,
lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying
end; % with a smaller learning rate
end; % end if weights in bounds
end; % end training %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~laststep
laststep = step;
end;
lrates = lrates(1,1:laststep); % truncate lrate history vector
%
%%%%%%%%%%%%%% Orient components towards max positive activation %%%%%%
%
if strcmp(posactflag,'on')
[activations,winvout,weights] = posact(data,weights);
% changes signs of activations and weights to make activations
% net rms-positive
else
activations = weights*data;
end
%
%%%%%%%%%%%%%% If pcaflag, compose PCA and ICA matrices %%%%%%%%%%%%%%%
%
if strcmp(pcaflag,'on')
fprintf('Composing the eigenvector, weights, and sphere matrices\n');
fprintf(' into a single rectangular weights matrix; sphere=eye(%d)\n'...
,chans);
weights= weights*sphere*eigenvectors(:,1:ncomps)';
sphere = eye(urchans);
end
%
%%%%%% Sort components in descending order of max projected variance %%%%
%
if verbose,
fprintf(...
'Sorting components in descending order of mean projected variance ...\n');
end
%
%%%%%%%%%%%%%%%%%%%% Find mean variances %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
meanvar = zeros(ncomps,1); % size of the projections
if ncomps == urchans % if weights are square . . .
winv = inv(weights*sphere);
else
fprintf('Using pseudo-inverse of weight matrix to rank order component projections.\n');
winv = pinv(weights*sphere);
end
for s=1:ncomps
if verbose,
fprintf('%d ',s); % construct single-component data matrix
end
% project to scalp, then add row means
compproj = winv(:,s)*activations(s,:);
meanvar(s) = mean(sum(compproj.*compproj)/(size(compproj,1)-1));
% compute mean variance
end % at all scalp channels
if verbose,
fprintf('\n');
end
%
%%%%%%%%%%%%%% Sort components by mean variance %%%%%%%%%%%%%%%%%%%%%%%%
%
[sortvar, windex] = sort(meanvar);
windex = windex(ncomps:-1:1); % order large to small
meanvar = meanvar(windex);
%
%%%%%%%%%%%%%%%%%%%%% Filter data using final weights %%%%%%%%%%%%%%%%%%
%
if nargout>6, % if activations are to be returned
if verbose,
fprintf('Permuting the activation wave forms ...\n');
end
activations = activations(windex,:);
else
clear activations
end
weights = weights(windex,:);% reorder the weight matrix
bias = bias(windex); % reorder them
signs = diag(signs); % vectorize the signs matrix
signs = signs(windex); % reorder them
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
return
if nargout > 7
u=weights*data + bias*ones(1,frames);
y = zeros(size(u));
for c=1:chans
for f=1:frames
y(c,f) = 1/(1+exp(-u(c,f)));
end
end
end
|
github
|
lcnhappe/happe-master
|
writelocs.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/writelocs.m
| 10,300 |
utf_8
|
f0fb3a6c7068e5ae70ee752f60ad6a76
|
% writelocs() - write a file containing channel location, type and gain information
%
% Usage:
% >> writelocs( chanstruct, filename );
% >> writelocs( chanstruct, filename, 'key', 'val' );
%
% Inputs:
% chanstruct - EEG.chanlocs data structure returned by readlocs() containing
% channel location, type and gain information.
% filename - File name for saving channel location, type and gain information
%
% Optional inputs:
% 'filetype' - ['loc'|'sph'|'sfp'|'xyz'|'polhemus'|'besa'|'chanedit'|'custom']
% Type of the file to write. By default the file type is indicated
% by the file extension.
% 'loc' - An EEGLAB 2-D polar coordinates channel locations file
% Coordinates are theta and radius (see definitions below).
% 'sph' - A Matlab spherical coordinates file (Note: spherical
% coordinates used by Matlab functions are different
% from spherical coordinates used in BESA - see below).
% 'sfp' - EGI cartesian coordinates (not Matlab cartesian - see below).
% 'xyz' - MATLAB/EEGLAB cartesian coordinates (Not EGI cartesian;
% z is toward nose; y is toward left ear; z is toward vertex).
% 'polhemus' or 'polhemusx' - Polhemus electrode location file recorded with
% 'X' on sensor pointing to subject (see below and readelp()).
% 'polhemusy' - Polhemus electrode location file recorded with
% 'Y' on sensor pointing to subject (see below and readelp()).
% 'besa' - BESA'(.elp') spherical coordinate file. (Not MATLAB spherical
% - see below).
% 'chanedit' - EEGLAB channel location files created by pop_chanedit().
% 'custom' - Ascii files with columns in user-defined 'format' (see below).
% 'format' - [cell array] Format of a 'custom' channel location file (see above).
% Default if no file type is defined. The cell array contains
% labels defining the meaning of each column of the input file.
% 'channum' [positive integer] channel number
% 'labels' [string] channel name (no spaces)
% 'theta' [real degrees] 2-D angle in polar coordinates.
% positive => rotating from nose (0) toward left ear
% 'radius' [real] radius in 2-D polar coords (0.5 is disk limits)
% 'X' [real] Matlab-cartesian X coordinate (to nose)
% 'Y' [real] Matlab-cartesian Y coordinate (to left ear)
% 'Z' [real] Matlab-cartesian Z coordinate (to vertex)
% '-X','-Y','-Z' Matlab-cartesian coordinates pointing away from above
% 'sph_theta' [real degrees] Matlab spherical horizontal angle.
% positive => rotating from nose (0) toward left ear.
% 'sph_phi' [real degrees] Matlab spherical elevation angle;
% positive => rotating from horizontal (0) upwards.
% 'sph_radius' [real] distance from head center (unused)
% 'sph_phi_besa' [real degrees] BESA phi angle from vertical.
% positive => rotating from vertex (0) towards right ear.
% 'sph_theta_besa' [real degrees] BESA theta horiz/azimuthal angle.
% positive => rotating from right ear (0) toward nose.
% The input file may also contain other channel information fields
% 'type' channel type: 'EEG', 'MEG', 'EMG', 'ECG', others ...
% 'calib' [real near 1.0] channel calibration value.
% 'gain' [real > 1] channel gain.
% 'custom1' custom field #1.
% 'custom2', 'custom3', 'custom4' more custom fields.
% 'unicoord' - ['on'|'off'] Uniformize all coordinates. Default 'on'.
% 'header' - ['on'|'off'] Add a header comment line with the name of each column.
% Comment lines begin with '%'. Default is 'off'.
% 'customheader' - [string] Add a custom header at the beginning of the file and
% preceded by '%'. If used with 'header' set to 'on',
% the column names will be insterted after the custom header.
% 'elecind' - [integer array] Indices of channels to export.
% Default is all channels.
%
% Note: for file formats, see readlocs() help (>> help readlocs)
%
% Author: Arnaud Delorme, Salk Institute, 16 Dec 2002
%
% See also: readlocs(), readelp()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 28 Feb 2002
%
% 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 writelocs( chans, filename, varargin );
if nargin < 2
help writelocs;
return;
end;
% get infos from readlocs
% -----------------------
%[listtype formatinfo listcolformat formatskip] = readlocs('getinfos');
[chanformat listcolformat] = readlocs('getinfos');
indformat = [];
for index = 1:length(chanformat),
if ~isstr(chanformat(index).importformat)
indformat = [ indformat index ];
end;
if isempty(chanformat(index).skipline), chanformat(index).skipline = 0; end;
end;
listtype = { chanformat(indformat).type };
formatinfo = { chanformat(indformat).importformat };
formatskip = [ chanformat(indformat).skipline ];
g = finputcheck( varargin, ...
{ 'filetype' 'string' listtype 'loc';
'header' 'string' { 'on','off' } 'off';
'customheader' 'string' [] '';
'elecind' 'integer' [1 Inf] [];
'unicoord' 'string' { 'on','off' } 'on';
'format' 'cell' [] {} }, 'writelocs');
if isstr(g), error(g); end;
if strcmpi(g.unicoord, 'on')
disp('Uniformizing coordinates');
chans = convertlocs(chans, 'auto', 'verbose', 'off');
end;
% select channels
% ---------------
if ~isempty(g.elecind)
chans = chans(g.elecind);
end;
% finding types of input
% ----------------------
if isempty(g.format)
indexformat = strmatch(lower(g.filetype), listtype, 'exact');
g.format = formatinfo{indexformat};
g.skipline = formatskip(indexformat);
else
g.skipline = 0;
end;
% creating file
% -------------
fid = fopen(filename, 'w');
% exporting header
% ----------------
if ~isempty(g.customheader)
allstrs = cellstr(g.customheader);
for index=1:length(allstrs)
fprintf(fid, '%s\n', allstrs{index});
end;
end;
if strcmpi(g.header, 'on') | g.skipline == 2
for index=1:length(g.format)
fprintf(fid, '%8s\t', g.format{index});
end;
fprintf(fid, '\n');
for index=1:length(g.format)
fprintf(fid, '%8s\t', char(ones(1,8)*45));
end;
fprintf(fid, '\n');
end;
if g.skipline == 1
fprintf(fid, '%d\n', length(chans));
end;
% writing infos
% -------------
for indexchan = 1:length(chans)
for index=1:length(g.format)
[str, mult] = checkformat(g.format{index});
if strcmpi(str, 'channum')
fprintf(fid, '%d', indexchan);
else
if ~isfield(chans, str)
error([ 'Non-existant field: ''' str '''' ]);
end;
eval( [ 'chanval = chans(indexchan).' str ';' ] );
if isstr(chanval), fprintf(fid, '%8s', chanval);
else
if abs(mult*chanval) > 1E-10
fprintf(fid, '%8s', num2str(mult*chanval,5));
else
fprintf(fid, '%8s', '0');
end;
end;
end;
if index ~= length(g.format)
fprintf(fid, '\t');
end;
end;
fprintf(fid, '\n');
end;
fclose(fid);
return;
% check field format
% ------------------
function [str, mult] = checkformat(str)
mult = 1;
if strcmpi(str, 'labels'), str = lower(str); return; end;
if strcmpi(str, 'channum'), str = lower(str); return; end;
if strcmpi(str, 'theta'), str = lower(str); return; end;
if strcmpi(str, 'radius'), str = lower(str); return; end;
if strcmpi(str, 'sph_theta'), str = lower(str); return; end;
if strcmpi(str, 'sph_phi'), str = lower(str); return; end;
if strcmpi(str, 'sph_radius'), str = lower(str); return; end;
if strcmpi(str, 'sph_theta_besa'), str = lower(str); return; end;
if strcmpi(str, 'sph_phi_besa'), str = lower(str); return; end;
if strcmpi(str, 'gain'), str = lower(str); return; end;
if strcmpi(str, 'calib'), str = lower(str); return; end;
if strcmpi(str, 'type') , str = lower(str); return; end;
if strcmpi(str, 'X'), str = upper(str); return; end;
if strcmpi(str, 'Y'), str = upper(str); return; end;
if strcmpi(str, 'Z'), str = upper(str); return; end;
if strcmpi(str, '-X'), str = upper(str(2:end)); mult = -1; return; end;
if strcmpi(str, '-Y'), str = upper(str(2:end)); mult = -1; return; end;
if strcmpi(str, '-Z'), str = upper(str(2:end)); mult = -1; return; end;
if strcmpi(str, 'custum1'), return; end;
if strcmpi(str, 'custum2'), return; end;
if strcmpi(str, 'custum3'), return; end;
if strcmpi(str, 'custum4'), return; end;
error(['writelocs: undefined field ''' str '''']);
|
github
|
lcnhappe/happe-master
|
env.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/env.m
| 3,005 |
utf_8
|
40959ed7c77b4d587e2986bebd89b254
|
% env() - return envelope of rows of a data matrix, or optionally
% of the data interpolated to a different sampling rate.
% Usage:
% >> envdata = env(data);
% >> envdata = env(data, timelimits, timearray);
%
% Inputs:
% data - (nchannels,ntimepoints) data array
%
% Optional Inputs:
% timelimits - (start_time, end_time) timelimits (default: none required)
% timearray - Optional times array to interpolate the data (default: none)
%
% Outputs:
% envdata - A (2,timepoints) array containing the "envelope" of
% a multichannel data set = the maximum and minimum values,
% across all the channels, at each time point. That is,
% >> envdata = [max(data');min(data')];
%
% Author: Scott Makeig & Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: ENVTOPO
% Scott Makeig & Arnaud Delorme - CNL / Salk Institute, La Jolla 8/8/97
%
% 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
% 2001 - extrapolation -ad
% 01-25-02 reformated help & license -ad
function envdata = env(data, timelimits, timearray )
maxdata = max(data);
mindata = min(data);
% extrapolate these values if necessary
% -------------------------------------
if nargin > 2
timelimits = timelimits(:)'; % make row vector
if size(timelimits,2)~=2 | size(timelimits,2)~=2
error('timelimits array must be a [start_time, end_time] vector')
end
X = linspace(timelimits(1),timelimits(2),length(maxdata)); % x-axis description (row vector)
Y = ones(1,size(X,2));
if size(timearray,1)>1 & size(timearray,2)>1
error('timearray must be a vector')
end
Xi = timearray(:)'; % make a row vector
Yi = ones(1,length(timearray));
try
[tmp1,tmp2,Zi] = griddata(Y, X, maxdata, Yi, Xi, 'v4'); % interpolate data
maxdata = Zi;
[tmp1,tmp2,Zi] = griddata(Y, X, mindata, Yi, Xi, 'v4'); % interpolate data
mindata = Zi;
catch
disp('Warning, "v4" interpolation failed, using linear interpolation instead (probably running Octave)');
[tmp1,tmp2,Zi] = griddata(Y, X, maxdata, Yi, Xi, 'linear'); % interpolate data
maxdata = Zi;
[tmp1,tmp2,Zi] = griddata(Y, X, mindata, Yi, Xi, 'linear'); % interpolate data
mindata = Zi;
end
end;
envdata = [maxdata;mindata];
return;
|
github
|
lcnhappe/happe-master
|
uiputfile2.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/uiputfile2.m
| 2,674 |
utf_8
|
3b31fa4d223e9408a8660905b763639a
|
% uiputfile2() - same as uigputfile but remember folder location.
%
% Usage: >> uiputfile2(...)
%
% Inputs: Same as uiputfile
%
% Author: Arnaud Delorme & Hilit Serby, Scott Makeig, SCCN, UCSD, 2004
% Thanks to input from Bas Kortmann
%
% Copyright (C) Arnaud Delorme & Hilit Serby, Scott Makeig, SCCN, UCSD, 2004
% 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 varargout = uiputfile2(varargin);
if nargin < 1
help uiputfile2;
return;
end;
% remember old folder
%% search for the (mat) file which contains the latest used directory
% -------------------
olddir = pwd;
try,
eeglab_options;
if option_rememberfolder
tmp_fld = getenv('TEMP');
if isempty(tmp_fld) & isunix
if exist('/tmp') == 7
tmp_fld = '/tmp';
end;
end;
if exist(fullfile(tmp_fld,'eeglab.cfg'))
load(fullfile(tmp_fld,'eeglab.cfg'),'Path','-mat');
s = ['cd([''' Path '''])'];
if exist(Path) == 7, eval(s); end;
end;
end;
catch, end;
%% Show the open dialog and save the latest directory to the file
% ---------------------------------------------------------------
[varargout{1} varargout{2}] = uiputfile(varargin{:});
try,
if option_rememberfolder
if varargout{1} ~= 0
Path = varargout{2};
try, save(fullfile(tmp_fld,'eeglab.cfg'),'Path','-mat','-V6'); % Matlab 7
catch,
try, save(fullfile(tmp_fld,'eeglab.cfg'),'Path','-mat');
catch, error('uigetfile2: save error, out of space or file permission problem');
end
end
if isunix
eval(['cd ' tmp_fld]);
system('chmod 777 eeglab.cfg');
end
end;
end;
catch, end;
cd(olddir)
|
github
|
lcnhappe/happe-master
|
entropy_rej.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/entropy_rej.m
| 3,641 |
utf_8
|
e83760bd8d661f0883b5b955383fa06b
|
% entropy_rej() - calculation of entropy of a 1D, 2D or 3D array and
% rejection of odd last dimension values of the input data array
% using the discrete entropy of the values in that dimension
% (and using the probability distribution of all columns).
%
% Usage:
% >> [entropy rej] = entropy_rej( signal, threshold, entropy, normalize, discret);
%
% Inputs:
% signal - one dimensional column vector of data values, two
% dimensional column vector of values of size
% sweeps x frames or three dimensional array of size
% component x sweeps x frames. If three dimensional,
% all components are treated independently.
% threshold - Absolute threshold. If normalization is used then the
% threshold is expressed in standard deviation of the
% mean. 0 means no threshold.
% entropy - pre-computed entropy_rej (only perform thresholding). Default
% is the empty array [].
% normalize - 0 = do not not normalize entropy. 1 = normalize entropy.
% Default is 0.
% discret - discretization variable for calculation of the
% discrete probability density. Default is 1000 points.
%
% Outputs:
% entropy - entropy (normalized or not) of the single data trials
% (same size as signal without the last dimension)
% rej - rejection matrix (0 and 1, size of number of rows)
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: realproba()
% 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 [ent, rej] = entropy_rej( signal, threshold, oldentropy_rej, normalize, discret );
if nargin < 1
help entropy_rej;
return;
end;
if nargin < 2
threshold = 0;
end;
if nargin < 3
oldentropy_rej = [];
end;
if nargin < 4
normalize = 0;
end;
if nargin < 5
discret = 1000;
end;
% threshold = erfinv(threshold);
if size(signal,2) == 1 % transpose if necessary
signal = signal';
end;
[nbchan pnts sweeps] = size(signal);
ent = zeros(nbchan,sweeps);
if ~isempty( oldentropy_rej ) % speed up the computation
ent = oldentropy_rej;
else
for rc = 1:nbchan
% COMPUTE THE DENSITY FUNCTION
% ----------------------------
[ dataProba sortbox ] = realproba( signal(rc, :), discret );
% compute all entropy
% -------------------
for index=1:sweeps
datatmp = dataProba((index-1)*pnts+1:index*pnts);
ent(rc, index) = - sum( datatmp .* log( datatmp ) );
end;
end;
% normalize the last dimension
% ----------------------------
if normalize
switch ndims( signal )
case 2, ent = (ent-mean(ent)) / std(ent);
case 3, ent = (ent-mean(ent,2)*ones(1,size(ent,2)))./ ...
(std(ent,0,2)*ones(1,size(ent,2)));
end;
end;
end
% reject
% ------
if threshold ~= 0
rej = abs(ent) > threshold;
else
rej = zeros(size(ent));
end;
return;
|
github
|
lcnhappe/happe-master
|
quantile.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/quantile.m
| 2,747 |
utf_8
|
1b58a5e543b13e76f3f75afd5f5f9219
|
% quantile() - computes the quantiles of the data sample from a distribution X
%
% Description:
% If F is the cumulative distribution function (CDF) of X,
% the p-th-quantile Qp of distribution X is the value for which holds
% F(x) < p, for x < Qp, and
% F(x) >= p, for x >= Qp.
% for example, for p = 0.5, Qp is the median of X. p must be in [0..1].
%
% Usage:
% >> q = quantile( data, pc );
%
% Inputs:
% data - vector of observations
% pc - the quantiles will be estimated at the values in pc [0..1]
%
% Outputs:
% q - pc-th-quantiles of the distribution generating the observation
%
% Authors: Scott Makeig & Luca Finelli, CNL/Salk Institute-SCCN, August 21, 2002
%
% Note: this function overload the function from the statistics toolbox. In
% case the statistic toolbox is present, the function from the
% statistics toolbox is being called instead.
%
% See also:
% pop_sample(), eeglab()
% Copyright (C) Scott Makeig & Luca Finelli, CNL/Salk Institute-SCCN, August 21, 2002
%
% 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 q = quantile(data,varargin);
% detect overloaded method in stat toolbox
curPath = fileparts(which('quantile'));
rmpath(curPath);
path2 = fileparts(which('quantile'));
addpath(curPath);
if ~isempty(path2)
addpath(path2);
q = quantile(data,varargin{:});
return;
else
pc = varargin{1};
end;
if nargin < 2
help quantile;
return;
end;
[prows pcols] = size(pc);
if prows ~= 1 & pcols ~= 1
error('pc must be a scalar or a vector.');
end
if any(pc > 1) | any(pc < 0)
error('pc must be between 0 and 1');
end
[i,j] = size(data);
sortdata = sort(data);
if i==1 | j==1 % if data is a vector
i = max(i,j); j = 1;
if i == 1,
fprintf(' quantile() note: input data is a single scalar!\n')
q = data*ones(length(pc),1); % if data is scalar, return it
return;
end
sortdata = sortdata(:);
end
pt = [0 ((1:i)-0.5)./i 1];
sortdata = [min(data); sortdata; max(data)];
q = interp1(pt,sortdata,pc);
|
github
|
lcnhappe/happe-master
|
eventlock.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/eventlock.m
| 6,609 |
utf_8
|
6794a0982011ab97d748d362169961d5
|
% eventlock() - DEPRECATED: Please use eegalign() instead.
% eventlock() - Time lock data epochs to specified event frames or event x-values.
% Use to timelock existing data epochs to reaction times or other events
%
% Usage:
% >> [dataout,medval,shiftframes] = eventlock(data,frames,eventframes,medval);
% >> [dataout,medval,shiftframes] = eventlock(data,xvals,eventvals,medval);
%
% Inputs for multi-channel data:
% data = input data, size(chans,frames*epochs)
% frames = scalar, frames per epoch {0 -> data length}
% eventframes = time locking event frames, size(1,epochs)
% medval = median eventframe to align to {default: median(eventvals)}
%
% Inputs for single-channel data:
% data = input data, size(frames, epochs)
% xvals = vector of epoch time-values, size(1,frames)
% OR xvals = [startval nframes srate] (ms N Hz)
% eventvals = x-values of time locking events, size(1,epochs)
% medval = median event time to align to {default: median(eventvals)}
%
% Outputs:
% dataout = shifted/sorted data out; size(dataout) = size(data)
% medval = median eventval (time or frame). Data is aligned to this.
% shifts = number of frames shifted for each epoch
% (Note: shift > 0 means shift forward|right)
%
% Note: Missing values are filled with NaN. Some toolbox functions
% ( timef(), crossf(), crosscoher() ) handle NaNs correctly.
% To truncate to non-NaN values, use
% >> dataout = matsel(dataout,frames,...
% 1+max(shifts(find(shifts>=0))):frames+min(shifts(find(shifts<=0))));
%
% Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 8/20/99
% Copyright (C) 8/20/99 Scott Makeig, SCCN/INC/UCSD, [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
% 8/23/99 debugged right shifts -sm
% 8/25/99 allowed single- or multiple-channel data -sm
% 3/9/00 fixed order of dims in help msg -sm & ev
% 01-25-02 reformated help & license -ad
function [data,medval,shifts] = eventlock(data,arg2,eventvals,medval)
VERBOSE=0;
%
%%%%%%%%%%%%%% Reshape data to (frames,ntrials) %%%%%%%%%%%%%
%
if nargin < 3
help eventlock
return
end
MULTICHANNEL = 0;
if length(arg2) == 1 % then assume multi-channel: size(chans,epochs*frames)
MULTICHANNEL = 1;
if arg2==0
frames = length(eventvals); % default 1 epoch
else
frames = arg2;
end
xvals = 1:frames;
else % assume single-channel: size(frames,epochs)
MULTICHANNEL = 0;
xvals = arg2;
if length(xvals) ~= 3
frames = length(xvals);
else
frames = xvals(2);
end
end
rows = size(data,1);
if MULTICHANNEL
ntrials = size(data,2)/frames;
else
ntrials = size(data,2);
end
if length(xvals) == 3 % assume [startval nvals srate] format
srate = xvals(3);
endval = xvals(1)+(xvals(2)-1)*xvals(3)+1e-16;
xvals = xvals(1):1000/xvals(3):endval;
xvals = xvals(1:frames); % make sure of length!
else
srate = 1000/(xvals(2)-xvals(1));
end
if MULTICHANNEL
if frames*ntrials ~= size(data,2)
fprintf(...
'Input data length (%d) is not a multiple of the eventframes length (%d).\n',...
size(data,2), frames);
return
end
elseif frames~= size(data,1)
fprintf(...
'Input data frames (%d) is not equal to xvals length (%d).\n',...
size(data,1), length(xvals));
return
end
if length(eventvals) ~= ntrials
fprintf(...
'eventlock(): Number of eventvals (%d) must equal number of trials (%d).\n',...
length(eventvals), ntrials);
return
end
if MULTICHANNEL
fprintf('Input data is %d channels by %d frames * %d trials.\n',...
rows,frames,ntrials);
else
fprintf('Input data is %d frames by %d trials.\n',...
frames,ntrials);
end
%
%%%%%%%%%%%%%%%%%%% Align data to eventvals %%%%%%%%%%%%%%%%%%%
%
if MULTICHANNEL
frames = rows*frames;
data = reshape(data,frames,ntrials);
end % NB: data is now size((chans*)frames,ntrials)
aligndata=repmat(nan,frames,ntrials); % begin with matrix of NaN's
shifts = zeros(1,ntrials);
if ~exist('medval') | isempty(medval)
medval= median(eventvals);
end
[medval medx] = min(abs(medval-xvals));
medval = xvals(medx);
if MULTICHANNEL
fprintf('Aligning data to median event frame %g.\n',medval);
else % SINGLE CHANNEL
fprintf('Aligning data to median event time %g.\n',medval);
end
for i=1:ntrials, %%%%%%%%% foreach trial %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% idx = eventvals(i);
% shft = round(medx-idx);
[tmpx idx] = min(abs(xvals-eventvals(i)));
shft = medx-idx;
if VERBOSE;fprintf('Trial %d -shift = %d\n',i,shft);end
shifts(i) = shft;
if MULTICHANNEL
shft = shft*rows; % shift in multiples of chans
end
if shft>0, % shift right %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if frames > shft
aligndata((1+shft):end,i) = data(1:(end-shft),i);
else
fprintf('No eventlocked data for epoch %d - required shift too large!\n',i);
end
elseif shft < 0 % shift left %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if frames > -shft
aligndata(1:(end+shft),i) = data((1-shft):end,i);
else
fprintf('No eventlocked data for epoch %d - required shift too large.\n',i);
end
else % shft == 0 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
aligndata(:,i) = data(:,i);
end
end % end trial %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('Shifted trials by %d to %d frames.\n',min(shifts),max(shifts));
if ~MULTICHANNEL
fprintf(' %g to %g msec.\n',...
1000/srate*min(shifts),1000/srate*max(shifts));
end
data = aligndata; % now data is aligned to sortvar
if MULTICHANNEL
data = reshape(data,rows,frames/rows*ntrials); % demultiplex channels
end
|
github
|
lcnhappe/happe-master
|
lookupchantemplate.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/lookupchantemplate.m
| 988 |
utf_8
|
16a6821223a3b7f6603677a26afeaecd
|
% lookupchantemplate - look up channel template.
%
% Usage:
% [ found transform ] = lookupchantemplate( filename, template_struct);
%
% Inputs:
% filename - channel location file name
% template_struct - template strcuture as defined in dipfitdefs
%
% Outputs:
% found - [0|1] 1 if a transformation was found for this template
% transform - [array] tranditional tailairach transformation
%
% Author: Arnaud Delorme, SCCN, INC, 2007
function [allkeywordstrue, transform] = lookupchantemplate(chanfile, tmpl);
if nargin < 2
help lookupchantemplate;
return;
end;
allkeywordstrue = 0;
transform = [];
for ind = 1:length(tmpl)
allkeywordstrue = 1;
if isempty(tmpl(ind).keywords), allkeywordstrue = 0; end;
for k = 1:length(tmpl(ind).keywords)
if isempty(findstr(lower(chanfile), lower(tmpl(ind).keywords{k}))), allkeywordstrue = 0; end;
end;
if allkeywordstrue,
transform = tmpl(ind).transform;
break;
end;
end;
|
github
|
lcnhappe/happe-master
|
readbdf.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/readbdf.m
| 3,261 |
utf_8
|
e0daaa58677f9efc8fade44506ade229
|
% readbdf() - Loads selected Records of an EDF or BDF File (European Data Format
% for Biosignals) into MATLAB. This function is outdate
% Use the functions sopen() and sread() instead
%
% This program is deprecated (obsolete). Use the sopen() and sread()
% function instead
% Version 2.11
% 03.02.1998
% Copyright (c) 1997,98 by Alois Schloegl
% [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.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This program has been modified from the original version for .EDF files
% The modifications are to the number of bytes read on line 53 (from 2 to
% 3) and to the type of data read - line 54 (from int16 to bit24). Finally the name
% was changed from readedf to readbdf
% T.S. Lorig Sept 6, 2002
%
% Header modified for eeglab() compatibility - Arnaud Delorme 12/02
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [DAT,S]=readbdf(DAT,Records,Mode)
disp('This function is outdated');
disp('Use the functions sopen() and sread() instead');
return;
if nargin<3 Mode=0; end;
EDF=DAT.Head;
RecLen=max(EDF.SPR);
S=NaN*zeros(RecLen,EDF.NS);
DAT.Record=zeros(length(Records)*RecLen,EDF.NS);
DAT.Valid=uint8(zeros(1,length(Records)*RecLen));
DAT.Idx=Records(:)';
for nrec=1:length(Records),
NREC=(DAT.Idx(nrec)-1);
if NREC<0 fprintf(2,'Warning READEDF: invalid Record Number %i \n',NREC);end;
fseek(EDF.FILE.FID,(EDF.HeadLen+NREC*EDF.AS.spb*3),'bof');
[s, count]=fread(EDF.FILE.FID,EDF.AS.spb,'bit24');
try,
S(EDF.AS.IDX2)=s;
catch,
error('File is incomplete (try reading begining of file)');
end;
%%%%% Test on Over- (Under-) Flow
% V=sum([(S'==EDF.DigMax(:,ones(RecLen,1))) + (S'==EDF.DigMin(:,ones(RecLen,1)))])==0;
V=sum([(S(:,EDF.Chan_Select)'>=EDF.DigMax(EDF.Chan_Select,ones(RecLen,1))) + ...
(S(:,EDF.Chan_Select)'<=EDF.DigMin(EDF.Chan_Select,ones(RecLen,1)))])==0;
EDF.ERROR.DigMinMax_Warning(find(sum([(S'>EDF.DigMax(:,ones(RecLen,1))) + (S'<EDF.DigMin(:,ones(RecLen,1)))]')>0))=1;
% invalid=[invalid; find(V==0)+l*k];
if floor(Mode/2)==1
for k=1:EDF.NS,
DAT.Record(nrec*EDF.SPR(k)+(1-EDF.SPR(k):0),k)=S(1:EDF.SPR(k),k);
end;
else
DAT.Record(nrec*RecLen+(1-RecLen:0),:)=S;
end;
DAT.Valid(nrec*RecLen+(1-RecLen:0))=V;
end;
if rem(Mode,2)==0 % Autocalib
DAT.Record=[ones(RecLen*length(Records),1) DAT.Record]*EDF.Calib;
end;
DAT.Record=DAT.Record';
return;
|
github
|
lcnhappe/happe-master
|
readedf.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/readedf.m
| 3,038 |
utf_8
|
1d2f12e3aec361bb64c8efdaa0d89e50
|
% readedf() - read eeg data in EDF format.
%
% Usage:
% >> [data,header] = readedf(filename);
%
% Input:
% filename - file name of the eeg data
%
% Output:
% data - eeg data in (channel, timepoint)
% header - structured information about the read eeg data
% header.length - length of header to jump to the first entry of eeg data
% header.records - how many frames in the eeg data file
% header.duration - duration (measured in second) of one frame
% header.channels - channel number in eeg data file
% header.channelname - channel name
% header.transducer - type of eeg electrods used to acquire
% header.physdime - details
% header.physmin - details
% header.physmax - details
% header.digimin - details
% header.digimax - details
% header.prefilt - pre-filterization spec
% header.samplerate - sampling rate
%
% Author: Jeng-Ren Duann, CNL/Salk Inst., 2001-12-21
% Copyright (C) Jeng-Ren Duann, CNL/Salk Inst., 2001-12-21
%
% 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
% 03-21-02 editing header, add help -ad
function [data,header] = readedf(filename);
if nargin < 1
help readedf;
return;
end;
fp = fopen(filename,'r','ieee-le');
if fp == -1,
error('File not found ...!');
return;
end
hdr = setstr(fread(fp,256,'uchar')');
header.length = str2num(hdr(185:192));
header.records = str2num(hdr(237:244));
header.duration = str2num(hdr(245:252));
header.channels = str2num(hdr(253:256));
header.channelname = setstr(fread(fp,[16,header.channels],'char')');
header.transducer = setstr(fread(fp,[80,header.channels],'char')');
header.physdime = setstr(fread(fp,[8,header.channels],'char')');
header.physmin = str2num(setstr(fread(fp,[8,header.channels],'char')'));
header.physmax = str2num(setstr(fread(fp,[8,header.channels],'char')'));
header.digimin = str2num(setstr(fread(fp,[8,header.channels],'char')'));
header.digimax = str2num(setstr(fread(fp,[8,header.channels],'char')'));
header.prefilt = setstr(fread(fp,[80,header.channels],'char')');
header.samplerate = str2num(setstr(fread(fp,[8,header.channels],'char')'))./header.duration;
fseek(fp,header.length,-1);
data = fread(fp,'int16');
fclose(fp);
data = reshape(data,header.duration*header.samplerate(1),header.channels,header.records);
temp = [];
for i=1:header.records,
temp = [temp data(:,:,i)'];
end
data = temp;
|
github
|
lcnhappe/happe-master
|
loadeeg.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/loadeeg.m
| 10,210 |
utf_8
|
3148017a8fe87eb6fa0f26fb433c1800
|
% loadeeg() - load a binary data file in Neuroscan .eeg file format.
%
% Usage:
% >> signal = loadeeg(filename);
% >> [signal, accept, typeeeg, rt, response, chan_names, pnts, ...
% ntrials, srate, xmin, xmax] = loadeeg( filename, chanlist, ...
% triallist, typerange, accepttype, rtrange, responsetype);
%
% Inputs:
% filename - [string] Input Neuroscan .eeg file
% chanlist - [integer array] Only import selected channels
% Ex: [3,4:10] {default: 'all'}
% triallist - [integer array] Only import selected trials {default: import all}
% typerange - [integer array] Only import trials of selected type
% {default: import all}
% accepttype - [integer array] Only import trials with the selected
% 'accept' field values {default: import all}
% rtrange - [float array] [min max] (ms) Only import trials with subject
% reaction times in this range {default: import all}
% responsetype - [integer array] Only import trials with selected
% response type values {default: import all}
% format - ['short'|'int32'|'auto'] data format. Neuroscan v4.3+ assume 32-bit data
% while older versions assume 16-bit. {default: 'auto' = Determine}
%
% Outputs:
% signal - Output signal of size (trials, points)
% accept - [1/0] vector of values for the accept field (one per trial)
% typeeeg - [Integer] values for the accept type (size 1,trials)
% rt - [float] values for the accept rt (size trials)
% response - [Integer] values for the accept response (size 1,trials)
% chan_names - ['string' array] channel names
% pnts - Number of time points per trial
% ntrials - Number of trials
% srate - Sampling rate (Hz)
% xmin - Trial start latency (ms)
% xmax - Trial end latency (ms)
%
% Example:
% % Load .eeg data into an array named 'signal'
% >> [signal]=loadeeg( 'test.eeg' );
% % Plot the signal in the first channel, first trial
% >> plot( signal(1,:) );
%
% Author: Arnaud Delorme, CNL, Salk Institute, 2001
%
% See also: pop_loadeeg(), eeglab()
% .eeg binary file format
% data are organised into an array of Number_of_electrode x (Number_of_points_per_trial*Number_of_sweeps)
% for a file with 32 electrodes, 700 points per trial and 300 sweeps, the resulting array is
% of 32 collumn and 700*300 rows (300 consecutive blocs of 700 points)
% 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 [signal, accept, typeeeg, rt, response, chan_names, pnts, ...
nsweeps, rate, xmin, xmax]=loadeeg( FILENAME, chanlist, ...
TrialList, typerange, acceptype, rtrange, responsetype, format)
if nargin<1
fprintf('Not enought arguments\n');
help loadeeg
return;
end;
if nargin<2 chanlist='all'; end;
if nargin<3 TrialList='all'; end;
if nargin<4 typerange='all'; end;
if nargin<5 acceptype='all'; end;
if nargin<6 rtrange ='all'; end;
if nargin<7 responsetype='all'; end;
if nargin<8 format='auto'; end;
format = lower(format);
if ~strcmpi(format, 'short') && ~strcmpi(format, 'int32') && ~strcmpi(format, 'auto'), error('loadeeg: format error'); end;
% open file for reading
% ---------------------
fid=fopen(FILENAME,'r','ieee-le');
if fid<0
fprintf('Error LOADEEG: File %s not found\n', FILENAME);
return;
end;
% determine the actual file format if auto is requested
%------------------------------------------------------
if strcmpi(format, 'auto')
format = 'short';
fseek(fid,12,'bof');
nextfile = fread(fid,1,'long');
if (nextfile > 0)
fseek(fid,nextfile+52,'bof');
is32bit = fread(fid,1,'char');
if (is32bit == 1)
format = 'int32'
end;
end;
frewind(fid);
end;
% read general part of the erp header and set variables
% -----------------------------------------------------
rev = char(fread(fid, 20, 'uchar'))'; % revision number
erp = fread(fid, 342, 'uchar'); % skip the firsts 362 from BOF (368 bytes in orginal comment?)
nsweeps = fread(fid, 1, 'ushort'); % number of sweeps
erp = fread(fid, 4, 'uchar'); % skip 4 bytes
pnts= fread(fid, 1, 'ushort'); % number of point per waveform
chan= fread(fid, 1, 'ushort'); % number of channels
erp = fread(fid, 4, 'uchar'); % skip 4 bytes
rate= fread(fid, 1, 'ushort'); % sample rate (Hz)
erp = fread(fid, 127, 'uchar'); % skip 127 bytes
xmin= fread(fid, 1, 'float32'); % in s
xmax= fread(fid, 1, 'float32'); % in s
erp = fread(fid, 387, 'uchar'); % skip 387 bytes
fprintf('number of channels : %d\n', chan);
fprintf('number of points per trial : %d\n', pnts);
fprintf('sampling rate (Hz) : %f\n', rate);
fprintf('xmin (s) : %f\n', xmin);
fprintf('xmax (s) : %f\n', xmax);
% read electrode configuration
% ----------------------------
fprintf('Electrode configuration\n');
for elec = 1:chan
channel_label_tmp = fread(fid, 10, 'uchar');
chan_names(elec,:) = channel_label_tmp';
for index = 2:9 if chan_names(elec,index) == 0 chan_names(elec,index)=' '; end; end;
erp = fread(fid, 47-10, 'uchar');
baseline(elec) = fread(fid, 1, 'ushort');
erp = fread(fid, 10, 'uchar');
sensitivity(elec) = fread(fid, 1, 'float32');
erp = fread(fid, 8, 'uchar');
calib(elec) = fread(fid, 1, 'float32');
fprintf('%s: baseline: %d\tsensitivity: %f\tcalibration: %f\n', ...
char(chan_names(elec,1:4)), baseline(elec), sensitivity(elec), calib(elec));
factor(elec) = calib(elec) * sensitivity(elec) / 204.8;
end;
%fprintf('Electrode configuration\n');
%for elec = 1:chan
% erp = fread(fid, 47, 'uchar');
% baseline(elec) = fread(fid, 1, 'ushort');
% erp = fread(fid, 10, 'uchar');
% sensitivity(elec) = fread(fid, 1, 'float32');
% erp = fread(fid, 8, 'uchar');
% calib(elec) = fread(fid, 1, 'float32');
% fprintf('baseline: %d\tsensitivity: %f\tcalibration: %f\n', baseline(elec), sensitivity(elec), calib(elec));
% factor(elec) = calib(elec) * sensitivity(elec) / 204.8;
%end;
xsize = chan * pnts;
buf_size = chan * pnts ; % size in shorts
% set tags for conditions
% -----------------------
if isstr(chanlist) && strcmpi(chanlist, 'all'), chanlist = [1:chan]; end;
if isstr(TrialList) && strcmpi(TrialList, 'all'), trialtagI = 1; else trialtagI = 0; end;
if isstr(acceptype) && strcmpi(acceptype, 'all'), acceptagI = 1; else acceptagI = 0; end;
if isstr(typerange) && strcmpi(typerange, 'all'), typetagI = 1; else typetagI = 0; end;
if isstr(responsetype) && strcmpi(responsetype, 'all'), responsetagI = 1; else responsetagI = 0; end;
if isstr(rtrange) && strcmpi(rtrange, 'all'), rttagI = 1; else rttagI = 0; end;
count_selected = 1;
fprintf('Reserving array (can take some time)\n');
if isstr(TrialList)
signal = zeros( chan, pnts*nsweeps);
else
signal = zeros( chan, pnts*length(TrialList));
end;
fprintf('Array reserved, scanning file\n');
for sweep = 1:nsweeps
% read sweeps header
% ------------------
s_accept = fread(fid, 1, 'uchar');
s_type = fread(fid, 1, 'ushort');
s_correct = fread(fid, 1, 'ushort');
s_rt = fread(fid, 1, 'float32');
s_response = fread(fid, 1, 'ushort');
s_reserved = fread(fid, 1, 'ushort');
unreaded_buf = 1;
% store the sweep or reject the sweep
% -----------------------------------
if trialtagI trialtag = 1; else trialtag = ismember_bc(sweep, TrialList); end;
if acceptagI acceptag = 1; else acceptag = ismember(s_accept, acceptype); end;
if typetagI typetag = 1; else typetag = ismember(s_type, typerange); end;
if responsetagI responsetag = 1; else responsetag = ismember_bc(s_response, responsetype); end;
if rttagI rttag = 1; else rttag = ismember(s_rt, rtrange); end;
if typetag
if trialtag
if acceptag
if responsetag
if rttag
buf = fread(fid, [chan pnts], format);
unreaded_buf = 0;
% copy information to array
% -------------------------
accept(count_selected) = s_accept;
typeeeg(count_selected) = s_type;
rt(count_selected) = s_rt;
response(count_selected) = s_response;
% demultiplex the data buffer and convert to microvolts
% -----------------------------------------------------
for elec = 1:chan
buf(elec, :) = (buf(elec, :)-baseline(elec)-0.0)*factor(elec);
end;
try
signal(:,[((count_selected-1)*pnts+1):count_selected*pnts]) = buf;
count_selected = count_selected + 1;
if not(mod(count_selected,10)) fprintf('%d sweeps selected out of %d\n', count_selected-1, sweep); end;
catch,
disp('Warning: File truncated, aborting file read.');
count_selected = count_selected + 1;
break;
end;
end;
end;
end;
end;
end;
if unreaded_buf
if strcmpi(format, 'short'), fseek(fid, buf_size*2, 'cof');
else fseek(fid, buf_size*4, 'cof');
end;
end;
end;
nsweeps = count_selected-1;
fclose(fid);
% restrincting array
% ---------------------------------------
fprintf('rereservation of variables\n');
signal = signal(chanlist, 1:(count_selected-1)*pnts);
chan_names = chan_names(chanlist,:);
return;
|
github
|
lcnhappe/happe-master
|
textsc.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/textsc.m
| 1,965 |
utf_8
|
8c2c0fcfccd2bafb12b0c76ab0e73b0c
|
% textsc() - places text in screen coordinates and places
% a title at the top of the figure.
%
% Usage:
% H = textsc(X,Y,TXT) places the text string, TXT
% at the normalized coordinates X and Y. H is the
% handle to the text object.
%
% H = textsc(TXT,'title') places a title at the top
% of the figure window. This is useful when you
% want to place a single title above multiple
% subplots.
%
% Notes: textsc creates an invisible AXES which occupies
% the entire FIGURE. The units of the AXES are
% normalized (range from 0 to 1). textsc checks
% all the children of the current FIGURE to determine
% if an AXES exist which meets these criteria already
% exist. If one does, then it places the text relative
% to that AXES.
%
% Author: John L. Galenski, January 21, 1994
% Written by John L. Galenski III
% All Rights Reserved January 21, 1994
% LDM031695jlg
function H = textsc(x,y,txt);
% Basic error checking
if nargin < 2
y = 'title';
end
% Check to see if AXES already exist
ch = get(gcf,'Children');
if ~isempty(ch)
try
ind = cellfun(@(x)isequal('axes', x), get(ch, 'type'));
catch
ind = cellfun(@(x)isequal('axes', x), {get(ch, 'type')}); % fix Joe Dien bug 1538
end;
if any(ind), ch = gca; end;
end;
ax = findobj(gcf,'Type','axes','Tag','TEXTSC');
if isempty(ax)
ax = axes('Units','Normal','Position',[0 0 1 1], ...
'Visible','Off','Tag','TEXTSC');
else
axes(ax)
end
% Place the text
if isstr(y) && isstr(x) && strcmp(lower(y),'title') % Subplot title
txt = x;
x = .5;
tmp = text('Units','normal','String','tmp','Position',[0 0 0]);
ext = get(tmp,'Extent');
delete(tmp)
H = ext(4);
y = 1 - .60*H;
end
h = text(x,y,txt,'VerticalAlignment','Middle', ...
'HorizontalAlignment','Center','interpreter', 'none' );
% Make the original AXES current
if ~isempty(ch)
set(gcf,'CurrentAxes',ch);
end
% Check for output
if nargout == 1
H = h;
end
|
github
|
lcnhappe/happe-master
|
runica_mlb.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/runica_mlb.m
| 42,615 |
utf_8
|
84b622d9b09d26c3a20c36f5b695f9b6
|
% runica() - Perform Independent Component Analysis (ICA) decomposition
% of input data using the logistic infomax ICA algorithm of
% Bell & Sejnowski (1995) with the natural gradient feature
% of Amari, Cichocki & Yang, or optionally the extended-ICA
% algorithm of Lee, Girolami & Sejnowski, with optional PCA
% dimension reduction. Annealing based on weight changes is
% used to automate the separation process.
% Usage:
% >> [weights,sphere] = runica(data); % train using defaults
% else
% >> [weights,sphere,compvars,bias,signs,lrates,activations] ...
% = runica(data,'Key1',Value1',...);
% Input:
% data = input data (chans,frames*epochs).
% Note that if data consists of multiple discontinuous epochs,
% each epoch should be separately baseline-zero'd using
% >> data = rmbase(data,frames,basevector);
%
% Optional keywords [argument]:
% 'extended' = [N] perform tanh() "extended-ICA" with sign estimation
% N training blocks. If N > 0, automatically estimate the
% number of sub-Gaussian sources. If N < 0, fix number of
% sub-Gaussian comps to -N [faster than N>0] (default|0 -> off)
% 'pca' = [N] decompose a principal component (default -> 0=off)
% subspace of the data. Value is the number of PCs to retain.
% 'ncomps' = [N] number of ICA components to compute (default -> chans or 'pca' arg)
% using rectangular ICA decomposition
% 'sphering' = ['on'/'off'] flag sphering of data (default -> 'on')
% 'weights' = [W] initial weight matrix (default -> eye())
% (Note: if 'sphering' 'off', default -> spher())
% 'lrate' = [rate] initial ICA learning rate (<< 1) (default -> heuristic)
% 'block' = [N] ICA block size (<< datalength) (default -> heuristic)
% 'anneal' = annealing constant (0,1] (defaults -> 0.90, or 0.98, extended)
% controls speed of convergence
% 'annealdeg' = [N] degrees weight change for annealing (default -> 70)
% 'stop' = [f] stop training when weight-change < this (default -> 1e-6
% if less than 33 channel and 1E-7 otherwise)
% 'maxsteps' = [N] max number of ICA training steps (default -> 512)
% 'bias' = ['on'/'off'] perform bias adjustment (default -> 'on')
% 'momentum' = [0<f<1] training momentum (default -> 0)
% 'specgram' = [srate loHz hiHz frames winframes] decompose a complex time/frequency
% transform of the data (Note: winframes must divide frames)
% (defaults [srate 0 srate/2 size(data,2) size(data,2)])
% 'posact' = make all component activations net-positive(default 'on'}
% 'verbose' = give ascii messages ('on'/'off') (default -> 'on')
%
% Outputs: [Note: RO means output in reverse order of projected mean variance
% unless starting weight matrix passed ('weights' above)]
% weights = ICA weight matrix (comps,chans) [RO]
% sphere = data sphering matrix (chans,chans) = spher(data)
% Note that unmixing_matrix = weights*sphere {if sphering off -> eye(chans)}
% compvars = back-projected component variances [RO]
% bias = vector of final (ncomps) online bias [RO] (default = zeros())
% signs = extended-ICA signs for components [RO] (default = ones())
% [ -1 = sub-Gaussian; 1 = super-Gaussian]
% lrates = vector of learning rates used at each training step [RO]
% activations = activation time courses of the output components (ncomps,frames*epochs)
%
% Authors: Scott Makeig with contributions from Tony Bell, Te-Won Lee,
% Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky, Delorme Arnaud,
% CNL/The Salk Institute, La Jolla, 1996-
% Uses: posact()
% Reference (please cite):
%
% Makeig, S., Bell, A.J., Jung, T-P and Sejnowski, T.J.,
% "Independent component analysis of electroencephalographic data,"
% In: D. Touretzky, M. Mozer and M. Hasselmo (Eds). Advances in Neural
% Information Processing Systems 8:145-151, MIT Press, Cambridge, MA (1996).
%
% Toolbox Citation:
%
% Makeig, Scott et al. "EEGLAB: ICA Toolbox for Psychophysiological Research".
% WWW Site, Swartz Center for Computational Neuroscience, Institute of Neural
% Computation, University of San Diego California
% <www.sccn.ucsd.edu/eeglab/>, 2000. [World Wide Web Publication].
%
% For more information:
% http://www.sccn.ucsd.edu/eeglab/icafaq.html - FAQ on ICA/EEG
% http://www.sccn.ucsd.edu/eeglab/icabib.html - mss. on ICA & biosignals
% http://www.cnl.salk.edu/~tony/ica.html - math. mss. on ICA
% Copyright (C) 1996 Scott Makeig et al, SCCN/INC/UCSD, [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
%%%%%%%%%%%%%%%%%%%%%%%%%%% Edit history %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% runica() - by Scott Makeig with contributions from Tony Bell, Te-Won Lee
% Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky et al.
% CNL / Salk Institute 1996-00
% 04-30-96 built from icatest.m and ~jung/.../wtwpwica.m -sm
% 07-28-97 new runica(), adds bias (default on), momentum (default off),
% extended-ICA (Lee & Sejnowski, 1997), cumulative angledelta
% (until lrate drops), keywords, signcount for speeding extended-ICA
% 10-07-97 put acos() outside verbose loop; verbose 'off' wasn't stopping -sm
% 11-11-97 adjusted help msg -sm
% 11-30-97 return eye(chans) if sphering 'off' or 'none' (undocumented option) -sm
% 02-27-98 use pinv() instead of inv() to rank order comps if ncomps < chans -sm
% 04-28-98 added 'posact' and 'pca' flags -sm
% 07-16-98 reduced length of randperm() for kurtosis subset calc. -se & sm
% 07-19-98 fixed typo in weights def. above -tl & sm
% 12-21-99 added 'specgram' option suggested by Michael Zibulevsky, UNM -sm
% 12-22-99 fixed rand() sizing inefficiency on suggestion of Mike Spratling, UK -sm
% 01-11-00 fixed rand() sizing bug on suggestion of Jack Foucher, Strasbourg -sm
% 12-18-00 test for existence of Sig Proc Tlbx function 'specgram'; improve
% 'specgram' option arguments -sm
% 01-25-02 reformated help & license -ad
% 01-25-02 lowered default lrate and block -ad
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [weights,sphere,meanvar,bias,signs,lrates,activations,y,loglik] = runica(data,p1,v1,p2,v2,p3,v3,p4,v4,p5,v5,p6,v6,p7,v7,p8,v8,p9,v9,p10,v10,p11,v11,p12,v12,p13,v13,p14,v14)
if nargin < 1
help runica
return
end
[chans frames] = size(data); % determine the data size
urchans = chans; % remember original data channels
datalength = frames;
if chans<2
fprintf('\nrunica() - data size (%d,%d) too small.\n\n', chans,frames);
return
end
%
%%%%%%%%%%%%%%%%%%%%%% Declare defaults used below %%%%%%%%%%%%%%%%%%%%%%%%
%
MAX_WEIGHT = 1e8; % guess that weights larger than this have blown up
DEFAULT_STOP = 1e-6; % stop training if weight changes below this
DEFAULT_ANNEALDEG = 60; % when angle change reaches this value,
DEFAULT_ANNEALSTEP = 0.98; % anneal by multiplying lrate by this
DEFAULT_EXTANNEAL = 0.98; % or this if extended-ICA
DEFAULT_MAXSTEPS = 500; % stop training after this many steps
DEFAULT_MOMENTUM = 0.0; % default momentum weight
DEFAULT_BLOWUP = 1000000000.0; % = learning rate has 'blown up'
DEFAULT_BLOWUP_FAC = 0.8; % when lrate 'blows up,' anneal by this fac
DEFAULT_RESTART_FAC = 0.9; % if weights blowup, restart with lrate
% lower by this factor
MIN_LRATE = 0.0001; % if weight blowups make lrate < this, quit
MAX_LRATE = 0.1; % guard against uselessly high learning rate
DEFAULT_LRATE = 0.00065/log(chans);
% heuristic default - may need adjustment
% for large or tiny data sets!
% DEFAULT_BLOCK = floor(sqrt(frames/4)); % heuristic default
DEFAULT_BLOCK = ceil(min(5*log(frames),0.3*frames)); % heuristic
% - may need adjustment!
% Extended-ICA option:
DEFAULT_EXTENDED = 1; % default off
DEFAULT_EXTBLOCKS = 1; % number of blocks per kurtosis calculation
DEFAULT_NSUB = 0; % initial default number of assumed sub-Gaussians
% for extended-ICA
DEFAULT_EXTMOMENTUM = 0.5; % momentum term for computing extended-ICA kurtosis
MAX_KURTSIZE = 6000; % max points to use in kurtosis calculation
MIN_KURTSIZE = 2000; % minimum good kurtosis size (flag warning)
SIGNCOUNT_THRESHOLD = 25; % raise extblocks when sign vector unchanged
% after this many steps
SIGNCOUNT_STEP = 2; % extblocks increment factor
DEFAULT_SPHEREFLAG = 'on'; % use the sphere matrix as the default
% starting weight matrix
DEFAULT_PCAFLAG = 'off'; % don't use PCA reduction
DEFAULT_POSACTFLAG = 'on'; % use posact()
DEFAULT_VERBOSE = 1; % write ascii info to calling screen
DEFAULT_BIASFLAG = 1; % default to using bias in the ICA update rule
%
%%%%%%%%%%%%%%%%%%%%%%% Set up keyword default values %%%%%%%%%%%%%%%%%%%%%%%%%
%
if nargout < 2,
fprintf('runica() - needs at least two output arguments.\n');
return
end
epochs = 1; % do not care how many epochs in data
pcaflag = DEFAULT_PCAFLAG;
sphering = DEFAULT_SPHEREFLAG; % default flags
posactflag = DEFAULT_POSACTFLAG;
verbose = DEFAULT_VERBOSE;
block = DEFAULT_BLOCK; % heuristic default - may need adjustment!
lrate = DEFAULT_LRATE;
annealdeg = DEFAULT_ANNEALDEG;
annealstep = 0; % defaults declared below
nochange = NaN;
momentum = DEFAULT_MOMENTUM;
maxsteps = DEFAULT_MAXSTEPS;
weights = 0; % defaults defined below
ncomps = chans;
biasflag = DEFAULT_BIASFLAG;
extended = DEFAULT_EXTENDED;
extblocks = DEFAULT_EXTBLOCKS;
kurtsize = MAX_KURTSIZE;
signsbias = 0.02; % bias towards super-Gaussian components
extmomentum= DEFAULT_EXTMOMENTUM; % exp. average the kurtosis estimates
nsub = DEFAULT_NSUB;
wts_blowup = 0; % flag =1 when weights too large
wts_passed = 0; % flag weights passed as argument
%
%%%%%%%%%% Collect keywords and values from argument list %%%%%%%%%%%%%%%
%
if (nargin> 1 & rem(nargin,2) == 0)
fprintf('runica(): Even number of input arguments???')
return
end
for i = 3:2:nargin % for each Keyword
Keyword = eval(['p',int2str((i-3)/2 +1)]);
Value = eval(['v',int2str((i-3)/2 +1)]);
if ~isstr(Keyword)
fprintf('runica(): keywords must be strings')
return
end
Keyword = lower(Keyword); % convert upper or mixed case to lower
if strcmp(Keyword,'weights') | strcmp(Keyword,'weight')
if isstr(Value)
fprintf(...
'runica(): weights value must be a weight matrix or sphere')
return
else
weights = Value;
wts_passed =1;
end
elseif strcmp(Keyword,'ncomps')
if isstr(Value)
fprintf('runica(): ncomps value must be an integer')
return
end
if ncomps < urchans & ncomps ~= Value
fprintf('runica(): Use either PCA or ICA dimension reduction');
return
end
ncomps = Value;
if ~ncomps,
ncomps = chans;
end
elseif strcmp(Keyword,'pca')
if ncomps < urchans & ncomps ~= Value
fprintf('runica(): Use either PCA or ICA dimension reduction');
return
end
if isstr(Value)
fprintf(...
'runica(): pca value should be the number of principal components to retain')
return
end
pcaflag = 'on';
ncomps = Value;
if ncomps > chans | ncomps < 1,
fprintf('runica(): pca value must be in range [1,%d]\n',chans)
return
end
chans = ncomps;
elseif strcmp(Keyword,'posact')
if ~isstr(Value)
fprintf('runica(): posact value must be on or off')
return
else
Value = lower(Value);
if ~strcmp(Value,'on') & ~strcmp(Value,'off'),
fprintf('runica(): posact value must be on or off')
return
end
posactflag = Value;
end
elseif strcmp(Keyword,'lrate')
if isstr(Value)
fprintf('runica(): lrate value must be a number')
return
end
lrate = Value;
if lrate>MAX_LRATE | lrate <0,
fprintf('runica(): lrate value is out of bounds');
return
end
if ~lrate,
lrate = DEFAULT_LRATE;
end
elseif strcmp(Keyword,'block') | strcmp(Keyword,'blocksize')
if isstr(Value)
fprintf('runica(): block size value must be a number')
return
end
block = floor(Value);
if ~block,
block = DEFAULT_BLOCK;
end
elseif strcmp(Keyword,'stop') | strcmp(Keyword,'nochange') ...
| strcmp(Keyword,'stopping')
if isstr(Value)
fprintf('runica(): stop wchange value must be a number')
return
end
nochange = Value;
elseif strcmp(Keyword,'maxsteps') | strcmp(Keyword,'steps')
if isstr(Value)
fprintf('runica(): maxsteps value must be an integer')
return
end
maxsteps = Value;
if ~maxsteps,
maxsteps = DEFAULT_MAXSTEPS;
end
if maxsteps < 0
fprintf('runica(): maxsteps value (%d) must be a positive integer',maxsteps)
return
end
elseif strcmp(Keyword,'anneal') | strcmp(Keyword,'annealstep')
if isstr(Value)
fprintf('runica(): anneal step value (%2.4f) must be a number (0,1)',Value)
return
end
annealstep = Value;
if annealstep <=0 | annealstep > 1,
fprintf('runica(): anneal step value (%2.4f) must be (0,1]',annealstep)
return
end
elseif strcmp(Keyword,'annealdeg') | strcmp(Keyword,'degrees')
if isstr(Value)
fprintf('runica(): annealdeg value must be a number')
return
end
annealdeg = Value;
if ~annealdeg,
annealdeg = DEFAULT_ANNEALDEG;
elseif annealdeg > 180 | annealdeg < 0
fprintf('runica(): annealdeg (%3.1f) is out of bounds [0,180]',...
annealdeg);
return
end
elseif strcmp(Keyword,'momentum')
if isstr(Value)
fprintf('runica(): momentum value must be a number')
return
end
momentum = Value;
if momentum > 1.0 | momentum < 0
fprintf('runica(): momentum value is out of bounds [0,1]')
return
end
elseif strcmp(Keyword,'sphering') | strcmp(Keyword,'sphereing') ...
| strcmp(Keyword,'sphere')
if ~isstr(Value)
fprintf('runica(): sphering value must be on, off, or none')
return
else
Value = lower(Value);
if ~strcmp(Value,'on') & ~strcmp(Value,'off') & ~strcmp(Value,'none'),
fprintf('runica(): sphering value must be on or off')
return
end
sphering = Value;
end
elseif strcmp(Keyword,'bias')
if ~isstr(Value)
fprintf('runica(): bias value must be on or off')
return
else
Value = lower(Value);
if strcmp(Value,'on')
biasflag = 1;
elseif strcmp(Value,'off'),
biasflag = 0;
else
fprintf('runica(): bias value must be on or off')
return
end
end
elseif strcmp(Keyword,'specgram') | strcmp(Keyword,'spec')
if ~exist('specgram') < 2 % if ~exist or defined workspace variable
fprintf(...
'runica(): MATLAB Sig. Proc. Toolbox function "specgram" not found.\n')
return
end
if isstr(Value)
fprintf('runica(): specgram argument must be a vector')
return
end
srate = Value(1);
if (srate < 0)
fprintf('runica(): specgram srate (%4.1f) must be >=0',srate)
return
end
if length(Value)>1
loHz = Value(2);
if (loHz < 0 | loHz > srate/2)
fprintf('runica(): specgram loHz must be >=0 and <= srate/2 (%4.1f)',srate/2)
return
end
else
loHz = 0; % default
end
if length(Value)>2
hiHz = Value(3);
if (hiHz < loHz | hiHz > srate/2)
fprintf('runica(): specgram hiHz must be >=loHz (%4.1f) and <= srate/2 (%4.1f)',loHz,srate/2)
return
end
else
hiHz = srate/2; % default
end
if length(Value)>3
Hzframes = Value(5);
if (Hzframes<0 | Hzframes > size(data,2))
fprintf('runica(): specgram frames must be >=0 and <= data length (%d)',size(data,2))
return
end
else
Hzframes = size(data,2); % default
end
if length(Value)>4
Hzwinlen = Value(4);
if rem(Hzframes,Hzwinlen) % if winlen doesn't divide frames
fprintf('runica(): specgram Hzinc must divide frames (%d)',Hzframes)
return
end
else
Hzwinlen = Hzframes; % default
end
Specgramflag = 1; % set flag to perform specgram()
elseif strcmp(Keyword,'extended') | strcmp(Keyword,'extend')
if isstr(Value)
fprintf('runica(): extended value must be an integer (+/-)')
return
else
extended = 1; % turn on extended-ICA
extblocks = fix(Value); % number of blocks per kurt() compute
if extblocks < 0
nsub = -1*fix(extblocks); % fix this many sub-Gauss comps
elseif ~extblocks,
extended = 0; % turn extended-ICA off
elseif kurtsize>frames, % length of kurtosis calculation
kurtsize = frames;
if kurtsize < MIN_KURTSIZE
fprintf(...
'runica() warning: kurtosis values inexact for << %d points.\n',...
MIN_KURTSIZE);
end
end
end
elseif strcmp(Keyword,'verbose')
if ~isstr(Value)
fprintf('runica(): verbose flag value must be on or off')
return
elseif strcmp(Value,'on'),
verbose = 1;
elseif strcmp(Value,'off'),
verbose = 0;
else
fprintf('runica(): verbose flag value must be on or off')
return
end
else
fprintf('runica(): unknown flag')
return
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Initialize weights, etc. %%%%%%%%%%%%%%%%%%%%%%%%
%
if ~annealstep,
if ~extended,
annealstep = DEFAULT_ANNEALSTEP; % defaults defined above
else
annealstep = DEFAULT_EXTANNEAL; % defaults defined above
end
end % else use annealstep from commandline
if ~annealdeg,
annealdeg = DEFAULT_ANNEALDEG - momentum*90; % heuristic
if annealdeg < 0,
annealdeg = 0;
end
end
if ncomps > chans | ncomps < 1
fprintf('runica(): number of components must be 1 to %d.\n',chans);
return
end
if weights ~= 0, % initialize weights
% starting weights are being passed to runica() from the commandline
if verbose,
fprintf('Using starting weight matrix named in argument list ...\n')
end
if chans>ncomps & weights ~=0,
[r,c]=size(weights);
if r~=ncomps | c~=chans,
fprintf(...
'runica(): weight matrix must have %d rows, %d columns.\n', ...
chans,ncomps);
return;
end
end
end;
%
%%%%%%%%%%%%%%%%%%%%% Check keyword values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if frames<chans,
fprintf('runica(): data length (%d) < data channels (%d)!\n',frames,chans)
return
elseif block < 1,
fprintf('runica(): block size %d too small!\n',block)
return
elseif block > frames,
fprintf('runica(): block size exceeds data length!\n');
return
elseif floor(epochs) ~= epochs,
fprintf('runica(): data length is not a multiple of the epoch length!\n');
return
elseif nsub > ncomps
fprintf('runica(): there can be at most %d sub-Gaussian components!\n',ncomps);
return
end;
%
% adjust nochange if necessary
%
if isnan(nochange)
if ncomps > 32
nochange = 1E-7;
nochangeupdated = 1; % for fprinting purposes
else
nochangeupdated = 1; % for fprinting purposes
nochange = DEFAULT_STOP;
end;
else
nochangeupdated = 0;
end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Process the data %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if verbose,
fprintf( ...
'\nInput data size [%d,%d] = %d channels, %d frames/n', ...
chans,frames,chans,frames);
if strcmp(pcaflag,'on')
fprintf('After PCA dimension reduction,\n finding ');
else
fprintf('Finding ');
end
if ~extended
fprintf('%d ICA components using logistic ICA.\n',ncomps);
else % if extended
fprintf('%d ICA components using extended ICA.\n',ncomps);
if extblocks > 0
fprintf(...
'Kurtosis will be calculated initially every %d blocks using %d data points.\n',...
extblocks, kurtsize);
else
fprintf(...
'Kurtosis will not be calculated. Exactly %d sub-Gaussian components assumed.\n',...
nsub);
end
end
fprintf('Decomposing %d frames per ICA weight ((%d)^2 = %d weights, %d frames)\n',...
floor(frames/ncomps.^2),ncomps.^2,frames);
fprintf('Initial learning rate will be %g, block size %d.\n',...
lrate,block);
if momentum>0,
fprintf('Momentum will be %g.\n',momentum);
end
fprintf( ...
'Learning rate will be multiplied by %g whenever angledelta >= %g deg.\n', ...
annealstep,annealdeg);
if nochangeupdated
fprintf('More than 32 channels: default stopping weight change 1E-7\n');
end;
fprintf('Training will end when wchange < %g or after %d steps.\n', ...
nochange,maxsteps);
if biasflag,
fprintf('Online bias adjustment will be used.\n');
else
fprintf('Online bias adjustment will not be used.\n');
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%%% Remove overall row means %%%%%%%%%%%%%%%%%%%%%%%%
%
if verbose,
fprintf('Removing mean of each channel ...\n');
end
data = data - mean(data')'*ones(1,frames); % subtract row means
if verbose,
fprintf('Final training data range: %g to %g\n', ...
min(min(data)),max(max(data)));
end
%
%%%%%%%%%%%%%%%%%%% Perform PCA reduction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmp(pcaflag,'on')
fprintf('Reducing the data to %d principal dimensions...\n',ncomps);
[eigenvectors,eigenvalues,data] = pcsquash(data,ncomps);
% make data its projection onto the ncomps-dim principal subspace
end
%
%%%%%%%%%%%%%%%%%%% Perform specgram transformation %%%%%%%%%%%%%%%%%%%%%%%
%
if exist('Specgramflag') == 1
% [P F T] = SPECGRAM(A,NFFT,Fs,WINDOW,NOVERLAP) % MATLAB Sig Proc Toolbox
% Hzwinlen = fix(srate/Hzinc); % CHANGED FROM THIS 12/18/00 -sm
Hzfftlen = 2^(ceil(log(Hzwinlen)/log(2))); % make FFT length next higher 2^k
Hzoverlap = 0; % use sequential windows
%
% Get freqs and times from 1st channel analysis
%
[tmp,freqs,tms] = specgram(data(1,:),Hzfftlen,srate,Hzwinlen,Hzoverlap);
fs = find(freqs>=loHz & freqs <= hiHz);
if isempty(fs)
fprintf('runica(): specified frequency range too narrow!\n');
return
end;
specdata = reshape(tmp(fs,:),1,length(fs)*size(tmp,2));
specdata = [real(specdata) imag(specdata)];
% fprintf(' size(fs) = %d,%d\n',size(fs,1),size(fs,2));
% fprintf(' size(tmp) = %d,%d\n',size(tmp,1),size(tmp,2));
%
% Loop through remaining channels
%
for ch=2:chans
[tmp] = specgram(data(ch,:),Hzwinlen,srate,Hzwinlen,Hzoverlap);
tmp = reshape((tmp(fs,:)),1,length(fs)*size(tmp,2));
specdata = [specdata;[real(tmp) imag(tmp)]]; % channels are rows
end
%
% Print specgram confirmation and details
%
fprintf(...
'Converted data to %d channels by %d=2*%dx%d points spectrogram data.\n',...
chans,2*length(fs)*length(tms),length(fs),length(tms));
if length(fs) > 1
fprintf(...
' Low Hz %g, high Hz %g, Hz incr %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),freqs(fs(2))-freqs(fs(1)),Hzwinlen);
else
fprintf(...
' Low Hz %g, high Hz %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),Hzwinlen);
end
%
% Replace data with specdata
%
data = specdata;
datalength=size(data,2);
end
%
%%%%%%%%%%%%%%%%%%% Perform sphering %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmp(sphering,'on'), %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if verbose,
fprintf('Computing the sphering matrix...\n');
end
sphere = 2.0*inv(sqrtm(cov(data'))); % find the "sphering" matrix = spher()
if ~weights,
if verbose,
fprintf('Starting weights are the identity matrix ...\n');
end
weights = eye(ncomps,chans); % begin with the identity matrix
else % weights given on commandline
if verbose,
fprintf('Using starting weights named on commandline ...\n');
end
end
if verbose,
fprintf('Sphering the data ...\n');
end
data = sphere*data; % actually decorrelate the electrode signals
elseif strcmp(sphering,'off') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~weights
if verbose,
fprintf('Using the sphering matrix as the starting weight matrix ...\n');
fprintf('Returning the identity matrix in variable "sphere" ...\n');
end
sphere = 2.0*inv(sqrtm(cov(data'))); % find the "sphering" matrix = spher()
weights = eye(ncomps,chans)*sphere; % begin with the identity matrix
sphere = eye(chans); % return the identity matrix
else % weights ~= 0
if verbose,
fprintf('Using starting weights named on commandline ...\n');
fprintf('Returning the identity matrix in variable "sphere" ...\n');
end
sphere = eye(chans); % return the identity matrix
end
elseif strcmp(sphering,'none')
sphere = eye(chans); % return the identity matrix
if ~weights
if verbose,
fprintf('Starting weights are the identity matrix ...\n');
fprintf('Returning the identity matrix in variable "sphere" ...\n');
end
weights = eye(ncomps,chans); % begin with the identity matrix
else % weights ~= 0
if verbose,
fprintf('Using starting weights named on commandline ...\n');
fprintf('Returning the identity matrix in variable "sphere" ...\n');
end
end
sphere = eye(chans,chans);
if verbose,
fprintf('Returned variable "sphere" will be the identity matrix.\n');
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Initialize ICA training %%%%%%%%%%%%%%%%%%%%%%%%%
%
lastt=fix((datalength/block-1)*block+1);
BI=block*eye(ncomps,ncomps);
delta=zeros(1,chans*ncomps);
changes = [];
degconst = 180./pi;
startweights = weights;
prevweights = startweights;
oldweights = startweights;
prevwtchange = zeros(chans,ncomps);
oldwtchange = zeros(chans,ncomps);
lrates = zeros(1,maxsteps);
onesrow = ones(1,block);
bias = zeros(ncomps,1);
signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1
for k=1:nsub
signs(k) = -1;
end
if extended & extblocks < 0 & verbose,
fprintf('Fixed extended-ICA sign assignments: ');
for k=1:ncomps
fprintf('%d ',signs(k));
end; fprintf('\n');
end
signs = diag(signs); % make a diagonal matrix
oldsigns = zeros(size(signs));;
signcount = 0; % counter for same-signs
signcounts = [];
urextblocks = extblocks; % original value, for resets
old_kk = zeros(1,ncomps); % for kurtosis momemtum
%
%%%%%%%% ICA training loop using the logistic sigmoid %%%%%%%%%%%%%%%%%%%
%
if verbose,
fprintf('Beginning ICA training ...');
if extended,
fprintf(' first training step may be slow ...\n');
else
fprintf('\n');
end
end
step=0;
laststep=0;
blockno = 1; % running block counter for kurtosis interrupts
logstep = 1; % iterator over log likelihood record
rand('state',sum(100*clock)); % set the random number generator state to
cost_step = 1; % record cost every cost_step iterations
% a position dependent on the system clock
while step < maxsteps, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
permute=randperm(datalength); % shuffle data order at each step
loglik(logstep) = 0;
for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%%
pause(0);
if ~isempty(get(0, 'currentfigure')) & strcmp(get(gcf, 'tag'), 'stop')
close; error('USER ABORT');
end;
if biasflag
u=weights*data(:,permute(t:t+block-1)) + bias*onesrow;
else
u=weights*data(:,permute(t:t+block-1));
end
if ~extended
%%%%%%%%%%%%%%%%%%% Logistic ICA weight update %%%%%%%%%%%%%%%%%%%
y=1./(1+exp(-u)); %
weights = weights + lrate*(BI+(1-2*y)*u')*weights; %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
else % Tanh extended-ICA weight update
%%%%%%%%%%%%%%%%%%% Extended-ICA weight update %%%%%%%%%%%%%%%%%%%
y=tanh(u); %
weights = weights + lrate*(BI-signs*y*u'-u*u')*weights; %
%%%%%%%%% Calculate log likelihood given our model %%%%%%%%%
if mod(step,cost_step) == 0
subgcomp = find(diag(signs) == -1);
supergcomp = find(diag(signs) == 1);
loglik(logstep) = loglik(logstep) + sum(sum(log(exp(-(1/2)*(u(subgcomp,:)-1).^2) + exp(-(1/2)*(u(subgcomp,:)+1).^2))));
loglik(logstep) = loglik(logstep) + sum(sum(-0.5*u(supergcomp,:).^2 - 2*log(cosh(u(supergcomp,:)))));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
if biasflag
if ~extended
%%%%%%%%%%%%%%%%%%%%%%%% Logistic ICA bias %%%%%%%%%%%%%%%%%%%%%%%
bias = bias + lrate*sum((1-2*y)')'; % for logistic nonlin. %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
else % extended
%%%%%%%%%%%%%%%%%%% Extended-ICA bias %%%%%%%%%%%%%%%%%%%%%%%%%%%%
bias = bias + lrate*sum((-2*y)')'; % for tanh() nonlin. %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
end
if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%%
weights = weights + momentum*prevwtchange;
prevwtchange = weights-prevweights;
prevweights = weights;
end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if max(max(abs(weights))) > MAX_WEIGHT
wts_blowup = 1;
change = nochange;
end
if extended & ~wts_blowup
%
%%%%%%%%%%% Extended-ICA kurtosis estimation %%%%%%%%%%%%%%%%%%%%%
%
if extblocks > 0 & rem(blockno,extblocks) == 0,
% recompute signs vector using kurtosis
if kurtsize < frames % 12-22-99 rand() size suggestion by M. Spratling
rp = fix(rand(1,kurtsize)*datalength); % pick random subset
% Accout for the possibility of a 0 generation by rand
ou = find(rp == 0);
while ~isempty(ou) % 1-11-00 suggestion by J. Foucher
rp(ou) = fix(rand(1,length(ou))*datalength);
ou = find(rp == 0);
end
partact=weights*data(:,rp(1:kurtsize));
else % for small data sets,
partact=weights*data; % use whole data
end
m2=mean(partact'.^2).^2;
m4= mean(partact'.^4);
kk= (m4./m2)-3.0; % kurtosis estimates
if extmomentum
kk = extmomentum*old_kk + (1.0-extmomentum)*kk; % use momentum
old_kk = kk;
end
signs=diag(sign(kk+signsbias)); % pick component signs
if signs == oldsigns,
signcount = signcount+1;
else
signcount = 0;
end
oldsigns = signs;
signcounts = [signcounts signcount];
if signcount >= SIGNCOUNT_THRESHOLD,
extblocks = fix(extblocks * SIGNCOUNT_STEP);% make kurt() estimation
signcount = 0; % less frequent if sign
end % is not changing
end % extblocks > 0 & . . .
end % if extended %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
blockno = blockno + 1;
if wts_blowup
break
end
end % training block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
loglik(logstep) = loglik(logstep) + log(abs(det(weights)));
logstep = logstep + 1;
if ~wts_blowup
oldwtchange = weights-oldweights;
step=step+1;
%
%%%%%%% Compute and print weight and update angle changes %%%%%%%%%
%
lrates(1,step) = lrate;
angledelta=0.;
delta=reshape(oldwtchange,1,chans*ncomps);
change=delta*delta';
end
%
%%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%%
%
if wts_blowup | isnan(change)|isinf(change), % if weights blow up,
fprintf('');
step = 0; % start again
change = nochange;
wts_blowup = 0; % re-initialize variables
blockno = 1;
lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate
weights = startweights; % and original weight matrix
oldweights = startweights;
change = nochange;
oldwtchange = zeros(chans,ncomps);
delta=zeros(1,chans*ncomps);
olddelta = delta;
extblocks = urextblocks;
prevweights = startweights;
prevwtchange = zeros(chans,ncomps);
lrates = zeros(1,maxsteps);
bias = zeros(ncomps,1);
if extended
signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1
for k=1:nsub
signs(k) = -1;
end
signs = diag(signs); % make a diagonal matrix
oldsigns = zeros(size(signs));;
end
if lrate> MIN_LRATE
r = rank(data);
if r<ncomps
fprintf('Data has rank %d. Cannot compute %d components.\n',...
r,ncomps);
return
else
fprintf(...
'Lowering learning rate to %g and starting again.\n',lrate);
end
else
fprintf( ...
'runica(): QUITTING - weight matrix may not be invertible!\n');
return;
end
else % if weights in bounds
%
%%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%%
%
if step> 2
angledelta=acos((delta*olddelta')/sqrt(change*oldchange));
end
if verbose,
places = -floor(log10(nochange));
if step > 2,
if ~extended,
ps = sprintf('step %d - lrate %5f, wchange %%%d.%df, angledelta %4.1f deg\n', ...
step, lrate, places+1,places, degconst*angledelta);
else
ps = sprintf('step %d - lrate %5f, wchange %%%d.%df, angledelta %4.1f deg, %d subgauss\n',...
step, lrate, degconst*angledelta,...
places+1,places, (ncomps-sum(diag(signs)))/2);
end
elseif ~extended
ps = sprintf('step %d - lrate %5f, wchange %%%d.%df\n',...
step, lrate, places+1,places );
else
ps = sprintf('step %5d - lrate %5f, wchange %%%d.%df, %d subgauss\n',...
step, lrate, places+1,places, (ncomps-sum(diag(signs)))/2);
end % step > 2
fprintf('step %d - lrate %5f, wchange %8.8f, angledelta %5.1f deg, loglik %6.2f, nsub = %d\n', ...
step, lrate, change, degconst*angledelta, loglik(step), sum(diag(signs)==-1));
% fprintf(ps,change); % <---- BUG !!!!
end; % if verbose
%
%%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
changes = [changes change];
oldweights = weights;
%
%%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if degconst*angledelta > annealdeg,
lrate = lrate*annealstep; % anneal learning rate
olddelta = delta; % accumulate angledelta until
oldchange = change; % annealdeg is reached
elseif step == 1 % on first step only
olddelta = delta; % initialize
oldchange = change;
end
%
%%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if step >2 & change < nochange, % apply stopping rule
laststep=step;
step=maxsteps; % stop when weights stabilize
elseif change > DEFAULT_BLOWUP, % if weights blow up,
lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying
end; % with a smaller learning rate
end; % end if weights in bounds
end; % end training %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~laststep
laststep = step;
end;
lrates = lrates(1,1:laststep); % truncate lrate history vector
%
%%%%%%%%%%%%%% Orient components towards max positive activation %%%%%%
%
if strcmp(posactflag,'on')
[activations,winvout,weights] = posact(data,weights);
% changes signs of activations and weights to make activations
% net rms-positive
else
activations = weights*data;
end
%
%%%%%%%%%%%%%% If pcaflag, compose PCA and ICA matrices %%%%%%%%%%%%%%%
%
if strcmp(pcaflag,'on')
fprintf('Composing the eigenvector, weights, and sphere matrices\n');
fprintf(' into a single rectangular weights matrix; sphere=eye(%d)\n'...
,chans);
weights= weights*sphere*eigenvectors(:,1:ncomps)';
sphere = eye(urchans);
end
%
%%%%%% Sort components in descending order of max projected variance %%%%
%
if verbose,
fprintf(...
'Sorting components in descending order of mean projected variance ...\n');
end
%
%%%%%%%%%%%%%%%%%%%% Find mean variances %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
meanvar = zeros(ncomps,1); % size of the projections
if ncomps == urchans % if weights are square . . .
winv = inv(weights*sphere);
else
fprintf('Using pseudo-inverse of weight matrix to rank order component projections.\n');
winv = pinv(weights*sphere);
end
for s=1:ncomps
if verbose,
fprintf('%d ',s); % construct single-component data matrix
end
% project to scalp, then add row means
compproj = winv(:,s)*activations(s,:);
meanvar(s) = mean(sum(compproj.*compproj)/(size(compproj,1)-1));
% compute mean variance
end % at all scalp channels
if verbose,
fprintf('\n');
end
%
%%%%%%%%%%%%%% Sort components by mean variance %%%%%%%%%%%%%%%%%%%%%%%%
%
[sortvar, windex] = sort(meanvar);
windex = windex(ncomps:-1:1); % order large to small
meanvar = meanvar(windex);
%
%%%%%%%%%%%%%%%%%%%%% Filter data using final weights %%%%%%%%%%%%%%%%%%
%
if nargout>6, % if activations are to be returned
if verbose,
fprintf('Permuting the activation wave forms ...\n');
end
activations = activations(windex,:);
else
clear activations
end
weights = weights(windex,:);% reorder the weight matrix
bias = bias(windex); % reorder them
signs = diag(signs); % vectorize the signs matrix
signs = signs(windex); % reorder them
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
return
%
%%%%%%%%%%%%%%%%%% return nonlinearly-transformed data %%%%%%%%%%%%%%%%
%
if nargout > 7
u=weights*data + bias*ones(1,frames);
y = zeros(size(u));
for c=1:chans
for f=1:frames
y(c,f) = 1/(1+exp(-u(c,f)));
end
end
end
|
github
|
lcnhappe/happe-master
|
eventalign.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/eventalign.m
| 1,247 |
utf_8
|
aae47eaea14a78b572fa7ac4a27e027d
|
% eventalign - function called by pop_importevent() to find the best
% sampling rate ratio to align 2 arrays of data events.
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, Dec 2003
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 9 Feb 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 mindiff = eventalign(factor, a, b, measure)
diffarray = abs(factor*a-b)';
[allmins poss] = min(diffarray);
if strcmpi(measure, 'mean')
mindiff = mean(allmins);
else
mindiff = median(allmins);
end;
|
github
|
lcnhappe/happe-master
|
writecnt.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/writecnt.m
| 19,451 |
utf_8
|
2103534700b0526bc4c1e243609e91d9
|
% writecnt() - Write a Neuroscan continuous signal file.
%
% Usage:
% >> writecnt(filename, CNT-dataset, varargin)
%
% Inputs:
% filename - name of the file with extension
% dataset - name of the CNT-dataset, a structure with the following fields
% cntdataset.header
% cntdataset.electloc
% cntdataset.data
% cntdataset.Teeg
% cntdataset.event
% cntdataset.tag
% cntdataset.endtag
%
% optional fields
% cntdataset.dataformat: 'int32' or 'int16'
%
% Optional inputs:
% 'header': bool, write header. (default=true)
% 'electrodes': bool, write electrode information. (default=true)
% 'data': bool, write data (default=true)
% 'eventtable': bool, write event table (default=true)
% 'endtag': bool, write end tag (default=true)
% 'append': bool, append requested information to end of file.
% (default=false) Requires that file exists.
% 't1' - start at time t1, default 0; ERROR WITH NONZERO VALUES
% 'sample1' - start at sample1, default 0, overrides t1 ERROR WITH NONZERO VALUES
% 'lddur' - duration of segment to load, default = whole file
% 'ldnsamples' - number of samples to load, default = whole file,
% overrides lddur
% 'scale' - ['on'|'off'] scale data to microvolt (default:'on')
% 'dataformat' - ['int16'|'int32'] default is 'int16' for 16-bit data.
% Use 'int32' for 32-bit data.
%
% Outputs:
% file - file containing NeuroScan CNT file with the continuous
% data and other information
%
% Authors: Sean Fitzgibbon, Arnaud Delorme, Michiel Vestjens and
% and Chris Bishop 2000-2014. Maintained by Chris Bishop
% (cwbishop_at_ucdavis.edu).
%
% Known limitations:
% For more see http://www.cnl.salk.edu/~arno/cntload/index.html
% Copyright (C) 2000 Sean Fitzgibbon, <[email protected]>
% Copyright (C) 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 f = writecnt(filename,cntdataset,varargin)
if ~isempty(varargin)
WriteOptions=struct(varargin{:});
else WriteOptions = [];
end;
try, WriteOptions.t1; catch, WriteOptions.t1=0; end
try, WriteOptions.sample1; catch, WriteOptions.sample1=[]; end
try, WriteOptions.lddur; catch, WriteOptions.lddur=[]; end
try, WriteOptions.ldnsamples; catch, WriteOptions.ldnsamples=[]; end
try, WriteOptions.scale; catch, WriteOptions.scale='on'; end
try, WriteOptions.dataformat; catch, WriteOptions.dataformat='int16'; end
%% CATCH FOR KNOWN ERRORS WITH NON ZERO T1 and SAMPLE1
if WriteOptions.t1~=0 || (~isempty(WriteOptions.sample1) && WriteOptions.sample1~=0)
error('writecnt:NonzeroStartPosition', 'writecnt cannot deal with nonzero write positions.');
end % if WriteOptions
%% ADDITIONAL CHECKS BY CWB
% Set defaults for optional inputs
if ~isfield(WriteOptions, 'header') || isempty(WriteOptions.header), WriteOptions.header=true; end
if ~isfield(WriteOptions, 'electrodes') || isempty(WriteOptions.electrodes), WriteOptions.electrodes=true; end
if ~isfield(WriteOptions, 'data') || isempty(WriteOptions.data), WriteOptions.data=true; end
if ~isfield(WriteOptions, 'eventtable') || isempty(WriteOptions.eventtable), WriteOptions.eventtable=true; end
if ~isfield(WriteOptions, 'append') || isempty(WriteOptions.append), WriteOptions.append=false; end
if ~isfield(WriteOptions, 'endtag') || isempty(WriteOptions.endtag), WriteOptions.endtag=true; end
%% SIZE OF EVENT DATA (differs based on version of SCAN)
sizeEvent1 = 8 ; %%% 8 bytes for Event1
sizeEvent2 = 19 ; %%% 19 bytes for Event2
type='cnt';
if nargin ==1
scan=0;
end
h = cntdataset.header;
e = cntdataset.electloc;
dat = cntdataset.data;
eT = cntdataset.Teeg;
ev2 = cntdataset.event;
t = cntdataset.tag;
if ~isfield(cntdataset,'endtag')
endtag=[];
else
endtag=cntdataset.endtag;
end
%% APPEND DATA?
% If not, then open data for general writing
if WriteOptions.append
fid=fopen(filename,'a+');
% display('Appending requested information ...');
else
fid = fopen(filename,'w');
end % if WriteOptions.append
% disp(['Writing file ' filename ' ...'])
% HEADER : 900 bytes => Starts at 0h, finishes with 383h.
if WriteOptions.header
fwrite(fid,h.rev,'char');
fwrite(fid,h.nextfile,'long');
fwrite(fid,h.prevfile,'long');
fwrite(fid,h.type,'char');
fwrite(fid,h.id,'char');
fwrite(fid,h.oper,'char');
fwrite(fid,h.doctor,'char');
fwrite(fid,h.referral,'char');
fwrite(fid,h.hospital,'char');
fwrite(fid,h.patient,'char');
fwrite(fid,h.age,'short');
fwrite(fid,h.sex,'char');
fwrite(fid,h.hand,'char');
fwrite(fid,h.med,'char');
fwrite(fid,h.category,'char');
fwrite(fid,h.state,'char');
fwrite(fid,h.label,'char');
fwrite(fid,h.date,'char');
fwrite(fid,h.time,'char');
fwrite(fid,h.mean_age,'float');
fwrite(fid,h.stdev,'float');
fwrite(fid,h.n,'short');
fwrite(fid,h.compfile,'char');
fwrite(fid,h.spectwincomp,'float');
fwrite(fid,h.meanaccuracy,'float');
fwrite(fid,h.meanlatency,'float');
fwrite(fid,h.sortfile,'char');
fwrite(fid,h.numevents,'int');
fwrite(fid,h.compoper,'char');
fwrite(fid,h.avgmode,'char');
fwrite(fid,h.review,'char');
fwrite(fid,h.nsweeps,'ushort');
fwrite(fid,h.compsweeps,'ushort');
fwrite(fid,h.acceptcnt,'ushort');
fwrite(fid,h.rejectcnt,'ushort');
fwrite(fid,h.pnts,'ushort');
fwrite(fid,h.nchannels,'ushort');
fwrite(fid,h.avgupdate,'ushort');
fwrite(fid,h.domain,'char');
fwrite(fid,h.variance,'char');
fwrite(fid,h.rate,'ushort');
fwrite(fid,h.scale,'double');
fwrite(fid,h.veogcorrect,'char');
fwrite(fid,h.heogcorrect,'char');
fwrite(fid,h.aux1correct,'char');
fwrite(fid,h.aux2correct,'char');
fwrite(fid,h.veogtrig,'float');
fwrite(fid,h.heogtrig,'float');
fwrite(fid,h.aux1trig,'float');
fwrite(fid,h.aux2trig,'float');
fwrite(fid,h.heogchnl,'short');
fwrite(fid,h.veogchnl,'short');
fwrite(fid,h.aux1chnl,'short');
fwrite(fid,h.aux2chnl,'short');
fwrite(fid,h.veogdir,'char');
fwrite(fid,h.heogdir,'char');
fwrite(fid,h.aux1dir,'char');
fwrite(fid,h.aux2dir,'char');
fwrite(fid,h.veog_n,'short');
fwrite(fid,h.heog_n,'short');
fwrite(fid,h.aux1_n,'short');
fwrite(fid,h.aux2_n,'short');
fwrite(fid,h.veogmaxcnt,'short');
fwrite(fid,h.heogmaxcnt,'short');
fwrite(fid,h.aux1maxcnt,'short');
fwrite(fid,h.aux2maxcnt,'short');
fwrite(fid,h.veogmethod,'char');
fwrite(fid,h.heogmethod,'char');
fwrite(fid,h.aux1method,'char');
fwrite(fid,h.aux2method,'char');
fwrite(fid,h.ampsensitivity,'float');
fwrite(fid,h.lowpass,'char');
fwrite(fid,h.highpass,'char');
fwrite(fid,h.notch,'char');
fwrite(fid,h.autoclipadd,'char');
fwrite(fid,h.baseline,'char');
fwrite(fid,h.offstart,'float');
fwrite(fid,h.offstop,'float');
fwrite(fid,h.reject,'char');
fwrite(fid,h.rejstart,'float');
fwrite(fid,h.rejstop,'float');
fwrite(fid,h.rejmin,'float');
fwrite(fid,h.rejmax,'float');
fwrite(fid,h.trigtype,'char');
fwrite(fid,h.trigval,'float');
fwrite(fid,h.trigchnl,'char');
fwrite(fid,h.trigmask,'short');
fwrite(fid,h.trigisi,'float');
fwrite(fid,h.trigmin,'float');
fwrite(fid,h.trigmax,'float');
fwrite(fid,h.trigdir,'char');
fwrite(fid,h.autoscale,'char');
fwrite(fid,h.n2,'short');
fwrite(fid,h.dir,'char');
fwrite(fid,h.dispmin,'float');
fwrite(fid,h.dispmax,'float');
fwrite(fid,h.xmin,'float');
fwrite(fid,h.xmax,'float');
fwrite(fid,h.automin,'float');
fwrite(fid,h.automax,'float');
fwrite(fid,h.zmin,'float');
fwrite(fid,h.zmax,'float');
fwrite(fid,h.lowcut,'float');
fwrite(fid,h.highcut,'float');
fwrite(fid,h.common,'char');
fwrite(fid,h.savemode,'char');
fwrite(fid,h.manmode,'char');
fwrite(fid,h.ref,'char');
fwrite(fid,h.rectify,'char');
fwrite(fid,h.displayxmin,'float');
fwrite(fid,h.displayxmax,'float');
fwrite(fid,h.phase,'char');
fwrite(fid,h.screen,'char');
fwrite(fid,h.calmode,'short');
fwrite(fid,h.calmethod,'short');
fwrite(fid,h.calupdate,'short');
fwrite(fid,h.calbaseline,'short');
fwrite(fid,h.calsweeps,'short');
fwrite(fid,h.calattenuator,'float');
fwrite(fid,h.calpulsevolt,'float');
fwrite(fid,h.calpulsestart,'float');
fwrite(fid,h.calpulsestop,'float');
fwrite(fid,h.calfreq,'float');
fwrite(fid,h.taskfile,'char');
fwrite(fid,h.seqfile,'char');
fwrite(fid,h.spectmethod,'char');
fwrite(fid,h.spectscaling,'char');
fwrite(fid,h.spectwindow,'char');
fwrite(fid,h.spectwinlength,'float');
fwrite(fid,h.spectorder,'char');
fwrite(fid,h.notchfilter,'char');
fwrite(fid,h.headgain,'short');
fwrite(fid,h.additionalfiles,'int');
fwrite(fid,h.unused,'char');
fwrite(fid,h.fspstopmethod,'short');
fwrite(fid,h.fspstopmode,'short');
fwrite(fid,h.fspfvalue,'float');
fwrite(fid,h.fsppoint,'short');
fwrite(fid,h.fspblocksize,'short');
fwrite(fid,h.fspp1,'ushort');
fwrite(fid,h.fspp2,'ushort');
fwrite(fid,h.fspalpha,'float');
fwrite(fid,h.fspnoise,'float');
fwrite(fid,h.fspv1,'short');
fwrite(fid,h.montage,'char');
fwrite(fid,h.eventfile,'char');
fwrite(fid,h.fratio,'float');
fwrite(fid,h.minor_rev,'char');
fwrite(fid,h.eegupdate,'short');
fwrite(fid,h.compressed,'char');
fwrite(fid,h.xscale,'float');
fwrite(fid,h.yscale,'float');
fwrite(fid,h.xsize,'float');
fwrite(fid,h.ysize,'float');
fwrite(fid,h.acmode,'char');
fwrite(fid,h.commonchnl,'uchar');
fwrite(fid,h.xtics,'char');
fwrite(fid,h.xrange,'char');
fwrite(fid,h.ytics,'char');
fwrite(fid,h.yrange,'char');
fwrite(fid,h.xscalevalue,'float');
fwrite(fid,h.xscaleinterval,'float');
fwrite(fid,h.yscalevalue,'float');
fwrite(fid,h.yscaleinterval,'float');
fwrite(fid,h.scaletoolx1,'float');
fwrite(fid,h.scaletooly1,'float');
fwrite(fid,h.scaletoolx2,'float');
fwrite(fid,h.scaletooly2,'float');
fwrite(fid,h.port,'short');
fwrite(fid,h.numsamples,'ulong');
fwrite(fid,h.filterflag,'char');
fwrite(fid,h.lowcutoff,'float');
fwrite(fid,h.lowpoles,'short');
fwrite(fid,h.highcutoff,'float');
fwrite(fid,h.highpoles,'short');
fwrite(fid,h.filtertype,'char');
fwrite(fid,h.filterdomain,'char');
fwrite(fid,h.snrflag,'char');
fwrite(fid,h.coherenceflag,'char');
fwrite(fid,h.continuoustype,'char');
fwrite(fid,h.eventtablepos,'long');
fwrite(fid,h.continuousseconds,'float');
fwrite(fid,h.channeloffset,'long');
fwrite(fid,h.autocorrectflag,'char');
fwrite(fid,h.dcthreshold,'uchar'); % = 383H
end % if WriteOptions.header
% ELECT.DESCRIPTIONS : 75*n.channels bytes.
% Starts with 384h, finishes with (899+75*nchannels)dec
% 10 channels: 671h % 12 channels: 707h
% 24 channels: A8Bh % 32 channels: CE3h
% 64 channels: 1643h % 128 channels: 2903h
if WriteOptions.electrodes
for n = 1:h.nchannels
lablength = fwrite(fid,e(n).lab,'char');
fwrite(fid,e(n).reference,'char',10-lablength);
fwrite(fid,e(n).skip,'char');
fwrite(fid,e(n).reject,'char');
fwrite(fid,e(n).display,'char');
fwrite(fid,e(n).bad,'char');
fwrite(fid,e(n).n,'ushort');
fwrite(fid,e(n).avg_reference,'char');
fwrite(fid,e(n).clipadd,'char');
fwrite(fid,e(n).x_coord,'float');
fwrite(fid,e(n).y_coord,'float');
fwrite(fid,e(n).veog_wt,'float');
fwrite(fid,e(n).veog_std,'float');
fwrite(fid,e(n).snr,'float');
fwrite(fid,e(n).heog_wt,'float');
fwrite(fid,e(n).heog_std,'float');
fwrite(fid,e(n).baseline,'short');
fwrite(fid,e(n).filtered,'char');
fwrite(fid,e(n).fsp,'char');
fwrite(fid,e(n).aux1_wt,'float');
fwrite(fid,e(n).aux1_std,'float');
fwrite(fid,e(n).senstivity,'float');
fwrite(fid,e(n).gain,'char');
fwrite(fid,e(n).hipass,'char');
fwrite(fid,e(n).lopass,'char');
fwrite(fid,e(n).page,'uchar');
fwrite(fid,e(n).size,'uchar');
fwrite(fid,e(n).impedance,'uchar');
fwrite(fid,e(n).physicalchnl,'uchar');
fwrite(fid,e(n).rectify,'char');
fwrite(fid,e(n).calib,'float');
end % for
end % if WriteOptions.electrodes
%% SET FILE POINTER TO END OF HEADER INFORMATION
% Need to advance the pointer in the event that the header and/or
% electrodes have not been written (or have already been written to
% file) since the file pointer position is used to determine the
% beginning of the data.
%
% This is a bit clunky, but ensures that 'append' mode works properly
% when calculated the number of data points to write.
fseek(fid, 900+75*h.nchannels, 'bof');
% finding if 32-bits of 16-bits file
% ----------------------------------
begdata = ftell(fid);
enddata = h.eventtablepos; % after data
if strcmpi(WriteOptions.dataformat, 'int16')
nums = (enddata-begdata)/h.nchannels/2;
else nums = (enddata-begdata)/h.nchannels/4;
end;
% number of sample to write
% -------------------------
if ~isempty(WriteOptions.sample1)
WriteOptions.t1 = WriteOptions.sample1/h.rate;
else
WriteOptions.sample1 = WriteOptions.t1*h.rate;
end;
if strcmpi(WriteOptions.dataformat, 'int16')
startpos = WriteOptions.t1*h.rate*2*h.nchannels;
else startpos = WriteOptions.t1*h.rate*4*h.nchannels;
end;
if isempty(WriteOptions.ldnsamples)
if ~isempty(WriteOptions.lddur)
WriteOptions.ldnsamples = round(WriteOptions.lddur*h.rate);
else WriteOptions.ldnsamples = nums;
end;
end;
% scaling data from microvolts
% ----------------------------
if strcmpi(WriteOptions.scale, 'on')
% disp('Scaling data .....')
for i=1:h.nchannels
bas=e(i).baseline;
sen=e(i).senstivity;
cal=e(i).calib;
mf=sen*(cal/204.8);
dat(i,:)=(dat(i,:)/mf)+bas;
end
end
% write data
% ----------
% disp('Writing data .....')
if type == 'cnt'
if WriteOptions.data
channel_off = h.channeloffset/2;
fseek(fid, startpos, 0);
if channel_off <= 1
for temploop =1:WriteOptions.ldnsamples;
fwrite(fid, dat(1:h.nchannels, temploop), WriteOptions.dataformat)';
end;
else
for temploop =1:h.nchannels;
fwrite(fid, dat(temploop, 1:channel_off), WriteOptions.dataformat)';
end;
counter = 1;
while counter*channel_off < WriteOptions.ldnsamples
for temploop =1:h.nchannels;
fwrite(fid, dat(temploop, counter*channel_off+1:counter*channel_off+channel_off), WriteOptions.dataformat)';
end;
counter = counter + 1;
end;
end;
end % if WriteOptions.data
if WriteOptions.eventtable
% write event table
% -----------------
frewind(fid);
fseek(fid,h.eventtablepos,'bof');
disp('Writing Event Table...')
fwrite(fid,eT.teeg,'uchar');
fwrite(fid,eT.size,'ulong');
fwrite(fid,eT.offset,'ulong');
if eT.teeg==2
nevents=eT.size/sizeEvent2;
elseif eT.teeg==1
nevents=eT.size/sizeEvent1;
else
disp('No !!! teeg <> 2 and teeg <> 1');
ev2 = [];
end % if eT.teeg==2
%%%% to change offset in points back to bytes
if ~isempty(ev2)
ev2p=ev2;
ioff=900+(h.nchannels*75); %% initial offset : header + electordes desc
% 140219 CWB: Writing events to file in byte form depends on
% data precision. Need to select the correct data precision
% here.
if strcmpi(WriteOptions.dataformat, 'int16')
NBYTES=2;
elseif strcmpi(WriteOptions.dataformat, 'int32')
NBYTES=4;
end % if strcmpi
for i=1:nevents
ev2p(i).offset=((ev2p(i).offset + WriteOptions.sample1)*NBYTES*h.nchannels) +ioff; %% 2 short int end
end
ev2 = ev2p;
end; % if ~isempty(ev2)
if eT.teeg==2
nevents=eT.size/sizeEvent2;
for i=1:nevents
ev2(i).stimtype = fwrite(fid,ev2(i).stimtype,'ushort');
ev2(i).keyboard = fwrite(fid,ev2(i).keyboard,'char');
ev2(i).keypad_accept = fwrite(fid,ev2(i).keypad_accept,'char');
ev2(i).offset = fwrite(fid,ev2(i).offset,'long');
ev2(i).type = fwrite(fid,ev2(i).type,'short');
ev2(i).code = fwrite(fid,ev2(i).code,'short');
ev2(i).latency = fwrite(fid,ev2(i).latency,'float');
ev2(i).epochevent = fwrite(fid,ev2(i).epochevent,'char');
ev2(i).accept = fwrite(fid,ev2(i).accept,'char');
ev2(i).accuracy = fwrite(fid,ev2(i).accuracy,'char');
end % for i=1:nevents
elseif eT.teeg==1
nevents=eT.size/sizeEvent1;
for i=1:nevents
ev2(i).stimtype = fwrite(fid,ev2(i).stimtype,'ushort');
ev2(i).keyboard = fwrite(fid,ev2(i).keyboard,'char');
ev2(i).keypad_accept = fwrite(fid,ev2(i).keypad_accept,'char');
ev2(i).offset = fwrite(fid,ev2(i).offset,'long');
end % for i=1:nevents
else
disp('No !!! teeg <> 2 and teeg <> 1');
ev2 = [];
end %if/elseif/else
end % if WriteOptions.eventtable
end % if type=='cnt'
%% WE ARE AT h.nextfile position here
% So there has to be additional information at the end of the CNT file
% that is NOT read in by loadcnt.m but we ultimately need in order to
% rewrite the file.
%
% Ah, there IS more information that loadcnt is not actually reading,
% although it depends on some of it to determine if the data are 16 or 32
% bit.
%
% CWB put this information in a junk field (cntdataset.junk) that can be
% written if it's present.
if WriteOptions.endtag
if size(endtag,1)>1
fwrite(fid,endtag);
else
fwrite(fid,t,'char');
end
end % if WriteOptions.endtag
fclose(fid);
% disp(['Finished writing file ' filename ' ...'])
|
github
|
lcnhappe/happe-master
|
topo2sph.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/topo2sph.m
| 3,809 |
utf_8
|
e3c2ecaa32b502b60d330735ade6b95d
|
% topo2sph() - convert a topoplot() style 2-D polar-coordinate
% channel locations file to a 3-D spherical-angle
% file for use with headplot()
% Usage:
% >> [c h] = topo2sph('eloc_file','eloc_outfile', method, unshrink);
% >> [c h] = topo2sph( topoarray, method, unshrink );
%
% Inputs:
% 'eloc_file' = filename of polar 2-D electrode locations file used by
% topoplot(). See >> topoplot example or cart2topo()
% 'eloc_outfile' = output file of 3-D electrode locations in spherical angle
% coords. for use in headplot().
% topoarray = polar array of 2-D electrode locations, with polar angle
% in the first column and radius in the second one.
% method = [1|2] 1 is for Besa compatibility, 2 is for
% compatibility with Matlab function cart2sph(). {default: 2}
% unshrink = [0<real<1] unshrink factor. Enter a shrink factor used
% to convert spherical to topo (see sph2topo()). Only
% implemented for 'method' 1 (above). Electrode 'shrink'
% is now deprecated. See >> help topoplot
% Outputs:
% c = coronal rotation
% h = horizontal rotation
%
% Author: Scott Makeig & Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 1999
%
% See also: sph2topo(), cart2topo()
% Copyright (C) 1999 Scott Makeig, SCCN/INC/UCSD, [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
% 3-16-00 changed name to topo2sph() for compatibility with cart2topo() -sm
% 01-25-02 reformated help & license -ad
% 03-22-02 complete remodeling for returning arguments and taking arrays -ad
function [c, h] = topo2sph(eloc_locs,eloc_angles, method, unshrink)
MAXCHANS = 1024;
if nargin < 1
help topo2sph;
return;
end;
if nargin > 1 && ~isstr(eloc_angles)
if nargin > 2
unshrink = method;
end;
method = eloc_angles;
else
method = 2;
end;
if isstr(eloc_locs)
fid = fopen(eloc_locs);
if fid<1,
fprintf('topo2sph()^G: cannot open eloc_loc file (%s)\n',eloc_locs)
return
end
E = fscanf(fid,'%d %f %f %s',[7 MAXCHANS]);
E = E';
fclose(fid);
else
E = eloc_locs;
E = [ ones(size(E,1),1) E ];
end;
if nargin > 1 & isstr(eloc_angles)
if exist(eloc_angles)==2,
fprintf('topo2sph: eloc_angles file (%s) already exists and will be erased.\n',eloc_angles);
end
fid = fopen(eloc_angles,'a');
if fid<1,
fprintf('topo2sph()^G: cannot open eloc_angles file (%s)\n',eloc_angles)
return
end
end;
if method == 2
t = E(:,2); % theta
r = E(:,3); % radius
h = -t; % horizontal rotation
c = (0.5-r)*180;
else
for e=1:size(E,1)
% (t,r) -> (c,h)
t = E(e,2); % theta
r = E(e,3); % radius
r = r*unshrink;
if t>=0
h(e) = 90-t; % horizontal rotation
else
h(e) = -(90+t);
end
if t~=0
c(e) = sign(t)*180*r; % coronal rotation
else
c(e) = 180*r;
end
end;
t = t';
r = r';
end;
for e=1:size(E,1)
if nargin > 1 & isstr(eloc_angles)
chan = E(e,4:7);
fprintf('%d %g %g %s\n',E(e,1),c(e),h(e),chan);
fprintf(fid,'%d %g %g %s\n',E(e,1),c(e),h(e),chan);
end;
end
|
github
|
lcnhappe/happe-master
|
spher.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/spher.m
| 365 |
utf_8
|
0308dc258a2489d286651ab9504dbea9
|
% spher() - return the sphering matrix for given input data
%
% Usage:
%
% >> sphere_matrix = spher(data);
%
% Reference: T. Bell (1996) - - -
%
% S. Makeig CNL / Salk Institute, La Jolla CA 7-17-97
function sphere = spher(data)
if nargin<1 | size(data,1)<1
help spher
return
end
sphere = 2.0*inv(sqrtm(cov(data'))); % return the "sphering" matrix
|
github
|
lcnhappe/happe-master
|
copyaxis.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/copyaxis.m
| 3,016 |
utf_8
|
ab1ad1b3dfa8e1a8ff4adaa6b8902625
|
% copyaxis() - helper function for axcopy()
%
% Usage: >> copyaxis();
% >> copyaxis( command );
%
% Note: The optional command option (a string that will be evaluated
% when the figure is created allows to customize display).
%
% Author: Tzyy-Ping Jung, SCCN/INC/UCSD, La Jolla, 2000
%
% See also: axcopy()
% Copyright (C) 3-16-2000 Tzyy-Ping Jung, SCCN/INC/UCSD, [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
% 02-16-02 added the ignore parent size option -ad
% 03-11-02 remove size option and added command option -ad
function copyaxis(command)
OFF_STD = 0.25; % std dev of figure offset
MIN_OFF = 0.15; % minimum offset for new figure
BORDER = 0.04; % screen edge tolerance
fig=gcf;
sel=gca;
%
% Get position for new figure
%
set(fig,'Units','normalized');
place=get(fig,'Position');
axiscolor=get(fig,'Color');
cmap=colormap;
newxy = (OFF_STD*randn(1,2))+place(1,1:2);
newx=newxy(1);newy=newxy(2);
if abs(newx-place(1,1))<MIN_OFF, newx=place(1,1)+sign(newx-place(1,1))*MIN_OFF;end
if abs(newy-place(1,1))<MIN_OFF, newy=place(1,1)+sign(newy-place(1,1))*MIN_OFF;end
if newx<BORDER, newx=BORDER; end
if newy<BORDER, newy=BORDER; end
if newx+place(3)>1-BORDER, newx=1-BORDER-place(3); end
if newy+place(4)>1-BORDER, newy=1-BORDER-place(4); end
newfig=figure('Units','Normalized','Position',[newx,newy,place(1,3:4)]);
%
% Copy object to new figure
%
set(newfig,'Color',axiscolor);
copyobj(sel,newfig);set(gca,'Position',[0.130 0.110 0.775 0.815]);
colormap(cmap);
%
% Increase font size
%
set(findobj('parent',newfig,'type','axes'),'FontSize',14);
set(get(gca,'XLabel'),'FontSize',16)
set(get(gca,'YLabel'),'FontSize',16)
set(get(gca,'Title'),'Fontsize',16);
%
% Add xtick and ytick labels if missing
%
if strcmp(get(gca,'Box'),'on')
set(gca,'xticklabelmode','auto')
set(gca,'xtickmode','auto')
set(gca,'yticklabelmode','auto')
set(gca,'ytickmode','auto')
end
%
% Turn on zoom in the new figure
%
zoom on;
%
% Turn off the axis copy for the new figure
%
hndl= findobj('parent',newfig,'type','axes');
set(hndl,'ButtonDownFcn','','Selected','off');
for a=1:length(hndl) % make all axes visible
set(findobj('parent',hndl(a)),'ButtonDownFcn','','Selected','off');
end
%
% Execute additional command if present
%
if exist('command') == 1
eval(command);
end;
|
github
|
lcnhappe/happe-master
|
eegplot_readkey.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/eegplot_readkey.m
| 231 |
utf_8
|
a65a871257ff3e64f58f29ff2c190071
|
% eegplot helper function to read key strokes
function eegplot_readkey(src,evnt)
if strcmp(evnt.Key, 'rightarrow')==1
eegplot('drawp',4);
elseif strcmp(evnt.Key, 'leftarrow')==1
eegplot('drawp',1);
end
|
github
|
lcnhappe/happe-master
|
moveaxes.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/moveaxes.m
| 2,214 |
utf_8
|
91a62b9d7772562c4900a56b35247ae9
|
% moveaxes() - move, resize, or copy Matlab axes using the mouse
%
% Usage: >> moveaxes
% >> moveaxes(fig)
% >> moveaxes off
%
% Note: clicking the left mouse button selects an axis
% dragging the left mouse button resizes a selected axis
% dragging the right mouse button copies a selected axis
% clicking the middle mouse button deselects a selected axis
%
% Authors: Colin Humphries & Scott Makeig, CNL / Salk Institute, La Jolla
% Copyright (C) Colin Humphries & Scott Makeig, SCCN/INC/UCSD, [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 moveaxes(fig)
if nargin<1
fig = gcf;
end
if ~isstr(fig)
tmp = findobj('tag','moveaxes');
if ~isempty(tmp) % turn off previous moveaxes Tags
ax = get(tmp,'children');
set(ax,'ButtonDownFcn','','Selected','Off');
set(tmp,'Tag','','UserData',[]);
end
ax = findobj('parent',fig,'type','axes');
for a=1:length(ax) % make all axes visible
axvis = get(ax(a),'visible');
set(ax(a),'visible','on','UserData',axvis);
end
set(ax,'ButtonDownFcn','selectmoveresize');
set(fig,'UserData',ax,'Tag','moveaxes');
elseif strcmp(fig,'off')
fig=findobj('Tag','moveaxes');
ax = get(fig,'UserData');
for a=1:length(ax) % reset original axis visibility
axvis= get(ax(a),'UserData')
set(ax(a),'visible',axvis);
end
set(ax,'ButtonDownFcn','','Selected','off');
set(fig,'Tag','','UserData',[]);
end
|
github
|
lcnhappe/happe-master
|
parsetxt.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/parsetxt.m
| 1,595 |
utf_8
|
daf4054768bfdb3e9112cbb24966ca21
|
% parsetxt() - parse text input into cell array
%
% Usage: >> cellarray = parsetxt( txt, delims );
%
% Inputs:
% txt - input text
% delims - optional char array of delimiters (default: [' ' ',' 9]);
%
% Note: commas, and simple quotes are ignored
%
% Author: Arnaud Delorme, CNL / Salk Institute, 18 April 2002
% Copyright (C) 18 April 2002 Arnaud Delorme, SCCN/INC/UCSD, [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 cellarray = parsetxt(txt, delims);
if nargin < 1
help parsetxt;
return;
end;
if nargin < 2
delims = [' ' ',' 9 '"' '''' ];
end;
cellarray = {};
tmptxt = '';
for index =1:length(txt)
if ~isempty(findstr(txt(index), delims))
if ~isempty(tmptxt), cellarray = { cellarray{:}, tmptxt }; end;
tmptxt = '';
else
tmptxt = [ tmptxt txt(index) ];
end;
end;
if ~isempty(tmptxt)
cellarray = { cellarray{:}, tmptxt };
end;
return;
|
github
|
lcnhappe/happe-master
|
coregister.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/coregister.m
| 39,331 |
utf_8
|
14a6f71096e2d95a1ff015fc16764102
|
% coregister() - Co-register measured or template electrode locations with a
% a reference channel locations file. For instance if you
% want to perform dipole modeling you have to coregister
% (align) your channel electrodes with the model (and the
% easiest way to do that is to coregister your channel
% electrodes with the electrodes file associated with the
% model. To use coregister(), one may for instance use the default
% MNI head and 10-5 System locations from Robert Oostenveld, used in
% the dipfit2() dipole modeling function as a reference.
% Use coregister() to linearly align or nonlinearly warp
% subsequently recorded or nominally identified (e.g., 'Cz') sets of
% channel head locations to the reference locations.
% Both channel locations and/or fiducial (non-electrode)
% locations can then be used by coregister() to linearly align
% or nonlinearly warp a given or measured montage to the reference
% locations. In its (default) manual mode, coregister() produces
% an interactive gui showing the imported and reference channel
% locations on the imported head mesh (if any), allowing the user
% to make additional manual adjustments using gui text entry boxes,
% and to rotate the display using the mouse.
% Usage:
% >> coregister(EEG.chanlocs); % Show channel locations in the coregister()
% % gui, for align, warp, or manual mode co-registration with the
% % dipfit2() model head mesh and 10-5 System reference locations.
% % Note: May need to scale channel x,y,z positions by 100 to see
% % the imported locations in the default dipfit2() head mesh.
%
% >> [chanlocs_out transform] = coregister( chanlocs, reflocs, 'key', 'val' )
% % Perform custom co-registration to a reference locations and
% % (optional) head mesh. If a ('warp' or 'alignfid') mode is
% % specified, no gui window is produced.
% Inputs:
% chanlocs - (EEG.chanlocs) channel locations structure (or file) to align
% For file structure, see >> headplot example
% or >> headplot cartesian
% reflocs - reference channel locations structure (or file) associated
% with the head mesh ('mesh' below) {default|[] -> 10-5 System locs}
%
% Optional 'keywords' and arguments ([ ]):
% 'mesh' - [cell array|string] head mesh. May contain {points triangles}
% or {points triangles normals} (see >> help plotmesh
% for details). May also be the name of a head mesh .mat
% file (several formats recognized). By default, loads the
% dipfit2() MNI head mesh file. Compare 'mheadnew.mat', the
% mesh used by headplot(); 'mesh',[] shows no head mesh.
% 'warpmethod' - ['rigidbody'|'globalrescale'|'traditional'|'nonlin1'|
% 'nonlin2'|'nonlin3'|'nonlin4'|'nonlin5']
% 'traditional' calls the dipfit2.* function traditionaldipfit()
% all others are enacted by electrodenormalize()
% {default: 'traditional}
% 'transform' - [real array] homogenous transformation matrix (>>help
% electrodenormalize) or a 1x9 matrix containing traditional
% 9-parameter "Talairach model" transformation (>> help traditional)
% used to calculate locs_out.
% 'chaninfo1' - [EEG.chaninfo struct] channel information structure for the
% montage to be coregistered. May contain (no-electrode) fiducial
% locations.
% 'chaninfo2' - [EEG.chaninfo struct] channel information structure for
% the reference montage.
% 'helpmsg' - ['on'|'off'] pop-up help message when calling function.
% {default: 'off'}
%
% Optional 'keywords' for MANUAL MODE (default):
% 'manual' - ['on'|'off'] Pops up the coregister() gui window to
% allow viewing the current alignment, performing 'alignfid' or
% 'warp' mode co-registration, and making manual
% adjustments. Default if 'on'.
%
% Optional 'keywords' for ALIGN MODE:
% 'alignfid' - {cell array of strings} = labels of (fiducial) channels to use
% as common landmarks for aligning the new channel locations to
% the reference locations. These labels must be in both channel
% locations (EEG.chanlocs) and/or EEG.chaninfo structures (see
% 'chaninfo1' and 'chaninfo2' below). Will then apply a linear
% transform including translation, rotation, and/or uniform
% scaling so as to best match the two sets of landmarks.
% See 'autoscale' below.
% 'autoscale' - ['on'|'off'] autoscale electrode radius when aligning
% fiducials. {default: 'on'}
%
% Optional 'keywords' for WARP MODE:
% 'warp' - {cell array of strings} channel labels used for non-linear
% warping of the new channel locations to reference locations.
% For example: Specifying all 10-20 channel labels will
% nonlinearly warp the 10-20 channel locations in the new
% chanlocs to the 10-20 locations in the reference chanlocs.
% Locations of other channels in the new chanlocs will be
% adjusted so as to produce a smooth warp. Entering the
% string 'auto' will automatically select the common channel
% labels.
%
% Outputs:
% chanlocs_out - transformed input channel locations (chanlocs) structure
% transform - transformation matrix. Use traditionaldipfit() to convert
% this to a homogenous transformation matrix used in
% 3-D plotting functions such as headplot().
%
% Note on how to create a template:
% (1) Extract a head mesh from a subject MRI (possibly in
% Matlab using the function isosurface).
% (2) Measure reference locations on the subject's head.
% (3) Align these locations to the extracted subject head mesh
% (using the coregister() graphic interface). The aligned locations
% then become reference locations for this mesh.
%
% Example:
% % This return the coregistration matrix to the MNI brain
% dipfitdefs;
% [newlocs transform] = coregister(EEG.chanlocs, template_models(2).chanfile, ...
% 'warp', 'auto', 'manual', 'off');
%
% % This pops-up the coregistration window for the BEM (MNI) model
% dipfitdefs;
% [newlocs transform] = coregister(EEG.chanlocs, template_models(2).chanfile, ...
% 'mesh', template_models(2).hdmfile);
%
% See also: traditionaldipfit(), headplot(), plotmesh(), electrodenormalize().
%
% Note: Calls Robert Oostenveld's FieldTrip coregistration functions for
% automatic coregistration.
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, 2005-06
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, 2005, [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
% Here we bypass channel info
% 'chaninfo' - [struct] channel information structure for the first
% dataset (may use a cell array { struct struct } to enter
% channel location info for both channel location struct.
%
function [ chanlocs1, transformmat ] = coregister(chanlocs1, chanlocs2, varargin)
if nargin < 1
help coregister
error('Not enough inputs');
end
if nargin < 2
chanlocs2 = [];
end
% manually for s1: transf = [4 0 -50 -0.3 0 -1.53 1.05 1.1 1.1]
% manually for s2: transf = [-4 -6 -50 -0.37 0 -1.35 1.1 1.15 1.1]
if isempty(chanlocs2)
dipfitdefs; chanlocs2 = template_models(1).chanfile;
end
% undocumented commands run from GUI
% ----------------------------------
if ischar(chanlocs1)
if ~strcmpi(chanlocs1, 'redraw') & ~strcmpi(chanlocs1, 'fiducials') & ~strcmpi(chanlocs1, 'warp')
chanlocs1 = readlocs(chanlocs1);
else
com = chanlocs1;
fid = chanlocs2;
% update GUI
% ----------
if strcmpi(com, 'redraw'), redrawgui(fid); return; end;
% select electrodes and warp montage
% ----------------------------------
dat = get(fid, 'userdata');
if strcmpi(com, 'fiducials')
[clist1 clist2] = pop_chancoresp( dat.elec1, dat.elec2, 'autoselect', 'fiducials');
try,
[ tmp transform ] = align_fiducials(dat.elec1, dat.elec2, dat.elec1.label(clist1), dat.elec2.label(clist2));
if ~isempty(transform), dat.transform = transform; end;
catch,
warndlg2(strvcat('Transformation failed', lasterr));
end;
elseif strcmpi(com, 'warp')
[clist1 clist2] = pop_chancoresp( dat.elec1, dat.elec2, 'autoselect', 'all');
% copy electrode names
if ~isempty(clist1)
tmpelec2 = dat.elec2;
for index = 1:length(clist2)
tmpelec2.label{clist2(index)} = dat.elec1.label{clist1(index)};
end;
%try,
[ tmp dat.transform ] = warp_chans(dat.elec1, tmpelec2, tmpelec2.label(clist2), 'traditional');
%catch,
% warndlg2(strvcat('Transformation failed', lasterr));
%end;
end;
end;
set(fid, 'userdata', dat);
redrawgui(fid);
return;
end;
end;
% check input arguments
% ---------------------
% defaultmesh = 'D:\matlab\eeglab\plugins\dipfit2.0\standard_BEM\standard_vol.mat';
defaultmesh = 'standard_vol.mat';
g = finputcheck(varargin, { 'alignfid' 'cell' {} {};
'warp' { 'string','cell' } { {} {} } {};
'warpmethod' 'string' {'rigidbody', 'globalrescale', 'traditional', 'nonlin1', 'nonlin2', 'nonlin3', 'nonlin4', 'nonlin5'} 'traditional';
'chaninfo1' 'struct' {} struct('no', {}); % default empty structure
'chaninfo2' 'struct' {} struct('no', {});
'transform' 'real' [] [];
'manual' 'string' { 'on','off' } 'on'; % -> pop up window
'autoscale' 'string' { 'on','off' } 'on';
'helpmsg' 'string' { 'on','off' } 'off';
'mesh' '' [] defaultmesh });
if ischar(g), error(g); end;
% load mesh if any
% ----------------
if ~isempty(g.mesh)
if ischar(g.mesh)
try
g.mesh = load(g.mesh);
catch, g.mesh = [];
end;
end;
if ischar(g.mesh)
if ~exist(g.mesh,'file')
fprintf('coregister(): mesh file not found\n');
end
end
if ~isempty(g.mesh)
if isstruct(g.mesh)
if isfield(g.mesh, 'vol')
if isfield(g.mesh.vol, 'r')
[X Y Z] = sphere(50);
dat.meshpnt = { X*max(g.mesh.vol.r) Y*max(g.mesh.vol.r) Z*max(g.mesh.vol.r) };
dat.meshtri = [];
else
dat.meshpnt = g.mesh.vol.bnd(1).pnt;
dat.meshtri = g.mesh.vol.bnd(1).tri;
end;
elseif isfield(g.mesh, 'bnd')
dat.meshpnt = g.mesh.bnd(1).pnt;
dat.meshtri = g.mesh.bnd(1).tri;
elseif isfield(g.mesh, 'TRI1')
dat.meshpnt = g.mesh.POS;
dat.meshtri = g.mesh.TRI1;
elseif isfield(g.mesh, 'vertices')
dat.meshpnt = g.mesh.vertices;
dat.meshtri = g.mesh.faces;
else
error('Unknown Matlab mesh file');
end;
else
dat.meshpnt = g.mesh{1};
dat.meshtri = g.mesh{2};
end;
else
dat.meshpnt = [];
dat.meshtri = [];
end;
else
dat.meshpnt = [];
dat.meshtri = [];
end;
% transform to arrays chanlocs1
% -------------------------
TMP = eeg_emptyset;
[TMP.chanlocs tmp2 tmp3 ind1] = readlocs(chanlocs1);
TMP.chaninfo = g.chaninfo1;
TMP.nbchan = length(TMP.chanlocs);
cfg = eeglab2fieldtrip(TMP, 'chanloc_withfid');
elec1 = cfg.elec;
% transform to arrays chanlocs2
% -------------------------
if ~isempty(chanlocs2)
TMP = eeg_emptyset;
[TMP.chanlocs tmp2 tmp3 ind1] = readlocs(chanlocs2);
TMP.chaninfo = g.chaninfo2;
TMP.nbchan = length(TMP.chanlocs);
cfg = eeglab2fieldtrip(TMP, 'chanloc_withfid');
elec2 = cfg.elec;
else
elec2 = [];
dat.transform = [ 0 0 0 0 0 0 1 1 1 ];
end;
% copy or compute alignment matrix
% --------------------------------
if ~isempty(g.transform)
dat.transform = g.transform;
else
% perfrom alignment
% -----------------
if strcmpi(g.autoscale, 'on')
avgrad1 = sqrt(sum(elec1.pnt.^2,2));
avgrad2 = sqrt(sum(elec2.pnt.^2,2));
ratio = mean(avgrad2)/mean(avgrad1);
else
ratio = 1;
end;
if ~isempty(g.alignfid)
% autoscale
% ---------
[ electransf transform ] = align_fiducials(electmp, elec2, g.alignfid);
if ~isempty(transform), dat.transform = [ transform(1:6)' ratio ratio ratio ]; end;
elseif ~isempty(g.warp)
if ischar(g.warp)
[clist1 clist2] = pop_chancoresp( elec1, elec2, 'autoselect', 'all', 'gui', 'off');
% copy electrode names
if isempty(clist1)
disp('Warning: cannot wrap electrodes (no common channel labels)');
else
tmpelec2 = elec2;
for index = 1:length(clist2)
tmpelec2.label{clist2(index)} = elec1.label{clist1(index)};
end;
try,
[ electransf dat.transform ] = warp_chans(elec1, tmpelec2, tmpelec2.label(clist2), 'traditional');
catch,
warndlg2(strvcat('Transformation failed', lasterr));
end;
end;
else
[ electransf dat.transform ] = warp_chans(elec1, elec2, g.warp, g.warpmethod);
end;
else
dat.transform = [0 0 0 0 0 0 ratio ratio ratio];
end;
end;
% manual mode off
% ---------------
if strcmpi(g.manual, 'off'),
transformmat = dat.transform;
dat.elec1 = elec1;
if size(dat.transform,1) > 1
dat.electransf.pnt = dat.transform*[ dat.elec1.pnt ones(size(dat.elec1.pnt,1),1) ]';
else
dat.electransf.pnt = traditionaldipfit(dat.transform)*[ dat.elec1.pnt ones(size(dat.elec1.pnt,1),1) ]';
end;
dat.electransf.pnt = dat.electransf.pnt(1:3,:)';
dat.electransf.label = dat.elec1.label;
chanlocs1 = dat.electransf;
return;
end;
% find common electrode names
% ---------------------------
dat.elec1 = elec1;
dat.elec2 = elec2;
dat.elecshow1 = 1:length(elec1.label);
dat.elecshow2 = 1:length(elec2.label);
dat.color1 = [0 1 0];
dat.color2 = [1 .75 .65]*.8;
%dat.color2 = [1 0 0];
dat.label1 = 0;
dat.label2 = 0;
dat.meshon = 1;
fid = figure('userdata', dat, 'name', 'coregister()', 'numbertitle', 'off');
try, icadefs; catch, end;
if 1
header = 'dattmp = get(gcbf, ''userdata'');';
footer = 'set(gcbf, ''userdata'', dattmp); clear dattmp; coregister(''redraw'', gcbf);';
cbright = [ header 'dattmp.transform(1) = str2num(get(gcbo, ''string''));' footer ];
cbforward = [ header 'dattmp.transform(2) = str2num(get(gcbo, ''string''));' footer ];
cbup = [ header 'dattmp.transform(3) = str2num(get(gcbo, ''string''));' footer ];
cbpitch = [ header 'dattmp.transform(4) = str2num(get(gcbo, ''string''));' footer ];
cbroll = [ header 'dattmp.transform(5) = str2num(get(gcbo, ''string''));' footer ];
cbyaw = [ header 'dattmp.transform(6) = str2num(get(gcbo, ''string''));' footer ];
cbresizex = [ header 'dattmp.transform(7) = str2num(get(gcbo, ''string''));' footer ];
cbresizey = [ header 'dattmp.transform(8) = str2num(get(gcbo, ''string''));' footer ];
cbresizez = [ header 'dattmp.transform(9) = str2num(get(gcbo, ''string''));' footer ];
cb_ok = 'set(gcbo, ''userdata'', ''ok'')';
cb_warp = 'coregister(''warp'', gcbf);';
cb_fid = 'coregister(''fiducials'', gcbf);';
opt = { 'unit', 'normalized', 'position' };
h = uicontrol( opt{:}, [0 .15 1 .02], 'style', 'text', 'string', '');
h = uicontrol( opt{:}, [0 .1 .2 .05], 'style', 'text', 'string', 'Move right {mm}');
h = uicontrol( opt{:}, [0 .05 .2 .05], 'style', 'text', 'string', 'Move front {mm}' );
h = uicontrol( opt{:}, [0 0 .2 .05], 'style', 'text', 'string', 'Move up {mm}');
h = uicontrol( opt{:}, [0.2 .1 .1 .05], 'tag', 'right' , 'callback', cbright , 'style', 'edit', 'string', '');
h = uicontrol( opt{:}, [0.2 .05 .1 .05], 'tag', 'forward', 'callback', cbforward, 'style', 'edit', 'string', '' );
h = uicontrol( opt{:}, [0.2 0 .1 .05], 'tag', 'up' , 'callback', cbup , 'style', 'edit', 'string', '');
h = uicontrol( opt{:}, [0.3 .1 .15 .05], 'style', 'text', 'string', 'Pitch (rad)');
h = uicontrol( opt{:}, [0.3 .05 .15 .05], 'style', 'text', 'string', 'Roll (rad)' );
h = uicontrol( opt{:}, [0.3 0 .15 .05], 'style', 'text', 'string', 'Yaw (rad)');
h = uicontrol( opt{:}, [0.45 .1 .1 .05], 'tag', 'pitch', 'callback', cbpitch, 'style', 'edit', 'string', '');
h = uicontrol( opt{:}, [0.45 .05 .1 .05], 'tag', 'roll' , 'callback', cbroll , 'style', 'edit', 'string', '' );
h = uicontrol( opt{:}, [0.45 0 .1 .05], 'tag', 'yaw' , 'callback', cbyaw , 'style', 'edit', 'string', '');
h = uicontrol( opt{:}, [0.55 .1 .15 .05], 'style', 'text', 'string', 'Resize {x}');
h = uicontrol( opt{:}, [0.55 .05 .15 .05], 'style', 'text', 'string', 'Resize {y}' );
h = uicontrol( opt{:}, [0.55 0 .15 .05], 'style', 'text', 'string', 'Resize {z}');
h = uicontrol( opt{:}, [0.7 .1 .1 .05], 'tag', 'resizex', 'callback', cbresizex, 'style', 'edit', 'string', '');
h = uicontrol( opt{:}, [0.7 .05 .1 .05], 'tag', 'resizey', 'callback', cbresizey, 'style', 'edit', 'string', '' );
h = uicontrol( opt{:}, [0.7 0 .1 .05], 'tag', 'resizez', 'callback', cbresizez, 'style', 'edit', 'string', '');
h = uicontrol( opt{:}, [0.8 .1 .2 .05], 'style', 'pushbutton', 'string', 'Align fiducials', 'callback', cb_fid);
h = uicontrol( opt{:}, [0.8 .05 .2 .05], 'style', 'pushbutton', 'string', 'Warp montage', 'callback', cb_warp );
h = uicontrol( opt{:}, [0.8 0 .1 .05], 'style', 'pushbutton', 'string', 'Cancel', 'callback', 'close(gcbf);' );
h = uicontrol( opt{:}, [0.9 0 .1 .05], 'style', 'pushbutton', 'string', 'Ok', 'tag', 'ok', 'callback', cb_ok);
% put labels next to electrodes
% -----------------------------
cb_label1 = [ 'tmp = get(gcbf, ''userdata'');' ...
'if tmp.label1, set(gcbo, ''string'', ''Labels on'');' ...
'else set(gcbo, ''string'', ''Labels off'');' ...
'end;' ...
'tmp.label1 = ~tmp.label1;' ...
'set(gcbf, ''userdata'', tmp);' ...
'clear tmp;' ...
'coregister(''redraw'', gcbf);' ];
cb_label2 = [ 'tmp = get(gcbf, ''userdata'');' ...
'if tmp.label2, set(gcbo, ''string'', ''Labels on'');' ...
'else set(gcbo, ''string'', ''Labels off'');' ...
'end;' ...
'tmp.label2 = ~tmp.label2;' ...
'set(gcbf, ''userdata'', tmp);' ...
'clear tmp;' ...
'coregister(''redraw'', gcbf);' ];
cb_mesh = [ 'tmp = get(gcbf, ''userdata'');' ...
'if tmp.meshon, set(gcbo, ''string'', ''Mesh on'');' ...
'else set(gcbo, ''string'', ''Mesh off'');' ...
'end;' ...
'tmp.meshon = ~tmp.meshon;' ...
'set(gcbf, ''userdata'', tmp);' ...
'clear tmp;' ...
'coregister(''redraw'', gcbf);' ];
cb_elecshow1 = [ 'tmp = get(gcbf, ''userdata'');' ...
'tmp.elecshow1 = pop_chansel( tmp.elec1.label, ''select'', tmp.elecshow1 );' ...
'if ~isempty(tmp.elecshow1), set(gcbf, ''userdata'', tmp);' ...
'coregister(''redraw'', gcbf); end; clear tmp;' ];
cb_elecshow2 = [ 'tmp = get(gcbf, ''userdata'');' ...
'tmpstrs = { ''21 elec (10/20 system)'' ''86 elec (10/10 system)'' ''all elec (10/5 system)'' };' ...
'tmpres = inputgui( ''uilist'', {{ ''style'' ''text'' ''string'' ''show only'' } ' ...
' { ''style'' ''listbox'' ''string'' strvcat(tmpstrs) }}, ' ...
' ''geometry'', { 1 1 }, ''geomvert'', [1 3] );' ...
'if ~isempty(tmpres), tmp.elecshow2 = tmpstrs{tmpres{1}}; end;' ...
'set(gcbf, ''userdata'', tmp);' ...
'clear tmp tmpres;' ...
'coregister(''redraw'', gcbf);' ];
h = uicontrol( opt{:}, [0 0.75 .13 .05], 'style', 'pushbutton', 'string', 'Mesh off', 'callback', cb_mesh );
% help message
% ------------
cb_helpme = [ 'warndlg2(strvcat( ''User channels (sometimes hidden in the 3-D mesh) are in green, reference channels in brown.'',' ...
'''Press "Warp" to automatically warp user channels to corresponding reference channels.'',' ...
'''Then, if desired, further edit the transformation manually using the coregister gui buttons.'',' ...
''' '',' ...
'''To use locations of corresponding reference channels (and discard current locations),'',' ...
'''select "Edit > Channel locations" in the EEGLAB mensu and press, "Look up loc." Select a '',' ...
'''head model. Then re-open "Tools > Locate dipoles using DIPFIT2 > Head model and settings"'',' ...
'''in the EEGLAB menu and select the "No coreg" option.'',' ];
if ~isstruct(chanlocs2)
if ~isempty(findstr(lower(chanlocs2), 'standard-10-5-cap385')) | ...
~isempty(findstr(lower(chanlocs2), 'standard_1005')),
cb_helpme = [ cb_helpme '''Then re-open "Tools > Locate dipoles using DIPFIT2 > Head model and settings"'',' ...
'''in the EEGLAB menu and select the "No coreg" option.''), ''Warning'');' ];
else
cb_helpme = [ cb_helpme '''Then re-open the graphic interface function you were using.''), ''Warning'');' ];
end;
end;
h = uicontrol( opt{:}, [0.87 0.95 .13 .05], 'style', 'pushbutton', 'string', 'Help me', 'callback', cb_helpme);
h = uicontrol( opt{:}, [0.87 0.90 .13 .05], 'style', 'pushbutton', 'string', 'Funct. help', 'callback', 'pophelp(''coregister'');' );
% change colors
% -------------
hh = findobj('parent', gcf, 'style', 'text');
set(hh, 'Backgroundcolor', GUIBACKCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
hh = findobj('parent', gcf, 'style', 'edit');
set(hh, 'Backgroundcolor', GUIBACKCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
hh = findobj('parent', gcf, 'style', 'pushbutton');
set(hh, 'Backgroundcolor', GUIBACKCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
h = uicontrol( opt{:}, [0 0.95 .13 .05], 'style', 'pushbutton', 'backgroundcolor', dat.color1, 'string', 'Labels on', 'callback', cb_label1 );
h = uicontrol( opt{:}, [0 0.9 .13 .05], 'style', 'pushbutton', 'backgroundcolor', dat.color1, 'string', 'Electrodes', 'callback', cb_elecshow1 );
h = uicontrol( opt{:}, [0 0.85 .13 .05], 'style', 'pushbutton', 'backgroundcolor', dat.color2, 'string', 'Labels on', 'callback', cb_label2 );
h = uicontrol( opt{:}, [0 0.8 .13 .05], 'style', 'pushbutton', 'backgroundcolor', dat.color2, 'string', 'Electrodes', 'callback', cb_elecshow2 );
end;
coregister('redraw', fid);
try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end
% wait until button press and return values
% -----------------------------------------
waitfor( findobj('parent', fid, 'tag', 'ok'), 'userdata');
try
tmpobj = findobj(fid); % figure still exist ?
if isempty(tmpobj), error(' '); end % After MATLAB 2014b
catch, transformmat = []; chanlocs1 = []; return; end;
dat = get(fid, 'userdata');
transformmat = dat.transform;
chanlocs1 = dat.electransf;
close(fid);
% plot electrodes
% ---------------
function plotelec(elec, elecshow, color, tag);
X1 = elec.pnt(elecshow,1);
Y1 = elec.pnt(elecshow,2);
Z1 = elec.pnt(elecshow,3);
XL = xlim;
YL = ylim;
ZL = zlim;
lim=max(1.05*max([X1;Y1;Z1]), max([XL YL ZL]));
eps=lim/20;
delete(findobj(gcf, 'tag', tag));
% make bigger if fiducial
% ------------------------
fidlist = { 'nz' 'lpa' 'rpa' 'nazion' 'left' 'right' 'nasion' 'fidnz' 'fidt9' 'fidt10'};
[tmp fids ] = intersect_bc(lower(elec.label(elecshow)), fidlist);
nonfids = setdiff_bc(1:length(elec.label(elecshow)), fids);
h1 = plot3(X1(nonfids),Y1(nonfids),Z1(nonfids), 'o', 'color', color); hold on;
set(h1, 'tag', tag, 'marker', '.', 'markersize', 20);
if ~isempty(fids)
h2 = plot3(X1(fids),Y1(fids),Z1(fids), 'o', 'color', color*2/3); hold on;
set(h2, 'tag', tag, 'marker', '.', 'markersize', 35); % make bigger if fiducial
end;
% plot axis and labels
%- -------------------
if isempty(findobj(gcf, 'tag', 'axlabels'))
plot3([0.08 0.12],[0 0],[0 0],'r','LineWidth',4) % nose
plot3([0 lim],[0 0],[0 0],'b--', 'tag', 'axlabels') % axis
plot3([0 0],[0 lim],[0 0],'g--')
plot3([0 0],[0 0],[0 lim],'r--')
plot3(0,0,0,'b+')
text(lim+eps,0,0,'X','HorizontalAlignment','center',...
'VerticalAlignment','middle','Color',[0 0 0],...
'FontSize',10)
text(0,lim+eps,0,'Y','HorizontalAlignment','center',...
'VerticalAlignment','middle','Color',[0 0 0],...
'FontSize',10)
text(0,0,lim+eps,'Z','HorizontalAlignment','center',...
'VerticalAlignment','middle','Color',[0 0 0],...
'FontSize',10)
box on
end;
lim = abs(lim(1)); axis([-lim lim -lim lim -lim*0.5 lim]);
axis equal;
% decode labels for electrode caps
% --------------------------------
% 86 channels
function indices = decodelabels( chanlocs, strchan );
label1020 = { 'nz' 'lpa' 'rpa' 'Fp1', 'Fpz', 'Fp2', 'F7', 'F3', 'Fz', 'F4', 'F8', 'T7', 'C3', 'Cz', 'C4', 'T8', 'P7', 'P3', 'Pz', 'P4', 'P8', 'O1', 'Oz', 'O2'}'; % 21 channels
label1010 = { 'nz' 'lpa' 'rpa' 'Fp1', 'Fpz', 'Fp2', 'AF9', 'AF7', 'AF5', 'AF3', 'AF1', 'AFz', 'AF2', 'AF4', 'AF6', 'AF8', 'AF10', 'F9', 'F7', 'F5', 'F3', 'F1', 'Fz', 'F2', 'F4', 'F6', 'F8', 'F10', 'FT9', 'FT7', 'FC5', 'FC3', 'FC1', 'FCz', 'FC2', 'FC4', 'FC6', 'FT8', 'FT10', 'T9', 'T7', 'C5', 'C3', 'C1', 'Cz', 'C2', ...
'C4', 'C6', 'T8', 'T10', 'TP9', 'TP7', 'CP5', 'CP3', 'CP1', 'CPz', 'CP2', 'CP4', 'CP6', 'TP8', 'TP10', 'P9', 'P7', 'P5', 'P3', 'P1', 'Pz', 'P2', 'P4', 'P6', 'P8', 'P10', 'PO9', 'PO7', 'PO5', 'PO3', 'PO1', 'POz', 'PO2', 'PO4', 'PO6', 'PO8', 'PO10', 'O1', 'Oz', 'O2', 'I1', 'Iz', 'I2'}'; ...
if ~ischar(strchan), indices = strchan; return; end;
switch strchan
case '21 elec (10/20 system)', indices = pop_chancoresp( struct('labels', chanlocs.label), struct('labels', label1020), 'gui', 'off');
case '86 elec (10/10 system)', indices = pop_chancoresp( struct('labels', chanlocs.label), struct('labels', label1010), 'gui', 'off');
case 'all elec (10/5 system)', indices = 1:length(chanlocs.label);
otherwise, error('Unknown option');
end;
% plot electrode labels
% ---------------------
function plotlabels(elec, elecshow, color, tag);
for i = 1:length(elecshow)
coords = elec.pnt(elecshow(i),:);
coords = coords*1.07;
text(coords(1), coords(2), coords(3), elec.label{elecshow(i)},'HorizontalAlignment','center',...
'VerticalAlignment','middle','Color',color, 'FontSize',10, 'tag', tag)
end
% align fiducials
% ---------------
function [elec1, transf] = align_fiducials(elec1, elec2, fidnames1, fidnames2)
% rename fiducials
% ----------------
ind1 = strmatch(fidnames1{1}, elec1.label, 'exact'); elec1.label{ind1} = fidnames2{1};
ind2 = strmatch(fidnames1{2}, elec1.label, 'exact'); elec1.label{ind2} = fidnames2{2};
ind3 = strmatch(fidnames1{3}, elec1.label, 'exact'); elec1.label{ind3} = fidnames2{3};
cfg = [];
cfg.elec = elec1;
cfg.template = elec2;
cfg.method = 'realignfiducial';
cfg.fiducial = fidnames2;
elec3 = electroderealign(cfg);
transf = homogenous2traditional(elec3.m);
% test difference
% ---------------
diff1 = mean(mean(abs(elec3.m-traditionaldipfit(transf))));
transf(6) = -transf(6);
diff2 = mean(mean(abs(elec3.m-traditionaldipfit(transf))));
if diff1 < diff2, transf(6) = -transf(6); end;
diff1 = mean(mean(abs(elec3.m-traditionaldipfit(transf))));
transf(5) = -transf(5);
diff2 = mean(mean(abs(elec3.m-traditionaldipfit(transf))));
if diff1 < diff2, transf(5) = -transf(5); end;
diff1 = mean(mean(abs(elec3.m-traditionaldipfit(transf))));
transf(4) = -transf(4);
diff2 = mean(mean(abs(elec3.m-traditionaldipfit(transf))));
if diff1 < diff2, transf(4) = -transf(4); end;
% rescale if necessary
% --------------------
coords1 = elec1.pnt([ind1 ind2 ind3],:); dist_coords1 = sqrt(sum(coords1.^2,2));
ind1 = strmatch(fidnames2{1}, elec2.label, 'exact');
ind2 = strmatch(fidnames2{2}, elec2.label, 'exact');
ind3 = strmatch(fidnames2{3}, elec2.label, 'exact');
coords2 = elec2.pnt([ind1 ind2 ind3],:); dist_coords2 = sqrt(sum(coords2.^2,2));
ratio = mean(dist_coords2./dist_coords1);
transf(7:9) = ratio;
transfmat = traditionaldipfit(transf);
elec1.pnt = transfmat*[ elec1.pnt ones(size(elec1.pnt,1),1) ]';
elec1.pnt = elec1.pnt(1:3,:)';
% warp channels
% -------------
function [elec1, transf] = warp_chans(elec1, elec2, chanlist, warpmethod)
cfg = [];
cfg.elec = elec1;
cfg.template = elec2;
cfg.method = warpmethod;
%cfg.feedback = 'yes';
cfg.channel = chanlist;
elec3 = electroderealign(cfg);
[tmp ind1 ] = intersect_bc( lower(elec1.label), lower(chanlist) );
[tmp ind2 ] = intersect_bc( lower(elec2.label), lower(chanlist) );
transf = elec3.m;
transf(4:6) = transf(4:6)/180*pi;
if length(transf) == 6, transf(7:9) = 1; end;
transf = checktransf(transf, elec1, elec2);
dpre = mean(sqrt(sum((elec1.pnt(ind1,:) - elec2.pnt(ind2,:)).^2, 2)));
transfmat = traditionaldipfit(transf);
elec1.pnt = transfmat*[ elec1.pnt ones(size(elec1.pnt,1),1) ]';
elec1.pnt = elec1.pnt(1:3,:)';
dpost = mean(sqrt(sum((elec1.pnt(ind1,:) - elec2.pnt(ind2,:)).^2, 2)));
fprintf('mean distance prior to warping %f, after warping %f\n', dpre, dpost);
% test difference and invert axis if necessary
% --------------------------------------------
function transf = checktransf(transf, elec1, elec2)
[tmp ind1 ind2] = intersect_bc( elec1.label, elec2.label );
transfmat = traditionaldipfit(transf);
tmppnt = transfmat*[ elec1.pnt ones(size(elec1.pnt,1),1) ]';
tmppnt = tmppnt(1:3,:)';
diff1 = tmppnt(ind1,:) - elec2.pnt(ind2,:);
diff1 = mean(sum(diff1.^2,2));
transf(6) = -transf(6); % yaw angle is sometimes inverted
transfmat = traditionaldipfit(transf);
tmppnt = transfmat*[ elec1.pnt ones(size(elec1.pnt,1),1) ]';
tmppnt = tmppnt(1:3,:)';
diff2 = tmppnt(ind1,:) - elec2.pnt(ind2,:);
diff2 = mean(sum(diff2.^2,2));
if diff1 < diff2, transf(6) = -transf(6); else diff1 = diff2; end;
transf(4) = -transf(4); % yaw angle is sometimes inverted
transfmat = traditionaldipfit(transf);
tmppnt = transfmat*[ elec1.pnt ones(size(elec1.pnt,1),1) ]';
tmppnt = tmppnt(1:3,:)';
diff2 = tmppnt(ind1,:) - elec2.pnt(ind2,:);
diff2 = mean(sum(diff2.^2,2));
if diff1 < diff2, transf(4) = -transf(4); end;
% redraw GUI
% ----------
function redrawgui(fid)
dat = get(fid, 'userdata');
tmpobj = findobj(fid, 'tag', 'pitch'); set(tmpobj, 'string', num2str(dat.transform(4),4));
tmpobj = findobj(fid, 'tag', 'roll' ); set(tmpobj, 'string', num2str(dat.transform(5),4));
tmpobj = findobj(fid, 'tag', 'yaw' ); set(tmpobj, 'string', num2str(dat.transform(6),4));
tmpobj = findobj(fid, 'tag', 'right' ); set(tmpobj, 'string', num2str(dat.transform(1),4));
tmpobj = findobj(fid, 'tag', 'forward'); set(tmpobj, 'string', num2str(dat.transform(2),4));
tmpobj = findobj(fid, 'tag', 'up' ); set(tmpobj, 'string', num2str(dat.transform(3),4));
tmpobj = findobj(fid, 'tag', 'resizex'); set(tmpobj, 'string', num2str(dat.transform(7),4));
tmpobj = findobj(fid, 'tag', 'resizey'); set(tmpobj, 'string', num2str(dat.transform(8),4));
tmpobj = findobj(fid, 'tag', 'resizez'); set(tmpobj, 'string', num2str(dat.transform(9),4));
tmpview = view;
if size(dat.transform,1) > 1
dat.electransf.pnt = dat.transform*[ dat.elec1.pnt ones(size(dat.elec1.pnt,1),1) ]';
else
dat.electransf.pnt = traditionaldipfit(dat.transform)*[ dat.elec1.pnt ones(size(dat.elec1.pnt,1),1) ]';
end;
dat.electransf.pnt = dat.electransf.pnt(1:3,:)';
dat.electransf.label = dat.elec1.label;
set(fid, 'userdata', dat);
h = findobj(fid, 'tag', 'plot3d');
if isempty(h)
axis off;
h = axes('unit', 'normalized', 'position', [0 0.2 1 0.75]);
set(h, 'tag', 'plot3d');
axis off;
else
axes(h);
%axis off;
end;
plotelec(dat.electransf, dat.elecshow1, dat.color1, 'elec1');
if ~isempty(dat.elec2)
dat.elecshow2 = decodelabels( dat.elec2, dat.elecshow2 );
plotelec(dat.elec2, dat.elecshow2, dat.color2, 'elec2');
end;
set(h, 'tag', 'plot3d');
% plot mesh
% ---------
if ~isempty(dat.meshpnt) & isempty(findobj(gcf, 'tag', 'mesh'))
if ~isempty(dat.meshtri)
p1 = plotmesh(dat.meshtri, dat.meshpnt, [], 1);
set(p1, 'tag', 'mesh');
else
facecolor(1,1,1) = 1; facecolor(1,1,2) = .75; facecolor(1,1,3) = .65;
cdat = repmat( facecolor, [ size(dat.meshpnt{1}) 1]);
h = mesh(dat.meshpnt{1}, dat.meshpnt{2}, dat.meshpnt{3}, ...
'cdata', cdat, 'tag', 'mesh', 'facecolor', squeeze(facecolor), 'edgecolor', 'none');
hidden off;
lightangle(45,30);
lightangle(45+180,30);
lighting phong
s = plotnose([85 0 -75 0 0 pi/2 10 10 40]);
set(s, 'tag', 'mesh');
end;
end;
meshobj = findobj(gcf, 'tag', 'mesh');
if dat.meshon
set( meshobj, 'visible', 'on');
else set( meshobj, 'visible', 'off');
end;
% plot electrodes
% ---------------
delete(findobj(gcf, 'tag', 'elec1labels'));
delete(findobj(gcf, 'tag', 'elec2labels'));
if dat.label1
plotlabels(dat.electransf, dat.elecshow1, dat.color1, 'elec1labels');
end;
if dat.label2
plotlabels(dat.elec2, dat.elecshow2, dat.color2*0.5, 'elec2labels');
end;
%view(tmpview);
rotate3d on
% function to plot the nose
% -------------------------
function s = plotnose(transf, col)
if nargin < 1
transf = [0 0 0 0 0 0 1 1 1];
end;
if nargin < 2
col = [1 0.75 0.65 ];
end;
x=[ % cube
NaN -1 1 NaN
-1 -1 1 1
-1 -1 1 1
NaN -1 1 NaN
NaN -1 1 NaN
NaN NaN NaN NaN
];
y=[ % cube
NaN -1 -1 NaN
-1 -1 -1 -1
1 1 1 1
NaN 1 1 NaN
NaN -1 -1 NaN
NaN NaN NaN NaN
];
z=[ % cube
NaN 0 0 NaN
0 1 1 0
0 1 1 0
NaN 0 0 NaN
NaN 0 0 NaN
NaN NaN NaN NaN
];
x=[ % noze
NaN -1 1 NaN
-1 0 0 1
-.3 0 0 .3
NaN -.3 .3 NaN
NaN -1 1 NaN
NaN NaN NaN NaN
];
y=[ % noze
NaN -1 -1 NaN
-1 -1 -1 -1
1 -1 -1 1
NaN 1 1 NaN
NaN -1 -1 NaN
NaN NaN NaN NaN
];
z=[ % noze
NaN 0 0 NaN
0 1 1 0
0 1 1 0
NaN 0 0 NaN
NaN 0 0 NaN
NaN NaN NaN NaN
];
% apply homogenous transformation
% -------------------------------
transfhom = traditionaldipfit( transf );
xyz = [ x(:) y(:) z(:) ones(length(x(:)),1) ];
xyz2 = transfhom * xyz';
x(:) = xyz2(1,:)';
y(:) = xyz2(2,:)';
z(:) = xyz2(3,:)';
% dealing with colors
% -------------------
cc=zeros(8,3);
cc(1,:) = col;
cc(2,:) = col;
cc(3,:) = col;
cc(4,:) = col;
cc(5,:) = col;
cc(6,:) = col;
cc(7,:) = col;
cc(8,:) = col;
cc(1,:)=[0 0 0]; % black
cc(2,:)=[1 0 0]; % red
cc(3,:)=[0 1 0]; % green
cc(4,:)=[0 0 1]; % blue
cc(5,:)=[1 0 1]; % magenta
cc(6,:)=[0 1 1]; % cyan
cc(7,:)=[1 1 0]; % yellow
cc(8,:)=[1 1 1]; % white
cs=size(x);
c=repmat(zeros(cs),[1 1 3]);
for i=1:size(cc,1)
ix=find(x==cc(i,1) &...
y==cc(i,2) &...
z==cc(i,3));
[ir,ic]=ind2sub(cs,ix);
for k=1:3
for m=1:length(ir)
c(ir(m),ic(m),k)=cc(i,k);
end
end
end
% plotting surface
% ----------------
facecolor = zeros(size(x,1), size(z,2), 3);
facecolor(:,:,1) = 1; facecolor(:,:,2) = .75; facecolor(:,:,3) = .65;
s=surf(x,y,z,facecolor);
set(s, 'edgecolor', [0.5 0.5 0.5]);
|
github
|
lcnhappe/happe-master
|
transformcoords.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/transformcoords.m
| 4,303 |
utf_8
|
5c18fcc7b4908f6238aee6106d85e43c
|
% transformcoords() - Select nazion and inion in anatomical MRI images.
%
% Usage:
% mewcoords = transformcoords(coords, rotate, scale, center, reverse);
%
% Inputs:
% coords - array of 3-D coordinates (3 by N or N by 3)
% rotate - [pitch roll yaw] rotate in 3-D using pitch (x plane),
% roll (y plane) and yaw (z plane). An empty array does
% not perform any rotation.
% scale - [scalex scaley scalez] scale axis. A single numeric
% input scale all the dimentions the same. Default 1
% does not scale.
% shifts - [x y z] shift coordinates (after rotation and scaling).
% Default [0 0 0] does not move the center.
% reverse - [0|1] when set to 1 perform the reverse transformation,
% first moving to the old center, unscaling, and unrotating.
% Default is 0.
%
% Output:
% newcoords - coordinates after rotating, scaling and recentering
%
% Author: Arnaud Delorme, Salk, SCCN, UCSD, CA, March 23, 2004
% Copyright (C) 2004 Arnaud Delorme
%
% 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 coords = transformcoords(coords, rotate, scale, center, reverse);
if nargin < 2
help transformcoords;
return;
end;
if nargin < 3
scale =1;
end;
if nargin < 4
center = [0 0 0];
end;
if nargin < 5
reverse = 0;
end;
if size(coords, 1) ~= 3
coords = coords';
trp = 1;
else
trp = 0;
end;
if size(coords, 1) ~= 3
error('Number of columns must be 3 for the coordinate input');
end;
if length(rotate) > 0 & length(rotate) ~= 3
error('rotate parameter must have 3 values');
end;
% decode parameters
% -----------------
centx = -center(1);
centy = -center(2);
centz = -center(3);
if length(scale) == 1
scale = [scale scale scale];
end;
scalex = scale(1);
scaley = scale(2);
scalez = scale(3);
if length(rotate) < 3
rotate = [0 0 0]
end;
pitch = rotate(1);
roll = rotate(2);
yaw = rotate(3);
if ~reverse
% pitch roll yaw rotation
% -----------------------
% pitch (x-axis); roll = y axis rotation; yaw = z axis
% see http://bishopw.loni.ucla.edu/AIR5/homogenous.html
cp = cos(pitch); sp = sin(pitch);
cr = cos(roll); sr = sin(roll);
cy = cos(yaw); sy = sin(yaw);
rot3d = [ cy*cr+sy*sp*sr sy*cr-cy*sp*sr cp*sr ;
-sy*cp cy*cp sp ;
sy*sp*cr-cy*sr -cy*sp*cr-sy*sr cp*cr ];
coords = rot3d*coords;
% scaling and centering
% ---------------------
coords(1,:) = coords(1,:)*scalex-centx;
coords(2,:) = coords(2,:)*scaley-centy;
coords(3,:) = coords(3,:)*scalez-centz;
else
% unscaling and uncentering
% -------------------------
coords(1,:) = (coords(1,:)+centx)/scalex;
coords(2,:) = (coords(2,:)+centy)/scaley;
coords(3,:) = (coords(3,:)+centz)/scalez;
% pitch roll yaw rotation
% -----------------------
cp = cos(-pitch); sp = sin(-pitch);
cr = cos(-roll); sr = sin(-roll);
cy = cos(-yaw); sy = sin(-yaw);
rot3d = [ cy*cr+sy*sp*sr sy*cr-cy*sp*sr cp*sr ;
-sy*cp cy*cp sp ;
sy*sp*cr-cy*sr -cy*sp*cr-sy*sr cp*cr ];
coords = rot3d*coords;
end;
if trp
coords = coords';
end;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.