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
|
ZijingMao/baselineeegtest-master
|
condstat.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/condstat.m
| 11,329 |
utf_8
|
836535e93ffa6254c14453b1557107cd
|
% condstat() - accumulate surrogate data for comparing two data conditions
%
% Usage:
% >> [diffres, accres, res1, res2] = condstat(formula, naccu, alpha, ...
% bootside, condboot, arg1, arg2 ...);
%
% Inputs:
% formula - [string or cell array of strings] formula(s) to compute a given measure.
% Takes arguments 'arg1', 'arg2' ... and X as inputs. e.g.,
% 'sum(arg1(:,:,X),3) ./ sqrt(sum(arg2(:,:,X))) ./ sqrt(sum(arg3(:,:,X)))'
% naccu - [integer] number of accumulations of surrogate data. e.g., 200
% alpha - [float] significance level (0<alpha<0.5)
% bootside - ['both'|'upper'] side of the surrogate distribution to
% consider for significance. This parameter affect the size
% of the last dimension of accumulation array 'accres' (size
% is 2 for 'both' and 1 for 'upper').
% condboot - ['abs'|'angle'|'complex'|''] When comparing two conditions, compare
% either absolute vales ('abs'), angles ('angles') or complex values
% ('complex'). Either '' or 'complex' leave the formula unchanged;
% 'abs' takes its norm before subtraction, and 'angle' normalizes
% each value (to norm 1) before taking the difference.
% arg1 - [cell_array] of two 1D,2D,or 3D matrices of values to compare.
% The last dimension of the array is shuffled to accumulate data, the
% other dimensions must be the same size across matrices.
% e.g. size(arg1{1})=[100 200 500], size(arg1{2})=[100 200 395]
% arg2 - same as arg1, note that it is compared only to itself, and has
% nothing to do with arg1 besides using the same formula, alpha, etc.
% ...argn - may call n number of arguement pairs
%
% Outputs:
% diffres - difference array for the actual (non-shuffled) data, if more than one
% arg pair is called, format is a cell array of matrices.
% accres - [cell array of 3D numerical arrays] for shuffled data, one per formula.
% res1 - result for first condition
% res2 - result for second condition
%
% Authors: Arnaud Delorme & Scott Makeig
% CNL/Salk Institute 1998-2001; SCCN/INC/UCSD, La Jolla, 2002-
%
% See also: timef(), crossf()
% Copyright (C) 2002 Arnaud Delorme, Lars Kai Hansen & Scott Makeig, 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
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [diffres, accres, res1, res2] = condstat(formula, naccu, alpha, bootside, condboot, varargin);
if nargin < 6
help condstat;
return;
end;
if ~ischar(formula) & ~iscell(formula)
error('The first argument must be a string formula or cell array of string');
end;
if ischar(formula)
formula = { formula };
end;
if ischar(bootside)
bootside = { bootside };
end;
for index = 1:length(bootside)
if ~strcmpi(bootside, 'both') & ~strcmpi(bootside, 'upper')
error('Bootside must be either ''both'' or ''upper''');
end;
end;
if ischar(condboot)
condboot = { condboot };
end;
for index = 1:length(condboot)
if isempty(condboot{index}), condboot{index} = 'complex'; end;
end;
for index = 1:length(varargin)
if ~iscell(varargin) | length(varargin{index}) ~=2
error('Except for the first arguments, all other arguments given to the function must be cell arrays of two numerical array');
end;
end;
% accumulate coherence images (all arrays [nb_points x timesout x trials])
% ---------------------------
for index=1:length(varargin)
tmpvar1 = varargin{index}{1};
tmpvar2 = varargin{index}{2};
if index == 1 % Shouldn't this be recalculated for arg2, etc.? TF 2007.06.04
cond1trials = size(tmpvar1,ndims(tmpvar1));
cond2trials = size(tmpvar2,ndims(tmpvar2));
for tmpi = 1:length(formula)
accres{tmpi} = zeros(size(tmpvar1,1), size(tmpvar1,2), naccu);
end;
end;
if ndims(tmpvar1) == 2
eval( [ 'arg' int2str(index) '=zeros(size(tmpvar1,1), cond1trials+cond2trials);' ] );
eval( [ 'arg' int2str(index) '(:,1:cond1trials)=tmpvar1;' ] );
eval( [ 'arg' int2str(index) '(:,cond1trials+1:end)=tmpvar2;' ] );
else
eval( [ 'arg' int2str(index) '=zeros(size(tmpvar1,1), size(tmpvar1,2), cond1trials+cond2trials);' ] );
eval( [ 'arg' int2str(index) '(:,:,1:cond1trials)=tmpvar1;' ] );
eval( [ 'arg' int2str(index) '(:,:,cond1trials+1:end)=tmpvar2;' ] );
end;
end;
fprintf('Accumulating permutation statistics:');
alltrials = [1:cond1trials+cond2trials];
% processing formulas
% -------------------
formula1 = [];
formula2 = [];
for index = 1:length(formula)
% updating formula
% ----------------
switch lower(condboot{ min(length(condboot), index) })
case 'abs', formula{index} = [ 'abs(' formula{index} ')' ];
%case 'angle', formula{index} = [ 'exp(j*angle(' formula{index} '))' ];
case 'angle', formula{index} = [ 'angle(' formula{index} ')/(2*pi)' ];
case 'complex', ;
otherwise, condboot, error('condstat argument must be either ''abs'', ''angle'', ''complex'' or empty');
end;
% computing difference (non-shuffled)
% -----------------------------------
X = 1:cond1trials;
eval( [ 'res1{index} = ' formula{index} ';'] );
X = cond1trials+1:cond1trials+cond2trials;
eval( [ 'res2{index} = ' formula{index} ';'] );
diffres{index} = res1{index}-res2{index};
% build formula to execute
% ------------------------
arrayname = [ 'accres{' int2str(index) '}' ];
if ndims(tmpvar1) == 2 % 2 dimensions
formula1 = [ formula1 arrayname '(:,index) = ' formula{index} ';'];
formala2 = [ formula2 arrayname '(:,index) = ' arrayname '(:,index) - ' formula{index} ';'];
else % 3 dimensions
formula1 = [ formula1 arrayname '(:,:,index) = ' formula{index} ';'];
formula2 = [ formula2 arrayname '(:,:,index) = ' arrayname '(:,:,index) - ' formula{index} ';'];
end;
end;
% accumulating (shuffling)
% -----------------------
for index=1:naccu
if rem(index,10) == 0, fprintf(' %d',index); end
if rem(index,120) == 0, fprintf('\n'); end
alltrials = shuffle(alltrials);
X = alltrials(1:cond1trials);
eval( formula1 );
X = alltrials(cond1trials+1:end);
eval( formula2 );
end;
% significance level
% ------------------
for index= 1:length(formula)
accarray = accres{index};
% size = nb_points*naccu
% size = nb_points*naccu*times
if ~isreal(accarray) % might want to introduce a warning here: a complex
% result may not be desirable, and a single complex value
% in accarray could turn this from a 2-tail to 1-tail
% bootstrap test, leading to false positives. Hard to
% think of a meaningful warning though...
% TF 2007.06.04
accarray = sqrt(accarray .* conj(accarray)); % faster than abs()
end;
% compute bootstrap significance level
i = round(naccu*alpha);
switch ndims(accarray)
case 3,
accarray = sort(accarray,3); % always sort on naccu (when 3D, naccu is the second dim)
if strcmpi(bootside{min(length(bootside), index)}, 'upper');
accarray = mean(accarray(:,:,naccu-i+1:naccu),3);
else
accarray = accarray(:,:,[end:-1:1]);
accarraytmp(:,:,2) = mean(accarray(:,:,1:i),3);
accarraytmp(:,:,1) = mean(accarray(:,:,naccu-i+1:naccu),3);
accarray = accarraytmp;
end;
case 2,
accarray = sort(accarray,2); % always sort on naccu (when 3D, naccu is the second dim)
if strcmpi(bootside{min(length(bootside), index)}, 'upper');
accarray = mean(accarray(:,naccu-i+1:naccu),2);
else
accarraytmp(:,2) = mean(accarray(:,1:i),2);
accarraytmp(:,1) = mean(accarray(:,naccu-i+1:naccu),2);
accarray = accarraytmp;
end;
case 1,
accarray = sort(accarray,1); % always sort on naccu (when 3D, naccu is the second dim)
if strcmpi(bootside{min(length(bootside), index)}, 'upper');
accarray = mean(accarray(naccu-i+1:naccu),1);
else
accarraytmp(2) = mean(accarray(1:i),1);
accarraytmp(1) = mean(accarray(naccu-i+1:naccu),1);
accarray = accarraytmp;
end;
end;
accres{index} = accarray;
end;
if length(res1) == 1
res1 = res1{1};
res2 = res2{1};
diffres = diffres{1};
accres = accres{1};
end;
fprintf('\n');
return;
% writing a function
% ------------------
% $$$ fid = fopen('tmpfunc.m', 'w');
% $$$ fprintf(fid, 'function [accres] = tmpfunc(alltrials, cond1trials, naccu,');
% $$$ for index=1:length(varargin)
% $$$ fprintf(fid, 'arg%d', index);
% $$$ if index ~=length(varargin), fprintf(fid,','); end;
% $$$ end;
% $$$ fprintf(fid, ')\n');
% $$$ commandstr = [ 'for index=1:naccu, ' ]
% $$$ % 'if rem(index,10) == 0, disp(index); end;' ];
% $$$ % 'if rem(index,10) == 0, fprintf('' %d'',index); end;' ...
% $$$ % 'if rem(index,120) == 0, fprintf(''\n''); end;' ];
% $$$ commandstr = [ commandstr 'shuffle(alltrials);' ];
% $$$ commandstr = [ commandstr 'X = alltrials(1:cond1trials);' ];
% $$$ if ndims(tmpvar1) == 2 % 2 dimensions
% $$$ commandstr = [ commandstr 'accres(:,index) = ' formula ';'];
% $$$ commandstr = [ commandstr 'X = alltrials(cond1trials+1:end);'];
% $$$ commandstr = [ commandstr 'accres(:,index) = accres(:,index)-' formula ';end;'];
% $$$ else
% $$$ commandstr = [ commandstr 'res1 = ' formula ';' 10];
% $$$ commandstr = [ commandstr 'X = alltrials(cond1trials+1:end);' 10];
% $$$ commandstr = [ commandstr 'res2 = ' formula ';' 10];
% $$$ commandstr = [ commandstr 'accres(:,:,index) = res1 - res2; end;'];
% $$$ end;
% $$$ fprintf(fid, commandstr);
% $$$ fclose(fid);
% $$$ profile on;
% $$$ accres = tmpfunc(alltrials, cond1trials, naccu, arg1);
% $$$ profile report;
% $$$ profile off;
% $$$ return;
% evaluating a command
% --------------------
% $$$ commandstr = [ 'for index=1:naccu, ' ...
% $$$ 'if rem(index,10) == 0, fprintf('' %d'',index); end;' ...
% $$$ 'if rem(index,120) == 0, fprintf(''\n''); end;' ];
% $$$ commandstr = [ commandstr 'shuffle(alltrials);' ];
% $$$ commandstr = [ commandstr 'X = alltrials(1:cond1trials);' ];
% $$$ if ndims(tmpvar1) == 2 % 2 dimensions
% $$$ commandstr = [ commandstr 'accres(:,index) = ' formula ';'];
% $$$ commandstr = [ commandstr 'X = alltrials(cond1trials+1:end);'];
% $$$ commandstr = [ commandstr 'accres(:,index) = accres(:,index)-' formula ';end;'];
% $$$ else
% $$$ commandstr = [ commandstr 'accres(:,:,index) = ' formula ';'];
% $$$ commandstr = [ commandstr 'X = alltrials(cond1trials+1:end);'];
% $$$ commandstr = [ commandstr 'accres(:,:,index) = accres(:,:,index)-' formula ';end;'];
% $$$ end;
% $$$ eval(commandstr);
% $$$ return;
% $$$
|
github
|
ZijingMao/baselineeegtest-master
|
movav.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/movav.m
| 7,664 |
utf_8
|
a7743cb15a5f70fdc8db72736287f7ec
|
% movav() - Perform a moving average of data indexed by xvals.
% Supports use of a moving non-rectangular window.
% Can be used to resample a data matrix to any size
% (see xadv NOTE below) and to regularize sampling of
% irregularly sampled data.
% Usage:
% >> [outdata,outx] = movav(data,xvals,xwidth,xadv,firstx,lastx,xwin,nonorm);
%
% Input:
% data = input data (chans,frames)
%
% Optional inputs:
% xvals = increasing x-values for data frames (columnsa). The default
% [1:frames] is fastest {def|[]|0 -> 1:frames}
% xwidth = smoothing-window width in xvals units {def|0->(hix-lox)/4}
% xadv = window step size in xvals units. NOTE: To reduce yyy frames
% to about xxx, xadv needs to be near yyy/xxx {default|0 -> 1}
% firstx = low xval of first averaging window {def|[] -> min xvals}
% lastx = high xval of last averaging window {def|[] -> max xvals}
% xwin = vector of window values {def|0 -> ones() = square window}
% May be long. NOTE: linear interp. is NOT used between values.
% Example: gauss(1001,2) -> [0.018 ... 1.0 ... 0.018]
% nonorm = [1|0] If non-zero, do not normalize the moving sum. If
% all y values are 1s. this creates a moving histogram.
% Ex: >> [oy,ox] = movav(ones(size(x)),x,xwd,xadv,[],[],0,1);
% returns a moving histogram of xvals {default: 0}
% Outputs:
% outdata = smoothed output data (chans,outframes)
% outx = xval midpoints of successive output windows
%
% Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 10-25-97
% Copyright (C) 10-25-97 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-20-98 fixed bug in multi-channel windowed averaging -sm
% 6-10-98 changed mean() and sum() to nanmean() and nansum() -sm
% 2-16-99 tested for stat toolbox functions nanmean() and nansum() -sm
% 9-03-01 fixed gauss() example -sm
% 01-25-02 reformated help & licenses -ad
function [outdata,outx] = movav(data,xvals,xwidth,xadv,firstx,lastx,xwin,nonorm)
MAXPRINT = 1; % max outframe numbers to print on tty
NEARZERO = 1e-22; %
DEFAULT_XADV = 1; % default xvals window step advance
verbose = 0; % If 1, output process info
nanexist = 0;
if nargin<1
help movav
return
else
[chans,frames]=size(data);
end
if chans>1 & frames == 1,
data = data'; % make row vector
tmp = chans;
chans = frames;
frames = tmp;
end
if frames < 4
error('data are too short');
return
end
flag_fastave = 0;
if nargin<2 | isempty(xvals) | (numel(xvals)==1 & xvals == 0)
xvals = 1:frames; % flag default xvals
flag_fastave = 0; % TURNED OFF THIS FEATURE - LEADS TO ?? BUG AT ABOUT 287
end % -sm 3/6/07
if size(xvals,1)>1 & size(xvals,2)>1
error('xvals must be a vector');
end
xvals = xvals(:)'; % make xvals a row vector
if frames ~= length(xvals)
error('lengths of xvals and data not equal');
end
if nargin < 8 | isempty(nonorm)
nonorm = 0; % default -> return moving mean
end
if abs(nonorm) > NEARZERO
nonorm = 1;
end
if nargin < 7 | isempty(xwin)
xwin = 0;
end
if nargin < 6 | isempty(lastx)
lastx = [];
end
if isempty(lastx),
if flag_fastave
lastx = frames;
else
lastx = max(xvals);
end
end
if nargin<5 | isempty(firstx)
firstx = [];
end
if isempty(firstx),
if flag_fastave
firstx = 1;
else
firstx = min(xvals);
end
end
if nargin<4 | isempty(xadv)
xadv = 0;
end
if isempty(xadv) | xadv == 0,
xadv = DEFAULT_XADV;
end
if nargin<3 | isempty(xwidth) | xwidth==0
xwidth = (lastx-firstx)/4; % DEFAULT XWIDTH
end
wlen = 1; % default;
if flag_fastave==0
if length(xwin)==1 & (xwin~=0) & (xwin~=1), % should be a vector or 0
error('xwin not vector or 0');
elseif size(xwin,1)>1 & size(xwin,2)>1 % not a matrix
error('xwin cannot be a matrix');
end
if size(xwin,1)>1
xwin = xwin'; % make row vector
end
if xwin~=0
wlen = length(xwin);
end
end
%outframes = floor(0.99999+((lastx-firstx+xadv)-xwidth)/xadv);
outframes = floor(((lastx-firstx+xadv+1)-xwidth)/xadv);
if verbose
fprintf('movav() will output %d frames.\n',outframes);
end
if outframes < 1,
outframes = 1;
end
outdata = zeros(chans,outframes);
outx = zeros(1,outframes);
outxval = firstx+xwidth/2;
%
%%%%%%%%%%%%%%%%%%%%%% Print header %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if verbose,
fprintf('Performing moving averaging:\n')
fprintf('Output will be %d chans by %d frames',chans,outframes);
if wlen>1,
fprintf(' using the specified width-%d window\n',wlen);
else
fprintf(' using a width-%d square window\n',xwidth);
end
fprintf(' and a window advance of %g\n',xadv);
end
%
%%%%%%%%%%%%%%%%%%% Perform averaging %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
lox = firstx;
i = 0; % flag_fastave default
for f=1:outframes
hix = lox+xwidth;
outx(1,f)=outxval;
outxval = outxval + xadv;
if flag_fastave == 0
i = find(xvals>=lox & xvals < hix);
end
if length(i)==0,
if f>1,
outdata(:,f) = outdata(:,f-1); % If no data, replicate
else
outdata(:,f) = zeros(chans,1); % or else output zeros
end
elseif length(xwin)==1,
if flag_fastave > 0
outdata(:,f) = nan_mean(data(:,round(lox):round(hix))')';
nix = length([round(lox):round(hix)]);
else
outdata(:,f) = nan_mean(data(:,i)')'; % Else average
nix = length(i);
end
if nonorm & nix % undo division by number of elements summed
outdata(:,f) = outdata(:,f)*nix;
end
%
%%%%%%%%%%%%%%%%% Windowed averaging %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
else % length(xwin) > 1
wadv=(hix-lox)/wlen;
ix = floor((xvals(i)-lox)/wadv)+1; % AG fix 3/6/07
if length(xwin)>1
sumx = sum(xwin(ix));
else
sumx=1;
end
% AG fix 3/6/7
outdata(:,f) = nan_sum((((ones(chans,1)*xwin(ix)).*data(:,i)))')';
if abs(sumx) > NEARZERO & nonorm == 0
outdata(:,f) = outdata(:,f)/sumx;
end
end
lox = lox+xadv;
if (outframes<MAXPRINT)
fprintf('%d ',f);
end
end
if verbose,
fprintf('\n');
end
%
%%%%%%%%%%%%%%%%%%%%%%% function nan_mean() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
% nan_mean() - take the column means of a matrix, ignoring NaN values
%
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,1);
nononnans = find(nonnans==0);
nonnans(nononnans) = 1;
out = sum(in,1)./nonnans;
out(nononnans) = NaN;
%
%%%%%%%%%%%%%%%%%%%%%%% function nan_sum() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
% nan_sum() - take the column sums of a matrix, ignoring NaN values
%
function out = nan_sum(in)
nans = find(isnan(in));
in(nans) = 0;
out = sum(in,1);
nonnans = ones(size(in));
nonnans(nans) = 0;
nonnans = sum(nonnans,1);
nononnans = find(nonnans==0);
out(nononnans) = NaN;
|
github
|
ZijingMao/baselineeegtest-master
|
readtxtfile.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/readtxtfile.m
| 1,473 |
utf_8
|
884a7c06601ae6728761a5e03fd42521
|
% readtxtfile() - Read text file into a Matlab variable
%
% Usage: >> str = readtxtfile( filename );
%
% Input:
% filename - [string] name of the file.
%
% Output:
% str - [string] content of the file.
%
% Author: Arnaud Delorme, SCCN / INC / UCSD, August 2009
% Copyright (C) Arnaud Delorme, August 2009
%
% 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 = readtxtfile(filename)
com = '';
if ~exist(filename)
disp([ 'Cannot find option file ' filename ]);
else
fid = fopen(filename, 'r');
if fid == -1
disp([ 'Cannot open option file ' filename ]);
else
com = '';
while ~feof(fid)
a = fgetl(fid);
com = [ com 10 a ];
end;
fclose(fid);
end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
openbdf.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/openbdf.m
| 6,712 |
utf_8
|
1496f13e75bb80dd10e647e3497b1a52
|
% openbdf() - Opens an BDF File (European Data Format for Biosignals) in MATLAB (R)
%
% Usage:
% >> EDF=openedf(FILENAME)
%
% Note: About EDF -> www.biosemi.com/faq/file_format.htm
%
% Author: Alois Schloegl, 5.Nov.1998
%
% See also: readedf()
% Copyright (C) 1997-1998 by Alois Schloegl
% [email protected]
% Ver 2.20 18.Aug.1998
% Ver 2.21 10.Oct.1998
% Ver 2.30 5.Nov.1998
%
% For use under Octave define the following function
% function s=upper(s); s=toupper(s); end;
% V2.12 Warning for missing Header information
% V2.20 EDF.AS.* changed
% V2.30 EDF.T0 made Y2K compatible until Year 2090
% 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.
% Name changed for bdf files Sept 6,2002 T.S. Lorig
% Header updated for EEGLAB format (update web link too) - Arnaud Delorme 14 Oct 2002
function [DAT,H1]=openbdf(FILENAME)
SLASH='/'; % defines Seperator for Subdirectories
BSLASH=setstr(92);
cname=computer;
if cname(1:2)=='PC' SLASH=BSLASH; end;
fid=fopen(FILENAME,'r','ieee-le');
if fid<0
fprintf(2,['Error LOADEDF: File ' FILENAME ' not found\n']);
return;
end;
EDF.FILE.FID=fid;
EDF.FILE.OPEN = 1;
EDF.FileName = FILENAME;
PPos=min([max(find(FILENAME=='.')) length(FILENAME)+1]);
SPos=max([0 find((FILENAME=='/') | (FILENAME==BSLASH))]);
EDF.FILE.Ext = FILENAME(PPos+1:length(FILENAME));
EDF.FILE.Name = FILENAME(SPos+1:PPos-1);
if SPos==0
EDF.FILE.Path = pwd;
else
EDF.FILE.Path = FILENAME(1:SPos-1);
end;
EDF.FileName = [EDF.FILE.Path SLASH EDF.FILE.Name '.' EDF.FILE.Ext];
H1=setstr(fread(EDF.FILE.FID,256,'char')'); %
EDF.VERSION=H1(1:8); % 8 Byte Versionsnummer
%if 0 fprintf(2,'LOADEDF: WARNING Version EDF Format %i',ver); end;
EDF.PID = deblank(H1(9:88)); % 80 Byte local patient identification
EDF.RID = deblank(H1(89:168)); % 80 Byte local recording identification
%EDF.H.StartDate = H1(169:176); % 8 Byte
%EDF.H.StartTime = H1(177:184); % 8 Byte
EDF.T0=[str2num(H1(168+[7 8])) str2num(H1(168+[4 5])) str2num(H1(168+[1 2])) str2num(H1(168+[9 10])) str2num(H1(168+[12 13])) str2num(H1(168+[15 16])) ];
% Y2K compatibility until year 2090
if EDF.VERSION(1)=='0'
if EDF.T0(1) < 91
EDF.T0(1)=2000+EDF.T0(1);
else
EDF.T0(1)=1900+EDF.T0(1);
end;
else ;
% in a future version, this is hopefully not needed
end;
EDF.HeadLen = str2num(H1(185:192)); % 8 Byte Length of Header
% reserved = H1(193:236); % 44 Byte
EDF.NRec = str2num(H1(237:244)); % 8 Byte # of data records
EDF.Dur = str2num(H1(245:252)); % 8 Byte # duration of data record in sec
EDF.NS = str2num(H1(253:256)); % 8 Byte # of signals
EDF.Label = setstr(fread(EDF.FILE.FID,[16,EDF.NS],'char')');
EDF.Transducer = setstr(fread(EDF.FILE.FID,[80,EDF.NS],'char')');
EDF.PhysDim = setstr(fread(EDF.FILE.FID,[8,EDF.NS],'char')');
EDF.PhysMin= str2num(setstr(fread(EDF.FILE.FID,[8,EDF.NS],'char')'));
EDF.PhysMax= str2num(setstr(fread(EDF.FILE.FID,[8,EDF.NS],'char')'));
EDF.DigMin = str2num(setstr(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); %
EDF.DigMax = str2num(setstr(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); %
% check validity of DigMin and DigMax
if (length(EDF.DigMin) ~= EDF.NS)
fprintf(2,'Warning OPENEDF: Failing Digital Minimum\n');
EDF.DigMin = -(2^15)*ones(EDF.NS,1);
end
if (length(EDF.DigMax) ~= EDF.NS)
fprintf(2,'Warning OPENEDF: Failing Digital Maximum\n');
EDF.DigMax = (2^15-1)*ones(EDF.NS,1);
end
if (any(EDF.DigMin >= EDF.DigMax))
fprintf(2,'Warning OPENEDF: Digital Minimum larger than Maximum\n');
end
% check validity of PhysMin and PhysMax
if (length(EDF.PhysMin) ~= EDF.NS)
fprintf(2,'Warning OPENEDF: Failing Physical Minimum\n');
EDF.PhysMin = EDF.DigMin;
end
if (length(EDF.PhysMax) ~= EDF.NS)
fprintf(2,'Warning OPENEDF: Failing Physical Maximum\n');
EDF.PhysMax = EDF.DigMax;
end
if (any(EDF.PhysMin >= EDF.PhysMax))
fprintf(2,'Warning OPENEDF: Physical Minimum larger than Maximum\n');
EDF.PhysMin = EDF.DigMin;
EDF.PhysMax = EDF.DigMax;
end
EDF.PreFilt= setstr(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); %
tmp = fread(EDF.FILE.FID,[8,EDF.NS],'char')'; % samples per data record
EDF.SPR = str2num(setstr(tmp)); % samples per data record
fseek(EDF.FILE.FID,32*EDF.NS,0);
EDF.Cal = (EDF.PhysMax-EDF.PhysMin)./ ...
(EDF.DigMax-EDF.DigMin);
EDF.Off = EDF.PhysMin - EDF.Cal .* EDF.DigMin;
tmp = find(EDF.Cal < 0);
EDF.Cal(tmp) = ones(size(tmp));
EDF.Off(tmp) = zeros(size(tmp));
EDF.Calib=[EDF.Off';(diag(EDF.Cal))];
%EDF.Calib=sparse(diag([1; EDF.Cal]));
%EDF.Calib(1,2:EDF.NS+1)=EDF.Off';
EDF.SampleRate = EDF.SPR / EDF.Dur;
EDF.FILE.POS = ftell(EDF.FILE.FID);
if EDF.NRec == -1 % unknown record size, determine correct NRec
fseek(EDF.FILE.FID, 0, 'eof');
endpos = ftell(EDF.FILE.FID);
EDF.NRec = floor((endpos - EDF.FILE.POS) / (sum(EDF.SPR) * 2));
fseek(EDF.FILE.FID, EDF.FILE.POS, 'bof');
H1(237:244)=sprintf('%-8i',EDF.NRec); % write number of records
end;
EDF.Chan_Select=(EDF.SPR==max(EDF.SPR));
for k=1:EDF.NS
if EDF.Chan_Select(k)
EDF.ChanTyp(k)='N';
else
EDF.ChanTyp(k)=' ';
end;
if findstr(upper(EDF.Label(k,:)),'ECG')
EDF.ChanTyp(k)='C';
elseif findstr(upper(EDF.Label(k,:)),'EKG')
EDF.ChanTyp(k)='C';
elseif findstr(upper(EDF.Label(k,:)),'EEG')
EDF.ChanTyp(k)='E';
elseif findstr(upper(EDF.Label(k,:)),'EOG')
EDF.ChanTyp(k)='O';
elseif findstr(upper(EDF.Label(k,:)),'EMG')
EDF.ChanTyp(k)='M';
end;
end;
EDF.AS.spb = sum(EDF.SPR); % Samples per Block
bi=[0;cumsum(EDF.SPR)];
idx=[];idx2=[];
for k=1:EDF.NS,
idx2=[idx2, (k-1)*max(EDF.SPR)+(1:EDF.SPR(k))];
end;
maxspr=max(EDF.SPR);
idx3=zeros(EDF.NS*maxspr,1);
for k=1:EDF.NS, idx3(maxspr*(k-1)+(1:maxspr))=bi(k)+ceil((1:maxspr)'/maxspr*EDF.SPR(k));end;
%EDF.AS.bi=bi;
EDF.AS.IDX2=idx2;
%EDF.AS.IDX3=idx3;
DAT.Head=EDF;
DAT.MX.ReRef=1;
%DAT.MX=feval('loadxcm',EDF);
return;
|
github
|
ZijingMao/baselineeegtest-master
|
anova2rm_cell.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/statistics/anova2rm_cell.m
| 6,774 |
utf_8
|
37ad08d0dfb97a5ae59971a6becc90b7
|
% anova2rm_cell() - compute F-values in cell array using repeated measure
% ANOVA.
%
% Usage:
% >> [FC FR FI dfc dfr dfi] = anova2rm_cell( data );
%
% Inputs:
% data = data consisting of PAIRED arrays to be compared. The last
% dimension of the data array is used to compute ANOVA.
% Outputs:
% FC - F-value for columns.
% FR - F-value for rows.
% FI - F-value for interaction.
% dfc - degree of freedom for columns.
% dfr - degree of freedom for rows.
% dfi - degree of freedom for interaction.
%
% Note: this function is inspired from rm_anova available at
% http://www.mathworks.se/matlabcentral/fileexchange/6874-two-way-rep
% eated-measures-anova
% It allows for fast computation of about 20 thousands ANOVA per
% second. It is different from anova2_cell which mimics the ANOVA
% fonction from the Matlab statistical toolbox. This function
% computes true repeated measure ANOVA.
%
% Example:
% a = { rand(1,10) rand(1,10) rand(1,10); rand(1,10) rand(1,10) rand(1,10) }
% [FC FR FI dfc dfr dfi] = anova2rm_cell(a)
% signifC = 1-fcdf(FC, dfc(1), dfc(2))
% signifR = 1-fcdf(FR, dfr(1), dfr(2))
% signifI = 1-fcdf(FI, dfi(1), dfi(2))
%
% % for comparison
% z = zeros(10,1); o = ones(10,1); t = ones(10,1)*2;
% rm_anova2( [ a{1,1}';a{1,2}';a{1,3}';a{2,1}';a{2,2}';a{2,3}' ], ...
% repmat([1:10]', [6 1]), [o;o;o;z;z;z], [z;o;t;z;o;t], {'a','b'})
%
% c = { rand(200,400,10) rand(200,400,10); ...
% rand(200,400,10) rand(200,400,10)};
% [FC FR FI dfc dfr dfi] = anova2rm_cell(c) % computes 200x400 ANOVAs
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 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 [fA fB fAB dfApair dfBpair dfABpair] = anova2rm_cell(data)
% compute all means and all std
% -----------------------------
a = size(data,1);
b = size(data,2);
nd = myndims( data{1} );
n = size( data{1} ,nd);
% only for paired stats
% ---------------------
if nd == 1
AB = zeros(a,b,'single');
AS = zeros(a,n,'single');
BS = zeros(b,n,'single');
sq = single(0);
for ind1 = 1:a
for ind2 = 1:b
AB(ind1,ind2) = sum(data{ind1,ind2});
AS(ind1,:) = AS(ind1,:) + data{ind1,ind2}';
BS(ind2,:) = BS(ind2,:) + data{ind1,ind2}';
sq = sq + sum(data{ind1,ind2}.^2);
end;
end;
dimA = 2;
dimB = 1;
elseif nd == 2
AB = zeros(size(data{1},1),a,b,'single');
AS = zeros(size(data{1},1),a,n,'single');
BS = zeros(size(data{1},1),b,n,'single');
sq = zeros(size(data{1},1),1,'single');
for ind1 = 1:a
for ind2 = 1:b
AB(:,ind1,ind2) = sum(data{ind1,ind2},nd);
AS(:,ind1,:) = AS(:,ind1,:) + reshape(data{ind1,ind2},size(data{1},1),1,n);
BS(:,ind2,:) = BS(:,ind2,:) + reshape(data{ind1,ind2},size(data{1},1),1,n);
sq = sq + sum(data{ind1,ind2}.^2,nd);
end;
end;
dimA = 3;
dimB = 2;
elseif nd == 3
AB = zeros(size(data{1},1),size(data{1},2),a,b,'single');
AS = zeros(size(data{1},1),size(data{1},2),a,n,'single');
BS = zeros(size(data{1},1),size(data{1},2),b,n,'single');
sq = zeros(size(data{1},1),size(data{1},2),'single');
for ind1 = 1:a
for ind2 = 1:b
AB(:,:,ind1,ind2) = sum(data{ind1,ind2},nd);
AS(:,:,ind1,:) = AS(:,:,ind1,:) + reshape(data{ind1,ind2},size(data{1},1),size(data{1},2),1,n);
BS(:,:,ind2,:) = BS(:,:,ind2,:) + reshape(data{ind1,ind2},size(data{1},1),size(data{1},2),1,n);
sq = sq + sum(data{ind1,ind2}.^2,nd);
end;
end;
dimA = 4;
dimB = 3;
elseif nd == 4
AB = zeros(size(data{1},1),size(data{1},2),size(data{1},3),a,b,'single');
AS = zeros(size(data{1},1),size(data{1},2),size(data{1},3),a,n,'single');
BS = zeros(size(data{1},1),size(data{1},2),size(data{1},3),b,n,'single');
sq = zeros(size(data{1},1),size(data{1},2),size(data{1},3),'single');
for ind1 = 1:a
for ind2 = 1:b
AB(:,:,:,ind1,ind2) = sum(data{ind1,ind2},nd);
AS(:,:,:,ind1,:) = AS(:,:,:,ind1,:) + reshape(data{ind1,ind2},size(data{1},1),size(data{1},2),size(data{1},3),1,n);
BS(:,:,:,ind2,:) = BS(:,:,:,ind2,:) + reshape(data{ind1,ind2},size(data{1},1),size(data{1},2),size(data{1},3),1,n);
sq = sq + sum(data{ind1,ind2}.^2,nd);
end;
end;
dimA = 5;
dimB = 4;
end;
A = sum(AB,dimA); % sum across columns, so result is ax1 column vector
B = sum(AB,dimB); % sum across rows, so result is 1xb row vector
S = sum(AS,dimB); % sum across columns, so result is 1xs row vector
T = sum(sum(A,dimB),dimA); % could sum either A or B or S, choice is arbitrary
% degrees of freedom
dfA = a-1;
dfB = b-1;
dfAB = (a-1)*(b-1);
dfS = n-1;
dfAS = (a-1)*(n-1);
dfBS = (b-1)*(n-1);
dfABS = (a-1)*(b-1)*(n-1);
% bracket terms (expected value)
expA = sum(A.^2,dimB)./(b*n);
expB = sum(B.^2,dimA)./(a*n);
expAB = sum(sum(AB.^2,dimA),dimB)./n;
expS = sum(S.^2,dimA)./(a*b);
expAS = sum(sum(AS.^2,dimB),dimA)./b;
expBS = sum(sum(BS.^2,dimB),dimA)./a;
expY = sq; %sum(Y.^2);
expT = T.^2 / (a*b*n);
% sums of squares
ssA = expA - expT;
ssB = expB - expT;
ssAB = expAB - expA - expB + expT;
ssS = expS - expT;
ssAS = expAS - expA - expS + expT;
ssBS = expBS - expB - expS + expT;
ssABS = expY - expAB - expAS - expBS + expA + expB + expS - expT;
ssTot = expY - expT;
% mean squares
msA = ssA / dfA;
msB = ssB / dfB;
msAB = ssAB / dfAB;
msS = ssS / dfS;
msAS = ssAS / dfAS;
msBS = ssBS / dfBS;
msABS = ssABS / dfABS;
% f statistic
fA = msA ./ msAS;
fB = msB ./ msBS;
fAB = msAB ./ msABS;
dfApair = [dfA dfAS];
dfBpair = [dfB dfBS];
dfABpair = [dfAB dfABS];
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
statcond.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/statistics/statcond.m
| 24,879 |
utf_8
|
8adfae55efd5defaad53dc2a93a6dc25
|
% statcond() - compare two or more data conditions statistically using
% standard parametric or nonparametric permutation-based ANOVA
% (1-way or 2-way) or t-test methods. Parametric testing uses
% fcdf() from the Matlab Statistical Toolbox.
% Usage:
% >> [stats, df, pvals, surrog] = statcond( data, 'key','val'... );
%
% Inputs:
% data = one-or two-dimensional cell array of data matrices.
% For nonparametric, permutation-based testing, the
% last dimension of the data arrays (which may be of up to
% 4 dimensions) is permuted across conditions, either in
% a 'paired' fashion (not changing the, e.g., subject or
% trial order in the last dimension) or in an umpaired
% fashion (not respecting this order). If the number of
% elements in the last dimension is not the same across
% conditions, the 'paired' option is turned 'off'. Note:
% All other dimensions MUST be constant across conditions.
% For example, consider a (1,3) cell array of matrices
% of size (100,20,x) each holding a (100,20) time/frequency
% transform from each of x subjects. Only the last dimension
% (here x, the number of subjects) may differ across the
% three conditions.
% The test used depends on the size of the data array input.
% When the data cell array has 2 columns and the data are
% paired, a paired t-test is performed; when the data are
% unpaired, an unpaired t-test is performed. If 'data'
% has only one row (paired or unpaired) and more than 2
% columns, a one-way ANOVA is performed. If the data cell
% array contains several rows and columns, and the data is
% paired, a two-way repeated measure ANOVA is performed.
% NOTE THAT IF THE DATA is unpaired, EEGLAB will use a
% balanced 1 or 2 way ANOVA and parametric results might not
% be meaningful (bootstrap and permstatcondutation should be fine).
%
% Optional inputs:
% 'paired' = ['on'|'off'] pair the data array {default: 'on' unless
% the last dimension of data array is of different lengths}.
% For two independent variables, this input is a cell array,
% for example { 'on' 'off' } indicating that the first
% independent variable is paired and the second is not.
% 'method' = ['perm'|'bootstrap'|'param'] method for computing the p-values:
% 'param' or 'parametric' = parametric testing (standard ANOVA
% or t-test);
% 'perm' or 'permutation' = non-parametric testing using
% surrogate data
% 'bootstrap' = non-parametric bootstrap
% made by permuting the input data {default: 'param'}
% 'naccu' = [integer] Number of surrogate data copies to use in 'perm'
% or 'bootstrap' method estimation (see above) {default: 200}.
% 'verbose' = ['on'|'off'] print info on the command line {default: 'on'}.
% 'variance' = ['homegenous'|'inhomogenous'] this option is exclusively
% for parametric statistics using unpaired t-test. It allows
% to compute a more accurate value for the degree of freedom
% using the formula for inhomogenous variance (see
% ttest2_cell function). Default is 'inhomegenous'.
% 'surrog' = surrogate data array (see output).
% 'stats' = F- or T-value array (see output).
% 'tail' = ['one'|'two'] run one-tailed (F-test) or two tailed
% (T-test). This option is only relevant when using the
% 'surrog' input. Otherwise it is ignored.
% 'forceanova' = ['on'|'off'] force the use of ANOVA calculation even
% for 2x1 designs. Default is 'off'.
% 'alpha' = [float] p-value threshold value. Allow returning
% confidence intervals and mask (requires structoutput below).
% 'structoutput' = ['on'|'off'] return an output structure instead of
% the regular output. Allow to output mask and confidence
% intervals.
%
% Legacy parameters:
% 'threshold' - now 'alpha'
% 'mode' - now 'method'
%
% Outputs:
% stats = F- or T-value array of the same size as input data without
% the last dimension. A T value is returned only when the data
% includes exactly two conditions.
% df = degrees of freedom, a (2,1) vector, when F-values are returned
% pvals = array of p-values. Same size as input data without the last
% data dimension. All returned p-values are two-tailed.
% surrog = surrogate data array (same size as input data with the last
% dimension filled with a number ('naccu') of surrogate data sets.
%
% Important note: When a two-way ANOVA is performed, outputs are cell arrays
% with three elements: output(1) = row effects;
% output(2) = column effects; output(3) = interactions
% between rows and columns.
%
% Examples:
% >> a = { rand(1,10) rand(1,10)+0.5 }; % pseudo 'paired' data vectors
% [t df pvals] = statcond(a); % perform paired t-test
% pvals =
% 5.2807e-04 % standard t-test probability value
% % Note: for different rand() outputs, results will differ.
%
% [t df pvals surog] = statcond(a, 'method', 'perm', 'naccu', 2000);
% pvals =
% 0.0065 % nonparametric t-test using 2000 permuted data sets
%
% a = { rand(2,11) rand(2,10) rand(2,12)+0.5 }; % pseudo 'unpaired'
% [F df pvals] = statcond(a); % perform an unpaired ANOVA
% pvals =
% 0.00025 % p-values for difference between columns
% 0.00002 % for each data row
%
% a = { rand(3,4,10) rand(3,4,10) rand(3,4,10); ...
% rand(3,4,10) rand(3,4,10) rand(3,4,10)+0.5 };
% % pseudo (2,3)-condition data array, each entry containing
% % ten (3,4) data matrices
% [F df pvals] = statcond(a); % perform a paired 2-way ANOVA
% % Output:
% pvals{1} % a (3,4) matrix of p-values; effects across rows
% pvals{2} % a (3,4) matrix of p-values; effects across colums
% pvals{3} % a (3,4) matrix of p-values; interaction effects
% % across rows and columns
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005-
% With thanks to Robert Oostenveld for fruitful discussions
% and advice on this function.
%
% See also: anova1_cell(), anova2_cell(), anova2rm_cell, fcdf()
% perform a paired t-test
% -----------------------
% a = { rand(2,10) rand(2,10) };
% [t df pval] = statcond(a); pval
% [h p t stat] = ttest( a{1}(1,:), a{2}(1,:)); p
% [h p t stat] = ttest( a{1}(2,:), a{2}(2,:)); p
%
% compare significance levels
% --------------------------
% a = { rand(1,10) rand(1,10) };
% [F df pval] = statcond(a, 'method', 'perm', 'naccu', 200); pval
% [h p t stat] = ttest( a{1}(1,:), a{2}(1,:)); p
% 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 [ ori_vals, df, pvals, surrogval ] = statcond( data, varargin );
if nargin < 1
help statcond;
return;
end;
try, warning('off', 'MATLAB:divideByZero'); catch, end;
if exist('finputcheck')
g = finputcheck( varargin, { 'naccu' 'integer' [1 Inf] 200;
'method' 'string' { 'param','parametric','perm','permutation','bootstrap' } 'param';
'mode' 'string' { } '';
'paired' 'string' { 'on','off' } 'on';
'surrog' { 'real','cell' } [] [];
'stats' { 'real','cell' } [] [];
'structoutput' 'string' { 'on','off' } 'off';
'forceanova' 'string' { 'on','off' } 'off';
'arraycomp' 'string' { 'on','off' } 'on';
'alpha' 'real' [] NaN;
'tail' 'string' { 'one','both','upper','lower'} 'both';
'variance' 'string' { 'homogenous','inhomogenous' } 'inhomogenous';
'returnresamplingarray' 'string' { 'on','off' } 'off';
'verbose' 'string' { 'on','off' } 'on' }, 'statcond');
if isstr(g), error(g); end;
else
g = struct(varargin{:});
if ~isfield(g, 'naccu'), g.naccu = 200; end;
if ~isfield(g, 'method'), g.method = 'param'; end;
if ~isfield(g, 'paired'), g.paired = 'on'; end;
if ~isfield(g, 'surrog'), g.surrog = []; end;
if ~isfield(g, 'orivals'), g.orivals = []; end;
if ~isfield(g, 'arraycomp'), g.arraycomp = 'on'; end;
if ~isfield(g, 'verbose'), g.verbose = 'on'; end;
if ~isfield(g, 'tail'), g.tail = 'both'; end;
if ~isfield(g, 'variance'), g.variance = 'homogenous'; end;
if ~isfield(g, 'structoutput'), g.structoutput = 'on'; end;
if ~isfield(g, 'returnresamplingarray'), g.returnresamplingarray = 'off'; end;
end;
if ~isempty(g.mode), g.method = g.mode; end;
if strcmpi(g.method, 'parametric'), g.method = 'param'; end;
if strcmpi(g.method, 'permutation'), g.method = 'perm'; end;
if strcmpi(g.verbose, 'on'), verb = 1; else verb = 0; end;
if strcmp(g.method, 'param' ) && exist('fcdf') ~= 2
myfprintf('on',['statcond(): parametric testing requires fcdf() \n' ...
' from the Matlab StatsticaL Toolbox.\n' ...
' Running nonparametric permutation tests\n.']);
g.method = 'perm';
end
if size(data,2) == 1, data = transpose(data); end; % cell array transpose
g.naccu = round(g.naccu);
% reshape matrices
% ----------------
nd = size(data{1});
nd = nd(1:end-1);
for index = 1:prod(size(data))
data{index} = reshape(data{index}, [prod(nd) size(data{index},myndims(data{index}))]);
end;
if ~strcmpi(g.method, 'param') && isempty(g.surrog)
tmpsize = size(data{1});
surrogval = zeros([ tmpsize(1:end-1) g.naccu ], 'single');
else surrogval = [];
end;
% check for NaNs or Inf
% ---------------------
for iDat = 1:length(data(:))
if any(isnan(reshape(data{iDat}, prod(size(data{iDat})),1))) || ...
any(isinf(reshape(data{iDat}, prod(size(data{iDat})),1)))
error('Statcond: One of the input array contains NaNs or Infinite values');
end;
end;
% bootstrap flag
% --------------
if strcmpi(g.method, 'bootstrap'), bootflag = 1;
else bootflag = 0;
end;
if isempty(g.surrog)
% test if data can be paired
% --------------------------
if length(unique(cellfun('size', data, ndims(data{1}) ))) > 1
g.paired = 'off';
end;
if strcmpi(g.paired, 'on')
pairflag = 1;
else pairflag = 0;
end;
% return resampling array
% -----------------------
if strcmpi(g.returnresamplingarray, 'on')
[ datavals datalen datadims ] = concatdata( data );
if strcmpi(g.arraycomp, 'on')
ori_vals = surrogdistrib( data, 'method', g.method, 'pairing', g.paired, 'naccu', g.naccu);
else
ori_vals = surrogdistrib( data, 'method', g.method, 'pairing', g.paired);
end;
return;
end;
% text output
% -----------
myfprintf(verb,'%d x %d, ', size(data,1), size(data,2));
if strcmpi(g.paired, 'on')
myfprintf(verb,'paired data, ');
else myfprintf(verb,'unpaired data, ');
end;
if size(data,1) == 1 && size(data,2) == 2
myfprintf(verb,'computing T values\n');
else myfprintf(verb,'computing F values\n');
end;
if size(data,1) > 1
if strcmpi(g.paired, 'on')
myfprintf(verb,'Using 2-way repeated measure ANOVA\n');
else myfprintf(verb,'Using balanced 2-way ANOVA (not suitable for parametric testing, only bootstrap)\n');
end;
elseif size(data,2) > 2
if strcmpi(g.paired, 'on')
myfprintf(verb,'Using 1-way repeated measure ANOVA\n');
else myfprintf(verb,'Using balanced 1-way ANOVA (equivalent to Matlab anova1)\n');
end;
else
if strcmpi(g.paired, 'on')
myfprintf(verb,'Using paired t-test\n');
else myfprintf(verb,'Using unpaired t-test\n');
end;
end;
if ~strcmpi(g.method, 'param')
if bootflag, myfprintf(verb,'Bootstraps (of %d):', g.naccu);
else myfprintf(verb,'Permutations (of %d):', g.naccu);
end;
end;
end;
tail = g.tail;
if isempty(g.surrog)
if size(data,1) == 1, % only one row
if size(data,2) == 2 && strcmpi(g.forceanova, 'off')
% paired t-test (very fast)
% -------------
[ori_vals df] = ttest_cell_select(data, g.paired, g.variance);
if strcmpi(g.method, 'param')
% Check if exist tcd.m file from the Statistics Toolbox (Bug 1352 )
if exist('tcdf','file') == 2 & license('test', 'Statistics_Toolbox')
pvals = 2*tcdf(-abs(ori_vals), df);
else
pvals = 2*mytcdf(-abs(ori_vals), df);
end
pvals = reshape(pvals, size(pvals));
else
if strcmpi(g.arraycomp, 'on')
try
myfprintf(verb,'...');
res = surrogdistrib( data, 'method', g.method, 'pairing', g.paired, 'naccu', g.naccu);
surrogval = ttest_cell_select( res, g.paired, g.variance);
catch,
lasterr
myfprintf(verb,'\nSuperfast array computation failed because of memory limitation, reverting to standard computation');
g.arraycomp = 'off';
end;
end;
if strcmpi(g.arraycomp, 'off')
[res precomp] = surrogdistrib( data, 'method', g.method, 'pairing', g.paired);
for index = 1:g.naccu
res = surrogdistrib( {}, 'precomp', precomp);
if mod(index, 10) == 0, myfprintf(verb,'%d ', index); end;
if mod(index, 100) == 0, myfprintf(verb,'\n'); end;
if myndims(res{1}) == 1
surrogval(index) = ttest_cell_select(res, g.paired, g.variance);
else surrogval(:,index) = ttest_cell_select(res, g.paired, g.variance);
end;
end;
end;
end;
else
% one-way ANOVA (paired) this is equivalent to unpaired t-test
% -------------
tail = 'one';
[ori_vals df] = anova1_cell_select( data, g.paired );
if strcmpi(g.method, 'param')
pvals = 1-fcdf(ori_vals, df(1), df(2));
else
if strcmpi(g.arraycomp, 'on')
try
myfprintf(verb,'...');
res = surrogdistrib( data, 'method', g.method, 'pairing', g.paired, 'naccu', g.naccu);
surrogval = anova1_cell_select( res, g.paired );
catch,
myfprintf(verb,'\nSuperfast array computation failed because of memory limitation, reverting to standard computing');
g.arraycomp = 'off';
end;
end;
if strcmpi(g.arraycomp, 'off')
[res precomp] = surrogdistrib( data, 'method', g.method, 'pairing', g.paired);
for index = 1:g.naccu
if mod(index, 10) == 0, myfprintf(verb,'%d ', index); end;
if mod(index, 100) == 0, myfprintf(verb,'\n'); end;
res = surrogdistrib( {}, 'precomp', precomp);
if myndims(data{1}) == 1
surrogval(index) = anova1_cell_select( res, g.paired );
else surrogval(:,index) = anova1_cell_select( res, g.paired );
end;
end;
end;
end;
end;
else
% two-way ANOVA (paired or unpaired)
% ----------------------------------
tail = 'one';
[ ori_vals{1} ori_vals{2} ori_vals{3} df{1} df{2} df{3} ] = anova2_cell_select( data, g.paired );
if strcmpi(g.method, 'param')
pvals{1} = 1-fcdf(ori_vals{1}, df{1}(1), df{1}(2));
pvals{2} = 1-fcdf(ori_vals{2}, df{2}(1), df{2}(2));
pvals{3} = 1-fcdf(ori_vals{3}, df{3}(1), df{3}(2));
else
surrogval = { surrogval surrogval surrogval };
dataori = data;
if strcmpi(g.arraycomp, 'on')
try
myfprintf(verb,'...');
res = surrogdistrib( data, 'method', g.method, 'pairing', g.paired, 'naccu', g.naccu);
[ surrogval{1} surrogval{2} surrogval{3} ] = anova2_cell_select( res, g.paired );
catch,
myfprintf(verb,'\nSuperfast array computation failed because of memory limitation, reverting to standard computing');
g.arraycomp = 'off';
end;
end;
if strcmpi(g.arraycomp, 'off')
[res precomp] = surrogdistrib( data, 'method', g.method, 'pairing', g.paired);
for index = 1:g.naccu
if mod(index, 10) == 0, myfprintf(verb,'%d ', index); end;
if mod(index, 100) == 0, myfprintf(verb,'\n'); end;
res = surrogdistrib( {}, 'precomp', precomp);
if myndims(data{1}) == 1
[ surrogval{1}(index) surrogval{2}(index) surrogval{3}(index) ] = anova2_cell_select( res, g.paired );
else [ surrogval{1}(:,index) surrogval{2}(:,index) surrogval{3}(:,index) ] = anova2_cell_select( res, g.paired );
end;
end;
end;
end;
end;
myfprintf(verb,'\n');
else
surrogval = g.surrog;
ori_vals = g.stats;
df = [];
end;
% compute p-values
% ----------------
if ~strcmpi(g.method, 'param')
if iscell( surrogval )
pvals{1} = stat_surrogate_pvals(surrogval{1}, ori_vals{1}, tail);
pvals{2} = stat_surrogate_pvals(surrogval{2}, ori_vals{2}, tail);
pvals{3} = stat_surrogate_pvals(surrogval{3}, ori_vals{3}, tail);
else
pvals = stat_surrogate_pvals(surrogval, ori_vals, tail);
end;
try, warning('on', 'MATLAB:divideByZero'); catch, end;
end;
[ ori_vals, pvals ] = reshape_results( nd, ori_vals, pvals);
[ surrogval ] = reshape_results( [nd g.naccu], surrogval);
% confidence intervals
% --------------------
if ~isnan(g.alpha)
outputstruct.ci = stat_surrogate_ci(surrogval, g.alpha, tail);
if strcmpi(g.structoutput, 'off')
disp('Warning: returning confidence interval requires an output structure');
end;
if iscell(pvals)
for ind = 1:length(pvals)
outputstruct.mask{ind} = pvals{ind} < g.alpha;
end;
else
outputstruct.mask = pvals < g.alpha;
end;
end;
% create a structure for outputing values
% ---------------------------------------
if strcmpi(g.structoutput, 'on')
outputstruct.method = g.method;
outputstruct.pval = pvals;
outputstruct.df = df;
outputstruct.surrog = surrogval;
if length(data(:)) == 2
outputstruct.t = ori_vals;
else outputstruct.f = ori_vals;
end;
outputstruct.stat = ori_vals;
ori_vals = outputstruct;
end;
% compute ANOVA 2-way
% -------------------
function [f1 f2 f3 df1 df2 df3] = anova2_cell_select( res, paired);
if strcmpi(paired,'on')
[f1 f2 f3 df1 df2 df3] = anova2rm_cell( res );
else
[f1 f2 f3 df1 df2 df3] = anova2_cell( res );
end;
% compute ANOVA 1-way
% -------------------
function [f df] = anova1_cell_select( res, paired);
if strcmpi(paired,'on')
[f df] = anova1rm_cell( res );
else
[f df] = anova1_cell( res );
end;
% compute t-test
% -------------------
function [t df] = ttest_cell_select( res, paired, homogenous);
if strcmpi(paired,'on')
[t df] = ttest_cell( res{1}, res{2});
else
[t df] = ttest2_cell( res{1}, res{2}, homogenous);
end;
% function to compute the number of dimensions
% --------------------------------------------
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
% function for verbose messages
% -----------------------------
function myfprintf(verb, varargin)
if verb
fprintf(varargin{:});
end;
% function to replace tcdf
% ------------------------
function p = mytcdf(x,v)
if length(v) == 1,
v = repmat(v, size(x));
end;
x2 = x.^2;
inds1 = (v < x2);
inds2 = (v >= x2);
if any(inds1(:)), p(inds1) = betainc(v(inds1) ./ (v(inds1) + x2(inds1)), v(inds1)/2, 0.5, 'lower') / 2; end;
if any(inds2(:)), p(inds2) = betainc(x2(inds2) ./ (v(inds2) + x2(inds2)), 0.5, v(inds2)/2, 'upper') / 2; end;
inds = (x > 0);
if any(inds)
p(inds) = 1 - p(inds);
end;
inds = (v > 1e7);
if any(inds(:)), p(inds) = normcum(x(inds)); end;
p(x == 0) = 0.5;
if isempty(p)
p = ones(size(x));
else
p = reshape(p, size(x));
end;
function [p] = normcum(z)
p = 0.5 * erfc(-z ./ sqrt(2));
% reshape results
% ---------------
function varargout = reshape_results(nd, varargin)
if length(varargin) > 1
for index = 1:length(varargin)
varargout{index} = reshape_results(nd, varargin{index});
end;
elseif iscell(varargin{1})
for index = 1:length(varargin{1})
varargout{1}{index} = reshape_results(nd, varargin{1}{index});
end;
else
if ~isempty(varargin{1})
if length(nd) == 1, nd = [ nd 1 ]; end;
varargout{1} = reshape(varargin{1}, nd);
else varargout{1} = [];
end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
surrogdistrib.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/statistics/surrogdistrib.m
| 5,888 |
utf_8
|
18526734957324ab037d603d38a328cf
|
% surrogdistrib - Build surrogate distribution
%
% surrog = surrogdistrib(data, varargin);
%
% Inputs:
% data - [cell] data arrays for which to compute a surrogate
% distribution.
%
% Optional inputs:
% 'method' - ['bootstrap'|'perm'] use either 'bootstrap' or 'permutation'
% method. Bootstrap performs draws with replacement and
% permutation performs draws without replacement. Default
% is 'perm'.
% 'pairing' - ['on'|'off'] pair the data arrays.
% 'naccu' - [integer] number of surrogate. Default is 1.
% 'precomp' - cell array containing precomputed value for speeding up
% mulitple calls
%
% Output:
% surrog - surrogate distribution
% precomp - cell array containing precomputed value for speeding up
% mulitple calls
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005-
% 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 [res precomp ] = surrogdistrib(data, varargin)
if nargin < 1
help surrogdistrib,
return;
end;
if ~strcmpi(varargin{1}, 'precomp')
opt = finputcheck(varargin, { 'naccu' 'integer' [1 Inf] 1;
'method' 'string' { 'perm','permutation','bootstrap' } 'perm';
'pairing' 'string' { 'on','off' } 'on';
'precomp' 'cell' {} {} }, 'surrogdistrib');
if isstr(opt), error(opt); end;
if strcmpi(opt.method, 'permutation'), opt.method = 'perm'; end;
if strcmpi(opt.method, 'bootstrap'), bootflag = 1;
else bootflag = 0;
end;
if strcmpi(opt.pairing, 'on')
pairflag = 1;
else pairflag = 0;
end;
else
opt.precomp = varargin{2};
end;
% concatenate data
% ----------------
if isempty(opt.precomp)
[ datavals datalen datadims ] = concatdata( data );
precomp = { datavals datalen datadims bootflag pairflag opt.naccu};
else
precomp = opt.precomp;
datavals = precomp{1};
datalen = precomp{2};
datadims = precomp{3};
bootflag = precomp{4};
pairflag = precomp{5};
opt.naccu = precomp{6};
end;
% compute surrogate distribution
% ------------------------------
if opt.naccu > 1
res = supersurrogate( datavals, datalen, datadims, bootflag, pairflag, opt.naccu);
else
res = surrogate( datavals, datalen, datadims, bootflag, pairflag);
end;
function res = supersurrogate(dat, lens, dims, bootstrapflag, pairedflag, naccu); % for increased speed only shuffle half the indices
% recompute indices in set and target cell indices
% ------------------------------------------------
ncond = length(lens)-1;
nsubj = lens(2);
if bootstrapflag
if pairedflag
indswap = mod( repmat([1:lens(end)],[naccu 1]) + ceil(rand(naccu,lens(end))*length(lens))*lens(2)-1, lens(end) )+1;
else indswap = ceil(rand(naccu,lens(end))*lens(end));
end;
else
if pairedflag
[tmp idx] = sort(rand(naccu,nsubj,ncond),3);
indswap = ((idx)-1)*nsubj + repmat( repmat([1:nsubj], [naccu 1 1]),[1 1 ncond]);
indswap = reshape(indswap, [naccu lens(end)]);
else
[tmp indswap] = sort(rand(naccu, lens(end)),2);
end;
end;
for i = 1:length(lens)-1
if myndims(dat) == 1
res{i} = reshape(dat(indswap(:,lens(i)+1:lens(i+1))), naccu, lens(i+1)-lens(i));
else res{i} = reshape(dat(:,indswap(:,lens(i)+1:lens(i+1))), size(dat,1), naccu, lens(i+1)-lens(i));
end;
end;
res = reshape(res, dims);
function res = surrogate(dataconcat, lens, dims, bootstrapflag, pairedflag); % for increased speed only shuffle half the indices
% recompute indices in set and target cell indices
% ------------------------------------------------
if bootstrapflag
if pairedflag
indswap = mod( [1:lens(end)]+ ceil(rand(1,lens(end))*length(lens))*lens(2)-1, lens(end) )+1;
else indswap = ceil(rand(1,lens(end))*lens(end));
end;
else
if pairedflag
indswap = [1:lens(end)];
indswap = reshape(indswap, [lens(2) length(lens)-1]);
for i = 1:size(indswap,1) % shuffle each row
[tmp idx] = sort(rand(1,size(indswap,2)));
indswap(i,:) = indswap(i,idx);
end;
indswap = reshape(indswap, [1 lens(2)*(length(lens)-1)]);
else
oriindices = [1:lens(end)]; % just shuffle indices
[tmp idx] = sort(rand(1,length(oriindices)));
indswap = oriindices(idx);
end;
end;
res = {};
for i = 1:length(lens)-1
if myndims(dataconcat) == 1
res{i} = dataconcat(indswap(lens(i)+1:lens(i+1)));
else res{i} = dataconcat(:,indswap(lens(i)+1:lens(i+1)));
end;
end;
res = reshape(res, dims);
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
stat_surrogate_pvals.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/statistics/stat_surrogate_pvals.m
| 2,648 |
utf_8
|
74534793d4027376c995150218faf240
|
function pvals = stat_surrogate_pvals(distribution,observed,tail)
% compute empirical p-vals under the null hypothesis that observed samples
% come from a given surrogate distribution. P-values for Type I error in
% rejecting the null hypothesis are obtained by finding the proportion of
% samples in the distribution that
% (a) are larger than the observed sample (one-sided test)
% (b) are larger or smaller than the observed sample (two-sided test).
%
% This function is based on Arnaud Delorme's statcond:compute_pvals()
% function from EEGLAB
%
% Inputs:
%
% distribution: [d1 x d2 x ... x dM x N] matrix of surrogate samples.
% distribution(i,j,k,...,:) is a collection of N samples
% from a surrogate distribution.
% observed: [d1 x d2 x ... x dM] matrix of observations.
% tail: can be 'one' or 'both' indicating a one-tailed or
% two-tailed test
% Outputs:
%
% pvals: [d1 x d2 x ... x dM] matrix of p-values specifying
% probability of Type I error in rejecting the null
% hypothesis
%
% Author: Tim Mullen and Arnaud Delorme, SCCN/INC/UCSD
% This function is part of the Source Information Flow Toolbox (SIFT)
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
numDims = myndims(distribution);
% append observed to last dimension of surrogate distribution
distribution = cat(numDims,distribution,observed);
numDims = myndims(distribution);
% sort along last dimension (replications)
[tmp idx] = sort( distribution, numDims,'ascend');
[tmp mx] = max( idx,[], numDims);
len = size(distribution, numDims );
pvals = 1-(mx-0.5)/len;
if strcmpi(tail, 'both')
pvals = min(pvals, 1-pvals);
pvals = 2*pvals;
end;
% get the number of dimensions in a matrix
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
anova1rm_cell.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/statistics/anova1rm_cell.m
| 3,731 |
utf_8
|
40890df8c96f1a41aca5846c8c9c4883
|
% anova1rm_cell() - compute F-values in cell array using repeated measure
% ANOVA.
%
% Usage:
% >> [FC dfc] = anova2rm_cell( data );
%
% Inputs:
% data = data consisting of PAIRED arrays to be compared. The last
% dimension of the data array is used to compute ANOVA.
% Outputs:
% FC - F-value for columns
% dfc - degree of freedom for columns
%
% Note: this function is inspired from rm_anova available at
% http://www.mathworks.se/matlabcentral/fileexchange/6874-two-way-rep
% eated-measures-anova
%
% Example:
% a = { rand(1,10) rand(1,10) rand(1,10) }
% [FC dfc] = anova1rm_cell(a)
% signifC = 1-fcdf(FC, dfc(1), dfc(2))
%
% % for comparison
% [F1 F2 FI df1 df2 dfi] = anova1rm_cell(a);
% F2
%
% c = { rand(200,400,10) rand(200,400,10) };
% [FC dfc] = anova2rm_cell(c) % computes 200x400 ANOVAs
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 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 [fA dfApair] = anova1rm_cell(data)
% compute all means and all std
% -----------------------------
a = length(data);
nd = myndims( data{1} );
sz = size( data{1} );
n = size( data{1} ,nd);
AS = zeros([ sz(1:nd-1) a n ], 'single');
sq = zeros([ sz(1:nd-1) 1], 'single');
% only for paired stats
% ---------------------
for ind1 = 1:a
switch nd
case 1, AS(ind1,:) = AS(ind1,:) + reshape(data{ind1},[sz(1:nd-1) 1 n]);
case 2, AS(:,ind1,:) = AS(:,ind1,:) + reshape(data{ind1},[sz(1:nd-1) 1 n]);
case 3, AS(:,:,ind1,:) = AS(:,:,ind1,:) + reshape(data{ind1},[sz(1:nd-1) 1 n]);
case 4, AS(:,:,:,ind1,:) = AS(:,:,:,ind1,:) + reshape(data{ind1},[sz(1:nd-1) 1 n]);
case 5, AS(:,:,:,:,ind1,:) = AS(:,:,:,:,ind1,:) + reshape(data{ind1},[sz(1:nd-1) 1 n]);
case 6, AS(:,:,:,:,:,ind1,:) = AS(:,:,:,:,:,ind1,:) + reshape(data{ind1},[sz(1:nd-1) 1 n]);
case 7, AS(:,:,:,:,:,:,ind1,:) = AS(:,:,:,:,:,:,ind1,:) + reshape(data{ind1},[sz(1:nd-1) 1 n]);
otherwise error('Dimension not supported');
end;
sq = sq + sum(data{ind1}.^2,nd);
end;
dimA = nd+1;
dimB = nd;
A = sum(AS,dimA); % sum across columns, so result is 1xs row vector
S = sum(AS,dimB); % sum across columns, so result is 1xs row vector
T = sum(sum(S,dimB),dimA); % could sum either A or B or S, choice is arbitrary
% degrees of freedom
dfA = a-1;
dfAS = (a-1)*(n-1);
% bracket terms (expected value)
expA = sum(A.^2,dimB)./n;
expS = sum(S.^2,dimA)./a;
expAS = sum(sum(AS.^2,dimB),dimA);
expT = T.^2 / (a*n);
% sums of squares
ssA = expA - expT;
ssAS = expAS - expA - expS + expT;
% mean squares
msA = ssA / dfA;
msAS = ssAS / dfAS;
% f statistic
fA = msA ./ msAS;
dfApair = [dfA dfAS];
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
teststat.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/statistics/teststat.m
| 20,505 |
utf_8
|
8521a1c623a39fbdaded6534e27d6c3c
|
% teststat - EEGLAB statistical testing function
%
% Statistics are critical for inference testing in Science. It is thus
% primordial to make sure than all the statistics implemented are
% robust and at least bug free. Statistical function using complex
% formulas are inherently prone to bugs. EEGLAB functions are all the
% more prone to bugs given that they only use complex Matlab code to
% avoid loops and speed up computation.
%
% This test function does not garantee that EEGLAB statistical functions
% are bug free. It does assure though that bugs are unlikely and minor
% if they are present.
%
% This function test 3 things.
%
% * First, it checks that for vector inputs the EEGLAB functions return
% the same output as other reference functions from the Matlab statistical
% toolbox or from other packages tested against the SPSS software for
% repeated measure ANOVA (rm_anova2 function).
%
% * Second, it checks that array inputs with different number of dimensions
% (from 1 to 3) the EEGLAB function return the same output.
%
% * Third, it checks that the permutation and bootstrap methods shuffle
% the data properly by running multiple tests.
function teststat;
% testing paired t-test
% ---------------------
a = { rand(1,10) rand(1,10)+0.5 };
[t df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[h p tmp stats] = ttest(a{1}, a{2});
fprintf('Statistics paired statcond t-value %2.2f df=%d p=%0.4f\n', t, df, pvals);
fprintf('Statistics paired ttest func. t-value %2.2f df=%d p=%0.4f\n', stats.tstat, stats.df, p);
assertsame([t stats.tstat], [df stats.df], [pvals p]);
disp('--------------------');
% testing unpaired t-test
% -----------------------
[t df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[h p tmp stats] = ttest2(a{1}, a{2});
fprintf('Statistics paired statcond t-value %2.2f df=%d p=%0.4f\n', t, df, pvals);
fprintf('Statistics paired ttest2 func. t-value %2.2f df=%d p=%0.4f\n', stats.tstat, stats.df, p);
assertsame([t stats.tstat], [df stats.df], [pvals p]);
disp('--------------------');
% testing paired 1-way ANOVA
% --------------------------
a = { rand(1,10) rand(1,10) rand(1,10)+0.2; rand(1,10) rand(1,10)+0.2 rand(1,10) };
[F df pvals surog] = statcond(a(1,:), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
z = zeros(10,1); o = ones(10,1); t = ones(10,1)*2;
stats = rm_anova2( [ a{1,1}';a{1,2}';a{1,3}'], repmat([1:10]', [3 1]), [o;o;o], [z;o;t], {'a','b'});
fprintf('Statistics 1-way paired statcond F-value %2.2f df1=%d df2=%d p=%0.4f\n', F, df(1), df(2), pvals);
fprintf('Statistics 1-way paired rm_avova2 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{3,5}, stats{3,3}, stats{6,3}, stats{3,6});
assertsame([F stats{3,5}], [df(1) stats{3,3}], [df(2) stats{6,3}], [pvals stats{3,6}]);
disp('--------------------');
% testing paired 2-way ANOVA
% --------------------------
[F df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
z = zeros(10,1); o = ones(10,1); t = ones(10,1)*2;
stats = rm_anova2( [ a{1,1}';a{1,2}';a{1,3}';a{2,1}';a{2,2}';a{2,3}' ], ...
repmat([1:10]', [6 1]), [o;o;o;z;z;z], [z;o;t;z;o;t], {'a','b'});
fprintf('Statistics 2-way paired statcond F-value %2.2f df1=%d df2=%d p=%0.4f\n', F{3}, df{3}(1), df{3}(2), pvals{3});
fprintf('Statistics 2-way paired rm_avova2 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{4,5}, stats{4,3}, stats{7,3}, stats{4,6});
assertsame([F{3} stats{4,5}], [df{3}(1) stats{4,3}], [df{3}(2) stats{7,3}], [pvals{3} stats{4,6}]);
disp('--------------------');
% testing 1-way unpaired ANOVA
% ----------------------------
[F df pvals surog] = statcond(a(1,:), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[p stats] = anova1( [ a{1,1}' a{1,2}' a{1,3}' ],{}, 'off');
fprintf('Statistics 1-way unpaired statcond F-value %2.2f df1=%d df2=%d p=%0.4f\n', F, df(1), df(2), pvals);
fprintf('Statistics 1-way unpaired anova1 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{2,5}, stats{2,3}, stats{3,3}, stats{2,6});
assertsame([F stats{2,5}], [df(1) stats{2,3}], [df(2) stats{3,3}], [pvals stats{2,6}]);
disp('--------------------');
% testing 2-way unpaired ANOVA
% ----------------------------
[F df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[p stats] = anova2( [ a{1,1}' a{1,2}' a{1,3}'; a{2,1}' a{2,2}' a{2,3}' ], 10, 'off');
fprintf('Statistics 2-way paired statcond F-value %2.2f df1=%d df2=%d p=%0.4f\n', F{3}, df{3}(1), df{3}(2), pvals{3});
fprintf('Statistics 1-way unpaired anova2 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{4,5}, stats{4,3}, stats{5,3}, stats{4,6});
assertsame([F{3} stats{4,5}], [df{3}(1) stats{4,3}], [df{3}(2) stats{5,3}], [pvals{3} stats{4,6}]);
disp('--------------------');
% testing different dimensions in statcond
% ----------------------------------------
a = { rand(1,10) rand(1,10)+0.5 rand(1,10)};
b = { rand(10,10) rand(10,10)+0.5 rand(10,10)}; b{1}(4,:) = a{1}; b{2}(4,:) = a{2}; b{3}(4,:) = a{3};
c = { rand(5,10,10) rand(5,10,10)+0.5 rand(5,10,10)}; c{1}(2,4,:) = a{1}; c{2}(2,4,:) = a{2}; c{3}(2,4,:) = a{3};
d = { rand(2,5,10,10) rand(2,5,10,10)+0.5 rand(2,5,10,10)}; d{1}(1,2,4,:) = a{1}; d{2}(1,2,4,:) = a{2}; d{3}(1,2,4,:) = a{3};
[t1 df1 pvals1] = statcond(a(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t2 df2 pvals2] = statcond(b(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t3 df3 pvals3] = statcond(c(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t4 df4 pvals4] = statcond(d(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
fprintf('Statistics paired statcond t-test dim1 t-value %2.2f df=%d p=%0.4f\n', t1, df1, pvals1);
fprintf('Statistics paired statcond t-test dim2 t-value %2.2f df=%d p=%0.4f\n', t2(4), df2, pvals2(4));
fprintf('Statistics paired statcond t-test dim3 t-value %2.2f df=%d p=%0.4f\n', t3(2,4), df3, pvals3(2,4));
fprintf('Statistics paired statcond t-test dim4 t-value %2.2f df=%d p=%0.4f\n', t4(1,2,4), df4, pvals4(1,2,4));
assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]);
disp('--------------------');
[t1 df1 pvals1] = statcond(a(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t2 df2 pvals2] = statcond(b(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t3 df3 pvals3] = statcond(c(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t4 df4 pvals4] = statcond(d(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
fprintf('Statistics unpaired statcond t-test dim1 t-value %2.2f df=%d p=%0.4f\n', t1, df1, pvals1);
fprintf('Statistics unpaired statcond t-test dim2 t-value %2.2f df=%d p=%0.4f\n', t2(4), df2, pvals2(4));
fprintf('Statistics unpaired statcond t-test dim3 t-value %2.2f df=%d p=%0.4f\n', t3(2,4), df3, pvals3(2,4));
fprintf('Statistics unpaired statcond t-test dim4 t-value %2.2f df=%d p=%0.4f\n', t4(1,2,4), df4, pvals4(1,2,4));
assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]);
disp('--------------------');
[t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
fprintf('Statistics paired statcond anova 1-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1, df1(1), df1(2), pvals1);
fprintf('Statistics paired statcond anova 1-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2(4), df2(1), df2(2), pvals2(4));
fprintf('Statistics paired statcond anova 1-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3(2,4), df3(1), df3(2), pvals3(2,4));
fprintf('Statistics paired statcond anova 1-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4(1,2,4), df4(1), df4(2), pvals4(1,2,4));
assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]);
disp('--------------------');
[t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
fprintf('Statistics unpaired statcond anova 1-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1, df1(1), df1(2), pvals1);
fprintf('Statistics unpaired statcond anova 1-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2(4), df2(1), df2(2), pvals2(4));
fprintf('Statistics unpaired statcond anova 1-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3(2,4), df3(1), df3(2), pvals3(2,4));
fprintf('Statistics unpaired statcond anova 1-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4(1,2,4), df4(1), df4(2), pvals4(1,2,4));
assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]);
disp('--------------------');
a(2,:) = a; a{1} = a{1}/2;
b(2,:) = b; b{1} = b{1}/2;
c(2,:) = c; c{1} = c{1}/2;
d(2,:) = d; d{1} = d{1}/2;
[t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
fprintf('Statistics paired statcond anova 2-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1{3}, df1{3}(1), df1{3}(2), pvals1{3});
fprintf('Statistics paired statcond anova 2-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2{3}(4), df2{3}(1), df2{3}(2), pvals2{3}(4));
fprintf('Statistics paired statcond anova 2-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3{3}(2,4), df3{3}(1), df3{3}(2), pvals3{3}(2,4));
fprintf('Statistics paired statcond anova 2-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4{3}(1,2,4), df4{3}(1), df4{3}(2), pvals4{3}(1,2,4));
assertsame([t1{3} t2{3}(4) t3{3}(2,4) t4{3}(1,2,4)], [df1{3}(1) df2{3}(1) df3{3}(1) df4{3}(1)], [df1{3}(2) df2{3}(2) df3{3}(2) df4{3}(2)], [pvals1{3} pvals2{3}(4) pvals3{3}(2,4) pvals4{3}(1,2,4)]);
disp('--------------------');
[t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
fprintf('Statistics unpaired statcond anova 2-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1{3}, df1{3}(1), df1{3}(2), pvals1{3});
fprintf('Statistics unpaired statcond anova 2-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2{3}(4), df2{3}(1), df2{3}(2), pvals2{3}(4));
fprintf('Statistics unpaired statcond anova 2-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3{3}(2,4), df3{3}(1), df3{3}(2), pvals3{3}(2,4));
fprintf('Statistics unpaired statcond anova 2-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4{3}(1,2,4), df4{3}(1), df4{3}(2), pvals4{3}(1,2,4));
assertsame([t1{3} t2{3}(4) t3{3}(2,4) t4{3}(1,2,4)], [df1{3}(1) df2{3}(1) df3{3}(1) df4{3}(1)], [df1{3}(2) df2{3}(2) df3{3}(2) df4{3}(2)], [pvals1{3} pvals2{3}(4) pvals3{3}(2,4) pvals4{3}(1,2,4)]);
disp('--------------------');
% testing shuffling and permutation for bootstrap
% -----------------------------------------------
clear a;
m1 = [1:10];
m2 = [1:10]+100;
m3 = [1:10]+1000;
a{1} = { m1 m2 };
a{2} = { m1 m2 m3 };
a{3} = { [ zeros(9,10); m1] [ zeros(9,10); m2] };
a{4} = { [ zeros(9,10); m1] [ zeros(9,10); m2] [ zeros(9,10); m3] };
tmpa = zeros(9,8,10); tmpa(end,end,:) = m1;
tmpb = zeros(9,8,10); tmpb(end,end,:) = m2;
tmpc = zeros(9,8,10); tmpc(end,end,:) = m3;
a{5} = { tmpa tmpb };
a{6} = { tmpa tmpb tmpc };
for method = 1:2
if method == 2, opt = {'arraycomp', 'off'}; else opt = {}; end;
for dim = 1:length(a)
[sa1] = statcond(a{dim}, 'mode', 'bootstrap', 'verbose', 'off', 'paired', 'on', 'returnresamplingarray', 'on', opt{:}, 'naccu', 10);
[sa2] = statcond(a{dim}, 'mode', 'perm' , 'verbose', 'off', 'paired', 'on', 'returnresamplingarray', 'on', opt{:}, 'naccu', 10);
[sa3] = statcond(a{dim}, 'mode', 'bootstrap', 'verbose', 'off', 'paired', 'off', 'returnresamplingarray', 'on', opt{:}, 'naccu', 10);
[sa4] = statcond(a{dim}, 'mode', 'perm' , 'verbose', 'off', 'paired', 'off', 'returnresamplingarray', 'on', opt{:}, 'naccu', 10);
% select data
nd = ndims(sa1{1});
if nd == 2 && size(sa1{1},2) > 1
for t=1:length(sa1),
sa1{t} = sa1{t}(end,:);
sa2{t} = sa2{t}(end,:);
sa3{t} = sa3{t}(end,:);
sa4{t} = sa4{t}(end,:);
end;
elseif nd == 3
for t=1:length(sa1),
sa1{t} = squeeze(sa1{t}(end,end,:));
sa2{t} = squeeze(sa2{t}(end,end,:));
sa3{t} = squeeze(sa3{t}(end,end,:));
sa4{t} = squeeze(sa4{t}(end,end,:));
end;
elseif nd == 4
for t=1:length(sa1),
sa1{t} = squeeze(sa1{t}(end,end,end,:));
sa2{t} = squeeze(sa2{t}(end,end,end,:));
sa3{t} = squeeze(sa3{t}(end,end,end,:));
sa4{t} = squeeze(sa4{t}(end,end,end,:));
end;
end;
% for paired bootstrap, we make sure that the resampling has only shuffled between conditions
% for instance [101 2 1003 104 ...] is an acceptable sequence
if all(rem(sa1{1}(:)',10) == [1:9 0]) && all(rem(sa1{2}(:)',10) == [1:9 0])
fprintf('Bootstrap paired dim%d resampling method %d Pass\n', dim, method);
else error('Bootstrap paired resampling Error');
end;
% for paired permutation, in addition, we make sure that the sum accross condition is constant
% which is not true for bootstrap
msa = meansa(sa2); msa = msa(:)-msa(1);
if all(rem(sa1{1}(:)',10) == [1:9 0]) && all(rem(sa1{2}(:)',10) == [1:9 0]) && ...
all(round(msa) == [0:9]') && length(unique(sa2{1})) == 10 && length(unique(sa2{2})) == 10
fprintf('Permutation paired dim%d resampling method %d Pass\n', dim, method);
else error('Permutation paired resampling Error');
end;
% for unpaired bootstrap, only make sure there are enough unique
% values
if length(unique(sa3{1})) > 3 && length(unique(sa3{2})) > 3
fprintf('Bootstrap unpaired dim%d reampling method %d Pass\n', dim, method);
else error('Bootstrap unpaired reampling Error');
end;
% for unpaired permutation, the number of unique values must be 10
% and the sum must be constant (not true for bootstrap)
if length(unique(sa4{1})) == 10 && length(unique(sa4{2})) == 10 && ( floor(mean(meansa(sa4))) == 55 || floor(mean(meansa(sa4))) == 372 )
fprintf('Permutation unpaired dim%d reampling method %d Pass\n', dim, method);
else error('Permutation unpaired reampling Error');
end;
disp('------------------------');
end;
end;
% function to check
function assertsame(varargin)
for ind = 1:length(varargin)
if length(varargin{1}) > 2
for tmpi = 1:length(varargin{1})-1
assertsame(varargin{1}(tmpi:tmpi+1));
end;
return;
else
if (varargin{ind}(1)-varargin{ind}(2)) > abs(mean(varargin{ind}))*0.01
error('Test failed');
end;
end;
end;
disp('Test pass');
function [meanmat] = meansa(mat)
meanmat = zeros(size(mat{1}));
for index = 1:length(mat)
meanmat = meanmat+mat{index}/length(mat);
end;
function stats = rm_anova2(Y,S,F1,F2,FACTNAMES)
%
% function stats = rm_anova2(Y,S,F1,F2,FACTNAMES)
%
% Two-factor, within-subject repeated measures ANOVA.
% For designs with two within-subject factors.
%
% Parameters:
% Y dependent variable (numeric) in a column vector
% S grouping variable for SUBJECT
% F1 grouping variable for factor #1
% F2 grouping variable for factor #2
% F1name name (character array) of factor #1
% F2name name (character array) of factor #2
%
% Y should be a 1-d column vector with all of your data (numeric).
% The grouping variables should also be 1-d numeric, each with same
% length as Y. Each entry in each of the grouping vectors indicates the
% level # (or subject #) of the corresponding entry in Y.
%
% Returns:
% stats is a cell array with the usual ANOVA table:
% Source / ss / df / ms / F / p
%
% Notes:
% Program does not do any input validation, so it is up to you to make
% sure that you have passed in the parameters in the correct form:
%
% Y, S, F1, and F2 must be numeric vectors all of the same length.
%
% There must be at least one value in Y for each possible combination
% of S, F1, and F2 (i.e. there must be at least one measurement per
% subject per condition).
%
% If there is more than one measurement per subject X condition, then
% the program will take the mean of those measurements.
%
% Aaron Schurger (2005.02.04)
% Derived from Keppel & Wickens (2004) "Design and Analysis" ch. 18
%
%
% Revision history...
%
% 11 December 2009 (Aaron Schurger)
%
% Fixed error under "bracket terms"
% was: expY = sum(Y.^2);
% now: expY = sum(sum(sum(MEANS.^2)));
%
stats = cell(4,5);
F1_lvls = unique_bc(F1);
F2_lvls = unique_bc(F2);
Subjs = unique_bc(S);
a = length(F1_lvls); % # of levels in factor 1
b = length(F2_lvls); % # of levels in factor 2
n = length(Subjs); % # of subjects
INDS = cell(a,b,n); % this will hold arrays of indices
CELLS = cell(a,b,n); % this will hold the data for each subject X condition
MEANS = zeros(a,b,n); % this will hold the means for each subj X condition
% Calculate means for each subject X condition.
% Keep data in CELLS, because in future we may want to allow options for
% how to compute the means (e.g. leaving out outliers > 3stdev, etc...).
for i=1:a % F1
for j=1:b % F2
for k=1:n % Subjs
INDS{i,j,k} = find(F1==F1_lvls(i) & F2==F2_lvls(j) & S==Subjs(k));
CELLS{i,j,k} = Y(INDS{i,j,k});
MEANS(i,j,k) = mean(CELLS{i,j,k});
end
end
end
% make tables (see table 18.1, p. 402)
AB = reshape(sum(MEANS,3),a,b); % across subjects
AS = reshape(sum(MEANS,2),a,n); % across factor 2
BS = reshape(sum(MEANS,1),b,n); % across factor 1
A = sum(AB,2); % sum across columns, so result is ax1 column vector
B = sum(AB,1); % sum across rows, so result is 1xb row vector
S = sum(AS,1); % sum across columns, so result is 1xs row vector
T = sum(sum(A)); % could sum either A or B or S, choice is arbitrary
% degrees of freedom
dfA = a-1;
dfB = b-1;
dfAB = (a-1)*(b-1);
dfS = n-1;
dfAS = (a-1)*(n-1);
dfBS = (b-1)*(n-1);
dfABS = (a-1)*(b-1)*(n-1);
% bracket terms (expected value)
expA = sum(A.^2)./(b*n);
expB = sum(B.^2)./(a*n);
expAB = sum(sum(AB.^2))./n;
expS = sum(S.^2)./(a*b);
expAS = sum(sum(AS.^2))./b;
expBS = sum(sum(BS.^2))./a;
expY = sum(sum(sum(MEANS.^2))); %sum(Y.^2);
expT = T^2 / (a*b*n);
% sums of squares
ssA = expA - expT;
ssB = expB - expT;
ssAB = expAB - expA - expB + expT;
ssS = expS - expT;
ssAS = expAS - expA - expS + expT;
ssBS = expBS - expB - expS + expT;
ssABS = expY - expAB - expAS - expBS + expA + expB + expS - expT;
ssTot = expY - expT;
% mean squares
msA = ssA / dfA;
msB = ssB / dfB;
msAB = ssAB / dfAB;
msS = ssS / dfS;
msAS = ssAS / dfAS;
msBS = ssBS / dfBS;
msABS = ssABS / dfABS;
% f statistic
fA = msA / msAS;
fB = msB / msBS;
fAB = msAB / msABS;
% p values
pA = 1-fcdf(fA,dfA,dfAS);
pB = 1-fcdf(fB,dfB,dfBS);
pAB = 1-fcdf(fAB,dfAB,dfABS);
% return values
stats = {'Source','SS','df','MS','F','p';...
FACTNAMES{1}, ssA, dfA, msA, fA, pA;...
FACTNAMES{2}, ssB, dfB, msB, fB, pB;...
[FACTNAMES{1} ' x ' FACTNAMES{2}], ssAB, dfAB, msAB, fAB, pAB;...
[FACTNAMES{1} ' x Subj'], ssAS, dfAS, msAS, [], [];...
[FACTNAMES{1} ' x Subj'], ssBS, dfBS, msBS, [], [];...
[FACTNAMES{1} ' x ' FACTNAMES{2} ' x Subj'], ssABS, dfABS, msABS, [], []};
return
|
github
|
ZijingMao/baselineeegtest-master
|
ttest2_cell.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/statistics/ttest2_cell.m
| 4,634 |
utf_8
|
cb20a27eff3e4cd6eb3c9ae82e863eed
|
% ttest2_cell() - compute unpaired t-test. Allow fast computation of
% multiple t-test using matrix manipulation.
%
% Usage:
% >> [F df] = ttest2_cell( { a b } );
% >> [F df] = ttest2_cell(a, b);
% >> [F df] = ttest2_cell(a, b, 'inhomogenous');
%
% Inputs:
% a,b = data consisting of UNPAIRED arrays to be compared. The last
% dimension of the data array is used to compute the t-test.
% 'inhomogenous' = use computation for the degree of freedom using
% inhomogenous variance. By default the computation of
% the degree of freedom is done with homogenous
% variances.
%
% Outputs:
% T - T-value
% df - degree of freedom (array)
%
% Example:
% a = { rand(1,10) rand(1,10)+0.5 }
% [T df] = ttest2_cell(a)
% signif = 2*tcdf(-abs(T), df(1))
%
% % for comparison, the same using the Matlab t-test function
% [h p ci stats] = ttest2(a{1}', a{2}');
% [ stats.tstat' p]
%
% % fast computation (fMRI scanner volume 100x100x100 and 10 control
% % subjects and 12 test subjects). The computation itself takes 0.5
% % seconds instead of half an hour using the standard approach (1000000
% % loops and Matlab t-test function)
% a = rand(100,100,100,10); b = rand(100,100,100,10);
% [F df] = ttest_cell({ a b });
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005
% (thank you to G. Rousselet for providing the formula for
% inhomogenous variances).
%
% Reference:
% Schaum's outlines in statistics (3rd edition). 1999. Mc Graw-Hill.
% Howel, Statistical Methods for Psychology. 2009. Wadsworth Publishing.
% 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 [tval, df] = ttest2_cell(a,b,c) % assumes equal variances
if nargin < 1
help ttest2_cell;
return;
end;
homogenous = 'homogenous';
if nargin > 1 && isstr(b)
homogenous = b;
end;
if nargin > 2 && isstr(c)
homogenous = c;
end;
if iscell(a),
b = a{2};
a = a{1};
end;
if ~strcmpi(homogenous, 'inhomogenous') && ~strcmpi(homogenous, 'homogenous')
error('Value for homogenous parameter can only be ''homogenous'' or ''inhomogenous''');
end;
nd = myndims(a);
na = size(a, nd);
nb = size(b, nd);
meana = mymean(a, nd);
meanb = mymean(b, nd);
if strcmpi(homogenous, 'inhomogenous')
% inhomogenous variance from Howel, 2009, "Statistical Methods for Psychology"
% thank you to G. Rousselet for providing these formulas
m = meana - meanb;
s1 = var(a,0,nd) ./ na;
s2 = var(b,0,nd) ./ nb;
se = sqrt(s1 + s2);
sd = sqrt([s1.*na, s2.*nb]);
tval = m ./ se;
df = ((s1 + s2).^2) ./ ((s1.^2 ./ (na-1) + s2.^2 ./ (nb-1)));
else
sda = mystd(a, [], nd);
sdb = mystd(b, [], nd);
sp = sqrt(((na-1)*sda.^2+(nb-1)*sdb.^2)/(na+nb-2));
tval = (meana-meanb)./sp/sqrt(1/na+1/nb);
df = na+nb-2;
end;
% check values againg Matlab statistics toolbox
% [h p ci stats] = ttest2(a', b');
% [ tval stats.tstat' ]
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
function res = mymean( data, varargin) % deal with complex numbers
res = mean( data, varargin{:});
if ~isreal(data)
res = abs( res );
end;
function res = mystd( data, varargin) % deal with complex numbers
if ~isreal(data)
res = std( abs(data), varargin{:});
else
res = sqrt(sum( bsxfun(@minus, data, mean( data, varargin{2})).^2, varargin{2})/(size(data,varargin{2})-1)); % 8 percent speedup
%res = std( data, varargin{:});
end;
|
github
|
ZijingMao/baselineeegtest-master
|
concatdata.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/statistics/concatdata.m
| 4,076 |
utf_8
|
f9b1c761e3ea4846ea5891a0ac56a923
|
% concatdata - concatenate data stored into a cell array into a single
% array. only concatenate along the last dimension
% Usage:
% [dataarray len dims] = concatata(cellarraydata);
%
% Input:
% cellarraydata - cell array containing data
%
% Output:
% dataarray - single array containing all data
% len - limits of each array
% dim - dimension of the orginal array
%
% Example:
% a = rand(3, 4, 3, 10);
% b = rand(3, 4, 3, 4);
% c = rand(3, 4, 3, 3);
% [ alldata len ] = concatdata({ a b c});
% % alldata is size [ 3 4 3 17 ]
% % len contains [ 0 10 14 17 ]
% % to access array number i, type "alldata(len(i)+1:len(i+1))
%
% Author: Arnaud Delorme, CERCO/CNRS & SCCN/INC/UCSD, 2009-
% 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 [ datac, alllen, dims ] = concatdata(data);
alllen = cellfun('size', data, myndims(data{1}) ); % by chance, pick up the last dimension
dims = size(data);
alllen = [ 0 alllen(:)' ];
switch myndims(data{1})
case 1,
datac = zeros(sum(alllen),1, 'single');
for i = 1:prod(dims)
alllen(i+1) = alllen(i+1) + alllen(i);
datac(alllen(i)+1:alllen(i+1)) = data{i};
end;
case 2,
datac = zeros(size(data{1},1), sum(alllen), 'single');
for i = 1:prod(dims)
alllen(i+1) = alllen(i+1) + alllen(i);
datac(:,alllen(i)+1:alllen(i+1)) = data{i};
end;
case 3,
datac = zeros(size(data{1},1), size(data{1},2), sum(alllen), 'single');
for i = 1:prod(dims)
alllen(i+1) = alllen(i+1) + alllen(i);
datac(:,:,alllen(i)+1:alllen(i+1)) = data{i};
end;
case 4,
datac = zeros(size(data{1},1), size(data{1},2), size(data{1},3), sum(alllen), 'single');
for i = 1:prod(dims)
alllen(i+1) = alllen(i+1) + alllen(i);
datac(:,:,:,alllen(i)+1:alllen(i+1)) = data{i};
end;
case 5,
datac = zeros(size(data{1},1), size(data{1},2), size(data{1},3), size(data{1},4), sum(alllen), 'single');
for i = 1:prod(dims)
alllen(i+1) = alllen(i+1) + alllen(i);
datac(:,:,:,:,alllen(i)+1:alllen(i+1)) = data{i};
end;
case 6,
datac = zeros(size(data{1},1), size(data{1},2), size(data{1},3), size(data{1},4),size(data{1},5), sum(alllen), 'single');
for i = 1:prod(dims)
alllen(i+1) = alllen(i+1) + alllen(i);
datac(:,:,:,:,:,alllen(i)+1:alllen(i+1)) = data{i};
end;
case 7,
datac = zeros(size(data{1},1), size(data{1},2), size(data{1},3), size(data{1},4), size(data{1},5), size(data{1},6), sum(alllen), 'single');
for i = 1:prod(dims)
alllen(i+1) = alllen(i+1) + alllen(i);
datac(:,:,:,:,:,:,alllen(i)+1:alllen(i+1)) = data{i};
end;
end;
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
ttest_cell.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/statistics/ttest_cell.m
| 3,107 |
utf_8
|
a669e2ffb5b0d990717a40eda3db4a2f
|
% ttest_cell() - compute paired t-test. Allow fast computation of
% multiple t-test using matrix manipulation.
%
% Usage:
% >> [F df] = ttest_cell( { a b } );
% >> [F df] = ttest_cell(a, b);
%
% Inputs:
% a,b = data consisting of PAIRED arrays to be compared. The last
% dimension of the data array is used to compute the t-test.
% Outputs:
% T - T-value
% df - degree of freedom (array)
%
% Example:
% a = { rand(1,10) rand(1,10)+0.5 }
% [T df] = ttest_cell(a)
% signif = 1-tcdf(T, df(1))
%
% % for comparison, the same using the Matlab t-test function
% [h p ci stats] = ttest(a{1}', b{1}');
% [ stats.tstat' p]
%
% % fast computation (fMRI scanner volume 100x100x100 and 10 subjects in
% % two conditions). The computation itself takes 0.5 seconds instead of
% % half an hour using the standard approach (1000000 loops and Matlab
% % t-test function)
% a = rand(100,100,100,10); b = rand(100,100,100,10);
% [F df] = ttest_cell({ a b });
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005
%
% Reference:
% Schaum's outlines in statistics (3rd edition). 1999. Mc Graw-Hill.
% 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 [tval, df] = ttest_cell(a,b)
if nargin < 1
help ttest_cell;
return;
end;
if iscell(a), b = a{2}; a = a{1}; end;
tmpdiff = a-b;
diff = mymean(tmpdiff, myndims(a));
sd = mystd( tmpdiff,[], myndims(a));
tval = diff./sd*sqrt(size(a, myndims(a)));
df = size(a, myndims(a))-1;
% check values againg Matlab statistics toolbox
%[h p ci stats] = ttest(a', b');
% [ tval stats.tstat' ]
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
function res = mymean( data, varargin) % deal with complex numbers
res = mean( data, varargin{:});
if ~isreal(data)
res = abs( res );
end;
function res = mystd( data, varargin) % deal with complex numbers
if ~isreal(data)
res = std( abs(data), varargin{:});
else
res = sqrt(sum( bsxfun(@minus, data, mean( data, varargin{2})).^2, varargin{2})/(size(data,varargin{2})-1)); % 8 percent speedup
%res = std( data, varargin{:});
end;
|
github
|
ZijingMao/baselineeegtest-master
|
statcondfieldtrip.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/statistics/statcondfieldtrip.m
| 15,444 |
utf_8
|
344cb60095d88b4626bf46c2475eab94
|
% statcondfiledtrip() - same as statcond except that it uses the fieldtrip
% statistical functions. This is useful to perform
% a wider variety of corrections for multiple
% comparisons for instance.
% Usage:
% >> [stats, df, pvals, surrog] = statcond( data, 'key','val'... );
% Inputs:
% data = same as for statcond()
%
% Optional inputs:
% 'paired' = ['on'|'off'] pair the data array {default: 'on' unless
% the last dimension of data array is of different lengths}.
% 'method' = ['permutation'|'parametric'] method for computing the p-values:
% 'parametric' = parametric testing (standard ANOVA or t-test);
% 'permutation' = non-parametric testing using surrogate data
% made by permuting the input data. Note that if 'bootstrap'
% is given as input, it is interpreted as 'permutation'
% Default is 'parametric'. Note that 'parametric'
% corresponds to the 'analytic' method of Fieldtrip and
% 'permutation' correspond to the 'montecarlo' method.
% 'naccu' = this input is passed on as 'numrandomization' to Fieldtrip
% 'neighbours' = Fieldtrip channel neighbour structure to perfom statistics
% and cluster correction for multiple comparisons accross
% channels.
% 'alpha' = [float] p-value threshold value. Allow returning
% confidence intervals and mask (requires structoutput below).
% 'structoutput' = ['on'|'off'] return an output structure instead of
% the regular output. Allow to output mask and confidence
% intervals.
%
% Fieldtrip options:
% Any option to the freqanalysis, the statistics_montecarlo, the
% statistics_analysis, statistics_stat, statistics_glm may be used
% using 'key', val argument pairs.
%
% Outputs:
% stats = F- or T-value array of the same size as input data without
% the last dimension. A T value is returned only when the data
% includes exactly two conditions.
% df = degrees of freedom, a (2,1) vector, when F-values are returned
% pvals = array of p-values. Same size as input data without the last
% data dimension. All returned p-values are two-tailed.
% surrog = surrogate data array (same size as input data with the last
% dimension filled with a number ('naccu') of surrogate data sets.
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005-
% With thanks to Robert Oostenveld for fruitful discussions
% and advice on this function.
%
% See also: freqanalysis(), statistics_montecarlol()
% 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 [ ori_vals, df, pvals ] = statcondfieldtrip( data, varargin );
if nargin < 1
help statcondfieldtrip;
return;
end;
[g cfgparams] = finputcheck( varargin, { 'naccu' '' [] [];
'method' 'string' { } 'param';
'mode' 'string' { } ''; % deprecated (old method)
'chanlocs' 'struct' { } struct([]);
'chandim' 'integer' [] 0;
'alpha' 'real' [] NaN;
'neighbours' 'struct' { } struct([]);
'structoutput' 'string' { 'on','off' } 'off';
% 'method' 'string' { } 'analytic'; % 'montecarlo','analytic','stat','glm'
'paired' 'string' { 'on','off' } 'on' }, 'statcond', 'ignore');
if isstr(g), error(g); end;
if ~isempty(g.mode), g.method = g.mode; end;
if strcmpi(g.method, 'parametric'), g.method = 'param'; end;
if strcmpi(g.method, 'permutation'), g.method = 'montecarlo'; end;
if ~isempty(g.neighbours) && isempty(g.chanlocs)
g.chanlocs = struct('labels', { g.neighbours(:).label });
end;
if size(data,2) == 1, data = transpose(data); end; % cell array transpose
alphaset = fastif(isnan(g.alpha) || isempty(g.alpha), 0, 1);
% remove first dimension for all input if necessary
% necessary for scalp topographies which are given as 1 x nelec x subj
% -------------------------------------------------
ndim = size(data{1});
if size(data{1},1) == 1
for index = 1:length(data(:))
data{index} = squeeze(data{index});
end;
end;
tmpsize = size(data{1});
% find the channel dimension if any
% ---------------------------------
if ~isempty(g.neighbours) && g.chandim == 0
for index = 1:ndims(data{1})
if size(data{1},index) == length(g.neighbours);
if g.chandim == 0
g.chandim = index;
else
error('Multiple possibilities for the channel dimension, please specify manually');
end;
end;
end;
end;
% cfg configuration for Fieldtrip
% -------------------------------
cfg = struct(cfgparams{:});
cfg.method = g.method;
if strcmpi(g.method, 'param') || strcmpi(g.method, 'parametric')
cfg.method = 'analytic';
elseif strcmpi(g.method, 'perm') && strcmpi(g.method, 'permutation') || strcmpi(g.method, 'bootstrap')
cfg.method = 'montecarlo';
end;
if ~isempty(g.neighbours)
cfg.neighbours = g.neighbours;
end;
if isfield(cfg, 'mcorrect')
cfg.correctm = cfg.mcorrect;
else cfg.mcorrect = [];
end;
cfg.feedback = 'no';
cfg.ivar = 1;
cfg.alpha = fastif(alphaset, g.alpha, 0.05);
cfg.numrandomization = g.naccu;
% test if data can be paired
% --------------------------
if length(unique(cellfun('size', data, ndims(data{1}) ))) > 1
g.paired = 'off';
end;
fprintf('%d x %d, ', size(data,1), size(data,2));
if strcmpi(g.paired, 'on')
fprintf('paired data, ');
else fprintf('unpaired data, ');
end;
if size(data,1) == 1 & size(data,2) == 2
fprintf('computing T values\n');
else fprintf('computing F values\n');
end;
% set randomizations
% ------------------
if strcmpi(cfg.method, 'montecarlo') && isempty(cfg.numrandomization)
cfg.numrandomization = 200;
if ~strcmpi(cfg.mcorrect, 'no'), cfg.numrandomization = cfg.numrandomization*20; end;
end;
cfg.correcttail = 'alpha';
if size(data,1) == 1, % only one row
if size(data,2) == 2 & strcmpi(g.paired, 'on')
% paired t-test (very fast)
% -------------
cfg.statistic = 'depsamplesT';
[newdata design1 design2 design3] = makefieldtripdata(data, g.chandim, g.chanlocs);
cfg.design = [ design1; design3 ];
cfg.uvar = 2;
stat = ft_freqstatistics(cfg, newdata{:});
if isfield(stat, 'df')
df = stat.df;
else df = [];
end;
elseif size(data,2) == 2 & strcmpi(g.paired, 'off')
% paired t-test (very fast)
% -------------
cfg.statistic = 'indepsamplesT';
[newdata design1] = makefieldtripdata(data, g.chandim, g.chanlocs);
cfg.design = design1;
stat = ft_freqstatistics(cfg, newdata{:});
if isfield(stat, 'df')
df = stat.df;
else df = [];
end;
elseif strcmpi(g.paired, 'on')
% one-way ANOVA (paired) this is equivalent to unpaired t-test
% -------------
cfg.tail = 1;
cfg.correcttail = 'no';
cfg.statistic = 'depsamplesF';
[newdata design1 design2 design3] = makefieldtripdata(data, g.chandim, g.chanlocs);
cfg.design = [ design1; design3 ];
cfg.uvar = 2;
stat = ft_freqstatistics(cfg, newdata{:});
if isfield(stat, 'dfnum')
df = [stat.dfnum stat.dfdenom];
else df = [];
end;
else
% one-way ANOVA (unpaired)
% -------------
cfg.tail = 1;
cfg.correcttail = 'no';
cfg.statistic = 'indepsamplesF';
[newdata design1] = makefieldtripdata(data, g.chandim, g.chanlocs);
cfg.design = [ design1 ];
warning off;
stat = ft_freqstatistics(cfg, newdata{:});
warning on;
if isfield(stat, 'dfnum')
df = [stat.dfnum stat.dfdenom];
else df = [];
end;
end;
else
if strcmpi(g.paired, 'on')
% two-way ANOVA (paired)
% -------------
cfg.tail = 1;
cfg.correcttail = 'no';
cfg.statistic = 'anovan';
[newdata design1 design2 design3] = makefieldtripdata(data, g.chandim, g.chanlocs);
cfg.design = [ design1; design2; design3 ];
cfg.effect = 'X1*X2';
cfg.ivar = [1 2];
cfg.uvar = 3;
stat = ft_freqstatistics(cfg, newdata{:});
ori_vals = stat.stat;
if isfield(stat, 'df')
df = stat.df;
else df = [];
end;
else
% two-way ANOVA (unpaired)
% -------------
cfg.tail = 1;
cfg.correcttail = 'no';
cfg.statistic = 'anovan';
cfg.clustercritval = 4.5416; % 95 percentile of n =10000; a = { rand(n,10) rand(n,10); rand(n,10) rand(n,10) }; [F df p ] = statcondfieldtrip(a, 'paired', 'off');
[newdata design1 design2] = makefieldtripdata(data, g.chandim, g.chanlocs);
if ~isempty(g.chanlocs)
for index = 1:length(newdata)
newdata{index}.powspctrm = squeeze(newdata{index}.powspctrm);
newdata{index}.label = { g.chanlocs.labels };
newdata{index}.freq = 1;
end;
end;
cfg
newdata{1}
cfg.design = [ design1; design2 ];
cfg.effect = 'X1*X2';
cfg.ivar = [1 2];
stat = ft_freqstatistics(cfg, newdata{:});
ori_vals = stat.stat;
df = stat.df;
end;
end;
ori_vals = stat.stat;
pvals = stat.prob;
if size(ori_vals,1) ~= size(data{1},1) && size(ori_vals,1) == 1
ori_vals = reshape(ori_vals, size(ori_vals,2), size(ori_vals,3), size(ori_vals,4));
pvals = reshape(pvals , size(pvals ,2), size(pvals ,3), size(pvals ,4));
if isfield(stat, 'mask')
stat.mask = reshape(stat.mask , size(stat.mask ,2), size(stat.mask ,3), size(stat.mask ,4));
end;
end;
if strcmpi(g.structoutput, 'on')
outputstruct.mask = stat.mask;
outputstruct.pval = pvals;
if length(data(:)) == 2
outputstruct.t = ori_vals;
else outputstruct.f = ori_vals;
end;
outputstruct.stat = ori_vals;
% outputstruct.method = g.method;
% outputstruct.pval = pvals;
% outputstruct.df = df;
% outputstruct.surrog = surrogval;
% if length(data(:)) == 2
% outputstruct.t = ori_vals;
% else outputstruct.f = ori_vals;
% end;
ori_vals = outputstruct;
end;
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
function [newdata, design1, design2, design3] = makefieldtripdata(data, chandim, chanlocs);
newdata = {};
swapdim = [];
for i = 1:length(data(:))
newdata{i}.dimord = 'rpt_chan_freq_time';
switch myndims(data{1})
case 1,
newdata{i}.powspctrm = data{i};
case 2,
if chandim
newdata{i}.powspctrm = transpose(data{i});
else newdata{i}.powspctrm = reshape(transpose(data{i}), size(data{i},2), 1, size(data{i},1));
end;
case 3,
if chandim == 2 % chandim can be 1 or 2
swapdim = [2 1];
end;
if chandim
newdata{i}.powspctrm = permute(data{i}, [3 1 2]);
else newdata{i}.powspctrm = permute(data{i}, [3 4 1 2]); % 4 is a singleton dimension
end;
case 4,
newdata{i}.powspctrm = permute(data{i}, [4 1 2 3]);
end;
newdata{i}.label = cell(1,size(newdata{i}.powspctrm,2));
newdata{i}.label(:) = { 'cz' };
for ic = 1:length(newdata{i}.label)
newdata{i}.label{ic} = [ 'c' num2str(ic) ];
end;
newdata{i}.freq = [1:size(newdata{i}.powspctrm,3)];
newdata{i}.time = [1:size(newdata{i}.powspctrm,4)];
% below in case channels are specified
% not that statistics are done on time x frequencies or channels
% so time x frequency x channels do not work yet here
if ~isempty(chanlocs)
newdata{i}.powspctrm = squeeze(newdata{i}.powspctrm);
newdata{i}.label = { chanlocs.labels };
newdata{i}.freq = 1;
newdata{i}.time = 1;
end;
if isempty(chanlocs) && size(newdata{i}.powspctrm,2) ~= 1
newdata{i}.dimord = 'rpt_freq_time';
end;
end;
design1 = [];
design2 = [];
design3 = [];
for i = 1:size(data,2)
for j = 1:size(data,1)
nrepeat = size(data{i}, ndims(data{i}));
ij = j+(i-1)*size(data,1);
design1 = [ design1 ones(1, nrepeat)*i ];
design2 = [ design2 ones(1, nrepeat)*j ];
design3 = [ design3 [1:nrepeat] ];
end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
corrcoef_cell.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/statistics/corrcoef_cell.m
| 3,242 |
utf_8
|
0c78b817804b92c20e7a7a7b084134ab
|
% corrcoef_cell() - compute pairwise correlations using arrays and
% cell array inputs.
%
% Usage:
% >> c = corrcoef_cell( data );
% >> c = corrcoef_cell( data );
%
% Inputs:
% data - [cell array] data consisting of PAIRED arrays to be compared.
% The last dimension of embeded data arrays is used to compute
% correlation (see examples).
% Outputs:
% c - Correlation values. Same size as data without the last dimension.
%
% Note: the main advantage over the corrcoef Matlab function is the
% capacity to compute millions of pairwise correlations per second.
%
% Example:
% a = { rand(1,10) rand(1,10) };
% c1 = corrcoef_cell(a);
% c2 = corrcoef(a{1}, a{2});
% % in this case, c1 is equal to c2(2)
%
% a = { rand(200,300,100) rand(200,300,100) };
% c = corrcoef_cell(a);
% % the call above would require 200 x 300 calls to the corrcoef function
% % and be about 1000 times slower
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 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 c = corrcoef_cell(a,b);
if nargin < 1
help corrcoef_cell;
return;
end;
if nargin < 2
b = a{2};
a = a{1};
end;
nd = myndims(a);
if nd == 1
aa = a-mean(a);
bb = b-mean(b);
cv = aa'*bb/(10-1);
cva = aa'*aa/(10-1);
cvb = bb'*bb/(10-1);
c = cv/sqrt(cva*cvb);
elseif nd == 2 % ND=2, 3, and 4 could be replaced with a single line
aa = bsxfun(@minus, a, mean(a,2));
bb = bsxfun(@minus, b, mean(b,2));
%aa = a-repmat(mean(a,2),[1 size(a,2)]);
%bb = b-repmat(mean(b,2),[1 size(a,2)]);
cv = sum(aa.*bb,2);
cva = sum(aa.*aa,2);
cvb = sum(bb.*bb,2);
c = cv./sqrt(cva.*cvb);
elseif nd == 3
aa = bsxfun(@minus, a, mean(a,3));
bb = bsxfun(@minus, b, mean(b,3));
%aa = a-repmat(mean(a,3),[1 1 size(a,3)]);
%bb = b-repmat(mean(b,3),[1 1 size(a,3)]);
cv = sum(aa.*bb,3);
cva = sum(aa.*aa,3);
cvb = sum(bb.*bb,3);
c = cv./sqrt(cva.*cvb);
elseif nd == 4
aa = bsxfun(@minus, a, mean(a,4));
bb = bsxfun(@minus, b, mean(b,4));
%aa = a-repmat(mean(a,4),[1 1 1 size(a,4)]);
%bb = b-repmat(mean(b,4),[1 1 1 size(a,4)]);
cv = sum(aa.*bb,4);
cva = sum(aa.*aa,4);
cvb = sum(bb.*bb,4);
c = cv./sqrt(cva.*cvb);
end;
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
stat_surrogate_ci.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/statistics/stat_surrogate_ci.m
| 3,125 |
utf_8
|
cd001b0625997e12a9b2e0bd2accbfe5
|
% compute empirical p-vals under the null hypothesis that observed samples
% come from a given surrogate distribution. P-values for Type I error in
% rejecting the null hypothesis are obtained by finding the proportion of
% samples in the distribution that
% (a) are larger than the observed sample (one-sided test)
% (b) are larger or smaller than the observed sample (two-sided test).
%
% Inputs:
% distribution: [d1 x d2 x ... x dM x N] matrix of surrogate samples.
% distribution(i,j,k,...,:) is a collection of N samples
% from a surrogate distribution.
% alpha: [float] alpha value. Default
% tail: can be 'one' or 'both' indicating a one-tailed or
% two-tailed test. Can also be 'lower' or 'upper'.
% Outputs:
%
% ci: [2 x d1 x d2 x ... x dM] matrix of confidence interval
%
% Author: Tim Mullen and Arnaud Delorme, SCCN/INC/UCSD
% This function is part of the Source Information Flow Toolbox (SIFT)
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function ci = stat_surrogate_ci(distribution,alpha,tail)
if nargin<3
tail = 'both';
end
if nargin<2
alpha = 0.05;
end
% reshape matrix
% --------------
nd = size(distribution);
if length(nd) == 2 && nd(2) == 1, nd(2) = []; end;
ndori = nd;
nd = nd(1:end-1);
if isempty(nd), nd = 1; end;
distribution = reshape(distribution, [prod(nd) size(distribution,myndims(distribution))]);
% append observed to last dimension of surrogate distribution
numDims = myndims(distribution);
% number of samples
N = size(distribution, numDims);
% sort along last dimension (replications)
[tmpsort idx] = sort( distribution, numDims,'ascend');
if strcmpi(tail, 'both'), alpha = alpha/2; end;
low = round(alpha*N);
high = N-low;
switch lower(tail)
case 'upper'
cilow = mean(tmpsort, numDims);
cihigh = tmpsort(:,high);
case 'lower'
cilow = tmpsort(:,low+1);
cihigh = mean(tmpsort, numDims);
case { 'both' 'one' }
cilow = tmpsort(:,low+1);
cihigh = tmpsort(:,high);
otherwise
error('Unknown tail option');
end
ci = reshape(cilow, [1 size(cilow)]);
ci(2,:) = cihigh;
ci = reshape(ci, [2 ndori(1:end-1) 1]);
% get the number of dimensions in a matrix
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
anova1_cell.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/statistics/anova1_cell.m
| 4,428 |
utf_8
|
60e8465ee6822f93b4e4d4bcad190d42
|
% anova1_cell() - compute F-values in cell array using ANOVA.
%
% Usage:
% >> [F df] = anova1_cell( data );
%
% Inputs:
% data = data consisting of PAIRED arrays to be compared. The last
% dimension of the data array is used to compute ANOVA.
% Outputs:
% F - F-value
% df - degree of freedom (array)
%
% Note: the advantage over the ANOVA1 function of Matlab statistical
% toolbox is that this function works on arrays (see examples). Note
% also that you still need the statistical toolbox to assess
% significance using the fcdf() function. The other advantage is that
% this function will work with complex numbers.
%
% Example:
% a = { rand(1,10) rand(1,10) rand(1,10) }
% [F df] = anova1_cell(a)
% signif = 1-fcdf(F, df(1), df(2))
%
% % for comparison
% anova1( [ a{1,1}' a{1,2}' a{1,3}' ]) % look in the graph for the F value
%
% b = { [ a{1,1}; a{1,1} ] [ a{1,2}; a{1,2} ] [ a{1,3}; a{1,3} ] }
% [F df] = anova1_cell(b)
%
% c{1,1} = reshape(repmat(b{1,1}, [2 1]),2,2,10);
% c{1,2} = reshape(repmat(b{1,2}, [2 1]),2,2,10);
% c{1,3} = reshape(repmat(b{1,3}, [2 1]),2,2,10);
% [F df] = anova1_cell(c)
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005
%
% Reference:
% Schaum's outlines in statistics (3rd edition). 1999. Mc Graw-Hill.
% 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 [F, df] = anova1_cell(data)
% This function does not return
% correct values (see bug 336)
% It should be fixed with Schaum's outlines p363
% but requires some work. It now calls
% anova2_cell which returns correct values
warning off;
[ F tmp tmp2 df] = anova2_cell(data);
warning on;
return;
% compute all means and all std
% -----------------------------
nd = myndims( data{1} );
if nd == 1
for i = 1:length(data)
n( i) = length(data{i});
m( i) = mymean( data{i});
sd(i) = mystd( data{i});
end;
nt = sum(n);
n = n';
m = m';
sd = sd';
elseif nd == 2
for i = 1:length(data)
n( :,i) = ones(size(data{i},1) * size(data{i},2), 'single');
m( :,i) = mymean( data{i},2);
sd(:,i) = mystd( data{i},[],2);
end;
nt = sum(n(1,:));
elseif nd == 3
for i = 1:length(data)
n( :,:,i) = ones(size(data{i},1),size(data{i},2) * size(data{i},3), 'single');
m( :,:,i) = mymean( data{i},3);
sd(:,:,i) = mystd( data{i},[],3);
end;
nt = sum(n(1,1,:));
elseif nd == 4
for i = 1:length(data)
n( :,:,:,i) = ones(size(data{i},1),size(data{i},2), size(data{i},3) * size(data{i},4), 'single');
m( :,:,:,i) = mymean( data{i},4);
sd(:,:,:,i) = mystd( data{i},[],4);
end;
nt = sum(n(1,1,1,:));
end;
mt = mean(m,nd);
ng = length(data); % number of conditions
VinterG = ( sum( n.*(m.^2), nd ) - nt*mt.^2 )/(ng-1);
VwithinG = sum( (n-1).*(sd.^2), nd )/(nt-ng);
F = VinterG./VwithinG;
df = [ ng-1 ng*(size(data{1},nd)-1) ];
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
function res = mymean( data, varargin) % deal with complex numbers
res = mean( data, varargin{:});
if ~isreal(data)
res = abs( res );
end;
function res = mystd( data, varargin) % deal with complex numbers
res = std( abs(data), varargin{:});
|
github
|
ZijingMao/baselineeegtest-master
|
fdr.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/statistics/fdr.m
| 2,273 |
utf_8
|
0339630d5b76067fde504d464d26a9bf
|
% fdr() - compute false detection rate mask
%
% Usage:
% >> [p_fdr, p_masked] = fdr( pvals, alpha);
%
% Inputs:
% pvals - vector or array of p-values
% alpha - threshold value (non-corrected). If no alpha is given
% each p-value is used as its own alpha and FDR corrected
% array is returned.
% fdrtype - ['parametric'|'nonParametric'] FDR type. Default is
% 'parametric'.
%
% Outputs:
% p_fdr - pvalue used for threshold (based on independence
% or positive dependence of measurements)
% p_masked - p-value thresholded. Same size as pvals.
%
% Author: Arnaud Delorme, SCCN, 2008-
% Based on a function by Tom Nichols
%
% Reference: Bejamini & Yekutieli (2001) The Annals of Statistics
% Copyright (C) 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 [pID, p_masked] = fdr(pvals, q, fdrType);
if nargin < 3, fdrType = 'parametric'; end;
if isempty(pvals), pID = []; return; end;
p = sort(pvals(:));
V = length(p);
I = (1:V)';
cVID = 1;
cVN = sum(1./(1:V));
if nargin < 2
pID = ones(size(pvals));
thresholds = exp(linspace(log(0.1),log(0.000001), 100));
for index = 1:length(thresholds)
[tmp p_masked] = fdr(pvals, thresholds(index));
pID(p_masked) = thresholds(index);
end;
else
if strcmpi(fdrType, 'parametric')
pID = p(max(find(p<=I/V*q/cVID))); % standard FDR
else
pID = p(max(find(p<=I/V*q/cVN))); % non-parametric FDR
end;
end;
if isempty(pID), pID = 0; end;
if nargout > 1
p_masked = pvals<=pID;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
anova2_cell.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/statistics/anova2_cell.m
| 8,530 |
utf_8
|
3f58b154b60557add57c3652a63d8b62
|
% anova2_cell() - compute F-values in cell array using ANOVA.
%
% Usage:
% >> [FC FR FI dfc dfr dfi] = anova2_cell( data );
%
% Inputs:
% data = data consisting of PAIRED arrays to be compared. The last
% dimension of the data array is used to compute ANOVA.
% Outputs:
% FC - F-value for columns.
% FR - F-value for rows.
% FI - F-value for interaction.
% dfc - degree of freedom for columns.
% dfr - degree of freedom for rows.
% dfi - degree of freedom for interaction.
%
% Note: the advantage over the ANOVA2 function of Matlab statistical
% toolbox is that this function works on arrays (see examples). Note
% also that you still need the statistical toolbox to assess
% significance using the fcdf() function. The other advantage is that
% this function will work with complex numbers.
%
% Example:
% a = { rand(1,10) rand(1,10) rand(1,10); rand(1,10) rand(1,10) rand(1,10) }
% [FC FR FI dfc dfr dfi] = anova2_cell(a)
% signifC = 1-fcdf(FC, dfc(1), dfc(2))
% signifR = 1-fcdf(FR, dfr(1), dfr(2))
% signifI = 1-fcdf(FI, dfi(1), dfi(2))
%
% % for comparison
% anova2( [ a{1,1}' a{1,2}' a{1,3}'; a{2,1}' a{2,2}' a{2,3}' ], 10)
%
% b = { [ a{1,1}; a{1,1} ] [ a{1,2}; a{1,2} ] [ a{1,3}; a{1,3} ];
% [ a{2,1}; a{2,1} ] [ a{2,2}; a{2,2} ] [ a{2,3}; a{2,3} ] }
% [FC FR FI dfc dfr dfi] = anova2_cell(b)
%
% c{1,1} = reshape(repmat(b{1,1}, [2 1]),2,2,10);
% c{1,2} = reshape(repmat(b{1,2}, [2 1]),2,2,10);
% c{1,3} = reshape(repmat(b{1,3}, [2 1]),2,2,10);
% c{2,3} = reshape(repmat(b{2,3}, [2 1]),2,2,10);
% c{2,2} = reshape(repmat(b{2,2}, [2 1]),2,2,10);
% c{2,1} = reshape(repmat(b{2,1}, [2 1]),2,2,10)
% [FC FR FI dfc dfr dfi] = anova2_cell(c)
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005
%
% Reference:
% Schaum's outlines in statistics (3rd edition). 1999. Mc Graw-Hill.
% 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 [FC, FR, FI, freeC, freeR, freeI] = anova2_cell(data)
% compute all means and all std
% -----------------------------
a = size(data,1);
b = size(data,2);
nd = myndims( data{1} );
c = size(data{1}, nd);
sz = size(data{1});
% dataabs if for complex data only
% --------------------------------
dataabs = data;
if ~isreal(data{1})
for i = 1:a
for ii = 1:b
dataabs{i,ii} = abs(data{i,ii});
end;
end;
end;
VE = zeros( [ sz(1:end-1) 1], 'single' );
m = zeros( [ sz(1:end-1) size(data) ], 'single' );
for i = 1:a
for ii = 1:b
tmpm = mymean(data{i,ii}, nd);
switch nd
case 1, m(i,ii) = tmpm;
case 2, m(:,i,ii) = tmpm;
case 3, m(:,:,i,ii) = tmpm;
case 4, m(:,:,:,i,ii) = tmpm;
case 5, m(:,:,:,:,i,ii) = tmpm;
case 6, m(:,:,:,:,:,i,ii) = tmpm;
case 7, m(:,:,:,:,:,:,i,ii) = tmpm;
otherwise error('Dimension not supported');
end;
VE = VE+sum( bsxfun(@minus, dataabs{i,ii}, tmpm).^2, nd);
end;
end;
X = mean(mean(m,nd+1),nd);
Xj = mean(m,nd+1);
Xk = mean(m,nd);
VR = b*c*sum( bsxfun(@minus, Xj, X).^2, nd);
VC = a*c*sum( bsxfun(@minus, Xk, X).^2, nd+1 );
VI = c*sum( sum( bsxfun(@plus, bsxfun(@minus, bsxfun(@minus, m, Xj), Xk), X).^2, nd+1 ), nd );
% before bsxfun
% VR = b*c*sum( (Xj-repmat(X, [ones(1,nd-1) size(Xj,nd )])).^2, nd );
% VC = a*c*sum( (Xk-repmat(X, [ones(1,nd ) size(Xk,nd+1)])).^2, nd+1 );
%
% Xj = repmat(Xj, [ones(1,nd) size(m,nd+1) ]);
% Xk = repmat(Xk, [ones(1,nd-1) size(m,nd) 1]);
% VI = c*sum( sum( ( m - Xj - Xk + repmat(X, [ones(1,nd-1) size(m,nd) size(m,nd+1)]) ).^2, nd+1 ), nd );
% if nd == 1
%
% VE = 0;
% m = zeros( size(data), 'single' );
% for i = 1:a
% for ii = 1:b
% m(i,ii) = mymean(data{i,ii});
% VE = VE+sum( (dataabs{i,ii}-m(i,ii)).^2 );
% end;
% end;
% X = mean(mean(m));
% Xj = mean(m,2);
% Xk = mean(m,1);
% VR = b*c*sum( (Xj-X).^2 );
% VC = a*c*sum( (Xk-X).^2 );
%
% Xj = repmat(Xj, [1 size(m,2) ]);
% Xk = repmat(Xk, [size(m,1) 1]);
% VI = c*sum( sum( ( m - Xj - Xk + X ).^2 ) );
%
% elseif nd == 2
%
% VE = zeros( size(data{1},1),1, 'single');
% m = zeros( [ size(data{1},1) size(data) ], 'single' );
% for i = 1:a
% for ii = 1:b
% tmpm = mymean(data{i,ii}, 2);
% m(:,i,ii) = tmpm;
% VE = VE+sum( (dataabs{i,ii}-repmat(tmpm, [1 size(data{i,ii},2)])).^2, 2);
% end;
% end;
% X = mean(mean(m,3),2);
% Xj = mean(m,3);
% Xk = mean(m,2);
% VR = b*c*sum( (Xj-repmat(X, [1 size(Xj,2)])).^2, 2 );
% VC = a*c*sum( (Xk-repmat(X, [1 1 size(Xk,3)])).^2, 3 );
%
% Xj = repmat(Xj, [1 1 size(m,3) ]);
% Xk = repmat(Xk, [1 size(m,2) 1]);
% VI = c*sum( sum( ( m - Xj - Xk + repmat(X, [1 size(m,2) size(m,3)]) ).^2, 3), 2 );
%
% elseif nd == 3
%
% VE = zeros( size(data{1},1), size(data{1},2), 'single' );
% m = zeros( [ size(data{1},1) size(data{1},2) size(data) ], 'single' );
% for i = 1:a
% for ii = 1:b
% tmpm = mymean(data{i,ii}, 3);
% m(:,:,i,ii) = tmpm;
% VE = VE+sum( (dataabs{i,ii}-repmat(tmpm, [1 1 size(data{i,ii},3)])).^2, 3);
% end;
% end;
% X = mean(mean(m,4),3);
% Xj = mean(m,4);
% Xk = mean(m,3);
% VR = b*c*sum( (Xj-repmat(X, [1 1 size(Xj,3) ])).^2, 3 );
% VC = a*c*sum( (Xk-repmat(X, [1 1 1 size(Xk,4)])).^2, 4 );
%
% Xj = repmat(Xj, [1 1 1 size(m,4) ]);
% Xk = repmat(Xk, [1 1 size(m,3) 1]);
% VI = c*sum( sum( ( m - Xj - Xk + repmat(X, [1 1 size(m,3) size(m,4)]) ).^2, 4 ), 3 );
%
% else % nd == 4
%
% VE = zeros( size(data{1},1), size(data{1},2), size(data{1},3), 'single' );
% m = zeros( [ size(data{1},1) size(data{1},2) size(data{1},3) size(data) ], 'single' );
% for i = 1:a
% for ii = 1:b
% tmpm = mymean(data{i,ii}, 4);
% m(:,:,:,i,ii) = tmpm;
% VE = VE+sum( (dataabs{i,ii}-repmat(tmpm, [1 1 1 size(data{i,ii},4)])).^2, 4);
% end;
% end;
% X = mean(mean(m,5),4);
% Xj = mean(m,5);
% Xk = mean(m,4);
% VR = b*c*sum( (Xj-repmat(X, [1 1 1 size(Xj,4) ])).^2, 4 );
% VC = a*c*sum( (Xk-repmat(X, [1 1 1 1 size(Xk,5)])).^2, 5 );
%
% Xj = repmat(Xj, [1 1 1 1 size(m,5) ]);
% Xk = repmat(Xk, [1 1 1 size(m,4) 1]);
% VI = c*sum( sum( ( m - Xj - Xk + repmat(X, [1 1 1 size(m,4) size(m,5)]) ).^2, 5 ), 4 );
%
% end;
SR2 = VR/(a-1);
SC2 = VC/(b-1);
SI2 = VI/(a-1)/(b-1);
SE2 = VE/(a*b*(c-1));
FR = SR2./SE2; % rows
FC = SC2./SE2; % columns
FI = SI2./SE2; % interaction
freeR = [ a-1 a*b*(c-1) ];
freeC = [ b-1 a*b*(c-1) ];
freeI = [ (a-1)*(b-1) a*b*(c-1) ];
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
function res = mymean( data, varargin) % deal with complex numbers
res = mean( data, varargin{:});
if ~isreal(data)
res = abs( res );
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_expica.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_expica.m
| 2,190 |
utf_8
|
de6256134d052dc2d501f1da80a85a5a
|
% pop_expica() - export ICA weights or inverse matrix
%
% Usage:
% >> pop_expica( EEG, whichica); % a window pops up
% >> pop_expica( EEG, whichica, filename );
%
% Inputs:
% EEG - EEGLAB dataset
% whichica - ['weights'|'inv'] export ica 'weights' or ica inverse
% matrix ('inv'). Note: for 'weights', the function
% export the product of the sphere and weights matrix.
% filename - text file name
%
% Author: Arnaud Delorme, CNL / Salk Institute, Mai 14, 2003
%
% See also: pop_export()
% Copyright (C) Mai 14, 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 com = pop_expica(EEG, whichica, filename);
com = '';
if nargin < 1
help pop_expica;
return;
end;
if nargin < 2
whichica = 'weights';
end;
switch lower(whichica)
case {'weights' 'inv'}, ;
otherwise error('Unrecognized option for ''whichica'' parameter');
end;
if nargin < 3
% ask user
[filename, filepath] = uiputfile('*.*', [ 'File name for ' ...
fastif(strcmpi(whichica, 'inv'), 'inverse', 'weight') ' matrix -- pop_expica()']);
drawnow;
if filename == 0 return; end;
filename = [filepath filename];
end;
% save datas
% ----------
if strcmpi(whichica, 'inv')
tmpmat = double(EEG.icawinv);
else
tmpmat = double(EEG.icaweights*EEG.icasphere);
end;
save(filename, '-ascii', 'tmpmat');
com = sprintf('pop_expica(%s, ''%s'', ''%s'');', inputname(1), whichica, filename);
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_loadbci.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_loadbci.m
| 13,381 |
utf_8
|
471e8acb985f699ddd0e2e3b3a723d45
|
% pop_loadbci() - import a BCI2000 ascii file into EEGLAB
%
% Usage:
% >> OUTEEG = pop_loadbci( filename, srate );
%
% Inputs:
% filename - file name
% srate - sampling rate
%
% Outputs:
% OUTEEG - EEGLAB data structure
%
% Author: Arnaud Delorme, CNL / Salk Institute, 9 July 2002
%
% See also: eeglab()
% Copyright (C) 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, command] = pop_loadbci(filename, srate);
EEG = [];
command = '';
if nargin < 1
% ask user
[filename, filepath] = uigetfile('*.*', 'Choose a BCI file -- pop_loadbci');
drawnow;
if filename == 0 return; end;
filename = [filepath filename];
promptstr = { 'Sampling rate' };
inistr = { '256' };
result = inputdlg2( promptstr, 'Import BCI2000 data -- pop_loadbci()', 1, inistr, 'pop_loadbci');
if length(result) == 0 return; end;
srate = eval( result{1} );
end;
% import data
% -----------
EEG = eeg_emptyset;
fprintf('Pop_loadbci: importing BCI file...\n');
try
% try to read as matlab
% ---------------------
bci = load( filename, '-mat');
allfields = fieldnames(bci);
allfields = setdiff_bc(allfields, 'signal');
for index = 1:size(bci.signal,2)
chanlabels{index} = [ 'C' int2str(index) ];
end;
for index = 1:length(allfields)
bci.signal(:,end+1) = getfield(bci, allfields{index});
end;
EEG.chanlocs = struct('labels', { chanlabels{:} allfields{:} });
EEG.data = bci.signal';
EEG.nbchan = size(EEG.data, 1);
EEG.pnts = size(EEG.data, 2);
EEG.trials = 1;
EEG.srate = srate;
EEG.comments = [ 'Original file: ' filename ];
EEG = eeg_checkset(EEG);
return;
catch
% get file names
% --------------
fields = loadtxt(filename, 'nlines', 1, 'verbose', 'off');
if length(fields) > 300
error('Not a BCI ASCII file');
end;
% read data
% ---------
fid = fopen(filename, 'r');
allcollumns = fgetl(fid);
tmpdata = fscanf(fid, '%d', Inf);
tmpdata = reshape(tmpdata, length(fields), length(tmpdata)/length(fields));
EEG.data = tmpdata;
EEG.chanlocs = struct('labels', fields);
EEG.nbchan = size(EEG.data, 1);
EEG.pnts = size(EEG.data, 2);
EEG.trials = 1;
EEG.srate = srate;
EEG = eeg_checkset(EEG);
return;
% data channel range
% ------------------
indices = strmatch('ch', fields);
bci = [];
for index = setdiff_bc(1:length(fields), indices)
bci = setfield(bci, fields{index}, tmpdata(index,:));
end;
bci.signal = tmpdata(indices,:);
end;
% ask for which event to import
% -----------------------------
geom = {[0.7 0.7 0.7]};
uilist = { { 'style' 'text' 'string' 'State name' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' ' Import' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Type of' 'fontweight' 'bold' } };
allfields = setdiff_bc(fieldnames(bci), 'signal');
latencyfields = { '-----' };
for index = 1:length(allfields)
if ~isempty(findstr( lower(allfields{index}), 'time'))
latencyfields{end+1} = allfields{index};
end;
end;
for index = 1:length(allfields)
geom = { geom{:} [1.3 0.3 0.3 0.3 1] };
uilist{end+1} = { 'style' 'text' 'string' allfields{index} };
if ~isempty(findstr( lower(allfields{index}), 'time'))
uilist{end+1} = { 'style' 'checkbox' 'value' 0 };
uilist{end+1} = { };
uilist{end+1} = { };
uilist{end+1} = { };
else
uilist{end+1} = { 'style' 'checkbox' };
uilist{end+1} = { };
uilist{end+1} = { };
uilist{end+1} = { 'style' 'listbox' 'string' strvcat(latencyfields) };
end;
end;
geom = { geom{:} [1] [0.08 1] };
uilist{end+1} = { };
uilist{end+1} = { 'style' 'checkbox' 'value' 0 };
uilist{end+1} = { 'style' 'text' 'string' 'Attempt to adjust event latencies using sourcetime?' };
result = inputgui( geom, uilist, 'pophelp(''pop_loadbci'')', 'Import BCI2000 data files - pop_loadbci()');
if isempty(result), return; end;
% convert results to command line input
% -------------------------------------
listimport = {};
count = 1;
for index = 1:length(allfields)
if ~isempty(findstr( lower(allfields{index}), 'time'))
if result{count}, listimport{end+1} = 'event'; listimport{end+1} = { allfields{index} }; end;
count = count+1;
else
if result{count}
if result{count+1} ~= 1
listimport{end+1} = 'event'; listimport{end+1} = { allfields{index} allfields{result{count+1}-1} };
else
listimport{end+1} = 'event'; listimport{end+1} = { allfields{index} };
end;
end;
count = count+2;
end;
end;
if result{end}, adjust = 1; else adjust = 0; end;
% decode command line input
% -------------------------
count = 1;
for index = 2:2:length(listimport)
tmpindmatch = strmatch(listimport{index}{1}, allfields, 'exact');
if ~isempty(tmpindmatch), indeximport(count) = tmpindmatch;
else error(['State ''' listimport{index}{1} ''' not found']);
end;
if length( listimport{index} ) > 1
tmpindmatch = strmatch(listimport{index}{2}, allfields, 'exact');
if ~isempty(tmpindmatch), corresp(count) = tmpindmatch;
else error(['State ''' listimport{index}{2} ''' not found']);
end;
else
corresp(count) = 0;
end;
count = count+1;
end;
% find block size
% ---------------
tmpevent = find( diff(getfield(bci, 'SourceTime')) ~= 0);
diffevent = tmpevent(2:end)-tmpevent(1:end-1);
blocksize = unique_bc(diffevent);
if length(blocksize) > 1, error('Error in determining block size');
else fprintf('Blocksize: %d\n', blocksize);
end;
% find types
% ----------
tmpcorresp = find(corresp);
indexcorresp = corresp(tmpcorresp);
indexcorrespval = indeximport(tmpcorresp);
if length(tmpcorresp) ~= length(intersect(corresp, indeximport))
disp('Warning: correspondance problem, some information will be lost');
end;
% remove type from latency array
% ------------------------------
indeximport(tmpcorresp) = [];
if adjust
fprintf('Latency of event will be adjusted\n');
else fprintf('WARNING: Latency of event will not be adjusted (latency uncertainty %2.1f ms)\n', ...
blocksize/srate*1000);
end;
% process events
% --------------
fprintf('Pop_loadbci: importing events...\n');
counte = 1; % event counter
events(10000).latency = 0;
indexsource = strmatch('sourcetime', lower( allfields ), 'exact' );
sourcetime = getfield(bci, allfields{ indexsource });
for index = 1:length(indeximport)
tmpdata = getfield(bci, allfields{indeximport(index)});
tmpevent = find( diff(tmpdata) > 0);
tmpevent = tmpevent+1;
tmpcorresp = find(indexcorresp == indeximport(index));
for tmpi = tmpevent'
if ~isempty(tmpcorresp)
events(counte).type = allfields{ indexcorrespval(tmpcorresp) };
else
events(counte).type = allfields{ indeximport(index) };
end;
if adjust
baselatency = sourcetime(tmpi); % note that this is the first bin a block
realtmpi = tmpi+blocksize; % jump to the end of the block+1
if curlatency < baselatency, curlatency = curlatency+65536; end; % in ms
events(counte).latency = realtmpi+(curlatency-baselatency)/1000*srate;
% (curlatency-baselatency)/1000*srate
% there is still a potentially large error between baselatency <-> realtmpi
else
events(counte).latency = tmpi+(blocksize-1)/2;
end;
counte = counte+1;
end;
end;
EEG.data = bci.signal';
EEG.nbchan = size(EEG.data, 1);
EEG.pnts = size(EEG.data, 2);
EEG.trials = 1;
EEG.srate = srate;
EEG = eeg_checkset(EEG);
EEG.event = events(1:counte-1);
EEG = eeg_checkset( EEG, 'eventconsistency' );
EEG = pop_editeventvals( EEG, 'sort', { 'latency', [0] } );
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$ dsffd
% $$$
% $$$ % find electrode indices
% $$$ % ----------------------
% $$$ indices = [];
% $$$ for index = 1:length(colnames)
% $$$ if strcmp( colnames{index}(1:2), 'ch')
% $$$ indices = [indices index ];
% $$$ end;
% $$$ end;
% $$$
% $$$ EEG.data = tmpdata(indices,:);
% $$$ EEG.nbchan = size(EEG.data, 1);
% $$$ EEG.srate = srate;
% $$$ try
% $$$ eventindices = setdiff_bc(1:length(colnames), indices);
% $$$ ISIind = eventindices(3 + 9);
% $$$ eventindices(3 + [ 1 2 3 4 7 8 9 10 11 12]) = [];
% $$$ eventindices(1:3) = []; % suppress these event
% $$$
% $$$ % add the trial number
% $$$ % --------------------
% $$$ tmptrial = find( diff(tmpdata(ISIind, :)) ~= 0);
% $$$ tmptrial = tmptrial+1;
% $$$
% $$$ % process events
% $$$ % --------------
% $$$ fprintf('Pop_loadbci: importing events...\n');
% $$$ counte = 1; % event counter
% $$$ events(10000).latency = 0;
% $$$ for index = eventindices
% $$$ counttrial = 1;
% $$$ tmpevent = find( diff(tmpdata(index, :)) ~= 0);
% $$$ tmpevent = tmpevent+1;
% $$$ for tmpi = tmpevent
% $$$ if tmpdata(index, tmpi)
% $$$ events(counte).type = [ colnames{index} int2str(tmpdata(index, tmpi)) ];
% $$$ events(counte).latency = tmpi;
% $$$ %events(counte).value = tmpdata(index, tmpi);
% $$$ %while tmpi > tmptrial(counttrial) & counttrial < length(tmptrial)
% $$$ % counttrial = counttrial+1;
% $$$ %end;
% $$$ %events(counte).trial = counttrial;
% $$$ counte = counte+1;
% $$$ %if mod(counte, 100) == 0, fprintf('%d ', counte); end;
% $$$ end;
% $$$ end;
% $$$ end;
% $$$
% $$$ % add up or down events
% $$$ % ---------------------
% $$$ EEG = eeg_checkset(EEG);
% $$$ EEG.event = events(1:counte-1);
% $$$ EEG = pop_editeventvals( EEG, 'sort', { 'latency', [0] } );
% $$$ for index=1:length(EEG.event)
% $$$ if strcmp(EEG.event(index).type(1:6), 'Target')
% $$$ targetcode = str2num(EEG.event(index).type(end));
% $$$ if targetcode == 1
% $$$ EEG.event(index).type = 'toptarget';
% $$$ else
% $$$ EEG.event(index).type = 'bottomtarget';
% $$$ end;
% $$$ else
% $$$ if strcmp(EEG.event(index).type(1:6), 'Result')
% $$$ resultcode = str2num(EEG.event(index).type(end));
% $$$ if resultcode == 1
% $$$ EEG.event(index).type = 'topresp';
% $$$ else
% $$$ EEG.event(index).type = 'bottomresp';
% $$$ end;
% $$$ EEG.event(end+1).latency = EEG.event(index).latency;
% $$$ if (resultcode == targetcode)
% $$$ EEG.event(end).type = 'correct';
% $$$ else
% $$$ EEG.event(end).type = 'miss';
% $$$ end;
% $$$ end;
% $$$ end;
% $$$ end;
% $$$ EEG = pop_editeventvals( EEG, 'sort', { 'latency', [0] } );
% $$$ %EEG.data = tmpdata([72 73 75],:);
% $$$ catch, disp('Failed to import data events');
% $$$ end;
% $$$
% $$$ command = sprintf('EEG = pop_loadbci(''%s'', %f);',filename, srate);
% $$$ return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_fileio.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_fileio.m
| 7,131 |
utf_8
|
9330dd4ef5ede2f403e6e848748bfd57
|
% pop_fileio() - import data files into EEGLAB using FileIO
%
% Usage:
% >> OUTEEG = pop_fileio; % pop up window
% >> OUTEEG = pop_fileio( filename );
%
% Inputs:
% filename - [string] file name
%
% Optional inputs:
% 'channels' - [integer array] list of channel indices
% 'samples' - [min max] sample point limits for importing data.
% 'trials' - [min max] trial's limit for importing data.
% 'memorymapped' - ['on'|'off'] import memory mapped file (useful if
% encountering memory errors). Default is 'off'.
%
% Outputs:
% OUTEEG - EEGLAB data structure
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2008-
%
% Note: FILEIO toolbox must be installed.
% Copyright (C) 2008 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, command] = pop_fileio(filename, varargin);
EEG = [];
command = '';
if ~plugin_askinstall('Fileio', 'ft_read_data'), return; end;
if nargin < 1
% ask user
ButtonName = questdlg2('Do you want to import a file or a folder?', ...
'FILE-IO import', ...
'Folder', 'File', 'File');
if strcmpi(ButtonName, 'file')
[filename, filepath] = uigetfile('*.*', 'Choose a file or header file -- pop_fileio()');
drawnow;
if filename(1) == 0 return; end;
filename = fullfile(filepath, filename);
else
filename = uigetfile('*.*', 'Choose a folder -- pop_fileio()');
drawnow;
if filename(1) == 0 return; end;
end;
% open file to get infos
% ----------------------
eeglab_options;
mmoval = option_memmapdata;
disp('Reading data file header...');
dat = ft_read_header(filename);
uilist = { { 'style' 'text' 'String' 'Channel list (defaut all):' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'String' [ 'Data range (in sample points) (default all [1 ' int2str(dat.nSamples) '])' ] } ...
{ 'style' 'edit' 'string' '' } };
geom = { [3 1] [3 1] };
if dat.nTrials > 1
uilist{end+1} = { 'style' 'text' 'String' [ 'Trial range (default all [1 ' int2str(dat.nTrials) '])' ] };
uilist{end+1} = { 'style' 'edit' 'string' '' };
geom = { geom{:} [3 1] };
end;
uilist = { uilist{:} { 'style' 'checkbox' 'String' 'Import as memory mapped file (use in case of out of memory error)' 'value' option_memmapdata } };
geom = { geom{:} [1] };
result = inputgui( geom, uilist, 'pophelp(''pop_fileio'')', 'Load data using FILE-IO -- pop_fileio()');
if length(result) == 0 return; end;
options = {};
if length(result) == 3, result = { result{1:2} '' result{3}}; end;
if ~isempty(result{1}), options = { options{:} 'channels' eval( [ '[' result{1} ']' ] ) }; end;
if ~isempty(result{2}), options = { options{:} 'samples' eval( [ '[' result{2} ']' ] ) }; end;
if ~isempty(result{3}), options = { options{:} 'trials' eval( [ '[' result{3} ']' ] ) }; end;
if result{4}, options = { options{:} 'memorymapped' fastif(result{4}, 'on', 'off') }; end;
else
dat = ft_read_header(filename);
options = varargin;
end;
% decode imput parameters
% -----------------------
g = finputcheck( options, { 'samples' 'integer' [1 Inf] [];
'trials' 'integer' [1 Inf] [];
'channels' 'integer' [1 Inf] [];
'memorymapped' 'string' { 'on';'off' } 'off' }, 'pop_fileio');
if isstr(g), error(g); end;
% import data
% -----------
EEG = eeg_emptyset;
fprintf('Reading data ...\n');
dataopts = {};
if ~isempty(g.samples ), dataopts = { dataopts{:} 'begsample', g.samples(1), 'endsample', g.samples(2)}; end;
if ~isempty(g.trials ), dataopts = { dataopts{:} 'begtrial', g.trials(1), 'endtrial', g.trials(2)}; end;
if strcmpi(g.memorymapped, 'off')
if ~isempty(g.channels), dataopts = { dataopts{:} 'chanindx', g.channels }; end;
alldata = ft_read_data(filename, 'header', dat, dataopts{:});
else
% read memory mapped file
g.datadims = [ dat.nChans dat.nSamples dat.nTrials ];
disp('Importing as memory mapped array, this may take a while...');
if isempty(g.channels), g.channels = [1:g.datadims(1)]; end;
if ~isempty(g.samples ), g.datadims(2) = g.samples(2) - g.samples(1); end;
if ~isempty(g.trials ), g.datadims(3) = g.trials(2) - g.trials(1); end;
g.datadims(1) = length(g.channels);
alldata = mmo([], g.datadims);
for ic = 1:length(g.channels)
alldata(ic,:,:) = ft_read_data(filename, 'header', dat, dataopts{:}, 'chanindx', g.channels(ic));
end;
end;
% convert to seconds for sread
% ----------------------------
EEG.srate = dat.Fs;
EEG.nbchan = dat.nChans;
EEG.data = alldata;
EEG.setname = '';
EEG.comments = [ 'Original file: ' filename ];
EEG.xmin = -dat.nSamplesPre/EEG.srate;
EEG.trials = dat.nTrials;
EEG.pnts = dat.nSamples;
if isfield(dat, 'label') && ~isempty(dat.label)
EEG.chanlocs = struct('labels', dat.label);
end
% extract events
% --------------
disp('Reading events...');
try
event = ft_read_event(filename);
catch, disp(lasterr); event = []; end;
if ~isempty(event)
subsample = 0;
if ~isempty(g.samples), subsample = g.samples(1); end;
for index = 1:length(event)
offset = fastif(isempty(event(index).offset), 0, event(index).offset);
EEG.event(index).type = event(index).value;
EEG.event(index).value = event(index).type;
EEG.event(index).latency = event(index).sample+offset+subsample;
EEG.event(index).duration = event(index).duration;
if EEG.trials > 1
EEG.event(index).epoch = ceil(EEG.event(index).latency/EEG.pnts);
end;
end;
EEG = eeg_checkset(EEG, 'eventconsistency');
else
disp('Warning: no event found. Events might be embeded in a data channel.');
disp(' To extract events, use menu File > Import Event Info > From data channel');
end;
% convert data to single if necessary
% -----------------------------------
EEG = eeg_checkset(EEG,'makeur'); % Make EEG.urevent field
% history
% -------
if isempty(options)
command = sprintf('EEG = pop_fileio(''%s'');', filename);
else
command = sprintf('EEG = pop_fileio(''%s'', %s);', filename, vararg2str(options));
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_compareerps.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_compareerps.m
| 2,848 |
utf_8
|
d0e259f378ec39efae7121f2225f9cbf
|
% pop_compareerps() - Compare the (ERP) averages of two datasets.
%
% Usage:
% >> pop_compareerps( ALLEEG, datasetlist, chansubset, title);
% Inputs:
% ALLEEG - array of datasets
% datasetlist - list of datasets
% chansubset - vector of channel subset
% title - plot title
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeglab(), plottopo()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% 03-11-02 added empty ALLEEG check -ad
% 03-18-02 added channel subset -ad
% 03-18-02 added title -ad & sm
function com = pop_compareerps( ALLEEG, setlist, chansubset, plottitle);
com = '';
if nargin < 1
help pop_compareerps;
return;
end;
if isempty(ALLEEG)
error('pop_compareerps: cannot process empty sets of data');
end;
if exist('plottitle') ~= 1
plottitle = '';
end;
if nargin < 2
% which set to save
% -----------------
promptstr = { 'List of datasets to compare (ex: 1 3 4):' ...
'Channels subset to consider ([]=all):' ...
'Plot title ([]=automatic):' };
inistr = { '1' '' '' };
result = inputdlg2( promptstr, 'Compare dataset ERPs -- pop_compareerps()', 1, inistr, 'pop_compareerps');
if length(result) == 0 return; end;
setlist = eval( [ '[' result{1} ']' ] );
chansubset = eval( [ '[' result{2} ']' ] );
if isempty( chansubset ), chansubset = 1:ALLEEG(setlist(1)).nbchan; end;
plottitle = result{3};
if isempty(plottitle)
plottitle = [ 'Compare datasets number (blue=first; red=sec.)' int2str(setlist) ];
end;
figure;
end;
try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end;
tracing = [];
for setindex = setlist
tracing = [ tracing squeeze(mean(ALLEEG(setindex).data,3))];
end;
% save channel names
% ------------------
plottopo( tracing, ALLEEG(setlist(1)).chanlocs, ALLEEG(setlist(1)).pnts, [ALLEEG(setlist(1)).xmin ALLEEG(setlist(1)).xmax 0 0]*1000, plottitle, chansubset );
com = sprintf('figure; pop_compareerps( %s, [%s], [%s], ''%s'');', inputname(1), num2str(setlist), num2str(chansubset), plottitle);
return;
|
github
|
ZijingMao/baselineeegtest-master
|
importevent.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/importevent.m
| 16,193 |
utf_8
|
3c5abc8a8b32a3fe9ba00144fbaed59d
|
% importevent() - Import experimental events from data file or Matlab
% array into a structure.
%
% Usage: >> eventstruct = importevent( event, oldevent, srate);
% >> eventstruct = importevent( event, oldevent, srate, 'key1', 'value1', ...);
%
% Input:
% event - [ 'filename'|array ] Filename of a text file, or name of
% Matlab array in the global workspace containing an
% array of events in the folowing format: The first column of
% the cell array is the type of the event, the second the latency.
% The others are user-defined. The function can read
% either numeric or text entries in ascii files.
% oldevent - Old event structure. Used for aligning new events with old
% ones. Enter [] is no such structure exist.
% srate - Sampling rate of the underlying data. Event latencies are
% expressed in terms of latency in sample point with respect
% to the data.
%
% Optional file or array input:
% 'fields' - [Cell array] List of the name of each user-defined column,
% optionally followed by a description. Ex: { 'type', 'latency' }
% 'skipline' - [Interger] Number of header rows to skip in the text file
% 'timeunit' - [ latency unit rel. to seconds ]. Default unit is 1 = seconds.
% NaN indicates that the latencies are given in time points.
% 'delim' - [string] String of delimiting characters in the input file.
% Default is tab|space.
%
% Optional oldevent input:
% 'append' - ['yes'|'no'] 'yes' = Append events to the current events in
% the EEG dataset {default}: 'no' = Erase the previous events.
% 'indices' - {integer vector] Vector indicating the indices of the events to
% modify.
% 'align' - [num] Align the first event latency to the latency of existing
% event number (num), and check latency consistency.
% A value of 0 indicates that the first events of the pre-defined
% events and imported events will be aligned. A positive value (num)
% aligns the first event to the num-th pre-existing event.
% A negative value can also be used; then event number (-num)
% is aligned to the first pre-existing event. Default is 0.
% (NaN-> no alignment).
% 'optimmeas' - ['median'|'mean'] Uses either the median of the mean
% distance to align events. Default is 'mean'. Median is
% preferable if events are missing in the event file.
% 'optimalign' - ['on'|'off'] Optimize the sampling rate of the new events so
% they best align with old events. Default is 'on'.
%
% Outputs:
% eventstruct - Event structure containing imported events
%
% Example: >> eventstruct = importevent( 'event_values.txt', [], 256, ...
% 'fields', {'type', 'latency','condition' }, ...
% 'append', 'no', 'align', 0, 'timeunit', 1E-3 );
%
% This loads the ascii file 'event_values.txt' containing 3 columns
% (event_type, latency, and condition). Latencies in the file are
% in ms (1E-3). The first event latency is re-aligned with the
% beginning of the dataset ('align', 0). Any previous events
% are erased ('append', 'no').
%
% Author: Arnaud Delorme & Scott Makeig, CNL / Salk Institute, 2004
%
% See also: pop_importevent()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 2004, [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
%% REVISION HISTORY
%% function definition, input check
function event = importevent(event, oldevent, srate, varargin)
if nargin < 1
help importevent;
return;
end;
I = [];
% remove the event field
% ----------------------
if ~isempty(oldevent), allfields = fieldnames(oldevent);
else allfields = {}; end;
g = finputcheck( varargin, { 'fields' 'cell' [] {};
'skipline' 'integer' [0 Inf] 0;
'indices' 'integer' [1 Inf] [];
'append' 'string' {'yes';'no';'''yes''';'''no''' } 'yes';
'timeunit' 'real' [] 1;
'event' { 'cell';'real';'string' } [] [];
'align' 'integer' [] NaN;
'optimalign' 'string' { 'on';'off' } 'on';
'optimmeas' 'string' { 'median';'mean' } 'mean';
'delim' {'integer';'string'} [] char([9 32 44])}, 'importevent');
if isstr(g), error(g); end;
if ~isempty(g.indices), g.append = 'yes'; end;
g.delim = char(g.delim);
% call from pop_importevent
% -------------------------
if ~isempty(g.event)
event = g.event;
if ~isstr(event)
if size(event,2) > size(event,1), event = event'; end;
if iscell(event)
eventStr = cellfun(@ischar, event);
eventNum = cellfun(@isnumeric, event);
if all(eventStr(1,:)) && ~all(eventStr(:,1))
event = event';
end;
if all(eventNum(1,:)) && ~all(eventNum(:,1))
event = event';
end;
end;
end;
end;
g.event = event;
% determine latency for old event alignment
% -----------------------------------------
tmpalign = g.align;
g.align = [];
g.align.val = tmpalign;
if ~isnan(g.align.val)
if isempty(oldevent)
error('Setevent: no pre-existing event, cannot perform alignment');
end;
if ~isfield(oldevent, 'latency')
error('Setevent: pre-existing events do not have a latency field for re-alignment');
end;
switch g.append
case {'yes' '''yes'''}, disp('Setevent warning: cannot align and append events at the same time; disabling event alignment');
end;
if g.align.val < 0
g.align.event = oldevent(1).latency;
else
g.align.event = oldevent(g.align.val+1).latency;
end
g.align.nbevent = length(oldevent);
g.oldevents = oldevent;
g.align.txt = sprintf([ 'Check alignment between pre-existing (old) and loaded event' ...
' latencies:\nOld event latencies (10 first): %s ...\n' ], ...
int2str([ oldevent(1:min(10, length(oldevent))).latency ]));
else
g.oldevents = [];
end;
tmpfields = fieldnames(g);
event = oldevent;
%% scan all the fields of g
% ------------------------
for curfield = tmpfields'
if ~isempty(event), allfields = fieldnames(event);
else allfields = {}; end;
switch lower(curfield{1})
case {'append', 'fields', 'skipline', 'indices', 'timeunit', 'align', 'delim' }, ; % do nothing now
case 'event', % load an ascii file
switch g.append
case { '''no''' 'no' } % ''no'' for backward compatibility
if isstr(g.event) && ~exist(g.event), g.event = evalin('caller', g.event); end;
event = load_file_or_array( g.event, g.skipline, g.delim );
allfields = g.fields(1:min(length(g.fields), size(event,2)));
event = eeg_eventformat(event, 'struct', allfields);
% generate ori fields
% -------------------
if ~isnan(g.timeunit)
for index = 1:length(event)
event(index).init_index = index;
event(index).init_time = event(index).latency*g.timeunit;
end;
end;
event = recomputelatency( event, 1:length(event), srate, ...
g.timeunit, g.align, g.oldevents, g.optimalign, g.optimmeas);
case { '''yes''' 'yes' }
% match existing fields
% ---------------------
if isstr(g.event) && ~exist(g.event), g.event = evalin('caller', g.event); end;
tmparray = load_file_or_array( g.event, g.skipline, g.delim );
if isempty(g.indices) g.indices = [1:size(tmparray,1)] + length(event); end;
if length(g.indices) ~= size(tmparray,1)
error('Set error: number of row in file does not match the number of event given as input');
end;
% add field
% ---------
g.fields = getnewfields( g.fields, size(tmparray,2)-length(g.fields));
% add new values
% ---------------------
for eventfield = 1:size(tmparray,2)
event = setstruct( event, g.fields{eventfield}, g.indices, { tmparray{:,eventfield} });
end;
% generate ori fields
% -------------------
offset = length(event)-size(tmparray,1);
for index = 1:size(tmparray,1)
event(index+offset).init_index = index;
event(index+offset).init_time = event(index+offset).latency*g.timeunit;
end;
event = recomputelatency( event, g.indices, srate, g.timeunit, ...
g.align, g.oldevents, g.optimalign, g.optimmeas);
end;
end;
end;
if isempty(event) % usefull 0xNB empty structure
event = [];
end;
%% remove the events wit out-of-bound latencies
% --------------------------------------------
if isfield(event, 'latency')
try
res = cellfun('isempty', { event.latency });
res = find(res);
if ~isempty(res)
fprintf( 'importevent warning: %d/%d event(s) have invalid latencies and were removed\n', ...
length(res), length(event));
event( res ) = [];
end;
end;
end;
%% interpret the variable name
% ---------------------------
function array = load_file_or_array( varname, skipline, delim );
if isstr(varname) & exist(varname) == 2 % mean that it is a filename
% --------------------------
array = loadtxt( varname, 'skipline', skipline, 'delim', delim, 'blankcell', 'off' );
else
if ~iscell(varname)
array = mattocell(varname);
else
array = varname;
end;
end;
return;
%% update latency values
% ---------------------
function event = recomputelatency( event, indices, srate, timeunit, align, oldevents, optimalign, optimmeas)
% update time unit
% ----------------
if ~isfield(event, 'latency'),
if isfield(event, 'duration')
error('A duration field cannot be defined if a latency field has not been defined');
end;
return;
end;
if ~isnan(timeunit)
for index = indices
event(index).latency = event(index).latency*srate*timeunit;
if isfield(event, 'duration')
event(index).duration = event(index).duration*srate*timeunit;
end;
end;
end;
% alignment with old events
% -------------------------
if ~isnan( align.val )
if align.val >= 0, alignlatency = event(1).latency;
else alignlatency = event(-align.val+1).latency;
end;
for index = indices
event(index).latency = event(index).latency-alignlatency+align.event;
end;
if length(event) ~= align.nbevent
disp('Setevent warning: the number of pre-existing events do not correspond to the number of events');
disp(' that were read, so their latencies may have been wrongly re-aligned');
end;
fprintf(align.txt);
fprintf('New event latencies (10 first): %s ...\n', int2str(round([ event(1:min(10, length(event))).latency ])));
end;
if strcmpi(optimalign, 'on') & ~isempty(oldevents)
newlat = [ event.latency ];
oldlat = [ oldevents.latency ];
newlat = repmat(newlat, [length(oldlat) 1]);
oldlat = repmat(oldlat', [1 size(newlat,2)]);
if align.val >= 0
newlat = newlat-newlat(1);
oldlat = oldlat-oldlat(1+align.val);
else
newlat = newlat-newlat(1-align.val);
oldlat = oldlat-oldlat(1);
end;
try
newfactor = fminsearch('eventalign',1,[],newlat, oldlat, optimmeas);
catch
newfactor = fminsearch('eventalign',1,[],[],newlat, oldlat, optimmeas); % Octave
end;
fprintf('Best sampling rate ratio found is %1.7f. Below latencies after adjustment\n', newfactor);
if newfactor > 1.01 | newfactor < 0.99
disp('Difference is more than 1%, something is wrong; ignoring ratio');
newfactor = 1;
else
difference1 = eventalign( 1 , newlat, oldlat, optimmeas);
difference2 = eventalign( newfactor, newlat, oldlat, optimmeas);
fprintf('The average difference before correction was %f sample points\n', difference1);
fprintf('The average difference after correction is %f sample points\n', difference2);
end;
%diffarray = abs(newfactor*newlat-oldlat)';
%[allmins poss] = min(diffarray);
%figure; hist(allmins);
else
newfactor = 1;
end;
if ~isnan( align.val ) & newfactor ~= 1
if align.val >= 0
latfirstevent = event(1).latency;
else
latfirstevent = event(-align.val+1).latency;
end;
for index = setdiff_bc(indices, 1)
event(index).latency = round(event(index).latency-latfirstevent)*newfactor+latfirstevent;
end;
if ~isempty(oldevents)
fprintf('Old event latencies (10 first): %s ...\n', int2str(round([ oldevents(1:min(10, length(oldevents))).latency ])));
fprintf('New event latencies (10 first): %s ...\n', int2str(round([ event(1:min(10, length(event))).latency ])));
end;
else
% must add one (because first sample point has latency 0
% ------------------------------------------------------
if ~isnan(timeunit)
for index = indices
event(index).latency = round((event(index).latency+1)*1000*newfactor)/1000;
end;
end;
end;
%% create new field names
% ----------------------
function epochfield = getnewfields( epochfield, nbfields )
count = 1;
while nbfields > 0
if isempty( strmatch([ 'var' int2str(count) ], epochfield ) )
epochfield = { epochfield{:} [ 'var' int2str(count) ] };
nbfields = nbfields-1;
else count = count+1;
end;
end
return;
%%
% ----------------------
function var = setstruct( var, fieldname, indices, values )
if exist('indices') ~= 1, indices = 1:length(var); end
if ~isempty(values)
for index = 1:length(indices)
var = setfield(var, {indices(index)}, fieldname, values{index});
end
else
for index = 1:length(indices)
var = setfield(var, {indices(index)}, fieldname, '');
end
end
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_saveset.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_saveset.m
| 12,652 |
utf_8
|
f327353b0e7ee940640ebfd448f68f9d
|
% pop_saveset() - save one or more EEG dataset structures
%
% Usage:
% >> pop_saveset( EEG ); % use an interactive pop-up window
% >> EEG = pop_saveset( EEG, 'key', 'val', ...); % no pop-up
%
% Inputs:
% EEG - EEG dataset structure. May only contain one dataset.
%
% Optional inputs:
% 'filename' - [string] name of the file to save to
% 'filepath' - [string] path of the file to save to
% 'check' - ['on'|'off'] perform extended syntax check. Default 'off'.
% 'savemode' - ['resave'|'onefile'|'twofiles'] 'resave' resave the
% current dataset using the filename and path stored
% in the dataset; 'onefile' saves the full EEG
% structure in a Matlab '.set' file, 'twofiles' saves
% the structure without the data in a Matlab '.set' file
% and the transposed data in a binary float '.dat' file.
% By default the option from the eeg_options.m file is
% used.
% 'version' - ['6'|'7.3'] save Matlab file as version 6 or
% '7.3' (default; as defined in eeg_option file).
%
% Outputs:
% EEG - saved dataset (after extensive syntax checks)
% ALLEEG - saved datasets (after extensive syntax checks)
%
% Note: An individual dataset should be saved with a '.set' file extension
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: pop_loadset(), 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
function [EEG, com] = pop_saveset( EEG, varargin);
com = '';
if nargin < 1
help pop_saveset;
return;
end;
if isempty(EEG) , error('Cannot save empty datasets'); end;
% empty filename (resave file)
emptyfilename = 0;
if nargin > 1
if isempty(varargin{1}) && isempty(EEG.filename), emptyfilename = 1; end;
if strcmpi(varargin{1},'savemode')
if length(EEG) == 1
if isempty(EEG(1).filename), varargin{2} = ''; emptyfilename = 1; end;
else
if any(cellfun(@isempty, { EEG.filename }))
error('Cannot resave files who have not been saved previously');
end;
end;
end;
end;
if nargin < 2 || emptyfilename
if length(EEG) >1, error('For reasons of consistency, this function does not save multiple datasets any more'); end;
% pop up window to ask for file
[filename, filepath] = uiputfile2('*.set', 'Save dataset with .set extension -- pop_saveset()');
if ~isstr(filename), return; end;
drawnow;
options = { 'filename' filename 'filepath' filepath };
else
% account for old calling format
% ------------------------------
if isempty(strmatch( lower(varargin{1}), { 'filename' 'filepath' 'savemode' 'check' }))
options = { 'filename' varargin{1} };
if nargin > 2
options = { options{:} 'filepath' varargin{2} };
end;
else
options = varargin;
end;
end;
% decode input parameters
% -----------------------
eeglab_options;
defaultSave = fastif(option_saveversion6, '6', '7.3');
g = finputcheck(options, { 'filename' 'string' [] '';
'filepath' 'string' [] '';
'version' 'string' { '6','7.3' } defaultSave;
'check' 'string' { 'on','off' } 'off';
'savemode' 'string' { 'resave','onefile','twofiles','' } '' });
if isstr(g), error(g); end;
% current filename without the .set
% ---------------------------------
if emptyfilename == 1, g.savemode = ''; end;
[g.filepath filenamenoext ext] = fileparts( fullfile(g.filepath, g.filename) ); ext = '.set';
g.filename = [ filenamenoext ext ];
% performing extended syntax check
% --------------------------------
if strcmpi(g.check, 'on')
fprintf('Pop_saveset: Performing extended dataset syntax check...\n');
EEG = eeg_checkset(EEG, 'eventconsistency');
EEG = eeg_checkset(EEG);
else
EEG = eeg_checkset(EEG);
end
% check for change in saving mode
% -------------------------------
if length(EEG) == 1
if strcmpi(g.savemode, 'resave') && isfield(EEG, 'datfile') && ~option_savetwofiles
disp('Note that your memory options for saving datasets does not correspond')
disp('to the format of the datasets on disk (ignoring memory options)')
% $$$ but = questdlg2(strvcat('This dataset has an associated ''.dat'' file, but since you have', ...
% $$$ 'changed of saving mode, all the data will now be saved within the', ...
% $$$ 'Matlab file and the ''.dat'' file will be deleted.', ...
% $$$ '(Note: Just press ''No'' if you do not know what you are doing)'), ...
% $$$ 'Warning: saving mode changed', 'Cancel', 'No, save as before', 'Yes, do it', 'Yes, do it');
% $$$ switch but
% $$$ case 'Cancel', return;
% $$$ case 'No, save as before', % nothing
% $$$ case 'Yes, do it', g.savemode = 'onefile';
% $$$ end;
% $$$ g.filename = EEG.filename;
% $$$ g.filepath = EEG.filepath;
elseif strcmpi(g.savemode, 'resave') && ~isfield(EEG, 'datfile') && option_savetwofiles
disp('Note that your memory options for saving datasets does not correspond')
disp('to the format of the datasets on disk (ignoring memory options)')
% $$$ but = questdlg2(strvcat('This dataset does not have yet an associated ''.dat'' file, but since you have', ...
% $$$ 'changed of saving mode, all the data will now be saved within the ''.dat''', ...
% $$$ 'file and not in the Matlab file (as it is currently the case).', ...
% $$$ '(Note: Just press ''No'' if you do not know what you are doing)'), ...
% $$$ 'Warning: saving mode changed', 'Cancel', 'No, save as before', 'Yes, do it', 'Yes, do it');
% $$$ switch but
% $$$ case 'Cancel', return;
% $$$ case 'No, save as before', % nothing
% $$$ case 'Yes, do it', g.savemode = 'twofiles';
% $$$ end;
% $$$ g.filename = EEG.filename;
% $$$ g.filepath = EEG.filepath;
end;
end;
% default saving otion
% --------------------
save_as_dat_file = 0;
data_on_disk = 0;
if strcmpi(g.savemode, 'resave')
% process multiple datasets
% -------------------------
if length(EEG) > 1
for index = 1:length(EEG)
pop_saveset(EEG(index), 'savemode', 'resave');
EEG(index).saved = 'yes';
end;
com = sprintf('%s = pop_saveset( %s, %s);', inputname(1), inputname(1), vararg2str(options));
return;
end;
if strcmpi( EEG.saved, 'yes'), disp('Dataset has not been modified; No need to resave it.'); return; end;
g.filename = EEG.filename;
g.filepath = EEG.filepath;
if isfield(EEG, 'datfile')
if ~isempty(EEG.datfile)
save_as_dat_file = 1;
end;
end;
if isstr(EEG.data) & ~save_as_dat_file % data in .set file
TMP = pop_loadset(EEG.filename, EEG.filepath);
EEG.data = TMP.data;
data_on_disk = 1;
end;
else
if length(EEG) >1, error('For reasons of consistency, this function does not save multiple datasets any more'); end;
if ~strcmpi(EEG.filename, g.filename) | ~strcmpi(EEG.filepath, g.filepath)
EEG.datfile = '';
end;
EEG.filename = g.filename;
EEG.filepath = g.filepath;
if isempty(g.savemode)
if option_savematlab, g.savemode = 'onefile';
else g.savemode = 'twofiles';
end;
end;
if strcmpi(g.savemode, 'twofiles')
save_as_dat_file = 1;
EEG.datfile = [ filenamenoext '.fdt' ];
end;
end;
% Saving data as float and Matlab
% -------------------------------
tmpica = EEG.icaact;
EEG.icaact = [];
if ~isstr(EEG.data)
if ~strcmpi(class(EEG.data), 'memmapdata') && ~strcmpi(class(EEG.data), 'mmo') && ~strcmpi(class(EEG.data), 'single')
tmpdata = single(reshape(EEG.data, EEG.nbchan, EEG.pnts*EEG.trials));
else
tmpdata = EEG.data;
end;
no_resave_dat = 'no';
else
no_resave_dat = 'yes';
end;
v = version;
try,
fprintf('Saving dataset...\n');
EEG.saved = 'yes';
if save_as_dat_file
if ~isstr(EEG.data)
EEG.data = EEG.datfile;
tmpdata = floatwrite( tmpdata, fullfile(EEG.filepath, EEG.data), 'ieee-le');
end;
else
if isfield(EEG, 'datfile')
if ~isempty(EEG.datfile)
if exist(fullfile(EEG.filepath, EEG.datfile))
try,
delete(fullfile(EEG.filepath, EEG.datfile));
disp('Deleting .dat/.fdt file on disk (all data is within the Matlab file)');
catch, end;
end;
end;
EEG.datfile = [];
end;
end;
try
if strcmpi(g.version, '6') save(fullfile(EEG.filepath, EEG.filename), '-v6', '-mat', 'EEG');
else save(fullfile(EEG.filepath, EEG.filename), '-v7.3', '-mat', 'EEG');
end;
catch
save(fullfile(EEG.filepath, EEG.filename), '-mat', 'EEG');
end;
if save_as_dat_file & strcmpi( no_resave_dat, 'no' )
EEG.data = tmpdata;
end;
% save ICA activities
% -------------------
% icafile = fullfile(EEG.filepath, [EEG.filename(1:end-4) '.icafdt' ]);
% if isempty(EEG.icaweights) & exist(icafile)
% disp('ICA activation file found on disk, but no more ICA activities. Deleting file.');
% delete(icafile);
% end;
% if ~option_saveica & exist(icafile)
% disp('Options indicate not to save ICA activations. Deleting ICA activation file.');
% delete(icafile);
% end;
% if option_saveica & ~isempty(EEG.icaweights)
% if ~exist('tmpdata')
% TMP = eeg_checkset(EEG, 'loaddata');
% tmpdata = TMP.data;
% end;
% if isempty(tmpica)
% tmpica2 = (EEG.icaweights*EEG.icasphere)*tmpdata(EEG.icachansind,:);
% else tmpica2 = tmpica;
% end;
% tmpica2 = reshape(tmpica2, size(tmpica2,1), size(tmpica2,2)*size(tmpica2,3));
% floatwrite( tmpica2, icafile, 'ieee-le');
% clear tmpica2;
% end;
catch,
rethrow(lasterror);
end;
% try to delete old .fdt or .dat files
% ------------------------------------
tmpfilename = fullfile(EEG.filepath, [ filenamenoext '.dat' ]);
if exist(tmpfilename) == 2
disp('Deleting old .dat file format detected on disk (now replaced by .fdt file)');
try,
delete(tmpfilename);
disp('Delete sucessfull.');
catch, disp('Error while attempting to remove file');
end;
end;
if save_as_dat_file == 0
tmpfilename = fullfile(EEG.filepath, [ filenamenoext '.fdt' ]);
if exist(tmpfilename) == 2
disp('Old .fdt file detected on disk, deleting file the Matlab file contains all data...');
try,
delete(tmpfilename);
disp('Delete sucessfull.');
catch, disp('Error while attempting to remove file');
end;
end;
end;
% recovering variables
% --------------------
EEG.icaact = tmpica;
if data_on_disk
EEG.data = 'in set file';
end;
if isnumeric(EEG.data) && v(1) < 7
EEG.data = double(reshape(tmpdata, EEG.nbchan, EEG.pnts, EEG.trials));
end;
EEG.saved = 'justloaded';
com = sprintf('%s = pop_saveset( %s, %s);', inputname(1), inputname(1), vararg2str(options));
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
|
ZijingMao/baselineeegtest-master
|
eeg_pv.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_pv.m
| 8,193 |
utf_8
|
23a0d260095460fdd46f49f5060dcf52
|
% eeg_pv() - Compute EEG.data 'percent variance ' (pv) of the whole EEG data versus the projections
% of specified components.
% Can omit specified components and channels from the computation. Can draw a plot
% of the scalp distribution of pv, or progressively compute the pv for comps
% 1:k, where k = 1 -> the total number of components. Note: pv's of spatially
% non-orthogonal independent components may not add to 100%, and individual component
% pv could be < 0%.
% Usage:
% >> [pv] = eeg_pv(EEG,comps);
% >> [pv,pvs,vars] = eeg_pv(EEG,comps,artcomps,omitchans,fraction,'plot');
% Inputs:
% EEG - EEGLAB dataset. Must have icaweights, icasphere, icawinv, icaact.
% comps - vector of component indices to sum {default|[] -> progressive mode}
% In progressive mode, comps is first [1], then [1 2], etc. up to
% [1:size(EEG.icaweights,2)] (all components); here, the plot shows pv.
% artcomps - vector of artifact component indices to remove from data before
% computing pv {default|[]: none}
% omitchans - channels to omit from the computation (e.g. off-head, etc) {default|[]: none}
% fraction - (0<real<=1) fraction of the data to randomly select {default|[]: 1=all}
% 'plot' - Plot scalp map of channel pvs. {default: Plot only if no output arguments}
%
% Outputs:
% pv - (real) percent total variance accounted for by the summed back-projection of
% the requested components. If comps is [], a vector of pvs for the sum of
% components 1:k (k=1:ncomps).
% pvs - (real vector) percent variance accounted for by the summed back-projection of
% the requested components to each data channel. If comps is [], a matrix of
% pvs (as for pv above).
% vars - variances of the requested channels
%
% Fields:
% Assumes existence of the following EEG fields: EEG.data, EEG.pnts, EEG.nbchan, EEG.trials,
% EEG.icaact, EEG.icaweights, EEG.icasphere, EEG.icawinv, and for plot, EEG.chanlocs
%
% See also: eeg_pvaf()
%
% Author: from eeg_pvaf(), Scott Makeig, SCCN/INC/UCSD, 02/04/05
function [pv,pvs,pvall] = eeg_pv(EEG,comps,artcomps,omitchans,fraction,plotflag)
if nargin < 1 | nargin > 6
help eeg_pv
return
end
numcomps = size(EEG.icaact,1);
plotit = 0;
if nargin>5 | nargout < 1
plotit = 1;
end
if nargin<5 | isempty(fraction)
fraction = 1;
end
if fraction>1
fprintf('eeg_pv(): considering all the data.\n');
fraction=1;
end
if round(fraction*EEG.pnts*EEG.trials)<1
error('fraction of data specified too small.')
return
end
if nargin<4 | isempty(omitchans)
omitchans = [];
end
if nargin<3|isempty(artcomps)
artcomps=[];
end
numchans = EEG.nbchan;
chans = 1:numchans;
if ~isempty(omitchans)
if max(omitchans)>numchans
help eeg_pv
error('at least one channel to omit > number of channels in data');
end
if min(omitchans)<1
help eeg_pv
error('channel numbers to omit must be > 0');
end
chans(omitchans) = [];
end
progressive = 0; % by default, progressive mode is off
if nargin < 2 | isempty(comps)|comps==0
comps = [];
progressive = 1; % turn progressive mode on
end
if isempty(EEG.icaweights)
help eeg_pv
return
end
if isempty(EEG.icasphere)
help eeg_pv
return
end
if isempty(EEG.icawinv)
EEG.icawinv = pinv(EEG.icaweights*EEG.icasphere);
end
if isempty(EEG.icaact)
help eeg_pv
fprintf('EEG.icaact not present.\n');
% EEG.icaact = EEG.icaweights*EEG.icasphere*EEG.data; % remake it like this
end
if max(comps) > size(EEG.icawinv,1)
help eeg_pv
fprintf('Only %d components in this dataset. Cannot project component %d.\n',numcomps,max(comps));
error('bad comps input');
end
if ~isempty(artcomps) & max(artcomps) > numcomps
help eeg_pv
fprintf('Only %d components in this dataset. Cannot project artcomp %d.\n',numcomps,max(artcomps));
error('bad artcomps input')
end
npts = EEG.trials*EEG.pnts;
allcomps = 1:numcomps;
if progressive
fprintf('Considering components up to: ');
cum_pv = zeros(1,numcomps);
cum_pvs = zeros(numcomps,numchans);
end
for comp = 1:numcomps %%%%%%%%%%%%%%% progressive mode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if progressive
comps = allcomps(1:comp); % summing components 1 to current comp
fprintf('%d ',comp)
end
if ~isempty(artcomps)
[a b c] = intersect_bc(artcomps,comps);
if ~isempty(a)
if ~progressive
if length(a)>1
fprintf('eeg_pv(): not back-projecting %d comps already in the artcomps.\n',length(c));
else
fprintf('eeg_pv(): not back-projecting comp %d already in the artcomps.\n',comps(c));
end
end
comps(c) = [];
end
end
if ~isempty(artcomps) & min([comps artcomps]) < 1
error('comps and artcomps must contain component indices');
end
%
%%%%%%%%%%%%%%%%%%%%%%%% compute variance accounted for by specified components %%%%%%%%%%%%%
%
if ~progressive | comp == 1 % pare out omitchans and artcomps from EEG.data
if ~isempty(artcomps)
EEG.data = EEG.data(chans,:) - EEG.icawinv(chans,artcomps)*EEG.icaact(artcomps,:);
else
EEG.data = EEG.data(chans,:);
end
nsel = round(fraction*npts);
varpts = randperm(npts);
varwts = ones(size(varpts));
if nsel<npts
varwts(varpts(nsel+1:npts)) = 0;
end
pvall = var(EEG.data(:,:)',varwts);
end
chans
comps
size(EEG.icawinv(chans,comps))
size(EEG.icaact(comps,:)')
pvcomp = var((EEG.icawinv(chans,comps)*EEG.icaact(comps,:))', varwts);
%
%%%%%%%%%%%%%%%%%%%%%%%% compute percent variance %%%%%%%%%%%%%%%
%
pvs = pvcomp ./ pvall;
pvs = 100*pvs;
pv = sum(pvcomp) ./ sum(pvall);
pv = 100*pv;
if ~progressive
break
else
cum_pv(comp) = pv;
cum_pvs(comp,:) = pvs;
end
end %%%%%%%%%%%%%% end progressive forloop %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if progressive % output accumulated results
fprintf('\n');
pv = cum_pv;
pvs = cum_pvs;
if plotit
plot(1:numcomps,pv);
xl = xlabel('Components Included (1:n)');
yl = ylabel('Percent Variance Accounted For (pv)');
set(xl,'fontsize',15);
set(yl,'fontsize',15);
set(gca,'fontsize',14);
end
elseif plotit
%
%%%%%%%%%%%%%%%%%%%%%%%% plot the scalp distribtion of pv %%%%%%%%%%%%%
%
if isfield(EEG,'chanlocs')
chanlocs = EEG.chanlocs;
if ~isempty(omitchans)
chanlocs(omitchans) = [];
end
topoplot(pvs',chanlocs); % plot pv here
if length(comps)>5 % add text legend
if length(artcomps)>3
tlstr=sprintf('Pvaf by %d comps in data minus %d comps',length(comps),length(artcomps));
elseif isempty(artcomps)
tlstr=sprintf('Pvaf by %d comps in data',length(comps));
elseif length(artcomps)==1 % < 4 artcomps, list them
tlstr=sprintf('Pvaf by %d comps in data (less comp ',length(comps));
tlstr = [tlstr sprintf('%d ',artcomps) ')'];
else
tlstr=sprintf('Pvaf by %d comps in data (less comps ',length(comps));
tlstr = [tlstr sprintf('%d ',artcomps) ')'];
end
else % < 6 comps, list them
if length(comps)>1
tlstr=sprintf('Pvaf by comps ');
else
tlstr=sprintf('Pvaf by comp ');
end
if length(artcomps)>3
tlstr = ...
[tlstr sprintf('%d ',comps) sprintf('in data minus %d comps',length(comps),length(artcomps))];
else
if isempty(artcomps)
tlstr = [tlstr sprintf('%d ',comps) 'in data'];
elseif length(artcomps)==1
tlstr = [tlstr sprintf('%d ',comps) 'in data (less comp '];
tlstr = [tlstr int2str(artcomps) ')'];
else
tlstr = [tlstr sprintf('%d ',comps) 'in data (less comps '];
tlstr = [tlstr sprintf('%d ',artcomps) ')'];
end
end
end
tl=title(tlstr);
if max(pvs)>100,
maxc=max(pvs)
else
maxc=100;
end;
pvstr=sprintf('Total pv: %3.1f%%',pv);
tx=text(-0.9,-0.6,pvstr);
caxis([-100 100]);
cb=cbar('vert',33:64,[0 100]); % color bar showing >0 (green->red) only
else
fprintf('EEG.chanlocs not found - not plotting scalp pv\n');
end
end % plotit
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_epoch2continuous.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_epoch2continuous.m
| 1,716 |
utf_8
|
79ffa71e29359c2ca1a0f21c2caf95cf
|
% eeg_epoch2continuous() - convert epoched dataset to continuous dataset
% with data epochs separated by boundary events.
% Usage:
% >> EEGOUT = eeg_epoch2continuous(EEGIN);
%
% Inputs:
% EEGIN - a loaded epoched EEG dataset structure.
%
% Inputs:
% EEGOUT - a continuous EEG dataset structure.
%
% Authors: Arnaud Delorme, SCCN, INC, UCSD, January, 2012
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 2012, [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_epoch2continuous(EEG)
if nargin < 1
help eeg_epoch2continuous;
return;
end;
EEG.data = reshape(EEG.data, size(EEG.data,1), size(EEG.data,2)*size(EEG.data,3));
for index = 1:EEG.trials-1
EEG.event(end+1).type = 'boundary';
EEG.event(end ).latency = index*EEG.pnts-0.5;
EEG.event(end ).duration = NaN;
end;
EEG.pnts = size(EEG.data,2);
EEG.trials = 1;
if ~isempty(EEG.event) && isfield(EEG.event, 'epoch')
EEG.event = rmfield(EEG.event, 'epoch');
end;
EEG = eeg_checkset(EEG);
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_interp.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_interp.m
| 14,003 |
utf_8
|
03c4611ad200bccfeeffd29ef6682a23
|
% eeg_interp() - interpolate data channels
%
% Usage: EEGOUT = eeg_interp(EEG, badchans, method);
%
% Inputs:
% EEG - EEGLAB dataset
% badchans - [integer array] indices of channels to interpolate.
% For instance, these channels might be bad.
% [chanlocs structure] channel location structure containing
% either locations of channels to interpolate or a full
% channel structure (missing channels in the current
% dataset are interpolated).
% method - [string] method used for interpolation (default is 'spherical').
% 'invdist'/'v4' uses inverse distance on the scalp
% 'spherical' uses superfast spherical interpolation.
% 'spacetime' uses griddata3 to interpolate both in space
% and time (very slow and cannot be interupted).
% Output:
% EEGOUT - data set with bad electrode data replaced by
% interpolated data
%
% Author: Arnaud Delorme, CERCO, CNRS, Mai 2006-
% Copyright (C) Arnaud Delorme, CERCO, 2006, [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_interp(ORIEEG, bad_elec, method)
if nargin < 2
help eeg_interp;
return;
end;
EEG = ORIEEG;
if nargin < 3
disp('Using spherical interpolation');
method = 'spherical';
end;
% check channel structure
tmplocs = ORIEEG.chanlocs;
if isempty(tmplocs) || isempty([tmplocs.X])
error('Interpolation require channel location');
end;
if isstruct(bad_elec)
% add missing channels in interpolation structure
% -----------------------------------------------
lab1 = { bad_elec.labels };
tmpchanlocs = EEG.chanlocs;
lab2 = { tmpchanlocs.labels };
[tmp tmpchan] = setdiff_bc( lab2, lab1);
tmpchan = sort(tmpchan);
if ~isempty(tmpchan)
newchanlocs = [];
fields = fieldnames(bad_elec);
for index = 1:length(fields)
if isfield(bad_elec, fields{index})
for cind = 1:length(tmpchan)
fieldval = getfield( EEG.chanlocs, { tmpchan(cind) }, fields{index});
newchanlocs = setfield(newchanlocs, { cind }, fields{index}, fieldval);
end;
end;
end;
newchanlocs(end+1:end+length(bad_elec)) = bad_elec;
bad_elec = newchanlocs;
end;
if length(EEG.chanlocs) == length(bad_elec), return; end;
lab1 = { bad_elec.labels };
tmpchanlocs = EEG.chanlocs;
lab2 = { tmpchanlocs.labels };
[tmp badchans] = setdiff_bc( lab1, lab2);
fprintf('Interpolating %d channels...\n', length(badchans));
if length(badchans) == 0, return; end;
goodchans = sort(setdiff(1:length(bad_elec), badchans));
% re-order good channels
% ----------------------
[tmp1 tmp2 neworder] = intersect_bc( lab1, lab2 );
[tmp1 ordertmp2] = sort(tmp2);
neworder = neworder(ordertmp2);
EEG.data = EEG.data(neworder, :, :);
% looking at channels for ICA
% ---------------------------
%[tmp sorti] = sort(neworder);
%{ EEG.chanlocs(EEG.icachansind).labels; bad_elec(goodchans(sorti(EEG.icachansind))).labels }
% update EEG dataset (add blank channels)
% ---------------------------------------
if ~isempty(EEG.icasphere)
[tmp sorti] = sort(neworder);
EEG.icachansind = sorti(EEG.icachansind);
EEG.icachansind = goodchans(EEG.icachansind);
EEG.chaninfo.icachansind = EEG.icachansind;
% TESTING SORTING
%icachansind = [ 3 4 5 7 8]
%data = round(rand(8,10)*10)
%neworder = shuffle(1:8)
%data2 = data(neworder,:)
%icachansind2 = sorti(icachansind)
%data(icachansind,:)
%data2(icachansind2,:)
end;
% { EEG.chanlocs(neworder).labels; bad_elec(sort(goodchans)).labels }
%tmpdata = zeros(length(bad_elec), size(EEG.data,2), size(EEG.data,3));
%tmpdata(goodchans, :, :) = EEG.data;
% looking at the data
% -------------------
%tmp1 = mattocell(EEG.data(sorti,1));
%tmp2 = mattocell(tmpdata(goodchans,1));
%{ EEG.chanlocs.labels; bad_elec(goodchans).labels; tmp1{:}; tmp2{:} }
%EEG.data = tmpdata;
EEG.chanlocs = bad_elec;
else
badchans = bad_elec;
goodchans = setdiff_bc(1:EEG.nbchan, badchans);
oldelocs = EEG.chanlocs;
EEG = pop_select(EEG, 'nochannel', badchans);
EEG.chanlocs = oldelocs;
disp('Interpolating missing channels...');
end;
% find non-empty good channels
% ----------------------------
origoodchans = goodchans;
chanlocs = EEG.chanlocs;
nonemptychans = find(~cellfun('isempty', { chanlocs.theta }));
[tmp indgood ] = intersect_bc(goodchans, nonemptychans);
goodchans = goodchans( sort(indgood) );
datachans = getdatachans(goodchans,badchans);
badchans = intersect_bc(badchans, nonemptychans);
if isempty(badchans), return; end;
% scan data points
% ----------------
if strcmpi(method, 'spherical')
% get theta, rad of electrodes
% ----------------------------
tmpgoodlocs = EEG.chanlocs(goodchans);
xelec = [ tmpgoodlocs.X ];
yelec = [ tmpgoodlocs.Y ];
zelec = [ tmpgoodlocs.Z ];
rad = sqrt(xelec.^2+yelec.^2+zelec.^2);
xelec = xelec./rad;
yelec = yelec./rad;
zelec = zelec./rad;
tmpbadlocs = EEG.chanlocs(badchans);
xbad = [ tmpbadlocs.X ];
ybad = [ tmpbadlocs.Y ];
zbad = [ tmpbadlocs.Z ];
rad = sqrt(xbad.^2+ybad.^2+zbad.^2);
xbad = xbad./rad;
ybad = ybad./rad;
zbad = zbad./rad;
EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts*EEG.trials);
%[tmp1 tmp2 tmp3 tmpchans] = spheric_spline_old( xelec, yelec, zelec, EEG.data(goodchans,1));
%max(tmpchans(:,1)), std(tmpchans(:,1)),
%[tmp1 tmp2 tmp3 EEG.data(badchans,:)] = spheric_spline( xelec, yelec, zelec, xbad, ybad, zbad, EEG.data(goodchans,:));
[tmp1 tmp2 tmp3 badchansdata] = spheric_spline( xelec, yelec, zelec, xbad, ybad, zbad, EEG.data(datachans,:));
%max(EEG.data(goodchans,1)), std(EEG.data(goodchans,1))
%max(EEG.data(badchans,1)), std(EEG.data(badchans,1))
EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts, EEG.trials);
elseif strcmpi(method, 'spacetime') % 3D interpolation, works but x10 times slower
disp('Warning: if processing epoch data, epoch boundary are ignored...');
disp('3-D interpolation, this can take a long (long) time...');
tmpgoodlocs = EEG.chanlocs(goodchans);
tmpbadlocs = EEG.chanlocs(badchans);
[xbad ,ybad] = pol2cart([tmpbadlocs.theta],[tmpbadlocs.radius]);
[xgood,ygood] = pol2cart([tmpgoodlocs.theta],[tmpgoodlocs.radius]);
pnts = size(EEG.data,2)*size(EEG.data,3);
zgood = [1:pnts];
zgood = repmat(zgood, [length(xgood) 1]);
zgood = reshape(zgood,prod(size(zgood)),1);
xgood = repmat(xgood, [1 pnts]); xgood = reshape(xgood,prod(size(xgood)),1);
ygood = repmat(ygood, [1 pnts]); ygood = reshape(ygood,prod(size(ygood)),1);
tmpdata = reshape(EEG.data, prod(size(EEG.data)),1);
zbad = 1:pnts;
zbad = repmat(zbad, [length(xbad) 1]);
zbad = reshape(zbad,prod(size(zbad)),1);
xbad = repmat(xbad, [1 pnts]); xbad = reshape(xbad,prod(size(xbad)),1);
ybad = repmat(ybad, [1 pnts]); ybad = reshape(ybad,prod(size(ybad)),1);
badchansdata = griddata3(ygood, xgood, zgood, tmpdata,...
ybad, xbad, zbad, 'nearest'); % interpolate data
else
% get theta, rad of electrodes
% ----------------------------
tmpchanlocs = EEG.chanlocs;
[xbad ,ybad] = pol2cart([tmpchanlocs( badchans).theta],[tmpchanlocs( badchans).radius]);
[xgood,ygood] = pol2cart([tmpchanlocs(goodchans).theta],[tmpchanlocs(goodchans).radius]);
fprintf('Points (/%d):', size(EEG.data,2)*size(EEG.data,3));
badchansdata = zeros(length(badchans), size(EEG.data,2)*size(EEG.data,3));
for t=1:(size(EEG.data,2)*size(EEG.data,3)) % scan data points
if mod(t,100) == 0, fprintf('%d ', t); end;
if mod(t,1000) == 0, fprintf('\n'); end;
%for c = 1:length(badchans)
% [h EEG.data(badchans(c),t)]= topoplot(EEG.data(goodchans,t),EEG.chanlocs(goodchans),'noplot', ...
% [EEG.chanlocs( badchans(c)).radius EEG.chanlocs( badchans(c)).theta]);
%end;
tmpdata = reshape(EEG.data, size(EEG.data,1), size(EEG.data,2)*size(EEG.data,3) );
if strcmpi(method, 'invdist'), method = 'v4'; end;
[Xi,Yi,badchansdata(:,t)] = griddata(ygood, xgood , double(tmpdata(datachans,t)'),...
ybad, xbad, method); % interpolate data
end
fprintf('\n');
end;
tmpdata = zeros(length(bad_elec), EEG.pnts, EEG.trials);
tmpdata(origoodchans, :,:) = EEG.data;
%if input data are epoched reshape badchansdata for Octave compatibility...
if length(size(tmpdata))==3
badchansdata = reshape(badchansdata,length(badchans),size(tmpdata,2),size(tmpdata,3));
end
tmpdata(badchans,:,:) = badchansdata;
EEG.data = tmpdata;
EEG.nbchan = size(EEG.data,1);
EEG = eeg_checkset(EEG);
% get data channels
% -----------------
function datachans = getdatachans(goodchans, badchans);
datachans = goodchans;
badchans = sort(badchans);
for index = length(badchans):-1:1
datachans(find(datachans > badchans(index))) = datachans(find(datachans > badchans(index)))-1;
end;
% -----------------
% spherical splines
% -----------------
function [x, y, z, Res] = spheric_spline_old( xelec, yelec, zelec, values);
SPHERERES = 20;
[x,y,z] = sphere(SPHERERES);
x(1:(length(x)-1)/2,:) = []; x = [ x(:)' ];
y(1:(length(y)-1)/2,:) = []; y = [ y(:)' ];
z(1:(length(z)-1)/2,:) = []; z = [ z(:)' ];
Gelec = computeg(xelec,yelec,zelec,xelec,yelec,zelec);
Gsph = computeg(x,y,z,xelec,yelec,zelec);
% equations are
% Gelec*C + C0 = Potential (C unknow)
% Sum(c_i) = 0
% so
% [c_1]
% * [c_2]
% [c_ ]
% xelec [c_n]
% [x x x x x] [potential_1]
% [x x x x x] [potential_ ]
% [x x x x x] = [potential_ ]
% [x x x x x] [potential_4]
% [1 1 1 1 1] [0]
% compute solution for parameters C
% ---------------------------------
meanvalues = mean(values);
values = values - meanvalues; % make mean zero
C = pinv([Gelec;ones(1,length(Gelec))]) * [values(:);0];
% apply results
% -------------
Res = zeros(1,size(Gsph,1));
for j = 1:size(Gsph,1)
Res(j) = sum(C .* Gsph(j,:)');
end
Res = Res + meanvalues;
Res = reshape(Res, length(x(:)),1);
function [xbad, ybad, zbad, allres] = spheric_spline( xelec, yelec, zelec, xbad, ybad, zbad, values);
newchans = length(xbad);
numpoints = size(values,2);
%SPHERERES = 20;
%[x,y,z] = sphere(SPHERERES);
%x(1:(length(x)-1)/2,:) = []; xbad = [ x(:)'];
%y(1:(length(x)-1)/2,:) = []; ybad = [ y(:)'];
%z(1:(length(x)-1)/2,:) = []; zbad = [ z(:)'];
Gelec = computeg(xelec,yelec,zelec,xelec,yelec,zelec);
Gsph = computeg(xbad,ybad,zbad,xelec,yelec,zelec);
% compute solution for parameters C
% ---------------------------------
meanvalues = mean(values);
values = values - repmat(meanvalues, [size(values,1) 1]); % make mean zero
values = [values;zeros(1,numpoints)];
C = pinv([Gelec;ones(1,length(Gelec))]) * values;
clear values;
allres = zeros(newchans, numpoints);
% apply results
% -------------
for j = 1:size(Gsph,1)
allres(j,:) = sum(C .* repmat(Gsph(j,:)', [1 size(C,2)]));
end
allres = allres + repmat(meanvalues, [size(allres,1) 1]);
% compute G function
% ------------------
function g = computeg(x,y,z,xelec,yelec,zelec)
unitmat = ones(length(x(:)),length(xelec));
EI = unitmat - sqrt((repmat(x(:),1,length(xelec)) - repmat(xelec,length(x(:)),1)).^2 +...
(repmat(y(:),1,length(xelec)) - repmat(yelec,length(x(:)),1)).^2 +...
(repmat(z(:),1,length(xelec)) - repmat(zelec,length(x(:)),1)).^2);
g = zeros(length(x(:)),length(xelec));
%dsafds
m = 4; % 3 is linear, 4 is best according to Perrin's curve
for n = 1:7
if ismatlab
L = legendre(n,EI);
else % Octave legendre function cannot process 2-D matrices
for icol = 1:size(EI,2)
tmpL = legendre(n,EI(:,icol));
if icol == 1, L = zeros([ size(tmpL) size(EI,2)]); end;
L(:,:,icol) = tmpL;
end;
end;
g = g + ((2*n+1)/(n^m*(n+1)^m))*squeeze(L(1,:,:));
end
g = g/(4*pi);
|
github
|
ZijingMao/baselineeegtest-master
|
pop_editeventvals.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_editeventvals.m
| 25,793 |
utf_8
|
de89caf08acbbceb7572ea96a994e688
|
% pop_editeventvals() - Edit events contained in an EEG dataset structure.
% If the dataset is the only input, a window pops up
% allowing the user to insert the relevant parameter values.
%
% Usage: >> EEGOUT = pop_editeventvals( EEG, 'key1', value1, ...
% 'key2', value2, ... );
% Input:
% EEG - EEG dataset
%
% Optional inputs:
% 'sort' - { field1 dir1 field2 dir2 } Sort events based on field1
% then on optional field2. Arg dir1 indicates the sort
% direction (0 = increasing, 1 = decreasing).
% 'changefield' - {num field value} Insert the given value into the specified
% field in event num. (Ex: {34 'latency' 320.4})
% 'changeevent' - {num value1 value2 value3 ...} Change the values of
% all fields in event num.
% 'add','append','insert' - {num value1 value2 value3 ...} Insert event
% before or at event num, and assign value to structure
% fields. Note that the latency field must be in second
% and will be converted to data sample. Note also that
% the index of the event is often irrelevant, as events
% will be automatically resorted by latencies.
% 'delete' - vector of indices of events to delete
%
% Outputs:
% EEGOUT - EEG dataset with the selected events only
%
% Ex: EEG = pop_editeventvals(EEG,'changefield', { 1 'type' 'target'});
% % set field type of event number 1 to 'target'
%
% Author: Arnaud Delorme & Hilit Serby, SCCN, UCSD, 15 March 2002
%
% See also: pop_selectevent(), pop_importevent()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 15 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
% 03-16-02 text interface editing -sm & ad
% 03-18-02 automatic latency switching display (epoch/continuous) - ad & sm
% 03-18-02 debug soring order - ad
% 03-18-02 put latencies in ms - ad, lf & sm
% 03-29-02 debug latencies in ms - ad & sm
% 04-02-02 debuging test - ad & sm
function [EEG, com] = pop_editeventvals(EEG, varargin);
com ='';
if nargin < 1
help pop_editeventvals;
return;
end;
if nargin >= 2 | isstr(EEG) % interpreting command from GUI or command line
if isstr(EEG) % GUI
gui = 1;
varargin = { EEG varargin{:} };
% user data
% ---------
userdata = get(gcf, 'userdata');
EEG = userdata{1};
oldcom = userdata{2};
allfields = fieldnames(EEG.event);
tmpind = strmatch('urevent', allfields);
allfields(tmpind) = [];
% current event
% -------------
objevent = findobj('parent', gcf, 'tag', 'numval');
valnum = str2num(get(objevent, 'string'));
shift = 0;
else % command line
gui = 0;
if isempty(EEG.event)
disp('Getevent: cannot deal with empty event structure');
return;
end;
allfields = fieldnames(EEG.event);
tmpind = strmatch('urevent', allfields);
allfields(tmpind) = [];
end;
% retinterpret inputs (fix BUG 454)
% --------------------------------
if ~gui
newvararg = {};
for indfield = 1:2:length(varargin)
com = varargin{ indfield };
tmpargs = varargin{ indfield+1 };
newvararg = { newvararg{:} com };
if any(strcmpi({'add','insert','append'},com))
evtind = tmpargs{1};
fields = fieldnames(EEG.event);
emptycells = cell(1,length(fields)-1);
newvararg = { newvararg{:}, { evtind emptycells{:} } };
if strcmpi(com, 'append'), evtind = evtind+1; end;
for ind = 2:length( tmpargs )
if ~strcmpi(fields{ind-1}, 'urevent')
newvararg = { newvararg{:},'changefield',{ evtind fields{ind-1} tmpargs{ind} } };
end;
end;
else
newvararg = { newvararg{:} tmpargs };
end;
end;
varargin = newvararg;
end;
% scan inputs
% -----------
for indfield = 1:2:length(varargin)
if length(varargin) >= indfield+1
tmparg = varargin{ indfield+1 };
end;
switch lower(varargin{indfield})
case 'goto', % ******************** GUI ONLY ***********************
% shift time
% ----------
shift = tmparg;
valnum = valnum + shift;
if valnum < 1, valnum = 1; end;
if valnum > length(EEG.event), valnum = length(EEG.event); end;
set(objevent, 'string', num2str(valnum,5));
% update fields
% -------------
for index = 1:length(allfields)
enable = 'on';
if isfield(EEG.event, 'type')
if strcmpi(EEG.event(valnum).type, 'boundary'), enable = 'off'; end;
end;
if strcmp( allfields{index}, 'latency') & ~isempty(EEG.event(valnum).latency)
if isfield(EEG.event, 'epoch')
value = eeg_point2lat( EEG.event(valnum).latency, EEG.event(valnum).epoch, ...
EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3);
else value = (EEG.event(valnum).latency-1)/EEG.srate+EEG.xmin;
end;
elseif strcmp( allfields{index}, 'duration') & ~isempty(EEG.event(valnum).duration)
if isfield(EEG.event, 'epoch')
value = EEG.event(valnum).duration/EEG.srate*1000; % milliseconds
else value = EEG.event(valnum).duration/EEG.srate; % seconds
end;
else
value = getfield( EEG.event(valnum), allfields{index});
end;
% update interface
% ----------------
tmpobj = findobj('parent', gcf, 'tag', allfields{index});
set(tmpobj, 'string', num2str(value,5), 'enable', enable);
end;
% update original
% ---------------
tmpobj = findobj('parent', gcf, 'tag', 'original');
if isfield(EEG.event, 'urevent') & EEG.event(valnum).urevent ~= valnum
set(tmpobj, 'string', [ 'originally ' int2str(EEG.event(valnum).urevent)], ...
'horizontalalignment', 'center');
else set(tmpobj, 'string', ' ');
end;
return; % NO NEED TO SAVE ANYTHING
case { 'append' 'insert' 'add' }, % **********************************************************
if gui
shift = tmparg; % shift is for adding before or after the event
% add epoch number if data epoch
% ------------------------------
tmpcell = cell(1,1+length(fieldnames(EEG.event)));
tmpcell{1} = valnum;
if EEG.trials > 1
indepoch = strmatch('epoch', fieldnames(EEG.event), 'exact');
if valnum > 1, tmpprevval = valnum-1;
else tmpprevval = valnum+1;
end;
if tmpprevval <= length(EEG.event)
tmpcell{indepoch+1} = EEG.event(tmpprevval).epoch;
end;
end;
% update commands
% ---------------
if shift
oldcom = { oldcom{:} 'append', tmpcell };
else
oldcom = { oldcom{:} 'insert', tmpcell };
end;
else
if strcmpi(lower(varargin{indfield}), 'append') % not 'add' for backward compatibility
shift = 1;
else shift = 0;
end;
valnum = tmparg{1};
end;
% find ur index
% -------------
valnum = valnum + shift;
if isfield(EEG.event, 'epoch'), curepoch = EEG.event(valnum).epoch; end;
if isfield(EEG, 'urevent') & isfield(EEG.event, 'urevent')
% find non empty urvalnum
urvalnum = [];
count = 0;
while isempty(urvalnum)
tmpindex = mod(valnum+count-1, length(EEG.event)+1)+1;
urvalnum = EEG.event(valnum+count).urevent;
count = count+1;
end;
if isfield(EEG.urevent, 'epoch'), urcurepoch = EEG.urevent(urvalnum).epoch; end;
urvalnum = urvalnum;
end;
% update urevents
% ---------------
if isfield(EEG, 'urevent') & isfield(EEG.event, 'urevent')
EEG.urevent(end+3) = EEG.urevent(end);
EEG.urevent(urvalnum+1:end-2) = EEG.urevent(urvalnum:end-3);
EEG.urevent(urvalnum) = EEG.urevent(end-1);
EEG.urevent = EEG.urevent(1:end-2);
if isfield(EEG.urevent, 'epoch'), EEG.urevent(urvalnum).epoch = urcurepoch; end;
end;
% update events
% -------------
EEG.event(end+3) = EEG.event(end);
EEG.event(valnum+1:end-2) = EEG.event(valnum:end-3);
EEG.event(valnum) = EEG.event(end-1);
EEG.event = EEG.event(1:end-2);
if isfield(EEG.event, 'epoch'), EEG.event(valnum).epoch = curepoch; end;
if isfield(EEG, 'urevent') & isfield(EEG.event, 'urevent')
EEG.event(valnum).urevent = urvalnum;
for index = valnum+1:length(EEG.event)
EEG.event(index).urevent = EEG.event(index).urevent+1;
end;
end;
% update type field
% -----------------
for tmpind = 1:length(allfields)
EEG.event = checkconsistency(EEG.event, valnum, allfields{tmpind});
end;
case 'delete', % **********************************************************
if ~gui
valnum = tmparg;
end
EEG.event(valnum) = [];
if gui,
valnum = min(valnum,length(EEG.event));
set(objevent, 'string', num2str(valnum));
% update commands
% ---------------
oldcom = { oldcom{:} 'delete', valnum };
end;
case { 'assign' 'changefield' }, % **********************************************************
if gui, % GUI case
field = tmparg;
objfield = findobj('parent', gcf, 'tag', field);
editval = get(objfield, 'string');
if ~isempty(editval) & ~isempty(str2num(editval)), editval = str2num(editval); end;
% update history
% --------------
oldcom = { oldcom{:},'changefield',{ valnum field editval }};
else % command line case
valnum = tmparg{1};
field = tmparg{2};
editval = tmparg{3};
end;
% latency and duration case
% -------------------------
if strcmp( field, 'latency') & ~isempty(editval)
if isfield(EEG.event, 'epoch')
editval = eeg_lat2point( editval, EEG.event(valnum).epoch, ...
EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3);
else editval = (editval- EEG.xmin)*EEG.srate+1;
end;
end;
if strcmp( field, 'duration') & ~isempty(editval)
if isfield(EEG.event, 'epoch')
editval = editval/1000*EEG.srate; % milliseconds
else editval = editval*EEG.srate; % seconds
end;
end;
% adapt to other formats
% ----------------------
EEG.event(valnum) = setfield(EEG.event(valnum), field, editval);
EEG.event = checkconsistency(EEG.event, valnum, field);
% update urevents
% ---------------
if isfield(EEG, 'urevent') & isfield(EEG.event, 'urevent')
urvalnum = EEG.event(valnum).urevent;
% latency case
% ------------
if strcmp( field, 'latency') & ~isempty(editval)
if isfield(EEG.urevent, 'epoch')
urepoch = EEG.urevent(urvalnum).epoch;
% find closest event latency
% --------------------------
if valnum<length(EEG.event)
if EEG.event(valnum+1).epoch == urepoch
urlatency = EEG.urevent(EEG.event(valnum+1).urevent).latency;
latency = EEG.event(valnum+1).latency;
end;
end;
if valnum>1
if EEG.event(valnum-1).epoch == urepoch
urlatency = EEG.urevent(EEG.event(valnum-1).urevent).latency;
latency = EEG.event(valnum-1).latency;
end;
end;
% update event
% ------------
if exist('urlatency') ~=1
disp('Urevent not updated: could not find other event in the epoch');
else
editval = urlatency - ( latency - editval ); % new latency value
end;
else
editval = eeg_urlatency(EEG.event, EEG.event(valnum).latency);
end;
elseif strcmp( field, 'latency') % empty editval
EEG.event(valnum).latency = NaN;
end;
% duration case
% ------------
if strcmp( field, 'duration') & ~isempty(editval)
if isfield(EEG.event, 'epoch')
editval = editval/1000*EEG.srate; % milliseconds -> point
else editval = editval*EEG.srate; % seconds -> point
end;
end;
EEG.urevent = setfield(EEG.urevent, {urvalnum}, field, editval);
end;
case 'sort', % **********************************************************
if gui % retrieve data
field1 = get(findobj('parent', gcf, 'tag', 'listbox1'), 'value');
field2 = get(findobj('parent', gcf, 'tag', 'listbox2'), 'value');
dir1 = get(findobj('parent', gcf, 'tag', 'order1'), 'value');
dir2 = get(findobj('parent', gcf, 'tag', 'order2'), 'value');
if field1 > 1, field1 = allfields{field1-1}; else return; end;
if field2 > 1, field1 = allfields{field2-1}; else field2 = []; end;
% update history
% --------------
oldcom = { oldcom{:},'sort',{ field1 dir1 field2 dir2 } };
else % command line
field1 = tmparg{1};
if length(tmparg) < 2, dir1 = 0;
else dir1 = tmparg{2};
end;
if length(tmparg) < 3, field2 = [];
else field2 = tmparg{3};
end;
if length(tmparg) < 4, dir2 = 0;
else dir2 = tmparg{4};
end;
end;
% Toby edit 11/16/2005 This section is scrambling the eeg.event
% fields. Requires further investigation.
if ~isempty(field2)
tmpevent = EEG.event;
if ~ischar(EEG.event(1).(field2))
tmparray = [ tmpevent.(field2) ];
else tmparray = { tmpevent.(field2) };
end
% Commented out 11/18/2005, Toby
% These lines were incorrectly sorting the event.latency field in
% units of time (seconds) relevant to each event's relative
% latency time as measured from the start of each epoch. It is
% possible that there are occasions when it is desirable to do
% so, but in the case of pop_mergset() it is not.
%if strcmp(field2, 'latency') & EEG.trials > 1
% tmparray = eeg_point2lat(tmparray, {EEG.event.epoch}, EEG.srate, [EEG.xmin EEG.xmax], 1);
%end;
[X I] = mysort( tmparray );
if dir2 == 1, I = I(end:-1:1); end;
events = EEG.event(I);
else
events = EEG.event;
end;
tmpevent = EEG.event;
if ~ischar(EEG.event(1).(field1))
tmparray = [ tmpevent.(field1) ];
else tmparray = { tmpevent.(field1) };
end
% Commented out 11/18/2005, Toby
%if strcmp( field1, 'latency') & EEG.trials > 1
% tmparray = eeg_point2lat(tmparray, {events.epoch}, EEG.srate, [EEG.xmin EEG.xmax], 1);
%end;
[X I] = mysort( tmparray );
if dir1 == 1, I = I(end:-1:1); end;
EEG.event = events(I);
if gui
% warn user
% ---------
warndlg2('Sorting done');
else
noeventcheck = 1; % otherwise infinite recursion with eeg_checkset
end;
end; % end switch
end; % end loop
% save userdata
% -------------
if gui
userdata{1} = EEG;
userdata{2} = oldcom;
set(gcf, 'userdata', userdata);
pop_editeventvals('goto', shift);
else
if ~exist('noeventcheck','var')
EEG = eeg_checkset(EEG, 'eventconsistency');
EEG = eeg_checkset(EEG, 'checkur');
end;
end;
return;
end;
% ----------------------
% graphic interface part
% ----------------------
if isempty(EEG.event)
disp('Getevent: cannot deal with empty event structure');
return;
end;
allfields = fieldnames(EEG.event);
tmpind = strmatch('urevent', allfields);
allfields(tmpind) = [];
if nargin<2
% add field values
% ----------------
geometry = { [2 0.5] };
tmpstr = sprintf('Edit event field values (currently %d events)',length(EEG.event));
uilist = { { 'Style', 'text', 'string', tmpstr, 'fontweight', 'bold' } ...
{ 'Style', 'pushbutton', 'string', 'Delete event', 'callback', 'pop_editeventvals(''delete'');' }};
for index = 1:length(allfields)
geometry = { geometry{:} [1 1 1 1] };
% input string
% ------------
if strcmp( allfields{index}, 'latency') | strcmp( allfields{index}, 'duration')
if EEG.trials > 1
inputstr = [ allfields{index} ' (ms)'];
else inputstr = [ allfields{index} ' (sec)'];
end;
else inputstr = allfields{index};
end;
% callback for displaying help
% ----------------------------
if index <= length( EEG.eventdescription )
tmptext = EEG.eventdescription{ index };
if ~isempty(tmptext)
if size(tmptext,1) > 15, stringtext = [ tmptext(1,1:15) '...' ];
else stringtext = tmptext(1,:);
end;
else stringtext = 'no-description'; tmptext = 'no-description';
end;
else stringtext = 'no-description'; tmptext = 'no-description';
end;
cbbutton = ['questdlg2(' vararg2str(tmptext) ...
',''Description of field ''''' allfields{index} ''''''', ''OK'', ''OK'');' ];
% create control
% --------------
cbedit = [ 'pop_editeventvals(''assign'', ''' allfields{index} ''');' ];
uilist = { uilist{:}, { }, ...
{ 'Style', 'pushbutton', 'string', inputstr, 'callback',cbbutton }, ...
{ 'Style', 'edit', 'tag', allfields{index}, 'string', '', 'callback', cbedit } ...
{ } };
end;
% add buttons
% -----------
geometry = { geometry{:} [1] [1.2 0.6 0.6 1 0.6 0.6 1.2] [1.2 0.6 0.6 1 0.6 0.6 1.2] [2 1 2] };
tpappend = 'Append event after the current event';
tpinsert = 'Insert event before the current event';
tporigin = 'Original index of the event (in EEG.urevent table)';
uilist = { uilist{:}, ...
{ }, ...
{ },{ },{ }, {'Style', 'text', 'string', 'Event Num', 'fontweight', 'bold' }, { },{ },{ }, ...
{ 'Style', 'pushbutton', 'string', 'Insert event', 'callback', 'pop_editeventvals(''append'', 0);', 'tooltipstring', tpinsert }, ...
{ 'Style', 'pushbutton', 'string', '<<', 'callback', 'pop_editeventvals(''goto'', -10);' }, ...
{ 'Style', 'pushbutton', 'string', '<', 'callback', 'pop_editeventvals(''goto'', -1);' }, ...
{ 'Style', 'edit', 'string', '1', 'callback', 'pop_editeventvals(''goto'', 0);', 'tag', 'numval' }, ...
{ 'Style', 'pushbutton', 'string', '>', 'callback', 'pop_editeventvals(''goto'', 1);' }, ...
{ 'Style', 'pushbutton', 'string', '>>', 'callback', 'pop_editeventvals(''goto'', 10);' }, ...
{ 'Style', 'pushbutton', 'string', 'Append event', 'callback', 'pop_editeventvals(''append'', 1);', 'tooltipstring', tpappend }, ...
{ }, { 'Style', 'text', 'string', ' ', 'tag', 'original' 'horizontalalignment' 'center' 'tooltipstring' tporigin } { } };
% add sorting options
% -------------------
listboxtext = 'No field selected';
for index = 1:length(allfields)
listboxtext = [ listboxtext '|' allfields{index} ];
end;
geometry = { geometry{:} [1] [1 1 1] [1 1 1] [1 1 1] };
uilist = { uilist{:}, ...
{ 'Style', 'text', 'string', 'Re-order events (for review only)', 'fontweight', 'bold' }, ...
{ 'Style', 'text', 'string', 'Main sorting field:' }, ...
{ 'Style', 'popupmenu', 'string', listboxtext, 'tag', 'listbox1' }, ...
{ 'Style', 'checkbox', 'string', 'Click for decreasing order', 'tag', 'order1' } ...
{ 'Style', 'text', 'string', 'Secondary sorting field:' }, ...
{ 'Style', 'popupmenu', 'string', listboxtext, 'tag', 'listbox2' }, ...
{ 'Style', 'checkbox', 'string', 'Click for decreasing order', 'tag', 'order2' }, ...
{ } { 'Style', 'pushbutton', 'string', 'Re-sort', 'callback', 'pop_editeventvals(''sort'');' }, ...
{ } };
userdata = { EEG {} };
inputgui( geometry, uilist, 'pophelp(''pop_editeventvals'');', ...
'Edit event values -- pop_editeventvals()', userdata, 'plot');
pop_editeventvals('goto', 0);
% wait for figure
% ---------------
fig = gcf;
waitfor( findobj('parent', fig, 'tag', 'ok'), 'userdata');
try, userdata = get(fig, 'userdata'); close(fig); % figure still exist ?
catch, return; end;
% transfer events
% ---------------
if ~isempty(userdata{2})
com = sprintf('%s = pop_editeventvals(%s,%s);', inputname(1), inputname(1), vararg2str(userdata{2}));
end;
if isempty(findstr('''sort''', com))
if ~isempty(userdata{2}) % some modification have been done
EEG = userdata{1};
disp('Checking event consistency...');
EEG = eeg_checkset(EEG, 'eventconsistency');
EEG = eeg_checkset(EEG, 'checkur');
end;
else
com = '';
disp('WARNING: all edits discarded because of event resorting. The EEGLAB event structure');
disp(' must contain events sorted by latency (you may obtain an event structure');
disp(' with resorted event by calling this function from the command line).');
end;
return;
end;
return;
% format the output field
% -----------------------
function strval = reformat( val, latencycondition, trialcondition, eventnum)
if latencycondition
if trialcondition
strval = ['eeg_lat2point(' num2str(val) ', EEG.event(' int2str(eventnum) ').epoch, EEG.srate,[EEG.xmin EEG.xmax]*1000, 1E-3);' ];
else
strval = [ '(' num2str(val) '-EEG.xmin)*EEG.srate+1;' ];
end;
else
if isstr(val), strval = [ '''' val '''' ];
else strval = num2str(val);
end;
end;
% sort also empty values
% ----------------------
function [X, I] = mysort(tmparray);
if iscell(tmparray)
if all(cellfun('isreal', tmparray))
tmpempty = cellfun('isempty', tmparray);
tmparray(tmpempty) = { 0 };
tmparray = [ tmparray{:} ];
end;
end;
try,
[X I] = sort(tmparray);
catch,
disp('Sorting failed. Check that selected fields contain uniform value format.');
X = tmparray;
I = 1:length(X);
end;
% checkconsistency of new event
% -----------------------------
function eventtmp = checkconsistency(eventtmp, valnum, field)
otherval = mod(valnum+1, length(eventtmp))+1;
if isstr(getfield(eventtmp(valnum), field)) & ~isstr(getfield(eventtmp(otherval), field))
eventtmp(valnum) = setfield(eventtmp(valnum), field, str2num(getfield(eventtmp(valnum), field)));
end;
if ~isstr(getfield(eventtmp(valnum), field)) & isstr(getfield(eventtmp(otherval), field))
eventtmp(valnum) = setfield(eventtmp(valnum), field, num2str(getfield(eventtmp(valnum), field)));
end;
if strcmpi(field, 'latency') & isempty(getfield(eventtmp(valnum), field))
eventtmp(valnum).latency = NaN;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_icathresh.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_icathresh.m
| 14,758 |
utf_8
|
365bfcb08f0dd1c0da09de203c810155
|
% pop_icathresh() - main menu for choosing threshold for component
% rejection in EEGLAB.
%
% Usage:
% >> [OUTEEG rej] = pop_icathresh(INEEG, threshval, rejmethod,
% rejvalue, interact);
%
% Inputs:
% INEEG - input dataset
% threshval - values of thresholds for each of the 3 statistical
% measures. Default is [] and the program uses the value
% in the dataset.
% rejmethod - either 'percent', 'dataset' or 'current'. 'percent'
% will reject a given percentage of components with
% the highest value in one or several statistical
% measure. 'dataset' will use an other dataset for
% calibration. 'current' will use the current dataset
% for calibration. Default is 'current'.
% rejvalue - percentage if rejmethod is 'percent', dataset number
% if rejmethod is 'dataset' (no input if 'current'). If it
% is a percentage, '25' for instance means that the 25%
% independent components with the highest values of one
% statistical measure are rejected. Note that, one can
% also enter one percentage per statistical value (such as
% 25 20 30).
% interact - interactive windows or just rejection
%
% Inputs:
% OUTEEG - output dataset with updated thresholds
% rej - new rejection array
%
% Graphic interface:
% The graphic interface is divided into 3 parts. On the top, the
% experimenter chooses the basis for the component rejection (see
% rejmethod input). On the middle panel, the user can tune thresholds
% manually and plot the distribution of statistical values. Each time
% that setting of one of these two top panels is modified, the curve
% on the third panel are redrawn.
% The third panel is composed of 3 graphs, one for each statistical
% measure. The blue curve on each graph indicates the accuracy of the
% measure to detect artifactual components and non-artifactual
% components of a dataset. Note that 'artifactual components are
% defined with the rejection methods fields on the top (if you use
% the percentage methods, these artifactual components may not actually
% be artifactual). For accurate rejection, one should first reject
% artifactual component manually and then set up the threshold to
% approximate this manual rejection. The green curve indicate the
% rejection when all measure are considered. Points on the blue and
% on the green curves indicate the position of the current threshold on
% the parametric curve. Not that for the green cumulative curve, this
% point is at the same location for all graphs.
% How to tune the threshold? To tune the threshold, one should try to
% maximize the detection of non-artifactual components (because it is
% preferable to miss some artifactual components than to classify as
% artifactual non-artifact components).
%
% 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
%PROBLEM: when the % is set and we change manually yhe threshold,
% the software comes back to the percentage rejection
% 01-25-02 reformated help & license -ad
function [EEG, rej, com] = pop_icathresh( EEG, threshval, rejmethod, rejvalue, interact);
com = [];
rej = EEG.reject.gcompreject;
if nargin < 1
help pop_icathresh;
return;
end;
if nargin < 2
threshval = [];
end;
if nargin < 3
rejmethod = 'current';
end;
if nargin < 4
rejvalue = 25;
end;
if nargin < 5
interact = 1;
end;
if ~isempty(threshval)
EEG.reject.threshentropy = threshval(1);
EEG.reject.threshkurtact = threshval(2);
EEG.reject.threshkurtdist = threshval(3);
end;
tagmenu = 'pop_icathresh';
if ~isempty( findobj('tag', tagmenu))
error('cannot open two identical windows, close the first one first');
end;
% the current rejection will be stored in userdata of the figure
% --------------------------------------------------------------
gcf = figure('visible', 'off', 'numbertitle', 'off', 'name', 'Choose thresholds', 'tag', tagmenu, 'userdata', rej);
pos = get(gca, 'position');
q = [pos(1) pos(2) 0 0];
s = [pos(3) pos(4) pos(3) pos(4)]./100;
axis off;
% definition of callbacks
% -----------------------
cb_cancel = [ 'userdat = get(gcbo, ''userdata'');' ... % restore thresholds
'EEG.reject.threshentropy = userdat{1};' ...
'EEG.reject.threshkurtact = userdat{2};' ...
'EEG.reject.threshkurtdist = userdat{3};' ...
'clear userdat; close(gcbf);' ];
drawgraphs = [ 'if isempty( gcbf ), fig = gcf; else fig = gcbf; end;' ... % determine the figure handler
'if get( findobj(''parent'', fig, ''tag'', ''Ipercent''), ''value'') == 1, ' ... % test if percentage
' perc = str2num(get( findobj(''parent'', fig, ''tag'', ''Ipercenttext''), ''String''));' ...
' if length(perc < 2), perc = [perc perc perc]; end;' ...
' perc = round((100-perc) * length( EEG.stats.compenta) / 100);' ... % convert the percentage
' method = zeros( size( EEG.stats.compenta ) );' ...
' [tmprej tmpindex] = sort(EEG.stats.compenta(:));' ...
' method( tmpindex(perc(1)+1:end) ) = 1;' ...
' set( findobj(''parent'', fig, ''tag'', ''entstring''), ''string'', num2str(tmprej(perc(1)+1)));' ... % update threshold
' [tmprej tmpindex] = sort(EEG.stats.compkurta(:));' ...
' method( tmpindex(perc(2)+1:end) ) = 1;' ...
' set( findobj(''parent'', fig, ''tag'', ''kurtstring''), ''string'', num2str(tmprej(perc(1)+1)));' ... % update threshold
' [tmprej tmpindex] = sort(EEG.stats.compkurtdist(:));' ...
' method( tmpindex(perc(3)+1:end) ) = 1;' ...
' set( findobj(''parent'', fig, ''tag'', ''kurtdiststring''), ''string'', num2str(tmprej(perc(1)+1)));' ... % update threshold
' allvalues = [EEG.stats.compenta(:) EEG.stats.compkurta(:) EEG.stats.compkurtdist(:) ];' ...
' clear perc tmprej tmpindex;' ...
'end;' ...
'if get( findobj(''parent'', fig, ''tag'', ''Iother''), ''value'') == 1, ' ... % test if other dataset
' di = str2num(get( findobj(''parent'', fig, ''tag'', ''Iothertext''), ''String''));' ...
' if isempty( di ), clear fig; return; end;' ...
' method = ALLEEG(di).reject.gcompreject'';' ...
' allvalues = [ALLEEG(di).stats.compenta(:) ALLEEG(di).stats.compkurta(:) ALLEEG(di).stats.compkurtdist(:) ];' ...
' clear di;' ...
'end;' ...
'if get( findobj(''parent'', fig, ''tag'', ''Icurrent''), ''value'') == 1, ' ... % test if current dataset
' method = EEG.reject.gcompreject'';' ...
' allvalues = [EEG.stats.compenta(:) EEG.stats.compkurta(:) EEG.stats.compkurtdist(:) ];' ...
'end;' ...
'axes( findobj( ''parent'', fig, ''tag'', ''graphent'')); cla;' ...
'[tmp1 tmp2 tmp3] = drawproba( method, allvalues, [0 EEG.reject.threshkurtact EEG.reject.threshkurtdist ], ' ...
' { ''&'' ''|'' }, EEG.reject.threshentropy, ''Entropy of activity'',''Artifact detection (%)'', ''Non-artifact detection (%)'');' ...
'set(gca, ''tag'', ''graphent'');' ...
'axes( findobj( ''parent'', fig, ''tag'', ''graphkurt'')); cla;' ...
'[tmp1 tmp2 tmp3] = drawproba( method, allvalues, [EEG.reject.threshentropy 0 EEG.reject.threshkurtdist ], ' ...
' { ''&'' ''|'' }, EEG.reject.threshkurtact, ''Kurtosis of activity'', ''Artifact detection (%)'', '''');' ...
'set(gca, ''tag'', ''graphkurt'');' ...
'axes( findobj( ''parent'', fig, ''tag'', ''graphkurtdist'')); cla;' ...
'[tmp1 tmp2 tmp3] = drawproba( method, allvalues, [EEG.reject.threshentropy EEG.reject.threshkurtact 0 ], ' ...
' { ''&'' ''|'' }, EEG.reject.threshkurtdist, ''Kurtosis of topography'', ''Artifact detection (%)'', '''');' ...
'set(gca, ''tag'', ''graphkurtdist'');' ...
'clear method allvalues fig;' ...
];
cb_percent = [ 'if isempty( gcbf ), fig = gcf; else fig = gcbf; end;' ... % determine the figure handler
'set( findobj(''parent'', fig, ''tag'', ''Ipercent''), ''value'', 1);'...
'set( findobj(''parent'', fig, ''tag'', ''Iother''), ''value'', 0);' ...
'set( findobj(''parent'', fig, ''tag'', ''Icurrent''), ''value'', 0);' ...
'set( findobj(''parent'', fig, ''tag'', ''Ipercenttext''), ''enable'', ''on'');' ...
'set( findobj(''parent'', fig, ''tag'', ''Iothertext''), ''enable'', ''off''); clear fig;' drawgraphs ];
cb_other = [ 'if isempty( gcbf ), fig = gcf; else fig = gcbf; end;' ... % determine the figure handler
'set( findobj(''parent'', fig, ''tag'', ''Iother''), ''value'', 1);'...
'set( findobj(''parent'', fig, ''tag'', ''Ipercent''), ''value'', 0);' ...
'set( findobj(''parent'', fig, ''tag'', ''Icurrent''), ''value'', 0);' ...
'set( findobj(''parent'', fig, ''tag'', ''Ipercenttext''), ''enable'', ''off'');' ...
'set( findobj(''parent'', fig, ''tag'', ''Iothertext''), ''enable'', ''on''); clear fig;' drawgraphs ];
cb_current = [ 'if isempty( gcbf ), fig = gcf; else fig = gcbf; end;' ... % determine the figure handler
'set( findobj(''parent'', fig, ''tag'', ''Icurrent''), ''value'', 1);'...
'set( findobj(''parent'', fig, ''tag'', ''Iother''), ''value'', 0);' ...
'set( findobj(''parent'', fig, ''tag'', ''Ipercent''), ''value'', 0);' ...
'set( findobj(''parent'', fig, ''tag'', ''Ipercenttext''), ''enable'', ''off'');' ...
'set( findobj(''parent'', fig, ''tag'', ''Iothertext''), ''enable'', ''off''); clear fig;' drawgraphs ];
cb_entropy = [ 'EEG.reject.threshentropy = str2num(get(gcbo, ''string''));' ...
drawgraphs ];
cb_kurtact = [ 'EEG.reject.threshkurtact = str2num(get(gcbo, ''string''));' ...
drawgraphs ];
cb_kurtdist = [ 'EEG.reject.threshkurtdist = str2num(get(gcbo, ''string''));' ...
drawgraphs ];
if interact
cb_calrej = [ 'ButtonName=questdlg2( ''This will erase previous projections'', ''Confirmation'', ''CANCEL'', ''OK'', ''OK'');' ]
else
cb_calrej = [ 'ButtonName= ''OK''' ];
end;
cb_calrej = [ cb_calrej ...
'switch ButtonName,' ...
' case ''OK'',' ...
' rej1 = find(EEG.stats.compenta > EEG.reject.threshentropy);' ...
' rej2 = find(EEG.stats.compkurta > EEG.reject.threshkurtact);' ...
' rej3 = find(EEG.stats.compkurtdist > EEG.reject.threshkurtdist);' ...
' EEG.reject.gcompreject = (rej1 & rej2) | rej3;' ...
' clear rej1 rej2 rej3;' ...
'end; clear ButtonName;' ];
% default value for rejection methods
% -----------------------------------
rejvalother = '';
rejvalpercent = '25';
switch rejmethod
case 'percent', rejvalpercent = num2str( rejvalue);
case 'dataset', rejvalother = num2str( rejvalue);
end;
% -----------------------------------------------------
allh = supergui(gcf, { [1] ...
[2 1] [2 1] [2 1] ...
[1] ...
[1] ...
[1.5 0.5 1] [1.5 0.5 1] [1.5 0.5 1] ...
[1] [1] [1] [1] [1] [1] [1] [1] [1] [1] ...
[1 1 1 1 1] ...
}, [], ...
{ 'Style', 'text', 'string', 'Calibration method', 'FontSize', 13, 'fontweight', 'bold' }, ...
...
{ 'style', 'checkbox', 'String', '% of artifactual components (can also put one % per rejection)', 'tag', 'Ipercent', 'value', 1, 'callback', cb_percent}, ...
{ 'style', 'edit', 'String', rejvalpercent, 'tag', 'Ipercenttext', 'callback', drawgraphs }, ...
...
{ 'style', 'checkbox', 'String', 'Specific dataset (enter dataset number)', 'tag', 'Iother', 'value', 0, 'callback', cb_other}, ...
{ 'style', 'edit', 'String', rejvalother, 'tag', 'Iothertext', 'enable', 'off', 'callback', drawgraphs }, ...
...
{ 'style', 'checkbox', 'String', 'Current dataset', 'tag', 'Icurrent', 'value', 0, 'callback', cb_current}, ...
{ }, ...
...
{ }, ...
...
{ 'Style', 'text', 'string', 'Threshold values', 'FontSize', 13, 'fontweight', 'bold' }, ...
...
{ 'style', 'text', 'String', 'Entropy of activity threshold' }, ...
{ 'style', 'edit', 'String', num2str(EEG.reject.threshentropy), 'tag', 'entstring', 'callback', cb_entropy }, ...
{ 'style', 'pushbutton', 'String', 'Histogram', 'callback', 'figure; hist(EEG.stats.compenta,20); title(''Entropy of activity'');' }, ...
...
{ 'style', 'text', 'String', 'Kurtosis of activity threshold' }, ...
{ 'style', 'edit', 'String', num2str(EEG.reject.threshkurtact), 'tag', 'kurtstring', 'callback', cb_kurtact }, ...
{ 'style', 'pushbutton', 'String', 'Histogram', 'callback', 'figure; hist(EEG.stats.compkurta,200); title(''Kurtosis of activity'');' }, ...
...
{ 'style', 'text', 'String', 'Kurtosis of topography threshold' }, ...
{ 'style', 'edit', 'String', num2str(EEG.reject.threshkurtdist), 'tag', 'kurtdiststring', 'callback', cb_kurtdist }, ...
{ 'style', 'pushbutton', 'String', 'Histogram', 'callback', 'figure; hist(EEG.stats.compkurtdist,20); title(''Kurtosis of topography'');' }, ...
...
{ }, { }, { }, { }, { }, { }, { }, { }, { }, { }, ...
...
{ 'style', 'pushbutton', 'String', 'Cancel', 'callback', cb_cancel, 'userdata', { EEG.reject.threshentropy EEG.reject.threshkurtact EEG.reject.threshkurtdist }}, ...
{ 'style', 'pushbutton', 'String', 'Auto thresh' , 'callback', '', 'enable', 'off' }, ...
{ 'style', 'pushbutton', 'String', 'Help' , 'callback', 'pophelp(''pop_icathresh'');' }, ...
{ 'style', 'pushbutton', 'String', 'Accept thresh.' , 'callback', 'close(gcbf);' }, ...
{ 'style', 'pushbutton', 'String', 'Calc. rejection' , 'callback', 'close(gcbf);' } ...
...
);
h = axes('position', [0 15 30 30].*s+q, 'tag', 'graphent');
h = axes('position', [35 15 30 30].*s+q, 'tag', 'graphkurt');
h = axes('position', [70 15 30 30].*s+q, 'tag', 'graphkurtdist');
rejmethod
switch rejmethod
case 'dataset', eval([ 'gcbf = [];' cb_other]);
case 'current', eval([ 'gcbf = [];' cb_current]);
otherwise, eval([ 'gcbf = [];' cb_percent]);
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_eegthresh.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_eegthresh.m
| 9,769 |
utf_8
|
6b51b6f2693399b7690272bbcaf1e3fa
|
% pop_eegthresh() - reject artifacts by detecting outlier values. This has
% long been a standard method for selecting data to reject.
% Applied either for electrode data or component activations.
% Usage:
% >> pop_eegthresh( INEEG, typerej); % pop-up interactive window
% >> [EEG Indexes] = pop_eegthresh( INEEG, typerej, elec_comp, lowthresh, ...
% upthresh, starttime, endtime, superpose, reject);
%
% Graphic interface:
% "Electrode|Component number(s)" - [edit box] number(s) of the electrode(s) or
% component(s) to take into consideration. Same as the 'elec_comp'
% parameter from the command line.
% "Lower limit(s)" - [edit box] lower threshold limit(s) (in uV|std. dev.).
% Sets command line parameter 'lowthresh'.
% "Upper limit(s)" - [edit box] upper threshold limit(s) (in uV|std. dev.).
% Sets command line parameter 'upthresh'.
% "Start time(s)" - [edit box] starting time limit(s) (in seconds).
% Sets command line parameter 'starttime'.
% "End time(s)" - [edit box] ending time limit(s) (in seconds).
% Sets command line parameter 'endtime'.
% "Display with previously marked rejections?" - [edit box] either YES or
% NO. This edit box sets command line option 'superpose'.
% "Reject marked trials?" - [edit box] either YES or NO. This edit box
% sets command line option 'reject'.
%
% Inputs:
% INEEG - input EEG dataset
% typerej - type of rejection (0 = independent components; 1 = raw
% data). Default is 1. For independent components, before
% thresholding the activations are normalized (to have std. dev. 1).
% elec_comp - [e1 e2 ...] electrode|component numbers to take
% into consideration for rejection
% lowthresh - lower threshold limit (in uV|std. dev. For components, the
% threshold(s) are in std. dev.). Can be an array if more than one
% electrode|component number is given in elec_comp (above).
% If fewer values than the number of electrodes|components, the
% last value is used for the remaining electrodes|components.
% upthresh - upper threshold limit (in uV|std dev) (see lowthresh above)
% starttime - rejection window start time(s) in seconds (see lowthresh above)
% endtime - rejection window end time(s) in seconds (see lowthresh)
% superpose - [0|1] 0=do not superpose rejection markings on previous
% rejection marks stored in the dataset: 1=show both current and
% previously marked rejections using different colors. {Default: 0}.
% reject - [1|0] 0=do not actually reject the marked trials (but store the
% marks: 1=immediately reject marked trials. {Default: 1}.
% Outputs:
% Indexes - index of rejected trials
% When eegplot() is called, modifications are applied to the current
% dataset at the end of the call to eegplot() when the user presses
% the 'Reject' button.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eegthresh(), 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
% 01-25-02 reformated help & license -ad
% 03-07-02 added srate argument to eegplot call -ad
function [EEG, Irej, com] = pop_eegthresh( EEG, icacomp, elecrange, negthresh, posthresh, ...
starttime, endtime, superpose, reject, topcommand);
Irej = [];
com = '';
if nargin < 1
help pop_eegthresh;
return;
end;
if nargin < 2
icacomp = 1;
end;
if icacomp == 0
if isempty( EEG.icasphere )
disp('Error: you must run ICA first'); return;
end;
end;
if exist('reject') ~= 1
reject = 1;
end;
if nargin < 3
% which set to save
% -----------------
promptstr = { fastif(icacomp==0, 'Component (number(s), Ex: 2 4 5):', 'Electrode (number(s), Ex: 2 4 5):'), ...
fastif(icacomp==0, 'Lower limit(s) (std. dev, Ex: -3 -2.5 -2):', 'Lower limit(s) (uV, Ex:-20 -10 -15):'), ...
fastif(icacomp==0, 'Upper limit(s) (std. dev, Ex: 2 2 2.5):', 'Upper limit(s) (uV, Ex: 20 10 15):'), ...
'Start time(s) (seconds, Ex -0.1 0.3):', ...
'End time(s) (seconds, Ex 0.2):', ...
'Display with previously marked rejections? (YES or NO)', ...
'Reject marked trial(s)? (YES or NO)' };
inistr = { fastif(icacomp==1, ['1:' int2str(EEG.nbchan)], '1:5'), ...
fastif(icacomp==1, '-10', '-20'), ...
fastif(icacomp==1, '10', '20'), ...
num2str(EEG.xmin), ...
num2str(EEG.xmax), ...
'NO', ...
'NO' };
result = inputdlg2( promptstr, fastif(icacomp == 0, 'Rejection abnormal comp. values -- pop_eegthresh()', ...
'Rejection abnormal elec. values -- pop_eegthresh()'), 1, inistr, 'pop_eegthresh');
size_result = size( result );
if size_result(1) == 0 return; end;
elecrange = result{1};
negthresh = result{2};
posthresh = result{3};
starttime = result{4};
endtime = result{5};
switch lower(result{6}), case 'yes', superpose=1; otherwise, superpose=0; end;
switch lower(result{7}), case 'yes', reject=1; otherwise, reject=0; end;
end;
if isstr(elecrange) % convert arguments if they are in text format
calldisp = 1;
elecrange = eval( [ '[' elecrange ']' ] );
negthresh = eval( [ '[' negthresh ']' ] );
posthresh = eval( [ '[' posthresh ']' ] );
if isstr(starttime)
starttime = eval( [ '[' starttime ']' ] );
end;
if isstr(endtime)
endtime = eval( [ '[' endtime ']' ] );
end;
else
calldisp = 0;
end;
if any(starttime < EEG.xmin)
fprintf('Warning : starttime inferior to minimum time, adjusted\n');
starttime(find(starttime < EEG.xmin)) = EEG.xmin;
end;
if any(endtime > EEG.xmax)
fprintf('Warning : endtime superior to maximum time, adjusted\n');
endtime(find(endtime > EEG.xmax)) = EEG.xmax;
end;
if icacomp == 1
[Itmp Irej NS Erejtmp] = eegthresh( EEG.data, EEG.pnts, elecrange, negthresh, posthresh, [EEG.xmin EEG.xmax], starttime, endtime);
tmpelecIout = zeros(EEG.nbchan, EEG.trials);
tmpelecIout(elecrange,Irej) = Erejtmp;
else
icaacttmp = eeg_getdatact(EEG, 'component', elecrange);
[Itmp Irej NS Erejtmp] = eegthresh( icaacttmp, EEG.pnts, 1:length(elecrange), negthresh, posthresh, [EEG.xmin EEG.xmax], starttime, endtime);
tmpelecIout = zeros(size(EEG.icaweights,1), EEG.trials);
tmpelecIout(elecrange,Irej) = Erejtmp;
end;
fprintf('%d channel selected\n', size(elecrange(:), 1));
fprintf('%d/%d trials marked for rejection\n', length(Irej), EEG.trials);
tmprejectelec = zeros( 1, EEG.trials);
tmprejectelec(Irej) = 1;
rej = tmprejectelec;
rejE = tmpelecIout;
if calldisp
if icacomp == 1 macrorej = 'EEG.reject.rejthresh';
macrorejE = 'EEG.reject.rejthreshE';
else macrorej = 'EEG.reject.icarejthresh';
macrorejE = 'EEG.reject.icarejthreshE';
end;
colrej = EEG.reject.rejthreshcol;
eeg_rejmacro; % script macro for generating command and old rejection arrays
if icacomp == 1
eegplot( EEG.data(elecrange,:,:), 'srate', EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:});
else
eegplot( icaacttmp, 'srate', EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:});
end;
else
if reject == 1
EEG = pop_rejepoch(EEG, rej, 0);
end;
end;
if ~isempty(rej)
if icacomp == 1
EEG.reject.rejthresh = rej;
EEG.reject.rejthreshE = rejE;
else
EEG.reject.icarejthresh = rej;
EEG.reject.icarejthreshE = rejE;
end;
end;
%com = sprintf('Indexes = pop_eegthresh( %s, %d, [%s], [%s], [%s], [%s], [%s], %d, %d);', ...
% inputname(1), icacomp, num2str(elecrange), num2str(negthresh), ...
% num2str(posthresh), num2str(starttime ) , num2str(endtime), superpose, reject );
com = [ com sprintf('%s = pop_eegthresh(%s,%s);', inputname(1), ...
inputname(1), vararg2str({icacomp,elecrange,negthresh,posthresh,starttime,endtime,superpose,reject})) ];
if nargin < 3
Irej = com;
end;
return;
% reject artifacts in a sequential fashion to save memory (ICA ONLY)
% -------------------------------------------------------
function [Irej, Erej] = thresh( data, elecrange, timerange, negthresh, posthresh, starttime, endtime);
Irej = [];
Erej = zeros(size(data,1), size(data,2));
for index = 1:length(elecrange)
tmpica = data(index,:,:);
tmpica = reshape(tmpica, 1, size(data,2)*size(data,3));
% perform the rejection
% ---------------------
tmpica = (tmpica-mean(tmpica,2)*ones(1,size(tmpica,2)))./ (std(tmpica,0,2)*ones(1,size(tmpica,2)));
[I1 Itmprej NS Etmprej] = eegthresh( tmpica, size(data,2), 1, negthresh, posthresh, ...
timerange, starttime, endtime);
Irej = union_bc(Irej, Itmprej);
Erej(elecrange(index),Itmprej) = Etmprej;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_timef.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_timef.m
| 8,964 |
utf_8
|
479d128417dbb0d8ab96a1795c580e3b
|
% pop_timef() - Returns estimates and plots of event-related (log) spectral
% perturbation (ERSP) and inter-trial coherence (ITC) changes
% timelocked to a set of input events in one data channel.
%
% Usage:
% >> pop_timef(EEG, typeplot); % pop_up window
% >> pop_timef(EEG, typeplot, lastcom); % pop_up window
% >> pop_timef(EEG, typeplot, channel); % do not pop-up
% >> pop_timef(EEG, typeproc, num, tlimits,cycles,
% 'key1',value1,'key2',value2, ... );
%
% Inputs:
% INEEG - input EEG dataset
% typeproc - type of processing. 1 process the raw
% data and 0 the ICA components
% num - component or channel number
% tlimits - [mintime maxtime] (ms) sub-epoch time limits
% cycles - >0 -> Number of cycles in each analysis wavelet
% 0 -> Use FFTs (with constant window length)
%
% Optional inputs:
% See the timef() function.
%
% Outputs: same as timef(), no outputs are returned when a
% window pops-up to ask for additional arguments
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: timef(), eeglab()
% 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
% 01-25-02 reformated help & license -ad
% 03-08-02 add eeglab option & optimize variable sizes -ad
% 03-10-02 change timef call -ad
% 03-18-02 added title -ad & sm
% 04-04-02 added outputs -ad & sm
function varargout = pop_timef(EEG, typeproc, num, tlimits, cycles, varargin );
varargout{1} = '';
% display help if not enough arguments
% ------------------------------------
if nargin < 2
help pop_timef;
return;
end;
lastcom = [];
if nargin < 3
popup = 1;
else
popup = isstr(num) | isempty(num);
if isstr(num)
lastcom = num;
end;
end;
% pop up window
% -------------
if popup
[txt vars] = gethelpvar('timef.m');
geometry = { [1 0.5 0.5] [1 0.5 0.5] [1 0.5 0.5] [0.92 0.1 0.78] [1 0.5 0.5] [1 0.8 0.2] [1] [1 1]};
uilist = { ...
{ 'Style', 'text', 'string', fastif(typeproc, 'Channel number', 'Component number'), 'fontweight', 'bold' } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,3,[],'1') } {} ...
{ 'Style', 'text', 'string', 'Epoch time range [min max] (msec)', 'fontweight', 'bold', ...
'tooltipstring', 'Sub epoch time limits' } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,4,[],[ int2str(EEG.xmin*1000) ' ' int2str(EEG.xmax*1000) ]) } {} ...
{ 'Style', 'text', 'string', 'Wavelet cycles (0->FFT, see >> help timef)', 'fontweight', 'bold', ...
'tooltipstring', context('cycles',vars,txt) } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,5,[],'3 0.5') } {} ...
{ 'Style', 'text', 'string', '[set]->Linear coher / [unset]->Phase coher', 'fontweight', 'bold', ...
'tooltipstring', ['Compute linear inter-trial coherence (coher)' 10 ...
'OR Amplitude-normalized inter-trial phase coherence (phasecoher)'] } ...
{ 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'phasecoher','present',1) } { } ...
{ 'Style', 'text', 'string', 'Bootstrap significance level (Ex: 0.01 -> 1%)', 'fontweight', 'bold', ...
'tooltipstring', context('alpha',vars,txt) } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,'alpha') } {} ...
{ 'Style', 'text', 'string', 'Optional timef() arguments (see Help)', 'fontweight', 'bold', ...
'tooltipstring', 'See timef() help via the Help button on the right...' } ...
{ 'Style', 'edit', 'string', '''padratio'', 4, ''plotphase'',''off''' } ...
{ 'Style', 'pushbutton', 'string', 'Help', 'callback', 'pophelp(''timef'');' } ...
{} ...
{ 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotersp','present',0), 'string', ...
'Plot Event Related Spectral Power', 'tooltipstring', ...
'Plot log spectral perturbation image in the upper panel' } ...
{ 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotitc','present',0), 'string', ...
'Plot Inter Trial Coherence', 'tooltipstring', ...
'Plot the inter-trial coherence image in the lower panel' } ...
};
% { 'Style', 'edit', 'string', '''padratio'', 4, ''plotphase'', ''off''' } ...
%{ 'Style', 'text', 'string', '[set] -> Plot ITC phase sign', 'fontweight', 'bold', ...
% 'tooltipstring', ['Plot the sign (+/-) of inter-trial coherence phase' 10 ...
% 'as red (+) or blue (-)'] } ...
% { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotphase','present',1) } { } ...
result = inputgui( geometry, uilist, 'pophelp(''pop_timef'');', ...
fastif(typeproc, 'Plot channel time frequency -- pop_timef()', ...
'Plot component time frequency -- pop_timef()'));
if length( result ) == 0 return; end;
num = eval( [ '[' result{1} ']' ] );
tlimits = eval( [ '[' result{2} ']' ] );
cycles = eval( [ '[' result{3} ']' ] );
if result{4}
options = [ ',''type'', ''coher''' ];
else
options = [',''type'', ''phasecoher''' ];
end;
% add topoplot
% ------------
if isfield(EEG.chanlocs, 'theta')
if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end;
if typeproc == 1
options = [options ', ''topovec'', ' int2str(num) ...
', ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ];
else
options = [options ', ''topovec'', EEG.icawinv(:,' int2str(num) ...
'), ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ];
end;
end;
% add title
% ---------
if isempty( findstr( '''title''', result{6}))
if ~isempty(EEG.chanlocs) & typeproc
chanlabel = EEG.chanlocs(num).labels;
else
chanlabel = int2str(num);
end;
switch lower(result{4})
case 'coher', options = [options ', ''title'',' fastif(typeproc, '''Channel ', '''Component ') chanlabel ...
' power and inter-trial coherence' fastif(~ isempty(EEG.setname), [' (' EEG.setname ')''' ], '''') ];
otherwise, options = [options ', ''title'',' fastif(typeproc, '''Channel ', '''Component ') chanlabel ...
' power and inter-trial phase coherence' fastif(~ isempty(EEG.setname), [' (' EEG.setname ')''' ], '''') ];
end;
end;
if ~isempty( result{5} )
options = [ options ', ''alpha'',' result{5} ];
end;
if ~isempty( result{6} )
options = [ options ',' result{6} ];
end;
if ~result{7}
options = [ options ', ''plotersp'', ''off''' ];
end;
if ~result{8}
options = [ options ', ''plotitc'', ''off''' ];
end;
figure; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end;
else
options = [ ',' vararg2str(varargin) ];
end;
% compute epoch limits
% --------------------
if isempty(tlimits)
tlimits = [EEG.xmin, EEG.xmax]*1000;
end;
pointrange1 = round(max((tlimits(1)/1000-EEG.xmin)*EEG.srate, 1));
pointrange2 = round(min((tlimits(2)/1000-EEG.xmin)*EEG.srate, EEG.pnts));
pointrange = [pointrange1:pointrange2];
% call function sample either on raw data or ICA data
% ---------------------------------------------------
if typeproc == 1
tmpsig = EEG.data(num,pointrange,:);
else
if ~isempty( EEG.icasphere )
tmpsig = eeg_getdatact(EEG, 'component', num, 'samples', pointrange);
else
error('You must run ICA first');
end;
end;
% outputs
% -------
outstr = '';
if ~popup
for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end;
if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end;
end;
% plot the datas and generate output command
% --------------------------------------------
if length( options ) < 2
options = '';
end;
if nargin < 4
varargout{1} = sprintf('figure; pop_timef( %s, %d, %d, %s, %s %s);', inputname(1), typeproc, num, ...
vararg2str({tlimits}), vararg2str({cycles}), options);
end;
com = sprintf('%s timef( tmpsig(:, :), length(pointrange), [tlimits(1) tlimits(2)], EEG.srate, cycles %s);', outstr, options);
eval(com)
return;
% get contextual help
% -------------------
function txt = context(var, allvars, alltext);
loc = strmatch( var, allvars);
if ~isempty(loc)
txt= alltext{loc(1)};
else
disp([ 'warning: variable ''' var ''' not found']);
txt = '';
end;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_chantype.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_chantype.m
| 2,353 |
utf_8
|
cc106eb578fad38a9d0ce04e66c68cc5
|
% eeg_chantype() - Returns the channel indices of the desired channel type(s).
%
% Usage:
% >> indices = eeg_chantype(struct, types )
%
% Inputs:
% struct - EEG.chanlocs data structure returned by readlocs() containing
% channel location, type and gain information.
%
% Optional input
% types - [cell array] cell array containing types ...
%
% Output:
% indices -
%
% Author: Toby Fernsler, Arnaud Delorme, Scott Makeig
%
% See also: topoplot()
% Copyright (C) 2005 Toby Fernsler, 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 indices = eeg_chantype(data,chantype)
if nargin < 1
help eeg_chantype;
end;
if ischar(chantype), chantype = cellstr(chantype); end
if ~iscell(chantype),
error( 'chantype must be cell array, e.g. {''EEG'', ''EOG''}, or single character string, e.g.''EEG''.');
end
% Define 'datatype' variable, listing the type of each channel.
% ------------------------------------------------------------
if isfield(data,'type')
datatype = {data.type};
elseif isfield(data,'chanlocs') & isfield(data.chanlocs,'type')
datatype = {data.chanlocs.type};
else error('Incorrect ''data'' input. Should be ''EEG'' or ''loc_file'' structure variable in the format associated with EEGLAB.');
end
% seach for types
% ---------------
k = 1;
plotchans = [];
for i = 1:length(chantype)
for j = 1:length(datatype)
if strcmpi(chantype{i},char(datatype{j}))
plotchans(k) = j;
k = k + 1;
end;
end
end
indices = sort(plotchans);
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_eegrej.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_eegrej.m
| 5,443 |
utf_8
|
2eaad3df9a82438942a603294477a83f
|
% eeg_eegrej() - reject porition of continuous data in an EEGLAB
% dataset
%
% Usage:
% >> EEGOUT = eeg_eegrej( EEGIN, regions );
%
% Inputs:
% INEEG - input dataset
% regions - array of regions to suppress. number x [beg end] of
% regions. 'beg' and 'end' are expressed in term of points
% in the input dataset. Size of the array is
% number x 2 of regions.
%
% Outputs:
% INEEG - output dataset with updated data, events latencies and
% additional boundary events.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 8 August 2002
%
% See also: eeglab(), eegplot(), pop_rejepoch()
% Copyright (C) 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, com] = eeg_eegrej( EEG, regions);
com = '';
if nargin < 2
help eeg_eegrej;
return;
end;
if nargin<3
probadded = [];
end
if isempty(regions)
return;
end;
% regions = sortrows(regions,3); % Arno and Ramon on 5/13/2014 for bug 1605
% Ramon on 5/29/2014 for bug 1619
if size(regions,2) > 2
regions = sortrows(regions,3);
else
regions = sortrows(regions,1);
end;
try
% For AMICA probabilities...Temporarily add model probabilities as channels
%-----------------------------------------------------
if isfield(EEG.etc, 'amica') && ~isempty(EEG.etc.amica) && isfield(EEG.etc.amica, 'v_smooth') && ~isempty(EEG.etc.amica.v_smooth) && ~isfield(EEG.etc.amica,'prob_added')
if isfield(EEG.etc.amica, 'num_models') && ~isempty(EEG.etc.amica.num_models)
if size(EEG.data,2) == size(EEG.etc.amica.v_smooth,2) && size(EEG.data,3) == size(EEG.etc.amica.v_smooth,3) && size(EEG.etc.amica.v_smooth,1) == EEG.etc.amica.num_models
EEG = eeg_formatamica(EEG);
%-------------------------------------------
[EEG com] = eeg_eegrej(EEG,regions);
%-------------------------------------------
EEG = eeg_reformatamica(EEG);
EEG = eeg_checkamica(EEG);
return;
else
disp('AMICA probabilities not compatible with size of data, probabilities cannot be epoched')
disp('Load AMICA components before extracting epochs')
disp('Resuming rejection...')
end
end
end
% ------------------------------------------------------
catch
warnmsg = strcat('your dataset contains amica information, but the amica plugin is not installed. Continuing and ignoring amica information.');
warning(warnmsg)
end
if isfield(EEG.event, 'latency'),
tmpevent = EEG.event;
tmpalllatencies = [ tmpevent.latency ];
else tmpalllatencies = [];
end;
% handle regions from eegplot
% ---------------------------
if size(regions,2) > 2, regions = regions(:, 3:4); end;
regions = combineregions(regions);
[EEG.data EEG.xmax tmpalllatencies boundevents] = eegrej( EEG.data, ...
regions, EEG.xmax-EEG.xmin, tmpalllatencies);
oldEEGpnts = EEG.pnts;
EEG.pnts = size(EEG.data,2);
EEG.xmax = EEG.xmax+EEG.xmin;
% add boundary events
% -------------------
if ~isempty(boundevents) % boundevent latencies will be recomputed in the function below
[ EEG.event ] = eeg_insertbound(EEG.event, oldEEGpnts, regions);
EEG = eeg_checkset(EEG, 'eventconsistency');
end;
com = sprintf('%s = eeg_eegrej( %s, %s);', inputname(1), inputname(1), vararg2str({ regions }));
% combine regions if necessary
% it should not be necessary but a
% bug in eegplot makes that it sometimes is
% ----------------------------
% function newregions = combineregions(regions)
% newregions = regions;
% for index = size(regions,1):-1:2
% if regions(index-1,2) >= regions(index,1)
% disp('Warning: overlapping regions detected and fixed in eeg_eegrej');
% newregions(index-1,:) = [regions(index-1,1) regions(index,2) ];
% newregions(index,:) = [];
% end;
% end;
function newregions = combineregions(regions)
% 9/1/2014 RMC
regions = sortrows(sort(regions,2)); % Sorting regions
allreg = [ regions(:,1)' regions(:,2)'; ones(1,numel(regions(:,1))) -ones(1,numel(regions(:,2)')) ].';
allreg = sortrows(allreg,1); % Sort all start and stop points (column 1),
mboundary = cumsum(allreg(:,2)); % Rationale: regions will start always with 1 and close with 0, since starts=1 end=-1
indx = 0; count = 1;
while indx ~= length(allreg)
newregions(count,1) = allreg(indx+1,1);
[tmp,I]= min(abs(mboundary(indx+1:end)));
newregions(count,2) = allreg(I + indx,1);
indx = indx + I ;
count = count+1;
end
% Verbose
if size(regions,1) ~= size(newregions,1)
disp('Warning: overlapping regions detected and fixed in eeg_eegrej');
end
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_point2lat.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_point2lat.m
| 3,118 |
utf_8
|
e0dbc1311eceee071f6dcfb1dfcfb9bb
|
% eeg_point2lat() - convert latency in data points to latency in ms relative
% to the time locking. Used in eeglab().
% Usage:
% >> [newlat ] = eeg_point2lat( lat_array, [], srate);
% >> [newlat ] = eeg_point2lat( lat_array, epoch_array,...
% srate, timelimits, timeunit);
% Inputs:
% lat_array - latency array in data points assuming concatenated
% data epochs (see eeglab() event structure)
% epoch_array - epoch number corresponding to each latency value
% srate - data sampling rate in Hz
% timelimits - [min max] timelimits in 'timeunit' units (see below)
% timeunit - time unit in second. Default is 1 = seconds.
%
% Outputs:
% newlat - converted latency values (in 'timeunit' units) for each epoch
%
% Example:
% tmpevent = EEG.event;
% eeg_point2lat( [ tmpevent.latency ], [], EEG.srate, [EEG.xmin EEG.xmax]);
% % returns the latency of all events in second for a continuous
% % dataset EEG
%
% eeg_point2lat( [ tmpevent.latency ], [ tmpevent.epoch ],
% EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3);
% % returns the latency of all events in millisecond for a dataset
% % containing data epochs.
%
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2 Mai 2002
%
% See also: eeg_lat2point(), eeglab(), pop_editieventvals(), pop_loaddat()
% Copyright (C) 2 Mai 2002 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function newlat = eeg_point2lat( lat_array, epoch_array, srate, timewin, timeunit);
if nargin <3
help eeg_point2lat;
return;
end;
if isempty( epoch_array )
epoch_array = ones( size(lat_array) );
end;
if nargin <4
timewin = 0;
end;
if nargin <5
timeunit = 1;
end;
if length(lat_array) ~= length(epoch_array)
if length(epoch_array)~= 1
disp('eeg_point2lat: latency and epoch arrays must have the same length'); return;
else
epoch_array = ones(1,length(lat_array))*epoch_array;
end;
end;
if length(timewin) ~= 2
disp('eeg_point2lat: timelimits array must have length 2'); return;
end;
if iscell(epoch_array)
epoch_array = [ epoch_array{:} ];
end;
if iscell(lat_array)
lat_array = [ lat_array{:} ];
end
timewin = timewin*timeunit;
if length(timewin) == 2
pnts = (timewin(2)-timewin(1))*srate+1;
else
pnts = 0;
end;
newlat = ((lat_array - (epoch_array-1)*pnts-1)/srate+timewin(1))/timeunit;
newlat = round(newlat*1E9)*1E-9;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_averef.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_averef.m
| 2,591 |
utf_8
|
13d6362c4bcdd4d0c831e5b62379549f
|
% pop_averef() - Convert an EEG dataset to average reference.
% This function is obsolete. See pop_reref() instead.
%
% Usage:
% >> EEGOUT = pop_averef( EEG );
%
% Author: Arnaud Delorme, CNL / Salk Institute, 22 March 2002
%
% See also: eeglab(), reref(), averef()
% 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 [EEG, com] = pop_averef( EEG, confirm);
[EEG, com] = pop_reref(EEG, []);
return;
com = '';
if nargin < 1
help pop_averef;
return;
end;
if isempty(EEG.data)
error('Pop_averef: cannot process empty data');
end;
if nargin < 2 | confirm == 1
% which set to save
% -----------------
ButtonName=questdlg2( strvcat('Convert the data to average reference?', ...
'Note: ICA activations will also be converted if they exist...'), ...
'Average reference confirmation -- pop_averef()', 'Cancel', 'Yes','Yes');
switch lower(ButtonName),
case 'cancel', return;
end;
confirm = 0;
end;
EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts*EEG.trials);
if ~isempty(EEG.icaweights)
disp('pop_averef(): converting ICA weight matrix to average reference (see >> help averef)');
[EEG.data EEG.icaweights EEG.icasphere EEG.rmave] = averef(EEG.data,EEG.icaweights,EEG.icasphere);
EEG.icawinv = [];
if size(EEG.icaweights,1) > EEG.nbchan
disp('Warning: one or more channels may have been removed; component weight re-referencing may be inaccurate');
end;
if size(EEG.icasphere,1) < EEG.nbchan
disp('Warning: one or more components may have been removed; component weight re-referencing could be inaccurate');
end;
else
EEG.data = averef(EEG.data);
end;
EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts, EEG.trials);
EEG.averef = 'Yes';
EEG.icaact = [];
EEG = eeg_checkset(EEG);
com = sprintf('%s = pop_averef( %s, %d);', inputname(1), inputname(1), confirm);
return;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_matchchans.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_matchchans.m
| 5,088 |
utf_8
|
070c5b272529f4f74dc88932ce5baa77
|
% eeg_matchchans() - find closest channels in a larger EEGLAB chanlocs structure
% to channels in a smaller chanlocs structure
% Usage:
% >> [selchans,distances,selocs] = eeg_matchchans(BIGlocs,smalllocs,'noplot');
% Inputs:
% BIGlocs - larger (or equal-sized) EEG.chanlocs structure array
% smalllocs - smaller (or equal-sized) EEG.chanlocs structure array
% Optional inputs:
% 'noplot' - [optional string 'noplot'] -> do not produce plots {default:
% produce illustrative plots of the BIG and small locations}
% Outputs:
% selchans - indices of BIGlocs channels closest to the smalllocs channels
% distances - vector of distances between the selected BIGlocs and smalllocs chans
% selocs - EEG.chanlocs structure array containing nearest BIGlocs channels
% to each smalllocs channel: 1, 2, 3,... n. This structure has
% two extra fields:
% bigchan - original channel index in BIGlocs
% bigdist - distance between bigchan and smalllocs chan
% ==> bigdist assumes both input locs have sph_radius 1.
%
% Author: Scott Makeig, SCCN/INC/UCSD, April 9, 2004
% Copyright (C) 2004 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
% History: began Jan 27, 2004 as selectchans.m(?) -sm
function [selchans,dists,selocs] = eeg_matchchans(bglocs,ltlocs,noplot)
if nargin < 2
help eeg_matchchans
return
end
no_plot = 0; % yes|no flag
if nargin > 2 & strcmp(lower(noplot),'noplot')
no_plot = 1;
end
if ~isstruct(bglocs) | ~isstruct(ltlocs)
help eeg_matchchans
end
ltchans = length(ltlocs);
bgchans = length(bglocs);
if ltchans > bgchans
fprintf('BIGlocs chans (%d) < smalllocs chans (%d)\n',bgchans,ltchans);
return
end
selchans = zeros(ltchans,1);
dists = zeros(ltchans,1);
bd = zeros(bgchans,1);
%
%%%%%%%%%%%%%%%%% Compute the distances %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
fprintf('BIG ltl Dist\n');
for c=1:ltchans
for C=1:bgchans
if ~isempty(ltlocs(c).X) & ~isempty(bglocs(C).X)
bd(C) = sqrt((ltlocs(c).X/ltlocs(c).sph_radius - bglocs(C).X/bglocs(C).sph_radius)^2 + ...
(ltlocs(c).Y/ltlocs(c).sph_radius - bglocs(C).Y/bglocs(C).sph_radius)^2 + ...
(ltlocs(c).Z/ltlocs(c).sph_radius - bglocs(C).Z/bglocs(C).sph_radius)^2);
end
end
%
%%%%%%%%%%%%%%%%% Find the nearest BIGlocs channel %%%%%%%%%%%%%%%%%%%%%%%
%
[bd ix] = sort(bd); % find smallest distance c <-> C
bglocs(1).bigchan = [];
k=1;
while ~isempty(bglocs(ix(k)).bigchan) & k<=bgchans % avoid empty channels
k=k+1;
end
if k>bgchans
fprintf('No match found for smalllocs channel %d - error!?\n',c);
return % give up - should not reach here!
end
while k<length(ix)
if c>1 & sum(ismember(ix(k),selchans(1:c-1)))>0 % avoid chans already chosen
k = k+1;
else
break
end
end
if k==length(ix)
fprintf('NO available nearby channel for littlechan %d - using %d\n',...
c,ix(k));
end
selchans(c) = ix(k); % note the nearest BIGlocs channel
dists(c) = bd(k); % note its distance
bglocs(ix(k)).bigchan = selchans(c); % add this info to the output
bglocs(ix(k)).bigdist = dists(c);
fprintf('.bigchan %4d, c %4d, k %d, .bigdist %3.2f\n',...
bglocs(ix(k)).bigchan,c,k,bglocs(ix(k)).bigdist); % commandline printout
end; % c
selocs = bglocs(selchans); % return the selected BIGlocs struct array subset
%
%%%%%%%%%%%%%%%%% Plot the results %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~no_plot
figure;
titlestring = sprintf('%d-channel subset closest to %d channel locations',ltchans,bgchans);
tl=textsc(titlestring,'title');
set(tl,'fontweight','bold');
set(tl,'fontsize',15);
sbplot(7,2,[3 13]);
hist(dists,length(dists));
title('Distances between corresponding channels');
xlabel('Euclidian distance (sph. rad. 1)');
ylabel('Number of channels');
sbplot(7,5,[8,35]);
topoplot(dists,selocs,'electrodes','numbers','style','both');
title('Distances');
clen = size(colormap,1);
sbnull = sbplot(7,2,[10 12])
cb=cbar;
cbar(cb,[clen/2+1:clen]);
set(sbnull,'visible','off')
axcopy; % turn on axcopy
end
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_insertbound.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_insertbound.m
| 7,147 |
utf_8
|
cdb944c0e4d9182d26465cca98d458a1
|
% eeg_insertbound() - insert boundary event in an EEG event structure.
%
% Usage:
% >> [eventout indnew] = eeg_insertbound( eventin, pnts, ...
% abslatency, duration);
% Required Inputs:
% eventin - EEGLAB event structure (EEG.event)
% pnts - data points in EEG dataset (EEG.pnts * EEG.trials)
% abslatency - absolute latency of regions in original dataset. Can
% also be an array of [beg end] latencies with one row
% per region removed. Then 'lengths' argument is ignored.
% Optional Inputs:
% lengths - lengths of removed regions
%
% Outputs:
% eventout - EEGLAB event output structure with added boundaries
% indnew - array of indices returning new event index for any old
% (input eventin) event index
% Notes:
% This function performs the following:
% 1) add boundary events to the 'event' structure;
% remove nested boundaries;
% recompute the latencies of all events.
% 2) all latencies are given in (float) data points.
% e.g., a latency of 2000.3 means 0.3 samples (at EEG.srate)
% after the 2001st data frame (since first frame has latency 0).
%
% Author: Arnaud Delorme and Hilit Serby, SCCN, INC, UCSD, April, 19, 2004
%
% See also: eeg_eegrej(), pop_mergeset()
% Copyright (C) 2004 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 [eventout,indnew] = eeg_insertbound( eventin, pnts, regions, lengths);
if nargin < 3
help eeg_insertbound;
return;
end;
if size(regions,2) ~= 1 & exist('lengths') ~= 1
lengths = regions(:,2)-regions(:,1)+1;
regions = regions(:,1);
end;
if exist('lengths') ~= 1
lengths = zeros(size(regions));
end;
if length(regions)
fprintf('eeg_insertbound(): %d boundary (break) events added.\n', size(regions, 1));
else
return;
end;
% recompute latencies of boundevents (in new dataset)
% ---------------------------------------------------
[regions tmpsort] = sort(regions);
lengths = lengths(tmpsort);
boundevents = regions(:,1)-0.5;
% sort boundevents by decreasing order (otherwise bug in new event index)
% ------------------------------------
boundevents = boundevents(end:-1:1);
lengths = lengths (end:-1:1);
eventout = eventin;
indnew = 1:length(eventin);
allnest = [];
countrm = 0;
for tmpindex = 1:length(boundevents) % sorted in decreasing order
if boundevents(tmpindex) >= 0.5 & boundevents(tmpindex) <= pnts
% find event succeding boundary to insert event
% at the correct location in the event structure
% ----------------------------------------------
if ~isempty(eventout) & isfield(eventout, 'latency')
alllats = [ eventout.latency ] - boundevents(tmpindex);
tmpind = find( alllats >= 0 );
[tmp tmpind2 ] = min(alllats(tmpind));
tmpind2 = tmpind(tmpind2);
else
tmpind2 = [];
end;
% insert event at tmpind2
% -----------------------
if ~isempty(tmpind2)
eventout(end+1).type = 'boundary';
tmp = eventout(end);
eventout(tmpind2+1:end) = eventout(tmpind2:end-1);
eventout(tmpind2) = tmp;
indnew(tmpind2:end) = indnew(tmpind2:end)+1;
else
tmpind2 = length(eventout)+1;
eventout(tmpind2).type = 'boundary';
end;
eventout(tmpind2).latency = boundevents(tmpindex);
eventout(tmpind2).duration = lengths(tmpindex); % just to create field
[ tmpnest addlength ] = findnested(eventout, tmpind2);
% recompute latencies and remove events in the rejected region
% ------------------------------------------------------------
eventout(tmpnest) = [];
countrm = countrm+length(tmpnest);
for latind = tmpind2+1:length(eventout)
eventout(latind).latency = eventout(latind).latency-lengths(tmpindex);
end;
% add lengths of previous events (must be done after above)
% ---------------------------------------------------------
eventout(tmpind2).duration = lengths(tmpindex)+addlength;
if eventout(tmpind2).duration == 0, eventout(tmpind2).duration=NaN; end;
end;
end;
if countrm > 0
fprintf('eeg_insertbound(): event latencies recomputed and %d events removed.\n', countrm);
end;
% look for nested events
% retrun indices of nested events and
% their total length
% -----------------------------------
function [ indnested, addlen ] = findnested(event, ind);
indnested = [];
addlen = 0;
tmpind = ind+1;
while tmpind <= length(event) & ...
event(tmpind).latency < event(ind).latency+event(ind).duration
if strcmpi(event(tmpind).type, 'boundary')
if ~isempty( event(tmpind).duration )
addlen = addlen + event(tmpind).duration;
% otherwise old event duration or merge data discontinuity
end;
end;
indnested = [ indnested tmpind ];
tmpind = tmpind+1;
end;
% remove urevent and recompute indices
% THIS FUNCTION IS DEPRECATED
% ------------------------------------
function [event, urevent] = removenested(event, urevent, nestind);
if length(nestind) > 0
fprintf('eeg_insertbound() debug msg: removing %d nested urevents\n', length(nestind));
nestind = sort(nestind);
urind = [ event.urevent ]; % this must not be done in the loop
% since the indices are dyanmically updated
end;
for ind = 1:length(nestind)
% find event urindices higher than the urevent to suppress
% --------------------------------------------------------
tmpind = find( urind > nestind(ind) );
for indevent = tmpind
event(indevent).urevent = event(indevent).urevent-1;
end;
end;
urevent(nestind) = [];
|
github
|
ZijingMao/baselineeegtest-master
|
pop_reref.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_reref.m
| 12,991 |
utf_8
|
14d26bdeeaca5ad12a0890e8f01c25df
|
% pop_reref() - Convert an EEG dataset to average reference or to a
% new common reference channel (or channels). Calls reref().
% Usage:
% >> EEGOUT = pop_reref( EEG ); % pop up interactive window
% >> EEGOUT = pop_reref( EEG, ref, 'key', 'val' ...);
%
% Graphic interface:
% "Compute average reference" - [edit box] Checking this box (for 'yes') is
% the same as giving an empty value for the commandline 'ref'
% argument. Unchecked, the data are transformed to common reference.
% "Re-reference data to channel(s)" - [checkbox] Checking this option
% automatically unchecks the checkbox above, allowing reference
% channel indices to be entered in the text edit box to its right
% (No commandline equivalent).
% "Retain old reference channels in data" - [checkbox] When re-referencing the
% data, checking this checkbox includes the data for the
% previous reference channel.
% "Exclude channel indices (EMG, EOG)" - [edit box] exclude the given
% channel indices from rereferencing.
% "Add current reference channel back to the data" - [edit box] When
% re-referencing the data, checking this checkbox
% reconstitutes the data for the previous reference
% channel. If the location for this channel was not
% defined, it can be specified using the text box below.
% Inputs:
% EEG - input dataset
% ref - reference: [] = convert to average reference
% [int vector] = new reference electrode number(s)
% Optional inputs:
% 'exclude' - [integer array] List of channels to exclude. Default: none.
% 'keepref' - ['on'|'off'] keep the reference channel. Default: 'off'.
% 'refloc' - [structure] Previous reference channel structure. Default: none.
%
% Outputs:
% EEGOUT - re-referenced output dataset
%
% Notes:
% For other options, call reref() directly. See >> help reref
%
% Author: Arnaud Delorme, CNL / Salk Institute, 12 Nov 2002
%
% See also: reref(), eeglab()
% Copyright (C) 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, com] = pop_reref( EEG, ref, varargin);
com = '';
if nargin < 1
help pop_reref;
return;
end;
if isempty(EEG.data)
error('Pop_reref: cannot process empty data');
end;
% gui inputs
% ----------
orichanlocs = EEG.chanlocs;
orinbchan = EEG.nbchan;
if nargin < 2
% find initial reference
% ----------------------
if length(EEG.chanlocs) == EEG.nbchan+1
includeref = 1;
end;
geometry = { [1] [1] [1.8 1 0.3] [1] [1] [1.8 1 0.3] [1.8 1 0.3] };
cb_setref = [ 'set(findobj(''parent'', gcbf, ''tag'', ''refbr'') , ''enable'', ''on'');' ...
'set(findobj(''parent'', gcbf, ''tag'', ''reref'') , ''enable'', ''on'');' ...
'set(findobj(''parent'', gcbf, ''tag'', ''keepref'') , ''enable'', ''on'');' ];
cb_setave = [ 'set(findobj(''parent'', gcbf, ''tag'', ''refbr'') , ''enable'', ''off'');' ...
'set(findobj(''parent'', gcbf, ''tag'', ''reref'') , ''enable'', ''off'');' ...
'set(findobj(''parent'', gcbf, ''tag'', ''keepref'') , ''enable'', ''off'', ''value'', 0);' ];
cb_averef = [ 'set(findobj(''parent'', gcbf, ''tag'', ''rerefstr'') , ''value'', ~get(gcbo, ''value''));' ...
'if get(gcbo, ''value''),' cb_setave ...
'else,' cb_setref ...
'end;' ];
cb_ref = [ 'set(findobj(''parent'', gcbf, ''tag'', ''ave'') , ''value'', ~get(gcbo, ''value''));' ...
'if get(gcbo, ''value''),' cb_setref ...
'else,' cb_setave ...
'end;' ];
cb_chansel1 = 'tmpchanlocs = EEG(1).chanlocs; [tmp tmpval] = pop_chansel({tmpchanlocs.labels}, ''withindex'', ''on''); set(findobj(gcbf, ''tag'', ''reref'' ), ''string'',tmpval); clear tmpchanlocs tmp tmpval';
cb_chansel2 = 'tmpchanlocs = EEG(1).chanlocs; [tmp tmpval] = pop_chansel({tmpchanlocs.labels}, ''withindex'', ''on''); set(findobj(gcbf, ''tag'', ''exclude'' ), ''string'',tmpval); clear tmpchanlocs tmp tmpval';
cb_chansel3 = [ 'if ~isfield(EEG(1).chaninfo, ''nodatchans''), ' ...
' warndlg2(''There are no Reference channel defined, add it using the channel location editor'');' ...
'elseif isempty(EEG(1).chaninfo.nodatchans),' ...
' warndlg2(''There are no Reference channel defined, add it using the channel location editor'');' ...
'else,' ...
' tmpchaninfo = EEG(1).chaninfo; [tmp tmpval] = pop_chansel({tmpchaninfo.nodatchans.labels}, ''withindex'', ''on''); set(findobj(gcbf, ''tag'', ''refloc'' ), ''string'',tmpval); clear tmpchanlocs tmp tmpval;' ...
'end;' ];
if isempty(EEG.chanlocs), cb_chansel1 = ''; cb_chansel2 = ''; cb_chansel3 = ''; end;
% find current reference (= reference most used)
% ----------------------------------------------
if isfield(EEG(1).chanlocs, 'ref')
tmpchanlocs = EEG(1).chanlocs;
[curref tmp allinds] = unique_bc( { tmpchanlocs.ref });
maxind = 1;
for ind = unique_bc(allinds)
if length(find(allinds == ind)) > length(find(allinds == maxind))
maxind = ind;
end;
end;
curref = curref{maxind};
if isempty(curref), curref = 'unknown'; end;
else curref = 'unknown';
end;
uilist = { { 'style' 'text' 'string' [ 'Current data reference state is: ' curref] } ...
...
{ 'style' 'checkbox' 'tag' 'ave' 'value' 1 'string' 'Compute average reference' 'callback' cb_averef } ...
...
{ 'style' 'checkbox' 'tag' 'rerefstr' 'value' 0 'string' 'Re-reference data to channel(s):' 'callback' cb_ref } ...
{ 'style' 'edit' 'tag' 'reref' 'string' '' 'enable' 'off' } ...
{ 'style' 'pushbutton' 'string' '...' 'callback' cb_chansel1 'enable' 'off' 'tag' 'refbr' } ...
...
{} ...
...
{ 'style' 'checkbox' 'value' 0 'enable' 'off' 'tag' 'keepref' 'string' 'Retain old reference channels in data' } ...
...
{ 'style' 'text' 'string' 'Exclude channel indices (EMG, EOG)' } ...
{ 'style' 'edit' 'tag' 'exclude' 'string' '' } ...
{ 'style' 'pushbutton' 'string' '...' 'callback' cb_chansel2 } ...
...
{ 'style' 'text' 'tag' 'reflocstr' 'string' 'Add current reference channel back to the data' } ...
{ 'style' 'edit' 'tag' 'refloc' 'string' '' } ...
{ 'style' 'pushbutton' 'string' '...' 'callback' cb_chansel3 } };
[result tmp tmp2 restag] = inputgui(geometry, uilist, 'pophelp(''pop_reref'')', 'pop_reref - average reference or re-reference data');
if isempty(result), return; end;
% decode inputs
% -------------
options = {};
if ~isempty(restag.refloc),
try
tmpchaninfo = EEG.chaninfo;
tmpallchans = lower({ tmpchaninfo.nodatchans.labels });
allelecs = parsetxt(lower(restag.refloc));
chanind = [];
for iElec = 1:length(allelecs)
chanind = [chanind strmatch( allelecs{iElec}, tmpallchans, 'exact') ];
end;
options = { options{:} 'refloc' EEG.chaninfo.nodatchans(chanind) };
catch, disp('Error with old reference: ignoring it');
end;
end;
if ~isempty(restag.exclude), options = { options{:} 'exclude' eeg_chaninds(EEG, restag.exclude) }; end;
if restag.keepref, options = { options{:} 'keepref' 'on' }; end;
if restag.ave, ref = []; end;
if restag.rerefstr
if isempty(restag.reref)
warndlg2('Abording: you must enter one or more reference channels');
return;
else
ref = eeg_chaninds(EEG, restag.reref);
end;
end;
else
options = varargin;
end;
optionscall = options;
% include channel location file
% -----------------------------
if ~isempty(EEG.chanlocs)
optionscall = { optionscall{:} 'elocs' EEG.chanlocs };
end;
nchans = EEG.nbchan;
fprintf('Re-referencing data\n');
oldchanlocs = EEG.chanlocs;
[EEG.data EEG.chanlocs refchan ] = reref(EEG.data, ref, optionscall{:});
g = struct(optionscall{:});
if ~isfield(g, 'exclude'), g.exclude = []; end;
if ~isfield(g, 'keepref'), g.keepref = 'off'; end;
if ~isfield(g, 'refloc') , g.refloc = []; end;
% deal with reference
% -------------------
if ~isempty(refchan)
if ~isfield(EEG.chaninfo, 'nodatchans')
EEG.chaninfo.nodatchans = refchan;
elseif isempty(EEG.chaninfo.nodatchans)
EEG.chaninfo.nodatchans = refchan;
else
allf = fieldnames(refchan);
n = length(EEG.chaninfo.nodatchans);
for ind = 1:length(allf)
EEG.chaninfo.nodatchans = setfield(EEG.chaninfo.nodatchans, { n }, ...
allf{ind}, getfield(refchan, allf{ind}));
end;
end;
end;
if ~isempty(g.refloc)
allinds = [];
tmpchaninfo = EEG.chaninfo;
for iElec = 1:length(g.refloc)
allinds = [allinds strmatch( g.refloc(iElec).labels, { tmpchaninfo.nodatchans.labels }) ];
end;
EEG.chaninfo.nodatchans(allinds) = [];
end;
% legacy EEG.ref field
% --------------------
if isfield(EEG, 'ref')
if strcmpi(EEG.ref, 'common') && isempty(ref)
EEG.ref = 'averef';
elseif strcmpi(EEG.ref, 'averef') && ~isempty(ref)
EEG.ref = 'common';
end;
end;
EEG.nbchan = size(EEG.data,1);
EEG = eeg_checkset(EEG);
% include ICA or not
% ------------------
if ~isempty(EEG.icaweights)
if ~isempty(intersect(EEG.icachansind, g.exclude))
disp('Warning: some channels used for ICA were excluded from referencing');
disp(' the ICA decomposition has been removed');
EEG.icaweights = [];
EEG.icasphere = [];
elseif length(EEG.icachansind) ~= nchans - length(g.exclude)
disp('Error: some channels not used for ICA decomposition are used for rereferencing');
disp(' the ICA decomposition has been removed');
EEG.icaweights = [];
EEG.icasphere = [];
else
fprintf('Re-referencing ICA matrix\n');
if isempty(orichanlocs)
error('Cannot re-reference ICA decomposition without channel locations')
end;
newICAchaninds = zeros(orinbchan, size(EEG.icawinv,2));
newICAchaninds(EEG.icachansind,:) = EEG.icawinv;
[newICAchaninds newchanlocs] = reref(newICAchaninds, ref, optionscall{:});
% convert channel indices in icachanlocs (uses channel labels)
% ------------------------------------------------------------
icachansind = EEG.icachansind;
rminds = [1:size(newICAchaninds,1)];
for i=length(icachansind):-1:1
oldLabel = orichanlocs(icachansind(i)).labels;
newLabelPos = strmatch(oldLabel, { newchanlocs.labels }, 'exact');
if ~isempty( newLabelPos )
icachansind(i) = newLabelPos;
rminds(find(icachansind(i) == rminds)) = [];
else
icachansind(i) = [];
end;
end;
newICAchaninds(rminds,:) = [];
EEG.icawinv = newICAchaninds;
EEG.icachansind = icachansind;
if length(EEG.icachansind) ~= size(EEG.icawinv,1)
warning('Wrong channel indices, removing ICA decomposition');
EEG.icaweights = [];
EEG.icasphere = [];
else
EEG.icaweights = pinv(EEG.icawinv);
EEG.icasphere = eye(length(icachansind));
end;
end;
EEG = eeg_checkset(EEG);
end;
% generate the output command
% ---------------------------
com = sprintf('%s = pop_reref( %s, %s);', inputname(1), inputname(1), vararg2str({ref, options{:}}));
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_dipselect.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_dipselect.m
| 2,895 |
utf_8
|
b9770dbf991cd2bc42e30f80792ce7a4
|
% eeg_dipselect() - select componet dipoles from an EEG dataset with
% reisdual variance (rv) less than a selected threshold
% and equivalent dipole location inside the brain volume.
% Usage:
% >> selctedComponents = eeg_dipselect(EEG, rvThreshold, selectionType, depthThreshold)
%
% Inputs:
% EEG - EEGLAB dataset structure
%
% Optional Inputs
% rvThreshold - residual variance threshold (%). Dipoles with residual variance
% less than this value will be selected. {default = 15}
% selectionType - criteria for selecting dipoles:
% 'rv' = only by residual variance,
% 'inbrain' = inside brain volume and residual variance.
% {default = 'inbrain'}
%
% depthThreshold - maximum accepted distance outside brain volume (mm) {default = 1}
%
% Outputs:
% selctedComponents - vector of selected components
%
% Example:
% >> selctedComponents = eeg_dipselect(EEG) % select in-brain dipoles with rv less than 0.15 (default value)
% >> selctedComponents = eeg_dipselect(EEG, 20,'rv') % select dipoles with rv less than 0.2
%
% Author: Nima Bigdely Shamlo, Copyright (C) September 2007
% based on an script from Julie Onton and sourcedepth() function
% provided by Robert Oostenveld.
%
% See also: sourcedepth()
function brainComponents = eeg_dipselect(EEG, rvThreshold, selectionType, depthThreshold);
if nargin<2
rvThreshold = 0.15;
fprintf('Maximum residual variance for selected dipoles set to %1.2f (default).\n',rvThreshold);
else
rvThreshold = rvThreshold/100; % change from percent to value
if rvThreshold>1
error('Error: residual variance threshold should be less than 1.\n');
end;
end
if nargin<4
depthThreshold = 1;
end;
% find components with low residual variance
for ic = 1:length(EEG.dipfit.model)
residualvariance(1,ic) =EEG.dipfit.model(ic).rv;
end;
compLowResidualvariance = find(residualvariance <rvThreshold);
if isempty(compLowResidualvariance) || ( (nargin>=3) && strcmp(selectionType, 'rv')) % if only rv is requested (not in-brain)
brainComponents = compLowResidualvariance;
return;
else
if ~exist('ft_sourcedepth')
selectionType = 'rv';
tmpWarning = warning('backtrace');
warning backtrace off;
warning('You need to install the Fieldtrip extension to be able to select "in brain" dipoles');
warning(tmpWarning);
brainComponents = compLowResidualvariance;
return;
end;
load(EEG.dipfit.hdmfile);
posxyz = [];
for c = compLowResidualvariance
posxyz = cat(1,posxyz,EEG.dipfit.model(c).posxyz(1,:));
end;
depth = ft_sourcedepth(posxyz, vol);
brainComponents = compLowResidualvariance(find(depth<=depthThreshold));
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_loadcnt.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_loadcnt.m
| 9,914 |
utf_8
|
196225b3e7d78dc84817620c2a7cffab
|
% pop_loadcnt() - load a neuroscan CNT file (pop out window if no arguments).
%
% Usage:
% >> EEG = pop_loadcnt; % pop-up window mode
% >> EEG = pop_loadcnt( filename, 'key', 'val', ...);
%
% Graphic interface:
% "Data fomat" - [checkbox] 16-bits or 32-bits. We couldn't find in the
% data file where this information was stored. Command
% line equivalent in loadcnt() 'dataformat'.
% "Time interval in seconds" - [edit box] specify time interval [min max]
% to import portion of data. Command line equivalent
% in loadcnt: 't1' and 'lddur'
% "Import keystrokes" - [checkbox] set this option to import keystroke
% event types in dataset. Command line equivalent
% 'keystroke'.
% "loadcnt() 'key', 'val' params" - [edit box] Enter optional loadcnt()
% parameters.
%
% Inputs:
% filename - file name
%
% Optional inputs:
% 'keystroke' - ['on'|'off'] set the option to 'on' to import
% keystroke event types. Default is off.
% 'memmapfile' - ['memmapfile_name'] use this option if the .cnt file
% is too large to read in conventially. The suffix of
% the memmapfile_name must be .fdt. the memmapfile
% functions process files based on their suffix and an
% error will occur if you use a different suffix.
% Same as loadcnt() function.
%
% Outputs:
% EEG - EEGLAB data structure
%
% Note:
% 1) This function extract all non-null event from the CNT data structure.
% Null events are usually associated with internal signals (recalibrations...).
% 2) The "Average reference" edit box had been remove since the re-referencing
% menu of EEGLAB offers more options to re-reference data.
% 3) The 'blockread' has been disabled since we found where this information
% was stored in the file.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: loadcnt(), 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
function [EEG, command] = pop_loadcnt(filename, varargin);
command = '';
EEG = [];
if nargin < 1
% ask user
[filename, filepath] = uigetfile('*.CNT;*.cnt', 'Choose a CNT file -- pop_loadcnt()');
drawnow;
if filename == 0 return; end;
% popup window parameters
% -----------------------
callback16 = 'set(findobj(gcbf, ''tag'', ''B32''), ''value'', ~get(gcbo, ''value'')); set(findobj(gcbf, ''tag'', ''AD''), ''value'', ~get(gcbo, ''value''));';
callback32 = 'set(findobj(gcbf, ''tag'', ''B16''), ''value'', ~get(gcbo, ''value'')); set(findobj(gcbf, ''tag'', ''AD''), ''value'', ~get(gcbo, ''value''));';
callbackAD = 'set(findobj(gcbf, ''tag'', ''B16''), ''value'', ~get(gcbo, ''value'')); set(findobj(gcbf, ''tag'', ''B32''), ''value'', ~get(gcbo, ''value''));';
uigeom = { [1.3 0.5 0.5 0.5] [1 0.5] [1.09 0.13 0.4] [1 0.5] [1 0.5] 1 } ;
uilist = { { 'style' 'text' 'string' 'Data format 16 or 32 bit (Default = Autodetect)' } ...
{ 'style' 'checkbox' 'tag' 'B16' 'string' '16-bits' 'value' 0 'callback' callback16 } ...
{ 'style' 'checkbox' 'tag' 'B32' 'string' '32-bits' 'value' 0 'callback' callback32 } ...
{ 'style' 'checkbox' 'tag' 'AD' 'string' 'Autodetect' 'value' 1 'callback' callbackAD } ...
{ 'style' 'text' 'string' 'Time interval in s (i.e. [0 100]):' } ...
{ 'style' 'edit' 'string' '' 'callback' 'warndlg2([ ''Events latency might be innacurate when'' 10 ''importing time intervals (this is an open issue)'']);' } ...
{ 'style' 'text' 'string' 'Check to Import keystrokes:' } ...
{ 'style' 'checkbox' 'string' '' } { } ...
{ 'style' 'text' 'string' 'loadcnt() ''key'', ''val'' params' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'string' [ 'Large files, enter a file name for memory mapping (xxx.fdt)' ] } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'string' ' Note: requires to enable memory mapping in EEGLAB memory options and only works for 32-bit files' } };
result = inputgui( uigeom, uilist, 'pophelp(''pop_loadcnt'')', 'Load a CNT dataset');
if length( result ) == 0 return; end;
% decode parameters
% -----------------
options = [];
if result{1}, options = [ options ', ''dataformat'', ''int16''' ];
elseif result{2}, options = [ options ', ''dataformat'', ''int32''' ];
elseif result{3}, options = [ options ', ''dataformat'', ''auto''' ];
end;
if ~isempty(result{4}),
timer = eval( [ '[' result{4} ']' ]);
options = [ options ', ''t1'', ' num2str(timer(1)) ', ''lddur'', ' num2str(timer(2)-timer(1)) ];
end;
if result{5}, options = [ options ', ''keystroke'', ''on''' ]; end;
if ~isempty(result{6}), options = [ options ',' result{6} ]; end;
% Conditional pass if ~isempty(result{7}), options = ...
% [options ', ''memmapfile''', result{7} ] ; end ;
% Always pass the memmapfile paramter?
options = [ options ', ''memmapfile'', ''', result{7} '''' ] ;
else
options = vararg2str(varargin);
end;
% load datas
% ----------
EEG = eeg_emptyset;
if exist('filepath')
fullFileName = sprintf('%s%s', filepath, filename);
else
fullFileName = filename;
end;
if nargin > 0
if ~isempty(varargin)
r = loadcnt( fullFileName, varargin{:});
else
r = loadcnt( fullFileName);
end;
else
eval( [ 'r = loadcnt( fullFileName ' options ');' ]);
end;
if isfield(r, 'dat')
error('pop_loadcnt is not compatible with current loadcnt version, please use latest loadcnt() version');
end;
% Check to see if data is in memory or in a file.
EEG.data = r.data;
EEG.comments = [ 'Original file: ' fullFileName ];
EEG.setname = 'CNT file';
EEG.nbchan = r.header.nchannels;
% inport events
% -------------
I = 1:length(r.event);
if ~isempty(I)
EEG.event(1:length(I),1) = [ r.event(I).stimtype ];
EEG.event(1:length(I),2) = [ r.event(I).offset ]+1;
EEG.event = eeg_eventformat (EEG.event, 'struct', { 'type' 'latency' });
end;
% modified by Andreas Widmann 2005/05/12 14:15:00
try, % this piece of code makes the function crash sometimes - Arnaud Delorme 2006/04/27
temp = find([r.event.accept_ev1] == 14 | [r.event.accept_ev1] == 11); % 14: Discontinuity, 11: DC reset
if ~isempty(temp)
disp('pop_loadcnt note: event field ''type'' set to ''boundary'' for data discontinuities');
for index = 1:length(temp)
EEG.event(temp(index)).type = 'boundary';
end;
end
catch, end;
% end modification
% process keyboard entries
% ------------------------
if ~isempty(findstr('keystroke', lower(options)))
tmpkbd = [ r.event(I).keyboard ];
tmpkbd2 = [ r.event(I).keypad_accept ];
for index = 1:length(EEG.event)
if EEG.event(index).type == 0
if r.event(index).keypad_accept,
EEG.event(index).type = [ 'keypad' num2str(r.event(index).keypad_accept) ];
else
EEG.event(index).type = [ 'keyboard' num2str(r.event(index).keyboard) ];
end;
end;
end;
else
% removeing keystroke events
% --------------------------
rmind = [];
for index = 1:length(EEG.event)
if EEG.event(index).type == 0
rmind = [rmind index];
end;
end;
if ~isempty(rmind)
fprintf('Ignoring %d keystroke events\n', length(rmind));
EEG.event(rmind) = [];
end;
end;
% import channel locations (Neuroscan coordinates are not wrong)
% ------------------------
%x = celltomat( { r.electloc.x_coord } );
%y = celltomat( { r.electloc.y_coord } );
for index = 1:length(r.electloc)
names{index} = deblank(char(r.electloc(index).lab'));
if size(names{index},1) > size(names{index},2), names{index} = names{index}'; end;
end;
EEG.chanlocs = struct('labels', names);
%EEG.chanlocs = readneurolocs( { names x y } );
%disp('WARNING: Electrode locations imported from CNT files may not reflect true locations');
% Check to see if data is in a file or in memory
% If in memory, leave alone
% If in a file, use values set in loadcnt.m for nbchan and pnts.
EEG.srate = r.header.rate;
EEG.nbchan = size(EEG.data,1) ;
EEG.nbchan = r.header.nchannels ;
% EEG.nbchan = size(EEG.data,1);
EEG.trials = 1;
EEG.pnts = r.ldnsamples ;
%size(EEG.data,2)
%EEG.pnts = r.header.pnts
%size(EEG.data,2);
EEG = eeg_checkset(EEG, 'eventconsistency');
EEG = eeg_checkset(EEG, 'makeur');
if ((size(EEG.data,1) ~= EEG.nbchan) && (size(EEG.data,2) ~= EEG.pnts))
% Assume a data file
EEG = eeg_checkset(EEG, 'loaddata');
end
if length(options) > 2
command = sprintf('EEG = pop_loadcnt(''%s'' %s);',fullFileName, options);
else
command = sprintf('EEG = pop_loadcnt(''%s'');',fullFileName);
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_amplitudearea.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_amplitudearea.m
| 7,019 |
utf_8
|
712e8efc8565d2b601dd9ec225a4d36c
|
% eeg_amplitudearea() - Resamples an ERP average using spline interpolation
% at a new sample rate (resrate) in Hz to get the exact limits
% of the window of integration. Finely samples the window
% and adds together very narrow rectangles capped by
% right-angled triangles under the window. Output is in uV.
% Trade-off between speed and number of resamples and number of
% channels selected occurs.
% Usage:
% >> [channels, amplitude] = eeg_amplitudearea(EEG,channels, resrate, wstart, wend);
% Inputs:
% EEG - EEGLAB data struct containing a (3-D) epoched data matrix
% channels - vector of channel indices
% resrate - resampling rate for window of integration in Hz
% wstart - start of window of integration in ms post stimulus-onset
% wend - end of window of integration in ms post stimulus-onset
%
% Outputs:
% channels - a vector of channel indices.
% amplitude - 1-dimensional array in uV for the channels
%
% Example
% >> [channels, amplitude] = eeg_amplitudearea(EEG,[12 18 25 29], 2000, 90.52, 120.52);
%
% Author: Tom Campbell, Helsinki Collegium for Advanced Studies, Biomag Laboratory,
% Engineering Centre, Helsinki University Central Hospital Helsinki Brain
% Research Centre ([email protected]) Spartam nanctus es: Hanc exorna.
% Combined with amplitudearea_msuV() by Darren Weber, UCSF 28/1/05
% Retested and debugged Tom Campbell 2/2/05
% Reconceived, factored somewhat, tested and debugged Tom Campbell 13:24 23.3.2005
function [channels,overall_amplitude] = eeg_amplitudearea2(EEG, channels, resrate, wstart, wend)
if wstart > wend
error ('ERROR: wstart must be greater than wend')
else
[channels, overall_amplitude] = eeg_amplitudearea_msuV (EEG,channels, resrate, wstart, wend)
overall_amplitude = overall_amplitude/(wend - wstart)
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [channels, overall_area] = eeg_amplitudearea_msuV (EEG, channels, resrate, wstart, wend)
%if ndim(EEG.data) ~= 3
% error('EEG.data must be 3-D data epochs');
%end
erp = mean(EEG.data,3);
[tmp ind1] =min( abs( EEG.times - wstart ) ); % closest time index to wstart
[tmp ind2] =min( abs( EEG.times - wend ) ); % closest time index to wend
restep = 1/resrate
if EEG.times(ind1) > wstart
ind1= ind1 -1;
end
if EEG.times(ind2) < wend
ind2= ind2 +1;
end
for x= ind1:ind2
t = (x -ind1)+1;
tim(t) = EEG.times(x);
end
tr = 1
timr(tr) = wstart;
while timr(tr) < wend
tr = tr + 1;
timr(tr) = timr(tr-1)+ restep;
end
for x = 1:size(channels,2)
channel = channels(x)
%resamples
rerp(x, 1:tr) = spline(tim(:),erp(channel, ind1:ind2), timr(1:tr))
pent = timr(tr - 1)
overall_area(x) = 0
for y = 1:(tr -1)
v1 = rerp(x,(y))
v2 = rerp(x,(y+1))
if ((v1 > 0) & (v2 < 0)) | ((v1 < 0) & (v2 > 0))
if (y == (tr-1)) & (timr(y+1)> wend)
area1 = zero_crossing_truncated(v1, v2, restep, wend, pent)
else
area1 = zero_crossing(v1, v2, restep)
end
else
if( y == (tr-1)) & (timr(y+1)> wend)
area1 = rect_tri_truncated(v1, v2, restep,wend,pent)
else
area1 = rect_tri(v1, v2, restep)
end
end
overall_area(x) = overall_area(x) + area1
end
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [area] = zero_crossing(v1,v2,step)
if (v1 > v2)
T1 = v1
T2 = v2
else
T1 = v2
T2 = v1
end
tantheta = (abs(T1)+ abs(T2))/step
if (v1 > v2)
%decline
z = abs(T1)/tantheta
tr1= abs(T1)*(z/2)
tr2= abs(T2)*((step-z)/2)
else
%incline
z = abs(T2)/tantheta
tr2= abs(T2)*(z/2)
tr1= abs(T1)*((step-z)/2)
end
[area] = (tr1 - tr2)
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [area] = zero_crossing_truncated(v1,v2,step,wend,pent)
if (v1 > v2)
T1 = v1
T2 = v2
else
T1 = v2
T2 = v1
end
tantheta = (abs(T1)+ abs(T2))/step
s = wend - pent
if (v1 > v2)
z = abs(T1)/tantheta
if s < z
%decline,truncated before zerocrossing
t1 = tantheta * s
r1 = abs(T1)-abs(t1)
tr1= abs(t1)*(s/2)
tr2= 0
rect1 = r1*s
rect2 = 0
else
%decline,truncated after zerocrossing
t2= tantheta*(s-z)
tr1= abs(T1)*(z/2)
tr2 = abs(t2)*((s-z)/2)
rect1 = 0
rect2 = 0
end
else
z = abs(T2)/tantheta
if s < z
%incline,truncated before zerocrossing
t2 = tantheta * s
r2 = abs(T2)-abs(t2)
tr1= 0
tr2= abs(t2)*(s/2)
rect1 = 0
rect2 = r2*s
else
%incline,truncated after zerocrossing
t1= tantheta*(s-z)
tr1 = abs(t1)*((s-z)/2)
tr2 = abs(T2) * (z/2)
rect1 = 0
rect2 = 0
end
end
[area] = ((rect1 + tr1) - (rect2 + tr2))
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [area] = rect_tri(v1,v2,step)
if (abs(v1) > abs(v2))
T = abs(v1)-abs(v2)
R = abs(v2)
else
T = abs(v2)-abs(v1)
R = abs(v1)
end
rect = R*step
tri = T*(step/2)
if v1 > 0
area = 1* (rect+tri)
else
area = -1 * (rect+tri)
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [area] = rect_tri_truncated(v1,v2,step,wend,pent)
if (abs(v1) > abs(v2))
T = abs(v1)-abs(v2)
R = abs(v2)
else
T = abs(v2)-abs(v1)
R = abs(v1)
end
tantheta = abs(T)/step
s = wend -pent
if (v1>0)
if v1 >v2
%positive decline
t = tantheta*s
e = abs(T)-abs(t)
rect = s*R
exrect = s*e
tri = (s/2)*R
else
%positive incline
t = tantheta*s
rect = s*R
exrect = 0
tri = (s/2)*R
end
else
if v1 >v2
%negative decline
t = tantheta*s
rect = s*R
exrect = 0
tri = (s/2)*R
else
%negative incline
t = tantheta*s
e = abs(T)-abs(t)
rect = s*R
exrect = s*e
tri = (s/2)*R
end
end
tri = T*(step/2)
if v1 > 0
area = 1* (rect+exrect+tri)
else
area = -1 * (rect+exrect+tri)
end
return
|
github
|
ZijingMao/baselineeegtest-master
|
pop_eegplot.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_eegplot.m
| 9,306 |
utf_8
|
f7fe5ffcd511733cac5bd8dbec00bdb2
|
% pop_eegplot() - Visually inspect EEG data using a scrolling display.
% Perform rejection or marking for rejection of visually
% (and/or previously) selected data portions (i.e., stretches
% of continuous data or whole data epochs).
% Usage:
% >> pop_eegplot( EEG ) % Scroll EEG channel data. Allow marking for rejection via
% % button 'Update Marks' but perform no actual data rejection.
% % Do not show or use marks from previous visual inspections
% % or from semi-auotmatic rejection.
% >> pop_eegplot( EEG, typerej, superpose, reject );
%
% Graphic interface:
% "Add to previously marked rejections" - [edit box] Either YES or NO.
% Command line equivalent: 'superpose'.
% "Reject marked trials" - [edit box] Either YES or NO. Command line
% equivalent 'reject'.
% Inputs:
% EEG - input EEG dataset
% typerej - type of rejection 0 = independent components;
% 1 = data channels. {Default: 1 = data channels}
% superpose - 0 = Show new marks only: Do not color the background of data portions
% previously marked for rejection by visual inspection. Mark new data
% portions for rejection by first coloring them (by dragging the left
% mouse button), finally pressing the 'Update Marks' or 'Reject'
% buttons (see 'reject' below). Previous markings from visual inspection
% will be lost.
% 1 = Show data portions previously marked by visual inspection plus
% data portions selected in this window for rejection (by dragging
% the left mouse button in this window). These are differentiated
% using a lighter and darker hue, respectively). Pressing the
% 'Update Marks' or 'Reject' buttons (see 'reject' below)
% will then mark or reject all the colored data portions.
% {Default: 0, show and act on new marks only}
% reject - 0 = Mark for rejection. Mark data portions by dragging the left mouse
% button on the data windows (producing a background coloring indicating
% the extent of the marked data portion). Then press the screen button
% 'Update Marks' to store the data portions marked for rejection
% (stretches of continuous data or whole data epochs). No 'Reject' button
% is present, so data marked for rejection cannot be actually rejected
% from this eegplot() window.
% 1 = Reject marked trials. After inspecting/selecting data portions for
% rejection, press button 'Reject' to reject (remove) them from the EEG
% dataset (i.e., those portions plottted on a colored background.
% {default: 0, mark for rejection only}
% Outputs:
% Modifications are applied to the current EEG dataset at the end of the
% eegplot() call, when the user presses the 'Update Marks' or 'Reject' button.
% NOTE: The modifications made are not saved into EEGLAB history. As of v4.2,
% events contained in rejected data portions are remembered in the EEG.urevent
% structure (see EEGLAB tutorial).
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: 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
% 01-25-02 reformated help & license -ad
% 03-07-02 added srate argument to eegplot call -ad
% 03-27-02 added event latency recalculation for continuous data -ad
function com = pop_eegplot( EEG, icacomp, superpose, reject, topcommand, varargin)
com = '';
if nargin < 1
help pop_eegplot;
return;
end;
if nargin < 2
icacomp = 1;
end;
if nargin < 3
superpose = 0;
end;
if nargin < 4
reject = 1;
end;
if icacomp == 0
if isempty( EEG.icasphere )
disp('Error: you must run ICA first'); return;
end;
end;
if nargin < 3 & EEG.trials > 1
% which set to save
% -----------------
uilist = { { 'style' 'text' 'string' 'Add to previously marked rejections? (checked=yes)'} , ...
{ 'style' 'checkbox' 'string' '' 'value' 1 } , ...
{ 'style' 'text' 'string' 'Reject marked trials? (checked=yes)'} , ...
{ 'style' 'checkbox' 'string' '' 'value' 0 } };
result = inputgui( { [ 2 0.2] [ 2 0.2]} , uilist, 'pophelp(''pop_eegplot'');', ...
fastif(icacomp==0, 'Manual component rejection -- pop_eegplot()', ...
'Reject epochs by visual inspection -- pop_eegplot()'));
size_result = size( result );
if size_result(1) == 0 return; end;
if result{1}, superpose=1; end;
if ~result{2}, reject=0; end;
end;
if EEG.trials > 1
if icacomp == 1 macrorej = 'EEG.reject.rejmanual';
macrorejE = 'EEG.reject.rejmanualE';
else macrorej = 'EEG.reject.icarejmanual';
macrorejE = 'EEG.reject.icarejmanualE';
end;
if icacomp == 1
elecrange = [1:EEG.nbchan];
else elecrange = [1:size(EEG.icaweights,1)];
end;
colrej = EEG.reject.rejmanualcol;
rej = eval(macrorej);
rejE = eval(macrorejE);
eeg_rejmacro; % script macro for generating command and old rejection arrays
else % case of a single trial (continuous data)
%if icacomp,
% command = ['if isempty(EEG.event) EEG.event = [eegplot2event(TMPREJ, -1)];' ...
% 'else EEG.event = [EEG.event(find(EEG.event(:,1) ~= -1),:); eegplot2event(TMPREJ, -1, [], [0.8 1 0.8])];' ...
% 'end;'];
%else, command = ['if isempty(EEG.event) EEG.event = [eegplot2event(TMPREJ, -1)];' ...
% 'else EEG.event = [EEG.event(find(EEG.event(:,1) ~= -2),:); eegplot2event(TMPREJ, -1, [], [0.8 1 0.8])];' ...
% 'end;'];
%end;
%if reject
% command = ...
% [ command ...
% '[EEG.data EEG.xmax] = eegrej(EEG.data, EEG.event(find(EEG.event(:,1) < 0),3:end), EEG.xmax-EEG.xmin);' ...
% 'EEG.xmax = EEG.xmax+EEG.xmin;' ...
% 'EEG.event = EEG.event(find(EEG.event(:,1) >= 0),:);' ...
% 'EEG.icaact = [];' ...
% 'EEG = eeg_checkset(EEG);' ];
eeglab_options; % changed from eeglaboptions 3/30/02 -sm
if reject == 0, command = [];
else
command = ...
[ '[EEGTMP LASTCOM] = eeg_eegrej(EEG,eegplot2event(TMPREJ, -1));' ...
'if ~isempty(LASTCOM),' ...
' [ALLEEG EEG CURRENTSET tmpcom] = pop_newset(ALLEEG, EEGTMP, CURRENTSET);' ...
' if ~isempty(tmpcom),' ...
' EEG = eegh(LASTCOM, EEG);' ...
' eegh(tmpcom);' ...
' eeglab(''redraw'');' ...
' end;' ...
'end;' ...
'clear EEGTMP tmpcom;' ];
if nargin < 4
res = questdlg2( strvcat('Mark stretches of continuous data for rejection', ...
'by dragging the left mouse button. Click on marked', ...
'stretches to unmark. When done,press "REJECT" to', ...
'excise marked stretches (Note: Leaves rejection', ...
'boundary markers in the event table).'), 'Warning', 'Cancel', 'Continue', 'Continue');
if strcmpi(res, 'Cancel'), return; end;
end;
end;
eegplotoptions = { 'events', EEG.event };
if ~isempty(EEG.chanlocs) & icacomp
eegplotoptions = { eegplotoptions{:} 'eloc_file', EEG.chanlocs };
end;
end;
if EEG.nbchan > 100
disp('pop_eegplot() note: Baseline subtraction disabled to speed up display');
eegplotoptions = { eegplotoptions{:} 'submean' 'off' };
end;
if icacomp == 1
eegplot( EEG.data, 'srate', EEG.srate, 'title', 'Scroll channel activities -- eegplot()', ...
'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}, varargin{:});
else
tmpdata = eeg_getdatact(EEG, 'component', [1:size(EEG.icaweights,1)]);
eegplot( tmpdata, 'srate', EEG.srate, 'title', 'Scroll component activities -- eegplot()', ...
'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}, varargin{:});
end;
com = [ com sprintf('pop_eegplot( %s, %d, %d, %d);', inputname(1), icacomp, superpose, reject) ];
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_editset.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_editset.m
| 29,463 |
utf_8
|
1066952edf9caed66b7e3396d8f2f5f7
|
% pop_editset() - Edit EEG dataset structure fields.
%
% Usage:
% >> EEGOUT = pop_editset( EEG ); % pops-up a data entry window
% >> EEGOUT = pop_editset( EEG, 'key', val,...); % no pop-up window
%
% Graphic interface:
% "Dataset name" - [Edit box] Name for the new dataset.
% In the right column of the graphic interface, the "EEG.setname"
% text indicates which field of the EEG structure this parameter
% corresponds to (in this case, .'setname').
% Command line equivalent: 'setname'.
% "Data sampling rate" - [Edit box] In Hz. Command line equivalent: 'srate'
% "Time points per epoch" - [Edit box] Number of data frames (points) per epoch.
% Changing this value will change the number of data epochs.
% Command line equivalent: 'pnts'.
% "Start time" - [Edit box] This edit box is only present for epoched data
% and specifies the epoch start time in ms. Epoch end time
% is automatically calculated. Command line equivalent: 'xmin'
% "Number of channels" - [Edit box] Number of data channels. Command line
% equivalent: 'nbchan'. This edit box cannot be edited.
% "Ref. channel indices or mode" - [edit box] current reference. This edit box
% cannot be edited. To change the data reference, use menu item,
% 'Tools > Re-reference', calling function pop_reref(). The
% reference can be either a string (channel name), 'common',
% indicating an unknown common reference, 'averef' indicating
% average reference, or an array of integers containing indices
% of the reference channel(s).
% "Subject code" - [Edit box] subject code. For example, 'S01'. The command
% line equivalent is 'subject'.
% "Task Condition" - [Edit box] task condition. For example, 'Targets'.
% The command line equivalent 'condition'.
% "Session number" - [Edit box] session number (from the same subject).
% All datasets from the same subject and session will be
% assumed to use the same ICA decomposition. The command
% line equivalent 'session'.
% "Subject group" - [Edit box] subject group. For example 'Patients' or
% 'Control'. The command line equivalent is 'group'.
% "About this dataset" - [Edit box] Comments about the dataset. Command line
% equivalent is 'comments'.
% "Channel locations file or array" - [Edit box] For channel data formats, see
% >> readlocs help Command line equivalent: 'chanlocs'
% "ICA weights array or text/binary file" - [edit box] Import ICA weights from
% other decompositions (e.g., same session, different conditions).
% To use the ICA weights from another loaded dataset (n), enter
% ALLEEG(n).icaweights. Command line equivalent: 'icaweights'
% "ICA sphere array or text/binary file" - [edit box] Import ICA sphere matrix.
% In EEGLAB, ICA decompositions require a sphere matrix and
% an unmixing weight matrix (see above). To use the sphere
% matrix from a loaded dataset (n), enter ALLEEG(n).icasphere
% Command line equivalent: 'icasphere'.
% "From other dataset" - [push button] Press this button to enter the index
% of another dataset. This will update the channel locations or
% the ICA edit box.
% Inputs:
% EEG - EEG dataset structure
%
% Optional inputs:
% 'setname' - Name of the EEG dataset
% 'data' - ['varname'|'filename'] Import data from a Matlab variable or
% mat file into an EEG data structure
% 'dataformat' - ['array|matlab|ascii|float32le|float32be'] Input data format.
% 'array' is a Matlab array in the global workspace.
% 'matlab' is a Matlab file (containing a single variable).
% 'ascii' is an ascii file.
% 'float32le' and 'float32be' are 32-bit float data files
% with little-endian and big-endian byte order, respectively.
% Data must be organised as 2-D (channels, timepoints), i.e.
% channels = rows, timepoints = columns; else as 3-D (channels,
% timepoints, epochs). For convenience, the data file is
% transposed if the number of rows is larger than the number
% of columns, as the program assumes that there are more
% channels than data points.
% 'subject' - [string] subject code. For example, 'S01'.
% {default: none -> each dataset from a different subject}
% 'condition' - [string] task condition. For example, 'Targets'
% {default: none -> all datasets from one condition}
% 'group' - [string] subject group. For example 'Patients' or 'Control'.
% {default: none -> all subjects in one group}
% 'session' - [integer] session number (from the same subject). All datasets
% from the same subject and session will be assumed to use the
% same ICA decomposition {default: none -> each dataset from
% a different session}
% 'chanlocs' - ['varname'|'filename'] Import a channel location file.
% For file formats, see >> help readlocs
% 'nbchan' - [int] Number of data channels.
% 'xmin' - [real] Data epoch start time (in seconds).
% {default: 0}
% 'pnts' - [int] Number of data points per data epoch. The number of
% data trials is automatically calculated.
% {default: length of the data -> continuous data assumed}
% 'srate' - [real] Data sampling rate in Hz {default: 1Hz}
% 'ref' - [string or integer] reference channel indices; 'averef'
% indicates average reference. Note that this does not perform
% referencing but only sets the initial reference when the data
% are imported.
% 'icaweight' - [matrix] ICA weight matrix.
% 'icasphere' - [matrix] ICA sphere matrix. By default, the sphere matrix
% is initialized to the identity matrix if it is left empty.
% 'comments' - [string] Comments on the dataset, accessible through the
% EEGLAB main menu using ('Edit > About This Dataset').
% Use this to attach background information about the
% experiment or the data to the dataset.
% Outputs:
% EEGOUT - Modified EEG dataset structure
%
% Note:
% To create a new dataset:
% >> EEG = pop_editset( eeg_emptyset ); % eeg_emptyset() returns an empty dataset
%
% To erase a variable, use '[]'. The following suppresses channel locations:
% >> EEG = pop_editset( EEG, 'chanlocs', '[]');
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: pop_importdata(), pop_select(), eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% 03-16-02 text interface editing -sm & ad
% 03-16-02 remove EEG.xmax et EEG.xmin (for continuous) -ad & sm
% 03-31-02 changed interface, reprogrammed all function -ad
% 04-02-02 recompute event latencies when modifying xmin -ad
function [EEGOUT, com] = pop_editset(EEG, varargin);
com = '';
if nargin < 1
help pop_editset;
return;
end;
EEGOUT = EEG;
if nargin < 2 % if several arguments, assign values
% popup window parameters
% -----------------------
% popup window parameters
% -----------------------
geometry = { [2 3.38] [1] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] ...
[1] [1.4 0.7 .8 0.5] [1] [1.4 0.7 .8 0.5] [1.4 0.7 .8 0.5] [1.4 0.7 .8 0.5] };
editcomments = [ 'tmp = pop_comments(get(gcbf, ''userdata''), ''Edit comments of current dataset'');' ...
'if ~isempty(tmp), set(gcf, ''userdata'', tmp); end; clear tmp;' ];
commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ...
'if filename(1) ~=0,' ...
' set(findobj(''parent'', gcbf, ''tag'', tagtest), ''string'', [ filepath filename ]);' ...
'end;' ...
'clear filename filepath tagtest;' ];
commandselica = [ 'res = inputdlg2({ ''Enter dataset number'' }, ''Select ICA weights and sphere from other dataset'', 1, { ''1'' });' ...
'if ~isempty(res),' ...
' set(findobj( ''parent'', gcbf, ''tag'', ''weightfile''), ''string'', sprintf(''ALLEEG(%s).icaweights'', res{1}));' ...
' set(findobj( ''parent'', gcbf, ''tag'', ''sphfile'') , ''string'', sprintf(''ALLEEG(%s).icasphere'' , res{1}));' ...
' set(findobj( ''parent'', gcbf, ''tag'', ''icainds'') , ''string'', sprintf(''ALLEEG(%s).icachansind'' , res{1}));' ...
'end;' ];
commandselchan = [ 'res = inputdlg2({ ''Enter dataset number'' }, ''Select channel information from other dataset'', 1, { ''1'' });' ...
'if ~isempty(res),' ...
' set(findobj( ''parent'', gcbf, ''tag'', ''chanfile''), ' ...
' ''string'', sprintf(''{ ALLEEG(%s).chanlocs ALLEEG(%s).chaninfo ALLEEG(%s).urchanlocs }'', res{1}, res{1}, res{1}));' ...
'end;' ];
if isstr(EEGOUT.ref)
curref = EEGOUT.ref;
else
if length(EEGOUT.ref) > 1
curref = [ int2str(abs(EEGOUT.ref)) ];
else
curref = [ int2str(abs(EEGOUT.ref)) ];
end;
end;
uilist = { ...
{ 'Style', 'text', 'string', 'Dataset name', 'horizontalalignment', 'right', ...
'fontweight', 'bold' }, { 'Style', 'edit', 'string', EEG.setname }, { } ...
...
{ 'Style', 'text', 'string', 'Data sampling rate (Hz)', 'horizontalalignment', 'right', 'fontweight', ...
'bold' }, { 'Style', 'edit', 'string', num2str(EEGOUT.srate) }, ...
{ 'Style', 'text', 'string', 'Subject code', 'horizontalalignment', 'right', ...
}, { 'Style', 'edit', 'string', EEG.subject }, ...
{ 'Style', 'text', 'string', 'Time points per epoch (0->continuous)', 'horizontalalignment', 'right', ...
}, { 'Style', 'edit', 'string', num2str(EEGOUT.pnts) }, ...
{ 'Style', 'text', 'string', 'Task condition', 'horizontalalignment', 'right', ...
}, { 'Style', 'edit', 'string', EEG.condition }, ...
{ 'Style', 'text', 'string', 'Start time (sec) (only for data epochs)', 'horizontalalignment', 'right', ...
}, { 'Style', 'edit', 'string', num2str(EEGOUT.xmin) }, ...
{ 'Style', 'text', 'string', 'Session number', 'horizontalalignment', 'right', ...
}, { 'Style', 'edit', 'string', EEG.session }, ...
{ 'Style', 'text', 'string', 'Number of channels (0->set from data)', 'horizontalalignment', 'right', ...
}, { 'Style', 'edit', 'string', EEG.nbchan 'enable' 'off' }, ...
{ 'Style', 'text', 'string', 'Subject group', 'horizontalalignment', 'right', ...
}, { 'Style', 'edit', 'string', EEG.group }, ...
{ 'Style', 'text', 'string', 'Ref. channel indices or mode (see help)', 'horizontalalignment', 'right', ...
}, { 'Style', 'edit', 'string', curref 'enable' 'off' }, ...
{ 'Style', 'text', 'string', 'About this dataset', 'horizontalalignment', 'right', ...
}, { 'Style', 'pushbutton', 'string', 'Enter comments' 'callback' editcomments }, ...
{ } ...
{ 'Style', 'text', 'string', 'Channel location file or info', 'horizontalalignment', 'right', 'fontweight', ...
'bold' }, {'Style', 'pushbutton', 'string', 'From other dataset', 'callback', commandselchan }, ...
{ 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'chanfile' }, ...
{ 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''chanfile'';' commandload ] }, ...
...
{ 'Style', 'text', 'string', ...
' Note: The file format may be auto-detected from its file extension. See menu "Edit > Channel locations" for other options.', ...
'horizontalalignment', 'right' }, ...
...
{ 'Style', 'text', 'string', 'ICA weights array or text/binary file (if any):', 'horizontalalignment', 'right' }, ...
{ 'Style', 'pushbutton' 'string' 'from other dataset' 'callback' commandselica }, ...
{ 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'weightfile' }, ...
{ 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''weightfile'';' commandload ] }, ...
...
{ 'Style', 'text', 'string', 'ICA sphere array or text/binary file (if any):', 'horizontalalignment', 'right' }, ...
{ 'Style', 'pushbutton' 'string' 'from other dataset' 'callback' commandselica }, ...
{ 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'sphfile' } ...
{ 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''sphfile'';' commandload ] } ...
...
{ 'Style', 'text', 'string', 'ICA channel indices (by default all):', 'horizontalalignment', 'right' }, ...
{ 'Style', 'pushbutton' 'string' 'from other dataset' 'callback' commandselica }, ...
{ 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'icainds' } ...
{ } };
[ results newcomments ] = inputgui( geometry, uilist, 'pophelp(''pop_editset'');', 'Edit dataset information - pop_editset()', ...
EEG.comments);
if length(results) == 0, return; end;
args = {};
i = 1;
if ~strcmp( results{i }, EEG.setname ) , args = { args{:}, 'setname', results{i } }; end;
if ~strcmp( results{i+1}, num2str(EEG.srate) ) , args = { args{:}, 'srate', str2num(results{i+1}) }; end;
if ~strcmp( results{i+2}, EEG.subject ) , args = { args{:}, 'subject', results{i+2} }; end;
if ~strcmp( results{i+3}, num2str(EEG.pnts) ) , args = { args{:}, 'pnts', str2num(results{i+3}) }; end;
if ~strcmp( results{i+4}, EEG.condition ) , args = { args{:}, 'condition', results{i+4} }; end;
if ~strcmp( results{i+5}, num2str(EEG.xmin) ) , args = { args{:}, 'xmin', str2num(results{i+5}) }; end;
if ~strcmp( results{i+6}, num2str(EEG.session) ) , args = { args{:}, 'session', str2num(results{i+6}) }; end;
if ~strcmp( results{i+7}, num2str(EEG.nbchan) ) , args = { args{:}, 'nbchan', str2num(results{i+7}) }; end;
if ~strcmp( results{i+8}, EEG.group ) , args = { args{:}, 'group', results{i+8} }; end;
if ~strcmp( results{i+9}, num2str(EEG.ref) ) , args = { args{:}, 'ref', results{i+9} }; end;
if ~strcmp(EEG.comments, newcomments) , args = { args{:}, 'comments' , newcomments }; end;
if abs(str2num(results{i+5})) > 10,
fprintf('WARNING: are you sure the epoch start time (%3.2f) is in seconds\n', str2num(results{i+5}));
end;
if ~isempty( results{i+12} ) , args = { args{:}, 'icachansind', results{i+13} }; end;
if ~isempty( results{i+10} ) , args = { args{:}, 'chanlocs' , results{i+10} }; end;
if ~isempty( results{i+11} ), args = { args{:}, 'icaweights', results{i+11} }; end;
if ~isempty( results{i+12} ) , args = { args{:}, 'icasphere', results{i+12} }; end;
else % no interactive inputs
args = varargin;
% Do not copy varargin
% --------------------
%for index=1:2:length(args)
% if ~isempty(inputname(index+2)) & ~isstr(args{index+1}) & length(args{index+1})>1,
% args{index+1} = inputname(index+1);
% end;
%end;
end;
% create structure
% ----------------
if ~isempty(args)
try, g = struct(args{:});
catch, disp('Setevent: wrong syntax in function arguments'); return; end;
else
g = [];
end;
% test the presence of variables
% ------------------------------
try, g.dataformat; catch, g.dataformat = 'ascii'; end;
% assigning values
% ----------------
tmpfields = fieldnames(g);
for curfield = tmpfields'
switch lower(curfield{1})
case {'dataformat' }, ; % do nothing now
case 'setname' , EEGOUT.setname = getfield(g, {1}, curfield{1});
case 'subject' , EEGOUT.subject = getfield(g, {1}, curfield{1});
case 'condition' , EEGOUT.condition = getfield(g, {1}, curfield{1});
case 'group' , EEGOUT.group = getfield(g, {1}, curfield{1});
case 'session' , EEGOUT.session = getfield(g, {1}, curfield{1});
case 'setname' , EEGOUT.setname = getfield(g, {1}, curfield{1});
case 'setname' , EEGOUT.setname = getfield(g, {1}, curfield{1});
case 'pnts' , EEGOUT.pnts = getfield(g, {1}, curfield{1});
case 'comments' , EEGOUT.comments = getfield(g, {1}, curfield{1});
case 'nbchan' , tmp = getfield(g, {1}, curfield{1});
if tmp ~=0, EEGOUT.nbchan = tmp; end;
case 'averef' , disp('The ''averef'' argument is obsolete; use function pop_reref() instead');
case 'ref' , EEGOUT.ref = getfield(g, {1}, curfield{1});
disp('WARNING: CHANGING REFERENCE DOES NOT RE-REFERENCE THE DATA, use menu Tools > Rereference instead');
if ~isempty(str2num( EEGOUT.ref )), EEG,ref = str2num(EEG.ref); end;
case 'xmin' , oldxmin = EEG.xmin;
EEGOUT.xmin = getfield(g, {1}, curfield{1});
if oldxmin ~= EEGOUT.xmin
if ~isempty(EEG.event)
if nargin < 2
if ~popask( ['Warning: changing the starting point of epochs will' 10 'lead to recomputing epoch event latencies, Continue?'] )
com = ''; warndlg2('pop_editset(): transformation cancelled by user'); return;
end;
end;
if isfield(EEG.event, 'latency')
for index = 1:length(EEG.event)
EEG.event(index).latency = EEG.event(index).latency - (EEG.xmin-oldxmin)*EEG.srate;
end;
end;
end;
end;
case 'srate' , EEGOUT.srate = getfield(g, {1}, curfield{1});
case 'chanlocs', varname = getfield(g, {1}, curfield{1});
if isempty(varname)
EEGOUT.chanlocs = [];
elseif isstr(varname) & exist( varname ) == 2
fprintf('pop_editset(): channel locations file ''%s'' found\n', varname);
[ EEGOUT.chanlocs lab theta rad ind ] = readlocs(varname);
elseif isstr(varname)
EEGOUT.chanlocs = evalin('base', varname, 'fprintf(''pop_editset() warning: variable ''''%s'''' not found, ignoring\n'', varname)' );
if iscell(EEGOUT.chanlocs)
if length(EEGOUT.chanlocs) > 1, EEGOUT.chaninfo = EEGOUT.chanlocs{2}; end;
if length(EEGOUT.chanlocs) > 2, EEGOUT.urchanlocs = EEGOUT.chanlocs{3}; end;
EEGOUT.chanlocs = EEGOUT.chanlocs{1};
end;
else
EEGOUT.chanlocs = varname;
end;
case 'icaweights', varname = getfield(g, {1}, curfield{1});
if isstr(varname) & exist( varname ) == 2
fprintf('pop_editset(): ICA weight matrix file ''%s'' found\n', varname);
if ~isempty(EEGOUT.icachansind), nbcol = length(EEGOUT.icachansind); else nbcol = EEG.nbchan; end;
try, EEGOUT.icaweights = load(varname, '-ascii');
EEGOUT.icawinv = [];
catch,
try
EEGOUT.icaweights = floatread(varname, [1 Inf]);
EEGOUT.icaweights = reshape( EEGOUT.icaweights, [length(EEGOUT.icaweights)/nbcol nbcol]);
catch
fprintf('pop_editset() warning: error while reading filename ''%s'' for ICA weight matrix\n', varname);
end;
end;
else
if isempty(varname)
EEGOUT.icaweights = [];
elseif isstr(varname)
EEGOUT.icaweights = evalin('base', varname, 'fprintf(''pop_editset() warning: variable ''''%s'''' not found, ignoring\n'', varname)' );
EEGOUT.icawinv = [];
else
EEGOUT.icaweights = varname;
EEGOUT.icawinv = [];
end;
end;
if ~isempty(EEGOUT.icaweights) & isempty(EEGOUT.icasphere)
EEGOUT.icasphere = eye(size(EEGOUT.icaweights,2));
end;
case 'icachansind', varname = getfield(g, {1}, curfield{1});
if isempty(varname)
EEGOUT.icachansind = [];
elseif isstr(varname)
EEGOUT.icachansind = evalin('base', varname, 'fprintf(''pop_editset() warning: variable ''''%s'''' not found, ignoring\n'', varname)' );
else
EEGOUT.icachansind = varname;
end;
case 'icasphere', varname = getfield(g, {1}, curfield{1});
if isstr(varname) & exist( varname ) == 2
fprintf('pop_editset(): ICA sphere matrix file ''%s'' found\n', varname);
if ~isempty(EEGOUT.icachansind), nbcol = length(EEGOUT.icachansind); else nbcol = EEG.nbchan; end;
try, EEGOUT.icasphere = load(varname, '-ascii');
EEGOUT.icawinv = [];
catch,
try
EEGOUT.icasphere = floatread(varname, [1 Inf]);
EEGOUT.icasphere = reshape( EEGOUT.icasphere, [length(EEGOUT.icasphere)/nbcol nbcol]);
catch
fprintf('pop_editset() warning: erro while reading filename ''%s'' for ICA weight matrix\n', varname);
end;
end;
else
if isempty(varname)
EEGOUT.icasphere = [];
elseif isstr(varname)
EEGOUT.icasphere = evalin('base', varname, 'fprintf(''pop_editset() warning: variable ''''%s'''' not found, ignoring\n'', varname)' );
EEGOUT.icawinv = [];
else
EEGOUT.icaweights = varname;
EEGOUT.icawinv = [];
end;
end;
if ~isempty(EEGOUT.icaweights) & isempty(EEGOUT.icasphere)
EEGOUT.icasphere = eye(size(EEGOUT.icaweights,2));
end;
case 'data' , varname = getfield(g, {1}, curfield{1});
if isnumeric(varname)
EEGOUT.data = varname;
elseif exist( varname ) == 2 & ~strcmp(lower(g.dataformat), 'array');
fprintf('pop_editset(): raw data file ''%s'' found\n', varname);
switch lower(g.dataformat)
case 'ascii' ,
try, EEGOUT.data = load(varname, '-ascii');
catch, disp(lasterr); error(['pop_editset() error: cannot read ascii file ''' varname ''' ']);
end;
if ndims(EEGOUT.data)<3 & size(EEGOUT.data,1) > size(EEGOUT.data,2), EEGOUT.data = transpose(EEGOUT.data); end;
case 'matlab',
try,
x = whos('-file', varname);
if length(x) > 1,
error('pop_editset() error: .mat file must contain a single variable');
end;
tmpdata = load(varname, '-mat');
EEGOUT.data = getfield(tmpdata,{1},x(1).name);
clear tmpdata;
catch, error(['pop_editset() error: cannot read .mat file ''' varname ''' ']);
end;
if ndims(EEGOUT.data)<3 & size(EEGOUT.data,1) > size(EEGOUT.data,2), EEGOUT.data = transpose(EEGOUT.data); end;
case {'float32le' 'float32be'},
if EEGOUT.nbchan == 0,
error(['pop_editset() error: to read float32 data you must first specify the number of channels']);
end;
try, EEGOUT.data = floatread(varname, [EEGOUT.nbchan Inf], ...
fastif(strcmpi(g.dataformat, 'float32le'), 'ieee-le', 'ieee-be'));
catch, error(['pop_editset() error: cannot read float32 data file ''' varname ''' ']);
end;
otherwise, error('pop_editset() error: unrecognized file format');
end;
elseif isstr(varname)
% restoration command
%--------------------
try
res = evalin('base', ['exist(''' varname ''') == 1']);
catch
disp('pop_editset() warning: cannot find specified variable in global workspace!');
end;
if ~res,
error('pop_editset(): cannot find specified variable.');
end;
warning off;
try,
testval = evalin('base', ['isglobal(' varname ')']);
catch, testval = 0; end;
if ~testval
commandrestore = [ ' tmpp = ' varname '; clear global ' varname ';' varname '=tmpp;clear tmpp;' ];
else
commandrestore = [];
end;
% make global, must make these variable global, if you try to evaluate them direclty in the base
% workspace, with a large array the computation becomes incredibly slow.
%--------------------------------------------------------------------
comglobal = sprintf('global %s;', varname);
evalin('base', comglobal);
eval(comglobal);
eval( ['EEGOUT.data = ' varname ';' ]);
try, evalin('base', commandrestore); catch, end;
warning on;
else
EEGOUT.data = varname;
if ndims(EEGOUT.data)<3 & size(EEGOUT.data,1) > size(EEGOUT.data,2), EEGOUT.data = transpose(EEGOUT.data); end;
end;
otherwise, error(['pop_editset() error: unrecognized field ''' curfield{1} '''']);
end;
end;
EEGOUT = eeg_checkset(EEGOUT);
% generate the output command
% ---------------------------
if nargout > 1
com = sprintf( '%s = pop_editset(%s', inputname(1), inputname(1) );
for i=1:2:length(args)
if ~isempty( args{i+1} )
if isstr( args{i+1} ) com = sprintf('%s, ''%s'', %s', com, args{i}, vararg2str(args{i+1}) );
else com = sprintf('%s, ''%s'', [%s]', com, args{i}, num2str(args{i+1}) );
end;
else
com = sprintf('%s, ''%s'', []', com, args{i} );
end;
end;
com = [com ');'];
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
|
ZijingMao/baselineeegtest-master
|
pop_snapread.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_snapread.m
| 3,759 |
utf_8
|
28b076d60861433397b0c0dd49338875
|
% pop_snapread() - load an EEG SnapMaster file (pop out window if no arguments).
%
% Usage:
% >> [dat] = pop_snapread( filename, gain);
%
% Graphic interface:
% "Relative gain" - [edit box] to compute the relative gain, fisrt look at
% the text header of the snapmater file with a text editor.
% Find the recording unit, usually in volts (UNITS field).
% Then, find the voltage range in the "CHANNEL.RANGE" [cmin cmax]
% field. Finally, determine the gain of the amplifiers (directly
% on the machine, not in the header file).
% Knowing that the recording precision is 12 bits. The folowing
% formula
% 1/2^12*[cmax-cmin]*1e6/gain
% returns the relative gain. You have to compute it and enter
% it in the edit box. Enter 1, for preserving the data file units.
% (note that if the voltage range is not the same for all channels
% or if the CONVERSION.POLY field in the file header
% is not "0 + 1x" for all channels, you will have to load the data
% using snapread() and scale manually all channels, then import
% the Matlab array into EEGLAB).
%
% Inputs:
% filename - SnapMaster file name
% gain - relative gain. See graphic interface help.
%
% Outputs:
% dat - EEGLAB data structure
%
% Author: Arnaud Delorme, CNL/Salk Institute, 13 March 2002
%
% See also: eeglab(), snapread()
% Copyright (C) 13 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 [EEG, command] = pop_snapread(filename, gain);
command = '';
EEG = [];
if nargin < 1
% ask user
[filename, filepath] = uigetfile('*.SMA', 'Choose a SnapMaster file -- pop_snapread()');
if filename == 0 return; end;
filename = [filepath filename];
promptstr = { 'Relative gain (see help)' };
inistr = { '400' };
result = inputdlg2( promptstr, 'Import SnapMaster file -- pop_snapread()', 1, inistr, 'pop_snapread');
if length(result) == 0 return; end;
gain = eval( result{1} );
end;
if exist('gain') ~= 1
gain = 1;
end;
% load datas
% ----------
EEG = eeg_emptyset;
[EEG.data,params,events, head] = snapread(filename);
EEG.data = EEG.data*gain;
EEG.comments = [ 'Original file: ' filename ];
EEG.filepath = '';
EEG.setname = 'SnapMaster file';
EEG.nbchan = params(1);
EEG.pnts = params(2);
EEG.trials = 1;
EEG.srate = params(3);
EEG.xmin = 0;
A = find(events ~= 0);
if ~isempty(A)
EEG.event = struct( 'type', mattocell(events(A), [1], ones(1,length(events(A)))), ...
'latency', mattocell(A(:)', [1], ones(1,length(A))) );
end;
EEG = eeg_checkset(EEG, 'eventconsistency');
EEG = eeg_checkset(EEG, 'makeur');
command = sprintf('EEG = pop_snapread(''%s'', %f);', filename, gain);
return;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_decodechan.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_decodechan.m
| 3,799 |
utf_8
|
600c82eb2fe26e4e9b5b1d1af79b383d
|
% eeg_decodechan() - given an input EEG dataset structure, output a new EEG data structure
% retaining and/or excluding specified time/latency, data point, channel,
% and/or epoch range(s).
% Usage:
% >> [chaninds chanlist] = eeg_decodechan(chanlocs, chanlist);
%
% Inputs:
% chanlocs - channel location structure
% chanlist - list of channels, numerical indices [1 2 3 ...] or string
% 'cz pz fz' or cell array { 'cz' 'pz' 'fz' }
%
% Outputs:
% chaninds - integer array with the list of channel indices
% chanlist - cell array with a list of channel labels
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, 2009-
%
% see also: eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ chaninds chanlist ] = eeg_decodechan(chanlocs, chanstr);
if nargin < 2
help eeg_decodechan;
return;
end;
if isempty(chanlocs) && isstr(chanstr)
chaninds = str2num(chanstr);
chanlist = chaninds;
return;
end;
if isstr(chanstr)
% convert chanstr
% ---------------
chanstr(find(chanstr == ']')) = [];
chanstr(find(chanstr == '[')) = [];
chanlistnum = [];
chanstr = [ ' ' chanstr ' ' ];
chanlist = {};
sp = find(chanstr == ' ');
for i = 1:length(sp)-1
c = chanstr(sp(i)+1:sp(i+1)-1);
if ~isempty(c)
chanlist{end+1} = c;
if isnan(str2double(chanlocs(1).labels)) % channel labels are not numerical
if ~isnan(str2double(c))
chanlistnum(end+1) = str2double(c);
end;
end;
end;
end;
if length(chanlistnum) == length(chanlist)
chanlist = chanlistnum;
end;
else
chanlist = chanstr;
end;
% convert to values
% -----------------
chanval = 0;
if isnumeric(chanlist)
chanval = chanlist;
end;
% chanval = [];
% if iscell(chanlist)
% for ind = 1:length(chanlist)
%
% valtmp = str2double(chanlist{ind});
% if ~isnan(valtmp)
% chanval(end+1) = valtmp;
% else chanval(end+1) = 0;
% end;
% end;
% else
% chanval = chanlist;
% end;
% convert to numerical
% --------------------
if all(chanval) > 0
chaninds = chanval;
chanlist = chanval;
else
chaninds = [];
alllabs = lower({ chanlocs.labels });
chanlist = lower(chanlist);
for ind = 1:length(chanlist)
indmatch = find(strcmp(alllabs,chanlist{ind})); %#ok<STCI>
if ~isempty(indmatch)
for tmpi = 1:length(indmatch)
chaninds(end+1) = indmatch(tmpi);
end;
else
try,
eval([ 'chaninds = ' chanlist{ind} ';' ]);
if isempty(chaninds)
error([ 'Channel ''' chanlist{ind} ''' not found' ]);
else
end;
catch
error([ 'Channel ''' chanlist{ind} ''' not found' ]);
end;
end;
end;
end;
chaninds = sort(chaninds);
if ~isempty(chanlocs)
chanlist = { chanlocs(chaninds).labels };
else
chanlist = {};
end;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_getica.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_getica.m
| 1,704 |
utf_8
|
00350d1cd6a4ab711db93297dd29454d
|
% eeg_getica() - get ICA component activation. Recompute if necessary.
%
% >> mergelocs = eeg_getica(EEG, comp);
%
% Inputs:
% EEG - EEGLAB dataset structure
% comp - component index
%
% Output:
% icaact - ICA component activity
%
% Author: Arnaud Delorme, 2006
% Copyright (C) Arnaud Delorme, CERCO, 2006, [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 icaact = eeg_getica(EEG, comp)
if nargin < 1
help eeg_getica;
return;
end;
if nargin < 2
comp = 1:size(EEG.icaweights,1);
end;
if ~isempty(EEG.icaact)
icaact = EEG.icaact(comp,:,:);
else
disp('Recomputing ICA activations');
if isempty(EEG.icachansind)
EEG.icachansind = 1:EEG.nbchan;
disp('Channels indices are assumed to be in regular order and arranged accordingly');
end
icaact = (EEG.icaweights(comp,:)*EEG.icasphere)*reshape(EEG.data(EEG.icachansind,:,:), length(EEG.icachansind), EEG.trials*EEG.pnts);
icaact = reshape( icaact, size(icaact,1), EEG.pnts, EEG.trials);
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_mergeset.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_mergeset.m
| 13,085 |
utf_8
|
1f742cb4e4ef9f3cc91e350e36de68cb
|
% pop_mergeset() - Merge two or more datasets. If only one argument is given,
% a window pops up to ask for more arguments.
% Usage:
% >> OUTEEG = pop_mergeset( ALLEEG ); % use a pop-up window
% >> OUTEEG = pop_mergeset( ALLEEG, indices, keepall);
% >> OUTEEG = pop_mergeset( INEEG1, INEEG2, keepall);
%
% Inputs:
% INEEG1 - first input dataset
% INEEG2 - second input dataset
%
% else
% ALLEEG - array of EEG dataset structures
% indices - indices of EEG datasets to merge
%
% keepall - [0|1] 0 -> remove, or 1 -> preserve, ICA activations
% of the first dataset and recompute the activations
% of the merged data {default: 0}
%
% Outputs:
% OUTEEG - merged dataset
%
% 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 change format for events and trial conditions -ad
function [INEEG1, com] = pop_mergeset( INEEG1, INEEG2, keepall);
com = '';
if nargin < 1
help pop_mergeset;
return;
end;
if isempty(INEEG1)
error('needs at least two datasets');
end;
if nargin < 2 & length(INEEG1) == 1
error('needs at least two datasets');
end;
if nargin == 1
uilist = { { 'style' 'text' 'string' 'Dataset indices to merge' } ...
{ 'style' 'edit' 'string' '1' } ...
{ 'style' 'text' 'string' 'Preserve ICA weights of the first dataset ?' } ...
{ 'style' 'checkbox' 'string' '' } };
res = inputgui( 'uilist', uilist, 'geometry', { [3 1] [3 1] }, 'helpcom', 'pophelp(''pop_mergeset'')');
if isempty(res) return; end;
INEEG2 = eval( [ '[' res{1} ']' ] );
keepall = res{2};
else
if nargin < 3
keepall = 0; % default
end;
end;
fprintf('Merging datasets...\n');
if ~isstruct(INEEG2) % if INEEG2 is a vector of ALLEEG indices
indices = INEEG2;
if length(indices) < 2
error('needs at least two datasets');
end;
NEWEEG = eeg_retrieve(INEEG1, indices(1)); % why abandoned?
for index = 2:length(indices)
INEEG2 = eeg_retrieve(INEEG1, indices(index));
NEWEEG = pop_mergeset(NEWEEG, INEEG2, keepall); % recursive call
end;
INEEG1 = NEWEEG;
else % INEEG is an EEG struct
% check consistency
% -----------------
if INEEG1.nbchan ~= INEEG2.nbchan
error('The two datasets must have the same number of channels');
end;
if INEEG1.srate ~= INEEG2.srate
error('The two datasets must have the same sampling rate');
end;
if INEEG1.trials > 1 | INEEG2.trials > 1
if INEEG1.pnts ~= INEEG2.pnts
error('The two epoched datasets must have the same number of points');
end;
if INEEG1.xmin ~= INEEG2.xmin
INEEG2.xmin = INEEG1.xmin;
fprintf('Warning: the two epoched datasets do not have the same time onset, adjusted');
end;
if INEEG1.xmax ~= INEEG2.xmax
INEEG2.xmax = INEEG1.xmax;
fprintf('Warning: the two epoched datasets do not have the same time offset, adjusted');
end;
end;
% Merge the epoch field
% ---------------------
if INEEG1.trials > 1 | INEEG2.trials > 1
INEEGX = {INEEG1,INEEG2};
for n = 1:2
% make sure that both have an (appropriately-sized) epoch field
% -------------------------------------------------------------
if ~isfield(INEEGX{n},'epoch')
INEEGX{n}.epoch = repmat(struct(),[1,INEEGX{n}.trials]);
end
% make sure that the epoch number is correct in each dataset
% ----------------------------------------------------------
if ~isempty(INEEGX{n}.epoch) && length(INEEGX{n}.epoch) ~= INEEGX{n}.trials
disp('Warning: The number of trials does not match the length of the EEG.epoch field in one of');
disp(' the datasets. Its epoch info will be reset and derived from the respective events.');
INEEGX{n}.epoch = repmat(struct(),[1,INEEGX{n}.trials]);
end
end
for n=1:2
% purge all event-related epoch fields from each dataset (EEG.epoch.event* fields)
% --------------------------------------------------------------------------------
if isstruct(INEEGX{n}.epoch)
fn = fieldnames(INEEGX{n}.epoch);
INEEGX{n}.epoch = rmfield(INEEGX{n}.epoch,{fn{strmatch('event',fn)}});
% copy remaining field names to the other dataset
% -----------------------------------------------
for f = fieldnames(INEEGX{n}.epoch)'
if ~isfield(INEEGX{3-n}.epoch,f{1})
INEEGX{3-n}.epoch(1).(f{1}) = [];
end
end
% after this, both sets have an epoch field with the appropriate number of items
% and possibly some user-defined fields, but no event* fields.
end
end
% concatenate epochs
% ------------------
if isstruct(INEEGX{1}.epoch) && isstruct(INEEGX{2}.epoch)
if length(fieldnames(INEEGX{2}.epoch)) > 0
INEEGX{1}.epoch(end+1:end+INEEGX{2}.trials) = orderfields(INEEGX{2}.epoch,INEEGX{1}.epoch);
else
INEEGX{1}.epoch(end+1:end+INEEGX{2}.trials) = INEEGX{2}.epoch;
end;
end
% and write back
INEEG1 = INEEGX{1};
INEEG2 = INEEGX{2};
INEEGX = {};
end
% Concatenate data
% ----------------
if INEEG1.trials > 1 | INEEG2.trials > 1
INEEG1.data(:,:,end+1:end+size(INEEG2.data,3)) = INEEG2.data(:,:,:);
else
INEEG1.data(:,end+1:end+size(INEEG2.data,2)) = INEEG2.data(:,:);
end;
INEEG1.setname = 'Merged datasets';
INEEG1trials = INEEG1.trials;
INEEG2trials = INEEG2.trials;
INEEG1pnts = INEEG1.pnts;
INEEG2pnts = INEEG2.pnts;
if INEEG1.trials > 1 | INEEG2.trials > 1 % epoched data
INEEG1.trials = INEEG1.trials + INEEG2.trials;
else % continuous data
INEEG1.pnts = INEEG1.pnts + INEEG2.pnts;
end;
if isfield(INEEG1, 'reject')
INEEG1 = rmfield(INEEG1, 'reject' );
end;
INEEG1.specicaact = [];
INEEG1.specdata = [];
if keepall == 0
INEEG1.icaact = [];
INEEG1.icawinv = [];
INEEG1.icasphere = [];
INEEG1.icaweights = [];
if isfield(INEEG1, 'stats')
INEEG1 = rmfield(INEEG1, 'stats' );
end;
else
INEEG1.icaact = [];
end;
% concatenate events
% ------------------
if isempty(INEEG2.event) && INEEG2.trials == 1
% boundary event
% -------------
disp('Inserting boundary event...');
INEEG1.event(end+1).type = 'boundary'; % add boundary event between datasets
INEEG1.event(end ).latency = INEEG1pnts+0.5; % make boundary halfway between last,first pts
% check urevents
% --------------
if ~isfield(INEEG1, 'urevent'),
INEEG1.urevent = [];
fprintf('Warning: first dataset has no urevent structure.\n');
end;
% add boundary urevent
% --------------------
disp('Inserting boundary urevent...');
INEEG1.urevent(end+1).type = 'boundary';
if length(INEEG1.urevent) > 1 % if previous INEEG1 urevents
INEEG1.urevent(end ).latency = max(INEEG1pnts, INEEG1.urevent(end-1).latency)+0.5;
else
INEEG1.urevent(end ).latency = INEEG1pnts+0.5;
end;
else % is ~isempty(INEEG2.event)
% concatenate urevents
% --------------------
if isfield(INEEG2, 'urevent')
if ~isempty(INEEG2.urevent) && isfield(INEEG1.urevent, 'latency')
% insert boundary event
% ---------------------
disp('Inserting boundary event...');
INEEG1.urevent(end+1).type = 'boundary';
try
INEEG1.urevent(end ).latency = max(INEEG1pnts, INEEG1.urevent(end-1).latency)+0.5;
catch
% cko: sometimes INEEG1 has no events / urevents
INEEG1.urevent(end ).latency = INEEG1pnts+0.5;
end
% update urevent indices for second dataset
% -----------------------------------------
disp('Concatenating urevents...');
orilen = length(INEEG1.urevent);
newlen = length(INEEG2.urevent);
INEEG2event = INEEG2.event;
% update urevent index in INEEG2.event
tmpevents = INEEG2.event;
nonemptymask = ~cellfun('isempty',{tmpevents.urevent});
[tmpevents(nonemptymask).urevent] = celldeal(num2cell([INEEG2event.urevent]+orilen));
INEEG2.event = tmpevents;
% reserve space and append INEEG2.urevent
INEEG1.urevent(orilen+newlen).latency = [];
INEEG2urevent = INEEG2.urevent;
tmpevents = INEEG1.urevent;
for f = fieldnames(INEEG2urevent)'
[tmpevents((orilen+1):(orilen+newlen)).(f{1})] = INEEG2urevent.(f{1});
end
INEEG1.urevent = tmpevents;
else
INEEG1.urevent = [];
INEEG2.urevent = [];
fprintf('Warning: second dataset has empty urevent structure.\n');
end
end;
% concatenate events
% ------------------
disp('Concatenating events...');
orilen = length(INEEG1.event);
newlen = length(INEEG2.event);
%allfields = fieldnames(INEEG2.event);
% ensure similar event structures
% -------------------------------
if ~isempty(INEEG2.event)
if isstruct(INEEG1.event)
for f = fieldnames(INEEG1.event)'
if ~isfield(INEEG2.event,f{1})
INEEG2.event(1).(f{1}) = [];
end
end
end
if isstruct(INEEG2.event)
for f = fieldnames(INEEG2.event)'
if ~isfield(INEEG1.event,f{1})
INEEG1.event(1).(f{1}) = [];
end
end
end
INEEG2.event = orderfields(INEEG2.event, INEEG1.event);
end;
% append
INEEG1.event(orilen+(1:newlen)) = INEEG2.event;
INEEG2event = INEEG2.event;
if isfield(INEEG1.event,'latency') && isfield(INEEG2.event,'latency')
% update latency
tmpevents = INEEG1.event;
[tmpevents(orilen + (1:newlen)).latency] = celldeal(num2cell([INEEG2event.latency] + INEEG1pnts*INEEG1trials));
INEEG1.event = tmpevents;
end
if isfield(INEEG1.event,'epoch') && isfield(INEEG2.event,'epoch')
% update epoch index
tmpevents = INEEG1.event;
[tmpevents(orilen + (1:newlen)).epoch] = celldeal(num2cell([INEEG2event.epoch]+INEEG1trials));
INEEG1.event = tmpevents;
end
% add discontinuity event if continuous
% -------------------------------------
if INEEG1trials == 1 & INEEG2trials == 1
disp('Adding boundary event...');
INEEG1.event = eeg_insertbound(INEEG1.event, INEEG1.pnts, INEEG1pnts+1, 0); % +1 since 0.5 is subtracted
end;
end;
INEEG1.pnts = size(INEEG1.data,2);
if ~isfield(INEEG1.event,'epoch') && ~isempty(INEEG1.event) && (size(INEEG1.data,3)>1 || ~isempty(INEEG1.epoch))
INEEG1.event(1).epoch = [];
end
% rebuild event-related epoch fields
% ----------------------------------
disp('Reconstituting epoch information...');
INEEG1 = eeg_checkset(INEEG1, 'eventconsistency');
end
% build the command
% -----------------
if exist('indices') == 1
com = sprintf('EEG = pop_mergeset( %s, [%s], %d);', inputname(1), int2str(indices), keepall);
else
com = sprintf('EEG = pop_mergeset( %s, %s, %d);', inputname(1), inputname(2), keepall);
end
return
function varargout = celldeal(X)
varargout = X;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_importevent.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_importevent.m
| 12,593 |
utf_8
|
6b64e9391f0dca41020312951341bd55
|
% pop_importevent() - Import events into an EEG dataset. If the EEG dataset
% is the only input, a window pops up to ask for the relevant
% parameter values.
%
% Usage: >> EEG = pop_importevent( EEG ); % pop-up window mode
% >> EEG = pop_importevent( EEG, 'key1', 'value1', ...);
%
% Graphic interface:
% "Event indices" - [edit box] Enter indices of events to modify.
% Leave this field blank to import new events.
% Command line equivalent: 'indices'.
% "Append events?" - [checkbox] Check this checkbox to clear prior
% event information. In addition, see the "Align event latencies ..."
% edit box. Command line equivalent: 'append'.
% "Event file or array" - [edit box] Enter event file name. Use "Browse"
% button to browse for a file. If a file with the given name
% cannot be found, the function search for a variable with
% this name in the global workspace.
% Command line equivalent: 'filename'.
% "Input field (column) name" - [edit box] Enter a name for each of the
% columns in the event text file. If column names are defined
% in the text file, they cannnot be used and you must copy
% the names into this edit box (and skip the name row). Must
% provide a name for each column. The keywords "type",
% "latency", and "duration" are recognized EEGLAB keywords and
% should be used to define the event log file columns containing
% event types, latencies, and durations. Column names can be
% separated by commas, quoted or not.
% Command line equivalent: fields.
% "Latency time unit (sec)" - [edit box] Specify the time unit for the
% latency column defined above relative to seconds.
% Command line equivalent: 'timeunit'.
% "Number of header lines to ignore" - [edit box] For some text files, the
% first rows do not contain epoch information and need to be
% skipped. Command line equivalent: 'skiplines'.
% "Align event latencies to data events" - [edit box] For most EEG datasets,
% basic event information is defined along with the EEG, and
% a more detailed file is recorded separately. This option
% helps fuse the two sources of information by realigning the
% imported data text file information into the existing event.
% A value of 0 indicates that the first events of the pre-defined
% events and imported events will be aligned. A positive value (num)
% aligns the first event to the num-th pre-existing event.
% A negative value can also be used; then event number (-num)
% is aligned to the first pre-existing event. Default is 0.
% (NaN-> no alignment). Command line equivalent is 'align'.
% "Auto adjust event sampling rate" - [checkbox] When checked, the function
% automatically adjusts the sampling rate of the new events so
% they best align with the closest old events. This may account
% for small differences in sampling rate that could lead to
% big differences at the end of the experiement (e.g., A 0.01%
% clock difference over an hour would lead to a 360-ms difference
% if not corrected). Command line line equivalent is 'optimalim'.
% Input:
% EEG - input dataset
%
% Optional file or array input:
% 'event' - [ 'filename'|array ] Filename of a text file, or name of s
% Matlab array in the global workspace containing an
% array of events in the folowing format: The first column
% is the type of the event, the second the latency.
% The others are user-defined. The function can read
% either numeric or text entries in ascii files.
% 'fields' - [Cell array] List of the name of each user-defined column,
% optionally followed by a description. Ex: { 'type', 'latency' }
% 'skipline' - [Interger] Number of header rows to skip in the text file
% 'timeunit' - [ latency unit rel. to seconds ]. Default unit is 1 = seconds.
% 'delim' - [string] String of delimiting characters in the input file.
% Default is tab|space.
%
% Optional oldevent input:
% 'append' - ['yes'|'no'] 'yes' = Append events to the current events in
% the EEG dataset {default}: 'no' = Erase the previous events.
% 'indices' - {integer vector] Vector indicating the indices of the events to
% modify.
% 'align' - [num] Align the first event latency to the latency of existing
% event number (num), and check latency consistency.
% 'optimalign' - ['on'|'off'] Optimize the sampling rate of the new events so
% they best align with old events. Default is 'on'.
%
% Outputs:
% EEG - EEG dataset with updated event fields
%
% Example: >> [EEG, eventnumbers] = pop_importevent(EEG, 'event', ...
% 'event_values.txt', 'fields', {'type', 'latency','condition' }, ...
% 'append', 'no', 'align', 0, 'timeunit', 1E-3 );
%
% This loads the ascii file 'event_values.txt' containing 3 columns
% (event_type, latency, and condition). Latencies in the file are
% in ms (1E-3). The first event latency is re-aligned with the
% beginning of the dataset ('align', 0). Any previous events
% are erased ('append', 'no').
%
% Author: Arnaud Delorme & Scott Makeig, CNL / Salk Institute, 9 Feb 2002
%
% See also: importevent(), pop_editeventfield(), pop_selectevent()
% 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 [EEG, com] = pop_importevent(EEG, varargin);
com ='';
if nargin < 1
help pop_importevent;
return;
end;
if isempty(EEG.data)
disp('pop_importevent(): error: cannot process empty dataset'); return;
end;
I = [];
% warning if data epochs
% ----------------------
if nargin<2 & EEG.trials > 1
questdlg2(strvcat('Though epoch information is defined in terms of the event structure,', ...
'this function is usually used to import events into continuous data.', ...
'For epoched data, use menu item ''File > Import epoch info'''), ...
'pop_importevent warning', 'OK', 'OK');
end;
% remove the event field
% ----------------------
if ~isempty(EEG.event), allfields = fieldnames(EEG.event);
else allfields = {}; end;
if nargin<2
commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ...
'if filename ~=0,' ...
' set(findobj(''parent'', gcbf, ''tag'', tagtest), ''string'', [ filepath filename ]);' ...
'end;' ...
'clear filename filepath tagtest;' ];
helpfields = ['latency field (lowercase) must be present; field ''type'' and' 10 ...
'''duration'' are also recognized keywords and it is recommended to define them'];
uilist = { ...
{ 'Style', 'text', 'string', 'Event indices', 'fontweight', 'bold' }, ...
{ 'Style', 'text', 'string', 'Append events?', 'fontweight', 'bold' } };
geometry = { [ 1 1.1 1.1 1] [ 1 1 2] [1 1 2] [ 1.2 1 1] };
uilist = { uilist{:}, ...
{ 'Style', 'text', 'string', 'Event file or array', 'horizontalalignment', 'right', 'fontweight', 'bold' }, ...
{ 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''globfile'';' commandload ] }, ...
{ 'Style', 'edit' } ...
{ 'Style', 'checkbox', 'string', 'Yes/No', 'value', 0 }, ...
{ 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'globfile' }, ...
{ }, { 'Style', 'text', 'string', 'NB: No = overwrite', 'value', 0 }, { }, ...
{ 'Style', 'text', 'string', 'Input field (column) names ', 'fontweight', 'bold', 'tooltipstring', helpfields } ...
{ 'Style', 'edit', 'string', '' } { 'Style', 'text', 'string', 'Ex: type latency duration', 'tooltipstring', helpfields } };
geometry = { geometry{:} [1.2 1 1] [1.2 1 1] [1.2 1 1] [1.2 0.2 1.8] };
uilist = { uilist{:}, ...
{ 'Style', 'text', 'string', 'Number of file header lines', 'horizontalalignment', 'left' }, { 'Style', 'edit', 'string', '0' }, ...
{ 'Style', 'text', 'string', '(latency field required above)', 'tooltipstring', helpfields },...
{ 'Style', 'text', 'string', 'Time unit (sec)', 'horizontalalignment', 'left' }, { 'Style', 'edit', 'string', '1' } ...
{ 'Style', 'text', 'string', 'Ex: If ms, 1E-3; if points, NaN' },...
{ 'Style', 'text', 'string', 'Align event latencies to data events', 'horizontalalignment', 'left' }, ...
{ 'Style', 'edit', 'string', fastif(isempty(EEG.event),'NaN','0') } { 'Style', 'text', 'string', 'See Help' },...
{ 'Style', 'text', 'string', 'Auto adjust new events sampling rate', 'horizontalalignment', 'left' }, ...
{ 'Style', 'checkbox', 'value' 1 } { },...
};
results = inputgui( geometry, uilist, 'pophelp(''pop_importevent'');', 'Import event info -- pop_importevent()' );
if length(results) == 0, return; end;
% decode top inputs
% -----------------
args = {};
if ~isempty( results{1} ), args = { args{:}, 'indices', eval( [ '[' results{1} ']' ]) }; end;
if results{2} == 0 & ~isempty(EEG.event), args = { args{:}, 'append', 'no' }; end;
if ~isempty( results{3} ),
if isstr( results{3} ) && ~exist(results{3})
args = { args{:}, 'event', evalin('base', results{3}) };
else
args = { args{:}, 'event', results{3} };
end;
end;
if ~isempty( results{4} ), args = { args{:}, 'fields', parsetxt(results{4}) }; end;
% handle skipline
% ---------------
if ~isempty(eval(results{end-3})), if eval(results{end-3}) ~= 0, args = { args{:}, 'skipline', eval(results{end-3}) }; end; end;
% handle timeunit
% -------------
if ~isempty(eval(results{end-2})), if eval(results{end-2}) ~= 0, args = { args{:}, 'timeunit', eval(results{end-2}) }; end; end;
% handle alignment
% ----------------
if ~isempty(eval(results{end-1})), if ~isnan(eval(results{end-1})), args = { args{:}, 'align', eval(results{end-1}) }; end; end;
if ~results{end} ~= 0, args = { args{:}, 'optimalign', 'off' }; end;
else % no interactive inputs
args = varargin;
% scan args to modify array/file format
% array are transformed into string
% files are transformed into string of string
% (this is usefull to build the string command for the function)
% --------------------------------------------------------------
for index=1:2:length(args)
if iscell(args{index+1}), if iscell(args{index+1}{1}) args{index+1} = args{index+1}{1}; end; end; % double nested
if isstr(args{index+1}) & length(args{index+1}) > 2 & args{index+1}(1) == '''' & args{index+1}(end) == ''''
args{index+1} = args{index+1}(2:end-1); end;
%else if ~isempty( inputname(index+2) ), args{index+1} = inputname(index+2); end;
%end;
end;
end;
EEG.event = importevent( [], EEG.event, EEG.srate, args{:});
% generate ur variables
% ---------------------
EEG = eeg_checkset(EEG, 'eventconsistency');
EEG = eeg_checkset(EEG, 'makeur');
% generate the output command
% ---------------------------
com = sprintf('%s = pop_importevent( %s, %s);', inputname(1), inputname(1), vararg2str(args));
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_eventtypes.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_eventtypes.m
| 5,504 |
utf_8
|
d106acb9a7c18278b36620b4a206edb5
|
% eeg_eventtypes() - return a list of event or urevent types in a dataset and
% the respective number of events of each type. Ouput event
% types are sorted in reverse order of their number. If no
% outputs, print this list on the commandline instead.
%
% Usage:
% >> [types,numbers] = eeg_eventtypes(EEG);
% Inputs:
% EEG - EEGLAB dataset structure
% Outputs:
% types - cell array of event type strings
% numbers - vector giving the numbers of each event type in the data
%
% Example:
% >> eeg_eventtypes(EEG); % print numner of each event types
%
% Author: Scott Makeig, SCCN/INC/UCSD, April 28, 2004-
% >> [types,numbers] = eeg_eventtypes(EEG,types);
% >> [types,numbers] = eeg_eventtypes(EEG,'urevents',types);
% Inputs:
% EEG - EEGLAB dataset structure
% 'urevents' - return event information for the EEG.urevent structure
% types - {cell array} of event types to return or print.
% Outputs:
% types - cell array of event type strings
% numbers - vector giving the numbers of each event type in the data
%
% Note: Numeric (ur)event types are converted to strings, so, for example,
% types {13} and {'13'} are not distinguished.
%
% Example:
% >> eeg_eventtypes(EEG); % print numner of each event types
%
% Curently disabled:
% >> eeg_eventtypes(EEG,'urevent'); % print hist. of urevent types
% >> eeg_eventtypes(EEG,{'rt'});% print number of 'rt' events
% >> eeg_eventtypes(EEG,'urevent',{'rt','break'});
% % print numbers of 'rt' and 'break'
% % type urevents
% Copyright (C) 2004 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
%
%
% event types can be numbers, Stefan Debener, 05/12/2006,
% added 2nd and 3rd args, sorted outputs by number, Scott Makeig, 09/12/06
function [types,numbers] = eeg_eventtypes(EEG,arg2,arg3)
if nargin< 1
help eeg_eventtypes
return
end
if ~isstruct(EEG)
error('EEG argument must be a dataset structure')
end
if ~isfield(EEG,'event')
error('EEG.event field not found');
end
if nargin > 1
error('Multiple input arguments are currently disabled');
end;
UREVENTS = 0; % flag returning infor for urevents instead of events
typelist = [];
if nargin>1
if ischar(arg2)
if strcmp(arg2,'urevent') | strcmp(arg2,'urevents')
UREVENTS = 1; % change flag
else
error('second argument string not understood')
end
if nargin>2
if iscell(arg3)
typelist = arg3;
end
end
elseif iscell(arg2)
typelist = arg2;
end
end
if ~isempty(typelist) % cast to cell array of strings
for k=1:length(typelist)
if isnumeric(typelist{k})
typelist{k} = num2str(typelist{k});
end
end
end
if ~UREVENTS
nevents = length(EEG.event);
alltypes = cell(nevents,1);
for k=1:nevents
if isnumeric(EEG.event(k).type)
alltypes{k} = num2str(EEG.event(k).type);
else
alltypes{k} = EEG.event(k).type;
end
end
else
nevents = length(EEG.urevent);
alltypes = cell(nevents,1);
for k=1:nevents
if isnumeric(EEG.urevent(k).type)
alltypes{k} = num2str(EEG.urevent(k).type);
else
alltypes{k} = EEG.urevent(k).type;
end
end
end
[types i j] = unique_bc(alltypes);
istypes = 1:length(types);
notistypes = [];
if ~isempty(typelist)
notistypes = ismember_bc(typelist,types);
istypes = ismember_bc(types,typelist(find(notistypes==1))); % types in typelist?
notistypes = typelist(find(notistypes==0));
end
types(~istypes) = []; % restrict types to typelist
ntypes = length(types);
numbers = zeros(ntypes + length(notistypes),1);
for k=1:ntypes
numbers(k) = length(find(j==k));
end
types = [types(:); notistypes(:)]; % concatenate the types not found
ntypes = length(types);
for j = 1:length(notistypes)
numbers(k+j) = 0;
end
% sort types in reverse order of event numbers
[numbers nsort] = sort(numbers);
numbers = numbers(end:-1:1);
types = types(nsort(end:-1:1));
%
% print output on commandline %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if nargout < 1
fprintf('\n');
if UREVENTS
fprintf('EEG urevent types:\n\n')
else
fprintf('EEG event types:\n\n')
end
maxx = 0;
for k=1:ntypes
x = length(types{k});
if x > maxx
maxx = x; % find max type name length
end
end
for k=1:ntypes
fprintf(' %s',types{k});
for j=length(types{k})+1:maxx+4
fprintf(' ');
end
fprintf('%d\n',numbers(k));
end
fprintf('\n');
clear types % no return variables
end
|
github
|
ZijingMao/baselineeegtest-master
|
pop_signalstat.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_signalstat.m
| 5,079 |
utf_8
|
5066bdd6d63e075bfeaf649483b7b2bb
|
% pop_signalstat() - Computes and plots statistical characteristics of a signal,
% including the data histogram, a fitted normal distribution,
% a normal ditribution fitted on trimmed data, a boxplot, and
% the QQ-plot. The estimates value are printed in a panel and
% can be read as output. See SIGNALSTAT.
% Usage:
% >> OUTEEG = pop_signalstat( EEG, type ); % pops up
% >> [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh] = pop_signalstat( EEG, type, cnum );
% >> [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh] = pop_signalstat( EEG, type, cnum, percent );
%
% Inputs:
% EEG - input EEG dataset
% type - type of processing
% 1: process the raw data; 0: the ICA components
% cnum - selected channel or component
%
% Outputs:
% OUTEEG - output dataset
%
% Author: Luca Finelli, CNL / Salk Institute - SCCN, 2 August 2002
%
% See also:
% SIGNALSTAT, EEGLAB
% Copyright (C) 2002 Luca Finelli, Salk/SCCN, La Jolla, CA
%
% 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 = pop_signalstat( EEG, typeproc, cnum, percent );
% the command output is a hidden output that does not have to
% be described in the header
com = ''; % this initialization ensure that the function will return something
% if the user press the cancel button
varargout{1} = '';
% display help if not enough arguments
% ------------------------------------
if nargin < 2
help pop_signalstat;
return;
end;
popup=0;
if nargin < 3
popup = 1;
end;
if nargin < 4
percent=5;
end;
% pop up window
% -------------
if (nargin < 3 & typeproc==1)
promptstr = { 'Channel number:'; 'Trim percentage (each end):' };
inistr = { '1';'5' };
result = inputdlg2( promptstr, 'Plot signal statistics -- pop_signalstat()', 1, inistr, 'signalstat');
if length( result ) == 0 return; end;
cnum = eval( [ '[' result{1} ']' ] ); % the brackets allow processing Matlab arrays
percent = eval( [ '[' result{2} ']' ] );
elseif (nargin < 3 & typeproc==0)
promptstr = { 'Component number:'; 'Trim percentage (each end):' };
inistr = { '1'; '5' };
result = inputdlg2( promptstr, 'Plot signal statistics -- pop_signalstat()', 1, inistr, 'signalstat');
if length( result ) == 0 return; end;
cnum = eval( [ '[' result{1} ']' ] ); % the brackets allow processing Matlab arrays
percent = eval( [ '[' result{2} ']' ] );
end;
if length(cnum) ~= 1 | (cnum-floor(cnum)) ~= 0
error('pop_signalstat(): Channel/component number must be a single integer');
end
if cnum < 1 | cnum > EEG.nbchan
error('pop_signalstat(): Channel/component number out of range');
end;
% call function signalstat() either on raw data or ICA data
% ---------------------------------------------------------
if typeproc == 1
tmpsig=EEG.data(cnum,:);
% [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh]=signalstat( EEG.data(cnum,:),1,[], percent);
dlabel=[];
dlabel2=['Channel ' num2str(cnum)];
map = cnum;
else
if ~isempty( EEG.icasphere )
tmpsig = eeg_getdatact(EEG, 'component', cnum);
tmpsig = tmpsig(:,:);
% [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh]=signalstat( tmpsig,1,'Component Activity',percent);
dlabel='Component Activity';
dlabel2=['Component ' num2str(cnum)];
map = EEG.icawinv(:,cnum);
else
error('You must run ICA first');
end;
end;
% outputs
% -------
outstr = '';
if ~popup
for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end;
if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end;
end;
% return the string command
% -------------------------
%fprintf('Pop_signalstat: computing statistics...\n');
varargout{1} = sprintf('pop_signalstat( %s, %d, %d );', inputname(1), typeproc, cnum);
plotloc = 0;
if ~isempty(EEG.chanlocs)
if isfield(EEG.chanlocs, 'theta')
if ~isempty(EEG.chanlocs(cnum).theta)
plotloc = 1;
end;
end;
end;
if plotloc
if typeproc == 1
com = sprintf('%s signalstat( tmpsig, 1, dlabel, percent, dlabel2, map, EEG.chanlocs );', outstr);
else
com = sprintf('%s signalstat( tmpsig, 1, dlabel, percent, dlabel2, map, EEG.chanlocs(EEG.icachansind) );', outstr);
end;
else
com = sprintf('%s signalstat( tmpsig, 1, dlabel, percent, dlabel2);', outstr);
end;
eval(com)
try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_rejchanspec.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_rejchanspec.m
| 10,691 |
utf_8
|
8549b5c2d8a05e2ca0aa177b4a248efc
|
% pop_rejchanspec() - reject artifacts channels in an EEG dataset using
% channel spectrum. The average spectrum for all selected
% is computed and a threshold is applied.
%
% Usage:
% >> pop_rejchanspec( INEEG ) % pop-up interative window mode
% >> [OUTEEG, indelec] = pop_rejchanspec( INEEG, 'key', 'val');
%
% Inputs:
% INEEG - input EEGLAB dataset
%
% Optional inputs:
% 'freqlims' - [min max] frequency limits. May also be an array where
% each row defines a different set of limits. Default is
% 35 to the Niquist frequency of the data.
% 'stdthresh' - [max] positive threshold in terms of standard deviation.
% Default is 5.
% 'absthresh' - [max] positive threshold in terms of spectrum units
% (overides the option above).
% 'averef' - ['on'|'off'] 'on' computes average reference before
% applying threshold. Default is 'off'.
% 'plothist' - ['on'|'off'] 'on' plot the histogram of values along
% with the threshold.
% 'plotchans' - ['on'|'off'] 'on' plot the channels scrollplot with
% selected channels for rejection in red. Allow selected
% channels rejection with the 'REJECT' button.
% 'elec' - [integer array] only include specific channels. Default
% is to use all channels.
% 'specdata' - [fload array] use this array containing the precomputed
% spectrum instead of computing the spectrum. Default is
% empty.
% 'specfreqs' - [fload array] frequency array for precomputed spectrum
% above.
% 'verbose' - ['on'|'off'] display information. Default is 'off'.
%
% Outputs:
% OUTEEG - output dataset with updated joint probability array
% indelec - indices of rejected electrodes
% specdata - data spectrum for the selected channels
% specfreqs - frequency array for spectrum above
%
% Author: Arnaud Delorme, CERCO, UPS/CNRS, 2008-
% Copyright (C) 2008 Arnaud Delorme, CERCO, UPS/CNRS
%
% 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 allrmchan specdata specfreqs com] = pop_rejchanspec(EEG, varargin)
if nargin < 1
help pop_rejchanspec;
return;
end;
allrmchan = [];
specdata = [];
specfreqs = [];
com = '';
if nargin < 2
uilist = { { 'style' 'text' 'string' 'Electrode (number(s); Ex: 2 4 5)' } ...
{ 'style' 'edit' 'string' ['1:' int2str(EEG.nbchan)] } ...
{ 'style' 'text' 'string' 'Frequency limits [min max]' } ...
{ 'style' 'edit' 'string' [ '35 ' int2str(floor(EEG.srate/2)) ] } ...
{ 'style' 'text' 'string' 'Standard dev. threshold limits [max]' } ...
{ 'style' 'edit' 'string' '5' } ...
{ 'style' 'text' 'string' 'OR absolute threshold limit [min max]' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'string' 'Compute average reference first (check=on)' } ...
{ 'style' 'checkbox' 'string' '' 'value' 0 } { } ...
{ 'style' 'text' 'string' 'Plot histogram of power values (check=on)' } ...
{ 'style' 'checkbox' 'string' '' 'value' 0 } { } ...
{ 'style' 'text' 'string' 'Plot channels scrollplot (check=on)' } ...
{ 'style' 'checkbox' 'string' '' 'value' 0 } { } ...
};
geom = { [2 1] [2 1] [2 1] [2 1] [2 0.3 0.7] [2 0.3 0.7] [2 0.3 0.7] };
result = inputgui( 'uilist', uilist, 'geometry', geom, 'title', 'Reject channel using spectrum -- pop_rejchanspec()', ...
'helpcom', 'pophelp(''pop_rejchan'')');
if isempty(result), return; end;
options = { 'elec' eval( [ '[' result{1} ']' ] ) 'stdthresh' str2num(result{3}) 'freqlims' str2num(result{2}) };
if ~isempty(result{4})
options = { options{:} 'absthresh' str2num(result{4}) };
end;
if result{5},
options = { options{:} 'averef', 'on' };
end;
if result{6},
options = { options{:} 'plothist', 'on' };
end;
% Begin: Added by Romain on 22 July 2010
if result{7},
options = { options{:} 'plotchans', 'on' };
end;
% End: Added by Romain on 22 July 2010
else
options = varargin;
end;
% decode options
% --------------
opt = finputcheck( options, { 'averef' 'string' { 'on';'off' } 'off';
'plothist' 'string' { 'on';'off' } 'off';
'plotchans' 'string' { 'on';'off' } 'off';
'verbose' 'string' { 'on';'off' } 'off';
'elec' 'integer' [] [1:EEG.nbchan];
'freqlims' 'real' [] [35 EEG.srate/2];
'specdata' 'real' [] [];
'specfreqs' 'real' [] [];
'absthresh' 'real' [] [];
'stdthresh' 'real' [] 5 }, 'pop_rejchanspec');
if isstr(opt), error(opt); end;
% compute average referecne if necessary
if strcmpi(opt.averef, 'on')
NEWEEG = pop_reref(EEG, [], 'exclude', setdiff([1:EEG.nbchan], opt.elec));
else NEWEEG = EEG;
end;
if isempty(opt.specdata)
[tmpspecdata specfreqs] = pop_spectopo(NEWEEG, 1, [], 'EEG' , 'percent', 100, 'freqrange',[0 EEG.srate/2], 'plot', 'off');
% add back 0 channels
devStd = std(EEG.data(:,:), [], 2);
if any(devStd == 0)
goodchan = find(devStd ~= 0);
specdata = zeros(length(opt.elec), size(tmpspecdata,2));
specdata(goodchan,:) = tmpspecdata;
else
specdata = tmpspecdata;
end;
else
specdata = opt.specdata;
specfreqs = opt.specfreqs;
end;
if size(opt.stdthresh,1) == 1 && size(opt.freqlims,1) > 1
opt.stdthresh = ones(length(opt.stdthresh), size(opt.freqlims,1))*opt.stdthresh;
end;
allrmchan = [];
for index = 1:size(opt.freqlims,1)
% select frequencies, compute median and std then reject channels
% ---------------------------------------------------------------
[tmp fbeg] = min(abs(specfreqs - opt.freqlims(index,1)));
[tmp fend] = min(abs(specfreqs - opt.freqlims(index,2)));
selectedspec = mean(specdata(opt.elec, fbeg:fend), 2);
if ~isempty(opt.absthresh)
rmchan = find(selectedspec <= opt.absthresh(1) | selectedspec >= opt.absthresh(2));
else
m = median(selectedspec);
s = std( selectedspec);
nbTresh = size(opt.stdthresh);
if length(opt.stdthresh) > 1
rmchan = find(selectedspec <= m+s*opt.stdthresh(index,1) | selectedspec >= m+s*opt.stdthresh(index,2));
else
rmchan = find(selectedspec > m+s*opt.stdthresh(index));
end
end;
% print out results
% -----------------
if isempty(rmchan)
textout = sprintf('Range %2.1f-%2.1f Hz: no channel removed\n', opt.freqlims(index,1), opt.freqlims(index,2));
else textout = sprintf('Range %2.1f-%2.1f Hz: channels %s removed\n', opt.freqlims(index,1), opt.freqlims(index,2), int2str(opt.elec(rmchan')));
end;
fprintf(textout);
if strcmpi(opt.verbose, 'on')
for inde = 1:length(opt.elec)
if ismember(inde, rmchan)
fprintf('Elec %s power: %1.2f *\n', EEG.chanlocs(opt.elec(inde)).labels, selectedspec(inde));
else fprintf('Elec %s power: %1.2f\n', EEG.chanlocs(opt.elec(inde)).labels , selectedspec(inde));
end;
end;
end;
allrmchan = [ allrmchan rmchan' ];
% plot histogram
% --------------
if strcmpi(opt.plothist, 'on')
figure; hist(selectedspec);
hold on; yl = ylim;
if ~isempty(opt.absthresh)
plot([opt.absthresh(1) opt.absthresh(1)], yl, 'r');
plot([opt.absthresh(2) opt.absthresh(2)], yl, 'r');
else
if length(opt.stdthresh) > 1
threshold1 = m+s*opt.stdthresh(index,1);
threshold2 = m+s*opt.stdthresh(index,2);
plot([m m], yl, 'g');
plot([threshold1 threshold1], yl, 'r');
plot([threshold2 threshold2], yl, 'r');
else
threshold = m+s*opt.stdthresh(index,1);
plot([threshold threshold], yl, 'r');
end
end;
title(textout);
end;
end;
allrmchan = unique_bc(allrmchan);
com = sprintf('EEG = pop_rejchan(EEG, %s);', vararg2str(options));
if strcmpi(opt.plotchans, 'on')
tmpcom = [ 'EEGTMP = pop_select(EEG, ''nochannel'', [' num2str(opt.elec(allrmchan)) ']);' ];
tmpcom = [ tmpcom ...
'LASTCOM = ' vararg2str(com) ';' ...
'[ALLEEG EEG CURRENTSET tmpcom] = pop_newset(ALLEEG, EEGTMP, CURRENTSET);' ...
' if ~isempty(tmpcom),' ...
' EEG = eegh(LASTCOM, EEG);' ...
' eegh(tmpcom);' ...
' eeglab(''redraw'');' ...
' end; clear EEGTMP tmpcom;' ];
colors = cell(1,length(opt.elec)); colors(:) = { 'k' };
colors(allrmchan) = { 'r' }; colors = colors(end:-1:1);
fprintf('%d electrodes labeled for rejection\n', length(find(allrmchan)));
tmpchanlocs = EEG.chanlocs;
if ~isempty(EEG.chanlocs), tmplocs = EEG.chanlocs(opt.elec); tmpelec = { tmpchanlocs(opt.elec).labels }';
else tmplocs = []; tmpelec = mattocell([1:EEG.nbchan]');
end;
eegplot(EEG.data(opt.elec,:,:), 'srate', EEG.srate, 'title', 'Scroll component activities -- eegplot()', ...
'limits', [EEG.xmin EEG.xmax]*1000, 'color', colors, 'eloc_file', tmplocs, 'command', tmpcom);
else
EEG = pop_select(EEG, 'nochannel', opt.elec(allrmchan));
end;
if nargin < 2
allrmchan = sprintf('EEG = pop_rejchanspec(EEG, %s);', vararg2str(options));
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_rejtrend.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_rejtrend.m
| 8,506 |
utf_8
|
10c0f6234434be6f374f52008cc4407d
|
% pop_rejtrend() - Measure linear trends in EEG data; reject data epochs
% containing strong trends.
% Usage:
% >> pop_rejtrend( INEEG, typerej); % pop up an interactive window
% >> OUTEEG = pop_rejtrend( INEEG, typerej, elec_comp, ...
% winsize, maxslope, minR, superpose, reject,calldisp);
%
% Pop-up window interface:
% "Electrode|Component number(s)" - [edit box] electrode or component number(s)
% to take into consideration during rejection. Sets the 'elec_comp'
% parameter in the command line call (see below).
% "Slope window width" - [edit box] integer number of consecutive data
% points to use in detecting linear trends. Sets the 'winsize'
% parameter in the command line call.
% "Maximum slope to allow" - [edit box] maximal absolute slope of the
% linear trend to allow in the data. If electrode data, uV/epoch;
% if component data, std. dev./epoch. Sets the 'maxslope'
% parameter in the command line call.
% "R-square limit" -[edit box] maximal regression R-square (0 to 1) value
% to allow. Sets the 'minR' parameter in the command line call.
% This represents how "line-like" the rejected data should be; 0
% accepts everything that meets the slope requirement, 0.9 is visibly
% flat.
% "Display previous rejection marks?" - [edit box] either YES or NO.
% Sets the command line input option 'superpose'.
% "Reject marked trials?" - [edit box] either YES or NO.
% Sets the command line input option 'reject'.
% Command line inputs:
% INEEG - input EEG dataset
% typerej - [1|0] data to reject on: 0 = component activations;
% 1 = electrode data. {Default: 1}.
% elec_comp - [e1 e2 ...] electrode|component number(s) to take into
% consideration during rejection
% winsize - (integer) number of consecutive points
% to use in detecing linear trends
% maxslope - maximal absolute slope of the linear trend to allow in the data
% minR - minimal linear regression R-square value to allow in the data
% (= coefficient of determination, between 0 and 1)
% superpose - [0|1] 0 = Do not superpose marks on previous marks
% stored in the dataset; 1 = Show both types of marks using
% different colors. {Default: 0}
% reject - [1|0] 0 = Do not reject marked trials but store the
% labels; 1 = Reject marked trials. {Default: 1}
% calldisp - [0|1] 1 = Open scroll window indicating rejected trials
% 0 = Do not open scroll window. {Default: 1}
%
% Outputs:
% OUTEEG - output dataset with rejected trials marked for rejection
% Note: When eegplot() is called, modifications are applied to the current
% dataset at the end of the call to eegplot() (e.g., when the user presses
% the 'Reject' button).
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: rejtrend(), 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
% 01-25-02 reformated help & license -ad
% 03-07-02 added srate argument to eegplot call -ad
% 03-07-02 add the eeglab options -ad
function [EEG, com] = pop_rejtrend( EEG, icacomp, elecrange, winsize, ...
minslope, minstd, superpose, reject, calldisp);
com = '';
if nargin < 1
help pop_rejtrend;
return;
end;
if nargin < 2
icacomp = 1;
end;
if icacomp == 0
if isempty( EEG.icasphere )
ButtonName=questdlg( 'Do you want to run ICA now ?', ...
'Confirmation', 'NO', 'YES', 'YES');
switch ButtonName,
case 'NO', disp('Operation cancelled'); return;
case 'YES', [ EEG com ] = pop_runica(EEG);
end % switch
end;
end;
if exist('reject') ~= 1
reject = 1;
end;
if nargin < 3
% which set to save
% -----------------
promptstr = { fastif(icacomp==0, 'Component number(s), Ex: 2 4 5):', ...
'Electrode number(s), Ex: 2 4 5):'), ...
'Slope window width (in points)', ...
fastif(icacomp==0, ...
'Maximum slope to allow (uV/epoch)', ...
'Maximum slope to allow (std. dev./epoch)'), ...
'R-square limit to allow (0 to 1, Ex: 0.8):', ...
'Display previous rejection marks? (YES or NO)', ...
'Reject marked trial(s)? (YES or NO)' };
inistr = { ['1:' int2str(EEG.nbchan)], ...
int2str(EEG.pnts), ...
'0.5', ...
'0.3', ...
'NO', ...
'NO' };
result = inputdlg2( promptstr, fastif(~icacomp, 'Trend rejection in component(s) -- pop_rejtrend()', ...
'Data trend rejection -- pop_rejtrend()'), 1, inistr, 'pop_rejtrend');
size_result = size( result );
if size_result(1) == 0 return; end;
elecrange = result{1};
winsize = result{2};
minslope = result{3};
minstd = result{4};
calldisp = 1;
switch lower(result{5}), case 'yes', superpose=1; otherwise, superpose=0; end;
switch lower(result{6}), case 'yes', reject=1; otherwise, reject=0; end;
end;
if nargin < 7
superpose = 0;
reject = 0;
calldisp = 1;
end;
if nargin < 9
calldisp = 1;
end
if isstr(elecrange) % convert arguments if they are in text format
calldisp = 1;
elecrange = eval( [ '[' elecrange ']' ] );
winsize = eval( [ '[' winsize ']' ] );
minslope = eval( [ '[' minslope ']' ] );
minstd = eval( [ '[' minstd ']' ] );
end;
fprintf('Selecting trials...\n');
if icacomp == 1
[rej tmprejE] = rejtrend( EEG.data(elecrange, :, :), winsize, minslope, minstd);
rejE = zeros(EEG.nbchan, length(rej));
rejE(elecrange,:) = tmprejE;
else
% test if ICA was computed or if one has to compute on line
% ---------------------------------------------------------
icaacttmp = eeg_getdatact(EEG, 'component', elecrange);
[rej tmprejE] = rejtrend( icaacttmp, winsize, minslope, minstd);
rejE = zeros(size(icaacttmp,1), length(rej));
rejE(elecrange,:) = tmprejE;
end
rejtrials = find(rej > 0);
fprintf('%d channel(s) selected\n', size(elecrange(:), 1));
fprintf('%d/%d trial(s) marked for rejection\n', length(rejtrials), EEG.trials);
fprintf('The following trials have been marked for rejection\n');
fprintf([num2str(rejtrials) '\n']);
if calldisp
if icacomp == 1 macrorej = 'EEG.reject.rejconst';
macrorejE = 'EEG.reject.rejconstE';
else macrorej = 'EEG.reject.icarejconst';
macrorejE = 'EEG.reject.icarejconstE';
end;
colrej = EEG.reject.rejconstcol;
eeg_rejmacro; % script macro for generating command and old rejection arrays
if icacomp == 1
eegplot( EEG.data(elecrange,:,:), 'srate', ...
EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:});
else
eegplot( icaacttmp, 'srate', ...
EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:});
end;
end;
if ~isempty(rej)
if icacomp == 1
EEG.reject.rejconst = rej;
EEG.reject.rejconstE = rejE;
else
EEG.reject.icarejconst = rej;
EEG.reject.icarejconstE = rejE;
end;
if reject
EEG = pop_rejepoch(EEG, rej, 0);
end;
end;
%com = sprintf('Indexes = pop_rejtrend( %s, %d, [%s], %s, %s, %s, %d, %d);', ...
% inputname(1), icacomp, num2str(elecrange), num2str(winsize), num2str(minslope), num2str(minstd), superpose, reject );
com = [ com sprintf('%s = pop_rejtrend(%s,%s);', inputname(1), ...
inputname(1), vararg2str({icacomp,elecrange,winsize,minslope,minstd,superpose,reject})) ];
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_selectevent.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_selectevent.m
| 24,608 |
utf_8
|
4cc926ceeed20f4e4d5a975d4c884a9b
|
% pop_selectevent() - Find events in an EEG dataset. If the dataset
% is the only input, a window pops up to
% ask for the relevant parameter values.
%
% Usage: >> [EEGOUT,event_indices] = pop_selectevent( EEG, 'key1', value1, ...
% 'key2', value2, ... );
% Input:
% EEG - EEG dataset
%
% Optional inputs:
% 'latency' - [latency_range] latency range of events to include
% Ex: 'latency','400 <= 700' Include all events with
% latnecy in the range [400,700]
% 'omitlatency' - [latency_range] latency range of events to exclude
% 'type' - [type_range] event type(s) to include
% Ex: 'type',3 or [2 3 5] or 1:10
% 'omittype' - [type_range], type(s) of events to exclude
% 'event' - [event_range], indices of events to include
% 'omitevent' - [event_range], indices of events to exclude
% 'USER_VAR' - [VAR_range], 'USER_VAR' is any user-defined field in
% the event structure. Includes events with values of
% field 'USER_VAR' in the specified range. Use [vector]
% format for integers, 'min<max' format for real numbers.
% 'omitUSER_VAR' - [VAR_range], 'USER_VAR' range of events to exclude
% 'select' - ['normal'|'inverse'] invert the selection of events.
% {Default is 'normal'}
% 'deleteepochs' - ['on'|'off'] 'on' = Delete ALL epochs that do not include
% any of the specified events {Default = 'on'}.
% This option is relevant only for epoched datasets derived
% from continuous datasets.
% 'invertepochs' - ['on'|'off'] 'on' = Invert epoch selection. {Default = 'off'}.
% 'deleteevents' - ['on'|'off'] 'on' = Delete ALL events except
% the selected events. {Default = 'off'}.
% 'renametype' - [string] rename the type of selected events with the
% string given as parameter. {Default is [], do not rename
% field}.
% 'oldtypefield' - [string] in conjunction with the previous parameter,
% create a new field (whose 'name' is provided as parameter)
% to store the (old) type of the event whose type has been
% renamed. {Default is [], do not create field}.
%
% Outputs:
% EEGOUT - EEG dataset with the selected events only
% event_indices - indexes of the selected events
%
% Ex: [EEGTARGETS,target_indices] = pop_selectevent(EEG,'type',[1 6 11 16 21]);
%
% % Returns ONLY THOSE epochs containing any of the 5 specified
% types of target events.
%
% Note: By default, if several optional inputs are given, the function
% performs their conjunction (&).
% Boundary events are keeped by default??. (6/12/2014 Ramon)
%
% Author: Arnaud Delorme, CNL / Salk Institute, 27 Jan 2002-
%
% See also: eeg_eventformat(), pop_importevent()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 27 Jan 2002, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%02/01/2002 added inputgui and finalize function - ad
%02/06/2002 work on the header and event format - sm & ad
%02/09/2002 modify function according to new structure - ad
%02/12/2002 add getepoch compatibility - ad
%02/19/2002 add event indices & correct event selection - ad
function [EEG, Ievent, com] = pop_selectevent(EEG, varargin);
if nargin < 1
help pop_selectevent;
return;
end;
Ievent = [];
com ='';
event_indices = [];
% note that this function is also used for epochs
% -----------------------------------------------
I = [];
if isempty(EEG.event)
disp('Getevent: cannot deal with empty event structure');
return;
end;
% remove the event field if present
% ---------------------------------
allfields = fieldnames(EEG.event);
indexmatch = strmatch('urevent', allfields);
if ~isempty(indexmatch)
allfields = { allfields{1:indexmatch-1} allfields{indexmatch+1:end} };
end;
if nargin<2
geometry = { [0.6 2.1 1.2 0.8 ] };
uilist = { ...
{ 'Style', 'text', 'string', 'Field', 'horizontalalignment', 'center', 'fontweight', 'bold' }, ...
{} ...
{ 'Style', 'text', 'string', 'Selection', 'fontweight', 'bold' }, ...
{ 'Style', 'text', 'string', 'Set=NOT THESE', 'fontweight', 'bold' } };
% add all fields to graphic interface
% -----------------------------------
ind1 = strmatch('type', allfields, 'exact');
ind2 = strmatch('latency' , allfields, 'exact');
ind3 = strmatch('duration', allfields, 'exact');
neworder = [ ind2 ind3 ind1 setdiff(1:length(allfields), [ind1 ind2 ind3]) ];
allfields = { allfields{neworder} };
for index = 1:length(allfields)
% format the description to fit a help box
% ----------------------------------------
if index <= length( EEG.eventdescription )
tmptext = EEG.eventdescription{ neworder(index) };
if ~isempty(tmptext)
if size(tmptext,1) > 15, stringtext = [ tmptext(1,1:15) '...' ];
else stringtext = tmptext(1,:);
end;
else stringtext = 'no description'; tmptext = 'no description (use menu Edit > Event Field)';
end;
else stringtext = 'no description'; tmptext = 'no description (use menu Edit > Event Field)';
end;
descrip = { 'string', stringtext, 'callback', ['questdlg2(' vararg2str(tmptext) ...
',''Description of field ''''' allfields{index} ''''''', ''OK'', ''OK'');' ] };
% create the gui for this field
% -----------------------------
textfield = allfields{index};
if strcmp(textfield, 'latency') | strcmp(textfield, 'duration')
if EEG.trials > 1, textfield = [ textfield ' (ms)' ];
else textfield = [ textfield ' (s)' ];
end;
middletxt = { { 'Style', 'text', 'string', 'min' } { 'Style', 'edit', 'string', '' 'tag' [ 'min' allfields{index} ] } ...
{ 'Style', 'text', 'string', 'max' } { 'Style', 'edit', 'string', '' 'tag' [ 'max' allfields{index} ] } };
middlegeom = [ 0.3 0.35 0.3 0.35 ];
elseif strcmp(textfield, 'type')
commandtype = [ 'if ~isfield(EEG.event, ''type'')' ...
' errordlg2(''No type field'');' ...
'else' ...
' tmpevent = EEG.event;' ...
' if isnumeric(EEG.event(1).type),' ...
' [tmps,tmpstr] = pop_chansel(unique([ tmpevent.type ]));' ...
' else,' ...
' [tmps,tmpstr] = pop_chansel(unique({ tmpevent.type }));' ...
' end;' ...
' if ~isempty(tmps)' ...
' set(findobj(''parent'', gcbf, ''tag'', ''type''), ''string'', tmpstr);' ...
' end;' ...
'end;' ...
'clear tmps tmpv tmpevent tmpstr tmpfieldnames;' ];
middletxt = { { 'Style', 'edit', 'string', '' 'tag' 'type' } { 'Style', 'pushbutton', 'string', '...' 'callback' commandtype } };
middlegeom = [ 0.95 0.35 ];
else
middletxt = { { 'Style', 'edit', 'string', '' 'tag' textfield } };
middlegeom = 1.3;
end;
geometry = { geometry{:} [0.55 0.65 middlegeom 0.1 0.22 0.1] };
uilist = { uilist{:}, ...
{ 'Style', 'text', 'string', textfield }, ...
{ 'Style', 'pushbutton', descrip{:}, 'horizontalalignment', 'left' }, ...
middletxt{:}, ...
{ }, { 'Style', 'checkbox', 'string', ' ' 'tag' [ 'not' allfields{index} ] },{ } };
end;
% event indices
% -------------
uilist = { uilist{:} ...
{ 'Style', 'text', 'string', 'Event indices' }, ...
{ }, ...
{ 'Style', 'edit', 'string', '' 'tag' 'indices' }, ...
{ }, { 'Style', 'checkbox', 'string', ' ' 'tag' 'notindices' },{ } };
geometry = { geometry{:} [0.55 0.65 1.3 0.1 0.22 0.1] };
% rename/keep events
% ------------------
geometry = { geometry{:} [1] [1] [.1 2 .3 .2] [.1 1.5 0.5 0.5] [.1 1 0.5 1] [.1 1 0.5 1] };
uilist = { uilist{:} { } ...
{ 'Style', 'text', 'string','Event selection', 'fontweight', 'bold' } ...
{} { 'Style', 'checkbox', 'string','Select all events NOT selected above (Set this button and "all BUT" buttons (above) for logical OR)' 'tag' 'invertevent' } { } { } ...
{} { 'Style', 'checkbox', 'string','Keep only selected events and remove all other events', ...
'value', fastif(EEG.trials>1, 0, 1) 'tag' 'rmevents' } { } { } ...
{} { 'Style', 'text', 'string', 'Rename selected event type(s) as type:' } ...
{ 'Style', 'edit', 'string', '' 'tag' 'rename' } { } ...
{} { 'Style', 'text', 'string', 'Retain old event type name(s) in (new) field named:' } ...
{ 'Style', 'edit', 'string', '' 'tag' 'retainfield' } { } };
% epoch selections
% ----------------
if EEG.trials > 1
geometry = { geometry{:} [1] [0.1 2 0.5 0.5] [0.1 2 0.5 0.5]};
uilist = { uilist{:} ...
{ 'Style', 'text', 'string','Epoch selection', 'fontweight', 'bold' } ...
{ } { 'Style', 'checkbox', 'string','Remove epochs not referenced by any selected event', ...
'value', 1 'tag' 'rmepochs' } { } { } ...
{ } { 'Style', 'checkbox', 'string','Invert epoch selection', ...
'value', 0 'tag' 'invertepoch' } { } { } };
end;
[results tmp2 tmp3 res] = inputgui( geometry, uilist, 'pophelp(''pop_selectevent'')', 'Select events -- pop_selectevent()');
if length(results) == 0, return; end;
% decode inputs
% -------------
args = {};
if ~res.notindices, args = { args{:}, 'event', eval( [ '[' res.indices ']' ]) };
else args = { args{:}, 'omitevent', eval( [ '[' res.indices ']' ]) };
end;
for index = 1:length(allfields)
textfield = allfields{index};
tmpflag = getfield(res, [ 'not' textfield ]);
if strcmp(textfield, 'duration') | strcmp(textfield, 'latency')
tmpres = [];
minlat = getfield(res, [ 'min' textfield ]);
maxlat = getfield(res, [ 'max' textfield ]);
if ~isempty(minlat) & ~isempty(maxlat)
tmpres = [ minlat '<=' maxlat ];
end;
else
tmpres = getfield(res, textfield);
try, tmpres2 = eval( [ '[' tmpres ']' ] );
if ~isnumeric(tmpres2),
if tmpres(1) == ''''
tmpres = eval( [ '{' tmpres '}' ] );
else
tmpres = parsetxt( tmpres );
end;
else
tmpres = tmpres2;
end;
catch, tmpres = parsetxt( tmpres ); end;
end
if ~isempty(tmpres)
if ~tmpflag, args = { args{:}, textfield, tmpres };
else args = { args{:}, [ 'omit' textfield], tmpres };
end;
end;
end;
if res.invertevent, args = { args{:}, 'select', 'inverse' }; end;
if ~isempty(res.rename), args = { args{:}, 'renametype', res.rename }; end;
if ~isempty(res.retainfield), args = { args{:}, 'oldtypefield', res.retainfield }; end;
args = { args{:}, 'deleteevents', fastif(res.rmevents, 'on', 'off') };
if EEG.trials > 1
args = { args{:}, 'deleteepochs', fastif(res.rmepochs , 'on', 'off') };
args = { args{:}, 'invertepochs', fastif(res.invertepoch , 'on', 'off') };
end;
else % no interactive inputs
args = varargin;
end;
% setting default for the structure
% ---------------------------------
fieldlist = { 'event' 'integer' [] [1:length(EEG.event)] ;
'omitevent' 'integer' [] [] ;
'deleteepochs' 'string' { 'yes','no','on','off' } 'on' ;
'invertepochs' 'string' { 'on','off' } 'off' ;
'deleteevents' 'string' { 'yes','no','on','off' } 'off';
'renametype' 'string' [] '';
'oldtypefield' 'string' [] '';
'select' 'string' { 'normal','inverse','remove','keep' } 'normal' };
for index = 1:length(allfields)
fieldlist{end+1, 1} = allfields{index};
fieldlist{end , 2} = '';
fieldlist{end+1, 1} = [ 'omit' allfields{index} ];
fieldlist{end , 2} = '';
end;
g = finputcheck( args, fieldlist, 'pop_selectevent');
if isstr(g), error(g); end;
if isempty(g.event), g.event = [1:length(EEG.event)]; end;
if strcmpi(g.select, 'remove'), g.select = 'inverse'; end;
if strcmpi(g.select, 'keep' ), g.select = 'normal'; end;
if strcmpi(g.deleteepochs, 'yes' ), g.deleteepochs = 'on'; end;
if strcmpi(g.deleteepochs, 'no' ), g.deleteepochs = 'off'; end;
if ~isempty(g.oldtypefield) & isempty(g.renametype)
error('A name for the new type must be defined');
end;
% select the events to keep
% -------------------------
Ievent = g.event;
Ieventrem = g.omitevent;
for index = 1:length(allfields)
% convert the value if the field is a string field
% ------------------------------------------------
tmpvar = getfield(g, {1}, allfields{index});
if ~isempty(tmpvar)
if isnumeric(tmpvar)
if isstr(getfield( EEG.event, {1}, allfields{index}))
for tmpind = 1:length(tmpvar)
tmpvartmp{tmpind} = num2str(tmpvar(tmpind));
end;
tmpvar = tmpvartmp;
end;
elseif isstr(tmpvar) & isempty( findstr(tmpvar, '<='))
if isnumeric(getfield( EEG.event, {1}, allfields{index}))
error(['numerical values must be entered for field ''' allfields{index} '''']);
end;
end;
end;
if isstr(tmpvar) & isempty( findstr(tmpvar, '<='))
tmpvar = { tmpvar };
end;
% scan each field of EEG.event
% ----------------------------
if ~isempty( tmpvar )
if iscell( tmpvar ) % strings
eval( [ 'tmpevent = EEG.event; tmpvarvalue = {tmpevent(:).' allfields{index} '};'] );
Ieventtmp = [];
for index2 = 1:length( tmpvar )
tmpindex = transpose(find(strcmp(deblank(tmpvar{index2}), deblank(tmpvarvalue))));%Ramon: for bug 1318. Also for compatibility(strmatch will be deleted in next versions of MATLAB)
%tmpindex = strmatch( tmpvar{index2}, tmpvarvalue, 'exact');
if isempty( tmpindex ),
fprintf('Warning: ''%s'' field value ''%s'' not found\n', allfields{index}, tmpvar{index2});
end;
Ieventtmp = unique_bc( [ Ieventtmp; tmpindex ]);
end;
Ievent = intersect_bc( Ievent, Ieventtmp );
elseif isstr( tmpvar ) % real range
tmpevent = EEG.event;
% ======== JRI BUGFIX 3/6/14
%eval( [ 'tmpvarvalue = [ tmpevent(:).' allfields{index} ' ];'] );
tmpvarvalue = safeConcatenate(EEG.event, allfields{index});
min = eval(tmpvar(1:findstr(tmpvar, '<=')-1));
max = eval(tmpvar(findstr(tmpvar, '<=')+2:end));
if strcmp(allfields{index}, 'latency')
if EEG.trials > 1
tmpevent = EEG.event;
tmpvarvalue = eeg_point2lat(tmpvarvalue, {tmpevent.epoch}, EEG.srate, ...
[EEG.xmin EEG.xmax]*1000, 1E-3);
else
tmpvarvalue = eeg_point2lat(tmpvarvalue, ones(1,length(EEG.event)), EEG.srate, ...
[EEG.xmin EEG.xmax], 1);
end;
end;
if strcmp(allfields{index}, 'duration')
if EEG.trials > 1, tmpvarvalue = tmpvarvalue/EEG.srate*1000;
else tmpvarvalue = tmpvarvalue/EEG.srate;
end;
end;
Ieventlow = find( tmpvarvalue >= min);
Ieventhigh = find( tmpvarvalue <= max);
Ievent = intersect_bc( Ievent, intersect( Ieventlow, Ieventhigh ) );
else
if strcmp(allfields{index}, 'latency')
fprintf(['pop_selectevent warning: latencies are continuous values\n' ...
'so you may use the ''a<=b'' notation to select these values\n']);
end;
% ======== JRI BUGFIX 3/6/14
%eval( [ 'tmpevent = EEG.event; tmpvarvalue = [ tmpevent(:).' allfields{index} ' ];'] );
tmpvarvalue = safeConcatenate(EEG.event, allfields{index});
Ieventtmp = [];
for index2 = 1:length( tmpvar )
Ieventtmp = unique_bc( [ Ieventtmp find(tmpvarvalue == tmpvar(index2)) ] );
end;
Ievent = intersect_bc( Ievent, Ieventtmp );
end;
end;
% scan each field of EEG.event (omit)
% -----------------------------------
tmpvar = eval(['g.omit' allfields{index} ]);
if eval(['isstr(EEG.event(1).' allfields{index} ')' ]) & isnumeric(tmpvar) & ~isempty(tmpvar)
for tmpind = 1:length(tmpvar)
tmpvartmp{tmpind} = num2str(tmpvar(tmpind));
end;
tmpvar = tmpvartmp;
end;
if isstr(tmpvar) & isempty( findstr(tmpvar, '<='))
tmpvar = { tmpvar };
end;
if ~isempty( tmpvar )
if iscell( tmpvar )
eval( [ 'tmpevent = EEG.event; tmpvarvalue = {tmpevent(:).' allfields{index} '};'] );
Ieventtmp = [];
for index2 = 1:length( tmpvar )
tmpindex = strmatch( tmpvar{index2}, tmpvarvalue, 'exact');
if isempty( tmpindex ),
fprintf('Warning: ''%s'' field value ''%s'' not found\n', allfields{index}, tmpvar{index2});
end;
Ieventtmp = unique_bc( [ Ieventtmp; tmpindex ]);
end;
Ieventrem = union_bc( Ieventrem, Ieventtmp );
elseif isstr( tmpvar )
tmpevent = EEG.event;
% ======== JRI BUGFIX 3/6/14
%eval( [ 'tmpvarvalue = [ tmpevent(:).' allfields{index} ' ];'] );
tmpvarvalue = safeConcatenate(EEG.event, allfields{index});
min = eval(tmpvar(1:findstr(tmpvar, '<=')-1));
max = eval(tmpvar(findstr(tmpvar, '<=')+2:end));
if strcmp(allfields{index}, 'latency')
if EEG.trials > 1
tmpevent = EEG.event;
tmpvarvalue = eeg_point2lat(tmpvarvalue, {tmpevent.epoch}, EEG.srate, ...
[EEG.xmin EEG.xmax]*1000, 1E-3);
else
tmpvarvalue = eeg_point2lat(tmpvarvalue, ones(1,length(EEG.event)), EEG.srate, ...
[EEG.xmin EEG.xmax], 1);
end;
end;
if strcmp(allfields{index}, 'duration')
if EEG.trials > 1, tmpvarvalue = tmpvarvalue/EEG.srate*1000;
else tmpvarvalue = tmpvarvalue/EEG.srate;
end;
end;
Ieventlow = find( tmpvarvalue > min);
Ieventhigh = find( tmpvarvalue < max);
Ieventrem = union_bc( Ieventrem, intersect( Ieventlow, Ieventhigh ) );
else
if strcmp(allfields{index}, 'latency')
fprintf(['pop_selectevent warning: latencies are continuous values\n' ...
'so you may use the ''a<=b'' notation to select these values\n']);
end;
tmpevent = EEG.event;
% ======== JRI BUGFIX 3/6/14
%eval( [ 'tmpvarvalue = [ tmpevent(:).' allfields{index} ' ];'] );
tmpvarvalue = safeConcatenate(EEG.event, allfields{index});
Ieventtmp = [];
for index2 = 1:length( tmpvar )
Ieventtmp = unique_bc( [ Ieventtmp find( tmpvarvalue ==tmpvar(index2)) ] );
end;
Ieventrem = union_bc( Ieventrem, Ieventtmp );
end;
end;
end;
Ievent = setdiff_bc( Ievent, Ieventrem);
if strcmp(g.select, 'inverse')
Ievent = setdiff_bc( [1:length(EEG.event)], Ievent );
end;
% checking if trying to remove boundary events (in continuous data)
if isfield(EEG.event, 'type')
if isstr(EEG.event(1).type) & EEG.trials == 1
Ieventrem = setdiff_bc([1:length(EEG.event)], Ievent );
tmpevent = EEG.event;
boundaryindex = strmatch('boundary', { tmpevent(Ieventrem).type });
if ~isempty(boundaryindex)
boundaryindex = Ieventrem(boundaryindex);
Ievent = [ Ievent boundaryindex ];
end;
Ievent = sort(Ievent);
else boundaryindex = [];
end;
else boundaryindex = [];
end;
% rename events if necessary
% --------------------------
if ~isempty(g.renametype)
fprintf('Pop_selectevent: renaming %d selected events (out of %d)\n', length(Ievent), length(EEG.event));
if ~isempty(g.oldtypefield)
for index = setdiff_bc(Ievent, boundaryindex)
eval([ 'EEG.event(index).' g.oldtypefield '= EEG.event(index).type;']);
EEG.event(index).type = g.renametype;
end;
else
for index = setdiff_bc(Ievent, boundaryindex)
EEG.event(index).type = g.renametype;
end;
end;
end;
% Events: delete epochs
% ---------------------
if strcmp( lower(g.deleteepochs), 'on') & EEG.trials > 1
% ask for confirmation
% --------------------
Iepoch = ones(1, EEG.trials);
for index = 1:length(Ievent)
Iepoch(EEG.event(Ievent(index)).epoch) = 0;
end;
if strcmpi(g.invertepochs, 'on')
Iepoch = ~Iepoch;
end;
Iepoch = find(Iepoch == 0);
if length(Iepoch) == 0,
error('Empty dataset: all epochs have been removed');
end;
if nargin < 2
ButtonName=questdlg2(strvcat([ 'Warning: delete ' num2str(EEG.trials-length(Iepoch)) ...
' (out of ' int2str(EEG.trials) ') un-referenced epochs ?' ]), ...
'Confirmation', ...
'Cancel', 'Ok','Ok');
else ButtonName = 'ok'; end;
switch lower(ButtonName),
case 'cancel', return;
case 'ok',
if strcmpi(g.deleteevents, 'on')
EEG.event = EEG.event(Ievent);
end;
EEG = pop_select(EEG, 'trial', Iepoch);
end % switch
else
% delete events if necessary
% --------------------------
if strcmpi(g.deleteevents, 'on')
EEG.event = EEG.event(Ievent);
end;
end;
EEG = eeg_checkset(EEG, 'eventconsistency');
% generate the output command
% ---------------------------
argsout = {};
for index =1:2:length(args)
if ~isempty(args{index+1})
argsout = { argsout{:} args{index} args{index+1}};
end;
end;
com = sprintf('EEG = pop_selectevent( %s, %s);', inputname(1), vararg2str(argsout));
% chop the text so that it fits into the description window
% ---------------------------------------------------------
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;
% ======== JRI BUGFIX 3/6/14
% safely concatenate a numeric field that may contain empty values, replacing them with nans
% ---------------------------------------------------------
function tmpvarvalue = safeConcatenate(S, fieldname)
try
tmpvarvalue = {S.(fieldname)};
tmpvarvalue = cellfun(@(x) fastif(isempty(x),nan,x), tmpvarvalue);
catch
%keep this style for backwards compatibility?
eval( [ 'tmpvarvalue = {S(:).' fieldname ' };'] );
for itmp = 1:length(tmpvarvalue),
if isempty(tmpvarvalue{itmp}),
tmpvarvalue{itmp} = nan;
end
end
tmpvarvalue = cell2mat(tmpvarvalue);
end
% ======== JRI BUGFIX 3/6/14
|
github
|
ZijingMao/baselineeegtest-master
|
pop_saveh.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_saveh.m
| 2,630 |
utf_8
|
946d5b48194c0957d6393b94d4905de1
|
% pop_saveh() - save the EEGLAB session command history stored in ALLCOM
% or in the 'history' field of the current dataset
%
% Usage:
% >> pop_saveh( ALLCOM, filename, filepath);
% >> pop_saveh( EEG.history, filename, filepath);
%
% Inputs:
% ALLCOM - cell array of strings containing the EEGLAB command history
% EEG.history - history field of the current dataset
% filename - name of the file to save to (optional, default "eeglabhist.m"
% filepath - path of the file to save to (optional, default pwd)
%
% Author: Arnaud Delorme, CNL / Salk Institute, 22 March 2002
%
% See also: eegh(), eeglab()
% 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
% 01-25-02 reformated help & license -ad
% 03-29-02 added update menu -ad
function com = pop_saveh( allcoms, curfilename, curfilepath);
com = '';
if nargin < 1
help pop_saveh;
return;
end;
if nargin < 3
[curfilename, curfilepath] = uiputfile('eeglabhist.m', 'Save the EEGLAB session command history with .m extension -- pop_saveh()');
drawnow;
if curfilename == 0 return; end;
end;
fid = fopen( [ curfilepath '/' curfilename ], 'w');
if fid == -1
error('pop_saveh(): Cannot open named file');
end;
fprintf(fid, '%% EEGLAB history file generated on the %s\n', date);
fprintf(fid, '%% ------------------------------------------------\n');
if iscell(allcoms)
disp('Saving the EEGLAB session command history...');
for index = length(allcoms):-1:1
fprintf(fid, '%s\n', allcoms{index});
end;
fprintf(fid, 'eeglab redraw;\n');
else
disp('Saving the current EEG dataset command history...');
fprintf(fid, '%s\n', allcoms);
end;
fclose(fid);
if iscell(allcoms)
com = sprintf('pop_saveh( %s, ''%s'', ''%s'');', inputname(1), curfilename, curfilepath);
else
com = sprintf('pop_saveh( EEG.history, ''%s'', ''%s'');', curfilename, curfilepath);
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_resample.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_resample.m
| 9,995 |
utf_8
|
54415821c3cb9868db7b315fbecdd2f1
|
% pop_resample() - resample dataset (pop up window).
%
% Usage:
% >> [OUTEEG] = pop_resample( INEEG ); % pop up interactive window
% >> [OUTEEG] = pop_resample( INEEG, freq);
%
% Graphical interface:
% The edit box entitled "New sampling rate" contains the frequency in
% Hz for resampling the data. Entering a value in this box is the same
% as providing it in the 'freq' input from the command line.
%
% Inputs:
% INEEG - input dataset
% freq - frequency to resample (Hz)
%
% Outputs:
% OUTEEG - output dataset
%
% Author: Arnaud Delorme, CNL/Salk Institute, 2001
%
% Note: uses the resample() function from the signal processing toolbox
% if present. Otherwise use griddata interpolation method (it should be
% reprogrammed using spline interpolation for speed up).
%
% See also: resample(), eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% 03-08-02 remove ica activity resampling (now set to []) -ad
% 03-08-02 debug call to function help -ad
% 04-05-02 recompute event latencies -ad
function [EEG, command] = pop_resample( EEG, freq);
command = '';
if nargin < 1
help pop_resample;
return;
end;
if isempty(EEG(1).data)
disp('Pop_resample error: cannot resample empty dataset'); return;
end;
if nargin < 2
% popup window parameters
% -----------------------
promptstr = {['New sampling rate']};
inistr = { num2str(EEG(1).srate) };
result = inputdlg2( promptstr, 'Resample current dataset -- pop_resample()', 1, inistr, 'pop_resample');
if length(result) == 0 return; end;
freq = eval( result{1} );
end;
% process multiple datasets
% -------------------------
if length(EEG) > 1
[ EEG command ] = eeg_eval( 'pop_resample', EEG, 'warning', 'on', 'params', { freq } );
return;
end;
% finding the best ratio
[p,q] = rat(freq/EEG.srate, 0.0001); % not used right now
% set variable
% ------------
EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts, EEG.trials);
oldpnts = EEG.pnts;
% resample for multiple channels
% -------------------------
if isfield(EEG, 'event') & isfield(EEG.event, 'type') & isstr(EEG.event(1).type)
tmpevent = EEG.event;
bounds = strmatch('boundary', { tmpevent.type });
if ~isempty(bounds),
disp('Data break detected and taken into account for resampling');
bounds = [ tmpevent(bounds).latency ];
bounds(bounds <= 0 | bounds > size(EEG.data,2)) = []; % Remove out of range boundaries
bounds(mod(bounds, 1) ~= 0) = round(bounds(mod(bounds, 1) ~= 0) + 0.5); % Round non-integer boundary latencies
end;
bounds = [1 bounds size(EEG.data, 2) + 1]; % Add initial and final boundary event
bounds = unique(bounds); % Sort (!) and remove doublets
else
bounds = [1 size(EEG.data,2) + 1]; % [1:size(EEG.data,2):size(EEG.data,2)*size(EEG.data,3)+1];
end;
eeglab_options;
if option_donotusetoolboxes
usesigproc = 0;
elseif exist('resample') == 2
usesigproc = 1;
else usesigproc = 0;
disp('Signal Processing Toolbox absent: using custom interpolation instead of resample() function.');
disp('This method uses cubic spline interpolation after anti-aliasing (see >> help spline)');
end;
fprintf('resampling data %3.4f Hz\n', EEG.srate*p/q);
eeglab_options;
for index1 = 1:size(EEG.data,1)
fprintf('%d ', index1);
sigtmp = reshape(EEG.data(index1,:, :), oldpnts, EEG.trials);
if index1 == 1
tmpres = [];
indices = [1];
for ind = 1:length(bounds)-1
tmpres = [ tmpres; myresample( double( sigtmp(bounds(ind):bounds(ind+1)-1,:)), p, q, usesigproc ) ];
indices = [ indices size(tmpres,1)+1 ];
end;
if size(tmpres,1) == 1, EEG.pnts = size(tmpres,2);
else EEG.pnts = size(tmpres,1);
end;
if option_memmapdata == 1
tmpeeglab = mmo([], [EEG.nbchan, EEG.pnts, EEG.trials]);
else tmpeeglab = zeros(EEG.nbchan, EEG.pnts, EEG.trials);
end;
else
for ind = 1:length(bounds)-1
tmpres(indices(ind):indices(ind+1)-1,:) = myresample( double( sigtmp(bounds(ind):bounds(ind+1)-1,:) ), p, q, usesigproc );
end;
end;
tmpeeglab(index1,:, :) = tmpres;
end;
fprintf('\n');
EEG.srate = EEG.srate*p/q;
EEG.data = tmpeeglab;
% recompute all event latencies
% -----------------------------
if isfield(EEG.event, 'latency')
fprintf('resampling event latencies...\n');
for iEvt = 1:length(EEG.event)
% From >> help resample: Y is P/Q times the length of X (or the
% ceiling of this if P/Q is not an integer).
% That is, recomputing event latency by pnts / oldpnts will give
% inaccurate results in case of multiple segments and rounded segment
% length. Error is accumulated and can lead to several samples offset.
% Blocker for boundary events.
% Old version EEG.event(index1).latency = EEG.event(index1).latency * EEG.pnts /oldpnts;
% Recompute event latencies relative to segment onset
if strcmpi(EEG.event(iEvt).type, 'boundary') && mod(EEG.event(iEvt).latency, 1) == 0.5 % Workaround to keep EEGLAB style boundary events at -0.5 latency relative to DC event; actually incorrect
iBnd = sum(EEG.event(iEvt).latency + 0.5 >= bounds);
EEG.event(iEvt).latency = indices(iBnd) - 0.5;
else
iBnd = sum(EEG.event(iEvt).latency >= bounds);
EEG.event(iEvt).latency = (EEG.event(iEvt).latency - bounds(iBnd)) * p / q + indices(iBnd);
end
end
if isfield(EEG, 'urevent') & isfield(EEG.urevent, 'latency')
try
for iUrevt = 1:length(EEG.urevent)
% Recompute urevent latencies relative to segment onset
if strcmpi(EEG.urevent(iUrevt).type, 'boundary') && mod(EEG.urevent(iUrevt).latency, 1) == 0.5 % Workaround to keep EEGLAB style boundary events at -0.5 latency relative to DC event; actually incorrect
iBnd = sum(EEG.urevent(iUrevt).latency + 0.5 >= bounds);
EEG.urevent(iUrevt).latency = indices(iBnd) - 0.5;
else
iBnd = sum(EEG.urevent(iUrevt).latency >= bounds);
EEG.urevent(iUrevt).latency = (EEG.urevent(iUrevt).latency - bounds(iBnd)) * p / q + indices(iBnd);
end
end;
catch
disp('pop_resample warning: ''urevent'' problem, reinitializing urevents');
EEG = rmfield(EEG, 'urevent');
end;
end;
EEG = eeg_checkset(EEG, 'eventconsistency');
end;
% resample for multiple channels ica
EEG.icaact = [];
% store dataset
fprintf('resampling finished\n');
EEG.setname = [EEG.setname ' resampled'];
EEG.pnts = size(EEG.data,2);
EEG.xmax = EEG.xmin + (EEG.pnts-1)/EEG.srate; % cko: recompute xmax, since we may have removed a few of the trailing samples
EEG.times = linspace(EEG.xmin*1000, EEG.xmax*1000, EEG.pnts);
command = sprintf('EEG = pop_resample( %s, %d);', inputname(1), freq);
return;
% resample if resample is not present
% -----------------------------------
function tmpeeglab = myresample(data, pnts, new_pnts, usesigproc);
if length(data) < 2
tmpeeglab = data;
return;
end;
%if size(data,2) == 1, data = data'; end;
if usesigproc
% padding to avoid artifacts at the beginning and at the end
% Andreas Widmann May 5, 2011
%The pop_resample command introduces substantial artifacts at beginning and end
%of data when raw data show DC offset (e.g. as in DC recorded continuous files)
%when MATLAB Signal Processing Toolbox is present (and MATLAB resample.m command
%is used).
%Even if this artifact is short, it is a filtered DC offset and will be carried
%into data, e.g. by later highpass filtering to a substantial amount (easily up
%to several seconds).
%The problem can be solved by padding the data at beginning and end by a DC
%constant before resampling.
[p, q] = rat(pnts / new_pnts, 1e-12); % Same precision as in resample
N = 10; % Resample default
nPad = ceil((max(p, q) * N) / q) * q; % # datapoints to pad, round to integer multiple of q for unpadding
tmpeeglab = resample([data(ones(1, nPad), :); data; data(end * ones(1, nPad), :)], pnts, new_pnts);
nPad = nPad * p / q; % # datapoints to unpad
tmpeeglab = tmpeeglab(nPad + 1:end - nPad, :); % Remove padded data
return;
end;
% anti-alias filter
% -----------------
data = eegfiltfft(data', 256, 0, 128*pnts/new_pnts); % Downsample from 256 to 128 times the ratio of freq.
% Code was verified by Andreas Widdman March 2014
% spline interpolation
% --------------------
X = [1:length(data)];
nbnewpoints = length(data)*pnts/new_pnts;
nbnewpoints2 = ceil(nbnewpoints);
lastpointval = length(data)/nbnewpoints*nbnewpoints2;
XX = linspace( 1, lastpointval, nbnewpoints2);
cs = spline( X, data);
tmpeeglab = ppval(cs, XX)';
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_eventformat.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_eventformat.m
| 3,014 |
utf_8
|
d06b550e78556cb151a924c2b32b19f9
|
% eeg_eventformat() - Convert the event information of a dataset from struct
% to array or vice versa.
%
% Usage: >> [eventout fields] = eeg_eventformat( event, 'format', fields );
%
% Inputs:
% event - event array or structure
% format - ['struct'|'array'] see below
% fields - [optional] cell array of strings containing the names of
% the event struct fields. If this field is empty, it uses
% the following list for
% the names of the fields { 'type' 'latency' 'var1' ...
% 'var2' ... }.
% Output:
% eventout - output event array or structure
% fields - output cell array with the name of the fields
%
% Event formats:
% struct - Events are organised as an array of structs with at
% least two fields ('type' and 'latency')
% (Ex: reaction_time may be type 1).
% array - events are organized as an array, the first column
% representing the type, the second the latency and the
% other ones user-defined variables.
%
% Note: 1) The event structure is defined only for continuous data
% or epoched data derived from continuous data.
% 2) The event 'struct' format is more comprehensible.
% For instance, to see all the properties of event 7,
% type >> EEG.event(7)
% Unfortunately, structures are awkward for expert users to deal
% with from the command line (Ex: To get an array of latencies,
% >> [ EEG.event(:).latency ] )
% In array format, the same information is obtained by typing
% >> EEG.event(:,2)
% 3) This function automatically updates the 'eventfield'
% cell array depending on the format.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 27 Jan 2002
%
% See also: eeglab(), pop_selectevent(), pop_importevent()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 27 Jan 2002, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 2/06/02 modifed header - sm & ad
% 2/08/02 add field input - ad
% 2/12/02 reprogrammed function using epochformat.m - ad
function [event, eventfield] = eeg_eventformat(event, format, fields);
if nargin < 2
help eeg_eventformat;
return;
end;
if exist('fields') ~= 1, fields = { 'type', 'latency' }; end;
[event eventfield] = eeg_epochformat( event, format, fields);
|
github
|
ZijingMao/baselineeegtest-master
|
pop_newset.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_newset.m
| 27,050 |
utf_8
|
beafde40b79628c3a9ebfcfecb56c54e
|
% pop_newset() - Edit/save EEG dataset structure information.
%
% Usage:
% >> [ALLEEG EEG CURRENTSET] = pop_newset( ALLEEG, EEG, CURRENTSET,...
% 'key', val,...);
% Inputs and outputs:
% ALLEEG - array of EEG dataset structures
% EEG - current dataset structure or structure array
% CURRENTSET - index(s) of the current EEG dataset(s) in ALLEEG
%
% Optional inputs:
% 'setname' - ['string'] name for the new dataset
% 'comments' - ['string'] comments on the new dataset
% 'overwrite' - ['on'|'off'] overwrite the old dataset
% 'saveold' - ['filename'] filename in which to save the old dataset
% 'savenew' - ['filename'] filename in which to save the new dataset
% 'retrieve' - [index] retrieve the old dataset (ignore recent changes)
%
% Note: Calls eeg_store() which may modify the variable ALLEEG
% containing the current dataset(s).
%
% Author: Arnaud Delorme, CNL / Salk Institute, 23 Arpil 2002
%
% See also: eeg_store(), pop_editset(), eeglab()
% Copyright (C) 23 Arpil 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
% 'aboutparent' - ['on'|'off'] insert reference to parent dataset in the comments
% testing: both options must be tested with datasets that have 2
% files (.set and .dat) and with dataset using a single file
%
% Option when only one dataset is kept in memory
%
% *********** When STUDY present ***********
% Study selected -> select single dataset
% Study selected -> select multiple datasets
% Several dataset selected -> select single dataset
% Several dataset selected -> select other several datasets
% Several dataset selected -> select study
% Dataset (not modified) selected -> select study
% Dataset (not modified) selected -> select multiple datasets
% Dataset (not modified) selected -> select other single dataset
% Dataset (not modified) selected -> create new dataset (eg. resample)
% Dataset (modified) selected -> select study
% Dataset (modified) selected -> select multiple datasets
% Dataset (modified) selected -> select other single dataset
% Dataset (modified) selected -> create new dataset (eg. resample)
% *********** When study absent ************
% Several dataset selected -> select single dataset
% Several dataset selected -> select other several datasets
% Dataset (not modified) selected -> select multiple datasets
% Dataset (not modified) selected -> select other single dataset
% Dataset (not modified) selected -> create new dataset (eg. resample)
% Dataset (modified) selected -> select multiple datasets
% Dataset (modified) selected -> select other single dataset
% Dataset (modified) selected -> create new dataset (eg. resample)
%
% Option when several datasets can be kept in memory
%
% *********** When STUDY present ***********
% Study selected -> select single dataset
% Study selected -> select multiple datasets
% Several dataset selected -> select single dataset
% Several dataset selected -> select other several datasets
% Several dataset selected -> select study
% Dataset (not modified) selected -> select study
% Dataset (not modified) selected -> select multiple datasets
% Dataset (not modified) selected -> select other single dataset
% Dataset (not modified) selected -> create new dataset (eg. resample)
% Dataset (modified) selected -> select study
% Dataset (modified) selected -> select multiple datasets
% Dataset (modified) selected -> select other single dataset
% Dataset (modified) selected -> create new dataset (eg. resample)
% *********** When study absent ************
% Several dataset selected -> select single dataset
% Several dataset selected -> select other several datasets
% Dataset (not modified) selected -> select multiple datasets
% Dataset (not modified) selected -> select other single dataset
% Dataset (not modified) selected -> create new dataset (eg. resample)
% Dataset (modified) selected -> select multiple datasets
% Dataset (modified) selected -> select other single dataset
% Dataset (modified) selected -> create new dataset (eg. resample)
function [ALLEEG, EEG, CURRENTSET, com] = pop_newset( ALLEEG, EEG, OLDSET, varargin);
% pop_newset( ALLEEG, EEG, 1, 'retrieve', [], 'study', [1] (retreiving a study)
verbose = 0;
if nargin < 3
help pop_newset;
return;
end;
CURRENTSET = OLDSET;
com = sprintf('[ALLEEG EEG CURRENTSET] = pop_newset(ALLEEG, EEG, %s); ', vararg2str( { OLDSET varargin{:} } ));
[g varargin] = finputcheck(varargin, { ...
'gui' 'string' { 'on';'off' } 'on'; % []=none; can be multiple numbers
'retrieve' 'integer' [] []; % []=none; can be multiple numbers
'study' 'integer' [0 1] 0; % important because change behavior for modified datasets
}, 'pop_newset', 'ignore');
if isstr(g), error(g); end;
eeglab_options;
if length(EEG) > 1
% ***************************************************
% case 1 -> multiple datasets in memory (none has to be saved), retrieving single dataset
% ***************************************************
if ~isempty(g.retrieve)
[EEG, ALLEEG, CURRENTSET] = eeg_retrieve( ALLEEG, g.retrieve);
elseif length(OLDSET) == length(EEG)
% ***************************************************
% case 2 -> multiple datasets processed, storing them
% ***************************************************
[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, OLDSET);
else
% ***************************************************
% case 3 -> multiple datasets processed, storing new copies (not used in EEGLAB)
% ***************************************************
if strcmpi(EEG(1).saved, 'justloaded')
for ieeg = 1:length(EEG)
[ALLEEG TMP OLDSET] = pop_newset(ALLEEG, EEG(ieeg), OLDSET);
end;
CURRENTSET = OLDSET;
EEG = TMP;
else
[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG);
end;
end;
return;
elseif ~isempty(g.retrieve) % command line call
% ***************************************************
% case 4 -> single dataset, does not have to be saved,
% retrieving another dataset
% ***************************************************
if verbose, disp('Case 4'); end;
if ~(option_storedisk & strcmpi(EEG.saved, 'no'))
if strcmpi(EEG.saved, 'yes') & option_storedisk
fprintf('pop_newset(): Dataset %d has not been modified since last save, so did not resave it.\n', OLDSET);
EEG = update_datafield(EEG);
tmpsave = EEG.saved;
EEG = eeg_hist(EEG, com);
[ALLEEG EEG] = eeg_store(ALLEEG, EEG, OLDSET);
EEG.saved = tmpsave; % eeg_store automatically set it to 'no'
ALLEEG(OLDSET).saved = tmpsave;
end;
if ~isempty(g.retrieve)
[EEG, ALLEEG, CURRENTSET] = eeg_retrieve( ALLEEG, g.retrieve);
end;
return;
end;
end;
if isempty(EEG)
args = { 'retrieve', OLDSET }; % cancel
elseif length(varargin) == 0 & length(EEG) == 1 & strcmpi(g.gui, 'on') % if several arguments, assign values
% popup window parameters
% -----------------------
text_new = 'What do you want to do with the new dataset?';
comcomment = ['tmpuserdat = get(gcbf, ''userdata'');' ...
'tmpuserdat = pop_comments(tmpuserdat, ''Edit dataset comments'');' ...
'set(gcbf, ''userdata'', tmpuserdat); clear tmpuserdat;'];
comsavenew = ['[tmpfile tmppath] = uiputfile(''*.set'', ''Enter filename''); drawnow;' ...
'if tmpfile ~= 0,' ...
' set(findobj(''parent'', gcbf, ''tag'', ''filenamenew''), ''string'', fullfile(tmppath, tmpfile));' ...
'end;' ...
'clear tmpuserdat tmpfile tmppath;'];
cb_savenew = [ 'set(findobj(gcbf, ''userdata'', ''filenamenew''), ''enable'', fastif(get(gcbo, ''value''), ''on'', ''off''));' ];
cb_saveold = [ 'set(findobj(gcbf, ''userdata'', ''filenameold''), ''enable'', fastif(get(gcbo, ''value''), ''on'', ''off''));' ];
comsaveold = ['[tmpfile tmppath] = uiputfile(''*.set'', ''Enter filename''); drawnow;' ...
'if tmpfile ~= 0,' ...
' set(findobj(''parent'', gcbf, ''tag'', ''filenameold''), ''string'', fullfile(tmppath, tmpfile));' ...
'end;' ...
'clear tmpuserdat tmpfile tmppath;'];
enable_saveold = 'off';
enable_savenew = 'off';
value_saveold = 0;
value_savenew = 0;
value_owrt = 0;
cb_owrt = '';
userdat = EEG.comments;
% status of parent dataset etc...
saved = 1;
filenameold = '';
filenamenew = '';
if ~isempty(ALLEEG) & any(OLDSET ~= 0) & length(OLDSET) == 1
if strcmpi(ALLEEG(OLDSET).saved, 'no')
saved = 0;
if ~isempty(ALLEEG(OLDSET).filename)
filenameold = fullfile(ALLEEG(OLDSET).filepath, ALLEEG(OLDSET).filename);
end;
end;
end;
overwrite_or_save = 0;
have_to_save_new = 0;
% ***************************************************
% case 5 -> single dataset, has to be saved, one dataset to retreive and study present or several dataset to retrieve
% ***************************************************
if length(g.retrieve) > 1 | ( g.study & ~isempty(g.retrieve)) % selecting several datasets or a study is present
if verbose, disp('Case 5'); end;
text_new = 'Current dataset has not been saved. Saved it or reload it from disk.';
text_old = '';
have_to_save_new = 1;
value_savenew = 1;
enable_savenew = 'on';
filenamenew = fullfile(EEG.filepath, EEG.filename);
cb_savenew = [ 'if ~get(gcbo, ''value'') & ~get(findobj(gcbf, ''tag'', ''cb_loadold''), ''value''),' ...
' set(gcbo, ''value'', 1);' ...
' warndlg2(strvcat(''You must enter a filename for the dataset or use the copy on disk!'','' '',' ...
' ''It must be saved or you must use the old dataset on disk because, by your current memory'',' ...
' ''option, only one full dataset or study can be kept in memory. Note that if you choose to'',' ...
' ''save the dataset, this will be taken into account in the study.''));' ...
'else, ' cb_savenew ...
'end;' ];
% ***************************************************
% case 6 -> single dataset modified or not, study is present (the old
% dataset has to be replaced to preserve study consistency)
% ***************************************************
elseif g.study == 1 & isempty(g.retrieve)
if verbose, disp('Case 6'); end;
if saved
text_old = 'The old dataset has not been modified since last saved. What do you want to do with it?';
cb_saveold = '';
else
text_old = 'Some changes have not been saved. What do you want to do with the old dataset?';
end;
cb_owrt = [ ...
' set(gcbo, ''value'', 1);' ...
' warndlg2(strvcat(''Cannot unset the overwrite checkbox!'','' '',' ...
'''The old dataset must be overwriten since all datasets'',' ...
'''must be in the STUDY.''), ''warning'');' ];
value_owrt = 1;
filenamenew = fullfile(EEG.filepath, EEG.filename);
% ***************************************************
% case 7 -> single dataset modified, study is absent, old copy has to
% be flush to disk or overwritten
% ***************************************************
elseif ~saved & option_storedisk
if verbose, disp('Case 7'); end;
text_old = 'Some changes have not been saved. What do you want to do with the old dataset?';
cb_saveold = [ 'if ~get(findobj(gcbf, ''tag'', ''cb_owrt''), ''value''),' ...
' set(gcbo, ''value'', 1);' ...
' warndlg2(strvcat(''Cannot unset the save checkbox!'','' '',' ...
'''By your selected memory option, only one full dataset'',' ...
'''can be kept in memory. Thus, you must either'',' ...
'''save or delete/overwrite the old dataset.''));' ...
'else, ' cb_saveold ...
'end;' ];
cb_owrt = [ 'if ~get(findobj(gcbf, ''tag'', ''cb_saveold''), ''value''),' ...
' set(gcbo, ''value'', 1);' ...
' warndlg2(strvcat(''Cannot unset the overwrite checkbox!'','' '',' ...
'''By your memory option, only one full dataset'',' ...
'''can be kept in memory. Thus, you must either'',' ...
'''save or delete/overwrite the old dataset.''));' ...
'end;' ];
enable_saveold = 'on';
value_saveold = 1;
overwrite_or_save = 1;
elseif ~saved
% ***************************************************
% case 8 -> single dataset modified, study is absent, no constraint on saving
% ***************************************************
if verbose, disp('Case 8'); end;
text_old = 'Some changes have not been saved. What do you want to do with the old dataset?';
else
% ***************************************************
% case 9 -> single dataset not modified, study is absent, no constraint on saving
% ***************************************************
if verbose, disp('Case 9'); end;
text_old = 'What do you want to do with the old dataset (not modified since last saved)?';
cb_saveold = '';
cb_overwrite = 'Overwrite current dataset|New dataset';
end;
geometry = { [1] [0.15 0.5 1 0.5] [0.15 0.5 1 0.5] [1] [1] [0.15 1.8 0.1 0.1] [0.15 0.5 1 0.5] };
geomvert = [ ];
uilist = { ...
{ 'style', 'text', 'string', text_new, 'fontweight', 'bold' } ...
{} ...
{ 'Style', 'text', 'string', 'Name it:' } ...
{ 'Style', 'edit', 'string', EEG.setname 'tag' 'namenew' } ...
{ 'Style', 'pushbutton', 'string', 'Edit description', 'callback', comcomment } ...
{ 'Style', 'checkbox' , 'string', '', 'callback', cb_savenew 'value' value_savenew 'tag' 'cb_savenew' } ...
{ 'Style', 'text', 'string', 'Save it as file:' } ...
{ 'Style', 'edit', 'string', filenamenew, 'tag', 'filenamenew' 'userdata' 'filenamenew' 'enable' enable_savenew } ...
{ 'Style', 'pushbutton', 'string', 'Browse', 'callback', comsavenew 'userdata' 'filenamenew' 'enable' enable_savenew } ...
{ } ...
{ 'style', 'text', 'string', text_old 'fontweight' 'bold' } ...
{ 'Style', 'checkbox' , 'string', '' 'tag' 'cb_owrt' 'callback' cb_owrt 'value' value_owrt } ...
{ 'Style', 'text' , 'string', 'Overwrite it in memory (set=yes; unset=create a new dataset)' } {} ...
{ } ...
{ 'Style', 'checkbox' , 'string', '', 'callback', cb_saveold 'value' value_saveold 'tag' 'cb_saveold' } ...
{ 'Style', 'text' , 'string', 'Save it as file:' } ...
{ 'Style', 'edit' , 'string', filenameold, 'tag', 'filenameold' 'userdata' 'filenameold' 'enable' enable_saveold } ...
{ 'Style', 'pushbutton', 'string', 'Browse', 'callback', comsaveold 'userdata' 'filenameold' 'enable' enable_saveold } };
% remove old dataset if not present
% ---------------------------------
if OLDSET == 0
uilist = uilist(1:9);
geometry = geometry(1:3);
end;
if isempty(cb_saveold)
uilist(end-3:end) = [];
geometry(end) = [];
end;
% update GUI for selecting multiple datasets
% ------------------------------------------
if length(g.retrieve) > 1 | ( g.study & ~isempty(g.retrieve)) % selecting several datasets or a study is present
uilist = uilist(1:9);
geometry = geometry(1:3);
if ~isempty(EEG.filename)
cb_loadold = [ 'if ~get(gcbo, ''value'') & ~get(findobj(gcbf, ''tag'', ''cb_savenew''), ''value''),' ...
' set(gcbo, ''value'', 1);' ...
' warndlg2(strvcat(''You must enter a filename for the dataset or use the copy on disk!'','' '',' ...
' ''It must be saved or you must use the old dataset on disk because, by your current memory option, only one full'',' ...
' ''dataset or study can be kept in memory. This will also affect the'',' ...
' ''dataset at this position in the study.''));' ...
'end;' ];
uilist{end+1} = { 'Style', 'checkbox' , 'string', '', 'callback', cb_loadold 'tag' 'cb_loadold' };
uilist{end+1} = { 'Style', 'text', 'string', 'Reload copy from disk (will be done after optional saving above)' };
uilist{end+1} = {};
uilist{end+1} = {};
geometry = { geometry{:} [0.12 1.6 0.2 0.2] };
end;
end;
% remove new dataset if already saved
% -----------------------------------
if ~isfield(EEG, 'saved')
EEG = eeg_checkset(EEG);
end;
if strcmpi(EEG.saved, 'justloaded') | ~isempty(g.retrieve)
if overwrite_or_save % only pop-up a window if some action has to be taken
uilist = uilist(11:end);
geometry = geometry(5:end);
uilist(3) = {{ 'Style', 'text' , 'string', 'Delete it from memory (set=yes)' }};
elseif isempty(g.retrieve) % just loaded from disk
% remove data from file for old dataset
% -------------------------------------
if option_storedisk & ~isempty(ALLEEG) & OLDSET ~= 0
if ~isfield(ALLEEG(OLDSET), 'datfile'), ALLEEG(OLDSET).datfile = ''; end;
ALLEEG(OLDSET) = update_datafield(ALLEEG(OLDSET));
end;
[ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG, 0); % 0 means that it is saved on disk
com = '[ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG, 0 );';
return;
end;
end;
% show GUI (do not return if old dataset has to be saved or overwritten)
% ----------------------------------------------------------------------
cont = 1;
while cont
[result userdat tmp tags] = inputgui( 'geometry', geometry, 'uilist', uilist, 'helpcom', 'pophelp(''pop_newset'');', ...
'title', 'Dataset info -- pop_newset()', ...
'userdata', userdat, 'geomvert', geomvert);
try, tags.cb_owrt; catch, tags.cb_owrt = 0; end;
try, tags.cb_savenew; catch, tags.cb_savenew = 0; end;
try, tags.cb_saveold; catch, tags.cb_saveold = 0; end;
try, tags.cb_loadold; catch, tags.cb_loadold = 0; end;
try, tags.namenew; catch, tags.namenew = EEG.setname; end;
try, tags.filenamenew; catch, tags.filenamenew = ''; end;
cont = 0;
if ~isempty(result)
if overwrite_or_save & tags.cb_saveold % save but not overwrite
if isempty(tags.filenameold)
warndlg2(strvcat('Error: You must enter a filename for the old dataset!',' ', ...
'The old dataset must be saved because, by your', ...
'current memory option, only one full dataset', ...
'can be kept in memory. Thus, you must either', ...
'save or overwrite the old dataset.'));
cont = 1;
end;
end;
end;
if have_to_save_new
if isempty(result) % cancel
com = '';
drawnow;
return;
else
if isempty(tags.filenamenew) & tags.cb_savenew
warndlg2(strvcat('Error: You must enter a filename for the dataset!',' ', ...
'It must be saved because, by your current memory option, only one full', ...
'dataset or study can be kept in memory. Note that all changes will be', ...
'taken into account when processing the STUDY.'));
cont = 1;
end;
end;
end;
end;
drawnow;
% decode parameters
% -----------------
args = {};
if length(result) == 0,
if isempty(g.retrieve)
if isempty(OLDSET), error('Cancel operation'); end;
args = { 'retrieve', OLDSET }; % cancel
else
com = '';
return;
end;
else
% new dataset
% -----------
if ~strcmp(EEG.setname, tags.namenew )
args = { 'setname', tags.namenew };
end;
if tags.cb_savenew
if ~isempty(tags.filenamenew)
args = { args{:} 'savenew', tags.filenamenew };
else
disp('Warning: no filename given for new dataset, so it will not be saved to disk.');
end;
end;
if ~strcmp(EEG.comments, userdat)
args = { args{:} 'comments', userdat };
end;
if tags.cb_loadold
args = { args{:} 'reload' 'on' };
end;
% old dataset
% -----------
if tags.cb_owrt
args = { args{:} 'overwrite' 'on' };
end;
if tags.cb_saveold
if ~isempty(tags.filenameold)
args = { args{:} 'saveold', tags.filenameold };
else
disp('Warning: no file name given for the old dataset, so it will not be saved to disk.');
end;
end;
end;
elseif length(EEG) > 1
% processing multiple datasets
% ----------------------------
[ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG, OLDSET ); % it is possible to undo the operation here
com = '[ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG, CURRENTSET );';
return;
else
% no interactive inputs
args = varargin;
end;
% assigning values
% ----------------
overWflag = 0;
if isempty(g.retrieve) & ~isempty(EEG)
if strcmpi(EEG.saved, 'justloaded')
EEG.saved = 'yes';
else
EEG.saved = 'no';
end;
end;
for ind = 1:2:length(args)
switch lower(args{ind})
case 'setname' , EEG.setname = args{ind+1}; EEG = eeg_hist(EEG, [ 'EEG.setname=''' EEG.setname ''';' ]);
case 'comments' , EEG.comments = args{ind+1};
case 'reload' , EEG = pop_loadset('filename', EEG.filename, 'filepath', EEG.filepath, 'loadmode', 'info');
[ALLEEG EEG] = eeg_store(ALLEEG, EEG, OLDSET);
ALLEEG(OLDSET).saved = 'yes';
case 'retrieve' , if ~isempty(ALLEEG) & args{ind+1} ~= 0
EEG = eeg_retrieve(ALLEEG, args{ind+1});
else
EEG = eeg_emptyset;
end;
com = ''; return;
case { 'save' 'savenew' }, [filepath filename ext] = fileparts( args{ind+1} );
EEG = pop_saveset(EEG, [ filename ext ], filepath);
case 'saveold', [filepath filename ext] = fileparts( args{ind+1} );
TMPEEG = pop_saveset(ALLEEG(OLDSET), [ filename ext ], filepath);
[ALLEEG] = eeg_store(ALLEEG, TMPEEG, OLDSET);
ALLEEG(OLDSET).saved = 'yes';
case 'overwrite' , if strcmpi(args{ind+1}, 'on') | strcmpi(args{ind+1}, 'yes')
overWflag = 1; % so it can be done at the end
end;
otherwise, error(['pop_newset error: unrecognized key ''' args{ind} '''']);
end;
end;
% remove data from file if necessary
% ----------------------------------
if option_storedisk & ~isempty(ALLEEG) & OLDSET ~= 0
if ~isfield(ALLEEG, 'datfile'), ALLEEG(OLDSET).datfile = ''; end;
ALLEEG(OLDSET) = update_datafield(ALLEEG(OLDSET));
end;
% moving/erasing/creating datasets
% --------------------------------
if ~isempty(g.retrieve)
% in case the old dataset was modified
% ------------------------------------
if strcmpi(EEG.saved, 'yes')
[ALLEEG, EEG] = eeg_store( ALLEEG, EEG, OLDSET);
ALLEEG(OLDSET).saved = 'yes';
EEG.saved = 'yes';
else
[ALLEEG, EEG] = eeg_store( ALLEEG, EEG, OLDSET);
end;
% dataset retrieval
% -----------------
if overWflag % delete old dataset
ALLEEG = pop_delset( ALLEEG, OLDSET);
end;
[EEG, ALLEEG, CURRENTSET] = eeg_retrieve( ALLEEG, g.retrieve);
else
% new dataset
% -----------
if overWflag
if strcmpi(EEG.saved, 'yes')
[ALLEEG, EEG] = eeg_store( ALLEEG, EEG, OLDSET);
ALLEEG(OLDSET).saved = 'yes';
EEG.saved = 'yes';
else
[ALLEEG, EEG] = eeg_store( ALLEEG, EEG, OLDSET);
end;
else
if strcmpi(EEG.saved, 'yes') || strcmpi(EEG.saved, 'justloaded')
[ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG, 0); % 0 means that it is saved on disk
else
[ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG);
end;
end;
end;
com = sprintf('[ALLEEG EEG CURRENTSET] = pop_newset(ALLEEG, EEG, %s); ', vararg2str( { OLDSET args{:} 'gui' 'off' } ));
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 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
|
ZijingMao/baselineeegtest-master
|
pop_runscript.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_runscript.m
| 1,350 |
utf_8
|
e17c0b67edb0127bc40e128e564bcb2c
|
% pop_runscript() - Run Matlab script
%
% Usage: >> pop_runscript;
% >> pop_runscript( filename );
%
% Input:
% filename - [string] name of the file.
%
% Author: Arnaud Delorme, SCCN / INC / UCSD, August 2009
% Copyright (C) Arnaud Delorme, August 2009
%
% 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_runscript(filename);
com = [];
if nargin <1
[filename filepath] = uigetfile('*.*', 'Please select input script -- pop_runscript()');
if filename(1) == 0, return; end;
filename = fullfile(filepath, filename);
end;
str = readtxtfile(filename);
try
evalin('base', str);
catch
lasterr
end;
com = sprintf('pop_runscript(''%s'');', filename);
|
github
|
ZijingMao/baselineeegtest-master
|
pop_headplot.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_headplot.m
| 24,813 |
utf_8
|
a4984961bcc331f1b97faa890502c59a
|
% pop_headplot() - plot one or more spherically-splined EEG field maps
% using a semi-realistic 3-D head model. Requires a
% spline file, which is created first if not found.
% This may take some time, but does not need to be
% done again for this channel locations montage. A wait
% bar will pop up to indicate how much time remains.
% Usage:
% To open input GUI:
% >> EEGOUT = pop_headplot( EEG, typeplot)
% To run as a script without further GUI input:
% >> EEGOUT = pop_headplot( EEG, typeplot, ...
% latencies/components, title, rowscols, 'key', 'val' ...);
% Required Inputs:
% EEG - EEG dataset structure
% typeplot - 1=channel, 0=component {Default: 1}
%
% Required Inputs to bypass input GUI
% latencies/components - If channels, array of epoch mean latencies (in ms),
% Else, for components, array of component indices to plot.
%
% Optional inputs:
% title - Plot title
% rowscols - Vector of the form [m,n] where m is total vertical tiles and n
% horizontal tiles per page. If the number of maps exceeds m*n,
% multiple figures will be produced {def|0 -> 1 near-square page}
%
% Optional 'Key' 'Value' Paired Inputs
% 'setup' - ['name_of_file_to_save.spl'] Make the headplot spline file
% 'load' - ['name_of_file_to_load.spl'] Load the headplot spline file
% 'colorbar' - ['on' or 'off'] Switch to turn colorbar on or off. {Default: 'on'}
% others... - All other key-val calls are passed directly to headplot.
% See >> help headplot
%
% Output:
% EEGOUT - EEG dataset, possibly with a new or modified splinefile.
%
% Note:
% A new figure is created only when the pop_up window is called or when
% several channels/components are plotted. Therefore you may call this
% command to draw single 3-D topographic maps in an existing figure.
%
% Headplot spline file is a matlab .mat file with the extension .spl.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 20 March 2002
%
% See also: headplot(), eegplot(), traditional()
% Copyright (C) 20 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 [EEG, com] = pop_headplot( EEG, typeplot, arg2, topotitle, rowcols, varargin);
com = '';
if nargin < 1
help pop_headplot;
return;
end;
if isempty(EEG.chanlocs)
error('Pop_headplot: this dataset does not contain channel locations. Use menu item: Edit > Dataset info');
end;
if nargin < 3 % Open GUI input window
% remove old spline file
% ----------------------
if isfield(EEG, 'splinefile')
if ~isempty(EEG.splinefile) && exist(EEG.splinefile, 'file')
splfile = dir(EEG.splinefile);
byteperelec = splfile.bytes/EEG.nbchan;
if byteperelec/EEG.nbchan < 625, % old head plot file
EEG.splinefile = [];
disp('Warning: Wrong montage or old-version spline file version detected and removed; new spline file required');
end;
end;
end;
% show the file be recomputed
% ---------------------------
compute_file = 0;
if typeplot == 1 % ********** data plot
fieldname = 'splinefile';
if isempty(EEG.splinefile) && exist(EEG.splinefile, 'file')
if length(EEG.icachansind) == EEG.nbchan & ~isempty(EEG.icasplinefile)
EEG.splinefile = EEG.icasplinefile;
else
compute_file = 1;
end;
else
compute_file = 1;
end;
else % ************* Component plot
fieldname = 'icasplinefile';
if isempty(EEG.icasplinefile) && exist(EEG.icasplinefile, 'file')
if length(EEG.icachansind) == EEG.nbchan & ~isempty(EEG.splinefile)
EEG.icasplinefile = EEG.splinefile;
else
compute_file = 1;
end;
else
compute_file = 1;
end;
end;
if compute_file
warndlg2( strvcat('headplot() must generate a spline file the first', ...
'time it is called or after changes in the channel location file.', ...
'You must also co-register your channel locations with the', ...
'head template. Using a standard 10-20 system montage, default', ...
'parameters should allow creating the correct spline file.'), 'Headplot() warning');
else
pop_options = {};
end;
% graphic interface
% -----------------
template(1).keywords = { 'standard-10-5-cap385' };
template(1).transform = [ -0.355789 -6.33688 12.3705 0.0533239 0.0187461 -1.55264 1.06367 0.987721 0.932694 ];
%template(1).transform = [ -0.31937 -5.96928 13.1812 0.0509311 0.0172127 -1.55007 1.08221 1.00037 0.923518 ];
template(2).keywords = { 'standard_1005' };
template(2).transform = [ -1.13598 7.75226 11.4527 -0.0271167 0.0155306 -1.54547 0.912338 0.931611 0.806978 ];
% -0.732155 7.58141 11.8939 -0.0249659 0.0148571 0.0227427 0.932423 0.918943 0.793166 ];
template(3).keywords = { 'gsn' 'sfp' };
%template(3).transform = [ 0 -9 -9 -0.12 0 -1.6 9.7 10.7 11.5 ];
template(3).transform = [ 0.664455 -3.39403 -14.2521 -0.00241453 0.015519 -1.55584 11 10.1455 12];
template(4).keywords = { 'egi' 'elp' };
template(4).transform = [ 0.0773 -5.3235 -14.72 -0.1187 -0.0023 -1.5940 92.4 92.5 110.9 ];
transform = [];
if isfield(EEG.chaninfo, 'filename')
[tmp transform] = lookupchantemplate(lower(EEG.chaninfo.filename), template);
end;
if typeplot
txt = sprintf('Making headplots for these latencies (from %d to %d ms):', round(EEG.xmin*1000), round(EEG.xmax*1000));
else
%txt = ['Component numbers (negate index to invert component polarity):' 10 '(NaN -> empty subplot)(Ex: -1 NaN 3)'];
txt = ['Component numbers to plot (negative numbers invert comp. polarities):' ];
end;
if compute_file
enableload = 'off';
enablecomp = 'on';
else
enableload = 'on';
enablecomp = 'off';
end;
cb_load = [ 'set(findobj(gcbf, ''tag'', ''load''), ''enable'', ''on'');' ...
'set(findobj(gcbf, ''tag'', ''comp''), ''enable'', ''off'');' ...
'set(findobj(gcbf, ''tag'', ''compcb''), ''value'', 0);' ];
cb_comp = [ 'set(findobj(gcbf, ''tag'', ''load''), ''enable'', ''off'');' ...
'set(findobj(gcbf, ''tag'', ''comp''), ''enable'', ''on'');' ...
'set(findobj(gcbf, ''tag'', ''loadcb''), ''value'', 0);' ];
cb_browseload = [ '[filename, filepath] = uigetfile(''*.spl'', ''Select a spline file'');' ...
'if filename ~=0,' ...
' set(findobj( gcbf, ''userdata'', ''load''), ''string'', fullfile(filepath,filename));' ...
'end;' ...
'clear filename filepath tagtest;' ];
cb_browsecomp = [ '[filename, filepath] = uiputfile(''*.spl'', ''Select a spline file'');' ...
'if filename ~=0,' ...
' set(findobj( gcbf, ''userdata'', ''coregfile''), ''string'', fullfile(filepath,filename));' ...
'end;' ...
'clear filename filepath tagtest;' ];
cb_browsemesh = [ '[filename, filepath] = uigetfile(''*.spl'', ''Select a spline file'');' ...
'if filename ~=0,' ...
' set(findobj( gcbf, ''userdata'', ''meshfile''), ''style'', ''edit'', ''callback'', '''', ''string'', fullfile(filepath,filename));' ...
'end;' ...
'clear filename filepath tagtest;' ];
cb_browsemeshchan = [ '[filename, filepath] = uigetfile(''*.spl'', ''Select a spline file'');' ...
'if filename ~=0,' ...
' set(findobj( gcbf, ''userdata'', ''meshchanfile''), ''style'', ''edit'', ''callback'', '''', ''string'', fullfile(filepath,filename));' ...
'end;' ...
'clear filename filepath tagtest;' ];
cb_selectcoreg = [ 'tmpmodel = get( findobj(gcbf, ''userdata'', ''meshfile'') , ''string''); tmpmodel = tmpmodel{get( findobj(gcbf, ''userdata'', ''meshfile'') , ''value'')};' ...
'tmploc2 = get( findobj(gcbf, ''userdata'', ''meshchanfile''), ''string''); tmploc2 = tmploc2{ get( findobj(gcbf, ''userdata'', ''meshchanfile'') , ''value'')};' ...
'tmploc1 = get( gcbo, ''userdata'');' ...
'tmptransf = get( findobj(gcbf, ''userdata'', ''coregtext''), ''string'');' ...
'[tmp tmptransf] = coregister(tmploc1{1}, tmploc2, ''mesh'', tmpmodel, ''helpmsg'', ''on'',' ...
' ''chaninfo1'', tmploc1{2}, ''transform'', str2num(tmptransf));' ...
'if ~isempty(tmptransf), set( findobj(gcbf, ''userdata'', ''coregtext''), ''string'', num2str(tmptransf)); end;' ...
'clear tmpmodel tmploc2 tmploc1 tmp tmptransf;' ];
cb_helpload = [ 'warndlg2(strvcat(''If you have already generated a spline file for this channel location'',' ...
'''structure, you may enter it here. Click on the "Use existing spline file or'',' ...
'''structure" to activate the edit box first.''), ''Load file for headplot()'');' ];
cb_helpcoreg = [ 'warndlg2(strvcat(''Your channel locations must be co-registered with a 3-D head mesh to be plotted.'',' ...
'''If you are using one of the template location files, the "Talairach transformation matrix"'',' ...
'''field will be filled automatically (just enter an output file name and press "OK").'',' ...
'''Otherwise press the "Manual coreg." button to perform co-registration.''), ''Load file for headplot()'');' ];
cb_selectmesh = [ 'set(findobj(gcbf, ''userdata'', ''meshchanfile''), ''value'', get(gcbo, ''value''));' ...
'set(findobj(gcbf, ''userdata'', ''meshfile'') , ''value'', get(gcbo, ''value''));' ...
'tmpdat = get(gcbf, ''userdata'');' ...
'set(findobj(gcbf, ''userdata'', ''coregtext''), ''string'', num2str(tmpdat{get(gcbo, ''value'')}));' ];
defaultmat = { 'mheadnew.mat' 'colin27headmesh.mat' };
defaultloc = { 'mheadnew.xyz' 'colin27headmesh.xyz' };
defaulttransform = { transform [0 -15 10 0.05 0 -1.57 1.25 1.1 1] };
if iseeglabdeployed
defaultmat = fullfile(eeglabexefolder, defaultmat);
defaultloc = fullfile(eeglabexefolder, defaultloc);
end;
userdatatmp = { EEG.chanlocs EEG.chaninfo };
txt = { { 'style' 'text' 'string' 'Co-register channel locations with head mesh and compute a mesh spline file (each scalp montage needs a headplot() spline file)' 'fontweight' 'bold' } ...
{ 'style' 'checkbox' 'string' 'Use the following spline file or structure' 'userdata' 'loadfile' 'tag' 'loadcb' 'callback' cb_load 'value' ~compute_file } ...
{ 'style' 'edit' 'string' fastif(typeplot, EEG.splinefile, EEG.icasplinefile) 'userdata' 'load' 'tag' 'load' 'enable' enableload } ...
{ 'style' 'pushbutton' 'string' 'Browse' 'callback' cb_browseload 'tag' 'load' 'enable' enableload } ...
{ 'style' 'pushbutton' 'string' 'Help' 'callback' cb_helpload } ...
{ 'style' 'checkbox' 'string' 'Or (re)compute a new spline file named:' 'tag' 'compcb' 'callback' cb_comp 'value' compute_file } ...
{ 'style' 'edit' 'string' [fullfile(pwd, EEG.filename(1:length(EEG.filename)-3)),'spl'] 'userdata' 'coregfile' 'tag' 'comp' 'enable' enablecomp } ...
{ 'style' 'pushbutton' 'string' 'Browse' 'callback' cb_browsecomp 'tag' 'comp' 'enable' enablecomp } ...
{ 'style' 'pushbutton' 'string' 'Help' 'callback' cb_helpcoreg } ...
{ 'style' 'text' 'string' ' 3-D head mesh file' 'tag' 'comp' 'enable' enablecomp } ...
{ 'style' 'popupmenu' 'string' defaultmat 'userdata' 'meshfile' 'callback' cb_selectmesh 'tag' 'comp' 'enable' enablecomp } ...
{ 'style' 'pushbutton' 'string' 'Browse other' 'callback' cb_browsemesh 'tag' 'comp' 'enable' enablecomp } ...
{ } ...
{ 'style' 'text' 'string' ' Mesh associated channel file' 'tag' 'comp' 'enable' enablecomp } ...
{ 'style' 'popupmenu' 'string' defaultloc 'userdata' 'meshchanfile' 'callback' cb_selectmesh 'tag' 'comp' 'enable' enablecomp } ...
{ 'style' 'pushbutton' 'string' 'Browse other' 'callback' cb_browsemeshchan 'tag' 'comp' 'enable' enablecomp } ...
{ } ...
{ 'style' 'text' 'string' ' Talairach-model transformation matrix' 'tag' 'comp' 'enable' enablecomp } ...
{ 'style' 'edit' 'string' num2str(transform) 'userdata' 'coregtext' 'tag' 'comp' 'enable' enablecomp } ...
{ 'style' 'pushbutton' 'string' 'Manual coreg.' 'callback' cb_selectcoreg 'userdata' userdatatmp 'tag' 'comp' 'enable' enablecomp } ...
{ } ...
{ } ...
{ 'style' 'text' 'string' 'Plot interpolated activity onto 3-D head' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' txt } ...
{ 'style' 'edit' 'string' fastif( typeplot, '', ['1:' int2str(size(EEG.data,1))] ) } { } ...
{ 'style' 'text' 'string' 'Plot title:' } ...
{ 'style' 'edit' 'string' [ fastif( typeplot, 'ERP scalp maps of dataset:', 'Components of dataset: ') ...
fastif(~isempty(EEG.setname), EEG.setname, '') ] } { } ...
{ 'style' 'text' 'string' 'Plot geometry (rows,columns): (Default [] = near square)' } ...
{ 'style' 'edit' 'string' '' } { } ...
{ 'style' 'text' 'string' 'Other headplot options (See >> help headplot):' } ...
{ 'style' 'edit' 'string' '' } { } };
% plot GUI and protect parameters
% -------------------------------
geom = { [1] [1.3 1.6 0.5 0.5 ] [1.3 1.6 0.5 0.5 ] [1.3 1.6 0.6 0.4 ] [1.3 1.6 0.6 0.4 ] [1.3 1.6 0.6 0.4 ] ...
[1] [1] [1.5 1 0.5] [1.5 1 0.5] [1.5 1 0.5] [1.5 1 0.5] };
optiongui = { 'uilist', txt, 'title', fastif( typeplot, 'ERP head plot(s) -- pop_headplot()', ...
'Component head plot(s) -- pop_headplot()'), 'geometry', geom 'userdata' defaulttransform };
[result, userdat2, strhalt, outstruct] = inputgui( 'mode', 'noclose', optiongui{:});
if isempty(result), return; end;
if ~isempty(get(0, 'currentfigure')) currentfig = gcf; else return; end;
while test_wrong_parameters(currentfig)
[result, userdat2, strhalt, outstruct] = inputgui( 'mode', currentfig, optiongui{:});
if isempty(result), return; end;
end;
close(currentfig);
% decode setup parameters
% -----------------------
options = {};
if result{1}, options = { options{:} 'load' result{2} };
else
if ~isstr(result{5}) result{5} = defaultmat{result{5}}; end;
if isempty(result{7}) setupopt = { result{4} 'meshfile' result{5} }; % no coreg
else setupopt = { result{4} 'meshfile' result{5} 'transform' str2num(result{7}) };
fprintf('Transformation matrix: %s\n', result{7});
end;
options = { options{:} 'setup' setupopt };
if ~strcmpi(result{5}, 'mheadnew.mat'), EEG.headplotmeshfile = result{5}; end;
end;
% decode other parameters
% -----------------------
arg2 = eval( [ '[' result{8} ']' ] );
if length(arg2) > EEG.nbchan
tmpbut = questdlg2(['This will draw ' int2str(length(arg2)) ' plots. Continue ?'], '', 'Cancel', 'Yes', 'Yes');
if strcmp(tmpbut, 'Cancel'), return; end;
end;
if length(arg2) == 0, error('please choose a latency(s) to plot'); end
topotitle = result{9};
rowcols = eval( [ '[ ' result{10} ' ]' ] );
tmpopts = eval( [ '{ ' result{11} ' }' ] );
if ~isempty(tmpopts)
options = { options{:} tmpopts{:} };
end;
if size(arg2(:),1) == 1, figure; end;
else % Pass along parameters and bypass GUI input
options = varargin;
end;
% Check if pop_headplot input 'colorbar' was called, and don't send it to headplot
loc = strmatch('colorbar', options(1:2:end), 'exact');
loc = loc*2-1;
if ~isempty(loc)
colorbar_switch = strcmp('on',options{ loc+1 });
options(loc:loc+1) = [];
else
colorbar_switch = 1;
end
% read or generate file if necessary
% ----------------------------------
pop_options = options;
loc = strmatch('load', options(1:2:end)); loc = loc*2-1;
if ~isempty(loc)
if typeplot
EEG.splinefile = options{ loc+1 };
else
EEG.icasplinefile = options{ loc+1 };
end;
options(loc:loc+1) = [];
end;
loc = strmatch('setup', options(1:2:end)); loc = loc*2-1;
if ~isempty(loc)
if typeplot
headplot('setup', EEG.chanlocs, options{loc+1}{1}, 'chaninfo', EEG.chaninfo, options{ loc+1 }{2:end});
EEG.splinefile = options{loc+1}{1};
else
headplot('setup', EEG.chanlocs, options{loc+1}{1}, 'chaninfo', EEG.chaninfo, 'ica', 'on', options{ loc+1 }{2:end});
EEG.icasplinefile = options{loc+1}{1};
end;
options(loc:loc+1) = [];
compute_file = 1;
else
compute_file = 0;
end;
% search for existing file if necessary
% -------------------------------------
if typeplot == 1 % ********** data plot
fieldname = 'splinefile';
if isempty(EEG.splinefile)
if length(EEG.icachansind) == EEG.nbchan & ~isempty(EEG.icasplinefile)
EEG.splinefile = EEG.icasplinefile;
end;
end;
else % ************* Component plot
fieldname = 'icasplinefile';
if isempty(EEG.icasplinefile)
if length(EEG.icachansind) == EEG.nbchan & ~isempty(EEG.splinefile)
EEG.icasplinefile = EEG.splinefile;
end;
end;
end;
% headplot mesh file
% ------------------
if isfield(EEG, 'headplotmeshfile')
if ~isempty(EEG.headplotmeshfile)
options = { options{:} 'meshfile' EEG.headplotmeshfile };
end;
end;
% check parameters
% ----------------
if ~exist('topotitle')
topotitle = '';
end;
if typeplot
if isempty(EEG.splinefile)
error('Pop_headplot: cannot find spline file, aborting...');
end;
else
if isempty(EEG.icasplinefile)
error('Pop_headplot: cannot find spline file, aborting...');
end;
end;
SIZEBOX = 150;
nbgraph = size(arg2(:),1);
if ~exist('rowcols') | isempty(rowcols) | rowcols == 0
rowcols(2) = ceil(sqrt(nbgraph));
rowcols(1) = ceil(nbgraph/rowcols(2));
end;
fprintf('Plotting...\n');
% determine the scale for plot of different times (same scales)
% -------------------------------------------------------------
if typeplot
SIGTMP = reshape(EEG.data, EEG.nbchan, EEG.pnts, EEG.trials);
pos = round( (arg2/1000-EEG.xmin)/(EEG.xmax-EEG.xmin) * (EEG.pnts-1))+1;
indexnan = find(isnan(pos));
nanpos = find(isnan(pos));
pos(nanpos) = 1;
SIGTMPAVG = mean(SIGTMP(:,pos,:),3);
SIGTMPAVG(:, nanpos) = NaN;
maxlim = max(SIGTMPAVG(:));
minlim = min(SIGTMPAVG(:));
maplimits = max(maxlim, -minlim);
maplimits = maplimits*1.1;
maplimits = [ -maplimits maplimits ];
else
maplimits = [-1 1];
end;
% plot the graphs
% ---------------
counter = 1;
disp('IMPORTANT NOTICE: electrodes are projected to the head surface so their location');
disp(' might slightly differ from the one they had during coregistration ');
for index = 1:size(arg2(:),1)
if nbgraph > 1
if mod(index, rowcols(1)*rowcols(2)) == 1
if index> 1, a = textsc(0.5, 0.05, topotitle); set(a, 'fontweight', 'bold'); end;
figure;
pos = get(gcf,'Position');
posx = max(0, pos(1)+(pos(3)-SIZEBOX*rowcols(2))/2);
posy = pos(2)+pos(4)-SIZEBOX*rowcols(1);
set(gcf,'Position', [posx posy SIZEBOX*rowcols(2) SIZEBOX*rowcols(1)]);
try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end;
end;
subplot( rowcols(1), rowcols(2), mod(index-1, rowcols(1)*rowcols(2))+1);
end;
if ~isnan(arg2(index))
if typeplot
headplot( SIGTMPAVG(:,index), EEG.splinefile, 'maplimits', maplimits, options{:});
if nbgraph == 1, title( topotitle );
else title([int2str(arg2(index)) ' ms']);
end;
else
if arg2(index) < 0
headplot( -EEG.icawinv(:, -arg2(index)), EEG.icasplinefile, options{:});
else
headplot( EEG.icawinv(:, arg2(index)), EEG.icasplinefile, options{:});
end;
if nbgraph == 1, title( topotitle );
else title(['' int2str(arg2(index))]);
end;
end;
drawnow;
axis equal;
rotate3d off;
else
axis off
end
end
% Draw colorbar
if colorbar_switch
if nbgraph == 1
ColorbarHandle = cbar(0,0,[maplimits(1) maplimits(2)]);
pos = get(ColorbarHandle,'position'); % move left & shrink to match head size
set(ColorbarHandle,'position',[pos(1)-.05 pos(2)+0.13 pos(3)*0.7 pos(4)-0.26]);
else
cbar('vert',0,[maplimits(1) maplimits(2)]);
end
if ~typeplot % Draw '+' and '-' instead of numbers for colorbar tick labels
tmp = get(gca, 'ytick');
set(gca, 'ytickmode', 'manual', 'yticklabelmode', 'manual', 'ytick', [tmp(1) tmp(end)], 'yticklabel', { '-' '+' });
end
end
try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end;
if nbgraph> 1,
a = textsc(0.5, 0.05, topotitle);
set(a, 'fontweight', 'bold');
axcopy(gcf, [ 'set(gcf, ''''units'''', ''''pixels''''); postmp = get(gcf, ''''position'''');' ...
'set(gcf, ''''position'''', [postmp(1) postmp(2) 560 420]); rotate3d(gcf); clear postmp;' ]);
end;
% generate output command
% -----------------------
com = sprintf('pop_headplot(%s, %d, %s, ''%s'', [%s], %s);', inputname(1), typeplot, vararg2str(arg2), ...
topotitle, int2str(rowcols), vararg2str( pop_options ) );
if compute_file, com = [ 'EEG = ' com ]; end;
if nbgraph== 1, com = [ 'figure; ' com ]; rotate3d(gcf); end;
return;
% test for wrong parameters
% -------------------------
function bool = test_wrong_parameters(hdl)
bool = 0;
loadfile = get( findobj( hdl, 'userdata', 'loadfile') , 'value' );
textlines = '';
if ~loadfile
coreg1 = get( findobj( hdl, 'userdata', 'coregtext') , 'string' );
coreg3 = get( findobj( hdl, 'userdata', 'coregfile') , 'string' );
if isempty(coreg1)
textlines = strvcat('You must co-register your channel locations with the head model.', ...
'This is an easy process: Press the "Manual coreg." button in the', ...
'right center of the pop_headplot() window and follow instructions.',...
'To bypass co-registration (not recommended), enter', ...
'"0 0 0 0 0 0 1 1 1" as the "Tailairach transformation matrix.');
bool = 1;
end;
if isempty(coreg3)
textlines = strvcat(textlines, ' ', 'You need to enter an output file name.');
bool = 1;
end;
if bool
warndlg2( textlines, 'Error');
end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_loadset.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_loadset.m
| 14,435 |
utf_8
|
93a26aeae3a4c3fd4bc70166ff7f5328
|
% pop_loadset() - load an EEG dataset. If no arguments, pop up an input window.
%
% Usage:
% >> EEGOUT = pop_loadset; % pop up window to input arguments
% >> EEGOUT = pop_loadset( 'key1', 'val1', 'key2', 'val2', ...);
% >> EEGOUT = pop_loadset( filename, filepath); % old calling format
%
% Optional inputs:
% 'filename' - [string] dataset filename. Default pops up a graphical
% interface to browse for a data file.
% 'filepath' - [string] dataset filepath. Default is current folder.
% 'loadmode' - ['all', 'info', integer] 'all' -> load the data and
% the dataset structure. 'info' -> load only the dataset
% structure but not the actual data. [integer] -> load only
% a specific channel. This is efficient when data is stored
% in a separate '.dat' file in which individual channels
% may be loaded independently of each other. {default: 'all'}
% 'eeg' - [EEG structure] reload current dataset
% Note:
% Multiple filenames and filepaths may be specified. If more than one,
% the output EEG variable will be an array of EEG structures.
% Output
% EEGOUT - EEG dataset structure or array of structures
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001; SCCN/INC/UCSD, 2002-
%
% See also: eeglab(), pop_saveset()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
function [EEG, command] = pop_loadset( inputname, inputpath, varargin)
command = '';
EEG = [];
if nargin < 1
% pop up window
% -------------
[inputname, inputpath] = uigetfile2('*.SET*;*.set', 'Load dataset(s) -- pop_loadset()', 'multiselect', 'on');
drawnow;
if isequal(inputname, 0) return; end;
options = { 'filename' inputname 'filepath' inputpath };
else
% account for old calling format
% ------------------------------
if ~strcmpi(inputname, 'filename') && ~strcmpi(inputname, 'filepath') && ~strcmpi(inputname, 'eeg')
options = { 'filename' inputname };
if nargin > 1
options = { options{:} 'filepath' inputpath };
end;
if nargin > 2
options = { options{:} 'loadmode' varargin{1} };
end;
else
options = { inputname inputpath varargin{:} };
end;
end;
% decode input parameters
% -----------------------
g = finputcheck( options, ...
{ 'filename' { 'string';'cell' } [] '';
'filepath' 'string' [] '';
'check' 'string' { 'on';'off' } 'on';
'loadmode' { 'string';'integer' } { { 'info' 'all' } [] } 'all';
'eeg' 'struct' [] struct('data',{}) }, 'pop_loadset');
if isstr(g), error(g); end;
if isstr(g.filename), g.filename = { g.filename }; end;
% reloading EEG structure from disk
% ---------------------------------
if ~isempty(g.eeg)
EEG = pop_loadset( 'filepath', g.eeg.filepath, 'filename', g.eeg.filename);
else
eeglab_options;
ALLEEGLOC = [];
for ifile = 1:length(g.filename)
if ifile > 1 && option_storedisk
g.loadmode = 'last';
% warndlg2(strvcat('You may only load a single dataset','when selecting the "Store at most one', 'dataset in memory" option'));
% break;
end;
% read file
% ---------
filename = fullfile(g.filepath, g.filename{ifile});
fprintf('pop_loadset(): loading file %s ...\n', filename);
%try
TMPVAR = load('-mat', filename);
%catch,
% error([ filename ': file is protected or does not exist' ]);
%end;
% variable not found
% ------------------
if isempty(TMPVAR)
error('No dataset info is associated with this file');
end;
if isfield(TMPVAR, 'EEG')
% load individual dataset
% -----------------------
EEG = checkoldformat(TMPVAR.EEG);
[ EEG.filepath EEG.filename ext ] = fileparts( filename );
EEG.filename = [ EEG.filename ext ];
% account for name changes etc...
% -------------------------------
if isstr(EEG.data) && ~strcmpi(EEG.data, 'EEGDATA')
[tmp EEG.data ext] = fileparts( EEG.data ); EEG.data = [ EEG.data ext];
if ~isempty(tmp) && ~strcmpi(tmp, EEG.filepath)
disp('Warning: updating folder name for .dat|.fdt file');
end;
if ~strcmp(EEG.filename(1:end-3), EEG.data(1:end-3))
disp('Warning: the name of the dataset has changed on disk, updating .dat & .fdt data file to the new name');
EEG.data = [ EEG.filename(1:end-3) EEG.data(end-2:end) ];
EEG.saved = 'no';
end;
end;
% copy data to output variable if necessary (deprecated)
% -----------------------------------------
if ~strcmpi(g.loadmode, 'info') && isfield(TMPVAR, 'EEGDATA')
if ~option_storedisk || ifile == length(g.filename)
EEG.data = TMPVAR.EEGDATA;
end;
end;
elseif isfield(TMPVAR, 'ALLEEG') % old format
eeglab_options;
if option_storedisk
error('Cannot load multiple dataset file. Change memory option to allow multiple datasets in memory, then try again. Remember that this file type is OBSOLETE.');
end;
% this part is deprecated as of EEGLAB 5.00
% since all dataset data have to be saved in separate files
% -----------------------------------------------------
disp('pop_loadset(): appending datasets');
EEG = TMPVAR.ALLEEG;
for index=1:length(EEG)
EEG(index).filename = '';
EEG(index).filepath = '';
if isstr(EEG(index).data),
EEG(index).filepath = g.filepath;
if length(g.filename{ifile}) > 4 && ~strcmp(g.filename{ifile}(1:end-4), EEG(index).data(1:end-4)) && strcmpi(g.filename{ifile}(end-3:end), 'sets')
disp('Warning: the name of the dataset has changed on disk, updating .dat data file to the new name');
EEG(index).data = [ g.filename{ifile}(1:end-4) 'fdt' int2str(index) ];
end;
end;
end;
else
EEG = checkoldformat(TMPVAR);
if ~isfield( EEG, 'data')
error('pop_loadset(): not an EEG dataset file');
end;
if isstr(EEG.data), EEG.filepath = g.filepath; end;
end;
%ALLEEGLOC = pop_newset(ALLEEGLOC, EEG, 1);
ALLEEGLOC = eeg_store(ALLEEGLOC, EEG, 0, 'verbose', 'off');
end;
EEG = ALLEEGLOC;
end;
% load all data or specific data channel
% --------------------------------------
if strcmpi(g.check, 'on')
EEG = eeg_checkset(EEG);
end;
if isstr(g.loadmode)
if strcmpi(g.loadmode, 'all')
EEG = eeg_checkset(EEG, 'loaddata');
elseif strcmpi(g.loadmode, 'last')
EEG(end) = eeg_checkset(EEG(end), 'loaddata');
end;
else
% load/select specific channel
% ----------------------------
EEG.datachannel = g.loadmode;
EEG.data = eeg_getdatact(EEG, 'channel', g.loadmode);
EEG.nbchan = length(g.loadmode);
if ~isempty(EEG.chanlocs)
EEG.chanlocs = EEG.chanlocs(g.loadmode);
end;
EEG.icachansind = [];
EEG.icaact = [];
EEG.icaweights = [];
EEG.icasphere = [];
EEG.icawinv = [];
%if isstr(EEG.data)
% EEG.datfile = EEG.data;
% fid = fopen(fullfile(EEG.filepath, EEG.data), 'r', 'ieee-le');
% fseek(fid, EEG.pnts*EEG.trials*( g.loadmode - 1), 0 );
% EEG.data = fread(fid, EEG.pnts*EEG.trials, 'float32');
% fclose(fid);
%else
% EEG.data = EEG.data(g.loadmode,:,:);
%end;
end;
% set file name and path
% ----------------------
if length(EEG) == 1
tmpfilename = g.filename{1};
if isempty(g.filepath)
[g.filepath tmpfilename ext] = fileparts(tmpfilename);
tmpfilename = [ tmpfilename ext ];
end;
EEG.filename = tmpfilename;
EEG.filepath = g.filepath;
end;
% set field indicating that the data has not been modified
% --------------------------------------------------------
if isfield(EEG, 'changes_not_saved')
EEG = rmfield(EEG, 'changes_not_saved');
end;
for index=1:length(EEG)
EEG(index).saved = 'justloaded';
end;
command = sprintf('EEG = pop_loadset(%s);', vararg2str(options));
return;
function EEG = checkoldformat(EEG)
if ~isfield( EEG, 'data')
fprintf('pop_loadset(): Incompatible with new format, trying old format and converting...\n');
eegset = EEG.cellArray;
off_setname = 1; %= filename
off_filename = 2; %= filename
off_filepath = 3; %= fielpath
off_type = 4; %= type EEG AVG CNT
off_chan_names = 5; %= chan_names
off_chanlocs = 21; %= filename
off_pnts = 6; %= pnts
off_sweeps = 7; %= sweeps
off_rate = 8; %= rate
off_xmin = 9; %= xmin
off_xmax = 10; %= xmax
off_accept = 11; %= accept
off_typeeeg = 12; %= typeeeg
off_rt = 13; %= rt
off_response = 14; %= response
off_signal = 15; %= signal
off_variance = 16; %= variance
off_winv = 17; %= variance
off_weights = 18; %= variance
off_sphere = 19; %= variance
off_activations = 20; %= variance
off_entropytrial = 22; %= variance
off_entropycompo = 23; %= variance
off_threshold = 24; %= variance
off_comporeject = 25; %= variance
off_sigreject = 26;
off_kurtA = 29;
off_kurtR = 30;
off_kurtDST = 31;
off_nbchan = 32;
off_elecreject = 33;
off_comptrial = 34;
off_kurttrial = 35; %= variance
off_kurttrialglob = 36; %= variance
off_icareject = 37; %= variance
off_gcomporeject = 38; %= variance
off_eegentropy = 27;
off_eegkurt = 28;
off_eegkurtg = 39;
off_tmp1 = 40;
off_tmp2 = 40;
% must convert here into new format
EEG.setname = eegset{off_setname };
EEG.filename = eegset{off_filename };
EEG.filepath = eegset{off_filepath };
EEG.namechan = eegset{off_chan_names};
EEG.chanlocs = eegset{off_chanlocs };
EEG.pnts = eegset{off_pnts };
EEG.nbchan = eegset{off_nbchan };
EEG.trials = eegset{off_sweeps };
EEG.srate = eegset{off_rate };
EEG.xmin = eegset{off_xmin };
EEG.xmax = eegset{off_xmax };
EEG.accept = eegset{off_accept };
EEG.eegtype = eegset{off_typeeeg };
EEG.rt = eegset{off_rt };
EEG.eegresp = eegset{off_response };
EEG.data = eegset{off_signal };
EEG.icasphere = eegset{off_sphere };
EEG.icaweights = eegset{off_weights };
EEG.icawinv = eegset{off_winv };
EEG.icaact = eegset{off_activations };
EEG.stats.entropy = eegset{off_entropytrial };
EEG.stats.kurtc = eegset{off_kurttrial };
EEG.stats.kurtg = eegset{off_kurttrialglob};
EEG.stats.entropyc = eegset{off_entropycompo };
EEG.reject.threshold = eegset{off_threshold };
EEG.reject.icareject = eegset{off_icareject };
EEG.reject.compreject = eegset{off_comporeject };
EEG.reject.gcompreject= eegset{off_gcomporeject };
EEG.reject.comptrial = eegset{off_comptrial };
EEG.reject.sigreject = eegset{off_sigreject };
EEG.reject.elecreject = eegset{off_elecreject };
EEG.stats.kurta = eegset{off_kurtA };
EEG.stats.kurtr = eegset{off_kurtR };
EEG.stats.kurtd = eegset{off_kurtDST };
EEG.stats.eegentropy = eegset{off_eegentropy };
EEG.stats.eegkurt = eegset{off_eegkurt };
EEG.stats.eegkurtg = eegset{off_eegkurtg };
%catch
% disp('Warning: some variables may not have been assigned');
%end;
% modify the eegtype to match the new one
try
if EEG.trials > 1
EEG.events = [ EEG.rt(:) EEG.eegtype(:) EEG.eegresp(:) ];
end;
catch, end;
end;
% check modified fields
% ---------------------
if isfield(EEG,'icadata'), EEG.icaact = EEG.icadata; end;
if isfield(EEG,'poschan'), EEG.chanlocs = EEG.poschan; end;
if ~isfield(EEG, 'icaact'), EEG.icaact = []; end;
if ~isfield(EEG, 'chanlocs'), EEG.chanlocs = []; end;
if isfield(EEG, 'events') && ~isfield(EEG, 'event')
try
if EEG.trials > 1
EEG.events = [ EEG.rt(:) ];
EEG = eeg_checkset(EEG);
EEG = pop_importepoch(EEG, EEG.events, { 'rt'}, {'rt'}, 1E-3);
end;
if isfield(EEG, 'trialsval')
EEG = pop_importepoch(EEG, EEG.trialsval(:,2:3), { 'eegtype' 'response' }, {},1,0,0);
end;
EEG = eeg_checkset(EEG, 'eventconsistency');
catch, disp('Warning: could not import events'); end;
end;
rmfields = {'icadata' 'events' 'accept' 'eegtype' 'eegresp' 'trialsval' 'poschan' 'icadata' 'namechan' };
for index = 1:length(rmfields)
if isfield(EEG, rmfields{index}),
disp(['Warning: field ' rmfields{index} ' is deprecated']);
end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_selectcomps.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_selectcomps.m
| 7,460 |
utf_8
|
8edde953edd442f1cc480f2a403c8086
|
% pop_selectcomps() - Display components with button to vizualize their
% properties and label them for rejection.
% Usage:
% >> OUTEEG = pop_selectcomps( INEEG, compnum );
%
% Inputs:
% INEEG - Input dataset
% compnum - vector of component numbers
%
% Output:
% OUTEEG - Output dataset with updated rejected components
%
% Note:
% if the function POP_REJCOMP is ran prior to this function, some
% fields of the EEG datasets will be present and the current function
% will have some more button active to tune up the automatic rejection.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: pop_prop(), 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
function [EEG, com] = pop_selectcomps( EEG, compnum, fig );
COLREJ = '[1 0.6 0.6]';
COLACC = '[0.75 1 0.75]';
PLOTPERFIG = 35;
com = '';
if nargin < 1
help pop_selectcomps;
return;
end;
if nargin < 2
promptstr = { 'Components to plot:' };
initstr = { [ '1:' int2str(size(EEG.icaweights,1)) ] };
result = inputdlg2(promptstr, 'Reject comp. by map -- pop_selectcomps',1, initstr);
if isempty(result), return; end;
compnum = eval( [ '[' result{1} ']' ]);
if length(compnum) > PLOTPERFIG
ButtonName=questdlg2(strvcat(['More than ' int2str(PLOTPERFIG) ' components so'],'this function will pop-up several windows'), ...
'Confirmation', 'Cancel', 'OK','OK');
if ~isempty( strmatch(lower(ButtonName), 'cancel')), return; end;
end;
end;
fprintf('Drawing figure...\n');
currentfigtag = ['selcomp' num2str(rand)]; % generate a random figure tag
if length(compnum) > PLOTPERFIG
for index = 1:PLOTPERFIG:length(compnum)
pop_selectcomps(EEG, compnum([index:min(length(compnum),index+PLOTPERFIG-1)]));
end;
com = [ 'pop_selectcomps(' inputname(1) ', ' vararg2str(compnum) ');' ];
return;
end;
if isempty(EEG.reject.gcompreject)
EEG.reject.gcompreject = zeros( size(EEG.icawinv,2));
end;
try, icadefs;
catch,
BACKCOLOR = [0.8 0.8 0.8];
GUIBUTTONCOLOR = [0.8 0.8 0.8];
end;
% set up the figure
% -----------------
column =ceil(sqrt( length(compnum) ))+1;
rows = ceil(length(compnum)/column);
if ~exist('fig')
figure('name', [ 'Reject components by map - pop_selectcomps() (dataset: ' EEG.setname ')'], 'tag', currentfigtag, ...
'numbertitle', 'off', 'color', BACKCOLOR);
set(gcf,'MenuBar', 'none');
pos = get(gcf,'Position');
set(gcf,'Position', [pos(1) 20 800/7*column 600/5*rows]);
incx = 120;
incy = 110;
sizewx = 100/column;
if rows > 2
sizewy = 90/rows;
else
sizewy = 80/rows;
end;
pos = get(gca,'position'); % plot relative to current axes
hh = gca;
q = [pos(1) pos(2) 0 0];
s = [pos(3) pos(4) pos(3) pos(4)]./100;
axis off;
end;
% figure rows and columns
% -----------------------
if EEG.nbchan > 64
disp('More than 64 electrodes: electrode locations not shown');
plotelec = 0;
else
plotelec = 1;
end;
count = 1;
for ri = compnum
if exist('fig')
button = findobj('parent', fig, 'tag', ['comp' num2str(ri)]);
if isempty(button)
error( 'pop_selectcomps(): figure does not contain the component button');
end;
else
button = [];
end;
if isempty( button )
% compute coordinates
% -------------------
X = mod(count-1, column)/column * incx-10;
Y = (rows-floor((count-1)/column))/rows * incy - sizewy*1.3;
% plot the head
% -------------
if ~strcmp(get(gcf, 'tag'), currentfigtag);
disp('Aborting plot');
return;
end;
ha = axes('Units','Normalized', 'Position',[X Y sizewx sizewy].*s+q);
if plotelec
topoplot( EEG.icawinv(:,ri), EEG.chanlocs, 'verbose', ...
'off', 'style' , 'fill', 'chaninfo', EEG.chaninfo, 'numcontour', 8);
else
topoplot( EEG.icawinv(:,ri), EEG.chanlocs, 'verbose', ...
'off', 'style' , 'fill','electrodes','off', 'chaninfo', EEG.chaninfo, 'numcontour', 8);
end;
axis square;
% plot the button
% ---------------
button = uicontrol(gcf, 'Style', 'pushbutton', 'Units','Normalized', 'Position',...
[X Y+sizewy sizewx sizewy*0.25].*s+q, 'tag', ['comp' num2str(ri)]);
command = sprintf('pop_prop( %s, 0, %d, gcbo, { ''freqrange'', [1 50] });', inputname(1), ri); %RMC command = sprintf('pop_prop( %s, 0, %d, %3.15f, { ''freqrange'', [1 50] });', inputname(1), ri, button);
set( button, 'callback', command );
end;
set( button, 'backgroundcolor', eval(fastif(EEG.reject.gcompreject(ri), COLREJ,COLACC)), 'string', int2str(ri));
drawnow;
count = count +1;
end;
% draw the bottom button
% ----------------------
if ~exist('fig')
hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'Cancel', 'Units','Normalized', 'backgroundcolor', GUIBUTTONCOLOR, ...
'Position',[-10 -10 15 sizewy*0.25].*s+q, 'callback', 'close(gcf); fprintf(''Operation cancelled\n'')' );
hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'Set threhsolds', 'Units','Normalized', 'backgroundcolor', GUIBUTTONCOLOR, ...
'Position',[10 -10 15 sizewy*0.25].*s+q, 'callback', 'pop_icathresh(EEG); pop_selectcomps( EEG, gcbf);' );
if isempty( EEG.stats.compenta ), set(hh, 'enable', 'off'); end;
hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'See comp. stats', 'Units','Normalized', 'backgroundcolor', GUIBUTTONCOLOR, ...
'Position',[30 -10 15 sizewy*0.25].*s+q, 'callback', ' ' );
if isempty( EEG.stats.compenta ), set(hh, 'enable', 'off'); end;
hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'See projection', 'Units','Normalized', 'backgroundcolor', GUIBUTTONCOLOR, ...
'Position',[50 -10 15 sizewy*0.25].*s+q, 'callback', ' ', 'enable', 'off' );
hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'Help', 'Units','Normalized', 'backgroundcolor', GUIBUTTONCOLOR, ...
'Position',[70 -10 15 sizewy*0.25].*s+q, 'callback', 'pophelp(''pop_selectcomps'');' );
command = '[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET); eegh(''[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET);''); close(gcf)';
hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'OK', 'Units','Normalized', 'backgroundcolor', GUIBUTTONCOLOR, ...
'Position',[90 -10 15 sizewy*0.25].*s+q, 'callback', command);
% sprintf(['eeg_global; if %d pop_rejepoch(%d, %d, find(EEG.reject.sigreject > 0), EEG.reject.elecreject, 0, 1);' ...
% ' end; pop_compproj(%d,%d,1); close(gcf); eeg_retrieve(%d); eeg_updatemenu; '], rejtrials, set_in, set_out, fastif(rejtrials, set_out, set_in), set_out, set_in));
end;
com = [ 'pop_selectcomps(' inputname(1) ', ' vararg2str(compnum) ');' ];
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_readsegegi.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_readsegegi.m
| 3,697 |
utf_8
|
c101ff1d191f9634bc1ce0aba263842c
|
% pop_readsegegi() - load a segmented EGI EEG file. Pop up query
% window if no arguments.
% Usage:
% >> EEG = pop_readsegegi; % a window pops up
% >> EEG = pop_readsegegi( filename ); % no pop-up window
%
% Inputs:
% filename - first EGI file name
%
% Outputs:
% EEG - EEGLAB data structure
%
% Author: Arnaud Delorme, CNL / Salk Institute, 10 April 2003
%
% See also: eeglab(), readegi(), readegihdr()
% 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, command] = pop_readegi(filename);
EEG = [];
command = '';
if nargin < 1
% ask user
[filename, filepath] = uigetfile('*.RAW;*.raw', 'Choose first EGI RAW file -- pop_readsegegi()');
drawnow;
if filename == 0 return; end;
filename = fullfile(filepath, filename);
end;
% load datas
% ----------
EEG = eeg_emptyset;
tailname = filename(end-3:end);
basename = filename(1:end-7);
index = 1;
cont = 1;
Eventdata = [];
disp('Removing trailing character of selected file to find base file name');
fprintf('Base file name is: %s\n', basename);
orifilename = [ basename sprintf('%3.3d', index) tailname ];
if ~exist(orifilename)
disp ([ 'First file of series ''' orifilename ''' not found' ] );
error([ 'First file of series ''' orifilename ''' not found' ] );
end;
while cont
tmpfilename = [ basename sprintf('%3.3d', index) tailname ];
try,
disp(['Importing ' tmpfilename ]);
[Head tmpdata tmpevent] = readegi( tmpfilename );
EEG.data = [ EEG.data tmpdata ];
Eventdata = [ Eventdata tmpevent ];
index = index + 1;
catch,
cont = 0;
end;
end;
% add one channel with the event data
% -----------------------------------
if ~isempty(Eventdata) & size(Eventdata,2) == size(EEG.data,2)
EEG.data(end+1:end+size(Eventdata,1),:) = Eventdata;
end;
EEG.comments = [ 'Original files: ' orifilename ' to ' tmpfilename ];
EEG.filepath = '';
EEG.setname = 'EGI file';
EEG.nbchan = size(EEG.data,1);
EEG.srate = Head.samp_rate;
EEG.trials = Head.segments;
EEG.pnts = Head.segsamps;
EEG.xmin = 0;
% importing the events
% --------------------
if ~isempty(Eventdata)
orinbchans = EEG.nbchan;
for index = size(Eventdata,1):-1:1
EEG = pop_chanevent( EEG, orinbchans-size(Eventdata,1)+index, 'edge', 'leading', ...
'delevent', 'off', 'typename', Head.eventcode(index,:), ...
'nbtype', 1, 'delchan', 'on');
end;
end;
% importing channel locations
% ---------------------------
if all(EEG.data(end,1:10) == 0)
disp('Deleting empty data reference channel (reference channel location is retained)');
EEG.data(end,:) = [];
EEG.nbchan = size(EEG.data,1);
EEG = eeg_checkset(EEG);
end;
EEG = readegilocs(EEG);
EEG = eeg_checkset(EEG);
command = sprintf('EEG = pop_readsegegi(''%s'');', filename);
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_rmbase.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_rmbase.m
| 7,439 |
utf_8
|
45f9353a46caf1ebb9c14f4c7932108c
|
% pop_rmbase() - remove channel baseline means from an epoched or
% continuous EEG dataset. Calls rmbase().
% Usage:
% >> OUTEEG = pop_rmbase( EEG ); % pop up an interactive arg entry window
% >> OUTEEG = pop_rmbase( EEG, timerange, pointrange); % call rmbase()
%
% Graphic interface:
% "Baseline latency range" - [edit box] Latency range for the baseline in ms.
% Collects the 'timerange' command line input.
% Empty or [] input -> Use whole epoch as baseline
% "Baseline points vector" - [edit box] Collects the 'pointrange' command line
% option (below). (Overwritten by 'timerange' above).
% Empty or [] input -> Use whole epoch as baseline
% Inputs:
% EEG - Input dataset
% timerange - [min_ms max_ms] Baseline latency range in milliseconds.
% Empty or [] input -> Use whole epoch as baseline
% pointrange - [min:max] Baseline points vector (overwritten by timerange).
% Empty or [] input -> Use whole epoch as baseline
% Outputs:
% OUTEEG - Output dataset
%
% Note: If dataset is continuous, channel means are removed separately
% for each continuous data region, respecting 'boundary' events
% marking boundaries of excised or concatenated data portions.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: rmbase(), 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
function [EEG, com] = pop_rmbase( EEG, timerange, pointrange);
com ='';
if nargin < 1
help pop_rmbase;
return;
end;
if isempty(EEG(1).data)
disp('pop_rmbase(): cannot remove baseline of an empty dataset'); return;
end;
if nargin < 1
help pop_rmbase;
return;
end;
if nargin < 2 & EEG(1).trials > 1
% popup window parameters
% -----------------------
defaultbase = [num2str(EEG(1).xmin*1000) ' 0'];
if EEG(1).xmin*1000 >= 0
defaultbase = '[ ]';
end;
uilist = { { 'style' 'text' 'string' 'Baseline latency range ([min max] in ms) ([ ] = whole epoch):' } ...
{ 'style' 'edit' 'string' defaultbase } ...
{ 'style' 'text' 'string' 'Or remove baseline points vector (ex:1:56):' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'string' 'Note: press Cancel if you do not want to remove the baseline' } ...
};
uigeom = { [3 1] [3 1] [1] };
[result usrdat] = inputgui( 'uilist', uilist, 'geometry', uigeom, 'title', 'Baseline removal - pop_rmbase()', 'helpcom', 'pophelp(''pop_rmbase'');');
if isempty(result), return; end;
if ~isempty(usrdat) && isnan(usrdat), return; end;
% decode parameters
% -----------------
if numel(result) < 2 | ((isempty(result{1}) | strcmp(result{1},'[]') ) ...
& (isempty(result{2}) | strcmp(result{2},'[]')))
timerange = [num2str(EEG(1).xmin*1000) num2str(EEG(1).xmax*1000)]; % whole epoch latency range
fprintf('pop_rmbase(): using whole epoch as baseline.\n');
% fprintf('pop_rmbase(): baseline limits must be specified.\n');
% return; end;
else
timerange = eval( [ '[' result{1} ']' ] );
pointrange = eval( [ '[' result{2} ']' ] );
end
elseif nargin < 2 & EEG(1).trials == 1
% popup window parameters
% -----------------------
resp = questdlg2(strvcat('Remove mean of each data channel'), 'pop_rmbase', 'Cancel', 'Ok', 'Ok');
if strcmpi(resp, 'Cancel'), return; end;
timerange = [];
pointrange = [1:EEG(1).pnts];
end;
% process multiple datasets
% -------------------------
if length(EEG) > 1
[ EEG com ] = eeg_eval( 'pop_rmbase', EEG, 'warning', 'on', 'params', ...
{ timerange pointrange } );
return;
end;
if exist('pointrange') ~= 1 && ~isempty(timerange)
if (timerange(1) < EEG.xmin*1000) & (timerange(2) > EEG.xmax*1000)
error('pop_rmbase(): Bad time range');
end;
pointrange = round((timerange(1)/1000-EEG.xmin)*EEG.srate+1):round((timerange(2)/1000-EEG.xmin)*EEG.srate);
end;
if isempty(timerange)
timerange = [ EEG(1).xmin*1000 EEG(1).xmax*1000];
end;
if exist('pointrange') ~= 1 || isempty(pointrange)
if ~isempty(timerange) && (timerange(1) < EEG.xmin*1000) & (timerange(2) > EEG.xmax*1000)
error('pop_rmbase(): Bad time range');
end;
pointrange = round((timerange(1)/1000-EEG.xmin)*EEG.srate+1):ceil((timerange(2)/1000-EEG.xmin)*EEG.srate);
if pointrange(end) > EEG.pnts, pointrange(end) = EEG.pnts; end;
end;
if ~isempty(pointrange) && ((min(pointrange) < 1) || (max( pointrange ) > EEG.pnts))
error('pop_rmbase(): Wrong point range');
end;
fprintf('pop_rmbase(): Removing baseline...\n');
%
% Respect excised data boundaries if continuous data
% ---------------------------------------------------
if EEG.trials == 1 && ~isempty(EEG.event) ...
&& isfield(EEG.event, 'type') ...
&& isstr(EEG.event(1).type)
tmpevent = EEG.event;
boundaries = strmatch('boundary', {tmpevent.type});
if ~isempty(boundaries) % this is crashing
fprintf('Pop_rmbase(): finding continuous data discontinuities\n');
boundaries = round([ tmpevent(boundaries).latency ] -0.5-pointrange(1)+1);
boundaries(boundaries>=pointrange(end)-pointrange(1)) = [];
boundaries(boundaries<1) = [];
boundaries = [0 boundaries pointrange(end)-pointrange(1)+1];
for index=1:length(boundaries)-1
tmprange = [boundaries(index)+1:boundaries(index+1)];
if length(tmprange) > 1
EEG.data(:,tmprange) = rmbase( EEG.data(:,tmprange), length(tmprange), ...
[1:length(tmprange)]);
elseif length(tmprange) == 1
EEG.data(:,tmprange) = 0;
end;
end;
else
EEG.data = rmbase( EEG.data, EEG.pnts, pointrange );
end;
else
for indc = 1:EEG.nbchan
tmpmean = mean(double(EEG.data(indc,pointrange,:)),2);
EEG.data(indc,:,:) = EEG.data(indc,:,:) - repmat(tmpmean, [1 EEG.pnts 1]);
end;
% EEG.data = rmbase( reshape(EEG.data, EEG.nbchan, EEG.pnts*EEG.trials), EEG.pnts, pointrange );
end;
EEG.data = reshape( EEG.data, EEG.nbchan, EEG.pnts, EEG.trials);
EEG.icaact = [];
if ~isempty(timerange)
com = sprintf('%s = pop_rmbase( %s, [%s]);', inputname(1), inputname(1), ...
num2str(timerange));
else
com = sprintf('%s = pop_rmbase( %s, [], %s);', inputname(1), inputname(1), ...
vararg2str({pointrange}));
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_fileiodir.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_fileiodir.m
| 2,897 |
utf_8
|
0b71b35b5266ba0571298a6974edf189
|
% pop_fileiodir() - import directory into EEGLAB using FileIO
%
% Usage:
% >> OUTEEG = pop_fileiodir; % pop up window
% >> OUTEEG = pop_fileiodir( folder );
%
% Inputs:
% folder - [string] folder name
%
% Optional inputs:
% 'channels' - [integer array] list of channel indices
% 'samples' - [min max] sample point limits for importing data.
% 'trials' - [min max] trial's limit for importing data.
%
% Outputs:
% OUTEEG - EEGLAB data structure
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2012-
%
% Note: FILEIO toolbox must be installed.
% Copyright (C) 2012 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, command] = pop_fileiodir(folder, varargin);
EEG = [];
command = '';
if nargin < 1
% ask user
folder = uigetdir('*.*', 'Choose a directory -- pop_fileiodir()');
if folder == 0 return; end;
drawnow;
% open file to get infos
% ----------------------
disp('Reading data file header...');
dat = ft_read_header(folder);
uilist = { { 'style' 'text' 'String' 'Channel list (defaut all):' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'String' [ 'Data range (in sample points) (default all [1 ' int2str(dat.nSamples) '])' ] } ...
{ 'style' 'edit' 'string' '' } };
geom = { [3 1] [3 1] };
if dat.nTrials > 1
uilist{end+1} = { 'style' 'text' 'String' [ 'Trial range (default all [1 ' int2str(dat.nTrials) '])' ] };
uilist{end+1} = { 'style' 'edit' 'string' '' };
geom = { geom{:} [3 1] };
end;
result = inputgui( geom, uilist, 'pophelp(''pop_fileiodir'')', 'Load data using FILE-IO -- pop_fileiodir()');
if length(result) == 0 return; end;
options = {};
result = { result{:} '' };
if ~isempty(result{1}), options = { options{:} 'channels' eval( [ '[' result{1} ']' ] ) }; end;
if ~isempty(result{2}), options = { options{:} 'samples' eval( [ '[' result{2} ']' ] ) }; end;
if ~isempty(result{3}), options = { options{:} 'trials' eval( [ '[' result{3} ']' ] ) }; end;
else
dat = ft_read_header(folder);
options = varargin;
end;
[EEG command] = pop_fileio(folder, options{:});
|
github
|
ZijingMao/baselineeegtest-master
|
pop_prop.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_prop.m
| 15,968 |
utf_8
|
cf47b5aef84eae867c3e697e131faab1
|
% pop_prop() - plot the properties of a channel or of an independent
% component.
% Usage:
% >> pop_prop( EEG); % pops up a query window
% >> pop_prop( EEG, typecomp); % pops up a query window
% >> pop_prop( EEG, typecomp, chanorcomp, winhandle,spectopo_options);
%
% Inputs:
% EEG - EEGLAB dataset structure (see EEGGLOBAL)
%
% Optional inputs:
% typecomp - [0|1] 1 -> display channel properties
% 0 -> component properties {default: 1 = channel}
% chanorcomp - channel or component number[s] to display {default: 1}
%
% winhandle - if this parameter is present or non-NaN, buttons
% allowing the rejection of the component are drawn.
% If non-zero, this parameter is used to back-propagate
% the color of the rejection button.
% spectopo_options - [cell array] optional cell arry of options for
% the spectopo() function.
% For example { 'freqrange' [2 50] }
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: pop_runica(), 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
% hidden parameter winhandle
% 01-25-02 reformated help & license -ad
% 02-17-02 removed event index option -ad
% 03-17-02 debugging -ad & sm
% 03-18-02 text settings -ad & sm
% 03-18-02 added title -ad & sm
function com = pop_prop(EEG, typecomp, chanorcomp, winhandle, spec_opt)
com = '';
if nargin < 1
help pop_prop;
return;
end;
if nargin < 5
spec_opt = {};
end;
if nargin == 1
typecomp = 1; % defaults
chanorcomp = 1;
end;
if typecomp == 0 & isempty(EEG.icaweights)
error('No ICA weights recorded for this dataset -- first run ICA on it');
end;
if nargin == 2
promptstr = { fastif(typecomp,'Channel index(ices) to plot:','Component index(ices) to plot:') ...
'Spectral options (see spectopo() help):' };
inistr = { '1' '''freqrange'', [2 50]' };
result = inputdlg2( promptstr, 'Component properties - pop_prop()', 1, inistr, 'pop_prop');
if size( result, 1 ) == 0 return; end;
chanorcomp = eval( [ '[' result{1} ']' ] );
spec_opt = eval( [ '{' result{2} '}' ] );
end;
% plotting several component properties
% -------------------------------------
if length(chanorcomp) > 1
for index = chanorcomp
pop_prop(EEG, typecomp, index, 0, spec_opt); % call recursively for each chanorcomp
end;
com = sprintf('pop_prop( %s, %d, [%s], NaN, %s);', inputname(1), ...
typecomp, int2str(chanorcomp), vararg2str( { spec_opt } ));
return;
end;
if chanorcomp < 1 | chanorcomp > EEG.nbchan % should test for > number of components ??? -sm
error('Component index out of range');
end;
% assumed input is chanorcomp
% -------------------------
try, icadefs;
catch,
BACKCOLOR = [0.8 0.8 0.8];
GUIBUTTONCOLOR = [0.8 0.8 0.8];
end;
basename = [fastif(typecomp,'Channel ', 'Component ') int2str(chanorcomp) ];
fh = figure('name', ['pop_prop() - ' basename ' properties'], 'color', BACKCOLOR, 'numbertitle', 'off', 'visible', 'off');
pos = get(gcf,'Position');
set(gcf,'Position', [pos(1) pos(2)-500+pos(4) 500 500], 'visible', 'on');
pos = get(gca,'position'); % plot relative to current axes
hh = gca;
q = [pos(1) pos(2) 0 0];
s = [pos(3) pos(4) pos(3) pos(4)]./100;
axis off;
% plotting topoplot
% -----------------
h = axes('Units','Normalized', 'Position',[-10 60 40 42].*s+q);
%topoplot( EEG.icawinv(:,chanorcomp), EEG.chanlocs); axis square;
if isfield(EEG.chanlocs, 'theta')
if typecomp == 1 % plot single channel locations
topoplot( chanorcomp, EEG.chanlocs, 'chaninfo', EEG.chaninfo, ...
'electrodes','off', 'style', 'blank', 'emarkersize1chan', 12); axis square;
else % plot component map
topoplot( EEG.icawinv(:,chanorcomp), EEG.chanlocs, 'chaninfo', EEG.chaninfo, ...
'shading', 'interp', 'numcontour', 3); axis square;
end;
else
axis off;
end;
basename = [fastif(typecomp,'Channel ', 'IC') int2str(chanorcomp) ];
% title([ basename fastif(typecomp, ' location', ' map')], 'fontsize', 14);
title(basename, 'fontsize', 14);
% plotting erpimage
% -----------------
hhh = axes('Units','Normalized', 'Position',[45 62 48 38].*s+q);
eeglab_options;
if EEG.trials > 1
% put title at top of erpimage
axis off
hh = axes('Units','Normalized', 'Position',[45 62 48 38].*s+q);
EEG.times = linspace(EEG.xmin, EEG.xmax, EEG.pnts);
if EEG.trials < 6
ei_smooth = 1;
else
ei_smooth = 3;
end
if typecomp == 1 % plot channel
offset = nan_mean(EEG.data(chanorcomp,:));
erp=nan_mean(squeeze(EEG.data(chanorcomp,:,:))')-offset;
erp_limits=get_era_limits(erp);
erpimage( EEG.data(chanorcomp,:)-offset, ones(1,EEG.trials)*10000, EEG.times*1000, ...
'', ei_smooth, 1, 'caxis', 2/3, 'cbar','erp','erp_vltg_ticks',erp_limits);
else % plot component
icaacttmp = eeg_getdatact(EEG, 'component', chanorcomp);
offset = nan_mean(icaacttmp(:));
era = nan_mean(squeeze(icaacttmp)')-offset;
era_limits=get_era_limits(era);
erpimage( icaacttmp-offset, ones(1,EEG.trials)*10000, EEG.times*1000, ...
'', ei_smooth, 1, 'caxis', 2/3, 'cbar','erp', 'yerplabel', '','erp_vltg_ticks',era_limits);
end;
axes(hhh);
title(sprintf('%s activity \\fontsize{10}(global offset %3.3f)', basename, offset), 'fontsize', 14);
else
% put title at top of erpimage
EI_TITLE = 'Continous data';
axis off
hh = axes('Units','Normalized', 'Position',[45 62 48 38].*s+q);
ERPIMAGELINES = 200; % show 200-line erpimage
while size(EEG.data,2) < ERPIMAGELINES*EEG.srate
ERPIMAGELINES = 0.9 * ERPIMAGELINES;
end
ERPIMAGELINES = round(ERPIMAGELINES);
if ERPIMAGELINES > 2 % give up if data too small
if ERPIMAGELINES < 10
ei_smooth = 1;
else
ei_smooth = 3;
end
erpimageframes = floor(size(EEG.data,2)/ERPIMAGELINES);
erpimageframestot = erpimageframes*ERPIMAGELINES;
eegtimes = linspace(0, erpimageframes-1, length(erpimageframes)); % 05/27/2014 Ramon: length(erpimageframes) by EEG.srate/1000 in eegtimes = linspace(0, erpimageframes-1, EEG.srate/1000);
if typecomp == 1 % plot channel
offset = nan_mean(EEG.data(chanorcomp,:));
% Note: we don't need to worry about ERP limits, since ERPs
% aren't visualized for continuous data
erpimage( reshape(EEG.data(chanorcomp,1:erpimageframestot),erpimageframes,ERPIMAGELINES)-offset, ones(1,ERPIMAGELINES)*10000, eegtimes , ...
EI_TITLE, ei_smooth, 1, 'caxis', 2/3, 'cbar');
else % plot component
icaacttmp = eeg_getdatact(EEG, 'component', chanorcomp);
offset = nan_mean(icaacttmp(:));
erpimage(reshape(icaacttmp(:,1:erpimageframestot),erpimageframes,ERPIMAGELINES)-offset,ones(1,ERPIMAGELINES)*10000, eegtimes , ...
EI_TITLE, ei_smooth, 1, 'caxis', 2/3, 'cbar','yerplabel', '');
end
else
axis off;
text(0.1, 0.3, [ 'No erpimage plotted' 10 'for small continuous data']);
end;
axes(hhh);
end;
% plotting spectrum
% -----------------
if ~exist('winhandle')
winhandle = NaN;
end;
if ishandle(winhandle) % RMC isnan by ~ishandle
h = axes('units','normalized', 'position',[5 10 95 35].*s+q);
else
h = axes('units','normalized', 'position',[5 0 95 40].*s+q);
end;
%h = axes('units','normalized', 'position',[45 5 60 40].*s+q);
try
eeglab_options;
if typecomp == 1
[spectra freqs] = spectopo( EEG.data(chanorcomp,:), EEG.pnts, EEG.srate, spec_opt{:} );
else
if option_computeica
[spectra freqs] = spectopo( EEG.icaact(chanorcomp,:), EEG.pnts, EEG.srate, 'mapnorm', EEG.icawinv(:,chanorcomp), spec_opt{:} );
else
icaacttmp = (EEG.icaweights(chanorcomp,:)*EEG.icasphere)*reshape(EEG.data(EEG.icachansind,:,:), length(EEG.icachansind), EEG.trials*EEG.pnts);
[spectra freqs] = spectopo( icaacttmp, EEG.pnts, EEG.srate, 'mapnorm', EEG.icawinv(:,chanorcomp), spec_opt{:} );
end;
end;
% set up new limits
% -----------------
%freqslim = 50;
%set(gca, 'xlim', [0 min(freqslim, EEG.srate/2)]);
%spectra = spectra(find(freqs <= freqslim));
%set(gca, 'ylim', [min(spectra) max(spectra)]);
%tmpy = get(gca, 'ylim');
%set(gca, 'ylim', [max(tmpy(1),-1) tmpy(2)]);
set( get(gca, 'ylabel'), 'string', 'Power 10*log_{10}(\muV^{2}/Hz)', 'fontsize', 14);
set( get(gca, 'xlabel'), 'string', 'Frequency (Hz)', 'fontsize', 14);
title('Activity power spectrum', 'fontsize', 14);
catch err
axis off;
text(0.1, 0.3, [ 'Error: no spectrum plotted' 10 err.message 10]);
% lasterror
% text(0.1, 0.3, [ 'Error: no spectrum plotted' 10 ' make sure you have the ' 10 'signal processing toolbox']);
end;
% display buttons
% ---------------
if ishandle(winhandle)
COLREJ = '[1 0.6 0.6]';
COLACC = '[0.75 1 0.75]';
% CANCEL button
% -------------
h = uicontrol(gcf, 'Style', 'pushbutton', 'backgroundcolor', GUIBUTTONCOLOR, 'string', 'Cancel', 'Units','Normalized','Position',[-10 -10 15 6].*s+q, 'callback', 'close(gcf);');
% VALUE button
% -------------
hval = uicontrol(gcf, 'Style', 'pushbutton', 'backgroundcolor', GUIBUTTONCOLOR, 'string', 'Values', 'Units','Normalized', 'Position', [15 -10 15 6].*s+q);
% REJECT button
% -------------
if ~isempty(EEG.reject.gcompreject)
status = EEG.reject.gcompreject(chanorcomp);
else
status = 0;
end;
hr = uicontrol(gcf, 'Style', 'pushbutton', 'backgroundcolor', eval(fastif(status,COLREJ,COLACC)), ...
'string', fastif(status, 'REJECT', 'ACCEPT'), 'Units','Normalized', 'Position', [40 -10 15 6].*s+q, 'userdata', status, 'tag', 'rejstatus');
command = [ 'set(gcbo, ''userdata'', ~get(gcbo, ''userdata''));' ...
'if get(gcbo, ''userdata''),' ...
' set( gcbo, ''backgroundcolor'',' COLREJ ', ''string'', ''REJECT'');' ...
'else ' ...
' set( gcbo, ''backgroundcolor'',' COLACC ', ''string'', ''ACCEPT'');' ...
'end;' ];
set( hr, 'callback', command);
% HELP button
% -------------
h = uicontrol(gcf, 'Style', 'pushbutton', 'backgroundcolor', GUIBUTTONCOLOR, 'string', 'HELP', 'Units','Normalized', 'Position', [65 -10 15 6].*s+q, 'callback', 'pophelp(''pop_prop'');');
% OK button
% ---------
command = [ 'global EEG;' ...
'tmpstatus = get( findobj(''parent'', gcbf, ''tag'', ''rejstatus''), ''userdata'');' ...
'EEG.reject.gcompreject(' num2str(chanorcomp) ') = tmpstatus;' ];
if winhandle ~= 0
if VERS < 8.04
command = [ command ...
sprintf('if tmpstatus set(%3.15f, ''backgroundcolor'', %s); else set(%3.15f, ''backgroundcolor'', %s); end;', ...
winhandle, COLREJ, winhandle, COLACC)];
elseif VERS >= 8.04
command = [ command ...
sprintf('if tmpstatus set(findobj(''Tag'', ''%s''), ''backgroundcolor'', %s); else set(findobj(''Tag'',''%s''), ''backgroundcolor'', %s); end;', ...
winhandle.Tag, COLREJ, winhandle.Tag, COLACC)];
end
end;
command = [ command 'close(gcf); clear tmpstatus' ];
h = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'OK', 'backgroundcolor', GUIBUTTONCOLOR, 'Units','Normalized', 'Position',[90 -10 15 6].*s+q, 'callback', command);
% draw the figure for statistical values
% --------------------------------------
index = num2str( chanorcomp );
command = [ ...
'figure(''MenuBar'', ''none'', ''name'', ''Statistics of the component'', ''numbertitle'', ''off'');' ...
'' ...
'pos = get(gcf,''Position'');' ...
'set(gcf,''Position'', [pos(1) pos(2) 340 340]);' ...
'pos = get(gca,''position'');' ...
'q = [pos(1) pos(2) 0 0];' ...
's = [pos(3) pos(4) pos(3) pos(4)]./100;' ...
'axis off;' ...
'' ...
'txt1 = sprintf(''(\n' ...
'Entropy of component activity\t\t%2.2f\n' ...
'> Rejection threshold \t\t%2.2f\n\n' ...
' AND \t\t\t----\n\n' ...
'Kurtosis of component activity\t\t%2.2f\n' ...
'> Rejection threshold \t\t%2.2f\n\n' ...
') OR \t\t\t----\n\n' ...
'Kurtosis distibution \t\t\t%2.2f\n' ...
'> Rejection threhold\t\t\t%2.2f\n\n' ...
'\n' ...
'Current thesholds sujest to %s the component\n\n' ...
'(after manually accepting/rejecting the component, you may recalibrate thresholds for future automatic rejection on other datasets)'',' ...
'EEG.stats.compenta(' index '), EEG.reject.threshentropy, EEG.stats.compkurta(' index '), ' ...
'EEG.reject.threshkurtact, EEG.stats.compkurtdist(' index '), EEG.reject.threshkurtdist, fastif(EEG.reject.gcompreject(' index '), ''REJECT'', ''ACCEPT''));' ...
'' ...
'uicontrol(gcf, ''Units'',''Normalized'', ''Position'',[-11 4 117 100].*s+q, ''Style'', ''frame'' );' ...
'uicontrol(gcf, ''Units'',''Normalized'', ''Position'',[-5 5 100 95].*s+q, ''String'', txt1, ''Style'',''text'', ''HorizontalAlignment'', ''left'' );' ...
'h = uicontrol(gcf, ''Style'', ''pushbutton'', ''string'', ''Close'', ''Units'',''Normalized'', ''Position'', [35 -10 25 10].*s+q, ''callback'', ''close(gcf);'');' ...
'clear txt1 q s h pos;' ];
set( hval, 'callback', command);
if isempty( EEG.stats.compenta )
set(hval, 'enable', 'off');
end;
com = sprintf('pop_prop( %s, %d, %d, 0, %s);', inputname(1), typecomp, chanorcomp, vararg2str( { spec_opt } ) );
else
com = sprintf('pop_prop( %s, %d, %d, NaN, %s);', inputname(1), typecomp, chanorcomp, vararg2str( { spec_opt } ) );
end;
return;
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;
function era_limits=get_era_limits(era)
%function era_limits=get_era_limits(era)
%
% Returns the minimum and maximum value of an event-related
% activation/potential waveform (after rounding according to the order of
% magnitude of the ERA/ERP)
%
% Inputs:
% era - [vector] Event related activation or potential
%
% Output:
% era_limits - [min max] minimum and maximum value of an event-related
% activation/potential waveform (after rounding according to the order of
% magnitude of the ERA/ERP)
mn=min(era);
mx=max(era);
mn=orderofmag(mn)*round(mn/orderofmag(mn));
mx=orderofmag(mx)*round(mx/orderofmag(mx));
era_limits=[mn mx];
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
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_getepochevent.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_getepochevent.m
| 11,756 |
utf_8
|
5ea09aae0a884131df8e8c4e1d238cf3
|
% eeg_getepochevent() - Return dataset event field values for all events
% of one or more specified types
% Usage:
% >> epochval = eeg_getepochevent( EEG );
% >> epochval = eeg_getepochevent( EEG, 'key', 'val');
%
% Inputs:
% EEG - Input dataset
%
% Optional inputs:
% 'type' - String containing an event type. Cell array of string
% may be used to select several event types;
% {} is all types of events. Note: Requires that
% a field named 'type' is defined in 'EEG.event'.
% 'timewin' - [start end] Event time window in milliseconds
% (default []=whole epoch).
% 'fieldname' - Name of the field to return the values for.
% Default field is 'EEG.event.latency' in milliseconds
% (though internally this information is stored in
% real frames).
% 'trials' - [integer array] return values only for selected trials.
%
% Outputs:
% epochval - A value of the selected field for each epoch. This is
% NaN if no selected event occurred during the epoch. If
% several values are available for each epoch, only the
% first one is taken into consideration.
% Latencies are measured in msec relative to epoch onset.
% Forced to be numerical, where a string is converted by
% double to its ascii number which is normalized to be
% between 0 and 1, and the string is summed together. See
% the subfunction ascii2num for more details.
% allepochval - cell array with same length as the number of epoch
% containing all values for all epochs. This output is
% usefull when several value are found within each epoch.
% Not forced to be numerical.
%
% Notes: 1) Each epoch structure refers to the events that occurred
% during its time window. This function allows the user to return
% specified field values for a subset of the defined events.
%
% 2) If several of the selected events occur during a single epoch,
% a warning is issued, and value of ONLY THE FIRST event in the epoch
% is returned.
%
% If NO EVENT is selected in a given epoch, the value returned
% is NaN.
%
% 3) If the user elects to return the latency field, eeg_getepochevent()
% recomputes the latency of each event relative to the epoch time
% limits.
%
% Example:
% >> latencies = eeg_getepochevent(EEG, 'rt');
% % Return the latencies (by default) in milliseconds of events having
% % type 'rt' (reaction time)
%
% >> latencies = eeg_getepochevent(EEG, {'target','rare'}, [0 300], 'position');
% % Return the position (field 'position') of 'target' or 'rare' type
% % events occurring between 0 and 300 milliseconds of each epoch.
% % Returns NaN for epochs with no such events. (See Notes above).
%
% Author: Arnaud Delorme & Scott Makeig, CNL / Salk Institute, 15 Feb 2002
%
% See also: eeglab(), epoch()
% 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
% 02/15/02 modified function according to new event structure -ad
function [epochval, allepochval] = eeg_getepochevent(EEG, varargin);
if nargin < 2
help eeg_getepochevent;
return;
end;
% process more than one EEG dataset (for STUDY purposes)
% ------------------------------------------------------
if length(EEG) > 1
% the trial input may be a cell array; it has to be
% extracted before calling the function on each dataset
trials = cell(1,length(EEG));
for iArg = length(varargin)-1:-2:1
if strcmpi(varargin{iArg}, 'trials')
trials = varargin{iArg+1};
varargin(iArg:iArg+1) = [];
end;
end;
epochval = [];
for dat = 1:length(EEG)
tmpepochval = eeg_getepochevent(EEG(dat), 'trials', trials{dat}, varargin{:});
epochval = [ epochval tmpepochval ];
end;
return;
end;
% deal with old input format
% -------------------------
options = {};
oldformat = 0;
if nargin < 3
oldformat = 1;
elseif isnumeric(varargin{2}) && length(varargin{2}) == 2
oldformat = 1;
elseif length(varargin) == 3 && isfield(EEG.event,varargin(3))
oldformat = 1;
end;
if oldformat
if nargin > 1, options = { options{:} 'type' varargin{1} }; end;
if nargin > 2, options = { options{:} 'timewin' varargin{2} }; end;
if nargin > 3, options = { options{:} 'fieldname' varargin{3} }; end;
else
options = varargin;
end;
opt = finputcheck(options, { 'type' { 'string';'cell' } { [] [] } '';
'timewin' 'real' [] [-Inf Inf];
'fieldname' 'string' [] 'latency';
'trials' { 'real';'cell' } [] [] }, 'eeg_getepochevent');
if isstr(opt), error(opt); end;
if iscell(opt.trials) && ~isempty(opt.trials), opt.trials = opt.trials{1}; end;
if isempty(opt.timewin)
opt.timewin = [-Inf Inf];
end;
if isempty(EEG.event)
disp('Getepochevent: no event structure, aborting.'); return;
end;
% check if EEG.epoch contain references to events
% -----------------------------------------------
if ~isfield( EEG.event, 'epoch' )
disp('Getepochevent: no epoch indices in events, considering continuous values.');
end;
% check if EEG.epoch and EEG.event contains 'latency' field
% ------------------------------------------
if ~isfield( EEG.event, opt.fieldname)
disp(['Getepochevent: no ''' opt.fieldname ''' field in events, aborting.']); return;
end;
% deal with empty types
% ---------------------
if ~isempty(opt.type) & ~iscell(opt.type)
opt.type = { opt.type };
end;
% convert types
% -------------
for indextype=1:length(opt.type)
if isstr(opt.type{indextype}) & isnumeric(EEG.event(1).type)
if ~isempty(str2num(opt.type{indextype}))
opt.type{indextype} = str2num(opt.type{indextype});
else
error('eeg_getepochevent: string type cannot be found in numeric event type array');
end;
elseif isnumeric(opt.type{indextype}) & isstr(EEG.event(1).type)
opt.type{indextype} = num2str(opt.type{indextype});
end;
end;
% select epochs
% -------------
if ~isempty(opt.type)
Ieventtmp = [];
tmpevent = EEG.event;
for indextype=1:length(opt.type)
typeval = opt.type{indextype};
if isstr(typeval)
Ieventtmp = [Ieventtmp strmatch(typeval, { tmpevent.type }, 'exact')' ];
else
Ieventtmp = [Ieventtmp find(typeval == [ tmpevent.type ] ) ];
end;
end;
else
Ieventtmp = [1:length(EEG.event)];
end;
% select latencies
% ----------------
if isfield(EEG.event, 'latency') & (opt.timewin(1) ~= -Inf | opt.timewin(2) ~= Inf)
selected = ones(size(Ieventtmp));
for index=1:length(Ieventtmp)
if ~isfield(EEG.event, 'epoch'), epoch = 1;
else epoch = EEG.event(Ieventtmp(index)).epoch;
end;
reallat = eeg_point2lat(EEG.event(Ieventtmp(index)).latency, epoch, ...
EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3);
if reallat < opt.timewin(1) | reallat > opt.timewin(2)
selected(index) = 0;
end;
end;
Ieventtmp = Ieventtmp( find(selected == 1) );
end;
% select events
% -------------
epochval = cell(1,EEG.trials); epochval(:) = { nan };
allepochval = cell(1, EEG.trials); allepochval(:) = { {} };
if strcmp(opt.fieldname, 'latency')
for index = 1:length(Ieventtmp)
if ~isfield(EEG.event, 'epoch'), epoch = 1;
else epoch = EEG.event(Ieventtmp(index)).epoch;
end;
allepochval{epoch}{end+1} = eeg_point2lat(EEG.event(Ieventtmp(index)).latency, epoch, ...
EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3);
if length(allepochval{epoch}) == 1
epochval{epoch} = allepochval{epoch}{end};
else
if length(allepochval{epoch}) == 2 & nargout < 2
disp(['Warning: multiple event latencies found in epoch ' int2str(epoch) ]);
%, ignoring event ' int2str(Ieventtmp(index)) ' (''' num2str(EEG.event(Ieventtmp(index)).type) ''' type)' ]);
end;
end;
end;
elseif strcmp(opt.fieldname, 'duration')
for index = 1:length(Ieventtmp)
eval( [ 'val = EEG.event(Ieventtmp(index)).' opt.fieldname ';']);
if ~isempty(val)
if ~isfield(EEG.event, 'epoch'), epoch = 1;
else epoch = EEG.event(Ieventtmp(index)).epoch;
end;
epochval{epoch} = val/EEG.srate*1000;
allepochval{epoch}{end+1} = val/EEG.srate*1000;
end;
end;
else
for index = 1:length(Ieventtmp)
eval( [ 'val = EEG.event(Ieventtmp(index)).' opt.fieldname ';']);
if ~isempty(val)
if isstr(val)
val = ascii2num(val);
%val_tmp = double(val); % force epochval output to be numerical
% **Turn string into number that will sort in alphebetical order**
%val = 0;
%for val_count = 1:length(val_tmp)
% -48 so that '1' is scaled to ascii number 1, not 49
% /74 to scale double('z')=122 to 1
% 10^((2-... scale to 0 to 100milliseconds
% val = val + (val_tmp(val_count)-48)/74*10^(2-(val_count-1));
%end
% **End turn string ...**
end
if ~isfield(EEG.event, 'epoch'),
epoch = 1;
else epoch = EEG.event(Ieventtmp(index)).epoch;
end
epochval{epoch} = val(1);
allepochval{epoch}{end+1} = val(1);
end;
end;
end;
if isnumeric(epochval{1})
try
epochval = [ epochval{:} ];
for index = 1:length(allepochval)
allepochval{index} = [ allepochval{index}{:} ];
end
catch
end
end
% select specific trials
if ~isempty(opt.trials)
epochval = epochval(opt.trials);
allepochval = allepochval(opt.trials);
end;
%% SUBFUNCTION ASCII2NUM
% Maps ascii characters ['0','9'] to [1, 10], ['a','z'] to [11, 36]
% This is intended for alphebetically sorting string arrays numerically
% ascii_in [string array]
% output [double]
function out = ascii2num(ascii_in)
ascii_vector = double(ascii_in);
out = 0;
% go through each character in the string and scale and add it to output
for val_count = 1:length(ascii_vector)
ascii_char = ascii_vector(val_count);
if ascii_char>=48 & ascii_char<=57 % ['0','9'] to [1, 10]
ascii_adj = ascii_char - 47;
elseif ascii_char>=65 & ascii_char<=90 % ['A','Z'] to [11, 36]
ascii_adj = ascii_char - 64;
elseif ascii_char>=97 & ascii_char<=122 % ['a','z'] to [11, 36]
ascii_adj = ascii_char - 96;
else ascii_adj = ascii_char;
end
out = out + ascii_adj/36^val_count;
end
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_timeinterp.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_timeinterp.m
| 3,370 |
utf_8
|
365cfdc876b172e03a77db2833308aee
|
% eeg_timeinterp() - perform spline interpolation of a portion
% of data based on prior and post activity. See
% eeg_interp() for interpolation of bad channels.
%
% Usage:
% >> OUTEEG = eeg_timeinterp( INEEG, samples, 'key', 'val');
%
% Inputs:
% INEEG - input EEG structure
% samplerange - [min max] range sample points in continuous
% or epoched data. Only one sample point range
% may be given at a time.
%
% Optional inputs:
% 'elecinds' - indices of electrodes to interpolate (default all)
% 'epochinds' - indices of epochs for epoched data (default all)
% 'interpwin' - [integer] number of data points to use before and
% after the sample range. Default is 5 times the
% interpolated sample range.
% 'epochcont' - ['on'|'off'] epochs are contiguous. Only works for
% interpolating the end of epochs (default 'off')
%
% Outputs:
% OUTEEG - EEGLAB data structure
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, 2007
% Copyright (C) Arnaud Delorme, SCCN/INC/UCSD, 2007
%
% 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_timeinterp( EEG, samples, varargin);
if nargin < 2
help eeg_timeinterp;
return;
end;
opt = finputcheck(varargin, { 'epochinds' 'integer' [] [1:EEG.trials]; ...
'interpwin' 'integer' [] 5; ...
'elecinds' 'integer' [] [1:EEG.nbchan]; ...
'epochcont' 'string' { 'on';'off' } 'off' }, 'eeg_timeinterp');
if isstr(opt), error(opt); end;
srange = samples(2)-samples(1);
data = EEG.data;
pnts = EEG.pnts;
if strcmpi(opt.epochcont, 'on')
data(:,end+1:end+srange*opt.interpwin,1:end-1) = data(:,1:srange*opt.interpwin,2:end);
pnts = pnts + srange*opt.interpwin;
end;
% determine region to interpolate
% and region to use for interpolation
% -----------------------------------
samplesin = [min(samples(1)-srange*opt.interpwin,1):samples(1)-1 samples(2)+1:min(samples(2)+srange*opt.interpwin, pnts)];
samplesout = [samples(1):samples(2)];
if length(opt.epochinds) > 1, fprintf('Trials:'); end;
for index = opt.epochinds
for elec = opt.elecinds
EEG.data(elec,samplesout,index) = spline( samplesin, data(elec, samplesin, index), samplesout);
end;
if length(opt.epochinds) > 1,
fprintf('.');
if mod(index,40) == 01, fprintf('\n'); end;
end;
end;
if length(opt.epochinds) > 1, fprintf('\n'); end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_comments.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_comments.m
| 5,327 |
utf_8
|
e203d4a9ef43004035f13e5afe147831
|
% pop_comments() - edit comments
%
% Usage:
% >> newcomments = pop_comments( oldcomments);
% >> newcomments = pop_comments( oldcomments, title, newcomments, concat);
%
% Inputs:
% oldcomments - old comments (string or cell array of strings)
% title - optional window title (string)
% newcomments - new comments (string or cell array of strings)
% to assign (during commandline calls only)
% concat - [0|1] 1 concatenate the newcomments to the old one.
% Default is 0.
%
% Outputs:
% newcomments - new comments, string
%
% Note: if new comments are given as input, there are simply
% converted and returned by the function; otherwise a
% window pops up.
%
% Example
% EEG.comments = pop_comments( { 'This is the first line.' ' ' ...
% 'This is the third line.' }, 'Editing');
% EEG.comments = pop_comments(EEG.comments,'','This is the fourth line.",1);
%
% 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
% 03-16-02 text interface editing -sm & ad
function [newcomments, com] = pop_comments( comments, plottitle, newcomments, concat );
com = '';
if exist('comments') ~=1, comments = '';
elseif iscell(comments), comments = strvcat(comments{:});
end;
% remove trailing blanks and make multiline
comments = strmultiline( comments, 53);
if nargin < 3
newcomments = comments;
try, icadefs;
catch,
BACKCOLOR = [.8 .8 .8];
GUIBUTTONCOLOR = [.8 .8 .8];
end;
figure('menubar', 'none', 'tag', 'comment', 'color', BACKCOLOR, 'userdata', 0, ...
'numbertitle', 'off', 'name', 'Read/Enter comments -- pop_comments()');
pos = get(gca,'position'); % plot relative to current axes
q = [pos(1) pos(2) 0 0];
s = [pos(3) pos(4) pos(3) pos(4)]./100;
if exist('plottitle') ~=1, plottitle = ''; end;
h = title(plottitle);
set(h, 'fontname','Helvetica','fontweight', 'bold', 'interpreter', 'none');
axis off;
% create the buttons
% ------------------
uicontrol('Parent',gcf, ...
'Units','Normalized', ...
'Position', [0 -5 20 10].*s+q, ...
'backgroundcolor', GUIBUTTONCOLOR, ...
'string','CANCEL', 'callback', 'close(findobj(''tag'', ''comment''));' );
uicontrol('Parent',gcf, ...
'Units','Normalized', ...
'Position', [80 -5 20 10].*s+q, ...
'backgroundcolor', GUIBUTTONCOLOR, ...
'string','SAVE', 'callback', ...
[ 'set(gcbf, ''userdata'', ' ...
'get(findobj(''parent'', gcbf, ''tag'', ''edit''), ''string''));' ]);
%hh = text( q(1), 100*s(2)+q(2), comments, 'tag', 'edit');
%set( hh, 'editing', 'on', 'verticalalignment', 'top');
%hh = uicontrol('Parent',gcf, ...
%'Units','Normalized', ...
%'style', 'text', ...
%'Position', [0 100 105 5].*s+q, ...
%'string', 'Warning: each blank line must contain at least a ''space'' character', ...
%'horizontalalignment', 'left', ...
%'backgroundcolor', BACKCOLOR );
hh = uicontrol('Parent',gcf, ...
'Units','Normalized', ...
'style', 'edit', ...
'tag', 'edit', ...
'Position', [0 10 105 85].*s+q, ...
'string', comments, ...
'backgroundcolor', [ 1 1 1], ...
'horizontalalignment', 'left', ...
'max', 3, ...
'fontsize', 12);
% Try to use 'courier' since it has constant character size
lf = listfonts;
tmppos = strmatch('Courier', lf);
if ~isempty(tmppos)
set(hh, 'fontname', lf{tmppos(1)}, 'fontsize', 10);
end;
waitfor(gcf, 'userdata');
% find return mode
if isempty(get(0, 'currentfigure')), return; end;
tmp = get(gcf, 'userdata');
if ~isempty(tmp) & isstr(tmp)
newcomments = tmp; % ok button
else return;
end;
close(findobj('tag', 'comment'));
else
if iscell(newcomments)
newcomments = strvcat(newcomments{:});
end;
if nargin > 3 & concat == 1
newcomments = strvcat(comments, newcomments);
end;
return;
end;
I = find( comments(:) == '''');
comments(I) = ' ';
if nargout > 1
if ~strcmp( comments, newcomments)
allsame = 1;
for index = 1:size(comments, 1)
if ~strcmp(comments(index,:), newcomments(index,:)), allsame = 0; end;
end;
else
allsame = 0;
end;
if allsame & ~isempty(comments)
com =sprintf('EEG.comments = pop_comments(EEG.comments, '''', %s, 1);', vararg2str(newcomments(index+1:end,:)));
else
com =sprintf('EEG.comments = pop_comments('''', '''', %s);', vararg2str(newcomments));
end;
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_emptyset.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_emptyset.m
| 2,505 |
utf_8
|
a93f07a3989f904c1eade15794aab1f1
|
% eeg_emptyset() - Initialize an EEG dataset structure with default values.
%
% Usage:
% >> EEG = eeg_emptyset();
%
% Outputs:
% EEG - empty dataset structure with default values.
%
% 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
function EEG = eeg_emptyset();
EEG.setname = '';
EEG.filename = '';
EEG.filepath = '';
EEG.subject = '';
EEG.group = '';
EEG.condition = '';
EEG.session = [];
EEG.comments = '';
EEG.nbchan = 0;
EEG.trials = 0;
EEG.pnts = 0;
EEG.srate = 1;
EEG.xmin = 0;
EEG.xmax = 0;
EEG.times = [];
EEG.data = [];
EEG.icaact = [];
EEG.icawinv = [];
EEG.icasphere = [];
EEG.icaweights = [];
EEG.icachansind = [];
EEG.chanlocs = [];
EEG.urchanlocs = [];
EEG.chaninfo = [];
EEG.ref = [];
EEG.event = [];
EEG.urevent = [];
EEG.eventdescription = {};
EEG.epoch = [];
EEG.epochdescription = {};
EEG.reject = [];
EEG.stats = [];
EEG.specdata = [];
EEG.specicaact = [];
EEG.splinefile = '';
EEG.icasplinefile = '';
EEG.dipfit = [];
EEG.history = '';
EEG.saved = 'no';
EEG.etc = [];
%EEG.reject.threshold = [1 0.8 0.85];
%EEG.reject.icareject = [];
%EEG.reject.compreject = [];
%EEG.reject.gcompreject= [];
%EEG.reject.comptrial = [];
%EEG.reject.sigreject = [];
%EEG.reject.elecreject = [];
%EEG.stats.kurta = [];
%EEG.stats.kurtr = [];
%EEG.stats.kurtd = [];
%EEG.stats.eegentropy = [];
%EEG.stats.eegkurt = [];
%EEG.stats.eegkurtg = [];
%EEG.stats.entropy = [];
%EEG.stats.kurtc = [];
%EEG.stats.kurtt = [];
%EEG.stats.entropyc = [];
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_eventstat.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_eventstat.m
| 4,984 |
utf_8
|
a4b8019a80d3c517ad7407e9b6906815
|
% pop_eventstat() - Computes and plots statistical characteristics of an EEG event,
% including the data histogram, a fitted normal distribution,
% a normal ditribution fitted on trimmed data, a boxplot, and
% the QQ-plot. The estimates value are printed in a panel and
% can be read as output. NaNs are omitted. See signalstat().
%
% Usage:
% >> OUTEEG = pop_eventstat( EEG ); % pops up
% >> [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh] = pop_eventstat( EEG, eventfield, type );
% >> [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh] = pop_eventstat( EEG, eventfield, type, percent );
%
% Inputs:
% EEG - input EEG dataset
% eventfield - event field to process (i.e. latency)
% type - name of the event type(s) to process. Can be a single element or
% a cell array. Default is all types.
% latrange - [min max] event latency range within data epochs in milliseconds.
% Default is whole epoch.
% percent - percentage for trimmed data statistics. Default is 5%. (see signalstat())
%
% Outputs:
% OUTEEG - output dataset
%
% Author: Arnaud Delorme & Luca Finelli, CNL / Salk Institute - SCCN, 15 August 2002
%
% See also: signalstat(), eeg_getepochevent(), eeglab()
% Copyright (C) 2002 Arnaud Delorme & Luca Finelli, Salk/SCCN, La Jolla, CA
%
% 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 = pop_eventstat( EEG, eventfield, type, latrange, percent );
% the command output is a hidden output that does not have to
% be described in the header
com = ''; % this initialization ensure that the function will return something
% if the user press the cancel button
varargout{1} = '';
% display help if not enough arguments
% ------------------------------------
if nargin < 1
help pop_eventstat;
return;
end;
popup=0;
if nargin < 2
popup = 1;
end;
if nargin < 3
percent=5;
end;
% pop up window
% -------------
if nargin < 2
promptstr = { 'Event field to process:' ...
strvcat('Event type(s) ([]=all):', ...
'Select "Edit > Event values" to see type values') ...
strvcat('Event latency range (ms)', ...
'Default is whole epoch or data') ...
'Percent for trimmed statistics:' };
inistr = { 'latency' '' '' '5' };
result = inputdlg2( promptstr, 'Plot event statistics -- pop_eventstat()', 1, inistr, 'signalstat');
if length( result ) == 0 return; end;
eventfield = deblank(result{1}); % the brackets allow to process matlab arrays
if ~isempty(result{2})
if strcmpi(result{2}(1),'''')
type = eval( [ '{' result{2} '}' ] );
else type = parsetxt( result{2});
end;
else
disp('WARNING: you should select an event type');
type = {};
end;
latrange = eval( [ '[' result{3} ']' ] );
percent = eval( [ '[' result{4} ']' ] );
else
if nargin < 3
type = [];
end;
if nargin < 4
latrange = [];
end;
if nargin < 5
percent = 5;
end;
end;
% call function signalstat() either on raw data or ICA data
% ---------------------------------------------------------
[ typevals alltypevals ] = eeg_getepochevent(EEG, type, latrange, eventfield);
% concatenate alltypevals
% -----------------------
typevals = [];
for index = 1:length(alltypevals)
typevals = [ typevals alltypevals{index} ];
end;
if isempty(typevals)
error('No such events found. See Edit > Event values to confirm event type.');
end;
dlabel='Event values';
if isempty(type)
dlabel2=['All event statistics for ''' eventfield ''' info'];
else
dlabel2=['Event ' vararg2str(type) ' statistics for ''' eventfield ''' info'];
end;
% outputs
% -------
outstr = '';
if ~popup
for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end;
if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end;
end;
% return the string command
% -------------------------
fprintf('pop_eventstat: extracting events...\n');
varargout{1} = sprintf('pop_eventstat( %s, %s );', inputname(1), vararg2str({eventfield type latrange percent}));
com = sprintf('%s signalstat( typevals, 1, dlabel, percent, dlabel2 ); %s', outstr);
eval(com)
try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
getchanlist.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/getchanlist.m
| 2,052 |
utf_8
|
12fe9861407f310f8b008f835753091b
|
% getchanlist() - Obtain indices of specified channel types.
%
% Usage:
% >> chanlist = getchanlist(chanlocs, type)
%
% Inputs:
% chanlocs - EEGLAB channel location structure
% type - [string] select channel of specified type
% can enter a cell array to select several channel types
%
% Output:
% chanlist - list of channel indices for the selected type(s)
% sorted in increasing order
%
% Note: this function is not case sensitive
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2004
%
% See also: pop_chanedit()
% Copyright (C) Arnaud Delorme, SCCN, INC, 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 chanlist = getchanlist(chanlocs, type)
if nargin < 1
help getchanlist;
return;
end;
if nargin < 2 || ~isfield(chanlocs, 'type')
chanlist = [1:length(chanlocs)];
return;
end;
% search channel types
% --------------------
if isstr(type), type = { type }; end;
type = lower(type);
chanlist = [];
alltypes = lower({ chanlocs.type });
for index = 1:length(type)
tmplist = strmatch(type{index}, alltypes, 'exact');
if isempty(tmplist)
fprintf('Warning: no channel of type ''%s'' found\n', type{index});
end;
chanlist = [ chanlist tmplist' ];
end;
chanlist = sort(chanlist);
|
github
|
ZijingMao/baselineeegtest-master
|
pop_biosig.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_biosig.m
| 11,082 |
utf_8
|
7f80b9e3e215ef99bd71c1590b87ccb0
|
% pop_biosig() - import data files into EEGLAB using BIOSIG toolbox
%
% Usage:
% >> OUTEEG = pop_biosig; % pop up window
% >> OUTEEG = pop_biosig( filename, channels, type);
%
% Inputs:
% filename - [string] file name
%
% Optional inputs:
% 'channels' - [integer array] list of channel indices
% 'blockrange' - [min max] integer range of data blocks to import, in seconds.
% Entering [0 3] will import the first three blocks of data.
% Default is empty -> import all data blocks.
% 'importevent' - ['on'|'off'] import events. Default if 'on'.
% 'importannot' - ['on'|'off'] import annotations (EDF+ only). Default if 'on'
% 'blockepoch' - ['on'|'off'] force importing continuous data. Default is 'on'
% 'ref' - [integer] channel index or index(s) for the reference.
% Reference channels are not removed from the data,
% allowing easy re-referencing. If more than one
% channel, data are referenced to the average of the
% indexed channels. WARNING! Biosemi Active II data
% are recorded reference-free, but LOSE 40 dB of SNR
% if no reference is used!. If you do not know which
% channel to use, pick one and then re-reference after
% the channel locations are read in. {default: none}.
% For more information see http://www.biosemi.com/faq/cms&drl.htm
% 'refoptions' - [Cell] Option for the pop_reref function. Default is to
% remove the reference channel if there is one of them and to
% keep it if there are several of them from the graphic
% interface. From the command line default option is to
% keep the reference channel.
% 'rmeventchan' - ['on'|'off'] remove event channel after event
% extraction. Default is 'on'.
% 'memorymapped' - ['on'|'off'] import memory mapped file (useful if
% encountering memory errors). Default is 'off'.
%
% Outputs:
% OUTEEG - EEGLAB data structure
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Oct. 29, 2003-
%
% Note: BIOSIG toolbox must be installed. Download BIOSIG at
% http://biosig.sourceforge.net
% Contact [email protected] for troubleshooting using BIOSIG.
% 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, command, dat] = pop_biosig(filename, varargin);
EEG = [];
command = '';
if ~plugin_askinstall('Biosig', 'sopen'), return; end;
if nargin < 1
% ask user
[filename, filepath] = uigetfile('*.*', 'Choose a data file -- pop_biosig()'); %%% this is incorrect in original version!!!!!!!!!!!!!!
drawnow;
if filename == 0 return; end;
filename = [filepath filename];
% look if MEG
% -----------
if length(filepath)>4
if strcmpi(filepath(end-3:end-1), '.ds'), filename = filepath(1:end-1); end;
end;
% open file to get infos
% ----------------------
disp('Reading data file header...');
dat = sopen(filename, 'r', [], 'OVERFLOWDETECTION:OFF');
if ~isfield(dat, 'NRec')
error('Unsuported data format');
end;
% special BIOSEMI
% ---------------
eeglab_options;
if strcmpi(dat.TYPE, 'BDF')
disp(upper('We highly recommend that you choose a reference channel IF these are Biosemi data'));
disp(upper('(e.g., a mastoid or other channel). Otherwise the data will lose 40 dB of SNR!'));
disp('For more information, see <a href="http://www.biosemi.com/faq/cms&drl.htm">http://www.biosemi.com/faq/cms&drl.htm</a>');
end;
uilist = { { 'style' 'text' 'String' 'Channel list (defaut all):' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'String' [ 'Data range (in seconds) to read (default all [0 ' int2str(dat.NRec) '])' ] } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'String' 'Extract event' } ...
{ 'style' 'checkbox' 'string' '' 'value' 1 'enable' 'on' } {} ...
{ 'style' 'text' 'String' 'Import anotations (EDF+ only)' } ...
{ 'style' 'checkbox' 'string' '' 'value' 1 'enable' 'on' } {} ...
{ 'style' 'text' 'String' 'Force importing continuous data' 'value' 1} ...
{ 'style' 'checkbox' 'string' '' 'value' 0 } {} ...
{ 'style' 'text' 'String' 'Reference chan(s) indices - required for BIOSEMI' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'checkbox' 'String' 'Import as memory mapped file (use if out of memory error)' 'value' option_memmapdata } };
geom = { [3 1] [3 1] [3 0.35 0.5] [3 0.35 0.5] [3 0.35 0.5] [3 1] [1] };
result = inputgui( geom, uilist, 'pophelp(''pop_biosig'')', ...
'Load data using BIOSIG -- pop_biosig()');
if length(result) == 0 return; end;
% decode GUI params
% -----------------
options = {};
if ~isempty(result{1}), options = { options{:} 'channels' eval( [ '[' result{1} ']' ] ) }; end;
if ~isempty(result{2}), options = { options{:} 'blockrange' eval( [ '[' result{2} ']' ] ) }; end;
if length(result) > 2
if ~result{3}, options = { options{:} 'importevent' 'off' }; end;
if ~result{4}, options = { options{:} 'importannot' 'off' }; end;
if result{5}, options = { options{:} 'blockepoch' 'off' }; end;
if ~isempty(result{6}), options = { options{:} 'ref' eval( [ '[' result{6} ']' ] ) }; end;
if result{7}, options = { options{:} 'memorymapped' 'on' }; end;
end;
if length(eval( [ '[' result{6} ']' ] )) > 1
options = { options{:} 'refoptions' { 'keepref' 'off' } };
end;
else
options = varargin;
end;
% decode imput parameters
% -----------------------
g = finputcheck( options, { 'blockrange' 'integer' [0 Inf] [];
'channels' 'integer' [0 Inf] [];
'ref' 'integer' [0 Inf] [];
'refoptions' 'cell' {} { 'keepref' 'on' };
'rmeventchan' 'string' { 'on';'off' } 'on';
'importevent' 'string' { 'on';'off' } 'on';
'importannot' 'string' { 'on';'off' } 'on';
'memorymapped' 'string' { 'on';'off' } 'off';
'blockepoch' 'string' { 'on';'off' } 'off' }, 'pop_biosig');
if isstr(g), error(g); end;
% import data
% -----------
EEG = eeg_emptyset;
[dat DAT interval] = readfile(filename, g.channels, g.blockrange, g.memorymapped);
if strcmpi(g.blockepoch, 'off')
dat.NRec = 1;
end;
EEG = biosig2eeglab(dat, DAT, interval, g.channels, strcmpi(g.importevent, 'on'));
if strcmpi(g.rmeventchan, 'on') & strcmpi(dat.TYPE, 'BDF') & isfield(dat, 'BDF')
if size(EEG.data,1) >= dat.BDF.Status.Channel,
disp('Removing event channel...');
EEG.data(dat.BDF.Status.Channel,:) = [];
if ~isempty(EEG.chanlocs) && length(EEG.chanlocs) >= dat.BDF.Status.Channel
EEG.chanlocs(dat.BDF.Status.Channel) = [];
end;
end;
EEG.nbchan = size(EEG.data,1);
end;
% rerefencing
% -----------
if ~isempty(g.ref)
disp('Re-referencing...');
EEG = pop_reref(EEG, g.ref, g.refoptions{:});
% EEG.data = EEG.data - repmat(mean(EEG.data(g.ref,:),1), [size(EEG.data,1) 1]);
% if length(g.ref) == size(EEG.data,1)
% EEG.ref = 'averef';
% end;
% if length(g.ref) == 1
% disp([ 'Warning: channel ' int2str(g.ref) ' is now zeroed (but still present in the data)' ]);
% else
% disp([ 'Warning: data matrix rank has decreased through re-referencing' ]);
% end;
end;
% test if annotation channel is present
% -------------------------------------
if isfield(dat, 'EDFplus') && strcmpi(g.importannot, 'on')
tmpfields = fieldnames(dat.EDFplus);
for ind = 1:length(tmpfields)
tmpdat = getfield(dat.EDFplus, tmpfields{ind});
if length(tmpdat) == EEG.pnts
EEG.data(end+1,:) = tmpdat;
EEG.nbchan = EEG.nbchan+1;
if ~isempty(EEG.chanlocs)
EEG.chanlocs(end+1).labels = tmpfields{ind};
end;
end;
end;
end;
% convert data to single if necessary
% -----------------------------------
EEG = eeg_checkset(EEG,'makeur'); % Make EEG.urevent field
EEG = eeg_checkset(EEG);
% history
% -------
if isempty(options)
command = sprintf('EEG = pop_biosig(''%s'');', filename);
else
command = sprintf('EEG = pop_biosig(''%s'', %s);', filename, vararg2str(options));
end;
% ---------
% read data
% ---------
function [dat DAT interval] = readfile(filename, channels, blockrange, memmapdata);
if isempty(channels), channels = 0; end;
dat = sopen(filename, 'r', channels,'OVERFLOWDETECTION:OFF');
if strcmpi(memmapdata, 'off')
fprintf('Reading data in %s format...\n', dat.TYPE);
if ~isempty(blockrange)
newblockrange = blockrange;
% newblockrange = newblockrange*dat.Dur;
DAT=sread(dat, newblockrange(2)-newblockrange(1), newblockrange(1));
else
DAT=sread(dat, Inf);% this isn't transposed in original!!!!!!!!
newblockrange = [];
end
sclose(dat);
else
fprintf('Reading data in %s format (file will be mapped to memory so this may take a while)...\n', dat.TYPE);
inc = ceil(250000/(dat.NS*dat.SPR)); % 1Mb block
if isempty(blockrange), blockrange = [0 dat.NRec]; end;
blockrange(2) = min(blockrange(2), dat.NRec);
allblocks = [blockrange(1):inc:blockrange(end)];
count = 1;
for bind = 1:length(allblocks)-1
TMPDAT=sread(dat, (allblocks(bind+1)-allblocks(bind))*dat.Dur, allblocks(bind)*dat.Dur);
if bind == 1
DAT = mmo([], [size(TMPDAT,2) (allblocks(end)-allblocks(1))*dat.SPR]);
end;
DAT(:,count:count+length(TMPDAT)-1) = TMPDAT';
count = count+length(TMPDAT);
end;
sclose(dat);
end;
if ~isempty(blockrange)
interval(1) = blockrange(1) * dat.SampleRate(1) + 1;
interval(2) = blockrange(2) * dat.SampleRate(1);
else interval = [];
end
|
github
|
ZijingMao/baselineeegtest-master
|
pop_export.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_export.m
| 8,253 |
utf_8
|
d7e2bbf82fd68b8df5f65244d810f123
|
% pop_export() - export EEG dataset
%
% Usage:
% >> com = pop_export(EEG); % a window pops up
% >> com = pop_export(EEG, filename, 'key', 'val', ... );
%
% Inputs:
% EEG - eeglab dataset
% filename - file name
%
% Optional inputs:
% 'ica' - ['on'|'off'] export ICA activities (or ERP). Default 'off'.
% 'time' - ['on'|'off'] include time values. Default 'on'.
% 'timeunit' - [float] time unit rel. to seconds. Default: 1E-3 = msec.
% 'elec' - ['on'|'off'] include electrodes names or component numbers.
% Default 'on'.
% 'transpose' - ['on'|'off'] 'off'-> electrode data = rows; 'on' -> electrode
% data = columns. Default 'off'.
% 'erp' - ['on'|'off'] export ERP instead of raw data. Default 'off'.
% 'expr' - [string] evaluate epxression on data. The expression must
% contain a variable 'x' representing the 2-D or 3-D
% data. For example "x = 2*x" to multiply the data by 2.
% 'precision' - [float] number of significant digits in output. Default 7.
% Default of 7 should allow to reach about 23 to 24 bits
% of precision and should be enough for EEG.
%
% Outputs:
% com - The expresion that execute this function. i.e. 'pop_export(MyEEG, 'ExpEEG.mat')'
%
% Note: tabulation are used as a delimiter.
%
% Author: Arnaud Delorme, CNL / Salk Institute, May 13, 2003
% Copyright (C) May 13, 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 com = pop_export(EEG, filename, varargin);
com = '';
if nargin < 1
help pop_export;
return;
end;
if nargin < 2
commandload = [ '[filename, filepath] = uiputfile(''*'', ''Select a text file'');' ...
'if filename ~=0,' ...
' set(findobj(''parent'', gcbf, ''tag'', ''tagedit''), ''string'', [ filepath filename ]);' ...
'end;' ...
'clear filename filepath tagtest;' ];
uilist = { { 'style' 'text' 'string' 'Output file name' }, ...
{ 'style' 'edit' 'string' '' 'tag' 'tagedit' }, ...
{ 'style' 'pushbutton' 'string' 'Browse' 'callback' commandload },...
{ 'style' 'text' 'string' 'Export ICA activities instead of EEG data:' }, ...
{ 'style' 'checkbox' 'string' '' }, { },{ }, ...
{ 'style' 'text' 'string' 'Export ERP average instead of trials:' }, ...
{ 'style' 'checkbox' 'string' '' }, { }, { }, ...
{ 'style' 'text' 'string' 'Transpose matrix (elec -> rows):' }, ...
{ 'style' 'checkbox' 'string' '' }, { }, { }, ...
{ 'style' 'text' 'string' 'Export channel labels/component numbers:' }, ...
{ 'style' 'checkbox' 'string' '' 'value' 1 }, { }, { }, ...
{ 'style' 'text' 'string' 'Export time values:' }, ...
{ 'style' 'checkbox' 'string' '' 'value' 1 }, ...
{ 'style' 'text' 'string' 'Unit (re. sec)' }, { 'style' 'edit' 'string' '1E-3' }, ...
{ 'style' 'text' 'string' 'Number of significant digits to output:' }, ...
{ 'style' 'edit' 'string' '4' }, { }, { }, ...
{ 'style' 'text' 'string' 'Apply an expression to the output (see ''expr'' help):'} , ...
{ 'style' 'edit' 'string' '' } { } { } };
bcheck = [1.7 0.25 0.7 0.6];
uigeom = { [1 2 0.5] bcheck bcheck bcheck bcheck bcheck [3 0.7 0.8 0.6] [3 2 0.05 0.05] };
result = inputgui( uigeom, uilist, 'pophelp(''pop_export'');', 'Export data - pop_export()' );
if length( result ) == 0 return; end;
% decode options
% --------------
if isempty(result{1}), error('File name required'); end;
filename = result{1};
options = {};
if result{2}, options = { options{:} 'ica' 'on' }; end;
if result{3}, options = { options{:} 'erp' 'on' }; end;
if result{4}, options = { options{:} 'transpose' 'on' }; end;
if ~result{5}, options = { options{:} 'elec' 'off' }; end;
if ~result{6}, options = { options{:} 'time' 'off' }; end;
if ~strcmpi(result{7}, '1E-3'), options = { options{:} 'timeunit' eval(result{7}) }; end;
if ~strcmpi(result{8}, '7'), options = { options{:} 'precision' eval(result{8}) }; end;
if ~isempty(result{9}), options = { options{:} 'expr' result{9} }; end;
else
options = varargin;
end;
% test inputs
% -----------
g = finputcheck(options, { ...
'ica' 'string' { 'on';'off' } 'off';
'time' 'string' { 'on';'off' } 'on';
'timeunit' 'float' [0 Inf] 1E-3;
'elec' 'string' { 'on';'off' } 'on';
'transpose' 'string' { 'on';'off' } 'off';
'erp' 'string' { 'on';'off' } 'off';
'precision' 'integer' [0 Inf] 7;
'expr' 'string' [] '' }, 'pop_export');
if isstr(g), error(g); end;
% select data
% ----------
if strcmpi(g.ica, 'on');
eeglab_options; % changed from eeglaboptions 3/30/02 -sm
if option_computeica
x = EEG.icaact;
else
x = EEG.icaweights*EEG.icasphere*reshape(EEG.data(EEG.icachansind,:,:), length(EEG.icachansind), EEG.trials*EEG.pnts);
x = reshape(x, size(x,1), EEG.pnts, EEG.trials);
end;
else
x = EEG.data;
end;
% select erp
% ----------
if strcmpi(g.erp, 'on');
x = mean(x, 3);
else
x = reshape(x, size(x,1), size(x,2)*size(x,3));
end;
% write data
% ----------
if ~isempty(g.expr)
eval([ g.expr ';' ]);
end;
% add time axis
% -------------
if strcmpi(g.time, 'on');
timeind = repmat( linspace(EEG.xmin, EEG.xmax, EEG.pnts)/g.timeunit, ...
[ 1 fastif(strcmpi(g.erp,'on'), 1, EEG.trials) ]);
xx = zeros(size(x,1)+1, size(x,2));
xx(1,:) = timeind;
xx(2:end,:) = x;
x = xx; clear xx;
end
% transpose and write to disk
% ---------------------------
fid = fopen(filename, 'w');
if strcmpi(g.transpose, 'on');
% writing electrodes
% ------------------
strprintf = '';
for index = 1:size(x,1)
if strcmpi(g.time, 'on'), tmpind = index-1;
else tmpind = index;
end;
if strcmpi(g.elec, 'on')
if tmpind > 0
if ~isempty(EEG.chanlocs) & ~strcmpi(g.ica, 'on')
fprintf(fid, '%s\t', EEG.chanlocs(tmpind).labels);
else fprintf(fid, '%d\t', tmpind);
end;
else
fprintf(fid, ' \t');
end;
end;
strprintf = [ strprintf '%.' num2str(g.precision) 'f\t' ];
end;
strprintf(end) = 'n';
if strcmpi(g.elec, 'on'), fprintf(fid, '\n'); end;
fprintf(fid, strprintf, x);
else
% writing electrodes
% ------------------
for index = 1:size(x,1)
if strcmpi(g.time, 'on'), tmpind = index-1;
else tmpind = index;
end;
if strcmpi(g.elec, 'on')
if tmpind > 0
if ~isempty(EEG.chanlocs) & ~strcmpi(g.ica, 'on')
fprintf(fid,'%s\t', EEG.chanlocs(tmpind).labels);
else fprintf(fid,'%d\t', tmpind);
end;
else
fprintf(fid, ' \t');
end;
end;
fprintf(fid,[ '%.' num2str(g.precision) 'f\t' ], x(index, :));
fprintf(fid, '\n');
end;
end;
fclose(fid);
com = sprintf('pop_export(%s,%s);', inputname(1), vararg2str({ filename, options{:} }));
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_rejchan.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_rejchan.m
| 10,276 |
utf_8
|
a844de4616006a4306ad0d4e4b770160
|
% pop_rejchan() - reject artifacts channels in an EEG dataset using joint
% probability of the recorded electrode.
%
% Usage:
% >> pop_rejchan( INEEG ) % pop-up interative window mode
% >> [EEG, indelec, measure, com] = ...
% = pop_rejchan( INEEG, 'key', 'val');
%
% Inputs:
% INEEG - input dataset
%
% Optional inputs:
% 'elec' - [n1 n2 ...] electrode number(s) to take into
% consideration for rejection
% 'threshold' - [max] absolute thresold or activity probability
% limit(s) (in std. dev.) if norm is 'on'.
% 'measure' - ['prob'|'kurt'|'spec'] compute probability 'prob', kurtosis 'kurt'
% or spectrum 'spec' for each channel. Default is 'kurt'.
% 'norm' - ['on'|'off'] normalize measure above (using trimmed
% normalization as described in the function jointprob()
% and rejkurt(). Default is 'off'.
% 'precomp' - [float array] use this array instead of computing the 'prob'
% or 'kurt' measures.
% 'freqrange' - [min max] frequency range for spectrum computation.
% Default is 1 to sampling rate divided by 2. The average
% of the log spectral power is computed over the frequency
% range of interest.
%
% Outputs:
% OUTEEG - output dataset with updated joint probability array
% indelec - indices of rejected electrodes
% measure - measure value for each electrode
% com - executed command
%
% Author: Arnaud Delorme, CERCO, UPS/CNRS, 2008-
%
% See also: jointprob(), rejkurt()
% Copyright (C) 2008 Arnaud Delorme, CERCO, UPS/CNRS
%
% 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, indelec, measure, com] = pop_rejchan( EEG, varargin);
com = '';
indelec = [];
measure = [];
if nargin < 1
help pop_rejchan;
return;
end;
if nargin < 2
% which set to save
% -----------------
cb_select = [ 'if get(gcbo, ''value'') == 3,' ...
' set(findobj(gcbf, ''tag'', ''spec''), ''enable'', ''on'');' ...
'else,' ...
' set(findobj(gcbf, ''tag'', ''spec''), ''enable'', ''off'');' ...
'end;' ];
cb_norm = [ 'if get(gcbo, ''value''),' ...
' set(findobj(gcbf, ''tag'', ''normlab''), ''string'', ''Z-score threshold [max] or [min max]'');' ...
'else,' ...
' set(findobj(gcbf, ''tag'', ''normlab''), ''string'', ''Absolute threshold [max] or [min max]'');' ...
'end;' ];
uilist = { { 'style' 'text' 'string' 'Electrode (number(s); Ex: 2 4 5)' } ...
{ 'style' 'edit' 'string' ['1:' int2str(EEG.nbchan)] } ...
{ 'style' 'text' 'string' 'Measure to use' } ...
{ 'style' 'popupmenu' 'string' 'Probability|Kurtosis|Spectrum' 'value' 2 'callback' cb_select } ...
{ 'style' 'text' 'string' 'Normalize measure (check=on)' } ...
{ 'style' 'checkbox' 'string' '' 'value' 1 'callback' cb_norm } { } ...
{ 'style' 'text' 'string' 'Z-score threshold [max] or [min max]' 'tag' 'normlab' } ...
{ 'style' 'edit' 'string' '5' } ...
{ 'style' 'text' 'string' 'Spectrum freq. range' 'enable' 'off' 'tag' 'spec' } ...
{ 'style' 'edit' 'string' num2str([1 EEG.srate/2]) 'enable' 'off' 'tag' 'spec' } }; % 7/16/2014 Ramon
geom = { [2 1.3] [2 1.3] [2 0.4 0.9] [2 1.3] [2 1.3] };
result = inputgui( 'uilist', uilist, 'geometry', geom, 'title', 'Reject channel -- pop_rejchan()', ...
'helpcom', 'pophelp(''pop_rejchan'')');
if isempty(result), return; end;
options = { 'elec' eval( [ '[' result{1} ']' ] ) 'threshold' str2num(result{4}) };
if result{3},
options = { options{:} 'norm', 'on' };
else options = { options{:} 'norm', 'off' };
end;
if result{2} == 1
options = { options{:} 'measure', 'prob' };
elseif result{2} == 2
options = { options{:} 'measure', 'kurt' };
else
options = { options{:} 'measure', 'spec' };
options = { options{:} 'freqrange', str2double(result{5})}; % 7/16/2014 Ramon
end;
else
options = varargin;
end;
opt = finputcheck( options, { 'norm' 'string' { 'on';'off' } 'off';
'measure' 'string' { 'prob';'kurt';'spec' } 'kurt';
'precomp' 'real' [] [];
'freqrange' 'real' [] [1 EEG.srate/2];
'elec' 'integer' [] [1:EEG.nbchan];
'threshold' 'real' [] 400 }, 'pop_rejchan');
if isstr(opt), error(opt); end;
% compute the joint probability
% -----------------------------
if strcmpi(opt.norm, 'on')
normval = 2;
else
normval = 0;
end;
if strcmpi(opt.measure, 'prob')
fprintf('Computing probability for channels...\n');
[ measure indelec ] = jointprob( reshape(EEG.data(opt.elec,:,:), length(opt.elec), size(EEG.data,2)*size(EEG.data,3)), opt.threshold, opt.precomp, normval);
elseif strcmpi(opt.measure, 'kurt')
fprintf('Computing kurtosis for channels...\n');
[ measure indelec ] = rejkurt( reshape(EEG.data(opt.elec,:,:), length(opt.elec), size(EEG.data,2)*size(EEG.data,3)), opt.threshold, opt.precomp, normval);
else
fprintf('Computing spectrum for channels...\n');
[measure freq] = pop_spectopo(EEG, 1, [], 'EEG' , 'plot','off');
% select frequency range
if ~isempty(opt.freqrange)
[tmp fBeg] = min(abs(freq-opt.freqrange(1)));
[tmp fEnd] = min(abs(freq-opt.freqrange(2)));
measure = measure(:, fBeg:fEnd);
end;
% consider that data below 20 db has been filtered and remove it
indFiltered = find(mean(measure) < -20);
if ~isempty(indFiltered) && indFiltered(1) > 11, measure = measure(:,1:indFiltered(1)-10); disp('Removing spectrum data below -20dB (most likelly filtered out)'); end;
meanSpec = mean(measure);
stdSpec = std( measure);
% for indChan = 1:size(measure,1)
% if any(measure(indChan,:) > meanSpec+stdSpec*opt.threshold), indelec(indChan) = 1; end;
% end;
if strcmpi(opt.norm, 'on')
measure1 = max(bsxfun(@rdivide, bsxfun(@minus, measure, meanSpec), stdSpec),[],2);
if length(opt.threshold) > 1
measure2 = min(bsxfun(@rdivide, bsxfun(@minus, measure, meanSpec), stdSpec),[],2);
indelec = measure2 < opt.threshold(1) | measure1 > opt.threshold(end);
disp('Selecting minimum and maximum normalized power over the frequency range');
else
indelec = measure1 > opt.threshold(1);
disp('Selecting maximum normalized power over the frequency range');
end;
else
measure1 = max(measure,[],2);
if length(opt.threshold) > 1
measure2 = min(measure,[],2);
indelec = measure2 < opt.threshold(1) | measure1 > opt.threshold(end);
disp('Selecting minimum and maximum power over the frequency range');
else
indelec = measure > opt.threshold(1);
disp('Selecting maximum power over the frequency range');
end;
end;
measure = measure1;
end;
colors = cell(1,length(opt.elec)); colors(:) = { 'k' };
colors(find(indelec)) = { 'r' }; colors = colors(end:-1:1);
fprintf('%d electrodes labeled for rejection\n', length(find(indelec)));
% output variables
indelec = find(indelec)';
tmpchanlocs = EEG.chanlocs;
if ~isempty(EEG.chanlocs), tmplocs = EEG.chanlocs(opt.elec); tmpelec = { tmpchanlocs(opt.elec).labels }';
else tmplocs = []; tmpelec = mattocell([opt.elec]'); % tmpelec = mattocell([1:EEG.nbchan]');%Ramon on 8/7/2014
end;
if exist('measure2', 'var')
fprintf('#\tElec.\t[min]\t[max]\n');
tmpelec(:,3) = mattocell(measure2);
tmpelec(:,4) = mattocell(measure);
else fprintf('#\tElec.\tMeasure\n');
tmpelec(:,3) = mattocell(measure);
end;
tmpelec(:,2) = tmpelec(:,1);
tmpelec(:,1) = mattocell([1:length(measure)]');
for index = 1:size(tmpelec,1)
if exist('measure2', 'var')
fprintf('%d\t%s\t%3.2f\t%3.2f', tmpelec{index,1}, tmpelec{index,2}, tmpelec{index,3}, tmpelec{index,4});
elseif ~isempty(EEG.chanlocs)
fprintf('%d\t%s\t%3.2f' , tmpelec{index,1}, tmpelec{index,2}, tmpelec{index,3});
else % Ramon on 8/7/2014
fprintf('%d\t%d\t%3.2f' , tmpelec{index,1}, tmpelec{index,2}, tmpelec{index,3});
end;
if any(indelec == index), fprintf('\t*Bad*\n');
else fprintf('\n');
end;
end;
if isempty(indelec), return; end;
com = sprintf('EEG = pop_rejchan(EEG, %s);', vararg2str(options));
if nargin < 2
tmpcom = [ 'EEGTMP = pop_select(EEG, ''nochannel'', [' num2str(opt.elec(indelec)) ']);' ];
tmpcom = [ tmpcom ...
'LASTCOM = ' vararg2str(com) ';' ...
'[ALLEEG EEG CURRENTSET tmpcom] = pop_newset(ALLEEG, EEGTMP, CURRENTSET);' ...
' if ~isempty(tmpcom),' ...
' EEG = eegh(LASTCOM, EEG);' ...
' eegh(tmpcom);' ...
' eeglab(''redraw'');' ...
' end; clear EEGTMP tmpcom;' ];
eegplot(EEG.data(opt.elec,:,:), 'srate', EEG.srate, 'title', 'Scroll component activities -- eegplot()', ...
'limits', [EEG.xmin EEG.xmax]*1000, 'color', colors(end:-1:1), 'eloc_file', tmplocs, 'command', tmpcom);
else
EEG = pop_select(EEG, 'nochannel', opt.elec(indelec));
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_countepochs.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_countepochs.m
| 4,033 |
utf_8
|
a9c4c080c3befb23347f12d5c4360d4e
|
% eeg_countepochs() Count how many epochs there are of each type
%
% Usage:
% >> eeg_countepochs(EEG);
%
% Inputs:
% EEG - input dataset
% epochmarker - ['type'|'eventtype'] indicates which part of the
% EEG.epoch structure the different trial types are stored in. Depending
% on what system the data are from and how they were preprocessed, this
% may be either EEG.epoch.type or EEG.epoch.eventtype. Defaults to
% 'type'.
% Outputs:
% sweeps - Scalar structure showing, for each epoch type
% (sweeps.types) the number of sweeps in the dataset with that type
% (sweeps.counts)
%
% Example:
% eeg_countepochs( EEG, 'type' )
% eeg_countepochs( EEG, 'eventtype' )
%
% Author: Stephen Politzer-Ahles, University of Kansas, 2013
% 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 [sweeps] = eeg_countepochs(EEG, epochmarker);
if nargin < 1
help eeg_countepochs;
return;
end;
% Initialize an array which will keep counts
clearvars types counts
types{1} = '';
counts = [0];
% Iterate through all trials
for trial=1:length(EEG.epoch)
% Default 'epochmarker' to 'type' if no input was provided.
if nargin < 2
epochmarker = 'type';
end;
% Look for epochs that have >1 event and find which event is epoched around
eventindex = 1; % if only 1 event, eventindex=1
if length(EEG.epoch(trial).eventlatency) > 1
for eventnum = 1:length(EEG.epoch(trial).eventlatency)
if EEG.epoch(trial).eventlatency{eventnum}==0
eventindex = eventnum;
end % end if
end % end for
end % end if
% Get the trigger number for this trial
if strcmp(epochmarker,'eventtype')
% change event type from cell/number event to string
if iscell(EEG.epoch(trial).eventtype(eventindex))
type = EEG.epoch(trial).eventtype{eventindex};
elseif isnumeric(EEG.epoch(trial).eventtype(eventindex))
type = num2str( EEG.epoch(trial).eventtype(eventindex) );
else % is char
type = EEG.epoch(trial).eventtype;
end
elseif strcmp(epochmarker,'type')
% change cell/number event to string
if iscell(EEG.epoch(trial).type(eventindex))
type = EEG.epoch(trial).type{eventindex};
elseif isnumeric(EEG.epoch(trial).type(eventindex))
type = num2str( EEG.epoch(trial).type(eventindex) );
else % is char
type = EEG.epoch(trial).type;
end
end; % end if
% Find the row of the array that corresponds to this trigger (or if this trigger has not been counted yet)
index_of_type = find( cellfun(@(x) strcmp(x,type), types) );
% If this trial has a trigger that has already been counted before,
% 'row_of_type' will be a number. If not, it will be an empty
% array.
if index_of_type
% If we already have a count for this trigger, increment that count by 1
counts(index_of_type) = counts(index_of_type) + 1;
else
% If not, create a new count for this type
types = [types type];
counts(end+1) = 1;
end; % end if
end; % end for
% Remove the unnecessary first item
types = types(2:end);
counts = counts(2:end);
% Sorts
[Y,I] = sort( types );
% Add types and sweeps to a scalar structure
sweeps.types = types(I);
sweeps.counts = counts(I);
end
|
github
|
ZijingMao/baselineeegtest-master
|
pop_chanedit.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_chanedit.m
| 51,763 |
utf_8
|
9c5546ef49ec9730c495a9ae7d6c3596
|
% pop_chanedit() - Edit the channel locations structure of an EEGLAB dataset,
% EEG.chanlocs. For structure location and file formats,
% see >> help readlocs
%
% EEG.chanlocs. For structure location and file formats,
% see >> help readlocs
%
% Usage: >> EEG = pop_chanedit( EEG, 'key1', value1, 'key2', value2, ... );
% >> [ chanlocs options ] = pop_chanedit( chanlocs, 'key1', value1);
% >> [ chanlocs chaninfo options ] = pop_chanedit( chanlocs, chaninfo, ...
% 'key1', value1, 'key2', value2, ... );
%
% Graphic interface:
% "Channel information ('field name')" - [edit boxes] display channel field
% contents for the current channel. Command line equivalent
% to modify these fields: 'transform'
% "Opt. 3D center" - [button] optimally re-center 3-D channel coordinates. Uses
% chancenter(). Command line equivalent: 'convert', { 'chancenter'
% [xc yc zc] }, [xc yc zc] being the center of the sphere. Use []
% to find the center of the best fitting sphere.
% "Rotate axis" - [button] force one electrode to one position and rotate the other
% electrodes accordingly. Command line equivalent: 'forcelocs'.
% "Transform axis" - [button] perform any operation on channel fields. Command
% line equivalent: 'transform'.
% "Xyz->polar & sph." - [button] convert 3-D cartesian coordinates to polar and
% 3-D spherical coordinates. This is useful when you edit the
% coordinates manually. Command line equivalent: 'convert', 'cart2all'.
% "Sph.->polar & xyz" - [button] convert 3-D spherical coordinates to polar and
% 3-D cartesian coordinates. Command line equivalent: 'convert', 'sph2all'.
% "Polar->sph & xyz" - [button] convert 2-D polar coordinates to 3-D spherical and
% 3-D cartesian coordinates. Command line equivalent: 'convert', 'topo2all'.
% Note that if spherical radii are absent, they are forced to 1.
% "Set head radius" - [button] change head size radius. This is useful
% to make channels location compatible with a specified spherical model.
% Command line equivalent: 'headrad'.
% "Set channel types" - [button] set channel type names for a range of data channels.
% "Delete chan" - [button] delete channel. Command line equivalent: 'delete'.
% "Insert chan" - [button] insert channel before current channel.
% Command line equivalent: 'insert'.
% "<<" - [button] scroll channel backward by 10.
% "<" - [button] scroll channel backward by 1.
% ">" - [button] scroll channel forward by 1.
% ">>" - [button] scroll channel forward by 10.
% "Append chan" - [button] append channel after the current channel.
% Command line equivalent: 'append'.
% "Plot 2D" - [button] plot channel locations in 2-D using topoplot()
% "Plot radius [value (0.2-1.0), []=auto)" - [edit box] default plotting radius
% in 2-D polar views. This does NOT affect channel locations; it
% is only used for visualization. This parameter is attached to the
% chanlocs structure and is then used in all 2-D scalp topoplots.
% Default -> to data limits. Command line equivalent: 'plotrad'.
% "Nose along +X" - [list] Indicate the direction of the nose. This information
% is used in functions like topoplot(), headplot() and dipplot().
% Command line equivalent: 'nosedir'.
% "Plot 3D" - [button] plot channel positions in 3-D using plotchans3d()
% "Read locations" - [button] read location file using readlocs()
% Command line equivalent: 'load'.
% "Read help" - [button] display readlocs() function help.
% "Save .ced" - [button] save channel locations in native EEGLAB ".ced" format.
% Command line equivalent: 'save'.
% "Save others" - [button] save channel locations in other formats using
% pop_writelocs() (see readlocs() for available channel formats).
% "Cancel" - [button] cancel all editing.
% "Help" - [button] display this help message.
% "OK" - [button] save edits and propagate to parent.
%
% Inputs:
% EEG - EEG dataset
% chanlocs - EEG.chanlocs structure
%
% Optional inputs:
% 'convert' - {conversion_type [args]} Conversion type may be: 'cart2topo'
% 'sph2topo', 'topo2sph', 'sph2cart', 'cart2sph', or 'chancenter'.
% See help messages for these functions. Args are only relevant
% for 'chancenter'. More info is given in the graphic interface
% description above.
% 'transform' - String command for manipulating arrays. 'chan' is full channel
% info. Fields that can be manipulated are 'labels', 'theta'
% 'radius' (polar angle and radius), 'X', 'Y', 'Z' (cartesian
% 3-D) or 'sph_theta', 'sph_phi', 'sph_radius' for spherical
% horizontal angle, azimuth and radius.
% Ex: 'chans(3) = chans(14)', 'X = -X' or a multi-step transform
% with steps separated by ';': Ex. 'TMP = X; X = Y; Y = TMP'
% 'changechan' - {number value1 value2 value3 ...} Change the values of all fields
% for the given channel number, mimimally {num label theta radius}.
% Ex: 'changechan' {12 'PXz' -90 0.30}
% 'changefield' - {number field value} Change field value for channel number number.
% Ex: {34 'theta' 320.4}.
% 'insert' - {number label theta radius X Y Z sph_theta sph_phi sph_radius }
% Insert new channel and specified values before the current channel
% number. If the number of values is less than 10, remaining
% fields will be 0. (Previously, this parameter was termed 'add').
% 'append' - {num label theta radius X Y Z sph_theta sph_phi sph_radius }
% same as 'insert' (above) but insert the the new channel after
% the current channel number.
% 'delete' - [int_vector] Vector of channel numbers to delete.
% 'forcelocs' - [cell] call forcelocs() to force a particular channel to be at a
% particular location on the head sphere; rotate other channels
% accordingly.
% 'skirt' - Topographical polar skirt factor (see >> help topoplot)
% 'shrink' - Topographical polar shrink factor (see >> help topoplot)
% 'load' - [filename|{filename, 'key', 'val'}] Load channel location file
% optional arguments (such as file format) to the function
% readlocs() can be specified if the input is a cell array.
% 'save' - 'filename' Save text file with channel info.
% 'eval' - [string] evaluate string ('chantmp' is the name of the channel
% location structure).
% 'headrad' - [float] change head radius.
% 'lookup' - [string] look-up channel numbers for standard locations in the
% channel location file given as input.
%
% 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
% options - structure containing plotting options (equivalent to EEG.chaninfo)
%
% Ex: EEG = pop_chanedit(EEG,'load', { 'dummy.elp' 'elp' }, 'delete', [3 4], ...
% 'convert', { 'xyz->polar' [] -1 1 }, 'save', 'mychans.loc' )
% % Load polhemus file, delete two channels, convert to polar (see
% % cart2topo() for arguments) and save into 'mychans.loc'.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 20 April 2002
%
% See also: readlocs()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 15 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
% hidden parameter
% 'gui' - [figure value], allow to process the same dialog box several times
function [chansout, chaninfo, urchans, com] = pop_chanedit(chans, orichaninfo, varargin);
urchans = [];
com ='';
if nargin < 1
help pop_chanedit;
return;
end;
chansout = chans;
chaninfo = [];
fig = [];
if nargin < 2
orichaninfo = [];
end;
if isempty(chans) || ~sum(ishandle(chans))
% in case an EEG structure was given as input
% -------------------------------------------
if isfield(chans, 'chanlocs')
dataset_input = 1;
EEG = chans;
chans = EEG(1).chanlocs;
nchansori = EEG.nbchan;
if isfield(EEG, 'chaninfo')
chaninfo = EEG(1).chaninfo;
else chaninfo = [];
end;
if isfield(EEG, 'urchanlocs')
urchans = EEG(1).urchanlocs;
end;
else
nchansori = 0;
dataset_input = 0;
chaninfo = orichaninfo;
end;
% dealing with additional parameters
% ----------------------------------
if nargin > 1 && ~isstr(orichaninfo), % nothing
if nargin > 2
if ~isstr(varargin{1})
urchans = varargin{1};
varargin = varargin(2:end);
end;
end;
elseif nargin > 1 && ~isempty(orichaninfo) && isstr(orichaninfo)
varargin = { orichaninfo varargin{:} };
if isequal(orichaninfo, chaninfo)
chaninfo = [];
end;
orichaninfo = [];
end;
% insert "no data channels" in channel structure
% ----------------------------------------------
nbchan = length(chans);
[tmp chaninfo chans] = eeg_checkchanlocs(chans, chaninfo);
if isfield(chaninfo, 'shrink') && ~isempty(chaninfo.shrink)
icadefs;
if SHRINKWARNING
warndlg2( [ 'You are currently shrinking channel locations for display.' 10 ...
'A new option (more anatomically correct) is to plot channels' 10 ...
'outside head limits so the shrink option has been disabled.' 10 ...
'(Edit the icadefs file to disable this message)' ], 'Shrink factor warning');
end;
end;
oldchaninfo = chaninfo;
end;
if nargin < 3
totaluserdat = {};
% lookup channel locations if necessary
% -------------------------------------
if ~all(cellfun('isempty', {chans.labels})) && all(cellfun('isempty', {chans.theta}))
[chans chaninfo urchans com] = pop_chanedit(chans, chaninfo, 'lookupgui', []);
for index = 1:length(chans)
chans(index).ref = '';
chans(index).datachan = 1;
end;
if ~isempty(com)
totaluserdat = com;
%[chans chaninfo urchans com] = pop_chanedit(chans, chaninfo, com{:});
end;
end;
commentfields = { 'Channel label ("label")', ...
'Polar angle ("theta")', 'Polar radius ("radius")', ...
'Cartesian X ("X")', ...
'Cartesian Y ("Y")', ...
'Cartesian Z ("Z")', ...
'Spherical horiz. angle ("sph_theta")', ...
'Spherical azimuth angle ("sph_phi")', ...
'Spherical radius ("sph_radius")' ...
'Channel type' 'Reference' ...
'Index in backup ''urchanlocs'' structure' ...
'Channel in data array (set=yes)' };
% add field values
% ----------------
geometry = { 1 };
tmpstr = sprintf('Channel information ("field_name"):');
uilist = { { 'Style', 'text', 'string', tmpstr, 'fontweight', 'bold' } };
uiconvert = { ...
{ 'Style', 'pushbutton', 'string', 'Opt. head center', 'callback', 'pop_chanedit(gcbf, [], ''chancenter'', []);' } ...
{ 'Style', 'pushbutton', 'string', 'Rotate axis' , 'callback', 'pop_chanedit(gcbf, [], ''forcelocs'', []);' } ...
{ 'Style', 'pushbutton', 'string', 'Transform axes' , 'callback', 'pop_chanedit(gcbf, [], ''transform'', []);' } ...
{ }, ...
{ 'Style', 'pushbutton', 'string', 'xyz -> polar & sph.', 'callback', 'pop_chanedit(gcbf, [], ''convert'', {''cart2all''});' }, ...
{ 'Style', 'pushbutton', 'string', 'sph. -> polar & xyz', 'callback', 'pop_chanedit(gcbf, [], ''convert'', {''sph2all'' });' }, ...
{ 'Style', 'pushbutton', 'string', 'polar -> sph. & xyz', 'callback', 'pop_chanedit(gcbf, [], ''convert'', {''topo2all''});' }, ...
{ }, ...
{ 'Style', 'pushbutton', 'string', 'Set head radius', 'callback', 'pop_chanedit(gcbf, [], ''headrad'', []);' } ...
{ 'Style', 'pushbutton', 'string', 'Set channel types', 'callback', 'pop_chanedit(gcbf, [], ''settype'', []);' } ...
{ 'Style', 'pushbutton', 'string', 'Set reference', 'callback', 'pop_chanedit(gcbf, [], ''setref'' , []);' } ...
{ } { } };
% create text and edit for each field
% -----------------------------------
allfields = { 'labels' 'theta' 'radius' 'X' 'Y' 'Z' 'sph_theta' 'sph_phi' 'sph_radius' 'type' 'ref' 'urchan' 'datachan' };
for index = 1:length(allfields)-1
cbfield = [ 'valnumtmp = str2num(get(findobj(gcbf, ''tag'', ''chaneditnumval''), ''string''));' ...
'pop_chanedit(gcbf, [], ''changefield'', { valnumtmp ''' allfields{index} ''' get(gcbo, ''string'') });' ...
'clear valnumtmp;' ];
geometry = { geometry{:} [1.5 1 0.2 1] };
uilist = { uilist{:}, ...
{ 'Style', 'text', 'string', commentfields{index} }, ...
{ 'Style', 'edit', 'tag', [ 'chanedit' allfields{index} ], 'string', ...
num2str(getfield(chans,{1}, allfields{index})), 'horizontalalignment', 'center', 'callback', cbfield } ...
{ } uiconvert{index} };
end;
% special checkbox for chandata field
% -----------------------------------
geometry = { geometry{:} [2 0.35 0.5 1] };
cbfield = [ 'valnumtmp = str2num(get(findobj(gcbf, ''tag'', ''chaneditnumval''), ''string''));' ...
'pop_chanedit(gcbf, [], ''changefield'', { valnumtmp ''' allfields{end} ''' get(gcbo, ''value'') });' ...
'clear valnumtmp;' ];
uilist = { uilist{:}, ...
{ 'Style', 'text', 'string', commentfields{end} }, ...
{ 'Style', 'checkbox', 'tag', [ 'chanedit' allfields{end}], 'string', '' 'value', 1 'callback', cbfield } { } uiconvert{end} };
% add buttons
% -----------
geometry = { geometry{:} [1] [1.15 0.5 0.6 1.9 0.4 0.4 1.15] [1.15 0.7 0.7 1 0.7 0.7 1.15] };
cb_del = [ 'valnum = str2num(char(get(findobj(gcbf,''tag'', ''chaneditnumval''), ''string'')));' ...
'pop_chanedit(gcbf, [], ''deletegui'', valnum);' ];
cb_insert = [ 'valnum = str2num(char(get(findobj(gcbf,''tag'', ''chaneditnumval''), ''string'')));' ...
'pop_chanedit(gcbf, [], ''insert'', valnum);' ];
cb_append = [ 'valnum = str2num(char(get(findobj(gcbf,''tag'', ''chaneditnumval''), ''string'')));' ...
'pop_chanedit(gcbf, [], ''append'', valnum);' ];
uilist = { uilist{:}, ...
{ }, ...
{ 'Style', 'pushbutton', 'string', 'Delete chan', 'callback', cb_del }, ...
{ },{ }, ...
{ 'Style', 'text' , 'string', ['Channel number (of ' int2str(length(chans)) ')'], ...
'fontweight', 'bold', 'tag', 'chaneditscantitle' }, { },{ },{ }, ...
{ 'Style', 'pushbutton', 'string', 'Insert chan', 'callback', cb_insert } ...
{ 'Style', 'pushbutton', 'string', '<<', 'callback', [ 'pop_chanedit(gcbf, [], ''movecursor'', -10);' ] } ...
{ 'Style', 'pushbutton', 'string', '<', 'callback', [ 'pop_chanedit(gcbf, [], ''movecursor'', -1);' ] } ...
{ 'Style', 'edit' , 'string', '1', 'tag', 'chaneditnumval', 'callback', [ 'pop_chanedit(gcbf, []);' ] } ...
{ 'Style', 'pushbutton', 'string', '>', 'callback', [ 'pop_chanedit(gcbf, [], ''movecursor'', 1);' ] } ...
{ 'Style', 'pushbutton', 'string', '>>', 'callback', [ 'pop_chanedit(gcbf, [], ''movecursor'', 10);' ] } ...
{ 'Style', 'pushbutton', 'string', 'Append chan', 'callback', cb_append }, ...
};
% add sorting options
% -------------------
noseparam = strmatch(upper(chaninfo.nosedir), { '+X' '-X' '+Y' '-Y' });
if isempty(noseparam), error('Wrong value for nose direction'); end;
geometry = { geometry{:} [1] [0.9 1.3 0.6 1.1 0.9] [1] [1 1 1 1 1]};
uilist = { uilist{:},...
{ } ...
{ 'Style', 'pushbutton', 'string', 'Plot 2-D', 'callback', 'pop_chanedit(gcbf, [], ''plot2d'', []);' },...
{ 'Style', 'text', 'string', 'Plot radius (0.2-1, []=auto)'} ...
{ 'Style', 'edit', 'string', chaninfo.plotrad, 'tag', 'plotrad' 'callback' 'pop_chanedit(gcbf, [], ''plotrad'', []);' } ...
{ 'Style', 'popupmenu', 'string', 'Nose along +X|Nose along -X|Nose along +Y|Nose along -Y', ...
'tag' 'nosedir' 'value',noseparam, 'callback' 'pop_chanedit(gcbf,[],''nosedir'',[]);' 'listboxtop' noseparam } ...
{ 'Style', 'pushbutton', 'string', 'Plot 3-D (xyz)', 'callback', 'pop_chanedit(gcbf, [], ''plot3d'', []);' } ...
{}, ...
{ 'Style', 'pushbutton', 'string', 'Read locations', 'callback', 'pop_chanedit(gcbf,[],''load'',[]);' }, ...
{ 'Style', 'pushbutton', 'string', 'Read locs help', 'callback', 'pophelp(''readlocs.m'');' }, ...
{ 'Style', 'pushbutton', 'string', 'Look up locs', 'callback', 'pop_chanedit(gcbf,[], ''lookupgui'', []);' }, ...
{ 'Style', 'pushbutton', 'string', 'Save (as .ced)', 'callback', 'pop_chanedit(gcbf,[], ''save'',[]);' } ...
{ 'Style', 'pushbutton', 'string', 'Save (other types)' 'callback', 'pop_chanedit(gcbf,[], ''saveothers'',[]);' } ...
};
% evaluation of command below is required to center text (if
% declared a text instead of edit, the uicontrol is not centered)
comeval = [ 'set(findobj( ''tag'', ''chanediturchan''), ''style'', ''text'', ''backgroundcolor'', [.66 .76 1] );' ...
'set(findobj( ''tag'', ''chaneditref''), ''style'', ''text'', ''backgroundcolor'', [.66 .76 1] );' ...
'set(findobj( ''tag'', ''ok''), ''callback'', ''pop_chanedit(gcbf, [], ''''return'''', []);'')' ];
userdata.chans = chans;
userdata.nchansori = nchansori;
userdata.chaninfo = chaninfo;
userdata.commands = totaluserdat;
[results userdata returnmode] = inputgui( 'geometry', geometry, 'uilist', uilist, 'helpcom', ...
'pophelp(''pop_chanedit'');', 'title', 'Edit channel info -- pop_chanedit()', ...
'userdata', userdata, 'eval' , comeval );
if length(results) == 0,
com = '';
if dataset_input, chansout = EEG; end;
return;
end;
% transfer events back from global workspace
chans = userdata.chans;
chaninfo = userdata.chaninfo;
if ~isempty(userdata.commands)
com = sprintf('%s=pop_chanedit(%s, %s);', inputname(1), inputname(1), vararg2str(userdata.commands));
end;
else
% call from command line or from a figure
% ---------------------------------------
currentpos = 0;
if ishandle(chans)
fig = chans;
userdata = get(fig, 'userdata');
chans = userdata.chans;
nchansori = userdata.nchansori;
chaninfo = userdata.chaninfo;
currentpos = str2num(get(findobj(fig, 'tag', 'chaneditnumval'), 'string'));
end;
args = varargin;
% no interactive inputs
% scan all the fields of g
% ------------------------
for curfield = 1:2:length(args)
switch lower(args{curfield})
case 'return'
[tmpchans] = eeg_checkchanlocs(chans);
if nchansori ~= 0 & nchansori ~= length(tmpchans)
if ~popask(strvcat(['The number of data channels (' int2str(length(tmpchans)) ') not including fiducials does not'], ...
['correspond to the initial number of channels (' int2str(nchansori) '), so for consistency purposes'], ...
'new channel information will be ignored if this function was called from EEGLAB', ...
'If you have added a reference channel manually, check the "Data channel" checkbox is off'))
else
set(findobj(fig, 'tag', 'ok'), 'userdata', 'stop');
end;
else
set(findobj(fig, 'tag', 'ok'), 'userdata', 'stop');
end;
args = {};
case 'plot3d', % GUI only
tmpind = find(~cellfun('isempty', { chans.X }));
if ~isempty(tmpind),
plotchans3d([ [ chans(tmpind).X ]' [ chans(tmpind).Y ]' [ chans(tmpind).Z ]'], { chans(tmpind).labels });
else disp('cannot plot: no XYZ coordinates');
end;
args = {};
case 'plot2d', % GUI only
plotrad = str2num(get(findobj(fig, 'tag', 'plotrad'), 'string'));
figure; topoplot([],chans, 'style', 'blank', 'drawaxis', 'on', 'electrodes', ...
'labelpoint', 'plotrad', plotrad, 'chaninfo', chaninfo);
args = {};
case 'movecursor', % GUI only
currentpos = max(1,min(currentpos+args{curfield+1},length(chans)));
args = {};
case 'plotrad',
if isempty( args{curfield+1} )
args{curfield+1} = str2num(get(findobj(fig, 'tag', 'plotrad'), 'string'));
end;
chaninfo.plotrad = args{curfield+1};
case 'forcelocs',
if ~isempty(fig) % GUI BASED
[ comtmp tmpforce ] = forcelocs(chans);
if ~isempty(tmpforce),
args{curfield+1} = tmpforce{1};
end;
end;
if ~isempty(args{curfield+1})
chans = forcelocs(chans,args{curfield+1});
disp('Convert XYZ coordinates to spherical and polar');
end;
case 'chancenter',
if ~isempty(fig)
[chans newcenter tmpcom] = pop_chancenter(chans);
args{curfield } = 'eval';
args{curfield+1} = tmpcom;
end;
case 'convert',
if iscell(args{curfield+1})
method=args{curfield+1}{1};
extraargs = args{curfield+1}(2:end);
else
method=args{curfield+1};
extraargs = {''};
end;
if ~isempty(fig) & ~strcmp(method, 'chancenter')
tmpButtonName=questdlg2( strvcat('This will modify fields in the channel structure', ...
'Are you sure you want to apply this function ?'), 'Confirmation', 'Cancel', 'Yes','Yes');
if ~strcmpi(tmpButtonName, 'Yes'), return; end;
end;
switch method
case 'chancenter',
if isempty(extraargs)
[X Y Z]=chancenter( [chans.X ]', [ chans.Y ]', [ chans.Z ]',[]);
else
[X Y Z]=chancenter( [chans.X ]', [ chans.Y ]', [ chans.Z ]', extraargs{:});
end;
if isempty(X), return; end;
for index = 1:length(chans)
chans(index).X = X(index);
chans(index).Y = Y(index);
chans(index).Z = Z(index);
end;
disp('Note: automatically convert XYZ coordinates to spherical and polar');
chans = convertlocs(chans, 'cart2all');
otherwise
chans = convertlocs(chans, method, 'verbose', 'on');
end;
case 'settype'
if ~isempty(fig)
args{curfield+1} = inputdlg2({'Channel indices' 'Type (e.g. EEG)' }, ...
'Set channel type', 1, { '' '' }, 'pop_chanedit');
end;
try, tmpchans = args{curfield+1}{1}; tmptype = args{curfield+1}{2};catch, return; end;
if isempty(tmpchans) & isempty(tmptype), return; end;
if isstr(tmpchans)
tmpchans = eval( [ '[' tmpchans ']' ], 'settype: error in channel indices');
end;
if ~isstr(tmptype), tmptype = num2str(tmptype); end;
for index = 1:length(tmpchans)
if tmpchans(index) > 0 & tmpchans(index) <= length(chans)
chans( tmpchans(index) ).type = tmptype;
end;
end;
case 'setref'
if ~isempty(fig)
disp('Note that setting the reference only changes the reference labels');
disp('Use the re-referencing menu to change the reference');
args{curfield+1} = inputdlg2({'Channel indices' 'Reference (e.g. Cz)' }, ...
'Set channel reference', 1, { '' '' }, 'pop_chanedit');
end;
try, tmpchans = args{curfield+1}{1}; tmpref = args{curfield+1}{2};catch, return; end;
if isempty(tmpchans) & isempty(tmpref), return; end;
if isstr(tmpchans)
tmpchans = eval( [ '[' tmpchans ']' ], 'settype: error in channel indices');
end;
if ~isstr(tmpref), tmpref = num2str(tmpref); end;
for index = 1:length(tmpchans)
if tmpchans(index) > 0 & tmpchans(index) <= length(chans)
chans( tmpchans(index) ).ref = tmpref;
end;
end;
case 'transform'
if ~isempty(fig)
args{curfield+1} = inputdlg2({'Enter transform: (Ex: TMP=X; X=-Y; Y=TMP or Y(3) = X(2), etc.' }, ...
'Transform', 1, { '' }, 'pop_chanedit');
end;
try, tmpoper = args{curfield+1}; catch, return; end;
if isempty(deblank(tmpoper)), return; end;
if iscell(tmpoper), tmpoper = tmpoper{1}; end;
tmpoper = [ tmpoper ';' ];
[eloc, labels, theta, radius, indices] = readlocs(chans);
if isempty(findstr(tmpoper, 'chans'))
try,
X = [ chans(indices).X ];
Y = [ chans(indices).Y ];
Z = [ chans(indices).Z ];
sph_theta = [ chans(indices).sph_theta ];
sph_phi = [ chans(indices).sph_phi ];
sph_radius = [ chans(indices).sph_radius ];
eval(tmpoper);
for ind = 1:length(indices)
chans(indices(ind)).X = X(min(length(X),ind));
chans(indices(ind)).Y = Y(min(length(Y),ind));
chans(indices(ind)).Z = Z(min(length(Z),ind));
chans(indices(ind)).theta = theta(min(length(theta),ind));
chans(indices(ind)).radius = radius(min(length(radius),ind));
chans(indices(ind)).sph_theta = sph_theta(min(length(sph_theta),ind));
chans(indices(ind)).sph_phi = sph_phi(min(length(sph_phi),ind));
chans(indices(ind)).sph_radius = sph_radius(min(length(sph_radius),ind));
end;
if ~isempty(findstr(tmpoper, 'X')), chans = convertlocs(chans, 'cart2all'); end;
if ~isempty(findstr(tmpoper, 'Y')), chans = convertlocs(chans, 'cart2all'); end;
if ~isempty(findstr(tmpoper, 'Z')), chans = convertlocs(chans, 'cart2all'); end;
if ~isempty(findstr(tmpoper, 'sph_theta')), chans = convertlocs(chans, 'sph2all');
elseif ~isempty(findstr(tmpoper, 'theta')), chans = convertlocs(chans, 'topo2all'); end;
if ~isempty(findstr(tmpoper, 'sph_phi')), chans = convertlocs(chans, 'sph2all'); end;
if ~isempty(findstr(tmpoper, 'sph_radius')), chans = convertlocs(chans, 'sph2all');
elseif ~isempty(findstr(tmpoper, 'radius')), chans = convertlocs(chans, 'topo2all'); end;
catch, disp('Unknown error when applying transform'); end;
else
eval(tmpoper);
end;
case 'headrad'
if ~isempty(fig) % GUI
tmpres = inputdlg2({'Enter new head radius (same unit as DIPFIT head model):' }, ...
'Head radius', 1, { '' }, 'pop_chanedit');
if ~isempty(tmpres),
args{ curfield+1 } = str2num(tmpres{1});
else return;
end;
end;
if ~isempty( args{ curfield+1 } )
allrad = [ chans.sph_radius ];
if length(unique(allrad)) == 1 % already spherical
chans = pop_chanedit(chans, 'transform', [ 'sph_radius = ' num2str( args{ curfield+1 } ) ';' ]);
else % non-spherical, finding best match
factor = args{ curfield+1 } / mean(allrad);
chans = pop_chanedit(chans, 'transform', [ 'sph_radius = sph_radius*' num2str( factor ) ';' ]);
disp('Warning: electrodes do not lie on a sphere. Sphere model fitting for');
disp(' dipole localization will work but generate many warnings');
end;
chans = convertlocs(chans, 'sph2all');
end;
case 'shrink'
chans(1).shrink = args{ curfield+1 };
case 'plotrad'
chans(1).plotrad = args{ curfield+1 };
case 'deletegui'
chans(args{ curfield+1 })=[];
currentpos = min(length(chans), currentpos);
args{ curfield } = 'delete';
case 'delete'
chans(args{ curfield+1 })=[];
case 'changefield'
tmpargs = args{ curfield+1 };
if length( tmpargs ) < 3
error('pop_chanedit: not enough arguments to change field value');
end;
if ~isempty(strmatch( tmpargs{2}, { 'X' 'Y' 'Z' 'theta' 'radius' 'sph_theta' 'sph_phi' 'sph_radius'}))
if ~isnumeric(tmpargs{3}), tmpargs{3} = str2num(tmpargs{3}); end;
end;
eval([ 'chans(' int2str(tmpargs{1}) ').' tmpargs{2} '=' reformat(tmpargs{3} ) ';' ]);
case { 'insert' 'add' 'append' }
tmpargs = args{ curfield+1 };
allfields = fieldnames(chans);
if isnumeric(tmpargs)
tmpargs2 = cell(1, length(allfields)+1);
tmpargs2{1} = tmpargs;
tmpargs = tmpargs2;
if strcmpi(allfields{end}, 'datachan'), tmpargs{end} = 0; end;
end;
if length( tmpargs ) < length(allfields)+1
error('pop_chanedit: not enough arguments to change all field values');
end;
num = tmpargs{1};
if strcmpi(lower(args{curfield}), 'append'), num=num+1; currentpos = currentpos+1; end;
chans(end+1) = chans(end);
chans(num+1:end) = chans(num:end-1);
for index = 1:length( allfields )
chans = setfield(chans, {num}, allfields{index}, tmpargs{index+1});
end;
if isfield(chans, 'datachan')
if isempty(chans(num).datachan)
chans(num).datachan = 0;
end;
end;
case 'changechan'
tmpargs = args{ curfield+1 };
num = tmpargs{1};
allfields = fieldnames(chans);
if length( tmpargs ) < length(allfields)+1
error('pop_chanedit: not enough arguments to change all field values');
end;
for index = 1:length( allfields )
eval([ 'chans(' int2str(num) ').' allfields{index} '=' reformat(tmpargs{index+1}) ';' ]);
end;
case 'load'
if ~isempty(fig) % GUI
[tmpf tmpp] = uigetfile('*.*', 'Load a channel location file');
drawnow;
if ~isequal(tmpf, 0),
tmpformats = readlocs('getinfos');
tmpformattype = { 'autodetect' tmpformats(1:end-1).type };
tmpformatstr = { 'autodetect' tmpformats(1:end-1).typestring };
tmpformatdesc = { 'Autodetect file format from file extension' tmpformats(1:end-1).description };
%cb_listbox = 'tmpdesc=get(gcbf, ''userdata''); set(findobj(gcbf, ''tag'', ''strdesc''), ''string'', strmultiline([ ''File format: '' tmpdesc{get(gcbo, ''value'')} ], 30, 10)); clear tmpdesc;'' } }, ''pophelp(''''readlocs'''')'',' ...
% 'Read electrode file'', tmpformatdesc, ''normal'', 4);
%txtgui = [ strmultiline([ 'File format: Autodetect file format from file extension'], 20, 10) 10 10 ];
%tmpfmt = inputgui( 'geometry', {[1 1]}, ...
% 'uilist' , { { 'style', 'text', 'string', txtgui 'tag' 'strdesc' }, ...
% { 'style', 'listbox', 'string', strvcat(tmpformatstr) 'callback' '' } }, ...
% 'geomvert', [10], ...
% 'helpcom' , 'pophelp(''readlocs'');');
tmpfmt = inputgui( 'geometry', {[1 1 1] [1]}, ...
'uilist' , { { 'style', 'text', 'string', 'File format:' 'tag' 'strdesc' } {} {}, ...
{ 'style', 'listbox', 'string', strvcat(tmpformatstr) 'callback' '' } }, ...
'geomvert', [1 8], ...
'helpcom' , 'pophelp(''readlocs'');');
if isempty(tmpfmt),
args{ curfield+1 } = [];
else args{ curfield+1 } = { fullfile(tmpp, tmpf) 'filetype' tmpformattype{tmpfmt{1}} };
end;
else args{ curfield+1 } = [];
end;
end;
tmpargs = args{ curfield+1 };
if ~isempty(tmpargs),
if isstr(tmpargs)
[chans] = readlocs(tmpargs);
[tmp tmp2 chans] = eeg_checkchanlocs(chans);
chaninfo = [];
chaninfo.filename = tmpargs;
else
[chans] = readlocs(tmpargs{:});
[tmp tmp2 chans] = eeg_checkchanlocs(chans);
chaninfo = [];
chaninfo.filename = tmpargs{1};
end;
% backup file content etc...
% --------------------------
tmptext = loadtxt( chaninfo.filename, 'delim', [], 'verbose', 'off', 'convert', 'off');
chaninfo.filecontent = strvcat(tmptext{:});
% set urchan structure
% --------------------
urchans = chans;
for index = 1:length(chans)
chans(index).urchan = index;
end;
end;
if ~isfield(chans, 'datachan')
chans(1).datachan = [];
end;
for index = 1:length(chans)
if isempty(chans(index).datachan)
chans(index).datachan = 1;
end;
end;
case 'eval'
tmpargs = args{ curfield+1 };
eval(tmpargs);
case 'saveothers'
com = pop_writelocs(chans);
args{ curfield } = 'eval';
args{ curfield+1 } = com;
case 'save'
if ~isempty(fig)
[tmpf tmpp] = uiputfile('*.ced', 'Save channel locs in EEGLAB .ced format');
drawnow;
args{ curfield+1 } = fullfile(tmpp, tmpf);
end;
tmpargs = args{ curfield+1 };
if isempty(tmpargs), return; end;
fid = fopen(tmpargs, 'w');
if fid ==-1, error('Cannot open file'); end;
allfields = fieldnames(chans);
fields = { 'labels' 'theta' 'radius' 'X' 'Y' 'Z' 'sph_theta' 'sph_phi' 'sph_radius' 'type' };
tmpdiff = setdiff(fields, allfields);
if ~isempty(tmpdiff), error(sprintf('Field "%s" missing in channel location structure', tmpdiff{1})); end;
fprintf(fid, 'Number\t');
for field = 1:length(fields)
fprintf(fid, '%s\t', fields{field});
end;
fprintf(fid, '\n');
for index=1:length(chans)
fprintf(fid, '%d\t', index);
for field = 1:length(fields)
tmpval = getfield(chans, {index}, fields{field});
if isstr(tmpval)
fprintf(fid, '%s\t', tmpval);
else
fprintf(fid, '%3.3g\t', tmpval);
end;
end;
fprintf(fid, '\n');
end;
if isempty(tmpargs), chantmp = readlocs(tmpargs); end;
case 'nosedir'
nosevals = { '+X' '-X' '+Y' '-Y' };
if ~isempty(fig)
tmpval = get(findobj(gcbf, 'tag', 'nosedir'), 'value');
args{ curfield+1 } = nosevals{tmpval};
warndlg2( [ 'Changing the nose direction will force EEGLAB to physically rotate ' 10 ...
'electrodes, so next time you call this interface, nose direction will' 10 ...
'be +X. If your electrodes are currently aligned with a specific' 10 ...
'head model, you will have to rotate them in the model coregistration' 10 ...
'interface to realign them with the model.'], 'My Warn Dialog');
end;
chaninfo.nosedir = args{ curfield+1 };
if isempty(strmatch(chaninfo.nosedir, nosevals))
error('Wrong value for nose direction');
end;
case { 'lookup' 'lookupgui' }
if strcmpi(lower(args{curfield}), 'lookupgui')
standardchans = { 'Fp1' 'Fpz' 'Fp2' 'Nz' 'AF9' 'AF7' 'AF3' 'AFz' 'AF4' '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' 'PO3' 'POz' 'PO4' 'PO8' 'PO10' ...
'O1' 'Oz' 'O2' 'O9' 'O10' 'CB1' 'CB2' 'Iz' };
for indexchan = 1:length(chans)
if isempty(chans(indexchan).labels), chans(indexchan).labels = ''; end;
end;
[tmp1 ind1 ind2] = intersect_bc( lower(standardchans), {chans.labels});
if ~isempty(tmp1) | isfield(chans, 'theta')
% finding template location files
% -------------------------------
setmodel = [ 'tmpdat = get(gcbf, ''userdata'');' ...
'tmpval = get(gcbo, ''value'');' ...
'set(findobj(gcbf, ''tag'', ''elec''), ''string'', tmpdat{tmpval});' ...
'clear tmpval tmpdat;' ];
try
EEG = eeg_emptyset; % for dipfitdefs
dipfitdefs;
tmpp = which('eeglab.m');
tmpp = fullfile(fileparts(tmpp), 'functions', 'resources', 'Standard-10-5-Cap385_witheog.elp');
userdatatmp = { template_models(1).chanfile template_models(2).chanfile tmpp };
clear EEG;
catch, userdatatmp = { 'Standard-10-5-Cap385.sfp' 'Standard-10-5-Cap385.sfp' 'Standard-10-5-Cap385_witheog.elp' };
end;
% other commands for help/load
% ----------------------------
comhelp = [ 'warndlg2(strvcat(''The template file depends on the model'',' ...
'''you intend to use for dipole fitting. The default file is fine for'',' ...
'''spherical model.'');' ];
commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ...
'if filename ~=0,' ...
' set(findobj(''parent'', gcbf, ''tag'', ''elec''), ''string'', [ filepath filename ]);' ...
'end;' ...
'clear filename filepath tagtest;' ];
if ~isfield(chans, 'theta'), message =1;
elseif all(cellfun('isempty', {chans.theta })), message =1;
else message =2;
end;
if message == 1
textcomment = strvcat('Only channel labels are present currently, but some of these labels have known', ...
'positions. Do you want to look up coordinates for these channels using the electrode', ...
'file below? If you have a channel location file for this dataset, press cancel, then', ...
'use button "Read location" in the following gui. If you do not know, just press OK.');
else
textcomment = strvcat('Some channel labels may have known locations.', ...
'Do you want to look up coordinates for these channels using the electrode', ...
'file below? If you do not know, press OK.');
end;
uilist = { { 'style' 'text' 'string' textcomment } ...
{ 'style' 'popupmenu' 'string' [ 'use BESA file for 4-shell dipfit spherical model' ...
'|use MNI coordinate file for BEM dipfit model|Use spherical file with eye channels' ] ...
'callback' setmodel } ...
{ } ...
{ 'style' 'edit' 'string' userdatatmp{1} 'tag' 'elec' } ...
{ 'style' 'pushbutton' 'string' '...' 'callback' commandload } };
res = inputgui( { 1 [1 0.3] [1 0.3] }, uilist, 'pophelp(''pop_chanedit'')', 'Look up channel locations?', userdatatmp, 'normal', [4 1 1] );
if ~isempty(res)
chaninfo.filename = res{2};
args{ curfield } = 'lookup';
args{ curfield+1 } = res{2};
com = args;
else
return;
end;
end;
else
chaninfo.filename = args{ curfield+1 };
end;
if strcmpi(chaninfo.filename, 'standard-10-5-cap385.elp')
dipfitdefs;
chaninfo.filename = template_models(1).chanfile;
elseif strcmpi(chaninfo.filename, 'standard_1005.elc')
dipfitdefs;
chaninfo.filename = template_models(2).chanfile;
end;
tmplocs = readlocs( chaninfo.filename, 'defaultelp', 'BESA' );
for indexchan = 1:length(chans)
if isempty(chans(indexchan).labels), chans(indexchan).labels = ''; end;
end;
[tmp ind1 ind2] = intersect_bc(lower({ tmplocs.labels }), lower({ chans.labels }));
if ~isempty(tmp)
chans = struct('labels', { chans.labels }, 'datachan', { chans.datachan }, 'type', { chans.type });
[ind2 ind3] = sort(ind2);
ind1 = ind1(ind3);
for index = 1:length(ind2)
chans(ind2(index)).theta = tmplocs(ind1(index)).theta;
chans(ind2(index)).radius = tmplocs(ind1(index)).radius;
chans(ind2(index)).X = tmplocs(ind1(index)).X;
chans(ind2(index)).Y = tmplocs(ind1(index)).Y;
chans(ind2(index)).Z = tmplocs(ind1(index)).Z;
chans(ind2(index)).sph_theta = tmplocs(ind1(index)).sph_theta;
chans(ind2(index)).sph_phi = tmplocs(ind1(index)).sph_phi;
chans(ind2(index)).sph_radius = tmplocs(ind1(index)).sph_radius;
end;
tmpdiff = setdiff_bc([1:length(chans)], ind2);
if ~isempty(tmpdiff)
fprintf('Channel lookup: no location for ');
for index = 1:(length(tmpdiff)-1)
fprintf('%s,', chans(tmpdiff(index)).labels);
end;
fprintf('%s\nSend us standard location for your channels at [email protected]\n', ...
chans(tmpdiff(end)).labels);
end;
if ~isfield(chans, 'type'), chans(1).type = []; end;
end;
if ~isempty(findstr(args{ curfield+1 }, 'standard_10')) & ...
~isempty(findstr(args{ curfield+1 }, '.elc'))
chaninfo.nosedir = '+Y';
else
chaninfo.nosedir = '+X';
end;
urchans = chans;
for index = 1:length(chans)
chans(index).urchan = index;
chans(index).ref = '';
end;
end;
end;
end;
% call from a figure
% ------------------
if ~isempty(fig)
userdata.chans = chans;
userdata.chaninfo = chaninfo;
userdata.commands = { userdata.commands{:} args{:} };
set(fig, 'userdata', userdata);
set(findobj(fig, 'tag', 'chaneditnumval'), 'string', num2str(currentpos));
set(findobj(fig, 'tag', 'chaneditscantitle'), 'string', ['Channel number (of ' int2str(length(chans)) ')']);
% update GUI with current channel info
allfields = fieldnames(chans);
if ~isempty(chans)
for index = 1:length(allfields)
obj = findobj(fig, 'tag', [ 'chanedit' allfields{index}]);
if strcmpi(allfields{index}, 'datachan')
set(obj, 'value', getfield(chans(currentpos), allfields{index}));
else
tmpval = getfield(chans(currentpos), allfields{index});
if isstr(tmpval) && strcmpi(tmpval, '[]'), tmpval = ''; end;
set(obj, 'string', num2str(tmpval));
end;
end;
else
for index = 1:length(allfields)
obj = findobj(fig, 'tag', [ 'chanedit' allfields{index}]);
if strcmpi(allfields{index}, 'datachan')
set(obj, 'value', 0);
else
set(obj, 'string', '');
end;
end;
end;
else
[chans chaninfo] = eeg_checkchanlocs(chans, chaninfo);
if dataset_input,
if nchansori == length(chans)
for index = 1:length(EEG)
EEG(index).chanlocs = chans;
EEG(index).chaninfo = chaninfo;
end;
EEG = eeg_checkset(EEG); % for channel orientation
else
disp('Wrong channel structure size, changes ignored');
end;
chansout = EEG;
else chansout = chans;
end;
end;
return;
% format the output field
% -----------------------
function strval = reformat( val )
if isnumeric(val) & isempty(val), val = '[]'; end;
if isstr(val), strval = [ '''' val '''' ];
else strval = num2str(val);
end;
% extract text using tokens (not used)
% ------------------------------------
function txt = inserttxt( txt, tokins, tokfind);
locfind = findstr(txt, tokfind);
for index = length(locfind):-1:1
txt = [txt(1:locfind(index)-1) tokins txt(locfind(index):end)];
end;
% ask for confirmation
% --------------------
function num = popask( text )
ButtonName=questdlg2( text, ...
'Confirmation', 'Cancel', 'Yes','Yes');
switch lower(ButtonName),
case 'cancel', num = 0;
case 'yes', num = 1;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_newcrossf.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_newcrossf.m
| 9,208 |
utf_8
|
e9ec5bedf577d64df52c8c9838dae4e9
|
% pop_newcrossf() - Return estimates and plots of event-related spectral coherence
%
% Usage:
% >> pop_newcrossf(EEG, typeproc, num1, num2, tlimits,cycles,
% 'key1',value1,'key2',value2, ... );
% Inputs:
% INEEG - Input EEG dataset
% typeproc - Type of processing:
% 1 = process two raw-data channels,
% 0 = process two ICA components
% num1 - First component or channel number
% num2 - Second component or channel number
% tlimits - [mintime maxtime] Sub-epoch time limits in ms
% cycles - >0 -> Number of cycles in each analysis wavelet
% 0 -> Use FFTs (with constant window length)
%
% Optional inputs: As for newcrossf(). See >> help newcrossf
%
% Outputs: Same as newcrossf(). No outputs are returned when a
% window pops-up to ask for additional arguments
%
% Author: Arnaud Delorme, CNL / Salk Institute, 11 March 2002
%
% See also: timef(), eeglab()
% Copyright (C) 11 March 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
% 03-18-02 added title -ad & sm
% 04-04-02 added outputs -ad & sm
function varargout = pop_newcrossf(EEG, typeproc, num1, num2, tlimits, cycles, varargin );
varargout{1} = '';
% display help if not enough arguments
% ------------------------------------
if nargin < 2
help pop_newcrossf;
return;
end;
lastcom = [];
if nargin < 3
popup = 1;
else
popup = isstr(num1) | isempty(num1);
if isstr(num1)
lastcom = num1;
end;
end;
% pop up window
% -------------
if popup
[txt vars] = gethelpvar('timef.m');
geometry = { [1 0.5 0.5] [1 0.5 0.5] [1 0.5 0.5] [1 0.5 0.5] [0.92 0.15 0.73] [0.92 0.15 0.73] [1 0.5 0.5] [1 0.8 0.2] [1] [1 1]};
uilist = { { 'Style', 'text', 'string', fastif(typeproc, 'First channel number', 'First component number'), 'fontweight', 'bold' } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,3,[],'1') } {} ...
{ 'Style', 'text', 'string', fastif(typeproc, 'Second channel number', 'Second component number'), 'fontweight', 'bold' } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,4,[],'2') } {} ...
{ 'Style', 'text', 'string', 'Epoch time range [min max] (msec)', 'fontweight', 'bold', ...
'tooltipstring', 'Sub epoch time limits' } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,5,[],[ int2str(EEG.xmin*1000) ' ' int2str(EEG.xmax*1000) ]) } {} ...
{ 'Style', 'text', 'string', 'Wavelet cycles (0->FFT, see >> help timef)', 'fontweight', 'bold', ...
'tooltipstring', context('cycles',vars,txt) } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,6,[],'3 0.5') } {} ...
{ 'Style', 'text', 'string', '[set]->log. scale for frequencies (match STUDY)', 'fontweight', 'bold' } ...
{ 'Style', 'checkbox', 'value', getkeyval(lastcom,'logscale',1,0) } { } ...
{ 'Style', 'text', 'string', '[set]->Linear coher / [unset]->Phase coher', 'fontweight', 'bold', ...
'tooltipstring', ['Compute linear inter-trial coherence (coher)' 10 ...
'OR Amplitude-normalized inter-trial phase coherence (phasecoher)'] } ...
{ 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'phasecoher','present',1) } { } ...
{ 'Style', 'text', 'string', 'Bootstrap significance level (Ex: 0.01 -> 1%)', 'fontweight', 'bold', ...
'tooltipstring', context('alpha',vars,txt) } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,'alpha') } {} ...
{ 'Style', 'text', 'string', 'Optional timef() arguments (see Help)', 'fontweight', 'bold', ...
'tooltipstring', 'See newcrossf() help via the Help button on the right...' } ...
{ 'Style', 'edit', 'string', '''padratio'', 1' } ...
{ 'Style', 'pushbutton', 'string', 'Help', 'callback', 'pophelp(''newcrossf'');' } ...
{} ...
{ 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotersp','present',0), 'string', ...
'Plot coherence amplitude', 'tooltipstring', ...
'Plot coherence ampltitude image in the upper panel' } ...
{ 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotphase','present',0), 'string', ...
'Plot coherence phase', 'tooltipstring', ...
'Plot coherence phase image in the lower panel' } ...
};
result = inputgui( geometry, uilist, 'pophelp(''pop_newcrossf'');', ...
fastif(typeproc, 'Plot channel cross-coherence -- pop_newcrossf()', ...
'Plot component cross-coherence -- pop_newcrossf()'));
if length( result ) == 0 return; end;
num1 = eval( [ '[' result{1} ']' ] );
num2 = eval( [ '[' result{2} ']' ] );
tlimits = eval( [ '[' result{3} ']' ] );
cycles = eval( [ '[' result{4} ']' ] );
if result{5},
if isempty(result{8}), result{8} = '''freqscale'', ''log''';
else result{8} = [ result{8} ', ''freqscale'', ''log''' ];
end;
end;
if result{6}
options = [',''type'', ''coher''' ];
else
options = [',''type'', ''phasecoher''' ];
end;
% add topoplot
% ------------
if isfield(EEG.chanlocs, 'theta') && ~isempty(EEG.chanlocs(num1).theta) && ~isempty(EEG.chanlocs(num2).theta)
if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end;
if typeproc == 1
options = [options ', ''topovec'', [' int2str([num1 num2]) ...
'], ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ];
else % typeproc == 0
options = [options ', ''topovec'', EEG.icawinv(:, [' int2str([num1 num2]) ...
'])'', ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ];
end;
end;
% add title
% ---------
if isempty( findstr( 'title', result{8}))
if ~isempty(EEG.chanlocs) & typeproc
chanlabel1 = EEG.chanlocs(num1).labels;
chanlabel2 = EEG.chanlocs(num2).labels;
else
chanlabel1 = int2str(num1);
chanlabel2 = int2str(num2);
end;
if result{6}
options = [options ', ''title'',' fastif(typeproc, '''Channel ', '''Component ') chanlabel1 '-' chanlabel2 ...
' Coherence'''];
else
options = [options ', ''title'',' fastif(typeproc, '''Channel ', '''Component ') chanlabel1 '-' chanlabel2 ...
' Phase Coherence''' ];
end;
end;
if ~isempty( result{7} )
options = [ options ', ''alpha'',' result{7} ];
end;
if ~isempty( result{8} )
options = [ options ',' result{8} ];
end;
if ~result{9}
options = [ options ', ''plotersp'', ''off''' ];
end;
if ~result{10}
options = [ options ', ''plotphase'', ''off''' ];
end;
figure; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end;
else
options = [ ',' vararg2str(varargin) ];
end;
% compute epoch limits
% --------------------
if isempty(tlimits)
tlimits = [EEG.xmin, EEG.xmax];
end;
pointrange1 = round(max((tlimits(1)/1000-EEG.xmin)*EEG.srate, 1));
pointrange2 = round(min((tlimits(2)/1000-EEG.xmin)*EEG.srate, EEG.pnts));
pointrange = [pointrange1:pointrange2];
% call function sample either on raw data or ICA data
% ---------------------------------------------------
if typeproc == 1
tmpsig1 = EEG.data(num1,pointrange,:);
tmpsig2 = EEG.data(num2,pointrange,:);
else
if ~isempty( EEG.icasphere )
eeglab_options; % changed from eeglaboptions 3/30/02 -sm
tmpsig1 = eeg_getdatact(EEG, 'component', num1, 'samples',pointrange);
tmpsig2 = eeg_getdatact(EEG, 'component', num2, 'samples',pointrange);
else
error('You must run ICA first');
end;
end;
tmpsig1 = reshape( tmpsig1, 1, size(tmpsig1,2)*size(tmpsig1,3));
tmpsig2 = reshape( tmpsig2, 1, size(tmpsig2,2)*size(tmpsig2,3));
% outputs
% -------
outstr = '';
if ~popup
for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end;
if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end;
end;
% plot the datas and generate output command
% --------------------------------------------
if length( options ) < 2
options = '';
end;
varargout{1} = sprintf('figure; pop_newcrossf( %s, %d, %d, %d, [%s], [%s] %s);', ...
inputname(1), typeproc, num1, num2, int2str(tlimits), num2str(cycles), options);
com = sprintf( '%s newcrossf( tmpsig1, tmpsig2, length(pointrange), [tlimits(1) tlimits(2)], EEG.srate, cycles %s);', outstr, options);
eval(com)
return;
% get contextual help
% -------------------
function txt = context(var, allvars, alltext);
loc = strmatch( var, allvars);
if ~isempty(loc)
txt= alltext{loc(1)};
else
disp([ 'warning: variable ''' var ''' not found']);
txt = '';
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_spectopo.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_spectopo.m
| 16,618 |
utf_8
|
d85a54903c88f0466adac25dbdc5c0a2
|
% pop_spectopo() - Plot spectra of specified data channels or components.
% Show scalp maps of power at specified frequencies.
% Calls spectopo().
% Usage:
% >> pop_spectopo( EEG, dataflag); % pops-up interactive window
% OR
% >> [spectopo_outputs] = pop_spectopo( EEG, dataflag, timerange, ...
% process, 'key', 'val',...); % returns spectopo() outputs
%
% Graphic interface for EEG data (dataflag = 1):
% "Epoch time range" - [edit box] [min max] Epoch time range (in ms) to use
% in computing the spectra (by default the whole epoch or data).
% Command line equivalent: 'timerange'
% "Percent data to sample" - [edit box] Percentage of data to use in
% computing the spectra (low % speeds up the computation).
% spectopo() equivalent: 'percent'
% "Frequencies to plot as scalp maps" - [edit box] Vector of 1-7 frequencies to
% plot topoplot() scalp maps of power at all channels.
% spectopo() equivalent: 'freqs'
% "Apply to EEG|ERP|BOTH" - [edit box] Plot spectra of the 'EEG', 'ERP' or of 'BOTH'.
% NOTE: This edit box does not appear for continuous data.
% Command line equivalent: 'process'
% "Plotting frequency range" - [edit box] [min max] Frequency range (in Hz) to plot.
% spectopo() equivalent: 'freqrange'
% "Spectral and scalp map options (see topoplot)" - [edit box] 'key','val','key',...
% sequence of arguments passed to spectopo() for details of the
% spectral decomposition or to topoplot() to adjust details of
% the scalp maps. For details see >> help topoplot
%
% Graphic interface for components (dataflag = 0):
% "Epoch time range" - [edit box] [min max] Epoch time range (in ms) to use
% in computing the spectra (by default the whole epoch or data).
% Command line equivalent: 'timerange'
% "Frequency (Hz) to analyze" - [edit box] Single frequency (Hz) at which to plot
% component contributions. spectopo() equivalent: 'freqs'
% "Electrode number to analyze" - [edit box] 1-nchans --> Plot component contributions
% at this channel; [] --> Plot contributions at channel with max
% power; 0 --> Plot component contributions to global (RMS) power.
% spectopo() equivalent: 'plotchan'
% "Percent data to sample" - [edit box] Percent of data to use in computing the spectra
% (low % speeds up the computation). spectopo() equivalent: 'percent'
% "Components to include ..." - [Edit box] Only compute spectrum of a subset of the
% components. spectopo() equivalent: 'icacomps'
% "Number of largest-contributing ..." - [edit box] Number of component maps
% to plot. spectopo() equivalent: 'nicamaps'
% "Else, map only these components ..." - [edit box] Use this entry to override
% plotting maps of the components that project most strongly (at
% the selected frequency) to the the selected channel (or whole scalp
% if 'plotchan' (above) == 0). spectopo() equivalent: 'icamaps'
% "[Checked] Compute comp spectra ..." - [checkbox] If checked, compute the spectra
% of the selected component activations; else, if unchecked
% compute the spectra of (the data MINUS each selected component).
% spectopo() equivalent: 'icamode'
% "Plotting frequency range" - [edit box] [min max] Frequency range (in Hz) to plot.
% spectopo() equivalent: 'freqrange'
% "Spectral and scalp map options (see topoplot)" - [edit box] 'key','val','key',...
% sequence of arguments passed to spectopo() for details of the
% spectral decomposition or to topoplot() to adjust details of
% the scalp maps. For details see >> help topoplot
% Inputs:
% EEG - Input EEGLAB dataset
% dataflag - If 1, process the input data channels.
% If 0, process its component activations.
% {Default: 1, process the data channels}.
% timerange - [min_ms max_ms] Epoch time range to use in computing the spectra
% {Default: whole input epochs}
% process - 'EEG'|ERP'|'BOTH' If processing data epochs, work on either the
% mean single-trial 'EEG' spectra, the spectrum of the trial-average
% 'ERP', or plot 'BOTH' the EEG and ERP spectra. {Default: 'EEG'}
%
% Optional inputs:
% 'key','val' - Optional topoplot() and/or spectopo() plotting arguments
% {Default, 'electrodes','off'}
%
% Outputs: As from spectopo(). When nargin<2, a query window pops-up
% to ask for additional arguments and NO outputs are returned.
% Note: Only the outputs of the 'ERP' spectral analysis
% are returned when plotting 'BOTH' ERP and EEG spectra.
%
% Author: Arnaud Delorme & Scott Makeig, CNL / Salk Institute, 10 March 2002
%
% See also: spectopo(), topoplot()
% Copyright (C) 10 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
% 03-15-02 debugging -ad
% 03-16-02 add all topoplot options -ad
% 04-04-02 added outputs -ad & sm
function varargout = pop_spectopo( EEG, dataflag, timerange, processflag, varargin);
varargout{1} = '';
if nargin < 1
help pop_spectopo;
return;
end;
if nargin < 2
dataflag = 1;
end;
if nargin < 3
processflag = 'EEG';
end;
chanlocs_present = 0;
if ~isempty(EEG.chanlocs)
if isfield(EEG.chanlocs, 'theta')
tmpchanlocs = EEG.chanlocs;
if any(~cellfun(@isempty, { tmpchanlocs.theta }))
chanlocs_present = 1;
end;
end;
end;
if nargin < 3
if dataflag
geometry = { [2 1] [2 1] [2 1] [2 1] [2 1] [2 1]};
scalp_freq = fastif(chanlocs_present, { '6 10 22' }, { '' 'enable' 'off' });
promptstr = { { 'style' 'text' 'string' 'Epoch time range to analyze [min_ms max_ms]:' }, ...
{ 'style' 'edit' 'string' [num2str( EEG.xmin*1000) ' ' num2str(EEG.xmax*1000)] }, ...
{ 'style' 'text' 'string' 'Percent data to sample (1 to 100):'}, ...
{ 'style' 'edit' 'string' '15' }, ...
{ 'style' 'text' 'string' 'Frequencies to plot as scalp maps (Hz):'}, ...
{ 'style' 'edit' 'string' scalp_freq{:} }, ...
{ 'style' 'text' 'string' 'Apply to EEG|ERP|BOTH:'}, ...
{ 'style' 'edit' 'string' 'EEG' }, ...
{ 'style' 'text' 'string' 'Plotting frequency range [lo_Hz hi_Hz]:'}, ...
{ 'style' 'edit' 'string' '2 25' }, ...
{ 'style' 'text' 'string' 'Spectral and scalp map options (see topoplot):' } ...
{ 'style' 'edit' 'string' '''electrodes'',''off''' } };
if EEG.trials == 1
geometry(3) = [];
promptstr(7:8) = [];
end;
result = inputgui( geometry, promptstr, 'pophelp(''pop_spectopo'')', 'Channel spectra and maps -- pop_spectopo()');
if size(result,1) == 0 return; end;
timerange = eval( [ '[' result{1} ']' ] );
options = [];
if isempty(EEG.chanlocs)
disp('Topographic plot options ignored. First import a channel location file');
disp('To plot a single channel, use channel property menu or the following call');
disp(' >> figure; chan = 1; spectopo(EEG.data(chan,:,:), EEG.pnts, EEG.srate);');
end;
if eval(result{2}) ~= 100, options = [ options ', ''percent'', ' result{2} ]; end;
if ~isempty(result{3}) & ~isempty(EEG.chanlocs), options = [ options ', ''freq'', [' result{3} ']' ]; end;
if EEG.trials ~= 1
processflag = result{4};
if ~isempty(result{5}), options = [ options ', ''freqrange'',[' result{5} ']' ]; end;
if ~isempty(result{6}), options = [ options ',' result{6} ]; end;
else
if ~isempty(result{4}), options = [ options ', ''freqrange'',[' result{4} ']' ]; end;
if ~isempty(result{5}), options = [ options ',' result{5} ]; end;
end;
else
if ~chanlocs_present
error('pop_spectopo(): cannot plot component contributions without channel locations');
end;
geometry = { [2 1] [2 1] [2 1] [2 1] [2 1] [2 1] [2 1] [2 0.18 0.78] [2 1] [2 1] };
promptstr = { { 'style' 'text' 'string' 'Epoch time range to analyze [min_ms max_ms]:' }, ...
{ 'style' 'edit' 'string' [num2str( EEG.xmin*1000) ' ' num2str(EEG.xmax*1000)] }, ...
{ 'style' 'text' 'string' 'Frequency (Hz) to analyze:'}, ...
{ 'style' 'edit' 'string' '10' }, ...
{ 'style' 'text' 'string' 'Electrode number to analyze ([]=elec with max power; 0=whole scalp):', 'tooltipstring', ...
['If value is 1 to nchans, plot component contributions at this channel' 10 ...
'If value is [], plot contributions at channel with max. power' 10 ...
'If value is 0, plot component contributions to global (RMS) power'] }, ...
{ 'style' 'edit' 'string' '0' }, ...
{ 'style' 'text' 'string' 'Percent data to sample (1 to 100):'}, ...
{ 'style' 'edit' 'string' '20' }, ...
{ 'style' 'text' 'string' 'Components to include in the analysis:' }, ...
{ 'style' 'edit' 'string' ['1:' int2str(size(EEG.icaweights,1))] }, ...
{ 'style' 'text' 'string' 'Number of largest-contributing components to map:' }, ...
{ 'style' 'edit' 'string' '5' }, ...
{ 'style' 'text' 'string' ' Else, map only these component numbers:', 'tooltipstring', ...
['Use this entry to override plotting maps of the components that project' 10 ...
'most strongly to the selected channel (or whole scalp) at the selected frequency.' ] }, ...
{ 'style' 'edit' 'string' '' }, ...
{ 'style' 'text' 'string' '[Checked] Compute comp spectra; [Unchecked] (data-comp) spectra:', 'tooltipstring' ...
['If checked, compute the spectra of the selected component activations' 10 ...
'else [if unchecked], compute the spectra of (the data MINUS each slected component)']}, ...
{ 'style' 'checkbox' 'value' 1 } { }, ...
{ 'style' 'text' 'string' 'Plotting frequency range ([min max] Hz):'}, ...
{ 'style' 'edit' 'string' '2 25' }, ...
{ 'style' 'text' 'string' 'Spectral and scalp map options (see topoplot):' } ...
{ 'style' 'edit' 'string' '''electrodes'',''off''' } };
result = inputgui( geometry, promptstr, 'pophelp(''spectopo'')', 'Component spectra and maps -- pop_spectopo()');
if size(result,1) == 0 return; end;
timerange = eval( [ '[' result{1} ']' ] );
options = '';
if ~isempty(result{2}) , options = [ options ', ''freq'', [' result{2} ']' ]; end;
if ~isempty(result{3}) , options = [ options ', ''plotchan'', ' result{3} ]; end;
if eval(result{4}) ~= 100, options = [ options ', ''percent'', ' result{4} ]; end;
if ~isempty(result{5}) , options = [ options ', ''icacomps'', [' result{5} ']' ]; end;
if ~isempty(result{6}) , options = [ options ', ''nicamaps'', ' result{6} ]; end;
if ~isempty(result{7}) , options = [ options ', ''icamaps'', [' result{7} ']' ]; end;
if ~result{8}, options = [ options ', ''icamode'', ''sub''' ]; end;
if ~isempty(result{9}), options = [ options ', ''freqrange'',[' result{9} ']' ]; end;
if ~isempty(result{10}), options = [ options ',' result{10} ]; end;
end;
figure('tag', 'spectopo');
set(gcf,'Name','spectopo()');
else
if ~isempty(varargin)
options = [',' vararg2str(varargin)];
else
options = '';
end;
if isempty(timerange)
timerange = [ EEG.xmin*1000 EEG.xmax*1000 ];
end;
if nargin < 3
percent = 100;
end;
if nargin < 4
topofreqs = [];
end;
end;
% set the background color of the figure
try, tmpopt = struct(varargin{:}); if ~isfield(tmpopt, 'plot') || strcmpi(tmpopt, 'on'), icadefs; set(gcf, 'color', BACKCOLOR); end; catch, end;
switch processflag,
case {'EEG' 'eeg' 'ERP' 'erp' 'BOTH' 'both'},;
otherwise, if nargin <3, close; end;
error('Pop_spectopo: processflag must be ''EEG'', ''ERP'' or ''BOTH''');
end;
if EEG.trials == 1 & ~strcmp(processflag,'EEG')
if nargin <3, close; end;
error('pop_spectopo(): must use ''EEG'' mode when processing continuous data');
end;
if ~isempty(EEG.chanlocs)
if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end;
spectopooptions = [ options ', ''verbose'', ''off'', ''chanlocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ];
if dataflag == 0 % i.e. components
spectopooptions = [ spectopooptions ', ''weights'', EEG.icaweights*EEG.icasphere' ];
end;
else
spectopooptions = options;
end;
if ~dataflag
spectopooptions = [ spectopooptions ', ''icawinv'', EEG.icawinv, ''icachansind'', EEG.icachansind' ];
end;
% The programming here is a bit redundant but it tries to optimize
% memory usage.
% ----------------------------------------------------------------
if timerange(1)/1000~=EEG.xmin | timerange(2)/1000~=EEG.xmax
posi = round( (timerange(1)/1000-EEG.xmin)*EEG.srate )+1;
posf = min(round( (timerange(2)/1000-EEG.xmin)*EEG.srate )+1, EEG.pnts );
pointrange = posi:posf;
if posi == posf, error('pop_spectopo(): empty time range'); end;
fprintf('pop_spectopo(): selecting time range %6.2f ms to %6.2f ms (points %d to %d)\n', ...
timerange(1), timerange(2), posi, posf);
end;
if isempty(EEG.icachansind) || dataflag == 1, chaninds = 1:EEG.nbchan;
else chaninds = EEG.icachansind;
end;
if exist('pointrange') == 1, SIGTMP = EEG.data(chaninds,pointrange,:); totsiz = length( pointrange);
else SIGTMP = EEG.data(chaninds,:,:); totsiz = EEG.pnts;
end;
% add boundaries if continuous data
% ----------------------------------
if EEG.trials == 1 & ~isempty(EEG.event) & isfield(EEG.event, 'type') & isstr(EEG.event(1).type)
tmpevent = EEG.event;
boundaries = strmatch('boundary', {tmpevent.type});
if ~isempty(boundaries)
if exist('pointrange')
boundaries = [ tmpevent(boundaries).latency ] - 0.5-pointrange(1)+1;
boundaries(find(boundaries>=pointrange(end)-pointrange(1))) = [];
boundaries(find(boundaries<1)) = [];
boundaries = [0 boundaries pointrange(end)-pointrange(1)];
else
boundaries = [0 [ tmpevent(boundaries).latency ]-0.5 EEG.pnts ];
end;
spectopooptions = [ spectopooptions ',''boundaries'',[' int2str(round(boundaries)) ']'];
end;
fprintf('Pop_spectopo: finding data discontinuities\n');
end;
% outputs
% -------
outstr = '';
if nargin >= 2
for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end;
if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end;
end;
% plot the data and generate output and history commands
% ------------------------------------------------------
popcom = sprintf('figure; pop_spectopo(%s, %d, [%s], ''%s'' %s);', inputname(1), dataflag, num2str(timerange), processflag, options);
switch processflag
case { 'EEG' 'eeg' }, SIGTMP = reshape(SIGTMP, size(SIGTMP,1), size(SIGTMP,2)*size(SIGTMP,3));
com = sprintf('%s spectopo( SIGTMP, totsiz, EEG.srate %s);', outstr, spectopooptions);
eval(com)
case { 'ERP' 'erp' }, com = sprintf('%s spectopo( mean(SIGTMP,3), totsiz, EEG.srate %s);', outstr, spectopooptions); eval(com)
case { 'BOTH' 'both' }, sbplot(2,1,1); com = sprintf('%s spectopo( mean(SIGTMP,3), totsiz, EEG.srate, ''title'', ''ERP'' %s);', outstr, spectopooptions); eval(com)
SIGTMP = reshape(SIGTMP, size(SIGTMP,1), size(SIGTMP,2)*size(SIGTMP,3));
sbplot(2,1,2); com = sprintf('%s spectopo( SIGTMP, totsiz, EEG.srate, ''title'', ''EEG'' %s);', outstr, spectopooptions); eval(com)
end;
if nargout < 2 & nargin < 3
varargout{1} = popcom;
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_epoch.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_epoch.m
| 16,923 |
utf_8
|
1fb4d2e74c69a52ed60d55d1621486e5
|
% pop_epoch() - Convert a continuous EEG dataset to epoched data by extracting
% data epochs time locked to specified event types or event indices.
% May also sub-epoch an already epoched dataset (if sub-epochs are
% same size or smaller). This pop_function calls epoch().
% Usage:
% >> OUTEEG = pop_epoch( EEG); % pop-up a data entry window
% >> OUTEEG = pop_epoch( EEG, events, timelimits);
% >> [OUTEEG, indices] = pop_epoch( EEG, typerange, timelimits,'key1', value1 ...);
%
% Graphic interface:
% "Time-locking event type(s)" - [edit box] Select 'Edit > Event values'
% to see a list of event.type values; else use the push button.
% To use event types containing spaces, enter in single-quotes.
% epoch() function command line equivalent: 'typerange'
% "..." - [push button] scroll event types.
% "Epoch limits" - [edit box] epoch latency range [start, end] in seconds relative
% to the time-locking events. epoch() function equivalent: 'timelim'
% "Name for the new dataset" - [edit box]
% epoch() function equivalent: 'newname'
% "Out-of-bounds EEG ..." - [edit box] Rejection limits ([min max], []=none).
% epoch() function equivalent: 'valuelim'
% Inputs:
% EEG - Input dataset. Data may already be epoched; in this case,
% extract (shorter) subepochs time locked to epoch events.
% typerange - Cell array of event types to time lock to. 'eventindices'
% {default {} --> time lock epochs to any type of event}
% (Note: An event field called 'type' must be defined in the
% 'EEG.event' structure. The command line argument is
% 'eventindices' below).
% timelim - Epoch latency limits [start end] in seconds relative to
% the time-locking event {default: [-1 2]}
%
% Optional inputs:
% 'eventindices'- [integer vector] Extract data epochs time locked to the
% indexed event numbers.
% 'valuelim' - [min max] or [max]. Lower and upper bound latencies for
% trial data. Else if one positive value is given, use its
% negative as the lower bound. The given values are also
% considered outliers (min max) {default: none}
% 'verbose' - ['yes'|'no'] {default: 'yes'}
% 'newname' - [string] New dataset name {default: "[old_dataset] epochs"}
% 'epochinfo'- ['yes'|'no'] Propagate event information into the new
% epoch structure {default: 'yes'}
%
% Outputs:
% OUTEEG - output dataset
% indices - indices of accepted events
%
% Authors: Arnaud Delorme and Hilit Serby, SCCN, INC, UCSD, 2001
%
% See also: eeglab, epoch
% deprecated
% 'timeunit' - Time unit ['seconds'|'points'] If 'seconds,' consider events
% times to be in seconds. If 'points,' consider events as
% indices into the data array. {default: '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
% 01-25-02 reformated help & license -ad
% 02-13-02 introduction of 'key', val arguments -ad
% 02-13-02 rereferencing of events -ad
% 03-18-02 interface and debugging -ad
% 03-27-02 interface and debugging -ad & sm
function [EEG, indices, com] = pop_epoch( EEG, events, lim, varargin );
if nargin < 1
help pop_epoch;
return;
end;
com = '';
indices = [];
if isempty(EEG.event)
if EEG.trials > 1 & EEG.xmin <= 0 & EEG.xmax >=0
disp('No EEG.event structure found: creating events of type ''TLE'' (Time-Locking Event) at time 0');
EEG.event(EEG.trials).epoch = EEG.trials;
for trial = 1:EEG.trials
EEG.event(trial).epoch = trial;
EEG.event(trial).type = 'TLE';
EEG.event(trial).latency = -EEG.xmin*EEG.srate+1+(trial-1)*EEG.pnts;
end;
else
disp('Cannot epoch data with no events'); beep;
return;
end;
end;
if ~isfield(EEG.event, 'latency'),
disp( 'Absent latency field in event array/structure: must name one of the fields ''latency''');
beep; return;
end;
OLDEEG = EEG;
if nargin < 3
% popup window parameters
% -----------------------
promptstr = { strvcat('Time-locking event type(s) ([]=all):', ...
'Select ''Edit > Event values'' to see type values.'), ...
'Epoch limits [start, end] in seconds:', ...
'Name for the new dataset:', ...
'Out-of-bounds EEG rejection limits ([min max], []=none):' };
cbevent = ['if ~isfield(EEG.event, ''type'')' ...
' errordlg2(''No type field'');' ...
'else' ...
' tmpevent = EEG.event;' ...
' if isnumeric(EEG.event(1).type),' ...
' [tmps,tmpstr] = pop_chansel(unique([ tmpevent.type ]));' ...
' else,' ...
' [tmps,tmpstr] = pop_chansel(unique({ tmpevent.type }));' ...
' end;' ...
' if ~isempty(tmps)' ...
' set(findobj(''parent'', gcbf, ''tag'', ''events''), ''string'', tmpstr);' ...
' end;' ...
'end;' ...
'clear tmps tmpevent tmpv tmpstr tmpfieldnames;' ];
geometry = { [2 1 0.5] [2 1 0.5] [2 1.5] [2 1 0.5] };
uilist = { { 'style' 'text' 'string' 'Time-locking event type(s) ([]=all)' } ...
{ 'style' 'edit' 'string' '' 'tag' 'events' } ...
{ 'style' 'pushbutton' 'string' '...' 'callback' cbevent } ...
{ 'style' 'text' 'string' 'Epoch limits [start, end] in seconds' } ...
{ 'style' 'edit' 'string' '-1 2' } ...
{ } ...
{ 'style' 'text' 'string' 'Name for the new dataset' } ...
{ 'style' 'edit' 'string' fastif(isempty(EEG.setname), '', [ EEG.setname ' epochs' ]) } ...
{ 'style' 'text' 'string' 'Out-of-bounds EEG limits if any [min max]' } ...
{ 'style' 'edit' 'string' '' } { } };
result = inputgui( geometry, uilist, 'pophelp(''pop_epoch'')', 'Extract data epochs - pop_epoch()');
if length(result) == 0 return; end;
if strcmpi(result{1}, '[]'), result{1} = ''; end;
if ~isempty(result{1})
if strcmpi(result{1}(1),'''') % If event type appears to be in single-quotes, use comma
% and single-quote as delimiter between event types. toby 2.24.2006
% fixed Arnaud May 2006
events = eval( [ '{' result{1} '}' ] );
else events = parsetxt( result{1});
end;
else events = {};
end
lim = eval( [ '[' result{2} ']' ] );
args = {};
if ~isempty( result{3} ), args = { args{:}, 'newname', result{3} }; end;
if ~isempty( result{4} ), args = { args{:}, 'valuelim', eval( [ '[' result{4} ']' ] ) }; end;
args = { args{:}, 'epochinfo', 'yes' };
else % no interactive inputs
args = varargin;
end;
% create structure
% ----------------
if ~isempty(args)
try, g = struct(args{:});
catch, disp('pop_epoch(): wrong syntax in function arguments'); return; end;
else
g = [];
end;
% test the presence of variables
% ------------------------------
try, g.epochfield; catch, g.epochfield = 'type'; end; % obsolete
try, g.timeunit; catch, g.timeunit = 'points'; end;
try, g.verbose; catch, g.verbose = 'on'; end;
try, g.newname; catch, g.newname = fastif(isempty(EEG.setname), '', [EEG.setname ' epochs' ]); end;
try, g.eventindices; catch, g.eventindices = 1:length(EEG.event); end;
try, g.epochinfo; catch, g.epochinfo = 'yes'; end;
try, if isempty(g.valuelim), g.valuelim = [-Inf Inf]; end; catch, g.valuelim = [-Inf Inf]; end;
% transform string events into a int array of column indices
% ----------------------------------------------------------
tmpevent = EEG.event;
tmpeventlatency = [ tmpevent(:).latency ];
[tmpeventlatency Itmp] = sort(tmpeventlatency);
EEG.event = EEG.event(Itmp); % sort by ascending time
Ievent = g.eventindices;
if ~isempty( events )
% select the events for epoching
% ------------------------------
Ieventtmp = [];
tmpevent = EEG.event;
tmpeventtype = { tmpevent.type };
if iscell(events)
if isstr(EEG.event(1).type)
for index2 = 1:length( events )
tmpevent = events{index2};
if ~isstr( tmpevent ), tmpevent = num2str( tmpevent ); end;
Ieventtmp = [ Ieventtmp ; strmatch(tmpevent, tmpeventtype, 'exact') ];
end;
else
for index2 = 1:length( events )
tmpevent = events{index2};
if isstr( tmpevent ),tmpevent = str2num( tmpevent ); end;
if isempty( tmpevent ), error('pop_epoch(): string entered in a numeric field'); end;
Ieventtmp = [ Ieventtmp find(tmpevent == [ tmpeventtype{:} ]) ];
end;
end;
else
error('pop_epoch(): multiple event types must be entered as {''a'', ''cell'', ''array''}'); return;
end;
Ievent = sort(intersect(Ievent, Ieventtmp));
end;
% select event latencies for epoching
%------------------------------------
Ievent = sort(Ievent);
alllatencies = tmpeventlatency(Ievent);
if isempty(alllatencies)
error('pop_epoch(): empty epoch range (no epochs were found).'); return;
end;
fprintf('pop_epoch():%d epochs selected\n', length(alllatencies));
try
% ----------------------------------------------------
% For AMICA probabilities...Temporarily add model probabilities as channels
%-----------------------------------------------------
if isfield(EEG.etc, 'amica') && ~isempty(EEG.etc.amica) && isfield(EEG.etc.amica, 'v_smooth') && ~isempty(EEG.etc.amica.v_smooth) && ~isfield(EEG.etc.amica,'prob_added')
if isfield(EEG.etc.amica, 'num_models') && ~isempty(EEG.etc.amica.num_models)
if size(EEG.data,2) == size(EEG.etc.amica.v_smooth,2) && size(EEG.data,3) == size(EEG.etc.amica.v_smooth,3) && size(EEG.etc.amica.v_smooth,1) == EEG.etc.amica.num_models
EEG = eeg_formatamica(EEG);
%--------------------
[EEG indices com] = pop_epoch(EEG,events,lim,args{:});
%---------------------------------
EEG = eeg_reformatamica(EEG);
EEG = eeg_checkamica(EEG);
return;
else
disp('AMICA probabilities not compatible with size of data, model probabilities cannot be epoched...')
end
end
end
% ----------------------------------------------------
catch
warnmsg = strcat('your dataset contains amica information, but the amica plugin is not installed. Continuing and ignoring amica information.');
warning(warnmsg)
end
% change boundaries in rare cases when limits do not include time-locking events
% ------------------------------------------------------------------------------
tmpevents = EEG.event;
if lim(1) > 0 && ischar(EEG.event(1).type)
% go through all onset latencies
for Z1 = length(alllatencies):-1:1
% if there is any event in between trigger and epoch onset which are boundary events
selEvt = find([tmpevents.latency] > alllatencies(Z1) & [tmpevents.latency] < alllatencies(Z1) + lim(1) * EEG.srate);
selEvt = selEvt(strcmp({tmpevents(selEvt).type}, 'boundary'));
if any(selEvt)
if sum([tmpevents(selEvt).duration]) > lim(1) * EEG.srate
alllatencies(Z1) = [];
else
% correct the latencies by the duration of the data that were cutout
alllatencies(Z1) = alllatencies(Z1) - sum([tmpevents(selEvt).duration]);
end;
end
end
end
if lim(2) < 0 && ischar(EEG.event(1).type)
% go through all onset latencies
for Z1 = length(alllatencies):-1:1
% if there is any event in between trigger and epoch onset which are boundary events
selEvt = find([tmpevents.latency] < alllatencies(Z1) & [tmpevents.latency] > alllatencies(Z1) + lim(2) * EEG.srate);
selEvt = selEvt(strcmp({tmpevents(selEvt).type}, 'boundary'));
if any(selEvt)
if sum([tmpevents(selEvt).duration]) > -lim(2) * EEG.srate
alllatencies(Z1) = [];
else
% correct the latencies by the duration of the data that were cutout
alllatencies(Z1) = alllatencies(Z1) + sum([tmpevents(selEvt).duration]);
end;
end
end
end
% select event time format and epoch
% ----------------------------------
switch lower( g.timeunit )
case 'points', [EEG.data tmptime indices epochevent]= epoch(EEG.data, alllatencies, [lim(1) lim(2)]*EEG.srate, ...
'valuelim', g.valuelim, 'allevents', tmpeventlatency);
tmptime = tmptime/EEG.srate;
case 'seconds', [EEG.data tmptime indices epochevent]= epoch(EEG.data, alllatencies, lim, 'valuelim', g.valuelim, ...
'srate', EEG.srate, 'allevents', tmpeventlatency);
otherwise, disp('pop_epoch(): invalid event time format'); beep; return;
end;
alllatencies = alllatencies(indices);
fprintf('pop_epoch():%d epochs generated\n', length(indices));
% update other fields
% -------------------
if lim(1) ~= tmptime(1) & lim(2)-1/EEG.srate ~= tmptime(2)
fprintf('pop_epoch(): time limits have been adjusted to [%3.3f %3.3f] to fit data points limits\n', ...
tmptime(1), tmptime(2)+1/EEG.srate);
end;
EEG.xmin = tmptime(1);
EEG.xmax = tmptime(2);
EEG.pnts = size(EEG.data,2);
EEG.trials = size(EEG.data,3);
EEG.icaact = [];
if ~isempty(EEG.setname)
if ~isempty(EEG.comments)
EEG.comments = strvcat(['Parent dataset "' EEG.setname '": ----------'], EEG.comments);
end;
EEG.comments = strvcat(['Parent dataset: ' EEG.setname ], ' ', EEG.comments);
end;
EEG.setname = g.newname;
% count the number of events to duplicate and duplicate them
% ----------------------------------------------------------
totlen = 0;
for index=1:EEG.trials, totlen = totlen + length(epochevent{index}); end;
EEG.event(1).epoch = 0; % create the epoch field (for assignment consistency afterwards)
if totlen ~= 0
newevent(totlen) = EEG.event(1); % reserve array
else
newevent = [];
end;
% modify the event structure accordingly (latencies and add epoch field)
% ----------------------------------------------------------------------
allevents = [];
count = 1;
for index=1:EEG.trials
for indexevent = epochevent{index}
newevent(count) = EEG.event(indexevent);
newevent(count).epoch = index;
newevent(count).latency = newevent(count).latency ...
- alllatencies(index) - tmptime(1)*EEG.srate + 1 + EEG.pnts*(index-1);
count = count + 1;
end;
end;
EEG.event = newevent;
EEG.epoch = [];
EEG = eeg_checkset(EEG, 'eventconsistency');
% check for boundary events
% -------------------------
disp('pop_epoch(): checking epochs for data discontinuity');
if ~isempty(EEG.event) & isstr(EEG.event(1).type)
tmpevent = EEG.event;
boundaryindex = strmatch('boundary', { tmpevent.type });
if ~isempty(boundaryindex)
indexepoch = [];
for tmpindex = boundaryindex
if isfield(tmpevent, 'epoch')
indexepoch = [indexepoch tmpevent(tmpindex).epoch ];
else
indexepoch = 1; % only one epoch
end;
end;
EEG = pop_select(EEG, 'notrial', indexepoch);
% update the "indices of accepted events", too
indices = indices(setdiff(1:length(indices),indexepoch));
end;
end;
% generate text command
% ---------------------
com = sprintf('%s = pop_epoch( %s, { ', inputname(1), inputname(1));
for j=1:length(events);
if isstr( events{j} ) com = sprintf('%s ''%s'' ', com, events{j} );
else com = sprintf('%s [%s] ', com, num2str(events{j}) );
end;
end;
com = sprintf('%s }, [%s]', com, num2str(lim));
for i=1:2:length(args)
if ~isempty( args{i+1} )
if isstr( args{i+1} ) com = sprintf('%s, ''%s'', ''%s''', com, args{i}, args{i+1} );
else com = sprintf('%s, ''%s'', [%s]', com, args{i}, num2str(args{i+1}) );
end;
end;
end;
com = [com ');'];
return; % text command
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_eventhist.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_eventhist.m
| 4,549 |
utf_8
|
075deb48deff9d15410e8cce6a433655
|
% eeg_eventhist() - return or plot histogram of event or urevent field values.
% If NO output args, plots the histogram. If the field values
% are not numbers or strings, no histogram is computed.
% Usage:
% >> figure; eeg_eventhist(EEG.event,'field',bins); % plot histogram
% >> [fldvals] = eeg_eventhist(EEG.event,'field'); % return field values
% >> [fldvals,binNs,binedges] = eeg_eventhist(EEG.event,'field',bins);
% Inputs:
%
% Event - an EEGLAB EEG.event or EEG.urevent structure
% 'field' - string containing the name of a field in the input Event structure
% bins - optional number of bins to use, else vector of bin edges {default: 10}
% If event field values are strings, this argument is ignored.
% Outputs:
%
% fldvals - numeric, struct, or cell array vector of field values for each event
% in the input event order (with [] values, if any, replaced by NaN's or ' 's).
% binNs - numbers of events in the histogram bins
% binedges - if numeric values, a one-column matrix giving bin edges of the [low,high) bins
% Else, if string values, cell array containing the string associated with each bin.
% Example:
% >> [vals,histNs,bins] = eeg_eventhist(EEG.event,'type');
% %
% % Returns cell array of event-type strings, numbers of each event type,
% % and event type strings, in alphabetic order. No bar() plot produced.
%
% See also: pop_eventstat(), signalstat(), pop_signalstat().
%
% Author: Scott Makeig, SCCN, Institute for Neural Computation, UCSD, March 26, 2004
%
% 8-20-05 replace found numeric field values [] with NaN to avoid bug -sm
% replace bin numbers in plot with bin labels if strings; add plot title
function [vals,histNs,outbins] = eeg_eventhist(Event,field,bins)
if nargin < 2
help eeg_eventhist
return
end
if nargin < 3
bins = 10;
end
if isempty(Event)
error('Event structure is empty');
end
if ~isfield(Event,field)
error('named field is not an Event field')
end
idx = 0; fld = [];
while isempty(fld)
idx = idx+1;
if idx > length(Event)
error('All named event fields are empty');
end
fld = getfield(Event(idx),field);
if ischar(fld)
IS_CHAR = 1;
elseif isstruct(fld)
IS_STRUCT = 1;
elseif ~isempty(fld)
IS_NUM = 1;
end
end
if exist('IS_NUM')
vals = zeros(length(Event),1);
fprintf('Assuming ''%s'' field values are numeric.\n',field);
elseif exist('IS_CHAR')
vals = cell(length(Event),1);
fprintf('Assuming ''%s'' field values are strings.\n',field);
elseif exist('IS_STRUCT')
vals = repmat(field1,length(Event),1);
fprintf('Assuming ''%s'' field values are structures.\n',field);
else
error('Cannot determine field value type')
end
if exist('IS_NUM')
for k=1:length(Event)
v = getfield(Event(k),field);
if isempty(v)
v = NaN;
end
vals(k) = v;
end
else
for k=1:length(Event)
vals{k} = getfield(Event(k),field);
end
end
if nargout == 1 | exist('IS_STRUCT')
return % return vals only, no histogram
end
%
if exist('IS_NUM') %%%%%%%%%%%%%%%% numeric values histogram %%%%%%%%%%%%%%%%%%%%%%
%
if numel(bins) == 1
if bins < 3
error('number of bins must be > 2');
end
mn = mean(vals);
stdev = std(vals);
binsout = zeros(bins,1);
fl2 = floor(bins/2);
for k = -1*fl2:ceil(bins/2)
binsout(k+fl2+1) = mn+k*stdev;
end
binsout(1) = -inf;
binsout(end) = inf;
histNs = histc(vals,binsout);
histNs = histNs(1:end-1);
else % accomodate specified bin edges
histNs = histc(vals,bins);
histNs = histNs(1:end-1);
end
outbins = binsout;
if nargout == 0
h = bar(histNs,'histc');
end
%
else % exist('IS_CHAR') %%%%%%%%%%%% string values histogram %%%%%%%%%%%%%%%%%%%%%%
%
for v=1:length(vals)
if isempty(cell2mat(vals(v)))
vals(v) = {' '};
end
end
outbins = unique_bc(vals);
histNs = zeros(length(outbins)-1,1);
for k=1:length(outbins)
histNs(k) = sum(ismember(vals,outbins{k}));
end
if nargout == 0
bar(histNs,1);
if IS_CHAR
set(gca,'xticklabel',outbins); % ??? NEEDS MORE WORK - CANT TEST FROM HOME
yl = get(gca,'ylim');
set(gca,'ylim',[yl(1) yl(2)*1.1]);
if strcmp(field,'type')
tl=title(['Histogram of event types']);
else
tl=title(['Histogram of event field ''' field ''' values']);
end
end
end
end
return
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_latencyur.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_latencyur.m
| 2,912 |
utf_8
|
d55ca27237bce37a4bf5491ff6639324
|
% eeg_latencyur() - transform latency of sample point in the continuous
% data into latencies in the transformed dataset.
%
% Usage:
% >> lat_out = eeg_latencyur( events, lat_in);
%
% Inputs:
% events - event structure. If this structure contain boundary
% events, the length of these events is added to restore
% the original latency from the relative latency in 'lat_in'
% lat_in - sample latency (in point) in the original urEEG.
%
% Outputs:
% lat_out - output latency
%
% Note: the function that finds the original (ur) latency in the original
% dataset using latencies in the current dataset is called
% eeg_urlatency()
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2011-
%
% See also: eeg_urlatency()
% Copyright (C) 2011 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 latout = eeg_latencyur( events, latin );
if nargin < 2
help eeg_latencyur;
return;
end;
boundevents = { events.type };
latout = latin;
if ~isempty(boundevents) & isstr(boundevents{1})
indbound = strmatch('boundary', boundevents);
if isfield(events, 'duration') & ~isempty(indbound)
for index = indbound'
lowerVals = find(latout > events(index).latency);
latout(lowerVals) = latout(lowerVals)-events(index).duration;
end;
end;
end;
return;
% build array of 0 and 1 (0 no data)
boundevents = { events.type };
latout = latin;
if ~isempty(boundevents) & isstr(boundevents{1})
indbound = strmatch('boundary', boundevents);
if isfield(events, 'duration') & ~isempty(indbound)
currentadd = 0;
points = ones(1, events(end).latency+sum([events(indbound').duration])); % arrays of 1
for index = indbound'
currentlat = events(index).latency+currentadd;
currentdur = events(index).duration;
points(round(currentlat):round(currentlat+currentdur)) = 0;
currentadd = currentadd + currentdur;
end;
end;
end;
8;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_importev2.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_importev2.m
| 2,489 |
utf_8
|
741843995eba3b57df4e2670647f78ef
|
% pop_importev2() - merge a neuroscan EV2 file with input dataset
% (pop out window if no arguments).
%
% Usage:
% >> OUTEEG = pop_importev2( INEEG ); % pop-up window mode
% >> OUTEEG = pop_importev2( INEEG, filename);
%
% Inputs:
% INEEG - input EEGLAB data structure
% filename - file name
%
% Outputs:
% OUTEEG - EEGLAB data structure
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2007
% Copyright (C) 2007 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, command] = pop_importev2(EEG, filename);
command = '';
if nargin < 1
help pop_importev2;
return;
end;
if nargin < 2
% ask user
[filename, filepath] = uigetfile('*.*', 'Choose a EV2 file -- pop_importev2');
drawnow;
if filename == 0 return; end;
filename = fullfile(filepath, filename);
end;
% find out if there is a line to skip or not
% ------------------------------------------
fid = fopen(filename, 'r');
tmpl = fgetl(fid);
if isempty(findstr('ype', tmpl)), skipline = 0;
else skipline = 1;
end;
fclose(fid);
% load datas
% ----------
tmpevent = EEG.event;
try, oldeventlats = [ tmpevent.latency ]; catch, end;
EEG = pop_importevent(EEG, 'fields', { 'num' 'type' 'response' 'acc' 'RT' 'latency'}, ...
'skipline', skipline, 'timeunit', 1E-3, 'align', NaN, 'append', 'no', 'event', filename );
tmpevent = EEG.event;
neweventlats = [ tmpevent.latency ];
if ~exist('oldeventlats'), oldeventlats = neweventlats; end;
len = min(min(length(oldeventlats), length(neweventlats)), 10);
if mean(oldeventlats(1:len) - neweventlats(1:len)) > 1
error('Wrong alignment of ev2 file with data');
end;
command = sprintf('%s = pop_importev2(%s, %s);', inputname(1), inputname(1), filename);
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_biosig16ying.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_biosig16ying.m
| 10,593 |
utf_8
|
1831d74dfa6b0ab3c1f6991654a256c8
|
% pop_biosig() - import data files into EEGLAB using BIOSIG toolbox
%
% Usage:
% >> OUTEEG = pop_biosig; % pop up window
% >> OUTEEG = pop_biosig( filename, channels, type);
%
% Inputs:
% filename - [string] file name
%
% Optional inputs:
% 'channels' - [integer array] list of channel indices
% 'blockrange' - [min max] integer range of data blocks to import, in seconds.
% Entering [0 3] will import the first three blocks of data.
% Default is empty -> import all data blocks.
% 'ref' - [integer] channel index or index(s) for the reference.
% Reference channels are not removed from the data,
% allowing easy re-referencing. If more than one
% channel, data are referenced to the average of the
% indexed channels. WARNING! Biosemi Active II data
% are recorded reference-free, but LOSE 40 dB of SNR
% if no reference is used!. If you do not know which
% channel to use, pick one and then re-reference after
% the channel locations are read in. {default: none}
% 'rmeventchan' - ['on'|'off'] remove event channel after event
% extraction. Default is 'on'.
%
% Outputs:
% OUTEEG - EEGLAB data structure
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Oct. 29, 2003-
%
% Note: BIOSIG toolbox must be installed. Download BIOSIG at
% http://biosig.sourceforge.net
% Contact [email protected] for troubleshooting using BIOSIG.
% 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, command] = my_pop_biosig(filename, varargin);
EEG = [];
command = '';
if nargin < 1
% ask user
[filename, filepath] = uigetfile('*.*', 'Choose an BDF file -- pop_biosig()'); %%% this is incorrect in original version!!!!!!!!!!!!!!
drawnow;
if filename == 0 return; end;
filename = [filepath filename];
% open file to get infos
% ----------------------
disp('Reading data file header...');
dat = sopen(filename);
% special BIOSEMI
% ---------------
if strcmpi(dat.TYPE, 'BDF')
disp('We highly recommend that you choose a reference channel IF these are Biosemi data');
disp('(e.g., a mastoid or other channel). Otherwise the data will lose 40 dB of SNR!');
end;
uilist = { { 'style' 'text' 'String' 'Channel list (defaut all):' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'String' [ 'Data range (in seconds) to read (default all [0 ' int2str(dat.NRec) '])' ] } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'String' 'Extract event - cannot be unset (set=yes)' } ...
{ 'style' 'checkbox' 'string' '' 'value' 1 'enable' 'on' } {} ...
{ 'style' 'text' 'String' 'Import continuous data (set=yes)' 'value' 1} ...
{ 'style' 'checkbox' 'string' '' 'value' 0 } {} ...
{ 'style' 'text' 'String' 'Reference chan(s) indices - required for BIOSEMI' } ...
{ 'style' 'edit' 'string' '' } };
geom = { [3 1] [3 1] [3 0.35 0.5] [3 0.35 0.5] [3 1] };
result = inputgui( geom, uilist, 'pophelp(''pop_biosig'')', ...
'Load data using BIOSIG -- pop_biosig()');
if length(result) == 0 return; end;
% decode GUI params
% -----------------
options = {};
if ~isempty(result{1}), options = { options{:} 'channels' eval( [ '[' result{1} ']' ] ) }; end;
if ~isempty(result{2}), options = { options{:} 'blockrange' eval( [ '[' result{2} ']' ] ) }; end;
if length(result) > 2
if ~isempty(result{4}), options = { options{:} 'ref' eval( [ '[' result{4} ']' ] ) }; end;
if ~result{3}, options = { options{:} 'rmeventchan' 'off' }; end;
end;
else
options = varargin;
end;
% decode imput parameters
% -----------------------
g = finputcheck( options, { 'blockrange' 'integer' [0 Inf] [];
'channels' 'integer' [0 Inf] [];
'ref' 'integer' [0 Inf] [];
'rmeventchan' 'string' { 'on';'off' } 'on' }, 'pop_biosig');
if isstr(g), error(g); end;
% import data
% -----------
EEG = eeg_emptyset;
if ~isempty(g.channels)
dat = sopen(filename, 'r', g.channels,'OVERFLOWDETECTION:OFF');
else dat = sopen(filename, 'r', 0,'OVERFLOWDETECTION:OFF');
end
fprintf('Reading data in %s format...\n', dat.TYPE);
if ~isempty(g.blockrange)
newblockrange = g.blockrange;
newblockrange(2) = min(newblockrange(2), dat.NRec);
newblockrange = newblockrange*dat.Dur;
DAT=sread(dat, newblockrange(2)-newblockrange(1), newblockrange(1))';
else
DAT=sread(dat, Inf)';% this isn't transposed in original!!!!!!!!
newblockrange = [];
end
dat = sclose(dat);
% convert to seconds for sread
% ----------------------------
EEG.nbchan = size(DAT,1);
EEG.srate = dat.SampleRate(1);
EEG.data = DAT;
clear DAT;
% $$$ try % why would you do the following??????? JO
% $$$ EEG.data = EEG.data';
% $$$ catch,
% $$$ pack;
% $$$ EEG.data = EEG.data';
% $$$ end;
EEG.setname = sprintf('%s file', dat.TYPE);
EEG.comments = [ 'Original file: ' filename ];
EEG.xmin = 0;
if strcmpi(dat.TYPE, 'BDF') || strcmpi(dat.TYPE, 'EDF')
EEG.trials = 1;
EEG.pnts = size(EEG.data,2);
else
EEG.trials = dat.NRec;
EEG.pnts = size(EEG.data,2)/dat.NRec;
end
if isfield(dat, 'Label') & ~isempty(dat.Label)
EEG.chanlocs = struct('labels', cellstr(char(dat.Label)));
end
EEG = eeg_checkset(EEG);
% extract events % this part I totally revamped to work... JO
% --------------
disp('Extracting events from last EEG channel...');
EEG.event = [];
% $$$ startval = mode(EEG.data(end,:)); % my code
% $$$ for p = 2:size(EEG.data,2)-1
% $$$ [codeout] = code(EEG.data(end,p));
% $$$ if EEG.data(end,p) > EEG.data(end,p-1) & EEG.data(end,p) >= EEG.data(end,p+1)
% $$$ EEG.event(end+1).latency = p;
% $$$ EEG.event(end).type = bitand(double(EEG.data(end,p)-startval),255);
% $$$ end;
% $$$ end;
% lastout = mod(EEG.data(end,1),256);newevs = []; % andrey's code 8 bits
% codeout = mod(EEG.data(end,2),256);
% for p = 2:size(EEG.data,2)-1
% nextcode = mod(EEG.data(end,p+1),256);
% if codeout > lastout & codeout >= nextcode
% newevs = [newevs codeout];
% EEG.event(end+1).latency = p;
% EEG.event(end).type = codeout;
% end;
% lastout = codeout;
% codeout = nextcode;
% end;
%lastout = mod(EEG.data(end,1),256*256);newevs = []; % andrey's code 16 bits
%codeout = mod(EEG.data(end,2),256*256);
%for p = 2:size(EEG.data,2)-1
% nextcode = mod(EEG.data(end,p+1),256*256);
% if (codeout > lastout) & (codeout >= nextcode)
% newevs = [newevs codeout];
% EEG.event(end+1).latency = p;
% EEG.event(end).type = codeout;
% end;
% lastout = codeout;
% codeout = nextcode;
%end;
% Modifieded by Andrey (Aug.5,2008) to detect all non-zero codes:
thiscode = 0;lastcode=0;
for p = 1:size(EEG.data,2)-1
prevcode = thiscode;
thiscode = mod(EEG.data(end,p),256*256); % andrey's code - 16 bits
if (thiscode ~= 0) && (thiscode~=prevcode) && (thiscode~=lastcode) % fix to avoid repeated codes (per Ying's demand)
EEG.event(end+1).latency = p;
EEG.event(end).type = thiscode;
lastcode = thiscode;
end;
end;
if strcmpi(g.rmeventchan, 'on')
EEG.data(dat.BDF.Status.Channel,:) = [];
EEG.nbchan = size(EEG.data,1);
if ~isempty(EEG.chanlocs)
EEG.chanlocs(dat.BDF.Status.Channel,:) = [];
end;
end;
EEG = eeg_checkset(EEG, 'eventconsistency');
% $$$ if ~isempty(dat.EVENT)
% $$$ if isfield(dat, 'out') % Alois fix for event interval does not work
% $$$ if isfield(dat.out, 'EVENT')
% $$$ dat.EVENT = dat.out.EVENT;
% $$$ end;
% $$$ end;
% $$$ if ~isempty(newblockrange)
% $$$ interval(1) = newblockrange(1) * dat.SampleRate(1) + 1;
% $$$ interval(2) = newblockrange(2) * dat.SampleRate(1);
% $$$ else interval = [];
% $$$ end
% $$$ EEG.event = biosig2eeglabevent(dat.EVENT, interval); % Toby's fix
% $$$ if strcmpi(g.rmeventchan, 'on') & strcmpi(dat.TYPE, 'BDF') & isfield(dat, 'BDF')
% $$$ disp('Removing event channel...');
% $$$ EEG.data(dat.BDF.Status.Channel,:) = [];
% $$$ EEG.nbchan = size(EEG.data,1);
% $$$ if ~isempty(EEG.chanlocs)
% $$$ EEG.chanlocs(dat.BDF.Status.Channel,:) = [];
% $$$ end;
% $$$ end;
% $$$ EEG = eeg_checkset(EEG, 'eventconsistency');
% $$$ else
% $$$ disp('Warning: no event found. Events might be embeded in a data channel.');
% $$$ disp(' To extract events, use menu File > Import Event Info > From data channel');
% $$$ end;
% rerefencing
% -----------
if ~isempty(g.ref)
disp('Re-referencing...');
EEG.data = EEG.data - repmat(mean(EEG.data(g.ref,:),1), [size(EEG.data,1) 1]);
if length(g.ref) == size(EEG.data,1)
EEG.ref = 'averef';
end;
if length(g.ref) == 1
disp([ 'Warning: channel ' int2str(g.ref) ' is now zeroed (but still present in the data)' ]);
else
disp([ 'Warning: data matrix rank has decreased through re-referencing' ]);
end;
end;
% convert data to single if necessary
% -----------------------------------
EEG = eeg_checkset(EEG,'makeur'); % Make EEG.urevent field
EEG = eeg_checkset(EEG);
% history
% -------
if isempty(options)
command = sprintf('EEG = my_pop_biosig(''%s'');', filename);
else
command = sprintf('EEG = my_pop_biosig(''%s'', %s);', filename, vararg2str(options));
end;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_oldica.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_oldica.m
| 4,381 |
utf_8
|
22d0c16288409e669fd273afd79ec6f0
|
% eeg_oldica() - report, return or add to oldicaweights and oldicasphere
% stored in cell arrays in EEG.etc of an EEGLAB dataset
% Usage:
% >> eeg_oldica(EEG); % report number of stored oldicaweights
% >> [EEG,icaweights, icasphere] = eeg_oldica(EEG,N); % return matrices
% >> EEG = eeg_oldica(EEG,N,icaweights,icasphere); % add wts and sph
% % matrices to EEG.etc.icaweights and EEG.etc.icasphere
% Inputs:
% EEG - EEGLAB dataset structure
% nreturn - index of the oldicaweights and sphere to return {default: 1}
% icaweights - ICA weights matrix to store in EEG.etc.oldicaweights
% icasphere - ICA sphere matrix to store in EEG.etc.oldicasphere
% Outputs:
% icaweights - ICA unmixing matrix (e.g., EEG.icaweights)
% icasphere - ICA data sphering matrix (e.g., EEG.icasphere)
%
% See also: pop_runica()
%
% Author: Scott Makeig, SCCN/INC/UCSD, March 17, 2005
% Copyright (C) 2004 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
function [EEG,oldicaweights,oldicasphere] = eeg_oldica(EEG, nreturn,icaweights,icasphere)
if nargin< 1
help eeg_oldica
return
end
if ~isstruct(EEG)
error('EEG argument must be a dataset structure')
end
if ~isfield(EEG,'etc')
error('EEG.etc field not found - no old ICA weights in dataset');
end
if ~isfield(EEG.etc,'oldicaweights') & nargin < 3
error('EEG.etc.oldicaweights field not found - no old ICA weights in dataset');
elseif nargout < 2 & nargin < 3
if length(EEG.etc.oldicaweights) > 1
fprintf('EEG.etc.oldicaweights contains %d weight matrices\n',length(EEG.etc.oldicaweights));
EEG.etc.oldicaweights
else
fprintf('EEG.etc.oldicaweights contains %d weight matrix\n',length(EEG.etc.oldicaweights));
EEG.etc.oldicaweights
end
end
if ~isfield(EEG.etc,'oldicasphere') & nargin < 3
fprintf('EEG.etc.oldicasphere field not found - no old ICA sphere matrix in dataset');
elseif nargout < 2 & nargin < 3
fprintf('\n');
if length(EEG.etc.oldicasphere) > 1
fprintf('EEG.etc.oldicasphere contains %d weight matrices\n',length(EEG.etc.oldicasphere));
EEG.etc.oldicasphere
else
fprintf('EEG.etc.oldicasphere contains %d weight matrix\n',length(EEG.etc.oldicasphere));
EEG.etc.oldicasphere
end
fprintf('\n');
end
if nargin < 2
nreturn = 1;
elseif nargin < 3
if nreturn< 1
error('nreturn must be an oldicaweights index');
elseif length(EEG.etc.oldicaweights) < nreturn
fprintf('nreturn (%d) > number of stored oldicaweights (%d) ', nreturn,length(EEG.etc.oldicaweights));
error(' ');
end
end
if nargin > 4
error('too many arguments.\n');
end
if nargin > 2
if nargout > 0
fprintf('New EEG.etc.oldicaweights: ');
EEG.etc.oldicaweights = [EEG.etc.oldicaweights {icaweights}];
EEG.etc.oldicaweights
else
error('To update oldicaweights, at least one output required');
end
end
if nargin > 3
fprintf('New EEG.etc.oldicasphere: ');
EEG.etc.oldicasphere = [EEG.etc.oldicasphere {icasphere}];
EEG.etc.oldicasphere
end
if nargout > 1
% fprintf('\n');
oldicaweights = EEG.etc.oldicaweights{nreturn};
% fprintf('Stored oldicaweights matrix (%d) returned (%d,%d).\n',nreturn,size(oldicaweights,1),size(oldicaweights,2));
if length(EEG.etc.oldicasphere) >= nreturn
oldicasphere = EEG.etc.oldicasphere{nreturn};
% fprintf('Stored oldicasphere matrix (%d) returned (%d,%d).\n',nreturn,size(oldicasphere,1),size(oldicasphere,2));
else
oldicasphere = [];
% fprintf('No corresponding oldicasphere matrix; [] returned.\n');
end
% fprintf('\n');
end
return
|
github
|
ZijingMao/baselineeegtest-master
|
pop_plotdata.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_plotdata.m
| 6,983 |
utf_8
|
a050f0fb99538d1e30279c41241ba0b6
|
% pop_plotdata() - Plot average of EEG channels or independent components in
% a rectangular array. Else, (over)plot single trials.
% Usage:
% >> avg = pop_plotdata(EEG, typeplot, indices, trials, title, singletrials, ydir, ylimits);
%
% Inputs:
% EEG - Input dataset
% typeplot - Type data to plot (1=channels, 0=components) {Default:1}
% indices - Array of channels (or component) indices to plot
% {Default: all}
% trials - Array of trial indices. sum specific trials in the average
% {Default: all}
% title - Plot title. {Default: []}.
% singletrials - [0|1], Plot average or overplot single trials
% 0 plot average, 1 plot single trials {Default: 0}
% ydir - [1|-1] y-axis polarity (pos-up = 1; neg-up = -1)
% {def command line-> pos-up; def GUI-> neg-up}
% ylimits - [ymin ymax] plotting limits {default [0 0] -> data range}
%
% Outputs:
% avg - [matrix] Data average
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: plotdata(), eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% 03-08-02 add eeglab options -ad
% 03-18-02 added title -ad & sm
% 03-30-02 added single trial capacities -ad
function [sigtmp, com] = pop_plotdata(EEG, typeplot, indices, trials, plottitle, singletrials, ydir,ylimits);
ylimits = [0 0];% default ylimits = data range
% warning signal must be in a 3D form before averaging
sigtmp = [];
com = '';
if nargin < 1
help pop_plotdata;
return;
end;
if nargin < 2
typeplot = 1; % 1=signal; 0=component
end;
if exist('plottitle') ~= 1
plottitle = '';
end;
if nargin <3
if typeplot % plot signal channels
result = inputdlg2({ 'Channel number(s):' ...
'Plot title:' ...
'Vertical limits ([0 0]-> data range):' ...
}, ...
'Channel ERPs in rect. array -- pop_plotdata()', 1, ...
{['1:' int2str(EEG.nbchan)] [fastif(isempty(EEG.setname), '',[EEG.setname ' ERP'])] ['0 0'] }, ...
'pop_plotdata' );
else % plot components
result = inputdlg2({ 'Component number(s):' ...
'Plot title:' ...
'Vertical limits ([0 0]-> data range):' ...
}, ...
'Component ERPs in rect. array -- pop_plotdata()', 1, ...
{ ['1:' int2str(size(EEG.icawinv,2))] [fastif(isempty(EEG.setname), '',[EEG.setname ' ERP'])] ['0 0'] }, ...
'pop_plotdata' );
end;
if length(result) == 0 return; end;
indices = eval( [ '[' result{1} ']' ] );
plottitle = result{2};
singletrials = 0;
ylimits = eval( [ '[' result{3} ']' ] );
if length(ylimits) ~= 2
ylimits = [0 0]; % use default if 2 values not given
end
end;
if ~(exist('trials') == 1)
trials = 1:EEG.trials;
end;
if exist('plottitle') ~= 1
plottitle = '';
end;
if exist('singletrials') ~= 1
singletrials = 0;
end;
if EEG.trials > 1 & singletrials == 0
fprintf('Selecting trials and components...\n');
if typeplot == 1
sigtmp = nan_mean(EEG.data(indices,:,trials),3);
else
if isempty(EEG.icasphere)
error('no ICA data for this set, first run ICA');
end;
tmpdata = eeg_getdatact(EEG, 'component', indices, 'trialindices', trials);
fprintf('Averaging...\n');
sigtmp = nan_mean(tmpdata,3);
end;
else
if typeplot == 1
sigtmp = EEG.data(indices,:,trials);
else
if isempty(EEG.icasphere)
error('no ICA data for this set, first run ICA');
end;
sigtmp = eeg_getdatact(EEG, 'component', indices, 'trialindices', trials);
end;
end;
figure;
try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end;
if exist('YDIR') ~= 1
ydir = 1;
else
ydir = YDIR;
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%% make the plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
sigtmp = reshape( sigtmp, size(sigtmp,1), size(sigtmp,2)*size(sigtmp,3));
ymin = ylimits(1);
ymax = ylimits(2);
if ischar(ymin)
ymin = str2num(ymin);
ymax = str2num(ymax);
end
% com = sprintf('pop_plotdata(%s, %d, %s, [1:%d], ''%s'', %d, %d, [%f %f]);', ...
% inputname(1), typeplot, vararg2str(indices), EEG.trials, plottitle, singletrials,ydir,ymin,ymax);
% fprintf([com '\n']);
if ~isempty(EEG.chanlocs) && typeplot == 1
tmpchanlocs = EEG.chanlocs;
chanlabels = strvcat({ tmpchanlocs(indices).labels });
else
chanlabels = num2str(indices(:));
end;
plottopo( sigtmp, 'frames', EEG.pnts, 'limits', [EEG.xmin*1000 EEG.xmax*1000 ymin ymax], 'title', plottitle, 'chans', 1:size(sigtmp,1), 'ydir', ydir, 'channames', chanlabels);
%plotdata(sigtmp, EEG.pnts, [EEG.xmin*1000 EEG.xmax*1000 ymin ymax], plottitle, indices,0,0,ydir);
%
%%%%%%%%%%%%%%%%%%%%%%%%%% add figure title %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if typeplot == 1
set(gcf, 'name', 'Plot > Channel ERPs > In rect. array -- plotdata()');
else
set(gcf, 'name', 'Plot > Component ERPs > In rect. array -- plotdata()');
end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%% set y-axis direction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if exist('ydir') ~= 1
if exist('YDIR') ~= 1
ydir = 1; % default positive up
else
ydir = YDIR; % icadefs.m system-wide default
end
end
if ydir==1
set(gca,'ydir','normal');
else % ydir == -1
set(gca,'ydir','reverse');
end
switch nargin
case {0, 1, 2, 3}, com = sprintf('pop_plotdata(%s, %d, %s, [1:%d], ''%s'', %d, %d, [%g %g]);', inputname(1), typeplot, vararg2str(indices), EEG.trials, plottitle, singletrials,ydir,ymin,ymax);
case 4, com = sprintf('pop_plotdata(%s, %d, %s, %s, ''%s'', %d, %d, [%g %g]);', inputname(1), typeplot, vararg2str(indices), vararg2str(trials), plottitle, singletrials,ydir,ymin,ymax);
end;
fprintf([com '\n']);
return;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function out = nan_mean(in, dim)
tmpin = in;
tmpin(find(isnan(in(:)))) = 0;
out = sum(tmpin, dim) ./ sum(~isnan(in),dim);
|
github
|
ZijingMao/baselineeegtest-master
|
pop_eegfilt.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_eegfilt.m
| 9,360 |
utf_8
|
f64d8d0b36d5e7e5ac64782c3412bb38
|
% pop_eegfilt() - interactively filter EEG dataset data using eegfilt()
%
% Usage:
% >> EEGOUT = pop_eegfilt( EEG, locutoff, hicutoff, filtorder);
%
% Graphical interface:
% "Lower edge ..." - [edit box] Lower edge of the frequency pass band (Hz)
% Same as the 'locutoff' command line input.
% "Higher edge ..." - [edit box] Higher edge of the frequency pass band (Hz)
% Same as the 'hicutoff' command line input.
% "Notch filter" - [edit box] provide the notch range, i.e. [45 55]
% for 50 Hz). This option overwrites the low and high edge limits
% given above. Set the 'locutoff' and 'hicutoff' values to the
% values entered as parameters, and set 'revfilt to 1, to swap
% from bandpass to notch filtering.
% "Filter length" - [edit box] Filter lenghth in point (default: see
% >> help eegfilt). Same as 'filtorder' optional input.
%
% Inputs:
% EEG - input dataset
% locutoff - lower edge of the frequency pass band (Hz) {0 -> lowpass}
% hicutoff - higher edge of the frequency pass band (Hz) {0 -> highpass}
% filtorder - length of the filter in points {default 3*fix(srate/locutoff)}
% revfilt - [0|1] Reverse filter polarity (from bandpass to notch filter).
% Default is 0 (bandpass).
% usefft - [0|1] 1 uses FFT filtering instead of FIR. Default is 0.
% plotfreqz - [0|1] plot frequency response of filter. Default is 0.
% firtype - ['firls'|'fir1'] filter design method, default is 'firls'
% from the command line
% causal - [0|1] 1 uses causal filtering. Default is 0.
%
% Outputs:
% EEGOUT - output dataset
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% 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
% 01-25-02 reformated help & license -ad
function [EEG, com] = pop_eegfilt( EEG, locutoff, hicutoff, filtorder, revfilt, usefft, plotfreqz, firtype, causal)
com = '';
if nargin < 1
help pop_eegfilt;
return;
end;
if isempty(EEG(1).data)
disp('Pop_eegfilt() error: cannot filter an empty dataset'); return;
end;
% warning
% -------
if exist('filtfilt') ~= 2
disp('Warning: cannot find the signal processing toolbox');
disp(' a simple fft/inverse fft filter will be used');
usefft = 1;
end;
if nargin < 2
% which set to save
% -----------------
uilist = { ...
{ 'style' 'text' 'string' 'Lower edge of the frequency pass band (Hz)' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'string' 'Higher edge of the frequency pass band (Hz)' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'string' 'FIR Filter order (default is automatic)' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'checkbox' 'string' 'Notch filter the data instead of pass band' } ...
{ 'style' 'checkbox' 'string' 'Use (sharper) FFT linear filter instead of FIR filtering' 'value' 0 } ...
{ 'style' 'text' 'string' '(Use the option above if you do not have the Signal Processing Toolbox)' } ...
{ 'style' 'checkbox' 'string' 'Use causal filter (useful when performing causal analysis)' 'value' 0} ...
{ 'style' 'checkbox' 'string' 'Plot the filter frequency response' 'value' 0} ...
{ 'style' 'checkbox' 'string' 'Use fir1 (check, recommended) or firls (uncheck, legacy)' 'value' 1}};
geometry = { [3 1] [3 1] [3 1] 1 1 1 1 1 1 };
result = inputgui( 'geometry', geometry, 'uilist', uilist, 'title', 'Filter the data -- pop_eegfilt()', ...
'helpcom', 'pophelp(''pop_eegfilt'')');
if isempty(result), return; end;
if isempty(result{1}), result{1} = '0'; end;
if isempty(result{2}), result{2} = '0'; end;
locutoff = eval( result{1} );
hicutoff = eval( result{2} );
if isempty( result{3} )
filtorder = [];
else filtorder = eval( result{3} );
end;
revfilt = 0;
if result{4},
revfilt = 1;
if locutoff == 0 | hicutoff == 0,
error('Need both lower and higher edge for notch filter');
end;
end;
if result{5}
usefft = 1;
else usefft = 0;
end;
if result{6}
causal = 1;
else causal = 0;
end;
plotfreqz = result{7};
if locutoff == 0 & hicutoff == 0 return; end;
if result{8}
firtype = 'fir1';
else
firtype = 'firls';
end
else
if nargin < 3
hicutoff = 0;
end;
if nargin < 4
filtorder = [];
end;
if nargin < 5
revfilt = 0;
end;
if nargin < 6
usefft = 0;
end;
if nargin < 7
plotfreqz = 0;
end
if nargin < 8
firtype = 'firls';
end
if nargin < 8
causal = 0;
end
end;
if locutoff && hicutoff
disp('WARNING: BANDPASS FILTERS SOMETIMES DO NOT WORK (MATLAB BUG)')
disp('WARNING: PLOT SPECTRUM AFTER FILTERING TO ASSESS FILTER EFFICIENCY')
disp('WARNING: IF FILTER FAILS, LOWPASS DATA THEN HIGHPASS DATA')
end;
% process multiple datasets
% -------------------------
if length(EEG) > 1
[ EEG com ] = eeg_eval( 'pop_eegfilt', EEG, 'warning', 'on', 'params', ...
{ locutoff, hicutoff, filtorder, revfilt } );
return;
end;
options = { EEG.srate, locutoff, hicutoff, 0 };
if ~isempty( filtorder )
options = { options{:} filtorder };
else
options = { options{:} 0 };
end;
options = {options{:} revfilt firtype causal};
if EEG.trials == 1
if ~isempty(EEG.event) & isfield(EEG.event, 'type') & isstr(EEG.event(1).type)
tmpevent = EEG.event;
boundaries = strmatch('boundary', { tmpevent.type });
if isempty(boundaries)
if ~usefft
[EEG.data, b] = eegfilt( EEG.data, options{:});
else
EEG.data = eegfiltfft( EEG.data, options{1:6}); % 7/30/2014 Ramon: {:} to {1:6};
end;
else
options{4} = 0;
disp('Pop_eegfilt:finding continuous data boundaries');
tmplat = [ tmpevent.latency ];
boundaries = tmplat(boundaries);
boundaries = [0 floor(boundaries-0.49) EEG.pnts];
try, warning off MATLAB:divideByZero
catch, end;
for n=1:length(boundaries)-1
if boundaries(n)+1 < boundaries(n+1)
try
fprintf('Processing continuous data (%d:%d)\n',boundaries(n),boundaries(n+1));
if ~usefft
[EEG.data(:,boundaries(n)+1:boundaries(n+1)), b] = ...
eegfilt(EEG.data(:,boundaries(n)+1:boundaries(n+1)), options{:});
else
EEG.data(:,boundaries(n)+1:boundaries(n+1)) = ...
eegfiltfft(EEG.data(:,boundaries(n)+1:boundaries(n+1)), options{1:6}); % 7/30/2014 Ramon: {:} to {1:6};
end;
catch
fprintf('\nFilter error: continuous data portion too narrow (DC removed if highpass only)\n');
if locutoff ~= 0 & hicutoff == 0
tmprange = [boundaries(n)+1:boundaries(n+1)];
EEG.data(:,tmprange) = ...
EEG.data(:,tmprange) - repmat(mean(EEG.data(:,tmprange),2), [1 length(tmprange)]);
end;
end;
end;
end
try, warning on MATLAB:divideByZero
catch, end;
end
else
if ~usefft
[EEG.data, b] = eegfilt( EEG.data, options{:});
else
EEG.data = eegfiltfft( EEG.data, options{1:6}); % 7/30/2014 Ramon: {:} to {1:6};
end;
end;
else
EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts*EEG.trials);
options{4} = EEG.pnts;
if ~usefft
[EEG.data, b] = eegfilt( EEG.data, options{:});
else
EEG.data = eegfiltfft( EEG.data, options{1:6}); % 7/30/2014 Ramon: {:} to {1:6};
end;
% Note: reshape does not reserve new memory while EEG.data(:,:) does
end;
EEG.icaact = [];
if ~usefft & plotfreqz & exist('b') == 1
freqz(b, 1, [], EEG.srate);
end
com = sprintf( '%s = pop_eegfilt( %s, %s, %s, [%s], [%s], %s, %s, ''%s'', %d);', inputname(1), inputname(1), ...
num2str( locutoff), num2str( hicutoff), num2str( filtorder ), num2str( revfilt ), num2str(usefft), num2str(plotfreqz), firtype, causal);
return
|
github
|
ZijingMao/baselineeegtest-master
|
pop_subcomp.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_subcomp.m
| 6,379 |
utf_8
|
e7794fc9bf9ce6971db47be696beba06
|
% pop_subcomp() - remove specified components from an EEG dataset.
% and subtract their activities from the data. Else,
% remove components already marked for rejection.
% Usage:
% >> OUTEEG = pop_subcomp( INEEG ); % pop-up window mode
% >> OUTEEG = pop_subcomp( INEEG, components, confirm);
%
% Pop-up window interface:
% "Component(s) to remove ..." - [edit box] Array of components to
% remove from the data. Sets the 'components' parameter
% in the command line call (see below).
% "Component(s) to retain ..." - [edit box] Array of components to
% to retain in the data. Sets the 'components' parameter in
% the command line call. Then, comp_to_remove = ...
% setdiff([1:size(EEG.icaweights,1)], comp_to_keep)
% Overwrites "Component(s) to remove" (above).
% Command line inputs:
% INEEG - Input EEG dataset.
% components - Array of components to remove from the data. If empty,
% remove components previously marked for rejection (e.g.,
% EEG.reject.gcompreject).
% confirm - [0|1] Display the difference between original and processed
% dataset. 1 = Ask for confirmation. 0 = Do not ask. {Default: 0}
% Outputs:
% OUTEEG - output dataset.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: compvar()
% 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
% 02-15-02 propagate ica weight matrix -ad sm jorn
function [EEG, com] = pop_subcomp( EEG, components, plotag )
com='';
if nargin < 1
help pop_subcomp;
return;
end;
if nargin < 3
plotag = 0;
end;
if nargin < 2
% popup window parameters
% -----------------------
if ~isempty(EEG.reject.gcompreject)
components = find(EEG.reject.gcompreject == 1);
components = components(:)';
promptstr = { ['Component(s) to remove from the data ([] = marked comps.)'] };
%promptstr = { ['Components to subtract from data' 10 '(default: pre-labeled components to reject):'] };
else
components = [];
promptstr = { ['Component(s) to remove from data:'] };
end;
uilist = { { 'style' 'text' 'string' ['Component(s) to remove from data:'] } ...
{ 'style' 'edit' 'string' int2str(components) } ...
{ 'style' 'text' 'string' 'Component(s) to retain (overwrites "Component(s) to remove")' } ...
{ 'style' 'edit' 'string' '' } ...
};
geom = { [2 0.7] [2 0.7] };
result = inputgui( 'uilist', uilist, 'geometry', geom, 'helpcom', 'pophelp(''pop_subcomp'')', ...
'title', 'Remove components from data -- pop_subcomp()');
if length(result) == 0 return; end;
components = eval( [ '[' result{1} ']' ] );
if ~isempty(result{2}),
components = eval( [ '[' result{2} ']' ] );
components = setdiff_bc([1:size(EEG.icaweights,1)], components);
end;
end;
if isempty(components)
if ~isempty(EEG.reject.gcompreject)
components = find(EEG.reject.gcompreject == 1);
else
fprintf('Warning: no components specified, no rejection performed\n');
return;
end;
else
if (max(components) > size(EEG.icaweights,1)) || min(components) < 1
error('Component index out of range');
end;
end;
fprintf('Computing projection ....\n');
component_keep = setdiff_bc(1:size(EEG.icaweights,1), components);
compproj = EEG.icawinv(:, component_keep)*eeg_getdatact(EEG, 'component', component_keep, 'reshape', '2d');
compproj = reshape(compproj, size(compproj,1), EEG.pnts, EEG.trials);
%fprintf( 'The ICA projection accounts for %2.2f percent of the data\n', 100*varegg);
if nargin < 2 | plotag ~= 0
ButtonName = 'continue';
while ~strcmpi(ButtonName, 'Cancel') & ~strcmpi(ButtonName, 'Accept')
ButtonName=questdlg2( [ 'Please confirm. Are you sure you want to remove these components?' ], ...
'Confirmation', 'Cancel', 'Plot ERPs', 'Plot single trials', 'Accept', 'Accept');
if strcmpi(ButtonName, 'Plot ERPs')
if EEG.trials > 1
tracing = [ squeeze(mean(EEG.data(EEG.icachansind,:,:),3)) squeeze(mean(compproj,3))];
figure;
plotdata(tracing, EEG.pnts, [EEG.xmin*1000 EEG.xmax*1000 0 0], ...
'Trial ERPs (red) with and (blue) without these components');
else
warndlg2('Cannot plot ERPs for continuous data');
end;
elseif strcmpi(ButtonName, 'Plot single trials')
eegplot( EEG.data(EEG.icachansind,:,:), 'srate', EEG.srate, 'title', 'Black = channel before rejection; red = after rejection -- eegplot()', ...
'limits', [EEG.xmin EEG.xmax]*1000, 'data2', compproj);
end;
end;
switch ButtonName,
case 'Cancel',
disp('Operation cancelled');
return;
case 'Accept',
disp('Components removed');
end % switch
end;
EEG.data(EEG.icachansind,:,:) = compproj;
EEG.setname = [ EEG.setname ' pruned with ICA'];
EEG.icaact = [];
goodinds = setdiff_bc(1:size(EEG.icaweights,1), components);
EEG.icawinv = EEG.icawinv(:,goodinds);
EEG.icaweights = EEG.icaweights(goodinds,:);
EEG.specicaact = [];
EEG.specdata = [];
EEG.reject = [];
try,
EEG.dipfit.model = EEG.dipfit.model(goodinds);
catch, end;
com = sprintf('%s = pop_subcomp( %s, [%s], %d);', inputname(1), inputname(1), ...
int2str(components), plotag);
return;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_topoplot.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_topoplot.m
| 13,363 |
utf_8
|
f7a6fe417c1429baaee4201b16da5df0
|
% eeg_topoplot() - plot scalp map
%
% eeg_topoplot( vals, chanlocs, 'key', 'val');
%
% Input:
% vals - values, one per channel
% chanlocs - channel structure, same size as vals
%
% Optional inputs:
% 'colormap' - colormap. Possible colormaps are 'blueredyellow', ...
% 'yellowredblue', 'bluered' or any Matlab colormap ('cool',
% 'jet', 'hsv', ...). It can also be a text file 'xxx.txt'.
% The text file must contain 3 columns and idealy 64 rows
% defining the colors in RGB format.
% 'maplimits' - can be [min max]. This help defines the color scale for
% maps.
% 'electrodes' - can be 'on' to show electrode dots, 'off', or
% 'labels' to show electrode labels. Default is 'on'
% 'dotsize' - size of electrode dots. Default is 5.
% 'shading' - 'flat','interp' {default: 'interp'}
% 'exclude' - labels or indices of electrodes not to be plotted. From the
% compiled files, these must be entered using underscores
% for separators (e.g., "cz_pz").
% 'sphspline' - can be 'on' or 'off'. If 'on' spherical splines are used
% for interpolation of the scalp map. If 'off' standard
% planar inverse distance interpolation is used.
% 'shrink' - shrink electrode positions (default is 0.75 to be able to
% plot electrode at the head limit if spherical interpolation
% is set and 0.95 for planar 2-D interpolation).
%
% References for spline interpolation:
% [1] Perrin, F., Pernier, J., Bertrand, O., & Echallier, J. F.
% (1989). Spherical splines for scalp potential and current
% density mapping. Electroencephalography and Clinical
% Neurophysiology, 72, 184-187
% [2] Ferree, T. C. (2000). Spline Interpolation of the Scalp EEG.
% Retrieved March 26, 2006, from
% www.egi.com/Technotes/SplineInterpolation.pdf
%
% limitation: does not plot anything below the upper part of the head
% Copyright (C) Arnaud Delorme, SCCN, INC, 2010
%
% 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_topoplot(values, chanlocs, varargin);
g = [];
for index = 1:2:length(varargin)
g = setfield(g, varargin{index}, varargin{index+1});
end;
if ~isfield(g, 'electrodes'), g.electrodes = 'on'; end;
if ~isfield(g, 'colormap'), g.colormap = jet; end;
if ~isfield(g, 'maplimits'), g.maplimits = []; end;
if ~isfield(g, 'headrad'), g.headrad = []; end;
if ~isfield(g, 'sphspline'), g.sphspline = 'on'; end;
if ~isfield(g, 'shading'), g.shading = 'interp'; end;
if ~isfield(g, 'contour'), g.contour = 'on'; end;
if ~isfield(g, 'dotsize'), g.dotsize = 5; end;
if ~isfield(g, 'mark'), g.mark = []; end;
if ~isfield(g, 'exclude'), g.exclude = []; end;
if ~isfield(g, 'linewidth'), g.linewidth = 2; end;
if ~isfield(g, 'shrink'), g.shrink = 1; end;
if isstr(g.dotsize), g.dotsize = str2num(g.dotsize); end;
if any(values == 0)
inds = find(values == 0);
if ~isempty( [ chanlocs(inds).theta ])
g.contour = 'off';
g.sphspline = 'off';
end;
end;
% exclude electrodes
% ------------------
if ~isempty(g.exclude)
chanlocs(g.exclude) = [];
values(g.exclude) = [];
end;
% find channel coordinates
% ------------------------
emptyvals = cellfun('isempty', { chanlocs.theta });
th = [ chanlocs.theta ];
rd = [ chanlocs.radius ];
[y x] = pol2cart(th/180*pi, rd); x=-x;
x = x*g.shrink;
y = y*g.shrink;
newvalues = values;
newvalues(emptyvals) = [];
labls = { chanlocs.labels };
labls(emptyvals) = [];
if strcmpi(g.sphspline, 'on')
% default head radius
% -------------------
g.headrad = 0.5;
% spherical plotting
% ------------------
xelec = [ chanlocs.X ];
yelec = [ chanlocs.Y ];
zelec = [ chanlocs.Z ];
dist = sqrt(xelec.^2+yelec.^2+zelec.^2);
xelec = xelec./dist;
yelec = yelec./dist;
zelec = zelec./dist;
if g.shrink ~= 1
[th phi rad] = cart2sph(xelec, yelec, zelec);
phi = (phi-pi/2)*g.shrink+pi/2;
[xelec, yelec, zelec] = sph2cart(th, phi, rad);
end;
[xsph, ysph, zsph, valsph] = spheric_spline(xelec,yelec,zelec,newvalues);
surf(-ysph/2,xsph/2,zsph/2,double(valsph), 'edgecolor', 'none'); view([0 0 1]);hold on;
shading(g.shading);
top = max(abs(valsph(:)))*1000;
if strcmpi(g.contour, 'on')
[c h] = contour3(-ysph/2, xsph/2, valsph+top/10, 5); view([0 0 1]);
set(h, 'cdata', [], 'edgecolor', 'k')
end;
% coordinates for electrodes
% --------------------------
xelec(find(zelec < 0)) = [];
yelec(find(zelec < 0)) = [];
x = yelec/2;
y = xelec/2;
else
% default head radius
% -------------------
if isempty(g.headrad);
g.headrad = max(sqrt(x.^2+y.^2));
end;
% data points for 2-D data plot
% -----------------------------
pnts = linspace(0,2*pi,200/0.25*(g.headrad.^2));
xx = sin(pnts)*g.headrad;
yy = cos(pnts)*g.headrad;
% make grid and add circle
% ------------------------
gridres = 30;
coords = linspace(-g.headrad, g.headrad, gridres);
ay = repmat(coords, [gridres 1]);
ax = repmat(coords', [1 gridres]);
for ind=1:length(xx)
[tmp closex] = min(abs(xx(ind)-coords));
[tmp closey] = min(abs(yy(ind)-coords));
ax(closex,closey) = xx(ind);
ay(closex,closey) = yy(ind);
end;
xx2 = sin(pnts)*(g.headrad-0.01);
yy2 = cos(pnts)*(g.headrad-0.01);
for ind=1:length(xx)
[tmp closex] = min(abs(xx2(ind)-coords));
[tmp closey] = min(abs(yy2(ind)-coords));
ax(closex,closey) = xx(ind);
ay(closex,closey) = yy(ind);
end;
% linear interpolation and removal of values outside circle
% ---------------------------------------------------------
a = griddata(x, y, newvalues, -ay, ax, 'v4');
aradius = sqrt(ax.^2 + ay.^2);
indoutcircle = find(aradius(:) > g.headrad+0.01);
a(indoutcircle) = NaN;
surf(ay, ax, a, 'edgecolor', 'none'); view([0 0 1]); hold on;
shading(g.shading);
top = max(values)*1.5;
% plot level lines
% ----------------
if strcmpi(g.contour, 'on')
[c h] = contour3(ay, ax, a, 5);
set(h, 'cdata', [], 'edgecolor', 'k')
end;
end;
% plot electrodes as dots
% -----------------------
if strcmpi(g.electrodes, 'on') | strcmpi(g.electrodes, 'labels')
rad = sqrt(x.^2 + y.^2);
x(find(rad > g.headrad)) = [];
y(find(rad > g.headrad)) = [];
plot3( -x, y, ones(size(x))*top, 'k.', 'markersize', g.dotsize);
for i = g.mark, plot3( -x(i), y(i), double(top), 'y.', 'markersize', 4*g.dotsize); plot3( -x(i), y(i), double(top), 'r.', 'markersize', 2*g.dotsize); end;
if strcmpi(g.electrodes, 'labels')
for index = 1:length(x)
text( -x(index)+0.02, y(index), double(top), labls{index});
end;
end;
else
% invisible electrode that avoid plotting problem (no surface, only
% contours)
plot3( -x, y, -ones(size(x))*top, 'k.', 'markersize', 0.001);
end;
% plot dipoles if any
% -------------------
if ~isempty(g.dipole)
hold on;
for index = 1:size(g.dipole,1)
g.dipole(index,:) = g.dipole(index,:)*0.5;
g.dipole(index,3:5) = g.dipole(index,3:5)/norm(g.dipole(index,3:end))*0.2;
if ~any(g.dipole(index,:))
fprintf('Note: dipole contains 0 - not plotted\n')
elseif sum(g.dipole(index,3:4).^2) <= 0.00001
fprintf('Note: dipole is length 0 - not plotted\n')
elseif sum(g.dipole(index,1:2).^2) > g.headrad
fprintf('Note: dipole is outside plotting area - not plotted\n')
else
hh = plot3( -g.dipole(index, 2), g.dipole(index, 1), top, '.');
set(hh, 'color', 'k', 'markersize', 30);
hh = line( -[g.dipole(index, 2) g.dipole(index, 2)+g.dipole(index, 4)]', ...
[g.dipole(index, 1) g.dipole(index, 1)+g.dipole(index, 3)]',[top top]);
set(hh, 'color', 'k', 'linewidth', 30/7);
end;
end;
end;
% special colormaps
% -----------------
if isstr(g.colormap)
if ~isempty(strmatch(g.colormap, { 'hsv' 'jet' 'gray' 'hot' 'cool' 'bone' ...
'copper', 'pink' 'flag' 'prism' }, 'exact'))
else % read text file
g.colormap = load('-ascii', g.colormap);
end;
end;
colormap(g.colormap);
if ~isempty(g.maplimits)
if ~isstr(g.maplimits) && ~isempty(g.maplimits) && ~isnan(g.maplimits(1))
caxis(g.maplimits);
end;
end;
% main circle
% -----------
radiuscircle = 0.5;
pnts = linspace(0,2*pi,200);
xc = sin(pnts)*radiuscircle;
yc = cos(pnts)*radiuscircle;
sf = 1; % scaling factor
plot3(xc*sf,yc*sf,ones(size(xc))*top, 'k', 'linewidth', g.linewidth); hold on;
% ears & nose
% -----------
rmax = 0.5;
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];
plot3(EarX*sf,EarY*sf,ones(size(EarX))*top,'color','k','LineWidth',g.linewidth) % plot left ear
plot3(-EarX*sf,EarY*sf,ones(size(EarY))*top,'color','k','LineWidth',g.linewidth) % plot right ear
plot3([basex;tiphw;0;-tiphw;-basex]*sf,[base;tip-tipr;tip;tip-tipr;base]*sf,top*ones(size([basex;tiphw;0;-tiphw;-basex])),'color','k','LineWidth',g.linewidth);
% axis limits
% -----------
axis off;
set(gca, 'ydir', 'normal');
axis equal
ylimtmp = max(g.headrad, 0.58);
ylim([-ylimtmp ylimtmp]);
% ----------------
% spherical spline
% ----------------
function [x, y, z, Res] = spheric_spline( xelec, yelec, zelec, values);
SPHERERES = 40;
[x,y,z] = sphere(SPHERERES);
x(1:(length(x)-1)/2,:) = [];
y(1:(length(x)-1)/2,:) = [];
z(1:(length(x)-1)/2,:) = [];
Gelec = computeg(xelec,yelec,zelec,xelec,yelec,zelec);
Gsph = computeg(x,y,z,xelec,yelec,zelec);
% equations are
% Gelec*C + C0 = Potential (C unknow)
% Sum(c_i) = 0
% so
% [c_1]
% * [c_2]
% [c_ ]
% xelec [c_n]
% [x x x x x] [potential_1]
% [x x x x x] [potential_ ]
% [x x x x x] = [potential_ ]
% [x x x x x] [potential_4]
% [1 1 1 1 1] [0]
% compute solution for parameters C
% ---------------------------------
meanvalues = mean(values);
values = values - meanvalues; % make mean zero
C = pinv([Gelec;ones(1,length(Gelec))]) * [values(:);0];
% apply results
% -------------
Res = zeros(1,size(Gsph,1));
for j = 1:size(Gsph,1)
Res(j) = sum(C .* Gsph(j,:)');
end
Res = Res + meanvalues;
Res = reshape(Res, size(x));
% compute G function
% ------------------
function g = computeg(x,y,z,xelec,yelec,zelec)
unitmat = ones(length(x(:)),length(xelec));
EI = unitmat - ((repmat(x(:),1,length(xelec)) - repmat(xelec,length(x(:)),1)).^2 +...
(repmat(y(:),1,length(xelec)) - repmat(yelec,length(x(:)),1)).^2 +...
(repmat(z(:),1,length(xelec)) - repmat(zelec,length(x(:)),1)).^2)/2;
g = zeros(length(x(:)),length(xelec));
m = 4; % 3 is linear, 4 is best according to Perrin's curve
for n = 1:7
L = legendre(n,EI);
g = g + ((2*n+1)/(n^m*(n+1)^m))*squeeze(L(1,:,:));
end
g = g/(4*pi);
% find electrode indices
% ----------------------
function allinds = elecind( str, chanlocs, values );
findmax = 0;
findmin = 0;
if ~iscell(str)
if strmatch(str, 'max', 'exact'), findmax = 1; end;
if strmatch(str, 'min', 'exact'), findmin = 1; end;
indunderscore = [ 0 find( str == '_' ) length(str)+1 ];
else indunderscore = [1:length(str)+1];
end;
% find maximum or minimum
% -----------------------
if findmax, [tmp allinds] = max(values); return; end;
if findmin, [tmp allinds] = min(values); return; end;
% find indices for labels
% -----------------------
labels = lower({ chanlocs.labels });
for i = 1:length(indunderscore)-1
if ~iscell(str)
tmpstr = str(indunderscore(i)+1:indunderscore(i+1)-1);
else tmpstr = str{i};
end;
tmpind = strmatch(lower(tmpstr), labels, 'exact');
if isempty(tmpind)
if str2num(tmpstr) > 0
tmpind = str2num(tmpstr);
else
error(sprintf('Could not find channel "%s"', tmpstr));
end;
end;
allinds(i) = tmpind;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_pvaf.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_pvaf.m
| 9,554 |
utf_8
|
0e527313c0a1dda9713e3cc25f465861
|
% eeg_pvaf() - Compute EEG.data 'percent variance accounted for' (pvaf) by specified components.
% Can omit specified components and channels from the computation. Can draw a plot
% of the scalp distribution of pvaf, or progressively compute the pvaf for comps
% 1:k, where k = 1 -> the total number of components. Note: pvaf's of spatially
% non-orthogonal independent components may not add to 100%, and individual component
% pvaf could be < 0%.
% Usage:
% >> [pv] = eeg_pvaf(EEG,comps);s
% >> [pvaf,pvafs,vars] = eeg_pvaf(EEG, comps,'key', val);
% Inputs:
% EEG - EEGLAB dataset. Must have icaweights, icasphere, icawinv, icaact.
% comps - vector of component indices to sum {default|[] -> progressive mode}
% In progressive mode, comps is first [1], then [1 2], etc. up to
% [1:size(EEG.icaweights,2)] (all components); here, the plot shows pvaf.
%
% Optional inputs:
% 'artcomps' - [integer] vector of artifact component indices to remove from data before
% computing pvaf {default|[]: none}
% 'omitchans' - [integer] channels to omit from the computation (e.g. off-head, etc)
% {default|[]: none}
% 'chans' - [integer] only compute pvaf at selected channels. Overwrite omitchans above.
% 'fraction' - [0<real<=1] fraction of the data to randomly select {default|[]: 1=all}
% 'plot' - ['on'|'off'] Plot scalp map of channel pvafs. {default: Plot only if no
% output arguments}
%
% Outputs:
% pvaf - (real) percent total variance accounted for by the summed back-projection of
% the requested components. If comps is [], a vector of pvafs for the sum of
% components 1:k (k=1:ncomps).
% pvafs - (real vector) percent variance accounted for by the summed back-projection of
% the requested components to each data channel. If comps is [], a matrix of
% pvafs (as for pv above).
% vars - variances of the requested channels
%
% Fields:
% Assumes existence of the following EEG fiels: EEG.data, EEG.pnts, EEG.nbchan, EEG.trials,
% EEG.icaact, EEG.icaweights, EEG.icasphere, EEG.icawinv, and for plot, EEG.chanlocs
%
% Author: Scott Makeig & Arnaud Delorme, SCCN, INC, UCSD, Fri Feb 13, 2004
% Copyright (C) 2004- Scott Makeig & 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
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [pvaf,pvafs,pvall] = eeg_pvaf(EEG,comps, varargin)
if nargin < 1
help eeg_pvaf
return
end
g = finputcheck(varargin, { 'artcomps' 'integer' [] [];
'omitchans' 'integer' [] [];
'chans' 'integer' [] [];
'fraction' 'real' [] 1;
'plot' 'string' { 'on';'off';'def' } 'def' }, 'eeg_pvaf');
if isstr(g), error(g); end;
numcomps = size(EEG.icaact,1);
if round(g.fraction*EEG.pnts*EEG.trials)<1
error('g.fraction of data specified too small.')
return
end
if strcmpi(g.plot, 'def')
if nargout > 0, g.plot = 'on';
else g.plot = 'off';
end;
end
numchans = EEG.nbchan;
chans = 1:numchans;
if ~isempty(g.chans)
g.omitchans = setdiff_bc([1:EEG.nbchan], g.chans);
end;
if ~isempty(g.omitchans)
if max(g.omitchans)>numchans
help eeg_pvaf
error('at least one channel to omit > number of channels in data');
end
if min(g.omitchans)<1
help eeg_pvaf
error('channel numbers to omit must be > 0');
end
chans(g.omitchans) = [];
end
progressive = 0; % by default, progressive mode is off
if nargin < 2 | isempty(comps)|comps==0
comps = [];
progressive = 1; % turn progressive mode on
end
if isempty(EEG.icaweights)
help eeg_pvaf
return
end
if isempty(EEG.icasphere)
help eeg_pvaf
return
end
if isempty(EEG.icawinv)
EEG.icawinv = pinv(EEG.icaweights*EEG.icasphere);
end
if isempty(EEG.icaact)
help eeg_pvaf
fprintf('EEG.icaact not present.\n');
% EEG.icaact = EEG.icaweights*EEG.icasphere*EEG.data; % remake it like this
end
if max(comps) > size(EEG.icawinv,1)
help eeg_pvaf
fprintf('Only %d components in this dataset. Cannot project component %d.\n',numcomps,max(comps));
error('bad comps input');
end
if ~isempty(g.artcomps) & max(g.artcomps) > numcomps
help eeg_pvaf
fprintf('Only %d components in this dataset. Cannot project artcomp %d.\n',numcomps,max(g.artcomps));
error('bad artcomps input')
end
npts = EEG.trials*EEG.pnts;
allcomps = 1:numcomps;
if progressive
fprintf('Considering components up to: ');
cum_pvaf = zeros(1,numcomps);
cum_pvafs = zeros(numcomps,numchans);
end
for comp = 1:numcomps %%%%%%%%%%%%%%% progressive mode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if progressive
comps = allcomps(1:comp); % summing components 1 to current comp
fprintf('%d ',comp)
end
if ~isempty(g.artcomps)
[a b c] = intersect_bc(g.artcomps,comps);
if ~isempty(a)
if ~progressive
if length(a)>1
fprintf('eeg_pvaf(): not back-projecting %d comps already in the artcomps.\n',length(c));
else
fprintf('eeg_pvaf(): not back-projecting comp %d already in the artcomps.\n',comps(c));
end
end
comps(c) = [];
end
end
if ~isempty(g.artcomps) & min([comps g.artcomps]) < 1
error('comps and artcomps must contain component indices');
end
%
%%%%%%%%%%%%%%%%%%%%%%%% compute variance accounted for by specified components %%%%%%%%%%%%%
%
if ~progressive | comp == 1 % pare out g.omitchans and artcomps from EEG.data
if ~isempty(g.artcomps)
EEG.data = EEG.data(chans,:) - EEG.icawinv(chans,g.artcomps)*EEG.icaact(g.artcomps,:);
else
EEG.data = EEG.data(chans,:);
end
nsel = round(g.fraction*npts);
varpts = randperm(npts);
varwts = ones(size(varpts));
if nsel<npts
varwts(varpts(nsel+1:npts)) = 0;
end
pvall = var(EEG.data(:,:)',varwts);
end
pvdiff = var((EEG.data(:,:) - EEG.icawinv(chans,comps)*EEG.icaact(comps,:))', varwts);
%
%%%%%%%%%%%%%%%%%%%%%%%% compute percent variance accounted for %%%%%%%%%%%%%%%
%
pvafs = pvdiff ./ pvall;
pvafs = 100-100*pvafs;
pvaf = sum(pvdiff) ./ sum(pvall);
pvaf = 100-100*pvaf;
if ~progressive
break
else
cum_pvaf(comp) = pvaf;
cum_pvafs(comp,:) = pvafs;
end
end %%%%%%%%%%%%%% end progressive forloop %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if progressive % output accumulated results
fprintf('\n');
pvaf = cum_pvaf;
pvafs = cum_pvafs;
if strcmpi(g.plot, 'on');
plot(1:numcomps,pvaf);
xl = xlabel('Components Included (1:n)');
yl = ylabel('Percent Variance Accounted For (pvaf)');
set(xl,'fontsize',15);
set(yl,'fontsize',15);
set(gca,'fontsize',14);
end
elseif strcmpi(g.plot, 'on')
%
%%%%%%%%%%%%%%%%%%%%%%%% plot the scalp distribtion of pvaf %%%%%%%%%%%%%
%
if isfield(EEG,'chanlocs')
chanlocs = EEG.chanlocs;
if ~isempty(g.omitchans)
chanlocs(g.omitchans) = [];
end
if length(chanlocs) > 1
topoplot(pvafs',chanlocs); % plot pvaf here
end;
if length(comps)>5 % add text legend
if length(g.artcomps)>3
tlstr=sprintf('Pvaf by %d comps in data minus %d comps',length(comps),length(g.artcomps));
elseif isempty(g.artcomps)
tlstr=sprintf('Pvaf by %d comps in data',length(comps));
elseif length(g.artcomps)==1 % < 4 g.artcomps, list them
tlstr=sprintf('Pvaf by %d comps in data (less comp ',length(comps));
tlstr = [tlstr sprintf('%d ',g.artcomps) ')'];
else
tlstr=sprintf('Pvaf by %d comps in data (less comps ',length(comps));
tlstr = [tlstr sprintf('%d ',g.artcomps) ')'];
end
else % < 6 comps, list them
if length(comps)>1
tlstr=sprintf('Pvaf by comps ');
else
tlstr=sprintf('Pvaf by comp ');
end
if length(g.artcomps)>3
tlstr = ...
[tlstr sprintf('%d ',comps) sprintf('in data minus %d comps',length(comps),length(g.artcomps))];
else
if isempty(g.artcomps)
tlstr = [tlstr sprintf('%d ',comps) 'in data'];
elseif length(g.artcomps)==1
tlstr = [tlstr sprintf('%d ',comps) 'in data (less comp '];
tlstr = [tlstr int2str(g.artcomps) ')'];
else
tlstr = [tlstr sprintf('%d ',comps) 'in data (less comps '];
tlstr = [tlstr sprintf('%d ',g.artcomps) ')'];
end
end
end
tl=title(tlstr);
if max(pvafs)>100,
maxc=max(pvafs)
else
maxc=100;
end;
pvstr=sprintf('Total pvaf: %3.1f%%',pvaf);
tx=text(-0.9,-0.6,pvstr);
caxis([-100 100]);
cb=cbar('vert',33:64,[0 100]); % color bar showing >0 (green->red) only
else
fprintf('EEG.chanlocs not found - not plotting scalp pvaf\n');
end
end % end plot
|
github
|
ZijingMao/baselineeegtest-master
|
pop_copyset.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_copyset.m
| 2,501 |
utf_8
|
5ff586e542073596297cfaa0cb6d2da0
|
% pop_copyset() - Copy the current EEG dataset into another dataset.
%
% Usage:
% >> ALLEEG = pop_copyset(ALLEEG, index1); % pop-up
% >> [ ALLEEG EEG CURRENTSET ] = pop_copyset(ALLEEG, index1, index2 );
%
% Inputs:
% ALLEEG - array of dataset structure
% index1 - input dataset number
% index2 - index of dataset to copy into
%
% Inputs:
% ALLEEG - array of dataset structures
% EEG - new copied structure
% CURRENTSET - index of the new dataset
%
% Note: this function performs ALLEEG(index2) = ALLEEG(index1);
% with dataset checks
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeg_store(), pop_delset(), 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
function [ALLEEG, EEG, CURRENTSET, com] = pop_copyset(ALLEEG, set_in, set_out);
com = '';
if nargin < 2
help pop_copyset;
return;
end;
if isempty(ALLEEG)
error(['Pop_copyset error: cannot copy' 10 'single dataset mode']);
end;
if set_in == 0
error('Pop_copyset error: cannot copy dataset'); return;
end;
if isempty(ALLEEG(set_in).data)
error('Pop_copyset error: cannot copy empty dataset'); return;
end;
if nargin < 3
% which set to save
% -----------------
promptstr = { 'Index of the new dataset:'};
inistr = { int2str(set_in+1) };
result = inputdlg2( promptstr, 'Copy dataset -- pop_copyset()', 1, inistr, 'pop_copyset');
if size( result ) == 0, EEG = []; CURRENTSET = 0; return; end;
set_out = eval( result{1} );
end;
ALLEEG = eeg_store(ALLEEG, eeg_retrieve(ALLEEG, set_in), set_out);
EEG = eeg_retrieve(ALLEEG, set_out);
CURRENTSET = set_out;
com = sprintf('[ALLEEG EEG CURRENTSET] = pop_copyset( %s, %d, %d);', inputname(1), set_in, set_out);
return;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_chaninds.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_chaninds.m
| 2,367 |
utf_8
|
2def40fab41159484d7bd8502397d5a6
|
% std_chaninds() - look up channel indices in a EEG structure
%
% Usage:
% >> inds = std_chaninds(EEG, channames);
% Inputs:
% EEG - EEG structure containing a chanlocs substructure.
% the chanlocs structure may also be used as input.
% channames - [cell] channel names. May also be a string containing
% one or several channel names.
%
% Outputs:
% inds - [integer array] channel indices
%
% Author: Arnaud Delorme, CERCO, 2009-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function finalinds = eeg_chaninds(EEG, channames, errorifnotfound);
if nargin < 2
help eeg_chaninds;
return;
end;
if nargin < 3
errorifnotfound = 1;
end;
if isfield(EEG, 'chanlocs')
chanlocs = EEG.chanlocs;
else chanlocs = EEG;
end;
% decode string if necessary
% --------------------------
if isstr(channames)
channames = parsetxt( channames );
end;
finalinds = [];
if isempty(chanlocs)
tmpallchans = [];
else tmpallchans = lower({ chanlocs.labels });
end;
if isempty(channames), finalinds = [1:length(chanlocs)]; return; end;
for c = 1:length(channames)
chanind = strmatch( lower(channames{c}), tmpallchans, 'exact');
if isempty(chanind),
chanind = str2double(channames{c});
if isnan(chanind), chanind = []; end;
if errorifnotfound && isempty(chanind)
error(sprintf('Channel %s not found', channames{c}));
end;
end;
finalinds = [ finalinds chanind ];
end;
finalinds = sort(finalinds);
|
github
|
ZijingMao/baselineeegtest-master
|
pop_readegi.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_readegi.m
| 8,591 |
utf_8
|
2f7b99d9be1290f1e4f5c78dd01815da
|
% pop_readegi() - load a EGI EEG file (pop out window if no arguments).
%
% Usage:
% >> EEG = pop_readegi; % a window pops up
% >> EEG = pop_readegi( filename );
% >> EEG = pop_readegi( filename, datachunks, forceversion, fileloc);
%
% Inputs:
% filename - EGI file name
% datachunks - desired frame numbers (see readegi() help)
% option available from the command line only
% forceversion - [integer] force reading a specfic file version
% fileloc - [string] channel location file name. Default is
% 'auto' (autodetection)
%
% Outputs:
% EEG - EEGLAB data structure
%
% Author: Arnaud Delorme, CNL / Salk Institute, 12 Nov 2002
%
% See also: eeglab(), readegi(), readegihdr()
% 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, command] = pop_readegi(filename, datachunks, forceversion, fileloc);
EEG = [];
command = '';
if nargin < 4, fileloc = 'auto'; end;
disp('Warning: This function can only import continuous files or');
disp(' epoch files with only one length for data epochs');
if nargin < 1
% ask user
[filename, filepath] = uigetfile('*.RAW;*.raw', ...
'Choose an EGI RAW file -- pop_readegi()');
drawnow;
if filename == 0 return; end;
filename = [filepath filename];
fid = fopen(filename, 'rb', 'b');
if fid == -1, error('Cannot open file'); end
head = readegihdr(fid); % read EGI file header
fclose(fid);
if head.segments ~= 0
fileloc = '';
floc = { 'GSN-HydroCel-32.sfp' 'GSN65v2_0.sfp' 'GSN129.sfp' 'GSN-HydroCel-257.sfp'};
switch head.nchan
case { 32 33 }, fileloc = floc;
case { 64 65 }, fileloc = {floc{2} floc{3:4} floc{1}};
case { 128 129 }, fileloc = {floc{3} floc{4} floc{1:2}};
case { 256 257 }, fileloc = {floc{4} floc{1:3}};
end;
uilist = { { 'style' 'text' 'string' sprintf('Segment/frame number (default: 1:%d)', head.segments) } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'string' 'Channel location file (in eeglab/sample_locs)' } ...
{ 'style' 'popupmenu' 'string' fileloc } ...
{ } ...
{ 'style' 'text' 'string' ...
[ 'Note: Choosing the correct electrode location file for your data is critical.' 10 ...
'Note that in some cases none of the channel location files listed will correspond' 10 ...
'to your montage as EGI has different versions of caps and is creating new ones' 10 ...
'constantly. Remember to check your montage in the channel editor and import. Channel' 10 ...
'location files are stored in the sample_locs sub-folder of the EEGLAB distribution.' ] } };
uigeometry = { [2 1] [2 1] [1] [1] };
uigeomvert = [1 1 1.5 3];
result = inputgui('uilist', uilist, 'geometry', uigeometry, 'geomvert', uigeomvert);
% promptstr = { sprintf('Segment/frame number (default: 1:%d)', head.segments) 'Channel location file (in eeglab/sample_locs)' };
% inistr = { '' fileloc(res{2})};
% result = inputdlg2( promptstr, 'Import EGI file -- pop_readegi()', 1, inistr, 'pop_readegi');
if length(result) == 0 return; end;
datachunks = eval( [ '[' result{1} ']' ] );
fileloc = char(fileloc(result{2}));
else
datachunks = [];
disp('Only one segment, cannot read portion of the file');
end;
end;
% load data
% ----------
EEG = eeg_emptyset;
if exist('datachunks') && exist('forceversion') && ~isempty(forceversion)
[Head EEG.data Eventdata SegCatIndex] = readegi( filename, datachunks,forceversion);
elseif exist('forceversion') && ~isempty(forceversion)
[Head EEG.data Eventdata SegCatIndex] = readegi( filename,[],forceversion);
elseif exist('datachunks')
[Head EEG.data Eventdata SegCatIndex] = readegi( filename, datachunks);
forceversion = [];
else
[Head EEG.data Eventdata SegCatIndex] = readegi( filename);
forceversion = [];
end
if ~isempty(Eventdata) & size(Eventdata,2) == size(EEG.data,2)
EEG.data(end+1:end+size(Eventdata,1),:) = Eventdata;
end;
EEG.comments = [ 'Original file: ' filename ];
EEG.setname = 'EGI file';
EEG.nbchan = size(EEG.data,1);
EEG.srate = Head.samp_rate;
EEG.trials = Head.segments;
EEG.pnts = Head.segsamps;
EEG.xmin = 0;
% importing the events
% --------------------
EEG = eeg_checkset(EEG);
if ~isempty(Eventdata)
orinbchans = EEG.nbchan;
for index = size(Eventdata,1):-1:1
EEG = pop_chanevent( EEG, orinbchans-size(Eventdata,1)+index, 'edge', 'leading', ...
'delevent', 'off', 'typename', Head.eventcode(index,:), ...
'nbtype', 1, 'delchan', 'on');
Head.eventcode(end,:) = [];
end;
% renaming event codes
% --------------------
try,
tmpevent = EEG.event;
alltypes = { tmpevent.type };
if isstr(alltypes{1})
indepoc = strmatch('epoc', lower(alltypes), 'exact');
indtim = strmatch('tim0', lower(alltypes), 'exact');
% if epoc but no tim0 then epoc represent pauses in recording
if isempty(indtim) & ~isempty(indepoc)
for index = indepoc
EEG.event(index).type = 'boundary';
end;
end;
% other wise if both non-empty data epochs
if ~isempty(indtim) & ~isempty(indepoc)
if rem(size(EEG.data,2) / (length(indepoc)+1),1) == 0
EEG.event(index) = []; % remove epoch events
EEG.trials = length(indepoc)+1;
else
disp('Warning: data epochs detected but wrong data size');
end;
end;
end;
catch, disp('Warning: event renaming failed'); end;
end;
% adding segment category indices
% -------------------------------
if ~isempty(SegCatIndex) && EEG.trials > 1
try
if ~isempty(EEG.event)
for index = 1:length(EEG.event)
EEG.event(index).category = Head.catname{SegCatIndex(EEG.event(index).epoch)};
end;
else % create time-locking events
for trial = 1:EEG.trials
EEG.event(trial).epoch = trial;
EEG.event(trial).type = 'TLE';
EEG.event(trial).latency = -EEG.xmin*EEG.srate+1+(trial-1)*EEG.pnts;
EEG.event(trial).category = Head.catname{SegCatIndex(trial)};
end;
end;
catch,
disp('Warning: error while importing trial categories');
EEG.event = rmfield(EEG.event, 'category');
end;
end;
EEG = eeg_checkset(EEG, 'makeur');
EEG = eeg_checkset(EEG, 'eventconsistency');
% importing channel locations
% ---------------------------
if nargin < 1
warndlg2( [ 'EEGLAB will now import a default electrode location file' 10 ...
'for your data. Note that this might not correspond' 10 ...
'to your montage as EGI has different versions of caps.' 10 ...
'Check your montage in the channel editor and import' 10 ...
'the correct location file if necessary.' ]);
end;
if all(EEG.data(end,1:10) == 0)
disp('Deleting empty data reference channel (reference channel location is retained)');
EEG.data(end,:) = [];
EEG.nbchan = size(EEG.data,1);
EEG = eeg_checkset(EEG);
end;
if ~isempty(fileloc)
if strcmpi(fileloc, 'auto')
EEG = readegilocs(EEG);
else
EEG = readegilocs(EEG, fileloc);
end;
end;
if nargin < 1
command = sprintf('EEG = pop_readegi(''%s'', %s);', filename, vararg2str({datachunks forceversion fileloc }) );
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_erpimage.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_erpimage.m
| 34,127 |
utf_8
|
7a821956c6e3beaf067346e54d7e5e01
|
% pop_erpimage() - draw an ERP-image plot of a given EEG channel or independent
% component. Uses a pop-up window if less than three (or four
% in one condition) input arguments are supplied. Calls erpimage().
% For futher details see >> help erpimage
% Usage:
% >> pop_erpimage(EEG, typeplot); % pop-up a data entry window
% >> pop_erpimage(EEG, typeplot, lastcom); % pop-up a data entry window
% >> pop_erpimage(EEG, typeplot, channel); % no pop-up window
% >> pop_erpimage(EEG, typeplot, channel, projchan, title, ...
% smooth, decimate, sortingtype, sortingwin, ...
% sortingeventfield, renorm, options...);
% Graphic interface:
% "Channel or Component" - [edit box] Enter channel number or component
% number to plot. erpimage() equivalent: 'channel'
% "Project to channel #" - [edit box] (for plotting independent components).
% Allow reprojecting the component activity
% to a given channel or group of channels.
% erpimage() equivalent: [none]
% "Smoothing" - [text box] Smoothing parameter in number of trials.
% erpimage() equivalent: 'smooth'
% "Downsampling" - [edit box] Decimate parameter.
% erpimage() equivalent: 'decimate'
% "Time limits" - [edit box] Enter the time limits in milliseconds.
% erpimage() equivalent: the 1st and 2nd parameters of the 'limit' array
% "Figure title" - [edit box] Enter the figure title here. If empty, a title
% is automatically generated. erpimage() equivalent: 'title'
% "Plot scalp map" - [checkbox] Setting this option plot a scalp map of the
% channel location (or component topography) next to the
% erpimage. erpimage() equivalent: 'topo'
% "plot ERP" - [checkbox] Setting this option plot the channel or component
% ERP below the ERP image. erpimage() equivalent: 'erp'
% "Plot colorbar" - [checkbox] Plot the colorbar on the right of the erpimage.
% erpimage() equivalent: 'cbar'
% "ERP limits" - [edit box] Set the minimum and maximum value for the ERP plot
% erpimage() equivalent: 3rd and 4th parameters of the 'limit' array
% "Color limits" - [edit box] Set the color limits for the ERP image.
% erpimage() equivalent: 'caxis'
% "Epoch sorting field" - [button and edit box] Specify the event field which
% values will be used to sort the trials. For instance, if you
% select the 'latency' fields, trials will be sorted by the
% latency of the selected events.
% erpimage() equivalent: 'sortingeventfield'
% "Event type(s)" - [button and edit box] Specify which event subset to select,
% based on the event 'type' field values (to scan for event types, use
% menu Edit > Events values and look at the values of the 'type'
% field). For instance, entering type 'rt' (if defined) and field
% 'latency' in option aboce will sort trials on reaction time latencies.
% When several selected events are present in individual trials,
% the first event values are used for sorting and a warning is issued.
% erpimage() equivalent: 'sortingtype'
% "Event time range" - [edit box] Specify which event subset to select based on
% event latency values. As the option above, this further restrains
% the selection of events. For example, entering [200 300] in this
% box, 'rt' for the event type (above), and 'latency' for the
% epoch sorting field will select trials with reaction-time latencies
% in between 200 and 300 ms. Trials with no such event will not be
% included in the ERP-image plot. erpimage() equivalent: 'sortingwin'
% "rescale" - [edit box] 'yes', 'no', or a Matlab formula.
% erpimage() equivalent: 'renorm'
% "align" - [edit box] Set this to 'Inf' to re-align the individual trials
% on the median latency of the selected events. Else, enter an epoch time
% (in ms) to align the events to (Ex: 0). erpimage() equivalent: 'align'
% "Don't sort by value" - [checkbox] Check this box if you do not want to
% sort the trials but do want to plot the selected event values.
% erpimage() equivalent: 'nosort'
% "Don't plot value" - [checkbox] Check this box if you do not want to
% plot the selected event values, but still want to sort
% the data trials according to these values.
% erpimage() eqivalent: 'noplot'
% "Sort by phase > Frequency" - [edit box] Specify the frequency or frequency
% range for sorting trials by phase. erpimage() equivalent:
% 3rd and 4th inputs to 'phasesort'
% "Window center (ms)" - [edit box] erpimage() equivalent: 1st 'phasesort' input
% "Percent low-amp. trials to ignore" - [edit box] erpimage() equivalent:
% 2nd 'phasesort' input
% "Wavelet cycles" - [text] Number of wavelet cycles used for spectral decomposition
% at the specified latency. To change this, see "More options" {default: 3}
% "Inter-trial coherence options > Frequency" - [edit box] Frequency at which
% to compute coherence. Constrained to be the same as the
% "Sort by phase > Frequency" edit box. erpimage() equivalent: 'coher'
% "Signif. level" - [edit box] Coherence significance cutoff, as a proability
% (Ex: .05). erpimage() equivalent: 'signif'
% "Amplitude limit" - [edit box] Amplitude limits [min max] for the data power
% plot at the selected frequency. erpimage() equivalent:
% 5th and 6th inputs to 'limit'
% "Coher limits" - [edit box] Upper limit (<=1) for the coherence
% plot. erpimage() equivalent: 7th and 8th inputs of 'limit'
% "Image amps" - [checkbox] Check this box for plotting the spectral amplitude
% image at the selected frequency (instead of plotting EEG potential).
% erpimage() equivalent: 'plotamp'
% "Plot spectrum" - [edit box] Plot the channel or component data spectrum in
% the top right corner of the ERP image. erpimage() equivalent: 'spec'
% "Baseline ampl." - [edit box] Baseline amplitude for data power plot at the
% selected frequency. erpimage() equivalent: 7th inputs of 'limit'
% "Mark times" - [edit box] Time(s) in ms to plot vertical lines.
% erpimage() equivalent: 'vert'
% "More options" - [edit box] Enter 'key', 'value' sequences. Other erpimage()
% options not handled by this interface, including: 'erpstd' to
% plot the ERP standard deviation; 'auxvar' to plot auxilary
% variables; 'ampsort' to sort trials based on amplitude at
% the selected frequency, etc. For further information see
% >> help erpimage()
% Inputs:
% EEG - dataset structure
% typeplot - 1=channel, 0=component {default: 1}
% lastcom - string containing previous pop_erpimage command (from LASTCOM)
% or from the previous function call output. The values from this
% function call are used as default in the graphic interface.
%
% Commandline options:
% channel - Index of channel or component(s) to plot {default: 1}
% projchan - Channel to back-project the selected component(s) to.
% If plotting channel activity, this argument is ignored.
% If [], the ICA component activation is plotted {default []}.
% title - ['string'] Plot title {default: []}
% smooth - Smoothing parameter (number of trials). {Default: 5}
% erpimage() equivalent: 'avewidth'
% decimate - Decimate parameter (i.e. ratio of trials_in/trials_out).
% erpaimge() equivalent: 'decimate' {Default: 0}
% sortingtype - Sorting event type(s) ([int vector]; []=all). See Notes below.
% Either a string or an integer.
% sortingwin - Sorting event window [start, end] in seconds ([]=whole epoch)
% sortingeventfield - Sorting field name. {default: none}. See Notes below.
% options - erpimage() options, separated by commas (Ex: 'erp', 'cbar').
% {Default: none}. For further details see >> erpimage help
%
% Outputs from pop-up:
% String containing the command used to evaluate this plotting function
% (saved by eeglab() as LASTCOM). Enter it as the 'lastcom' input to restore
% the previous parameters as defaults in a new pop_erpimage() pop-up window
%
% Outputs from commandline:
% Same as erpimage(). Note: No outputs are returned when a window pops-up
% to ask for additional arguments
%
% Notes:
% 1) A new figure is created only when the pop-up window is called,
% so you may call this command with >3 args to draw in sbplot() axes.
% 2) To sort epochs, first define the event field to be used with
% the argument 'sortingeventfield' (for instance 'latency'). Then,
% because there may be several events with different latencies in a
% given epoch, it is possible to consider only a subsets of events
% using the 'sortingtype' and 'sortingwin' arguments. The
% 'sortingtype' argument selects events with definite types. The
% 'sortingwin' argument helps to define a specific time window in the
% epoch to select events. For instance the epoch time range may be -1
% to 2 seconds but one may want to select events only in the range 0
% to 1 second. These three parameters are forwarded to the function
% eeg_getepochevent(), whose help message contains more details.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeglab(), erpimage(), eeg_getepochevent()
% 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
% 02-12-02 added new event format compatibility -ad
% 02-15-02 text interface editing -sm & ad
% 03-07-02 add the eeglab computeica options -ad
% 02-15-02 modified the function accoring to the new event/epoch structure -ad
% 03-18-02 added title -ad & sm
% 04-04-02 added outputs -ad & sm
function varargout = pop_erpimage( EEG, typeplot, channel, projchan, titleplot, smooth, decimate, sortingtype, ...
sortingwin, sortingeventfield, varargin)
varargout{1} = '';
if nargin < 1
help pop_erpimage;
return;
end;
if typeplot == 0 && isempty(EEG.icasphere)
error('no ICA data for this set, first run ICA');
end;
if EEG.trials == 1
error('erpimage of one trial cannot be plotted');
end;
if nargin < 2
typeplot = 1; %1=signal; 0=component
end;
lastcom = [];
if nargin < 3
popup = 1;
else
popup = isstr(channel) | isempty(channel);
if isstr(channel)
lastcom = channel;
end;
end;
if popup
% get contextual help
% -------------------
clear functions;
erpimagefile = which('erpimage.m');
[txt2 vars2] = gethelpvar(erpimagefile);
txt = { txt2{:}};
vars = { vars2{:}};
% [txt vars] = gethelpvar('erpimopt.m');
% txt = { txt{:} txt2{:}};
% vars = { vars{:} vars2{:}};
opt.topo = getkeyval(lastcom, 'topo', 'present', 1);
opt.fieldname = getkeyval(lastcom, 10);
opt.type = getkeyval(lastcom, 8);
opt.renorm = getkeyval(lastcom, 'renorm','', 'no');
opt.erp = fastif(getkeyval(lastcom, '''erp''', 'present', 1), 'on', 'off');
opt.cbar = fastif(getkeyval(lastcom, 'cbar', 'present', 1), 'on', 'off');
opt.nosort = fastif(getkeyval(lastcom, 'nosort', 'present', 0), 'on', 'off');
opt.noplot = fastif(getkeyval(lastcom, 'noplot', 'present', 0), 'on', 'off');
opt.plotamps = fastif(getkeyval(lastcom, 'plotamps', 'present', 0), 'on', 'off');
opt.index = str2num(getkeyval(lastcom,3,[],'1'));
opt.smoothing = str2num(getkeyval(lastcom, 6, [], int2str(min(max(EEG.trials-5,0), 10))));
opt.downsampling = str2num(getkeyval(lastcom, 7, [], '1'));
opt.caxis = str2num(getkeyval(lastcom, 'caxis'));
opt.eventrange = str2num(getkeyval(lastcom, 9));
opt.align = str2num(getkeyval(lastcom, 'align'));
opt.phasesort = str2num(getkeyval(lastcom, 'phasesort'));
opt.coher = str2num(getkeyval(lastcom, 'coher'));
opt.spec = str2num(getkeyval(lastcom, 'spec'));
opt.vert = str2num(getkeyval(lastcom, 'vert'));
opt.limits = str2num(getkeyval(lastcom, 'limits'));
opt.limits = [ opt.limits NaN NaN NaN NaN NaN NaN NaN NaN NaN ]; opt.limits = opt.limits(1:9);
opt.coher = [ opt.coher NaN NaN NaN NaN NaN NaN NaN NaN NaN ]; opt.coher = opt.coher(1:3);
opt.phasesort = [ opt.phasesort NaN NaN NaN NaN NaN NaN NaN NaN NaN ]; opt.phasesort = opt.phasesort(1:4);
if isnan(opt.limits(1)), opt.limits(1:2) = 1000*[EEG.xmin EEG.xmax]; end;
commandphase = [ 'if ~isempty(get(findobj(''parent'', gcbf, ''tag'', ''phase''),''string'')),' ...
' if ~isempty(get(findobj(''parent'', gcbf, ''tag'', ''coher''),''string'')), ' ...
' set(findobj(''parent'', gcbf, ''tag'', ''coher''), ''string'', get(findobj(''parent'', gcbf, ''tag'', ''phase''),''string''));' ...
'end; end;' ];
commandcoher = [ 'if ~isempty(get(findobj(''parent'', gcbf, ''tag'', ''coher''),''string'')),' ...
' if ~isempty(get(findobj(''parent'', gcbf, ''tag'', ''phase''),''string'')), ' ...
' set(findobj(''parent'', gcbf, ''tag'', ''phase''), ''string'', get(findobj(''parent'', gcbf, ''tag'', ''coher''),''string''));' ...
'end; end;' ];
commandfield = ['if isempty(EEG.event)' ...
' errordlg2(''No events'');' ...
'else' ...
' tmpfieldnames = fieldnames(EEG.event);' ...
' [tmps,tmpv] = listdlg2(''PromptString'', ''Select fields'', ''SelectionMode'',''single'',''ListString'', tmpfieldnames);' ...
' if tmpv' ...
' set(findobj(''parent'', gcbf, ''tag'', ''field''), ''string'', tmpfieldnames{tmps});' ...
' end;' ...
'end;' ...
'if isempty(get(findobj(''parent'', gcbf, ''tag'', ''type''), ''string'')),' ...
' warndlg2(''Do not forget to select an event type in the next edit box'');' ...
'end;' ...
'clear tmps tmpv tmpfieldnames;' ];
commandtype = [ 'if ~isfield(EEG.event, ''type'')' ...
' errordlg2(''No type field'');' ...
'else' ...
' tmpevent = EEG.event;' ...
' if isnumeric(EEG.event(1).type),' ...
' [tmps,tmpstr] = pop_chansel(unique([ tmpevent.type ]));' ...
' else,' ...
' [tmps,tmpstr] = pop_chansel(unique({ tmpevent.type }));' ...
' end;' ...
' if ~isempty(tmps)' ...
' set(findobj(''parent'', gcbf, ''tag'', ''type''), ''string'', tmpstr);' ...
' end;' ...
'end;' ...
'if isempty(get(findobj(''parent'', gcbf, ''tag'', ''field''), ''string'')),' ...
' warndlg2(''Do not forget to select an event type in the previous edit box'');' ...
'end;' ...
'clear tmps tmpv tmpstr tmpevent tmpfieldnames;' ];
geometry = { [1 1 0.1 0.8 2.1] [1 1 1 1 1] [1 1 1 1 1] [1 1 1 1 1] [1] [1] [1 1 1 0.8 0.8 1.2] [1 1 1 0.8 0.8 1.2] [1] [1] ...
[1.6 1.7 1.2 1 .5] [1.6 1.7 1.2 1 .5] [1] [1] [1.5 1 1 1 1] [1.5 1 1 1 1] [1] [1] [1.5 1 1 2.2] [1.5 1 1 2.2]};
uilist = { { 'Style', 'text', 'string', fastif(typeplot, 'Channel', 'Component(s)'), 'fontweight', 'bold' } ...
{ 'Style', 'edit', 'string', num2str(opt.index), 'tag', 'chan' } { } ...
{ 'Style', 'text', 'string', 'Figure title', 'fontweight', 'bold' } ...
{ 'Style', 'edit', 'string', '', 'tag', 'title' } ...
...
{ 'Style', 'text', 'string', 'Smoothing', 'fontweight', 'bold', 'tooltipstring', context('avewidth',vars,txt) } ...
{ 'Style', 'edit', 'string', num2str(opt.smoothing), 'tag', 'smooth' } ...
{ 'Style', 'checkbox', 'string', 'Plot scalp map', 'tooltipstring', 'plot a 2-d head map (vector) at upper left', ...
'value', opt.topo, 'tag', 'plotmap' } { } { } ...
{ 'Style', 'text', 'string', 'Downsampling', 'fontweight', 'bold', 'tooltipstring', context('decimate',vars,txt) } ...
{ 'Style', 'edit', 'string', num2str(opt.downsampling), 'tag', 'decimate' } ...
{ 'Style', 'checkbox', 'string', 'Plot ERP', 'tooltipstring', context('erp',vars,txt), 'value', fastif(strcmpi(opt.erp, 'on'), 1,0), 'tag', 'erp' } ...
{ 'Style', 'text', 'string', fastif(typeplot, 'ERP limits (uV)','ERP limits'), 'tooltipstring', [ 'Plotting limits for ERP trace [min_uV max_uV]' 10 '{Default: ERP data limits}'] } ...
{ 'Style', 'edit', 'string', fastif(~isnan(opt.limits(3)), num2str(opt.limits(3:4)), ''), 'tag', 'limerp' } ...
{ 'Style', 'text', 'string', 'Time limits (ms)', 'fontweight', 'bold', 'tooltipstring', 'Select time subset in ms' } ...
{ 'Style', 'edit', 'string', fastif(~isnan(opt.limits(1)), num2str(opt.limits(1:2)), ''), 'tag', 'limtime' } ...
{ 'Style', 'checkbox', 'string', 'Plot colorbar','tooltipstring', context('caxis',vars,txt), 'value', fastif(strcmpi(opt.cbar, 'on'), 1,0), 'tag', 'cbar' } ...
{ 'Style', 'text', 'string', 'Color limits (see Help)','tooltipstring', context('caxis',vars,txt) } ...
{ 'Style', 'edit', 'string', num2str(opt.caxis), 'tag', 'caxis' } ...
{} ...
{ 'Style', 'text', 'string', 'Sort/align trials by epoch event values', 'fontweight', 'bold'} ...
{ 'Style', 'pushbutton', 'string', 'Epoch-sorting field', 'callback', commandfield, ...
'tooltipstring', 'Epoch-sorting event field name (Ex: latency; default: no sorting):' } ...
{ 'Style', 'pushbutton', 'string', 'Event type(s)', 'callback', commandtype, 'tooltipstring', ['Event type(s) subset (default: all):' 10 ...
'(See ''/Edit/Edit event values'' for event types)'] } ...
{ 'Style', 'text', 'string', 'Event time range', 'tooltipstring', [ 'Sorting event window [start, end] in milliseconds (default: whole epoch):' 10 ...
'events are only selected within this time window (can be usefull if several' 10 ...
'events of the same type are in the same epoch, or for selecting trials with given response time)']} ...
{ 'Style', 'text', 'string', 'Rescale', 'tooltipstring', 'Rescale sorting variable to plot window (yes|no|a*x+b)(Ex:3*x+2):' } ...
{ 'Style', 'text', 'string', 'Align', 'tooltipstring', context('align',vars,txt) } ...
{ 'Style', 'checkbox', 'string', 'Don''t sort by value', 'tooltipstring', context('nosort',vars,txt), 'value', fastif(strcmpi(opt.nosort, 'on'), 1,0), 'tag', 'nosort' } ...
{ 'Style', 'edit', 'string', opt.fieldname, 'tag', 'field' } ...
{ 'Style', 'edit', 'string', opt.type, 'tag', 'type' } ...
{ 'Style', 'edit', 'string', num2str(opt.eventrange), 'tag', 'eventrange' } ...
{ 'Style', 'edit', 'string', opt.renorm, 'tag', 'renorm' } ...
{ 'Style', 'edit', 'string', num2str(opt.align), 'tag', 'align' } ...
{ 'Style', 'checkbox', 'string', 'Don''t plot values', 'tooltipstring', context('noplot',vars,txt), 'value', fastif(strcmpi(opt.noplot, 'on'), 1,0), 'tag', 'noplot' } ...
{} ...
{ 'Style', 'text', 'string', 'Sort trials by phase', 'fontweight', 'bold'} ...
{ 'Style', 'text', 'string', 'Frequency (Hz | minHz maxHz)', 'tooltipstring', ['sort by phase at maximum-power frequency' 10 ...
'in the data within the range [minHz,maxHz]' 10 '(overrides frequency specified in ''coher'' flag)'] } ...
{ 'Style', 'text', 'string', 'Percent low-amp. trials to ignore', 'tooltipstring', ['percent of trials to reject for low' ...
'amplitude. Else,' 10 'if prct is in the range [-100,0] -> percent to reject for high amplitude'] } ...
{ 'Style', 'text', 'string', 'Window center (ms)', 'tooltipstring', 'Center time of the n-cycle window' } ...
{ 'Style', 'text', 'string', 'Wavelet cycles', 'tooltipstring', 'cycles per wavelet window' } {}...
{ 'Style', 'edit', 'string', fastif(~isnan(opt.phasesort(3)),num2str(opt.phasesort(3:4)),'') 'tag', 'phase', 'callback', commandphase } ...
{ 'Style', 'edit', 'string', fastif(~isnan(opt.phasesort(2)),num2str(opt.phasesort(2)),''), 'tag', 'phase2' } ...
{ 'Style', 'edit', 'string', fastif(~isnan(opt.phasesort(1)),num2str(opt.phasesort(1)),''), 'tag', 'phase3' } ...
{ 'Style', 'text', 'string', ' 3' } {}...
{} ...
{ 'Style', 'text', 'string', 'Inter-trial coherence options', 'fontweight', 'bold'} ...
{ 'Style', 'text', 'string', 'Frequency (Hz | minHz maxHz)', 'tooltipstring', [ '[freq] -> plot erp plus amp & coher at freq (Hz)' 10 ...
'[minHz maxHz] -> find max in frequency range' 10 '(or at phase freq above, if specified)']} ...
{ 'Style', 'text', 'string', 'Signif. level (<0.20)', 'tooltipstring', 'add coher. signif. level line at alpha (alpha range: (0,0.1])' } ...
{ 'Style', 'text', 'string', 'Amplitude limits (dB)' } ...
{ 'Style', 'text', 'string', 'Coher limits (<=1)' } ...
{ 'Style', 'checkbox', 'string', 'Image amps', 'tooltipstring', context('plotamps',vars,txt), 'value', fastif(strcmpi(opt.plotamps, 'on'), 1,0), 'tag', 'plotamps' } ...
{ 'Style', 'edit', 'string', fastif(~isnan(opt.coher(1)), num2str(opt.coher(1:2)), ''), 'tag', 'coher', 'callback', commandcoher } ...
{ 'Style', 'edit', 'string', fastif(~isnan(opt.coher(3)), num2str(opt.coher(3)), ''), 'tag', 'coher2' } ...
{ 'Style', 'edit', 'string', fastif(~isnan(opt.limits(5)), num2str(opt.limits(5:6)), ''), 'tag', 'limamp' } ...
{ 'Style', 'edit', 'string', fastif(~isnan(opt.limits(7)), num2str(opt.limits(7:8)), ''), 'tag', 'limcoher' } ...
{'style', 'text', 'string', ' (Requires signif.)' } ...
{} ...
{ 'Style', 'text', 'string', 'Other options', 'fontweight', 'bold'} ...
{ 'Style', 'text', 'string', 'Plot spectrum (minHz maxHz)','tooltipstring', context('spec',vars,txt)} ...
{ 'Style', 'text', 'string', 'Baseline ampl. (dB)', 'tooltipstring', 'Use it to fix baseline amplitude' } ...
{ 'Style', 'text', 'string', 'Mark times (ms)','tooltipstring', context('vert',vars,txt)} ...
{ 'Style', 'text', 'string', 'More options (see >> help erpimage)' } ...
{ 'Style', 'edit', 'string', num2str(opt.spec), 'tag', 'spec' } ...
{ 'Style', 'edit', 'string', fastif(~isnan(opt.limits(9)), num2str(opt.limits(9)), ''), 'tag', 'limbaseamp' } ...
{ 'Style', 'edit', 'string', num2str(opt.vert), 'tag', 'vert' } ...
{ 'Style', 'edit', 'string', '', 'tag', 'others' } ...
};
if typeplot == 0 % add extra param for components
geometry = { [1 1 0.1 0.8 2.1] geometry{:} };
uilist = { { } { } { } { } { } uilist{:}};
uilist{1} = uilist{6};
uilist{2} = uilist{7};
uilist{6} = { 'Style', 'text', 'string', 'Project to channel #', 'fontweight', 'bold','tooltipstring', ['Project component(s) to data channel' 10 ...
'This allows plotting projected component activity at one channel in microvolts'] };
uilist{7} = { 'Style', 'edit', 'string', getkeyval(lastcom, 4), 'tag', 'projchan' };
end;
[oldres a b res] = inputgui( geometry, uilist, 'pophelp(''pop_erpimage'');', ...
fastif( typeplot, 'Channel ERP image -- pop_erpimage()', 'Component ERP image -- pop_erpimage()'));
if isempty(oldres), return; end;
% first rows
% ---------
channel = eval( [ '[' res.chan ']' ]);
titleplot = res.title;
if isfield(res, 'projchan'),
if ~isempty(res.projchan)
if strcmpi(res.projchan(1),'''')
projchan = eval( [ '{' res.projchan '}' ]);
else projchan = parsetxt( res.projchan);
end;
if ~isempty(projchan) && ~isempty(str2num(projchan{1}))
projchan = cellfun(@str2num, projchan);
end;
else
projchan = [];
end;
else,
projchan = [];
end;
opt = [];
if ~isempty(res.others)
try,
tmpcell = eval( [ '{' res.others '}' ] );
opt = struct( tmpcell{:} );
catch, error('Additional options ("More options") requires ''key'', ''val'' arguments');
end;
end;
if ~typeplot && isempty(projchan)
opt.yerplabel = '';
else
opt.yerplabel = '\muV' ;
end;
smooth = eval(res.smooth);
if res.plotmap
if isfield(EEG.chanlocs, 'theta')
if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end;
if typeplot == 0
opt.topo = [ ' { mean(EEG.icawinv(:,[' int2str(channel) ']),2) EEG.chanlocs EEG.chaninfo } '];
else opt.topo = [ ' { [' int2str(channel) '] EEG.chanlocs EEG.chaninfo } '];
end;
end;
end;
decimate = eval( res.decimate );
if res.erp
opt.erp = 'on';
end;
% finding limits
% --------------
limits(1:8) = NaN;
if ~isempty(res.limerp)
limits(3:4) = eval( [ '[' res.limerp ']' ]);
end;
if ~isempty(res.limtime) % time limits
if ~strcmp(res.limtime, num2str(1000*[EEG.xmin EEG.xmax]))
limits(1:2) = eval( [ '[' res.limtime ']' ]);
end;
end;
if ~isempty(res.limamp)
limits(5:6) = eval( [ '[' res.limamp ']' ]);
end;
if ~isempty(res.limcoher)
limits(7:8) = eval( [ '[' res.limcoher ']' ]);
end;
if ~isempty(res.limbaseamp)
limits(9) = eval( res.limbaseamp ); %bamp
end;
if ~all(isnan(limits))
opt.limits = limits;
end;
% color limits
% --------------
if res.cbar
opt.cbar = 'on';
end;
if res.caxis
opt.caxis = str2num(res.caxis);
end;
% event rows
% ----------
if res.nosort
opt.nosort = 'on';
end;
try, sortingeventfield = eval( res.field ); catch, sortingeventfield = res.field; end;
if ~isempty(res.type)
if strcmpi(res.type(1),'''')
sortingtype = eval( [ '{' res.type '}' ] );
else sortingtype = parsetxt( res.type );
end;
end
sortingwin = eval( [ '[' res.eventrange ']' ] );
if ~isempty(res.field) & ~strcmp(res.renorm, 'no')
opt.renorm = res.renorm;
end;
if ~isempty(res.align)
opt.align = str2num(res.align);
end;
if res.noplot
opt.noplot = 'on';
end;
% phase rows
% ----------
tmpphase = [];
if ~isempty(res.phase)
tmpphase = eval( [ '[ 0 0 ' res.phase ']' ]);
end;
if ~isempty(res.phase2)
tmpphase(2) = eval( res.phase2 );
end;
if ~isempty(res.phase3)
tmpphase(1) = eval( res.phase3 );
end;
if ~isempty(tmpphase)
opt.phasesort = tmpphase;
end;
% coher row
% ----------
tmpcoher = [];
if res.plotamps
opt.plotamps = 'on';
end;
if ~isempty(res.coher)
tmpcoher = eval( [ '[' res.coher ']' ]);
end;
if ~isempty(res.coher2)
if length(tmpcoher) == 1
tmpcoher(2) = tmpcoher(1);
end;
tmpcoher(3) = eval( res.coher2 );
end;
if ~isempty(tmpcoher)
opt.coher = tmpcoher;
end;
% options row
% ------------
if ~isempty(res.spec)
opt.spec = eval( [ '[' res.spec ']' ]);
end;
if ~isempty(res.vert)
opt.vert = eval( [ '[' res.vert ']' ]);
end;
figure;
options = '';
else
options = '';
if nargin < 4
projchan = [];
end;
if nargin < 5
titleplot = ' ';
end;
if nargin < 6
smooth = 5;
end;
if nargin < 7
decimate = 0;
end;
if nargin < 8
sortingtype = [];
end;
if nargin < 9
sortingwin = [];
end;
if nargin < 10
sortingeventfield = [];
end;
%options = vararg2str(varargin); % NO BECAUSE OF THE CHANNEL LOCATION
% PROBLEM BELOW
for i=1:length( varargin )
if isstr( varargin{ i } )
options = [ options ', ''' varargin{i} '''' ];
else
if ~iscell( varargin{ i } )
options = [ options ',' vararg2str({varargin{i}}) ];
else
%options = [ options ', { [' num2str(varargin{ i }{1}') ']'' EEG.chanlocs EEG.chaninfo }' ]; % JRI -- why does this ignore value passed as topo option?
if length(varargin{i})>1
optchanlocs = varargin{i}{2}; % JRI -- fix
else
optchanlocs = EEG.chanlocs;
end;
if length(varargin{i})>2,
optchaninfo = varargin{i}{3};
else
optchaninfo = EEG.chaninfo;
end
options = [ options ', { [' num2str(varargin{ i }{1}') ']'' optchanlocs optchaninfo }' ];
end;
end;
end;
end;
try, icadefs; set(gcf, 'color', BACKCOLOR,'Name',' erpimage()'); catch, end;
% testing inputs
% --------------
if typeplot == 0 && length(channel) > 1 && isempty(projchan)
error('A channel must be selected to plot (the sum of) several component projections');
end;
% find sorting latencies
% ---------------------
typetxt = '';
if ~isempty(sortingeventfield)
%events = eeg_getepochevent( EEG, sortingtype, sortingwin, sortingeventfield);
events = sprintf('eeg_getepochevent( EEG, %s)', vararg2str({sortingtype, sortingwin, sortingeventfield}));
% generate text for the command
% -----------------------------
for index = 1:length(sortingtype)
if isstr(sortingtype{index})
typetxt = [typetxt ' ''' sortingtype{index} '''' ];
else
typetxt = [typetxt ' ' num2str(sortingtype{index}) ];
end;
end;
% $$$ % renormalize latencies if necessary
% $$$ % ----------------------------------
% $$$ switch lower(renorm)
% $$$ case 'yes',
% $$$ disp('Pop_erpimage warning: *** sorting variable renormalized ***');
% $$$ events = (events-min(events)) / (max(events) - min(events)) * ...
% $$$ 0.5 * (EEG.xmax*1000 - EEG.xmin*1000) + EEG.xmin*1000 + 0.4*(EEG.xmax*1000 - EEG.xmin*1000);
% $$$ case 'no',;
% $$$ otherwise,
% $$$ locx = findstr('x', lower(renorm))
% $$$ if length(locx) ~= 1, error('Pop_erpimage error: unrecognize renormalazing formula'); end;
% $$$ eval( [ 'events =' renorm(1:locx-1) 'events' renorm(locx+1:end) ';'] );
% $$$ end;
else
events = 'ones(1, EEG.trials)*EEG.xmax*1000';
%events = ones(1, EEG.trials)*EEG.xmax*1000;
sortingeventfield = '';
end;
if isstr(projchan)
projchan = { projchan };
end;
if iscell(projchan)
projchannum = std_chaninds(EEG, projchan);
else
projchannum = projchan;
end;
if typeplot == 1
tmpsig = ['mean(EEG.data([' int2str(channel) '], :),1)'];
else
% test if ICA was computed or if one has to compute on line
% ---------------------------------------------------------
tmpsig = [ 'eeg_getdatact(EEG, ''component'', [' int2str(channel) '], ''projchan'', [' int2str(projchannum) '])' ];
end;
% outputs
% -------
outstr = '';
if ~popup
for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end;
if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end;
end;
% plot title
% ----------
if isempty(titleplot)
if typeplot==1 % if channel plot
if ~isempty(EEG.chanlocs) % if channel information exist
titleplot = [ EEG.chanlocs(channel).labels ];
else, titleplot = [ int2str(channel) ];
end
else
titleplot = [ 'Comp. ' int2str(channel) ];
if ~isempty(projchan),
tmpstr = vararg2str({projchan});
tmpstr(find(tmpstr == '''')) = '"';
titleplot = [ titleplot ' -> Chan. ' tmpstr ];
end;
end
end;
% plot the data and generate output command
% --------------------------------------------
if isempty( options )
if isfield(opt, 'topo')
tmptopo = opt.topo;
opt = rmfield(opt, 'topo');
else
tmptopo = '';
end;
fields = fieldnames(opt);
values = struct2cell(opt);
params = { fields{:}; values{:} };
options = [ ',' vararg2str( { params{:} } ) ];
tmpind = find( options == '\' ); options(tmpind(1:2:end)) = [];
if ~isempty(tmptopo), options = [ options ',''topo'',' tmptopo ]; end;
end;
% varargout{1} = sprintf('figure; pop_erpimage(%s,%d,%d,''%s'',%d,%d,{%s},[%s],''%s'',''%s''%s);', inputname(1), typeplot, channel, titleplot, smooth, decimate, typetxt, int2str(sortingwin), sortingeventfield, renorm, options);
popcom = sprintf('figure; pop_erpimage(%s,%d, [%s],[%s],''%s'',%d,%d,{%s},[%s],''%s'' %s);', inputname(1), typeplot, int2str(channel), vararg2str({projchan}), titleplot, smooth, decimate, typetxt, int2str(sortingwin), sortingeventfield, options);
com = sprintf('%s erpimage( %s, %s, linspace(EEG.xmin*1000, EEG.xmax*1000, EEG.pnts), ''%s'', %d, %d %s);', outstr, tmpsig, events, titleplot, smooth, decimate, options);
disp('Command executed by pop_erpimage:');
disp(' '); disp(com); disp(' ');
eval(com)
if popup
varargout{1} = popcom; % [10 '% Call: ' com];
end;
return;
% get contextual help
% -------------------
function txt = context(var, allvars, alltext);
loc = strmatch( var, allvars);
if ~isempty(loc)
txt= alltext{loc(1)};
else
disp([ 'warning: variable ''' var ''' not found']);
txt = '';
end;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_epochformat.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_epochformat.m
| 7,674 |
utf_8
|
b6227100d8d67253534322618e4b81fa
|
% eeg_epochformat() - Convert the epoch information of a dataset from struct
% to array or vice versa.
%
% Usage: >> [epochsout fields] = eeg_epochformat( epochs, 'format', fields, events );
%
% Input:
% epochs - epoch numerical or cell array or epoch structure
% format - ['struct'|'array'] convert epoch array to structure and epoch
% structure to array.
% fields - [optional] cell array of strings containing the names of
% the epoch struct fields. If this field is empty, it uses the
% following list for the names of the fields { 'var1' 'var2' ... }.
% For structure conversion, this field helps export a given
% event type. If this field is left empty, the time locking
% event for each epoch is exported.
% events - numerical array of event indices associated with each epoch.
% For array conversion, this field is ignored.
%
% Outputs:
% epochsout - output epoch array or structure
% fields - output cell array with the name of the fields
%
% Epoch format:
% struct - Epoch information is organised as an array of structs
% array - Epoch information is organised as an 2-d array of numbers,
% each column representing a user-defined variable (the
% order of the variable is a function of its order in the
% struct format).
%
% Note: 1) The epoch structure is defined only for epoched data.
% 2) The epoch 'struct' format is more comprehensible.
% For instance, to see all the properties of epoch i,
% type >> EEG.epoch(i)
% Unfortunately, structures are awkward for expert users to deal
% with from the command line (Ex: To get an array of 'var1' values,
% >> celltomat({EEG.epoch(:).var1})')
% In array format, asuming 'var1' is the first variable
% declared, the same information is obtained by
% >> EEG.epoch(:,1)
% 3) This function automatically updates the 'epochfields'
% cell array depending on the format.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 12 Feb 2002
%
% See also: eeglab()
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) from eeg_eventformat.m,
% Arnaud Delorme, CNL / Salk Institute, 12 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
% $Log: eeg_epochformat.m,v $
% Revision 1.4 2005/05/24 16:57:09 arno
% cell2mat
%
% Revision 1.3 2003/07/20 19:32:20 scott
% typos
%
% Revision 1.2 2002/04/21 01:10:35 scott
% *** empty log message ***
%
% Revision 1.1 2002/04/05 17:32:13 jorn
% Initial revision
%
% 03/13/02 added field arrays options -ad
function [ epoch, fields, epocheventout] = eeg_epochformat( epoch, format, fields, epochevent);
if nargin < 2
help eeg_epochformat;
return;
end;
if nargin < 3
fields = {};
end;
epocheventout = [];
switch format
case 'struct'
if ~isempty(epoch) & ~isstruct(epoch)
fields = getnewfields( fields, size(epoch,2) - length(fields));
% generate the structure
% ----------------------
command = 'epoch = struct(';
for index = 1:length(fields)
if iscell(epoch)
command = [ command '''' fields{index} ''', epoch(:,' num2str(index) ')'',' ];
else
command = [ command '''' fields{index} ''', mattocell( epoch(:,' num2str(index) ')'',' ...
'[1], ones(1,size(epoch,1))),' ];
end;
end;
eval( [command(1:end-1) ');' ] );
if exist('epochevent') == 1
for index = 1:size(epoch,2)
if iscell(epochevent)
epoch(index).event = epochevent{index};
else
epoch(index).event = epochevent(index);
end;
end;
end;
end
case 'array'
if isstruct(epoch)
% note that the STUDY std_maketrialinfo also gets the epoch info for the
% time locking event
selectedType = fields;
if iscell(fields) && ~isempty(fields), selectedType = fields{1}; end;
fields = fieldnames( epoch );
eval( [ 'values = { epoch.' fields{1} ' };' ]);
if any(cellfun(@length, values) > 1)
if ~isfield(epoch, 'eventlatency')
error('eventlatency field not present in data epochs');
end;
if isempty(selectedType)
% find indices of time locking events
for index = 1:length(epoch)
epochlat = [ epoch(index).eventlatency{:} ];
tmpevent = find( abs(epochlat) < 0.02 );
if isempty(tmpevent)
error('time locking event missing, cannot convert to array');
end;
epochSubIndex(index) = tmpevent;
end;
else
% find indices of specific event type (if several take the
% first one
for index = 1:length(epoch)
epochtype = epoch(index).eventtype;
tmpeventind = strmatch( selectedType, epochtype );
if length(tmpeventind) > 1
fprintf('Warning: epoch %d has several events of "type" %s, taking the fist one\n', index, selectedType);
end;
if isempty(tmpeventind)
epochSubIndex(index) = NaN;
else epochSubIndex(index) = tmpeventind(1);
end;
end;
end;
else
epochSubIndex = ones(1, length(epoch));
end;
% copy values to array
tmp = cell( length(epoch), length( fields ));
for index = 1:length( fields )
for trial = 1:length(epoch)
tmpval = getfield(epoch, {trial}, fields{index});
if isnan(epochSubIndex(trial))
tmp(trial, index) = { NaN };
elseif iscell(tmpval)
tmp(trial, index) = tmpval(epochSubIndex(trial));
elseif ~ischar(tmpval)
tmp(trial, index) = { tmpval(epochSubIndex(trial)) };
else tmp(trial, index) = { tmpval };
end;
end;
end;
epoch = tmp;
end;
otherwise, error('unrecognised format');
end;
return;
% create new field names
% ----------------------
function epochfield = getnewfields( epochfield, nbfields )
count = 1;
if nbfields > 0
while nbfields > 0
if isempty( strmatch([ 'var' int2str(count) ], epochfield ) )
epochfield = { epochfield{:} [ 'var' int2str(count) ] };
nbfields = nbfields-1;
else count = count+1;
end;
end;
else
epochfield = epochfield(1:end+nbfields);
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_urlatency.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_urlatency.m
| 2,237 |
utf_8
|
7a9b9b21f8b247ddcea52752ae05bc26
|
% eeg_urlatency() - find the original (ur) latency of a time point in
% the original continuous data.
%
% Usage:
% >> lat_out = eeg_urlatency( event, lat_in );
%
% Inputs:
% event - event structure. If this structure contain boundary
% events, the length of these events is added to restore
% the original latency from the relative latency in 'lat_in'
% lat_in - relative latency in sample point
%
% Outputs:
% lat_out - output latency
%
% Note: the function that finds the latency in the current dataset using (ur)
% original latencies as input is eeg_latencyur()
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, April, 15, 2004
%
% See also: eeg_latencyur()
% Copyright (C) 2004 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 latout = eeg_urlatency( events, latin );
if nargin < 2
help eeg_urlatency;
return;
end;
boundevents = { events.type };
latout = latin;
if ~isempty(boundevents) & isstr(boundevents{1})
indbound = strmatch('boundary', boundevents);
if isfield(events, 'duration') & ~isempty(indbound)
for index = indbound'
tmpInds = find(events(index).latency < latin); % the find handles several input latencies
latout(tmpInds) = latout(tmpInds) + events(index).duration;
end;
elseif ~isempty(indbound) % boundaries but with no associated duration
latout = NaN;
end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_context.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_context.m
| 27,634 |
utf_8
|
8abec48acc7f051c46340c6cbf7f45f4
|
% eeg_context() - returns (in output 'delays') a matrix giving, for each event of specified
% ("target") type(s), the latency (in ms) to the Nth preceding and/or following
% urevents (if any) of specified ("neighbor") type(s). Return the target event
% and urevent numbers, the neighbor urevent numbers, and the values of specified
% urevent field(s) for each of the neighbor urevents. Uses the EEG.urevent
% structure, plus EEG.event().urevent pointers to it. If epoched data, also
% uses the EEG.epoch structure. For use in event-handling scripts and functions.
% Usage:
% >> [targs,urnbrs,urnbrtypes,delays,tfields,urnfields] = ...
% eeg_context(EEG,{targets},{neighbors},[positions],{fields},alltargs);
% Required input:
% EEG - EEGLAB dataset structure containing EEG.event and EEG.urevent sub-structures
%
% Optional inputs:
% targets - string or cell array of strings naming event type(s) of the specified target
% events {default | []: all events}
% neighbors - string or cell array of strings naming event type(s) of the specified
% neighboring urevents {default | []: any neighboring events}.
% [positions] - int vector giving the relative positions of 'neighbor' type urevents to return.
% Ex: [-3 -2 -1 0 1 2 3] -> return the previous 3, current, and succeeding 3
% urevents of the specified {neighbor} types. [positions] values are arranged
% in ascending order before processing. {default | []: 1 = first succeeding}
% fields - string or cell array of strings naming one or more (ur)event field(s) to return
% values for neighbor urevents. {default: no field info returned}
% alltargs - string ('all'|[]) if 'all', return information about all target urevents,
% even those on which no epoch in the current dataset is centered.
% {default: [] -> only return information on epoch-centered target events}
% Outputs:
% targs - size(ntargets,4) matrix giving the indices of target events in the event
% structure in column 1 and in the urevent structure in column 2. Column 3 gives
% the epoch number in which the target has latency 0 (else NaN if no such epoch).
% The fourth column gives the index of the target type in the {targets} cell array.
% urnbrs - matrix of indices of "neighbor" events in the URevent structure (NaN if none).
% urnbrtypes - int array giving the urnbrs event type indices in the {neighbor} cell array,
% else NaN if no such neighbor. Ex: If nbr = {'square','rt'} (see below),
% then urnbrtypes outputs are [1|2]; if nbr = {'rt'}, returns [1]s.
% delays - matrix giving, for each {targets} type event, the latency of the delay (in ms)
% from each target event to its neighbor urevents. Else, returns NaN when no
% neighbor event. Output matrix size: (ntargets,length(positions)).
% tfields - real or cell array of values of the requested (ur)event field(s) for the target
% events. Values are the same type as the field values, else NaN if no such event.
% urnfields - real or cell array of values of the requested (ur)event field(s) for the neighbor
% urevents. Values are the same type as the field values, else NaN if no such event.
% If > 1 field specified, a 3-D array or cell array (nevents,nnbrpos,nfields).
% Example:
%
% >> target = 'square'; % target events are type 'square'
% >> nbr = {'square','rt'}; % neighbor events are either 'square' or 'rt'
%
% >> [trgs,urnbrs,urnbrtypes,delays,tflds,urnflds] = ...
% eeg_context(EEG,target,nbr,[-4 1],'position');
% %
% % Output 'delays' now contains latencies (in ms) from each 'square' target event to the
% % 4th preceding and 1st succeeding 'rt' OR 'square' urevent (else NaN when none such).
% % Outputs 'tfields' and 'urnflds' give the 'position' field values of target events and
% % neighbor urevents. Output 'urnbrtypes', the index of the type (1='square' or 2='rt')
% % of the ('urnbrs') neighbor urevents.
% %
% >> trts = find(trgs(:,4)==2); % targets followed by an 'rt' (before any 'square')
% >> pos3 = find(trgfld = 3); % targets with 'position'=3 (numeric field value).
% >> selevents = intersect_bc(trts,pos3); % target events by both criteria
% >> selepochs = trgs(selevents,3); % epoch numbers centered on the selected target events
%
% Author: Scott Makeig, SCCN, Institute for Neural Computation, UCSD, March 27, 2004
% Edit History:
% 1/10/05 added 4th (type) field to output trgs; added to Example;
% 5/25/04 test for isnan(urevent.duration) to detect real break events -sm
% 3/27/04 made no-such-event return NaNs; added {target} and {neighbor} defaults -sm
% 3/28/04 added test for boundary urevents; renamed relidx as positions, lats as delays -sm
% 3/29/04 reorganized output order, adding urnbrtypes -sm
% 3/29/04 changed urnbrtypes to int array -sm
% 3/31/04 ruled out searching 'boundary' events -sm
% 5/06/04 completed the function -sm
%
function [targs,ur_nbrs,ur_nbrtypes,delays,tfields,nfields] = eeg_context(EEG,targets,neighbors,positions,field,alltargs)
verbose = 0; % flag useful info printout (1=on|0=off)
debug_print = 0; % flag overly verbose printout
breakwarning = 0; % flag no pre-4.4 warning given
if nargin < 1
help eeg_context
return
end
if nargin< 6 | isempty(alltargs)
alltargs = 0;
elseif strcmpi(alltargs,'all')
alltargs = 1;
else
error('alltargs argument must be ''all'' or [].')
end
if ~isstruct(EEG)
error('first argument must be an EEG dataset structure');
end
if ~isfield(EEG,'event')
error('No EEG.event structure found');
end
if ~isfield(EEG,'urevent')
error('No EEG.urevent structure found');
end
if ~isfield(EEG.event,'urevent')
error('No EEG.event().urevent field found');
end
if EEG.trials == 1 | ~isfield(EEG.event(1),'epoch')
fprintf('Data are continuous: Returning info on all targets; no epoch info returned.\n')
alltargs = 1;
epochinfo = 0;
else
epochinfo = 1;
end
if epochinfo & ~isfield(EEG,'epoch')
error('No EEG.epoch information in this epoched dataset - run eeg_checkset()');
end
if epochinfo & ~isfield(EEG.epoch,'eventlatency')
error('No EEG.epoch.eventlatency information in this epoched dataset');
end
if epochinfo & ~isfield(EEG.epoch,'event')
error('No EEG.epoch.event information in this epoched dataset');
end
nevents = length(EEG.event);
nurevents = length(EEG.urevent);
if length(EEG.urevent) < nevents
fprintf('In this dataset there are more events than urevents. Check consistency.\n');
end
%
%%%%%%%%%%%%%%%%%% Substitute input defaults %%%%%%%%%%%%%%%%%%%%
%
if nargin < 5 | isempty(field)
NO_FIELD = 1; % flag no field variable output
end
if nargin < 4 | isempty(positions)
positions = 1; % default: find next
end
if nargin < 3 | isempty(neighbors)
neighbors = {'_ALL'}; % flag neighbors are all neighboring events
end
if nargin < 2 | isempty(targets)
targets = {'_ALL'}; % flag targets are all events
end
%
%%%%%%%%%%%%% Test and adjust input arguments %%%%%%%%%%%%%%%%%%%%
%
if ischar(targets)
targets = {targets};
end
if ~iscell(targets)
error('2nd argument "targets" must be a {cell array} of event types.');
end
if ischar(neighbors)
neighbors = {neighbors};
end
if ~iscell(neighbors)
error('3rd argument "neighbors" must be a {cell array} of event types.');
end
for k=1:length(targets) % make all target types strings
if ~ischar(targets{k})
targets{k} = num2str(targets{k});
end
end
for k=1:length(neighbors) % make all neighbor types strings
if ~ischar(neighbors{k})
neighbors{k} = num2str(neighbors{k});
end
end
tmp = sort(positions); % reorder positions in ascending order
if sum(tmp==positions) ~= length(positions)
fprintf('eeg_context(): returning neighbors in ascending order: ');
for k=1:length(tmp)
fprintf('%d ',tmp(k));
end
fprintf('\n');
end
positions = tmp;
%
%%%%%%%%%%%%%% Prepare to find "neighbor" events %%%%%%%%%%%%%%%%%%
%
zeroidx = find(positions == 0); % find 0's in positions vector
negidx = find(positions < 0);
negpos = positions(negidx);
if ~isempty(negpos)
negpos = abs(negpos(end:-1:1)); % work backwards, make negpos positive
negidx = negidx(end:-1:1); % index into output ur_nbrs
end
nnegpos = length(negpos); % number of negative positions to search for
posidx = find(positions>0); % work forwards
pospos = positions(posidx);
npospos = length(pospos); % number of positive positions to search for
%
%%%%%%%%%%%%%%%%%%%% Initialize output arrays %%%%%%%%%%%%%%%%%%%%%%
%
npos = length(positions);
delays = NaN*zeros(nevents,npos); % holds inter-event intervals in ms
% else NaN when no neighboring event
targs = NaN*zeros(nevents,1); % holds indices of targets
targepochs= NaN*zeros(nevents,1); % holds numbers of the epoch centered
% on each target (or NaN if none such)
ur_trgs = NaN*zeros(nevents,1); % holds indices of targets
ur_nbrs = NaN*zeros(nevents,npos); % holds indices of neighbors
ur_nbrtypes = NaN*zeros(nevents,npos); % holds {neighbors} type indices
cellfld = -1; % flag no field output specified
if ~exist('NO_FIELD','var') % if field values asked for
if ischar(field)
if ~isfield(EEG.urevent,field)
error('Specified field not found in urevent struct');
end
if ischar(EEG.urevent(1).(field)) ...
| iscell(EEG.urevent(1).(field)) ...
| isstruct(EEG.urevent(1).(field)),
tfields = cell(nevents,1);
nfields = cell(nevents,npos);
cellfld = 1; % flag that field outputs are cell arrays
else % is number
tfields = NaN*zeros(nevents,1);
nfields = NaN*zeros(nevents,npos);
cellfld = 0; % flag that field outputs are numeric arrays
end
field = {field}; % make string field a cell array for uniformity
nfieldnames = 1;
elseif iscell(field)
nfieldnames = length(field);
for f = 1:nfieldnames
if ~isfield(EEG.urevent,field{f})
error('Specified field not found in urevent struct');
end
if ischar(EEG.urevent(1).(field{f})) ...
| iscell(EEG.urevent(1).(field{f})) ...
| isstruct(EEG.urevent(1).(field{f})),
if f==1,
tfields = cell(nevents,nfieldnames);
nfields = cell(nevents,npos,nfieldnames);
end
cellfld = 1; % flag that field outputs are cell arrays
else % is number
if f==1
tfields = NaN*zeros(nevents,nfieldnames);
nfields = NaN*zeros(nevents,npos,nfieldnames);
end
end
end
if cellfld == -1,
cellfld = 0; % field value(s) must be numeric
end
else
error('''field'' value must be string or cell array');
end
end
targetcount = 0; % index of current target
% Below:
% evidx = current event index
% uridx = current urevent index
% uidx = neighbor urevent index
% tidx = target type index
% nidx = neighbor type index
% pidx = position index
%
%%%%%%%%%%%for each event in the dataset %%%%%%%%%%%%%%%%%%%%
%
wb=waitbar(0,'Computing event contexts...','createcancelbtn','delete(gcf)');
noepochs = 0; % counter of targets that are not epoch-centered
targidx = zeros(nevents,1);
for evidx = 1:nevents %%%%%% for each event in the dataset %%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
waitbar(evidx/nevents); % update the waitbar fraction
if ~strcmp(EEG.event(evidx).type,'boundary') % ignore boundary events (no urevents!)
%
%%%%%%%%%%%%%%%%%%%%%%%% find target events %%%%%%%%%%%%%%%%%
%
uridx = EEG.event(evidx).urevent; % find its urevent index
if isempty(uridx)
fprintf('eeg_context(): Data event %d does not point to an urevent.\n',evidx);
delete(wb);
return
end
istarget = 0; % initialize target flag
tidx = 1; % initialize target type index
%
%%%%%%%%%%%%%%% cycle through target types %%%%%%%%%%%%%%%%%%
%
while ~istarget & tidx<=length(targets) % for each potential target type
uridxtype = EEG.urevent(uridx).type;
if ~ischar(uridxtype), uridxtype = num2str(uridxtype); end
if strcmpi(uridxtype,targets(tidx)) | strcmp(targets{1},'_ALL')
% if is a target type
istarget=1; % flag event as target
targetcount = targetcount+1; % increment target count
%
%%%%%%%%%%%%% find 0th neighbors (=targets themselves)
%
if ~isempty(zeroidx) % if the target event is asked for in the nbrs array
delays(targetcount,zeroidx) = 0;
if ~exist('NO_FIELD','var')
for f=1:nfieldnames
if cellfld == 0
nfields(targetcount,zeroidx,f) = EEG.urevent(uridx).(field{f});
else % cellfld == 1
nfields{targetcount,zeroidx,f} = EEG.urevent(uridx).(field{f});
end
end
end
end
if epochinfo % if the data are epoched
is0epoch = 0;
for z = 1:length(EEG.event(evidx).epoch) % for each epoch the event is in
ep = EEG.event(evidx).epoch(z);
for e = 1:length(EEG.epoch(ep).event) % for each event in the epoch
if EEG.epoch(ep).event(e) == evidx % if current event
% js : added the if ~iscell loop
if ~iscell(EEG.epoch(ep).eventlatency) % i.e. not more than 1 eventtype in the epoch
if length(EEG.epoch(ep).eventlatency(e)) == 1
trglt = EEG.epoch(ep).eventlatency(e); % get its epoch latency
else
trglt = EEG.epoch(ep).eventlatency(1); % this shouldn't happen
fprintf('EEG.epoch(%d).eventlatency(%d) length > 1 ??\n',ep,e);
end
else
if length(EEG.epoch(ep).eventlatency{e}) == 1
trglt = EEG.epoch(ep).eventlatency{e}; % get its epoch latency
else
trglt = EEG.epoch(ep).eventlatency{e}(1); % this shouldn't happen
fprintf('EEG.epoch(%d).eventlatency{%d} length > 1 ??\n',ep,e);
end;
end
if trglt == 0
targepochs(targetcount) = ep;
is0epoch = 1;
break;
end
end
end
if is0epoch
break;
end
end % for
if ~is0epoch, noepochs = noepochs+1; end
end
targs(targetcount) = evidx; % save event index
ur_trgs(targetcount) = uridx; % save urevent index
if ~exist('NO_FIELD','var')
for f=1:nfieldnames
if cellfld ==0
tfields(targetcount,f) = EEG.urevent(uridx).(field{f});
elseif cellfld == 1
tfields{targetcount,f} = EEG.urevent(uridx).(field{f});
end
end
break % stop target type checking
end
else % next target type
tidx = tidx+1; % else try next target type
end % if is target
end % while ~istarget
if istarget % if current event is a target type
targidx(targetcount) = tidx; % save index of its type within targets
if ~isempty(negpos)
%
%%%%%%%%%%%%%%%%%% find previous neighbor urevents %%%%%%%%%%%%
%
uidx = uridx-1; % begin with the previous urevent
npidx = 1; % index into negpos
curpos = 1; % current (negative) position
seekpos = negpos(npidx); % begin with first negpos position
while uidx > 0 & npidx <= nnegpos % search through previous urevents
uidxtype = EEG.urevent(uidx).type;
if ~ischar(uidxtype), uidxtype = num2str(uidxtype); end
if strcmpi(uidxtype,'boundary') % flag boundary urevents
if ~isfield(EEG.urevent,'duration') ...
| ( isnan(EEG.urevent(uidx).duration) ...
| isempty(EEG.urevent(uidx).duration)) % pre-v4.4 or real break urevent
% (NaN duration)
if ~isfield(EEG.urevent,'duration') ... % pre version-4.4 dataset
& breakwarning == 0
fprintf('Pre-v4.4 boundary urevent found - duration field not defined.');
breakwarning = 1;
end
end
break % don't search for neighbors across a boundary urevent
end
isneighbor = 0; % initialize neighbor flag
nidx = 1; % initialize neighbor type index
%
%%%%%%%%%% cycle through neighbor types %%%%%%%%%%%%%
%
while ~isneighbor & nidx<=length(neighbors) % for each neighbor event type
if strcmpi(uidxtype,neighbors(nidx)) | strcmp(neighbors,'_ALL')
isneighbor=1; % flag 'neighbors' event
curpos = curpos+1;
%
%%%%%%%%%%%%%%% if an event in one of the specified positions %%%%%
%
if curpos-1 == seekpos
delays(targetcount,negidx(npidx)) = 1000/EEG.srate * ...
(EEG.urevent(uidx).latency - EEG.urevent(uridx).latency);
% return negative latencies for negpos events
ur_nbrs(targetcount,negidx(npidx))=uidx; % mark urevent as neighbor
ur_nbrtypes(targetcount,negidx(npidx)) = nidx;
if ~exist('NO_FIELD','var')
for f=1:nfieldnames
if cellfld ==0
if nfieldnames > 1
if ~isempty(EEG.urevent(uidx).(field{f}))
nfields(targetcount,negidx(npidx),f) = EEG.urevent(uidx).(field{f});
else
nfields(targetcount,negidx(npidx),f) = NaN;
end
elseif ~isempty(EEG.urevent(uidx).(field{f}))
nfields(targetcount,negidx(npidx)) = EEG.urevent(uidx).(field{f});
else
nfields(targetcount,negidx(npidx)) = NaN;
end
elseif cellfld == 1
if nfieldnames > 1
nfields{targetcount,negidx(npidx),f} = EEG.urevent(uidx).(field{f});
else
nfields{targetcount,negidx(npidx)} = EEG.urevent(uidx).(field{f});
end
end
end
end
npidx = npidx+1; % look for next negpos position
if npidx<=nnegpos
seekpos = negpos(npidx); % new seek position
end
end % if seekpos
break % stop neighbors type checking
else
nidx = nidx+1; % try next 'neighbors' event type
end
end % nidx - neighbor-type testing loop
%
%%%%%%%%%%%%%%% find preceding neighbor event %%%%%%%%%%%%%%
%
uidx = uidx-1; % keep checking for a 'neighbors' type event
end % while uidx - urevent type checking
end % if negpos
if ~isempty(pospos)
%
%%%%%%%%%%%%%%% find succeeding position urevents %%%%%%%%%%%%
%
uidx = uridx+1; % begin with the succeeding urevent
ppidx = 1; % index into pospos
curpos = 1; % current (positive) position
seekpos = pospos(ppidx); % begin with first pospos position
while uidx <= nurevents & ppidx <= npospos % search through succeeding urevents
isneighbor = 0; % initialize neighbor flag
uidxtype = EEG.urevent(uidx).type;
if ~ischar(uidxtype), uidxtype = num2str(uidxtype); end
if strcmpi(uidxtype,'boundary') % flag boundary events
if ~isfield(EEG.urevent,'duration') ...
| ( isnan(EEG.urevent(uidx).duration) ...
| isempty(EEG.urevent(uidx).duration)) % pre-v4.4 or real break urevent
% (NaN duration)
if ~isfield(EEG.urevent,'duration') ... % pre version-4.4 dataset
& breakwarning == 0
fprintf('Pre-v4.4 boundary urevent found - duration field not defined.');
breakwarning = 1;
end
end
break % don't search for neighbors across a boundary urevent
end
pidx = 1; % initialize neighbor type index
%
%%%%%%%%%% cycle through neighbor types %%%%%%%%%%%%%
%
while ~isneighbor & pidx<=length(neighbors) % for each neighbor event type
if strcmpi(uidxtype,neighbors(pidx)) ...
| strcmp(neighbors,'_ALL')
isneighbor=1; % flag 'neighbors' event
curpos = curpos+1;
%
%%%% if an event in one of the specified positions %%%%%
%
if curpos-1 == seekpos
ur_nbrs(targetcount,posidx(ppidx))=uidx; % mark urevent as neighbor
% ur_nbrtypes{targetcount,posidx(ppidx)} = EEG.urevent(uidx).type; % note its type
ur_nbrtypes(targetcount,posidx(ppidx)) = pidx; % note its type
delays(targetcount,posidx(ppidx)) = 1000/EEG.srate * ...
(EEG.urevent(uidx).latency - EEG.urevent(uridx).latency);
% return positive latencies for pospos events
if ~exist('NO_FIELD','var')
for f=1:nfieldnames
if cellfld ==0
if nfieldnames > 1
if ~isempty(EEG.urevent(uidx).(field{f}))
nfields(targetcount,posidx(ppidx),f) = EEG.urevent(uidx).(field{f});
else
nfields(targetcount,posidx(ppidx),f) = NaN;
end
elseif ~isempty(EEG.urevent(uidx).(field{f}))
nfields(targetcount,posidx(ppidx)) = EEG.urevent(uidx).(field{f});
else
nfields(targetcount,posidx(ppidx)) = NaN;
end
else % if cellfld == 1
if nfieldnames > 1
nfields{targetcount,posidx(ppidx),f} = EEG.urevent(uidx).(field{f});
else
nfields{targetcount,posidx(ppidx)} = EEG.urevent(uidx).(field{f});
end
end
end
end
ppidx = ppidx+1;
if ppidx<=npospos
seekpos = pospos(ppidx); % new seek position
end
break % stop neighbors type checking
end % if seekpos
break
else
%
%%%%%%%%%%%% find succeeding neighbor event %%%%%%%%%%%%
%
pidx = pidx+1; % try next 'neighbors' event-type
end
end % pidx - neighbor-type testing loop
uidx = uidx+1; % keep checking for 'neighbors' type urevents
end % uidx - urevent type checking
end % if pospos
%
%%%%%%%%%%%%%%% debug mode info printout %%%%%%%%%%%%%%%%%%%%%%
%
if debug_print
fprintf('%d. ',targetcount)
if targetcount<1000, fprintf(' '); end
if targetcount<100, fprintf(' '); end
if targetcount<10, fprintf(' '); end;
if uidx > 1
%fprintf('event %-4d ttype %s - delays: ',evidx,num2str(EEG.urevent(evidx).type));
for k=1:npos
fprintf('(%d) ',ur_nbrs(targetcount,k));
if ur_nbrs(targetcount,k)<1000, fprintf(' '); end
if ur_nbrs(targetcount,k)<100, fprintf(' '); end
if ur_nbrs(targetcount,k)<10, fprintf(' '); end;
fprintf('%2.0f ',delays(targetcount,k));
end
if ~exist('NO_FIELD','var')
if cellfld == 0 % numeric field values
fprintf('fields: ')
for f=1:nfieldnames
fprintf('%-5g - ',tfields(targetcount,f))
for k=1:npos
fprintf('%-5g ',nfields(targetcount,k,f));
end
end
elseif cellfld == 1 % cell array field values
fprintf('fields: ')
for f=1:nfieldnames
if ischar(EEG.urevent(1).(field{f}))
fprintf('%-5g -',tfields{targetcount,f})
for k=1:npos
fprintf('%-5g ',nfields{targetcount,k,f});
end % k
end % ischar
end % f
end % cellfield
end % ~NO_FIELD
end % uidx > 1
fprintf('\n');
end % debug_print
end % istarget
%
%%%%%%%%%%%%%%%%% find next target event %%%%%%%%%%%%%%%%%%%%%%
%
end % if not 'boundary' event
evidx = evidx+1; % continue event checking
end % event loop
%
%%%%%%%%% delete watibar %%%%%%%%
%
if ishandle(wb), delete(wb); end;
if ~alltargs
fprintf('Returning info on the %d of %d target events that have epochs centered on them.\n',...
targetcount-noepochs,targetcount);
else
fprintf('Returning info on all %d target events (%d have epochs centered on them).\n',...
targetcount,targetcount-noepochs);
end
if debug_print
fprintf('---------------------------------------------------\n');
fprintf('ur# event # ttype targtype - delays (urnbr) ms\n');
end
%
%%%%%%%%%%%%%% Truncate the output arrays %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if targetcount > 0
targs = [targs(1:targetcount) ur_trgs(1:targetcount) ...
targepochs(1:targetcount) targidx(1:targetcount)]; % 4-column output
ur_nbrs = ur_nbrs(1:targetcount,:);
delays = delays(1:targetcount,:);
epcenttargs = find(~isnan(targs(:,3))); % find targets that have an epoch centered on them
if ~alltargs
targs = targs(epcenttargs,:);
ur_nbrs = ur_nbrs(epcenttargs,:);
delays = delays(epcenttargs,:);
end
if ~exist('NO_FIELD','var')
if cellfld == 0
tfields = tfields(1:targetcount,:);
nfields = nfields(1:targetcount,:,:);
elseif cellfld == 1
tfields = tfields(1:targetcount,:);
nfields = nfields(1:targetcount,:,:);
end
if ~alltargs
tfields = tfields(epcenttargs,:);
nfields = nfields(epcenttargs,:,:);
end
else % NO_FIELD
tfields = [];
nfields = [];
end
ur_nbrtypes = ur_nbrtypes(1:targetcount,:);
if ~alltargs
ur_nbrtypes = ur_nbrtypes(epcenttargs,:);
end
else % return nulls if no targets found
if verbose
fprintf('eeg_context(): No target type events found.\n')
end
delays = [];
targs = [];
ur_nbrs = [];
tfields = [];
nfields = [];
end
|
github
|
ZijingMao/baselineeegtest-master
|
pop_biosig16.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_biosig16.m
| 10,480 |
utf_8
|
0740b905165b210b6e1c587304d14801
|
% pop_biosig() - import data files into EEGLAB using BIOSIG toolbox
%
% Usage:
% >> OUTEEG = pop_biosig; % pop up window
% >> OUTEEG = pop_biosig( filename, channels, type);
%
% Inputs:
% filename - [string] file name
%
% Optional inputs:
% 'channels' - [integer array] list of channel indices
% 'blockrange' - [min max] integer range of data blocks to import, in seconds.
% Entering [0 3] will import the first three blocks of data.
% Default is empty -> import all data blocks.
% 'ref' - [integer] channel index or index(s) for the reference.
% Reference channels are not removed from the data,
% allowing easy re-referencing. If more than one
% channel, data are referenced to the average of the
% indexed channels. WARNING! Biosemi Active II data
% are recorded reference-free, but LOSE 40 dB of SNR
% if no reference is used!. If you do not know which
% channel to use, pick one and then re-reference after
% the channel locations are read in. {default: none}
% 'rmeventchan' - ['on'|'off'] remove event channel after event
% extraction. Default is 'on'.
%
% Outputs:
% OUTEEG - EEGLAB data structure
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Oct. 29, 2003-
%
% Note: BIOSIG toolbox must be installed. Download BIOSIG at
% http://biosig.sourceforge.net
% Contact [email protected] for troubleshooting using BIOSIG.
% 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, command] = my_pop_biosig(filename, varargin);
EEG = [];
command = '';
if nargin < 1
% ask user
[filename, filepath] = uigetfile('*.*', 'Choose an BDF file -- pop_biosig()'); %%% this is incorrect in original version!!!!!!!!!!!!!!
drawnow;
if filename == 0 return; end;
filename = [filepath filename];
% open file to get infos
% ----------------------
disp('Reading data file header...');
dat = sopen(filename);
% special BIOSEMI
% ---------------
if strcmpi(dat.TYPE, 'BDF')
disp('We highly recommend that you choose a reference channel IF these are Biosemi data');
disp('(e.g., a mastoid or other channel). Otherwise the data will lose 40 dB of SNR!');
end;
uilist = { { 'style' 'text' 'String' 'Channel list (defaut all):' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'String' [ 'Data range (in seconds) to read (default all [0 ' int2str(dat.NRec) '])' ] } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'String' 'Extract event - cannot be unset (set=yes)' } ...
{ 'style' 'checkbox' 'string' '' 'value' 1 'enable' 'on' } {} ...
{ 'style' 'text' 'String' 'Import continuous data (set=yes)' 'value' 1} ...
{ 'style' 'checkbox' 'string' '' 'value' 0 } {} ...
{ 'style' 'text' 'String' 'Reference chan(s) indices - required for BIOSEMI' } ...
{ 'style' 'edit' 'string' '' } };
geom = { [3 1] [3 1] [3 0.35 0.5] [3 0.35 0.5] [3 1] };
result = inputgui( geom, uilist, 'pophelp(''pop_biosig'')', ...
'Load data using BIOSIG -- pop_biosig()');
if length(result) == 0 return; end;
% decode GUI params
% -----------------
options = {};
if ~isempty(result{1}), options = { options{:} 'channels' eval( [ '[' result{1} ']' ] ) }; end;
if ~isempty(result{2}), options = { options{:} 'blockrange' eval( [ '[' result{2} ']' ] ) }; end;
if length(result) > 2
if ~isempty(result{4}), options = { options{:} 'ref' eval( [ '[' result{4} ']' ] ) }; end;
if ~result{3}, options = { options{:} 'rmeventchan' 'off' }; end;
end;
else
options = varargin;
end;
% decode imput parameters
% -----------------------
g = finputcheck( options, { 'blockrange' 'integer' [0 Inf] [];
'channels' 'integer' [0 Inf] [];
'ref' 'integer' [0 Inf] [];
'rmeventchan' 'string' { 'on';'off' } 'on' }, 'pop_biosig');
if isstr(g), error(g); end;
% import data
% -----------
EEG = eeg_emptyset;
if ~isempty(g.channels)
dat = sopen(filename, 'r', g.channels,'OVERFLOWDETECTION:OFF');
else dat = sopen(filename, 'r', 0,'OVERFLOWDETECTION:OFF');
end
fprintf('Reading data in %s format...\n', dat.TYPE);
if ~isempty(g.blockrange)
newblockrange = g.blockrange;
newblockrange(2) = min(newblockrange(2), dat.NRec);
newblockrange = newblockrange*dat.Dur;
DAT=sread(dat, newblockrange(2)-newblockrange(1), newblockrange(1))';
else
DAT=sread(dat, Inf)';% this isn't transposed in original!!!!!!!!
newblockrange = [];
end
dat = sclose(dat);
% convert to seconds for sread
% ----------------------------
EEG.nbchan = size(DAT,1);
EEG.srate = dat.SampleRate(1);
EEG.data = DAT;
clear DAT;
% $$$ try % why would you do the following??????? JO
% $$$ EEG.data = EEG.data';
% $$$ catch,
% $$$ pack;
% $$$ EEG.data = EEG.data';
% $$$ end;
EEG.setname = sprintf('%s file', dat.TYPE);
EEG.comments = [ 'Original file: ' filename ];
EEG.xmin = 0;
if strcmpi(dat.TYPE, 'BDF') || strcmpi(dat.TYPE, 'EDF')
EEG.trials = 1;
EEG.pnts = size(EEG.data,2);
else
EEG.trials = dat.NRec;
EEG.pnts = size(EEG.data,2)/dat.NRec;
end
if isfield(dat, 'Label') & ~isempty(dat.Label)
EEG.chanlocs = struct('labels', cellstr(char(dat.Label)));
end
EEG = eeg_checkset(EEG);
% extract events % this part I totally revamped to work... JO
% --------------
disp('Extracting events from last EEG channel...');
EEG.event = [];
% $$$ startval = mode(EEG.data(end,:)); % my code
% $$$ for p = 2:size(EEG.data,2)-1
% $$$ [codeout] = code(EEG.data(end,p));
% $$$ if EEG.data(end,p) > EEG.data(end,p-1) & EEG.data(end,p) >= EEG.data(end,p+1)
% $$$ EEG.event(end+1).latency = p;
% $$$ EEG.event(end).type = bitand(double(EEG.data(end,p)-startval),255);
% $$$ end;
% $$$ end;
% lastout = mod(EEG.data(end,1),256);newevs = []; % andrey's code 8 bits
% codeout = mod(EEG.data(end,2),256);
% for p = 2:size(EEG.data,2)-1
% nextcode = mod(EEG.data(end,p+1),256);
% if codeout > lastout & codeout >= nextcode
% newevs = [newevs codeout];
% EEG.event(end+1).latency = p;
% EEG.event(end).type = codeout;
% end;
% lastout = codeout;
% codeout = nextcode;
% end;
%lastout = mod(EEG.data(end,1),256*256);newevs = []; % andrey's code 16 bits
%codeout = mod(EEG.data(end,2),256*256);
%for p = 2:size(EEG.data,2)-1
% nextcode = mod(EEG.data(end,p+1),256*256);
% if (codeout > lastout) & (codeout >= nextcode)
% newevs = [newevs codeout];
% EEG.event(end+1).latency = p;
% EEG.event(end).type = codeout;
% end;
% lastout = codeout;
% codeout = nextcode;
%end;
% Modifieded by Andrey (Aug.5,2008) to detect all non-zero codes:
thiscode = 0;
for p = 1:size(EEG.data,2)-1
prevcode = thiscode;
thiscode = mod(EEG.data(end,p),256*256); % andrey's code - 16 bits
if (thiscode ~= 0) && (thiscode~=prevcode)
EEG.event(end+1).latency = p;
EEG.event(end).type = thiscode;
end;
end;
if strcmpi(g.rmeventchan, 'on')
EEG.data(dat.BDF.Status.Channel,:) = [];
EEG.nbchan = size(EEG.data,1);
if ~isempty(EEG.chanlocs)
EEG.chanlocs(dat.BDF.Status.Channel,:) = [];
end;
end;
EEG = eeg_checkset(EEG, 'eventconsistency');
% $$$ if ~isempty(dat.EVENT)
% $$$ if isfield(dat, 'out') % Alois fix for event interval does not work
% $$$ if isfield(dat.out, 'EVENT')
% $$$ dat.EVENT = dat.out.EVENT;
% $$$ end;
% $$$ end;
% $$$ if ~isempty(newblockrange)
% $$$ interval(1) = newblockrange(1) * dat.SampleRate(1) + 1;
% $$$ interval(2) = newblockrange(2) * dat.SampleRate(1);
% $$$ else interval = [];
% $$$ end
% $$$ EEG.event = biosig2eeglabevent(dat.EVENT, interval); % Toby's fix
% $$$ if strcmpi(g.rmeventchan, 'on') & strcmpi(dat.TYPE, 'BDF') & isfield(dat, 'BDF')
% $$$ disp('Removing event channel...');
% $$$ EEG.data(dat.BDF.Status.Channel,:) = [];
% $$$ EEG.nbchan = size(EEG.data,1);
% $$$ if ~isempty(EEG.chanlocs)
% $$$ EEG.chanlocs(dat.BDF.Status.Channel,:) = [];
% $$$ end;
% $$$ end;
% $$$ EEG = eeg_checkset(EEG, 'eventconsistency');
% $$$ else
% $$$ disp('Warning: no event found. Events might be embeded in a data channel.');
% $$$ disp(' To extract events, use menu File > Import Event Info > From data channel');
% $$$ end;
% rerefencing
% -----------
if ~isempty(g.ref)
disp('Re-referencing...');
EEG.data = EEG.data - repmat(mean(EEG.data(g.ref,:),1), [size(EEG.data,1) 1]);
if length(g.ref) == size(EEG.data,1)
EEG.ref = 'averef';
end;
if length(g.ref) == 1
disp([ 'Warning: channel ' int2str(g.ref) ' is now zeroed (but still present in the data)' ]);
else
disp([ 'Warning: data matrix rank has decreased through re-referencing' ]);
end;
end;
% convert data to single if necessary
% -----------------------------------
EEG = eeg_checkset(EEG,'makeur'); % Make EEG.urevent field
EEG = eeg_checkset(EEG);
% history
% -------
if isempty(options)
command = sprintf('EEG = my_pop_biosig(''%s'');', filename);
else
command = sprintf('EEG = my_pop_biosig(''%s'', %s);', filename, vararg2str(options));
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_chanevent.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_chanevent.m
| 14,346 |
utf_8
|
6dd2b5a53ddab6deffe78bae70f589b9
|
% pop_chanevent() - import event latencies from the rising and/or falling 'edge'
% latencies of a specified event-marker channel in EEG.data
% Usage:
% >> OUTEEG = pop_chanevent( INEEG ); % select parameters via a pop-up window
% >> OUTEEG = pop_chanevent( INEEG, chanindices, 'key', 'val' ... ); % no pop-up
%
% Graphic interface:
% "Event channel(s)" - [edit box] indices of event channel(s) to import.
% Command line equivalent: chanindices.
% "Preprocessing transform" - [edit box] apply this preprocessing
% formula or function to the selected data channel(s) X,
% transforming X into the command output before edge
% extraction. Command line equivalent 'oper'.
% "Transition to extract" - [list box] extract events when the event
% channel values go up ('leading'), down ('trailing')
% or both ('both'). Command line equivalent: 'edge'.
% "Transition length" - [edit box] Increase this number to avoid having
% events very close to each other due to a not perfectly
% straight edge. Command line equivalent: 'edgelen'.
% "Assign duration to events?" - [checkbox] . Assign duration to each
% extracted event. This option can only be used when
% extracting events on leading edges. Event will last
% until next trailing edge (down) event. Command line
% equivalent: 'duration'.
% "Delete event channel(s)" - [checkbox] check to delete the event channel
% after events have been extracted from it.
% Command line equivalent: 'delchan'.
% "Delete old events if any" - [checkbox] check this checkbox to
% remove any prior events in the dataset. Otherwise
% imported events are appended to old events. Command
% line equivalent: 'delevent'.
% "Only one event type" - [checkbox] check this checkbox to assign
% all transitions in the event channel to one event
% type. Else, one type is assigned for each non-zero
% channel value. Command line equivalent: 'nbtype'.
% Inputs:
% INEEG - input dataset structure
% chanindices - index|(indices) of the event channel(s)
%
% Optional inputs:
% 'edge' - ['leading'|'trailing'|'both'] extract events when values
% in the event channel go up ('leading'), down ('trailing')
% or both ('both'). {Default is 'both'}.
% 'edgelen' - [integer] maximum edge length (for some data edge do not
% take whole value and it takes a few sample points for
% signal to rise. Default is 1 (perfect edges).
% 'oper' - [string] prior to extracting edges, preprocess data
% channel(s) using the string command argument.
% In this command, the data channel(s) are designated by
% (capital) X. For example, 'X>3' will test the value of X
% at each time point (returning 1 if the data channel value
% is larger than 3, and 0 otherwise). You may also use
% any function (Ex: 'myfunction(X)').
% 'duration' - ['on'|'off'] extract event duration. This option can only be
% used when extracting events on leading edges. Event will last
% until next trailing-edge (down) event { 'off' }.
% 'delchan' - ['on'|'off'] delete channel from data { 'on' }.
% 'delevent' - ['on'|'off'] delete old events if any { 'on' }.
% 'nbtype' - [1|NaN] setting this to 1 will force the program to
% consider all events to have the same type. {Default is NaN}.
% If set (1), all transitions are considered the same event type
% If unset (NaN), each (transformed) event channel value following a
% transition determines an event type (Ex: Detecting leading-edge
% transitions of 0 0 1 0 2 0 ... produces event types 1 and 2).
% 'typename' - [string] event type name. Only relevant if 'nbtype' is 1
% or if there is only one event type in the event channel.
% {Default is 'chanX', X being the index of
% the selected event channel}.
% Outputs:
% OUTEEG - EEGLAB output data structure
%
% Author: Arnaud Delorme, CNL / Salk Institute, 29 July 2002
%
% See also: eeglab()
% Copyright (C) 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, command] = pop_chanevent(EEG, chan, varargin);
command = '';
if nargin < 1
help pop_chanevent;
return;
end;
if nargin < 2
geometry = { [1.5 1 1] [1] [1.5 1 1] [1.5 1 1] [1.5 1 1] [1.5 0.2 0.36 0.84] ...
[1] [1.5 0.21 1] [1.5 0.21 1] [1.5 0.21 1] };
% callback from listbox to disable duration checkbox (if leading event is not selected)
% --------------------------------------------------
cb_list = [ 'if get(gcbo, ''value'') == 1,' ...
' set(findobj(gcbf, ''tag'', ''dur''), ''enable'', ''on'');' ...
'else,' ...
' set(findobj(gcbf, ''tag'', ''dur''), ''enable'', ''off'', ''value'', 0);' ...
'end;' ];
strgui = { { 'style' 'text' 'string' 'Event channel(s)' 'tooltipstring' 'indexes of event channels' } ...
{ 'style' 'edit' 'string' '' } { } ...
{} ...
{ 'style' 'text' 'string' 'Preprocessing transform (data=''X'')' 'tooltipstring' ...
[ 'For example, ''X>3'' will test the value of X' 10 ...
'at each time point (returning 1 if the data channel value' 10 ...
'is larger than 3, and 0 otherwise).' ] } ...
{ 'style' 'edit' 'string' '' } { 'style' 'text' 'string' 'Optional. Ex: X>3' } ...
{ 'style' 'text' 'string' 'Transitions to extract? (up|down)' 'tooltipstring' ...
[ 'Extract events whenever values in the (transformed) event channel(s) shift up' 10 ...
'(''leading''), down (''trailing'') or either (''both'').' 10 ...
'AFTER SCROLLING CLICK TO SELECT' ] } ...
{ 'style' 'listbox' 'string' 'up (leading)|both|down (trailing)' 'value' 1 'callback' cb_list } ...
{ 'style' 'text' 'string' '(click to select)'} ...
{ 'style' 'text' 'string' 'Transition length (1=perfect edges)' 'tooltipstring' ...
[ 'Increase this number to avoid having events very close to each other due.' 10 ...
'to a not perfectly straight edge' ] } ...
{ 'style' 'edit' 'string' '0' } { } ...
{ 'style' 'text' 'string' 'Assign duration to each events?' 'tag' 'dur' 'tooltipstring' ...
[ 'You may assign an event duration to each event if you select to detect' 10 ...
'event on the leading edge above. Event will last as long as the signal is non-0.' ] } ...
{ 'style' 'checkbox' 'string' '' 'value' 0 'tag' 'dur'} { } ...
{ 'style' 'text' 'string' '(set=yes)' } ...
{} ...
{ 'style' 'text' 'string' 'Delete event channel(s)? ' } ...
{ 'style' 'checkbox' 'value' 1 } { 'style' 'text' 'string' ' (set = yes)'} ...
{ 'style' 'text' 'string' 'Delete old events if any? ' } ...
{ 'style' 'checkbox' 'value' 1 } { } ...
{ 'style' 'text' 'string' 'All events of same type? ' 'tooltipstring' ...
['If set, all transitions are considered the same event type,' 10 ...
'If unset, each (transformed) event channel value following a transition' 10 ...
'determines an event type (Ex: Detecting leading-edge transitions of' 10 ...
'0 0 1 0 2 0 ... produces event types 1 and 2).' ] } ...
{ 'style' 'checkbox' 'value' 0 } { } };
result = inputgui( geometry, strgui, 'pophelp(''pop_chanevent'');', 'Extract event from channel(s) - pop_chanevent()');
if length(result) == 0 return; end;
chan = eval( [ '[' result{1} ']' ] );
options = {};
if ~isempty(result{2}), options = { options{:} 'oper' result{2} }; end;
switch result{3},
case 1, options = { options{:} 'edge' 'leading' };
case 2, options = { options{:} 'edge' 'both' };
case 3, options = { options{:} 'edge' 'trailing' };
end;
options = { options{:} 'edgelen' eval( [ '[' result{4} ']' ] ) };
if result{5}, options = { options{:} 'duration' 'on' }; end;
if ~result{6}, options = { options{:} 'delchan' 'off'}; end;
if ~result{7}, options = { options{:} 'delevent' 'off'}; end;
if result{8}, options = { options{:} 'nbtype' 1}; end;
else
options = varargin;
end;
listcheck = { 'edge' 'string' { 'both';'leading';'trailing'} 'both';
'edgelen' 'integer' [1 Inf] 1;
'delchan' 'string' { 'on';'off' } 'on';
'oper' 'string' [] '';
'delevent' 'string' { 'on';'off' } 'on';
'duration' 'string' { 'on';'off' } 'off';
'typename' 'string' [] [ 'chan' int2str(chan) ];
'nbtype' 'integer' [1 NaN] NaN };
g = finputcheck( options, listcheck, 'pop_chanedit');
if isstr(g), error(g); end;
% check inut consistency
% ----------------------
if strcmpi(g.duration, 'on') & ~strcmpi(g.edge, 'leading')
error('Must detect leading edge to extract event duration');
end;
% process events
% --------------
fprintf('pop_chanevent: importing events from data channel %d ...\n', chan);
counte = 1; % event counter
events(10000).latency = 0;
if isnan(g.nbtype)
if length(unique(EEG.data(chan, :))) == 2, g.nbtype = 1; end;
end;
for ci = chan
X = EEG.data(ci, :);
% apply preprocessing
% -------------------
if ~isempty(g.oper)
try, eval( [ 'X = ' g.oper ';' ]);
catch, error('pop_chanevent: error executing preprocessing string');
end;
end;
% extract edges
% -------------
tmpdiff = diff(abs([ X X(end) ]));
switch g.edge
case 'both' , tmpevent1 = find( tmpdiff > 0)-1; tmpevent2 = find( tmpdiff < 0);
case 'trailing', tmpevent2 = find( tmpdiff < 0);
case 'leading' , tmpevent1 = find( tmpdiff > 0)-1; tmpdur = find( tmpdiff < 0);
end;
% fuse close events if necessary
% ------------------------------
if exist('tmpevent1')
tmpclose = find( tmpevent1(2:end)-tmpevent1(1:end-1) < g.edgelen)+1;
tmpevent1(tmpclose) = [];
tmpevent = tmpevent1+1;
tmpeventval = tmpevent1+2;
end;
if exist('tmpevent2')
tmpclose = find( tmpevent2(2:end)-tmpevent2(1:end-1) < g.edgelen); % not +1
tmpevent2(tmpclose) = [];
tmpevent = tmpevent2+1;
tmpeventval = tmpevent2;
end;
if exist('tmpevent1') & exist('tmpevent2')
tmpevent = sort([ tmpevent1+1 tmpevent2+1]);
tmpeventval = sort([ tmpevent1+2 tmpevent2]);
end;
% adjust edges for duration if necessary
% ---------------------------------------
if strcmpi(g.duration, 'on')
tmpclose = find( tmpdur(2:end)-tmpdur(1:end-1) < g.edgelen); % not +1 (take out the first)
tmpdur(tmpclose) = [];
if tmpdur(1) < tmpevent(1), tmpdur(1) = []; end;
if length(tmpevent) > length(tmpdur), tmpdur(end+1) = EEG.pnts; end;
if length(tmpevent) ~= length(tmpdur)
error([ 'Error while attempting to extract event durations' 10 ...
'Maybe edges are not perfectly defined, try increasing edge length' ]);
end;
end;
if isempty(tmpevent),
fprintf('No event found for channel %d\n', ci);
else
for tmpi = 1:length(tmpevent)
if ~isnan(g.nbtype)
events(counte).type = g.typename;
else
events(counte).type = X(tmpeventval(tmpi));
end;
events(counte).latency = tmpevent(tmpi);
if strcmpi(g.duration, 'on')
events(counte).duration = tmpdur(tmpi) - tmpevent(tmpi);
end;
counte = counte+1;
end;
end;
events = events(1:counte-1);
end;
% resort events
% --------------
if strcmp(g.delevent, 'on')
EEG.event = events;
if EEG.trials > 1
for index = 1:length(events)
EEG.event(index).epoch = 1+floor((EEG.event(index).latency-1) / EEG.pnts);
end;
end;
else
for index = 1:length(events)
EEG.event(end+1).type = events(index).type;
EEG.event(end).latency = events(index).latency;
if EEG.trials > 1 | isfield(EEG.event, 'epoch');
EEG.event(end).epoch = 1+floor((EEG.event(end).latency-1) / EEG.pnts);
end;
end;
if EEG.trials > 1
EEG = pop_editeventvals( EEG, 'sort', { 'epoch' 0 'latency', [0] } );
else
EEG = pop_editeventvals( EEG, 'sort', { 'latency', [0] } );
end;
end;
if isfield(EEG.event, 'urevent'), EEG.event = rmfield(EEG.event, 'urevent'); end;
EEG = eeg_checkset(EEG, 'eventconsistency');
EEG = eeg_checkset(EEG, 'makeur');
% delete channels
% ---------------
if strcmp(g.delchan, 'on')
EEG = pop_select(EEG, 'nochannel', chan);
end;
if nargin < 2
command = sprintf('%s = pop_chanevent(%s, %s);', inputname(1), inputname(1), ...
vararg2str({ chan options{:} }));
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_rejspec.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_rejspec.m
| 12,800 |
utf_8
|
58cb37f8656d637dfad891aa266b393f
|
% pop_rejspec() - rejection of artifact in a dataset using
% thresholding of frequencies in the data.
% Usage:
% >> pop_rejspec(INEEG, typerej); % pop-up interactive window mode
% >> [OUTEEG, Indices] = pop_rejspec( INEEG, typerej, 'key', val, ...);
%
% Pop-up window options:
% "Electrode|Component" - [edit box] electrode or component number(s) to
% take into consideration for rejection. Sets the 'elecrange'
% parameter in the command line call (see below).
% "Lower limits(s)" - [edit box] lower threshold limits(s) (in dB).
% Sets the command line parameter 'threshold'. If more than
% one, apply to each electrode|component individually. If
% fewer than number of electrodes|components, apply the
% last values to all remaining electrodes|components.
% "Upper limits(s)" - [edit box] upper threshold limit(s) in dB.
% Sets the command line parameter 'threshold'.
% "Low frequency(s)" - [edit box] low-frequency limit(s) in Hz.
% Sets the command line parameter 'freqlimits'.
% "High frequency(s)" - [edit box] high-frequency limit(s) in Hz.
% Sets the command line parameter 'freqlimits'.
% "Display previous rejection marks?" - [edit box] either YES or NO.
% Sets the command line input option 'eegplotplotallrej'.
% "Reject marked trials?" - [edit box] either YES or NO. Sets the
% command line input option 'eegplotreject'.
%
% Command line inputs:
% INEEG - input dataset
% typerej - [1|0] data to reject on (0 = component activations; 1 =
% electrode data). {Default is 1}.
%
% Optional arguments.
% 'elecrange' - [e1 e2 ...] array of indices of electrode|component
% number(s) to take into consideration during rejection.
% 'threshold' - [lower upper] threshold limit(s) in dB.
% 'freqlimits' - [lower upper] frequency limit(s) in Hz.
% 'method' - ['fft'|'multitaper'] method to compute spectrum.
% 'specdata' - [array] precomputed spectral data.
% 'eegplotcom' - [string] EEGPLOT command to execute when pressing the
% reject button (see 'command' input of EEGPLOT).
% 'eegplotreject' - [0|1] 0 = Do not reject marked trials (but store the
% marks. 1 = Reject marked trials. {Default: 1}.
% 'eegplotplotallrej' - [0|1] 0 = Do not superpose rejection marks on previous
% marks stored in the dataset. 1 = Show both previous and
% current marks using different colors. {Default: 0}.
%
% Outputs:
% OUTEEG - output dataset with updated spectrograms
% Indices - index of rejected trials
% Note: When eegplot() is called, modifications are applied to the current
% dataset at the end of the call to eegplot() (e.g., when the user presses
% the 'Reject' button).
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001-
%
% See also: eegthresh(), 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
% 01-25-02 reformated help & license -ad
% 03-07-02 added srate argument to eegplot call -ad
% 03-08-02 reworked spectrum to save space & add eeglab options -ad
function [EEG, Irej, com] = pop_rejspec( EEG, icacomp, varargin);
%elecrange, negthresh, posthresh, ...
%startfreq, endfreq, superpose, reject);
Irej = [];
com = '';
if nargin < 1
help pop_rejspec;
return;
end;
if nargin < 2
icacomp = 1;
end;
if icacomp == 0
if isempty( EEG.icasphere )
ButtonName=questdlg( 'Do you want to run ICA now ?', ...
'Confirmation', 'NO', 'YES', 'YES');
switch ButtonName,
case 'NO', disp('Operation cancelled'); return;
case 'YES', [ EEG com ] = pop_runica(EEG);
end % switch
end;
end;
if nargin < 3
% which set to save
% -----------------
promptstr = { fastif(icacomp==0, 'Component number(s) (Ex: 2 4 5):', ...
'Electrode number(s) (Ex: 2 4 5):'), ...
'Lower limit(s) (dB):', ...
'Upper limit(s) (dB):', ...
'Low frequency(s) (Hz):', ...
'High frequency(s) (Hz):', ...
'Display previous rejection marks? (YES or NO)', ...
'Reject marked trial(s)? (YES or NO)' };
inistr = { ['1:' int2str(EEG.nbchan)], ...
'-30', ...
'30', ...
'15', ...
'30', ...
'NO', ...
'NO' };
result = inputdlg2( promptstr, fastif(~icacomp, 'Reject by component spectra -- pop_rejspec()', ...
'Reject by data spectra -- pop_rejspec()'), 1, inistr, 'pop_rejspec');
size_result = size( result );
if size_result(1) == 0 return; end;
options = {};
options = { options{:} 'elecrange' eval( [ '[' result{1} ']' ] ) };
thresholdsLow = eval( [ '[' result{2} ']' ] );
thresholdsHigh = eval( [ '[' result{3} ']' ] );
options = { options{:} 'threshold' [thresholdsLow(:) thresholdsHigh(:) ] };
freqLimitsLow = eval( [ '[' result{4} ']' ] );
freqLimitsHigh = eval( [ '[' result{5} ']' ] );
options = { options{:} 'freqlimits' [freqLimitsLow(:) freqLimitsHigh(:) ] };
switch lower(result{6}), case 'yes', superpose=1; otherwise, superpose=0; end;
switch lower(result{7}), case 'yes', reject=1; otherwise, reject=0; end;
options = { options{:} 'eegplotplotallrej' superpose };
options = { options{:} 'eegplotreject' reject };
else
if isnumeric(varargin{3}) || ~isempty(str2num(varargin{3}))
options = {};
if isstr(varargin{1}), varargin{1} = str2num(varargin{1}); end;
if isstr(varargin{2}), varargin{2} = str2num(varargin{2}); end;
if isstr(varargin{3}), varargin{3} = str2num(varargin{3}); end;
if isstr(varargin{4}), varargin{4} = str2num(varargin{4}); end;
if isstr(varargin{5}), varargin{5} = str2num(varargin{5}); end;
if nargin > 2, options = { options{:} 'elecrange' varargin{1} }; end;
if nargin > 3, options = { options{:} 'threshold' [ varargin{2}; varargin{3}]' }; end;
if nargin > 5, options = { options{:} 'freqlimits' [ varargin{4}; varargin{5}]' }; end;
if nargin > 7, options = { options{:} 'eegplotplotallrej' varargin{6} }; end;
if nargin > 8, options = { options{:} 'eegplotreject' varargin{7} }; end;
if nargin > 9, options = { options{:} 'eegplotcom' varargin{8} }; end;
else
options = varargin;
end;
end;
opt = finputcheck( options, { 'elecrange' 'integer' [] [1:EEG.nbchan];
'threshold' 'real' [] [-30 30];
'freqlimits' 'real' [] [15 30];
'specdata' 'real' [] EEG.specdata;
'eegplotcom' 'string' [] '';
'method' 'string' { 'fft';'multitaper' } 'multitaper';
'eegplotreject' 'integer' [] 0;
'eegplotplotallrej' 'integer' [] 0 }, 'pop_rejspec');
if isstr(opt), error(opt); end;
sizewin = 2^nextpow2(EEG.pnts);
if icacomp == 1
[allspec, Irej, tmprejE, freqs ] = spectrumthresh( EEG.data, opt.specdata, ...
opt.elecrange, EEG.srate, opt.threshold(:,1)', opt.threshold(:,2)', opt.freqlimits(:,1)', opt.freqlimits(:,2)', opt.method);
rejE = zeros(EEG.nbchan, EEG.trials);
rejE(opt.elecrange,Irej) = tmprejE;
else
% test if ICA was computed
% ------------------------
icaacttmp = eeg_getdatact(EEG, 'component', [1:size(EEG.icaweights,1)]);
[allspec, Irej, tmprejE, freqs ] = spectrumthresh( icaacttmp, EEG.specicaact, ...
opt.elecrange, EEG.srate, opt.threshold(:,1)', opt.threshold(:,2)', opt.freqlimits(:,1)', opt.freqlimits(:,2)', opt.method);
rejE = zeros(size(EEG.icaweights,1), size(icaacttmp,1));
rejE(opt.elecrange,Irej) = tmprejE;
end;
fprintf('%d channel selected\n', size(opt.elecrange(:), 1));
fprintf('%d/%d trials marked for rejection\n', length(Irej), EEG.trials);
rej = zeros( 1, EEG.trials);
rej(Irej) = 1;
if nargin < 3 || opt.eegplotplotallrej == 2
nbpnts = size(allspec,2);
if icacomp == 1 macrorej = 'EEG.reject.rejfreq';
macrorejE = 'EEG.reject.rejfreqE';
else macrorej = 'EEG.reject.icarejfreq';
macrorejE = 'EEG.reject.icarejfreqE';
end;
colrej = EEG.reject.rejfreqcol;
elecrange = opt.elecrange;
superpose = opt.eegplotplotallrej;
reject = opt.eegplotreject;
topcommand = opt.eegplotcom;
eeg_rejmacro; % script macro for generating command and old rejection arrays
if icacomp == 1
eegplot(EEG.data(opt.elecrange,:,:), 'winlength', 5, 'position', [100 550 800 500], ...
'limits', [EEG.xmin EEG.xmax]*1000, 'xgrid', 'off', 'tag', 'childEEG' );
else
eegplot(icaacttmp(opt.elecrange,:,:), 'winlength', 5, 'position', [100 550 800 500], 'limits', ...
[EEG.xmin EEG.xmax]*1000 , 'xgrid', 'off', 'tag', 'childEEG' );
end;
eegplot( allspec(elecrange,:,:), 'srate', EEG.srate, 'freqlimits', [1 EEG.srate/2], 'command', ...
command, 'children', findobj('tag', 'childEEG'), 'position', [100 50 800 500], eegplotoptions{:});
end;
if ~isempty(rej)
if icacomp == 1
EEG.reject.rejfreq = rej;
EEG.reject.rejfreqE = rejE;
else
EEG.reject.icarejfreq = rej;
EEG.reject.icarejfreqE = rejE;
end;
if opt.eegplotreject
EEG = pop_rejepoch(EEG, rej, 0);
end;
Irej = find(rej);
end;
% store variables
% ---------------
if icacomp == 1, EEG.specdata = allspec;
else, EEG.specicaact = allspec;
end;
com = [com sprintf('%s = pop_rejspec( %s, %s);', inputname(1), ...
inputname(1), vararg2str({icacomp, 'elecrange', opt.elecrange, 'threshold', opt.threshold, 'freqlimits', opt.freqlimits, ...
'eegplotcom', opt.eegplotcom, 'eegplotplotallrej' opt.eegplotplotallrej 'eegplotreject' opt.eegplotreject })) ];
return;
% compute spectrum and reject artifacts
% -------------------------------------
function [specdata, Irej, Erej, freqs ] = spectrumthresh( data, specdata, elecrange, srate, negthresh, posthresh, startfreq, endfreq, method);
% compute the fft if necessary - old version
if isempty(specdata)
if strcmpi(method, 'fft')
sizewin = size(data,2);
freqs = srate*[1, sizewin]/sizewin/2;
specdata = fft( data-repmat(mean(data,2), [1 size(data,2) 1]), sizewin, 2);
specdata = specdata( :, 2:sizewin/2+1, :);
specdata = 10*log10(abs( specdata ).^2);
specdata = specdata - repmat( mean(specdata,3), [1 1 size(data,3)]);
else
if ~exist('pmtm')
error('The signal processing toolbox needs to be installed');
end;
[tmp freqs] = pmtm( data(1,:,1), [],[],srate); % just to get the frequencies
fprintf('Computing spectrum (using slepian tapers; done only once):\n');
for index = 1:size(data,1)
fprintf('%d ', index);
for indextrials = 1:size(data,3)
[ tmpspec(index,:,indextrials) freqs] = pmtm( data(index,:,indextrials) , [],[],srate);
end;
end;
tmpspec = 10*log(tmpspec);
tmpspec = tmpspec - repmat( mean(tmpspec,3), [1 1 size(data,3)]);
specdata = tmpspec;
end;
else
if strcmpi(method, 'fft')
sizewin = size(data,2);
freqs = srate*[1, sizewin]/sizewin/2;
else
[tmp freqs] = pmtm( data(1,:,1), [],[],srate); % just to get the frequencies
end;
end;
% perform the rejection
% ---------------------
[I1 Irej NS Erej] = eegthresh( specdata(elecrange, :, :), size(specdata,2), 1:length(elecrange), negthresh, posthresh, ...
[freqs(1) freqs(end)], startfreq, min(freqs(end), endfreq));
fprintf('\n');
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.