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
readegi.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/readegi.m
5,517
utf_8
de08c5adb26f9e5f5987d0b8a286debe
% readegi() - read EGI Simple Binary datafile (versions 2,3,4,5,6,7). % Return header info, EEG data, and any event data. % Usage: % >> [head, TrialData, EventData, CatIndex] = readegi(filename, dataChunks, forceversion) % % Required Input: % filename = EGI data filename % % Optional Input: % dataChunks = vector containing desired frame numbers(for unsegmented % datafiles) or segments (for segmented files). If this % input is empty or is not provided then all data will be % returned. % forceversion = integer from 2 to 7 which overrides the EGI version read from the % file header. This has been occasionally necessary in cases where % the file format was incorrectly indicated in the header. % Outputs: % head = struct containing header info (see readegihdr() ) % TrialData = EEG channel data % EventData = event codes % CatIndex = segment category indices % % Author: Cooper Roddey, SCCN, 13 Nov 2002 % % Note: code derived from C source code written by % Tom Renner at EGI, Inc. % % See also: readegihdr() % Copyright (C) 2002 , Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [head, TrialData, EventData, SegmentCatIndex] = readegi(filename, dataChunks,forceversion) if nargin <1 | nargin > 3, help readegi; return; end if nargout < 2 | nargout > 4, error('2 to 4 output args required'); end if ~exist('dataChunks','var') dataChunks = []; end if ~isvector(dataChunks) error('dataChunks must either be empty or a vector'); end [fid,message] = fopen(filename,'rb','b'); if (fid < 0), error(message); end % get our header structure fprintf('Importing binary EGI data file ...\n'); if exist('forceversion') head = readegihdr(fid,forceversion); else head = readegihdr(fid); end % do we have segmented data? segmented = 0; switch(head.version), case {2,4,6} segmented = 0; case {3,5,7} segmented = 1; end % each type of event has a dedicated "channel" FrameVals = head.nchan + head.eventtypes; if (segmented) desiredSegments = dataChunks; if isempty(desiredSegments), desiredSegments = [1:head.segments]; end nsegs = length(desiredSegments); TrialData = zeros(FrameVals,head.segsamps*nsegs); readexpected = FrameVals*head.segsamps*nsegs; else desiredFrames = dataChunks; if isempty(desiredFrames), desiredFrames = [1:head.samples]; end nframes = length(desiredFrames); TrialData = zeros(FrameVals,nframes); readexpected = FrameVals*nframes; end % get datatype from version number switch(head.version) case {2,3} datatype = 'integer*2'; case {4,5} datatype = 'float32'; case {6,7} datatype = 'float64'; otherwise, error('Unknown data format'); end % read in epoch data readtotal = 0; j=0; SegmentCatIndex = []; if (segmented), for i=1:head.segments, segcatind = fread(fid,1,'integer*2'); segtime = fread(fid,1,'integer*4'); [tdata, count] = ... fread(fid,[FrameVals,head.segsamps],datatype); % check if this segment is one of our desired ones if ismember(i,desiredSegments) j=j+1; SegmentCatIndex(j) = segcatind; SegmentStartTime(j) = segtime; TrialData(:,[1+(j-1)*head.segsamps:j*head.segsamps]) = tdata; readtotal = readtotal + count; end if (j >= nsegs), break; end; end; else % read unsegmented data % if dataChunks is empty, read all frames if isempty(dataChunks) [TrialData, readtotal] = fread(fid, [FrameVals,head.samples],datatype); else % grab only the desiredFrames % This could take a while... for i=1:head.samples, [tdata, count] = fread(fid, [FrameVals,1],datatype); % check if this segment is a keeper if ismember(i,desiredFrames), j=j+1; TrialData(:,j) = tdata; readtotal = readtotal + count; end if (j >= nframes), break; end; end end end fclose(fid); if ~isequal(readtotal, readexpected) error('Number of values read not equal to the number expected.'); end EventData = []; if (head.eventtypes > 0), EventData = TrialData(head.nchan+1:end,:); TrialData = TrialData(1:head.nchan,:); end % convert from A/D units to microvolts if ( head.bits ~= 0 & head.range ~= 0 ) TrialData = (head.range/(2^head.bits))*TrialData; end % convert event codes to char % --------------------------- head.eventcode = char(head.eventcode); %--------------------------- isvector() --------------- function retval = isvector(V) s = size(V); retval = ( length(s) < 3 ) & ( min(s) <= 1 ); %------------------------------------------------------
github
ZijingMao/baselineeegtest-master
compvar.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/compvar.m
2,722
utf_8
006f804a7dec1ca7f3ad1fb6a588e688
% compvar() - project selected components and compute the variance of % the original data they account for. % % Usage: % >> [proj, variance] = compvar( data, wts_or_act, winv, components); % % Required Inputs: % data - 2-D (channels, points) or 3-D (channels, frames, trials) % data array. % wts_or_act - {sphere weights} cell array containing the ICA sphere % and weights matrices. May also be a 2-D (channels, points) % or 3-D (channels, frames, trials) array of component % activations. % winv - inverse or pseudo-inverse of the product of the weights % and sphere matrices returned by the ICA decompnumsition, % i.e., inv(weights*sphere) or pinv(weights*sphere). % components - array of component indices to back-project % % Outputs: % proj - summed back-projections of the specified components % pvaf - percent variance of the data that the selected % components account for (range: 100% to -Inf%). % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [ compproj, varegg ] = compvar( data, act, winv, compnums); if nargin < 4 help compvar; return; end; if iscell(act) && length(act) == 1 act = act{1}; end; data = reshape(data, size(data,1), size(data,2)*size(data,3)); act = reshape(act , size(act ,1), size(act ,2)*size( act,3)); squaredata = sum(sum(data.^2)); % compute the grand sum-squared data if iscell(act) sphere = act{1}; weight = act{2}; act = (weight(compnums,:)*sphere)*data; end; compproj = winv(:,compnums)*act(compnums,:)-data; % difference between data and back-projection squarecomp = sum(sum(compproj.^2)); % the summed-square difference varegg = 100*(1- squarecomp/squaredata); % compute pvaf of components in data compproj = compproj+data; % restore back-projected data return;
github
ZijingMao/baselineeegtest-master
plotsphere.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/plotsphere.m
4,822
utf_8
5a1e3b5a681d7d5be1d6ad3d5a0d3f0e
% plotsphere() - This function is used to plot a sphere and % project them onto specific surfaces. This may % be used for plotting dipoles for instance. % % Usage: % >> handle = plotsphere(pos, rad, 'key', 'val') % % Inputs: % pos - [x y z] 3-D position of the sphere center % rad - [real] sphere radius % % Optional inputs: % 'nvert' - number of vertices. Default is 15. % 'color' - sphere color. Default is red. % 'proj' - [x y z] project sphere to 3-D axes. Enter NaN for not % projecting. For instance [-40 NaN -80] will project % the sphere on the y/z plane axis at position x=-40 and on % the x/y plane at position z=-80. % 'projcol' - color of projected spheres % 'colormap' - [real] sphere colormap { default: jet } % % Output: % handle - sphere graphic handle(s). If projected sphere are ploted % handles of plotted projected spheres are also returned. % % Example: % figure; plotsphere([3 2 2], 1, 'proj', [0 0 -1]); % axis off; axis equal; lighting phong; camlight left; view([142 48]) % % Authors: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2004 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Copyright (C) Arnaud Delorme, 2004 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [handles] = plotsphere(pos, rad, varargin); if nargin < 2 help plotsphere; return; end; g = finputcheck(varargin, { 'color' { 'real','string' } [] [1 0 0]; 'nvert' 'integer' [2 Inf] 15; 'proj' 'real' [] []; 'colormap' 'real' [] jet(64); 'projcol' { 'real','string' } [] [0 0 0] }, 'plotsphere'); if isstr(g), error(g); end; % decode color if necessary % ------------------------- if ~isstr(g.color) & length(g.color) == 1 g.color = g.colormap(g.color,:); elseif isstr(g.color) g.color = strcol2real(g.color); end; if ~isstr(g.projcol) & length(g.projcol) == 1 g.projcol = g.colormap(g.projcol,:); elseif isstr(g.projcol) g.projcol = strcol2real(g.projcol); end; % ploting sphere % ============== [xstmp ystmp zs] = sphere(g.nvert); l=sqrt(xstmp.*xstmp+ystmp.*ystmp+zs.*zs); normals = reshape([xstmp./l ystmp./l zs./l],[g.nvert+1 g.nvert+1 3]); xs = pos(1) + rad*ystmp; ys = pos(2) + rad*xstmp; zs = pos(3) + rad*zs; colorarray = repmat(reshape(g.color , 1,1,3), [size(zs,1) size(zs,2) 1]); hold on; handles = surf(xs, ys, zs, colorarray, 'tag', 'tmpmov', 'EdgeColor','none', 'VertexNormals', normals, ... 'backfacelighting', 'lit', 'facelighting', 'phong', 'facecolor', 'interp', 'ambientstrength', 0.3); %axis off; axis equal; lighting phong; camlight left; rotate3d % plot projections % ================ if ~isempty(g.proj) colorarray = repmat(reshape(g.projcol, 1,1,3), [size(zs,1) size(zs,2) 1]); if ~isnan(g.proj(1)), handles(end+1) = surf(g.proj(1)*ones(size(xs)), ys, zs, colorarray, ... 'edgecolor', 'none', 'facelighting', 'none'); end; if ~isnan(g.proj(2)), handles(end+1) = surf(xs, g.proj(2)*ones(size(ys)), zs, colorarray, ... 'edgecolor', 'none', 'facelighting', 'none'); end; if ~isnan(g.proj(3)), handles(end+1) = surf(xs, ys, g.proj(3)*ones(size(zs)), colorarray, ... 'edgecolor', 'none', 'facelighting', 'none'); end; end; function color = strcol2real(color) switch color case 'r', color = [1 0 0]; case 'g', color = [0 1 0]; case 'b', color = [0 0 1]; case 'c', color = [0 1 1]; case 'm', color = [1 0 1]; case 'y', color = [1 1 0]; case 'k', color = [0 0 0]; case 'w', color = [1 1 1]; otherwise, error('Unknown color'); end;
github
ZijingMao/baselineeegtest-master
projtopo.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/projtopo.m
4,459
utf_8
dd1586daff2737f20be375d9f4e19666
% projtopo() - plot projections of one or more ICA components along with % the original data in a 2-d topographic array. Returns % the data plotted. Click on subplot to examine separately. % Usage: % >> [projdata] = projtopo(data,weights,[compnums],'chan_locs',... % 'title',[limits],colors,chans); % Inputs: % data = single epoch of runica() input data (chans,frames) % weights = unimxing weight matrix (runica() weights*sphere) % [compnums] = vector of component numbers to project and plot % 'chan_locs' = channel locations file. Example: >> topoplot example % Else [rows cols] for rectangular grid array % Optional: % 'title' = (short) plot title {default|0 -> none} % [limits] = [xmin xmax ymin ymax] (x's in msec) % {default|0|both y's 0 -> use data limits} % colors = file of color codes, 3 chars per line ('.' = space) % {default|0 -> default color order (black/white first)} % chans = vector of channel numbers to plot {default|0: all} % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 04-02-98 % % See also: plotproj(), topoplot() % Copyright (C) 04-02-98 from plotproj() Scott Makeig, SCCN/INC/UCSD, % [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % Without color arg, reads filename for PROJCOLORS from icadefs.m % 03-15-00 added plotchans arg -sm % 03-16-00 added axcopy() feature -sm & tpj % 12-19-00 adjusted new icaproj() args -sm % 12-20-00 removed argument "sphere" -sm % 07-12-01 fixed nargin test to allow 8 args -sm & cmk % 01-25-02 reformated help & license, added links -ad function [projdata] = projtopo(data,weights,compnums,chan_locs,titl,limits,colors,plotchans) icadefs % read default PROJCOLORS & MAXPLOTDATACHANS variables from icadefs.m axsize = 0; % use plottopo() default DEFAULT_TITLE = ''; % % Substitute for missing arguments % if nargin < 7, colors = 'white1st.col'; elseif colors==0 | isempty(colors) colors = 'white1st.col'; end if nargin < 6, limits = 0; end if nargin < 5, titl = 0; end if titl==0, titl = DEFAULT_TITLE; end if nargin < 4 | nargin > 8 help projtopo fprintf('projtopo(): requires 4-8 arguments.\n\n'); return end % % Test data size % [chans,framestot] = size(data); if ~exist('plotchans') | isempty(plotchans) | plotchans==0 plotchans = 1:chans; % default end frames = framestot; % assume one epoch [wr,wc] = size(weights); % % Substitute for 0 arguments % if compnums == 0, compnums = [1:wr]; end; if size(compnums,1)>1, % handle column of compnums ! compnums = compnums'; end; if length(compnums) > MAXPLOTDATACHANS, fprintf(... 'projtopo(): cannot plot more than %d channels of data at once.\n',... MAXPLOTDATACHANS); return end; if max(compnums)>wr, fprintf(... '\n projtopo(): Component index (%d) > number of components (%d).\n', ... max(compnums),wr); return end fprintf('Reconstructing (%d chan, %d frame) data summing %d components.\n', ... chans,frames,length(compnums)); % % Compute projected data for single components % projdata = data; fprintf('projtopo(): Projecting component(s) '); for s=compnums, % for each component fprintf('%d ',s); proj = icaproj(data,weights,s); % let offsets distribute projdata = [projdata proj]; % append projected data onto projdata end; fprintf('\n'); % % Make the plot % % >> plottopo(data,'chan_locs',frames,limits,title,channels,axsize,colors,ydir) plottopo(projdata,chan_locs,size(data,2),limits,titl,plotchans,axsize,colors); % make the plottopo() plot axcopy(gcf);
github
ZijingMao/baselineeegtest-master
voltype.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/voltype.m
677
utf_8
28455ecff10043767463871fdedc4413
% VOLTYPE determines the type of volume conduction model % % Use as % [type] = voltype(vol) % to get a string describing the type, or % [flag] = voltype(vol, desired) % to get a boolean value. % % See also COMPUTE_LEADFIELD % Copyright (C) 2007, Robert Oostenveld % function [type] = voltype(vol, desired) if isfield(vol, 'type') type = vol.type; elseif isfield(vol, 'r') && prod(size(vol.r))==1 type = 'singlesphere'; elseif isfield(vol, 'r') && isfield(vol, 'o') && all(size(vol.r)==size(vol.o)) type = 'multisphere'; elseif isfield(vol, 'r') type = 'concentric'; elseif isfield(vol, 'bnd') type = 'bem'; end if nargin>1 type = strcmp(type, desired); end
github
ZijingMao/baselineeegtest-master
strmultiline.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/strmultiline.m
3,151
utf_8
c1a6c98b7691f0623c7938d5cb68ae93
% strmultiline() - format a long string as a multi-line string. % % Usage: % >> strout = strmultiline( strin, maxlen, delimiter); % % Inputs: % strin - one-line or several-line string % maxlen - maximum line length % delimiter - enter 10 here to separate lines with character 10. Default is % empty: lines are on different rows of the returned array. % Outputs: % strout - string with multiple line % % Author: Arnaud Delorme, CNL / Salk Institute, 2005 % % See also: eegfilt(), eegfiltfft(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function strout = strmultiline( strinori, maxlen, delimiter); if nargin < 1 help strmultiline; return; end; if nargin < 3 delimiter = []; end; % first format input string % ------------------------- if ~isempty(find(strinori == 10)) tmpinds = [1 find(strinori == 10)+1 length(strinori)]; strinori = [ ' ' strinori ' ' ]; for ind = 2:length(tmpinds) allstrs{ind} = strinori(tmpinds(ind-1)+1:tmpinds(ind)-1); if isempty(allstrs{ind}), allstrs{ind} = ' '; end; end; strinori = strvcat(allstrs{:}); end; if size(strinori,2) < maxlen, strout = strinori; return; end; strout = []; for index = 1:size(strinori,1) % scan lines strin = deblank(strinori(index, :)); lines = {}; count = 1; curline = ''; while ~isempty( strin ) [tok strin] = strtok(strin); if length(curline) + length(tok) +1 > maxlen lines{count} = curline; curline = ''; count = count + 1; end; if isempty(curline) curline = tok; else curline = [ curline ' ' tok ]; end; end; if ~isempty(curline), lines{count} = curline; end; % type of delimiter % ----------------- if isempty(delimiter) if ~isempty(lines) strouttmp = strvcat(lines{:}); else strouttmp = ''; end; if isempty(strouttmp) strouttmp = ones(1,maxlen)*' '; elseif size(strouttmp, 2) < maxlen strouttmp(:,end+1:maxlen) = ' '; end; strout = strvcat(strout, strouttmp); else strouttmp = lines{1}; for index = 2:length(lines) strouttmp = [ strouttmp 10 lines{index} ]; end; if index == 1, strout = strouttmp; else strout = [ strout 10 strouttmp ]; end; end; end;
github
ZijingMao/baselineeegtest-master
floatread.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/floatread.m
5,572
utf_8
942a49968bcce849dfc9d359ac7d2651
% floatread() - Read matrix from float file ssuming four byte floating point number % Can use fseek() to read an arbitary (continguous) submatrix. % % Usage: >> a = floatread(filename,size,'format',offset) % % Inputs: % filename - name of the file % size - determine the number of float elements to be read and % the dimensions of the resulting matrix. If the last element % of 'size' is Inf, the size of the last dimension is determined % by the file length. If size is 'square,' floatread() attempts % to read a square 2-D matrix. % % Optional inputs: % 'format' - the option FORMAT argument specifies the storage format as % defined by fopen(). Default format ([]) is 'native'. % offset - either the number of first floats to skip from the beginning of the % float file, OR a cell array containing the dimensions of the original % data matrix and a starting position vector in that data matrix. % % Example: % Read a [3 10] submatrix of a four-dimensional float matrix % >> a = floatread('mydata.fdt',[3 10],'native',{[[3 10 4 5],[1,1,3,4]}); % % Note: The 'size' and 'offset' arguments must be compatible both % % with each other and with the size and ordering of the float file. % % Author: Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998 % % See also: floatwrite(), fopen() % Copyright (C) Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 04-26-99 modified by Sigurd Enghoff to handle variable-sized and % multi-dimensional data. % 07-08-99 modified by Sigurd Enghoff, FORMAT argument added. % 02-08-00 help updated for toolbox inclusion -sm % 02-14-00 added segment arg -sm % 08-14-00 added size 'square' option -sm % 01-25-02 reformated help & license, added links -ad function A = floatread(fname,Asize,fform,offset) if nargin<2 help floatread return end if ~exist('fform') | isempty(fform)|fform==0 fform = 'native'; end if ~exist('offset') offset = 0; end fid = fopen(fname,'rb',fform); if fid>0 if exist('offset') if iscell(offset) if length(offset) ~= 2 error('offset must be a positive integer or a 2-item cell array'); end datasize = offset{1}; startpos = offset{2}; if length(datasize) ~= length(startpos) error('offset must be a positive integer or a 2-item cell array'); end for k=1:length(datasize) if startpos(k) < 1 | startpos(k) > datasize(k) error('offset must be a positive integer or a 2-item cell array'); end end if length(Asize)> length(datasize) error('offset must be a positive integer or a 2-item cell array'); end for k=1:length(Asize)-1 if startpos(k) ~= 1 error('offset must be a positive integer or a 2-item cell array'); end end sizedim = length(Asize); if Asize(sizedim) + startpos(sizedim) - 1 > datasize(sizedim) error('offset must be a positive integer or a 2-item cell array'); end for k=1:length(Asize)-1 if Asize(k) ~= datasize(k) error('offset must be a positive integer or a 2-item cell array'); end end offset = 0; jumpfac = 1; for k=1:length(startpos) offset = offset + jumpfac * (startpos(k)-1); jumpfac = jumpfac * datasize(k); end elseif length(offset) > 1 error('offset must be a positive integer or a 2-item cell array'); end % perform the fseek() operation % ----------------------------- stts = fseek(fid,4*offset,'bof'); if stts ~= 0 error('floatread(): fseek() error.'); return end end % determine what 'square' means % ----------------------------- if ischar('Asize') if iscell(offset) if length(datasize) ~= 2 | datasize(1) ~= datasize(2) error('size ''square'' must refer to a square 2-D matrix'); end Asize = [datsize(1) datasize(2)]; elseif strcmp(Asize,'square') fseek(fid,0,'eof'); % go to end of file bytes = ftell(fid); % get byte position fseek(fid,0,'bof'); % rewind bytes = bytes/4; % nfloats froot = sqrt(bytes); if round(froot)*round(froot) ~= bytes error('floatread(): filelength is not square.') else Asize = [round(froot) round(froot)]; end end end A = fread(fid,prod(Asize),'float'); else error('floatread() fopen() error.'); return end % fprintf(' %d floats read\n',prod(size(A))); % interpret last element of Asize if 'Inf' % ---------------------------------------- if Asize(end) == Inf Asize = Asize(1:end-1); A = reshape(A,[Asize length(A)/prod(Asize)]); else A = reshape(A,Asize); end fclose(fid);
github
ZijingMao/baselineeegtest-master
writeeeg.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/writeeeg.m
9,957
utf_8
b80ba013a795acbaa4122e842203239c
% writeeeg - Generating CNT/EDF/BDF/GDF-files using BIOSIG toolbox. Note % that the CNT file format is not fully functional. See also the % writecnt.m Matlab function (there is no fully working % Neuroscan writing function to our knowledge). % % writeeeg( filename, data, srate, 'key', 'val') % % Inputs: % filename - [string] filename % data - [float] continuous or epoched data (channels x times x % epochs) % srate - [float] sampling rate in Hz % % Optional keys: % 'TYPE' - ['GDF'|'EDF'|'BDF'|'CFWB'|'CNT'] file format for writing % default is 'EDF'. % 'EVENT' - event structure (BIOSIG or EEGLAB format) % 'Label' - cell array of channel labels. Warning, this input is % case sensitive. % 'SPR' - [integer] sample per block, default is 1000 % % Other optional keys: % 'Patient.id' - [string] person identification, max 80 char % 'Patient.Sex' - [0|1|2] 0: undefined (default), 1: male, 2: female % 'Patient.Birthday' - Default [1951 05 13 0 0 0]; % 'Patient.Name' - [string] default 'anonymous' for privacy protection % 'Patient.Handedness' - [0|1|2|3] 0: unknown (default), 1:left, 2:right, % 3: equal % 'Patient.Weight' - [integer] default 0, undefined % 'Patient.Height' - [integer] default 0, undefined % 'Patient.Impairment.Heart' - [integer] 0: unknown 1: NO 2: YES 3: pacemaker % 'Patient.Impairment.Visual' - [integer] 0: unknown 1: NO 2: YES % 3: corrected (with visual aid) % 'Patient.Smoking' - [integer] 0: unknown 1: NO 2: YES % 'Patient.AlcoholAbuse' - [integer] 0: unknown 1: NO 2: YES % 'Patient.DrugAbuse' - [integer] 0: unknown 1: NO 2: YES % % 'Manufacturer.Name - [string] default is 'BioSig/EEGLAB' % 'Manufacturer.Model - [string] default is 'writeeeg.m' % 'Manufacturer.Version - [string] default is current version in CVS repository % 'Manufacturer.SerialNumber - [string] default is '00000000' % % 'T0' - recording time [YYYY MM DD hh mm ss.ccc] % 'RID' - [string] StudyID/Investigation, default is empty % 'REC.Hospital - [string] default is empty % 'REC.Techician - [string] default is empty % 'REC.Equipment - [string] default is empty % 'REC.IPaddr - [integer array] IP address of recording system. Default is % [127,0,0,1] % % Author: Arnaud Delorme, SCCN, UCSD/CERCO, 2009 % Based on BIOSIG, sopen and swrite % Copyright (C) 22 March 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function HDR = writeeeg(filename, x, srate, varargin) % decode structures HDR = []; for i=1:2:length( varargin ) str = varargin{i}; val = varargin{i+1}; ind = strfind(str, '.'); if length(ind) == 2 HDR = setfield(HDR, varargin{i}(1:ind(1)-1), {1}, varargin{i}(ind(1)+1:ind(2)-1), ... {1}, varargin{i}(ind(2)+1:end), val); elseif length(ind) == 1 HDR = setfield(HDR, varargin{i}(1:ind-1), {1}, varargin{i}(ind+1:end), val); else HDR = setfield(HDR, varargin{i}, varargin{i+1}); end; end; HDR.FileName = filename; HDR.FLAG.UCAL = 0; % select file format if ~isfield(HDR, 'EVENT'), HDR.EVENT = []; end; if ~isfield(HDR, 'TYPE'), HDR.TYPE ='GDF'; end; if ~isfield(HDR, 'Patient') HDR.Patient = []; end; if ~isfield(HDR.Patient, 'ID') HDR.Patient.ID = 'P0000'; end; if ~isfield(HDR.Patient, 'Sex') HDR.Patient.Sex = 0; end; if ~isfield(HDR.Patient, 'Name') HDR.Patient.Name = 'Anonymous'; end; if ~isfield(HDR.Patient, 'Handedness') HDR.Patient.Handedness = 0; end;% unknown, 1:left, 2:right, 3: equal % description of recording device if ~isfield(HDR,'Manufacturer') HDR.Manufacturer = []; end; if ~isfield(HDR.Manufacturer, 'Name'), HDR.Manufacturer.Name = 'BioSig/EEGLAB'; end; if ~isfield(HDR.Manufacturer, 'Model'), HDR.Manufacturer.Model = 'writeeeg.m'; end; if ~isfield(HDR.Manufacturer, 'Version'), HDR.Manufacturer.Version = '$Revision'; end; if ~isfield(HDR.Manufacturer, 'SerialNumber'), HDR.Manufacturer.SerialNumber = '00000000'; end; % recording identification, max 80 char. if ~isfield(HDR,'RID') HDR.RID = ''; end; %StudyID/Investigation [consecutive number]; if ~isfield(HDR,'REC') HDR.REC = []; end; if ~isfield(HDR.REC, 'Hospital') HDR.REC.Hospital = ''; end; if ~isfield(HDR.REC, 'Techician') HDR.REC.Techician = ''; end; if ~isfield(HDR.REC, 'Equipment') HDR.REC.Equipment = ''; end; if ~isfield(HDR.REC, 'IPaddr') HDR.REC.IPaddr = [127,0,0,1]; end; % IP address of recording system if ~isfield(HDR.Patient, 'Weight') HDR.Patient.Weight = 0; end; % undefined if ~isfield(HDR.Patient, 'Height') HDR.Patient.Height = 0; end; % undefined if ~isfield(HDR.Patient, 'Birthday') HDR.Patient.Birthday = [1951 05 13 0 0 0]; end; % undefined if ~isfield(HDR.Patient, 'Impairment') HDR.Patient.Impairment = []; end; if ~isfield(HDR.Patient.Impairment, 'Heart') HDR.Patient.Impairment.Heart = 0; end; % 0: unknown 1: NO 2: YES 3: pacemaker if ~isfield(HDR.Patient.Impairment, 'Visual') HDR.Patient.Impairment.Visual = 0; end; % 0: unknown 1: NO 2: YES 3: corrected (with visual aid) if ~isfield(HDR.Patient,'Smoking') HDR.Patient.Smoking = 0; end; % 0: unknown 1: NO 2: YES if ~isfield(HDR.Patient,'AlcoholAbuse') HDR.Patient.AlcoholAbuse = 0; end; % 0: unknown 1: NO 2: YES if ~isfield(HDR.Patient,'DrugAbuse') HDR.Patient.DrugAbuse = 0; end; % 0: unknown 1: NO 2: YES % recording time [YYYY MM DD hh mm ss.ccc] if ~isfield(HDR,'T0') HDR.T0 = clock; end; if ~isfield(HDR,'SPR') HDR.SPR = size(x,2); end; if isfield(HDR,'label') HDR.Label = HDR.label; HDR = rmfield(HDR, 'label'); end; if HDR.SPR > 1000, HDR.SPR = round(srate); end; % channel identification, max 80 char. per channel if ~isfield(HDR,'Label') for i = 1:size(x,1) chans{i} = sprintf('Chan %d', i); end; HDR.Label = chans; end; if iscell(HDR.Label), HDR.Label = char(HDR.Label{:}); end; if ~isempty(HDR.EVENT) if ~isfield(HDR.EVENT, 'TYP') EVENT = []; EVENT.CHN = zeros(length(HDR.EVENT),1); EVENT.TYP = zeros(length(HDR.EVENT),1); EVENT.POS = zeros(length(HDR.EVENT),1); EVENT.DUR = ones( length(HDR.EVENT),1); EVENT.VAL = zeros(length(HDR.EVENT),1)*NaN; if isfield(HDR.EVENT, 'type') for index = 1:length(HDR.EVENT) HDR.EVENT(index).type = num2str(HDR.EVENT(index).type); end; alltypes = unique_bc( { HDR.EVENT.type } ); end; for i = 1:length(HDR.EVENT) if isfield(HDR.EVENT, 'type') ind = str2num(HDR.EVENT(i).type); if isempty(ind) ind = strmatch(HDR.EVENT(i).type, alltypes, 'exact'); end; EVENT.TYP(i) = ind; end; if isfield(HDR.EVENT, 'latency') EVENT.POS(i) = HDR.EVENT(i).latency; end; if isfield(HDR.EVENT, 'duration') EVENT.DUR(i) = HDR.EVENT(i).duration; end; end; HDR.EVENT = EVENT; HDR.EVENT.SampleRate = srate; end; end; % reformat data HDR.NRec = size(x,3); x = double(x); x = reshape(x, [size(x,1) size(x,2)*size(x,3) ]); % recreate event channel if isempty(HDR.EVENT) HDR.EVENT.POS = []; HDR.EVENT.TYP = []; HDR.EVENT.POS = []; HDR.EVENT.DUR = []; HDR.EVENT.VAL = []; HDR.EVENT.CHN = []; elseif ~strcmpi(HDR.TYPE, 'GDF') % GDF can save events disp('Recreating event channel'); x(end+1,:) = 0; x(end,round(HDR.EVENT.POS')) = HDR.EVENT.TYP'; HDR.Label = char(HDR.Label, 'Status'); HDR.EVENT.POS = []; end; % number of channels HDR.NS = size(x,1); if ~isfield(HDR,'Transducer') HDR.Transducer = cell(1,HDR.NS); HDR.Transducer(:) = { '' }; end; if ~isfield(HDR,'PhysDim') HDR.PhysDim = cell(1,HDR.NS); HDR.PhysDim(:) = { 'uV' }; end; % Duration of one block in seconds HDR.SampleRate = srate; HDR.Dur = HDR.SPR/HDR.SampleRate; % define datatypes and scaling factors HDR.PhysMax = max(x, [], 2); HDR.PhysMin = min(x, [], 2); if strcmp(HDR.TYPE, 'GDF') HDR.GDFTYP = 16*ones(1,HDR.NS); % float32 HDR.DigMax = ones(HDR.NS,1)*100; % FIXME: What are the correct values for float32? HDR.DigMin = zeros(HDR.NS,1); else HDR.GDFTYP = 3*ones(1,HDR.NS); % int16 HDR.DigMin = repmat(-2^15, size(HDR.PhysMin)); HDR.DigMax = repmat(2^15-1, size(HDR.PhysMax)); end HDR.Filter.Lowpass = zeros(1,HDR.NS)*NaN; HDR.Filter.Highpass = zeros(1,HDR.NS)*NaN; HDR.Filter.Notch = zeros(1,HDR.NS)*NaN; HDR.VERSION = 2.11; HDR = sopen(HDR,'w'); HDR = swrite(HDR, x'); HDR = sclose(HDR);
github
ZijingMao/baselineeegtest-master
convertlocs.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/convertlocs.m
9,621
utf_8
9455542daae2061f96f576b6dc3d46da
% convertlocs() - Convert electrode locations between coordinate systems % using the EEG.chanlocs structure. % % Usage: >> newchans = convertlocs( EEG, 'command'); % % Input: % chanlocs - An EEGLAB EEG dataset OR a EEG.chanlocs channel locations structure % 'command' - ['cart2topo'|'sph2topo'|'sphbesa2topo'| 'sph2cart'|'topo2cart'|'sphbesa2cart'| % 'cart2sph'|'sphbesa2sph'|'topo2sph'| 'cart2sphbesa'|'sph2sphbesa'|'topo2sphbesa'| % 'cart2all'|'sph2all'|'sphbesa2all'|'topo2all'] % These command modes convert between four coordinate frames: 3-D Cartesian % (cart), Matlab spherical (sph), Besa spherical (sphbesa), and 2-D polar (topo) % 'auto' -- Here, the function finds the most complex coordinate frame % and constrains all the others to this one. It searches first for Cartesian % coordinates, then for spherical and finally for polar. Default is 'auto'. % % Optional input % 'verbose' - ['on'|'off'] default is 'off'. % % Outputs: % newchans - new EEGLAB channel locations structure % % Ex: CHANSTRUCT = convertlocs( CHANSTRUCT, 'cart2topo'); % % Convert Cartesian coordinates to 2-D polar (topographic). % % Author: Arnaud Delorme, CNL / Salk Institute, 22 Dec 2002 % % See also: readlocs() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 22 Dec 2002, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function chans = convertlocs(chans, command, varargin); if nargin < 1 help convertlocs; return; end; if nargin < 2 command = 'auto'; end; if nargin == 4 && strcmpi(varargin{2}, 'on') verbose = 1; else verbose = 0; % off end; % test if value exists for default % -------------------------------- if strcmp(command, 'auto') if isfield(chans, 'X') && ~isempty(chans(1).X) command = 'cart2all'; if verbose disp('Make all coordinate frames uniform using Cartesian coords'); end; else if isfield(chans, 'sph_theta') && ~isempty(chans(1).sph_theta) command = 'sph2all'; if verbose disp('Make all coordinate frames uniform using spherical coords'); end; else if isfield(chans, 'sph_theta_besa') && ~isempty(chans(1).sph_theta_besa) command = 'sphbesa2all'; if verbose disp('Make all coordinate frames uniform using BESA spherical coords'); end; else command = 'topo2all'; if verbose disp('Make all coordinate frames uniform using polar coords'); end; end; end; end; end; % convert % ------- switch command case 'topo2sph', theta = {chans.theta}; radius = {chans.radius}; indices = find(~cellfun('isempty', theta)); [sph_phi sph_theta] = topo2sph( [ [ theta{indices} ]' [ radius{indices}]' ] ); if verbose disp('Warning: electrodes forced to lie on a sphere for polar to 3-D conversion'); end; for index = 1:length(indices) chans(indices(index)).sph_theta = sph_theta(index); chans(indices(index)).sph_phi = sph_phi (index); end; if isfield(chans, 'sph_radius'), meanrad = mean([ chans(indices).sph_radius ]); if isempty(meanrad), meanrad = 1; end; else meanrad = 1; end; sph_radius(1:length(indices)) = {meanrad}; case 'topo2sphbesa', chans = convertlocs(chans, 'topo2sph', varargin{:}); % search for spherical coords chans = convertlocs(chans, 'sph2sphbesa', varargin{:}); % search for spherical coords case 'topo2cart' chans = convertlocs(chans, 'topo2sph', varargin{:}); % search for spherical coords if verbose disp('Warning: spherical coordinates automatically updated'); end; chans = convertlocs(chans, 'sph2cart', varargin{:}); % search for spherical coords case 'topo2all', chans = convertlocs(chans, 'topo2sph', varargin{:}); % search for spherical coords chans = convertlocs(chans, 'sph2sphbesa', varargin{:}); % search for spherical coords chans = convertlocs(chans, 'sph2cart', varargin{:}); % search for spherical coords case 'sph2cart', sph_theta = {chans.sph_theta}; sph_phi = {chans.sph_phi}; indices = find(~cellfun('isempty', sph_theta)); if ~isfield(chans, 'sph_radius'), sph_radius(1:length(indices)) = {1}; else sph_radius = {chans.sph_radius}; end; inde = find(cellfun('isempty', sph_radius)); if ~isempty(inde) meanrad = mean( [ sph_radius{:} ]); sph_radius(inde) = { meanrad }; end; [x y z] = sph2cart([ sph_theta{indices} ]'/180*pi, [ sph_phi{indices} ]'/180*pi, [ sph_radius{indices} ]'); for index = 1:length(indices) chans(indices(index)).X = x(index); chans(indices(index)).Y = y(index); chans(indices(index)).Z = z(index); end; case 'sph2topo', if verbose % disp('Warning: all radii constrained to one for spherical to topo transformation'); end; sph_theta = {chans.sph_theta}; sph_phi = {chans.sph_phi}; indices = find(~cellfun('isempty', sph_theta)); [chan_num,angle,radius] = sph2topo([ ones(length(indices),1) [ sph_phi{indices} ]' [ sph_theta{indices} ]' ], 1, 2); % using method 2 for index = 1:length(indices) chans(indices(index)).theta = angle(index); chans(indices(index)).radius = radius(index); if ~isfield(chans, 'sph_radius') || isempty(chans(indices(index)).sph_radius) chans(indices(index)).sph_radius = 1; end; end; case 'sph2sphbesa', % using polar coordinates sph_theta = {chans.sph_theta}; sph_phi = {chans.sph_phi}; indices = find(~cellfun('isempty', sph_theta)); [chan_num,angle,radius] = sph2topo([ones(length(indices),1) [ sph_phi{indices} ]' [ sph_theta{indices} ]' ], 1, 2); [sph_theta_besa sph_phi_besa] = topo2sph([angle radius], 1, 1); for index = 1:length(indices) chans(indices(index)).sph_theta_besa = sph_theta_besa(index); chans(indices(index)).sph_phi_besa = sph_phi_besa(index); end; case 'sph2all', chans = convertlocs(chans, 'sph2topo', varargin{:}); % search for spherical coords chans = convertlocs(chans, 'sph2sphbesa', varargin{:}); % search for spherical coords chans = convertlocs(chans, 'sph2cart', varargin{:}); % search for spherical coords case 'sphbesa2sph', % using polar coordinates sph_theta_besa = {chans.sph_theta_besa}; sph_phi_besa = {chans.sph_phi_besa}; indices = find(~cellfun('isempty', sph_theta_besa)); [chan_num,angle,radius] = sph2topo([ones(length(indices),1) [ sph_theta_besa{indices} ]' [ sph_phi_besa{indices} ]' ], 1, 1); %for index = 1:length(chans) % chans(indices(index)).theta = angle(index); % chans(indices(index)).radius = radius(index); % chans(indices(index)).labels = int2str(index); %end; %figure; topoplot([],chans, 'style', 'blank', 'electrodes', 'labelpoint'); [sph_phi sph_theta] = topo2sph([angle radius], 2); for index = 1:length(indices) chans(indices(index)).sph_theta = sph_theta(index); chans(indices(index)).sph_phi = sph_phi (index); end; case 'sphbesa2topo', chans = convertlocs(chans, 'sphbesa2sph', varargin{:}); % search for spherical coords chans = convertlocs(chans, 'sph2topo', varargin{:}); % search for spherical coords case 'sphbesa2cart', chans = convertlocs(chans, 'sphbesa2sph', varargin{:}); % search for spherical coords chans = convertlocs(chans, 'sph2cart', varargin{:}); % search for spherical coords case 'sphbesa2all', chans = convertlocs(chans, 'sphbesa2sph', varargin{:}); % search for spherical coords chans = convertlocs(chans, 'sph2all', varargin{:}); % search for spherical coords case 'cart2topo', chans = convertlocs(chans, 'cart2sph', varargin{:}); % search for spherical coords chans = convertlocs(chans, 'sph2topo', varargin{:}); % search for spherical coords case 'cart2sphbesa', chans = convertlocs(chans, 'cart2sph', varargin{:}); % search for spherical coords chans = convertlocs(chans, 'sph2sphbesa', varargin{:}); % search for spherical coords case 'cart2sph', if verbose disp('WARNING: If XYZ center has not been optimized, optimize it using Edit > Channel Locations'); end; X = {chans.X}; Y = {chans.Y}; Z = {chans.Z}; indices = find(~cellfun('isempty', X)); [th phi radius] = cart2sph( [ X{indices} ], [ Y{indices} ], [ Z{indices} ]); for index = 1:length(indices) chans(indices(index)).sph_theta = th(index)/pi*180; chans(indices(index)).sph_phi = phi(index)/pi*180; chans(indices(index)).sph_radius = radius(index); end; case 'cart2all', chans = convertlocs(chans, 'cart2sph', varargin{:}); % search for spherical coords chans = convertlocs(chans, 'sph2all', varargin{:}); % search for spherical coords end;
github
ZijingMao/baselineeegtest-master
isscript.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/isscript.m
385
utf_8
5e35a8cefee4828cc65eeb2abb2502a7
% function checking if a specific file is a script% function bool = isscript(fileName); fid = fopen(fileName, 'r'); cont = true; while cont && ~feof(fid) l = strtok(fgetl(fid)); if ~isempty(l) && l(1) ~= '%' if strcmpi(l, 'function') bool = false; return; else bool = true; return; end; end; end; bool = true; return;
github
ZijingMao/baselineeegtest-master
floatwrite.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/floatwrite.m
3,169
utf_8
8472e61c3208f7a445ec052e9cc52b4b
% floatwrite() - Write data matrix to float file. % % Usage: >> floatwrite(data,filename, 'format') % % Inputs: % data - write matrix data to specified file as four-byte floating point numbers. % filename - name of the file % 'format' - The option FORMAT argument specifies the storage format as % defined by fopen. Default format is 'native'. % 'transp|normal' - save the data transposed (.dat files) or not. % % Author: Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998 % % See also: floatread(), fopen() % Copyright (C) Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 07-08-99 FORMAT argument added -se % 02-08-00 new version included in toolbox -sm % 01-25-02 reformated help & license, added links -ad function A = floatwrite(A, fname, fform, transp) if ~exist('fform') fform = 'native'; end if nargin < 4 transp = 'normal'; end; if strcmpi(transp,'normal') if strcmpi(class(A), 'mmo') A = changefile(A, fname); return; elseif strcmpi(class(A), 'memmapdata') % check file to overwrite % ----------------------- [fpath1 fname1 ext1] = fileparts(fname); [fpath2 fname2 ext2] = fileparts(A.data.Filename); if isempty(fpath1), fpath1 = pwd; end; fname1 = fullfile(fpath1, [fname1 ext1]); fname2 = fullfile(fpath2, [fname2 ext2]); if ~isempty(findstr(fname1, fname2)) disp('Warning: raw data already saved in memory mapped file (no need to resave it)'); return; end; fid = fopen(fname,'wb',fform); if fid == -1, error('Cannot write output file, check permission and space'); end; if size(A,3) > 1 for ind = 1:size(A,3) tmpdata = A(:,:,ind); fwrite(fid,tmpdata,'float'); end; else blocks = [ 1:round(size(A,2)/10):size(A,2)]; if blocks(end) ~= size(A,2), blocks = [blocks size(A,2)]; end; for ind = 1:length(blocks)-1 tmpdata = A(:, blocks(ind):blocks(ind+1)); fwrite(fid,tmpdata,'float'); end; end; else fid = fopen(fname,'wb',fform); if fid == -1, error('Cannot write output file, check permission and space'); end; fwrite(fid,A,'float'); end; else % save transposed for ind = 1:size(A,1) fwrite(fid,A(ind,:),'float'); end; end; fclose(fid);
github
ZijingMao/baselineeegtest-master
kurt.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/kurt.m
1,697
utf_8
649871ee149fc000974e3081ac13ff98
% kurt() - return kurtosis of input data distribution % % Usage: % >> k=kurt(data) % % Algorithm: % Calculates kurtosis or normalized 4th moment of an input data vector % Given a matrix, returns a row vector giving the kurtosis' of the columns % (Ref: "Numerical Recipes," p. 612) % % Author: Martin Mckeown, CNL / Salk Institute, La Jolla, 10/2/96 % Copyright (C) Martin Mckeown, CNL / Salk Institute, La Jolla, 7/1996 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 2/28/97 - made to return separate kurtosis estimates of columns -Scott Makeig % 01-25-02 reformated help & license, added links -ad function [k] = kurt(data) [r,c]=size(data); if r==1, kdata = data'; % if a row vector, make into a column vector r = c; else kdata = data; end %fprintf('size of kdata = [%d,%d]\n',size(kdata,1),size(kdata,2)); mn = mean(kdata); % find the column means diff = kdata-ones(r,1)*mn; % remove the column means dsq = diff.*diff; % square the data k = (sum(dsq.*dsq)./std(kdata).^4)./r - 3;
github
ZijingMao/baselineeegtest-master
jointprob.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/jointprob.m
4,100
utf_8
6f1300fd6123684425efaaa56c1e95c1
% jointprob() - rejection of odd columns of a data array using % joint probability of the values in that column (and % using the probability distribution of all columns). % % Usage: % >> [jp rej] = jointprob( signal ); % >> [jp rej] = jointprob( signal, threshold, jp, normalize, discret); % % % Inputs: % signal - one dimensional column vector of data values, two % dimensional column vector of values of size % sweeps x frames or three dimensional array of size % component x sweeps x frames. If three dimensional, % all components are treated independently. % threshold - Absolute threshold. If normalization is used then the % threshold is expressed in standard deviation of the % mean. 0 means no threshold. % jp - pre-computed joint probability (only perform thresholding). % Default is the empty array []. % normalize - 0 = do not not normalize entropy. 1 = normalize entropy. % 2 is 20% trimming (10% low and 10% high) proba. before % normalizing. Default is 0. % discret - discretization variable for calculation of the % discrete probability density. Default is 1000 points. % % Outputs: % jp - normalized joint probability of the single trials % (size component x sweeps) % rej - rejected matrix (0 and 1, size comp x sweeps) % % Remark: % The exact values of joint-probability depend on the size of a time % step and thus cannot be considered as absolute. % % See also: realproba() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [jp, rej] = jointprob( signal, threshold, oldjp, normalize, discret ); if nargin < 1 help jointprob; return; end; if nargin < 2 threshold = 0; end; if nargin < 3 oldjp = []; end; if nargin < 4 normalize = 0; end; if nargin < 5 discret = 1000; end; if size(signal,2) == 1 % transpose if necessary signal = signal'; end; [nbchan pnts sweeps] = size(signal); jp = zeros(nbchan,sweeps); if exist('oldjp') & ~isempty( oldjp ) % speed up the computation jp = oldjp; else for rc = 1:nbchan % COMPUTE THE DENSITY FUNCTION % ---------------------------- [ dataProba sortbox ] = realproba( signal(rc, :), discret ); % compute all entropy % ------------------- for index=1:sweeps datatmp = dataProba((index-1)*pnts+1:index*pnts); jp(rc, index) = - sum( log( datatmp ) ); % - sum( datatmp .* log( datatmp ) ); would be the entropy end; end; % normalize the last dimension % ---------------------------- if normalize tmpjp = jp; if normalize == 2, tmpjp = sort(jp); tmpjp = tmpjp(round(length(tmpjp)*0.1):end-round(length(tmpjp)*0.1)); end; try, switch ndims( signal ) case 2, jp = (jp-mean(tmpjp)) / std(tmpjp); case 3, jp = (jp-mean(tmpjp,2)*ones(1,size(jp,2)))./ ... (std(tmpjp,0,2)*ones(1,size(jp,2))); end; catch, error('Error while normalizing'); end; end; end % reject % ------ if threshold ~= 0 if length(threshold) > 1 rej = (threshold(1) > jp) | (jp > threshold(2)); else rej = abs(jp) > threshold; end; else rej = zeros(size(jp)); end; return;
github
ZijingMao/baselineeegtest-master
readneurodat.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/readneurodat.m
3,182
utf_8
2658232f1fb962a2bad82932ad309164
% readneurodat() - read neuroscan location file (.dat) % % Usage: % >> [ CHANLOCS labels theta theta ] = readneurodat( filename ); % % Inputs: % filename - file name or matlab cell array { names x_coord y_coord } % % Outputs: % CHANLOCS - [structure] EEGLAB channel location data structure. See % help readlocs() % labels - [cell arrya] channel labels % theta - [float array]array containing 3-D theta angle electrode % position (in degree) % phi - [float array]array containing 3-D phi angle electrode % position (in degree) % % Author: Arnaud Delorme, CNL / Salk Institute, 28 Nov 2003 % % See also: readlocs(), readneurolocs() % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [chanlocs, labels, theta, phi] = readneurodat(filename); if nargin < 1 help readneurodat; return; end; % enter file name here % -------------------- %tmp = loadtxt('/home/ftp/pub/locfiles/neuroscan/cap128.dat'); %tmp = loadtxt('/home/arno/temp/quik128.DAT'); tmp = loadtxt(filename); % resort electrodes % ----------------- [tmp2 tmpind] = sort(celltomat(tmp(:,1))'); tmp = tmp(tmpind,:); % convert to polar coordinates % ---------------------------- %figure; plot(celltomat(tmp(:,2)), celltomat(tmp(:,3)), '.'); [phi,theta] = cart2pol(celltomat(tmp(:,end-1)), celltomat(tmp(:,end))); theta = theta/513.1617*44; phi = phi/pi*180; % convert to other types of coordinates % ------------------------------------- labels = tmp(:,end-2)'; chanlocs = struct('labels', labels, 'sph_theta_besa', mattocell(theta)', 'sph_phi_besa', mattocell(phi)'); chanlocs = convertlocs( chanlocs, 'sphbesa2all'); for index = 1:length(chanlocs) chanlocs(index).labels = num2str(chanlocs(index).labels); end; theta = theta/pi*180; fprintf('Note: .dat file contain polar 2-D coordinates. EEGLAB will use these coordinates\n'); fprintf(' to recreated 3-D coordinates.\n'); fprintf('\n'); fprintf('Warning: if the channels are clustered in the middle or oddly spaced removed\n'); fprintf(' the peripheral channels and then used the optimize head function\n'); fprintf(' in the Channel Locations GUI. It seems that sometimes the peripherals\n'); fprintf(' are throwing off the spacing.\n');
github
ZijingMao/baselineeegtest-master
shuffle.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/shuffle.m
1,610
utf_8
aef9a1bc7914b99d6e312694b0522085
% shuffle() - shuffle a given dimension in an array % % Usage: >> Y = shuffle(X) % >> [Y = shuffle(X, DIM) % % Inputs: % X - input array % DIM - dimension index (default is firt non-singleton dimention) % % Outputs: % Y - shuffled array % I - forward indices (Y = X(I) if 1D) % J - reverse indices (X(J) = Y if 1D) % % Author: Arnaud Delorme, SCCN/INC/UCSD USA, Dec 2000 % Copyright (C) Arnaud Delorme, SCCN/INC/UCSD USA, Dec 2000 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [x, i, j]=shuffle( y, dim) if nargin < 1 help shuffle; return; end; if nargin < 2 if size(y,1) ~= 1 dim = 1; else if size(y,2) ~= 1 dim = 2; else dim = 3; end; end; end; r =size(y, dim); a = rand(1,r); [tmp i] = sort(a); switch dim case 1 x = y(i,:,:,:,:); case 2 x = y(:,i,:,:,:); case 3 x = y(:,:,i,:,:); case 4 x = y(:,:,:,i,:); case 5 x = y(:,:,:,:,i); end; [tmp j] = sort(i); % unshuffle return;
github
ZijingMao/baselineeegtest-master
fastif.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/fastif.m
1,159
utf_8
ac76d723f5de7649f75655cbdb653c1a
% fastif() - fast if function. % % Usage: % >> res = fastif(test, s1, s2); % % Input: % test - logical test with result 0 or 1 % s1 - result if 1 % s2 - result if 0 % % Output: % res - s1 or s2 depending on the value of the test % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function res = fastif(s1, s2, s3); if s1 res = s2; else res = s3; end; return;
github
ZijingMao/baselineeegtest-master
chancenter.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/chancenter.m
3,703
utf_8
27a231ace0a066d6e9ad7c3da227bbb7
% chancenter() - recenter cartesian X,Y,Z channel coordinates % % Usage: >> [x y z newcenter] = chancenter(x,y,z,center); % % Optional inputs: % x,y,z = 3D coordintates of the channels % center = [X Y Z] known center different from [0 0 0] % [] will optimize the center location according % to the best sphere. Default is [0 0 0]. % % Note: 4th input gui is obsolete. Use pop_chancenter instead. % % Authors: Arnaud Delorme, Luca Finelli & Scott Makeig SCCN/INC/UCSD, % La Jolla, 11/1999-03/2002 % % See also: spherror(), cart2topo() % Copyright (C) 11/1999 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 3-16-00 improved help message -sm % 1-25-02 put spherror subfunction inside chancenter -ad % 1-25-02 help pops-up if no arguments -ad % 01-25-02 reformated help & license -ad % 02-13-02 now center fitting works, need spherror outside chancenter -lf % 02-14-02 radii are squeezed of squeeze in to fit topoplot circle -lf % 03-31-02 center fitting is optional % 04-01-02 automatic squeeze calculation -ad & sm function [ x, y, z, newcenter, optim] = chancenter( x, y, z, center, gui) optim = 0; if nargin<4 help chancenter return; end; if nargin > 4 & gui error('Chancenter: 4th input'' gui'' is obsolete. Use pop_chancenter instead'); else if isempty(center) optim = 1; center = [0 0 0]; end; end; options = {'MaxFunEvals',1000*length(center)}; x = x - center(1); % center the data y = y - center(2); z = z - center(3); radius = (sqrt(x.^2+y.^2+z.^2)); % assume xyz values are on a sphere if ~isempty(radius) wobble = std(radius); % test if xyz values are on a sphere else wobble = []; end; fprintf('Radius values: %g (mean) +/- %g (std)\n',mean(radius),wobble); newcenter = center; if wobble/mean(radius) > 0.01 & optim==1 % Find center % ---------------------------------------------- fprintf('Optimizing center position...\n'); kk=0; while wobble/mean(radius) > 0.01 & kk<5 try newcenter = fminsearch('spherror',center,options,x,y,z); catch newcenter = fminsearch('spherror',center,[], [], x,y,z); end; nx = x - newcenter(1); % re-center the data ny = y - newcenter(2); nz = z - newcenter(3); nradius = (sqrt(nx.^2+ny.^2+nz.^2)); % assume xyz values are on a sphere newobble = std(nradius); if newobble<wobble center=newcenter; fprintf('Wobble too strong (%3.2g%%)! Re-centering data on (%g,%g,%g)\n',... 100*wobble/mean(radius),newcenter(1),newcenter(2),newcenter(3)) x = nx; % re-center the data y = ny; z = nz; radius=nradius; wobble=newobble; kk=kk+1; else newcenter = center; kk=5; end end fprintf('Wobble (%3.2g%%) after centering data on (%g,%g,%g)\n',... 100*wobble/mean(radius),center(1),center(2), ... center(3)) %else % fprintf('Wobble (%3.2g%%) after centering data on (%g,%g,%g)\n',... % 100*wobble/mean(radius),center(1),center(2),center(3)) end
github
ZijingMao/baselineeegtest-master
eegplot2trial.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/eegplot2trial.m
3,493
utf_8
070a4620dcbcefa6063fde095d9ae592
% eegplot2trial() - convert EEGPLOT rejections into trial and electrode % rejections compatible with EEGLAB format. % % Usage: % >> [trialrej elecrej] = eegplot2trial( eegplotrej, frames, ... % sweeps, colorin, colorout ); % % Inputs: % eegplotrej - EEGPLOT output (TMPREJ; see eegplot for more details) % frames - number of points per epoch % sweeps - number of trials % colorin - only extract rejection of specific colors (here a n x 3 % array must be given). Default: extract all rejections. % colorout - do not extract rejection of specified colors. % % Outputs: % trialrej - array of 0 and 1 depicting rejected trials (size sweeps) % elecrej - array of 0 and 1 depicting rejected electrodes in % all trials (size nbelectrodes x sweeps ) % % Note: if colorin is used, colorout is ignored % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eegplot(), eeg_multieegplot(), eegplot2event(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [tmpsig, tmprejelec] = eegplot2trial( TMPREJINIT, pnts, sweeps, color, colorout ); if nargin < 3 help eegplot2trial; return; end; % only take into account specific colors % -------------------------------------- TMPREJINIT(:,3:5) = round(TMPREJINIT(:,3:5)*100)/100; TMPREJ = []; if exist('color') == 1 && ~isempty(color) color = round(color*100)/100; for index = 1:size(color,1) tmpcol1 = TMPREJINIT(:,3) + 255*TMPREJINIT(:,4) + 255*255*TMPREJINIT(:,5); tmpcol2 = color(index,1)+255*color(index,2)+255*255*color(index,3); I = find( tmpcol1 == tmpcol2); %if isempty(I) % fprintf('Warning: color [%d %d %d] not found\n', ... % color(index,1), color(index,2), color(index,3)); %end; TMPREJ = [ TMPREJ; TMPREJINIT(I,:)]; end; else TMPREJ = TMPREJINIT; % remove other specific colors % ---------------------------- if exist('colorout') == 1 colorout = round(colorout*100)/100; for index = 1:size(colorout,1) tmpcol1 = TMPREJ(:,3) + 255*TMPREJ(:,4) + 255*255*TMPREJ(:,5); tmpcol2 = colorout(index,1)+255*colorout(index,2)+255*255*colorout(index,3); I = find( tmpcol1 == tmpcol2); TMPREJ(I,:) = []; end; end; end; % perform the conversion % ---------------------- tmprejelec = []; tmpsig = zeros(1,sweeps); if ~isempty(TMPREJ) nbchan = size(TMPREJ,2)-5; TMPREJ = sortrows(TMPREJ,1); TMPREJ(find(TMPREJ(:,1) == 1),1) = 0; tmpsig = TMPREJ(:,1)''/pnts+1; I = find(tmpsig == round(tmpsig)); tmp = tmpsig(I); tmpsig = zeros(1,sweeps); tmpsig(tmp) = 1; I = find(tmpsig); tmprejelec = zeros( nbchan, sweeps); tmprejelec(:,I) = TMPREJ(:,6:nbchan+5)'; end; return;
github
ZijingMao/baselineeegtest-master
reref.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/reref.m
9,588
utf_8
d1a7ce88ac95a65fc25d21b6f9b28713
% reref() - convert common reference EEG data to some other common reference % or to average reference % Usage: % >> Dataout = reref(data); % convert all channels to average reference % >> [Dataout Chanlocs] = reref(data, refchan, 'key', 'val'); % % convert data to new reference with options % Inputs: % data - 2-D or 3-D data matrix (chans,frames*epochs) % refchan - reference channel number(s). There are three possibilities: % 1) [] - compute average reference % 2) [X]: re-reference to channel X % 2) [X Y Z ...]: re-reference to the average of channel X Y Z ... % % Optional inputs: % 'exclude' - [integer array] channel indices to exclude from re-referencing % (e.g., event marker channels, etc.) % 'keepref' - ['on'|'off'] keep reference channel in output (only usable % when there are several references). % 'elocs' - Current data electrode location structure (e.g., EEG.chanlocs). % 'refloc' - Reference channel location single element structure or cell array % {'label' theta radius} containing the name and polar coordinates % of the current channel. Including this entry means that % this channel will be included (reconstructed) in the % output. % % Outputs: % Dataout - Input data converted to the new reference % Chanlocs - Updated channel locations structure % % Notes: 1) The average reference calculation implements two methods % (see www.egi.com/Technotes/AverageReference.pdf) % V'i = (Vi-Vref) - sum(Vi-Vref)/number_of_electrodes % % Authors: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2009- % previous version: Arnaud Delorme & Scott Makeig, 1999-2002 % Deprecated inputs: % These inputs are still accepted but not processed. The function returns % accurate results irrespective of the entry of these options. % 'refstate ' - ['common'|'averef'|[indices]] Current reference condition, % ('averef') = average reference; ('common' or 0) = common % reference. [indices] designate the current reference channel % or channels if present in the data {default: 'common'} % 'method' - ['standard'|'withref'] Do not ('standard') or do ('withref') % include reference channel data in output {def: 'standard'}. % Note: Option 'withref' not possible when multiple ref channel % indices are given as argument to 'refstate' (below). % % ICA inputs: % These inputs are still accepted but not the ICA conversion is now % performed from within pop_reref() % 'icaweights' - ICA weight matrix. Note: If this is ICA weights*sphere, % then the 'icasphere' input below should be [] or identity. % 'icasphere' - ICA sphere matrix (if any) % 'icachansind' - Indices of the channels used in ICA decomposition % % Outputs: % Wout - ICA weight matrix (former icaweights*icasphere) % converted to new data reference % Sout - ICA sphere matrix converted to an identity matrix % ICAinds - New indices of channels used in ICA decomposition % meandata - (1,dataframes) means removed from each data point % % 2) In conversion of the weight matrix to a new reference % where WS = Wts*Sph and ica_act = WS*data, then % data = inv(WS)*ica_act; % If R*data are the re-referenced data, % R*data= R*inv(WS)*ica_act; % And Wout = inv(R*inv(WS)); % Now, Sout = eye(length(ICAinds)); % The re-referenced ICA component maps are now the % columns of inv(Wout), and the icasphere matrix, Sout, % is an identity matrix. Note: inv() -> pinv() when % PCA dimension reduction is used during ICA decomposition. % Copyright (C) 1999 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 12/16/99 Corrected denomiator on the suggestion of Ian Nimmo-Smith, Cambridge UK % 01-25-02 reformated help & license -ad function [data, Elocs, morechans, W, S, icachansind, meandata] = reref(data, ref, varargin) if nargin<1 help reref return end if nargin < 2 ref = []; end; % check inputs % ------------ g = finputcheck(varargin, { 'icaweight' 'real' [] []; 'icaweights' 'real' [] []; 'icasphere' 'real' [] []; 'icachansind' 'integer' [] []; 'method' 'string' { 'standard','withref' } 'standard'; 'refstate' { 'string','integer' } { { 'common','averef' } [1 size(data,1)] } 'common'; % ot used but kept for backward compatib. 'exclude' 'integer' [1 size(data,1)] []; 'refloc' { 'cell','struct' } { [] [] } {}; 'keepref' 'string' {'on','off' } 'off'; 'elocs' {'integer','struct'} [] [] }); if isstr(g), error(g); end; if ~isempty(g.icaweight) g.icaweights = g.icaweight; end; if ~isempty(g.icaweights) if isempty(g.icachansind), g.icachansind = [1:size(g.icaweights,2)]; disp('Warning: reref() output has changed slightly since EEGLAB 5.02'); disp(' the 4th output argument is the indices of channels used for ICA instead'); disp(' of the mean reference value (which is now output argument 5)'); end; end; if ~isempty(ref) if ref > size(data,1) error('reference channel index out of range'); end; end; [dim1 dim2 dim3] = size(data); data = reshape(data, dim1, dim2*dim3); % single reference not present in the data % add it as blank data channel at the end % ---------------------------------------- if ~isempty(g.refloc) == 1 if ~isempty(g.elocs) if iscell(g.refloc) data(end+1,:) = 0; g.elocs(end+1).labels = g.refloc{1}; g.elocs(end ).theta = g.refloc{2}; g.elocs(end ).radius = g.refloc{3}; else data(end+length(g.refloc),:) = 0; for iLocs = 1:length(g.refloc) g.elocs(end+1).labels = g.refloc(iLocs).labels; fieldloc = fieldnames(g.elocs); for ind = 1:length(fieldloc) g.elocs(end) = setfield(g.elocs(end), fieldloc{ind}, getfield(g.refloc(iLocs), fieldloc{ind})); end; end; end; end; [dim1 dim2 dim3] = size(data); end; % exclude some channels % --------------------- chansin = setdiff_bc([1:dim1], g.exclude); nchansin = length(chansin); % return mean data % ---------------- if nargout > 4 meandata = sum(data(chansin,2))/nchansin; end; % generate rereferencing matrix % ----------------------------- if 0 % alternate code - should work exactly the same if isempty(ref) ref=chansin; % average reference end % if chansout=chansin; data(chansout,:)=data(chansout,:)-ones(nchansin,1)*mean(data(ref,:),1); else if ~isempty(ref) % not average reference refmatrix = eye(nchansin); % begin with identity matrix tmpref = ref; for index = length(g.exclude):-1:1 tmpref(find(g.exclude(index) < tmpref)) = tmpref(find(g.exclude(index) < tmpref))-1; end; for index = 1:length(tmpref) refmatrix(:,tmpref(index)) = refmatrix(:,tmpref(index))-1/length(tmpref); end; else % compute average reference refmatrix = eye(nchansin)-ones(nchansin)*1/nchansin; end; chansout = chansin; data(chansout,:) = refmatrix*data(chansin,:); end; % change reference in elocs structure % ----------------------------------- if ~isempty(g.elocs) if isempty(ref) for ind = chansin g.elocs(ind).ref = 'average'; end; else reftxt = { g.elocs(ref).labels }; if length(reftxt) == 1, reftxt = reftxt{1}; else reftxt = cellfun(@(x)([x ' ']), reftxt, 'uniformoutput', false); reftxt = [ reftxt{:} ]; end; for ind = chansin g.elocs(ind).ref = reftxt; end; end; end; % remove reference % ---------------- morechans = []; if strcmpi(g.keepref, 'off') data(ref,:) = []; if ~isempty(g.elocs) morechans = g.elocs(ref); g.elocs(ref) = []; end; end; data = reshape(data, size(data,1), dim2, dim3); % treat optional ica parameters % ----------------------------- W = []; S = []; icachansind = []; if ~isempty(g.icaweights) disp('Warning: This function does not process ICA array anymore, use the pop_reref function instead'); end; Elocs = g.elocs;
github
ZijingMao/baselineeegtest-master
plotdata.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/plotdata.m
20,127
utf_8
dc7d1faf9633b845ff3de9c423067fc0
% plotdata() - plot concatenated multichannel data epochs in two-column format % % Usage: >> plotdata(data) % >> plotdata(data,frames) % >> plotdata(data,frames,limits,title,channames,colors,rtitle,ydir) % % Necessary input: % data = data consisting of consecutive epochs of (chans,frames) % % Optional inputs: % frames = time frames/points per epoch {default: 0 -> data length} % [limits] = [xmin xmax ymin ymax] (x's in ms) % {default|0 (or both y's 0) -> use data limits) % 'title' = plot title {default|0 -> none} % 'channames' = channel location file or structure (see readlocs()) % {default|0 -> channel numbers} % 'colors' = file of color codes, 3 chars per line % ( '.' = space) {default|0 -> default color order} % 'rtitle' = right-side plot title {default|0 -> none} % ydir = y-axis polarity (1 -> pos-up; -1 -> neg-up) % {default|0 -> set from default YDIR in 'icadefs.m'} % % Authors: Scott Makeig, Arnaud Delorme, Tzyy-Ping Jung, % SCCN/INC/UCSD, La Jolla, 05-01-96 % % See also: plottopo(), timtopo(), envtopo(), headplot(), compmap(), eegmovie() % Copyright (C) 05-01-96 Scott Makeig, Arnaud Delorme & Tzyy-Ping Jung, % SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 5-1-96 from showerps.m -sm from showerp.m -tpj % 5-3-96 added default channel numbering, frames & title -sm % 5-17-96 added nargin tests below -sm % 5-21-96 added right titles -sm % 6-29-96 removed Postscript file query -sm % 7-22-96 restored lines to fill printed page with figure -sm % 7-29-96 added [channumbers] option for channames argument. -sm % changed "channels" argument to "channames" in help statement above -sm % 1-6-97 debugged min/max time and +/- printing -tpj & sm % 3-3-97 restored previous Default axis parameters at end -sm % 4-2-97 debugged 32-epoch plotting -sm % 5-10-97 added no-args check -sm % 5-20-97 read icadefs.m for MAXPLOTDATACHANS and MAXPLOTDATAEPOCHS -sm % 6-23-97 use returns instead of errorcodes -sm % 10-31-97 use normalized PaperUnits for US/A4 compatibility, % fixed [xy]{min,max} printing, added clf, adding Clipping off, % fixed scaling, added limits tests -sm & ch % 11-19-97 removed an 'orient' command that caused problems printing -sm % 07-15-98 added 'ydir' arg, made pos-up the default -sm % 07-24-98 fixed 'ydir' arg, and pos-up default -sm % 01-02-99 added warning about frames not dividing data length -sm % 02-19-99 debugged axis limits -sm % 11-21-01 add compatibility to load .loc files for channames -ad % 01-25-02 reformated help & license, added links -ad % 02-16-02 added axcopy -ad & sm % 03-15-02 added readlocs and the use of eloc input structure -ad % 03-15-02 added smart axcopy -ad function plotdata(data,frames,limits,plottitle,channels,colors,righttitle,ydr) if nargin < 1, help plotdata return end % % Set defaults % FONTSIZE = 12; % font size to use for labels TICKFONTSIZE=12; % font size to use for axis labels icadefs; % read MAXPLOTDATACHANS constant from icadefs.m % read YDIR if ~exist('YDIR') fprintf('YDIR not read from ''icadefs.m'' - plotting positive-up.\n'); YDIR = 1; end DEFAULT_SIGN = YDIR; % default to plotting positive-up (1) or negative-up (-1) % Now, read sign from YDIR in icadefs.m ISSPEC = 0; % default - 0 = not spectral data, 1 = pos-only spectra axcolor= get(0,'DefaultAxesXcolor'); % find what the default x-axis color is plotfile = 'plotdata.ps'; ls_plotfile = 'ls -l plotdata.ps'; % %%%%%%%%%%%%%%%%%%%%%%%%%% Substitute defaults for missing parameters %%%%% % SIGN = DEFAULT_SIGN; % set default ydir from YDIR in icadefs.m if nargin < 8 ydr = []; end if ~isempty(ydr)& ydr ~=0 % override default from commandline if ydr == 1 SIGN = 1; else SIGN = -1; end end if nargin < 7, righttitle = 0; end; if nargin < 6 colors = 0; end if nargin < 5 channels = [1:size(data,1)]; % default channames = 1:chans end if nargin < 4 plottitle = 0; %CJH end limitset = 0; if nargin < 3, limits = 0; elseif length(limits)>1 limitset = 1; end if nargin < 2, frames = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%% Test parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % [chans,framestotal]=size(data); % data size if frames <=0, frames = framestotal; % default datasets=1; elseif frames==1, fprintf('plotdata: cannot plot less than 2 frames per trace.\n'); return datasets=1; else datasets = fix(framestotal/frames); % number of traces to overplot if datasets*frames < framestotal fprintf('\nWARNING: %d points at end of data will not be plotted.\n',... framestotal-datasets*frames); end end; if chans>MAXPLOTDATACHANS, fprintf('plotdata: not set up to plot more than %d channels.\n',... MAXPLOTDATACHANS); return end; if datasets>MAXPLOTDATAEPOCHS fprintf('plotdata: not set up to plot more than %d epochs.\n',... MAXPLOTDATAEPOCHS); return end; if datasets<1 fprintf('plotdata: cannot plot less than 1 epoch!\n'); return end; % %%%%%%%%%%%%% Extend the size of the plotting area in the window %%%%%%%%%%%% % curfig = gcf; h=figure(curfig); set(h,'Color',BACKCOLOR); % set the background color set(h,'PaperUnits','normalized'); % use percentages to avoid US/A4 difference set(h,'PaperPosition',[0.0235308 0.0272775 0.894169 0.909249]); % equivalent % orient portrait axis('normal'); % %%%%%%%%%%%%%%%%%%%% Read the channel names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if isnumeric(channels) & channels(1)==0, channels = [1:size(data,1)]; end; if isnumeric(channels), channames = num2str(channels(:)); %%CJH else [tmp channames] = readlocs(channels); channames = strvcat(channames{:}); end; % chid = fopen(channels,'r'); % if chid <3, % fprintf('plotdata(): cannot open file %s.\n',channels); % return % end; % if isempty( findstr( lower(channels), '.loc') ) % channames = fscanf(chid,'%s',[4 Inf]); % channames = channames'; % else % channames = fscanf(chid,'%d %f %f %s',[7 128]); % channames = char(channames(4:7,:)'); % end; % ii = find(channames == '.'); % channames(ii) = ' '; %channames = channames'; % [r c] = size(channames); %for i=1:r % for j=1:c % if channames(i,j)=='.', % channames(i,j)=' '; % end; % end; %end; % end; % setting channames % %%%%%%%%%%%%%%%%%%%%%%%%% Read the color names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if colors ~=0, if ~isstr(colors) fprintf('plotdata(): color file name must be a string.\n'); return end cid = fopen(colors,'r'); % fprintf('cid = %d\n',cid); if cid <3, fprintf('plotdata: cannot open file %s.\n',colors); return end; colors = fscanf(cid,'%s',[3 Inf]); colors = colors'; [r c] = size(colors); for i=1:r for j=1:c if colors(i,j)=='.', colors(i,j)=' '; end; end; end; else % use default color order (no yellow!) colors =['r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m ']; colors = [colors; colors]; % make > 64 available end; for c=1:size(colors,1) % make white traces black unless axis color is white if colors(c,1)=='w' & axcolor~=[1 1 1] colors(c,1)='k'; end end % %%%%%%%%%%%%%%%%%%%%%%% Read and adjust limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if limits==0, % == 0 or [0 0 0 0] xmin=0; xmax=frames-1; ymin=min(min(data)); ymax=max(max(data)); yrange = ymax-ymin; ymin = ymin - 0.00*yrange; ymax = ymax + 0.00*yrange; else if length(limits)~=4, fprintf( ... 'plotdata: limits should be 0 or an array [xmin xmax ymin ymax].\n'); return end; xmin = limits(1); xmax = limits(2); ymin = limits(3); ymax = limits(4); end; if xmax == 0 & xmin == 0, x = (0:1:frames-1); xmin = 0; xmax = frames-1; else dx = (xmax-xmin)/(frames-1); x=xmin*ones(1,frames)+dx*(0:frames-1); % compute x-values end; if xmax<=xmin, fprintf('plotdata() - xmax must be > xmin.\n') return end if ymax == 0 & ymin == 0, ymax=double(max(max(data))); ymin=double(min(min(data))); yrange = ymax-ymin; % ymin = ymin - 0.00*yrange; % ymax = ymax + 0.00*yrange; end if ymax<=ymin, fprintf('plotdata() - ymax must be > ymin.\n') return end xlabel = 'Time (ms)'; if ymin >= 0 & xmin >= 0, % For all-positive (spectral) data ISSPEC = 1; SIGN = 1; fprintf('\nPlotting positive up. Assuming data are spectra.\n'); xlabel = 'Freq (Hz)'; ymin = 0; % plot positive-up end; % %%%%%%%%%%%%%%%%%%%%%%%% Set up plotting environment %%%%%%%%%%%%%%%%%%%%%%%%% % h = gcf; % set(h,'YLim',[ymin ymax]); % set default plotting parameters % set(h,'XLim',[xmin xmax]); % set(h,'FontSize',18); % set(h,'DefaultLineLineWidth',1); % for thinner postscript lines % %%%%%%%%%%%%%%%%%%%%%%%%%% Print plot info %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % clf; % clear the current figure % print plottitle over (left) sbplot 1 if plottitle==0, plottitle = ''; end if righttitle==0, righttitle = ''; end if ~isempty(righttitle) sbplot(ceil(chans/2),2,2), h=gca;%title([righttitle], 'FontSize',FONTSIZE); % title plot and set(h,'FontSize',FONTSIZE); % choose font size set(h,'YLim',[ymin ymax]); % set default plotting parameters set(h,'XLim',[xmin xmax]); end; msg = ['\nPlotting %d traces of %d frames with colors: ']; for c=1:datasets msg = [msg colors(mod(c-1,length(colors))+1,:)]; end msg = [msg ' -> \n']; % print starting info on screen . . . fprintf(... '\n limits: [xmin,xmax,ymin,ymax] = [%4.1f %4.1f %4.2f %4.2f]\n',... xmin,xmax,ymin,ymax); fprintf(msg,datasets,frames); % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Plot traces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % xdiff=xmax-xmin; ydiff=ymax-ymin; for P=0:datasets-1, % for each data epoch fprintf('\ntrace %d: ',P+1); for I=1:chans, % for each data channel index=(2*((rem(I-1,ceil(chans/2))+1)))-1+floor(2*(I-1)/chans); % = 1 3 5 .. 2 4 6 .. % plot down left side of page first h=sbplot(ceil(chans/2),2,index); h=gca; pos = get(h,'position'); set(h,'position',[pos(1)-pos(4)*0.5 pos(2), pos(3),pos(4)*2]); % increase sbplot-height hold on; set(h,'YLim',[ymin ymax]); % set default plotting parameters set(h,'XLim',[xmin xmax]); axislcolor = get(gca,'Xcolor'); %%CJH % %%%%%%%%%%%%%%%%%%%%% Plot two-sided time-series data %%%%%%%%%%%%%%%%%%% % if ~ISSPEC % not spectral data ymin = double(ymin); ymax = double(ymax); if ymin == ymax, ymin = ymin-1; ymax = ymax+1; end; plot(x,SIGN*data(I,1+P*frames:1+P*frames+frames-1),colors(mod(P,length(colors))+1)); if SIGN > 0 axis([xmin xmax ymin ymax]); % set axis bounds (pos up) else axis([xmin xmax -1*ymax -1*ymin]); % set axis bounds (neg up) end if P==datasets-1, % on last traces if I==floor((chans+1)/2), % draw +/0 on lowest left plot signx = double(xmin-0.04*xdiff); if SIGN > 0 % pos up axis('off');hl=text(signx,ymin,num2str(ymin,3)); % text ymin axis('off');hi=text(signx,ymax,['+' num2str(ymax,3)]); % text +ymax else % neg up axis('off');hl=text(signx,-1*ymin,num2str(ymin,3)); % text ymin axis('off');hi=text(signx,-1*ymax,['+' num2str(ymax,3)]); % text +ymax end set(hl,'FontSize',TICKFONTSIZE); % choose font size set(hl,'HorizontalAlignment','right','Clipping','off'); set(hi,'FontSize',TICKFONTSIZE); % choose font size set(hi,'HorizontalAlignment','right','Clipping','off'); end if I==chans & limitset, % draw timescale on lowest right plot ytick = double(-ymax-0.25*ydiff); tick = [int2str(xmin)]; h=text(xmin,ytick,tick); % min time set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','center',... 'Clipping','off'); % center text tick = [xlabel]; h=text(xmin+xdiff/2,ytick,tick); % xlabel set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','center',... 'Clipping','off'); % center text tick = [int2str(xmax)]; h=text(xmax,ytick,tick); % max time set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','center',... 'Clipping','off'); % center text end; end; % %%%%%%%%%%%%%%%%%%%%% Plot spectral data positive-up [0,ymax] %%%%%%%%%%%%%%%%%%%%%%%% % else % ISSPEC ymin=0; plot(x,SIGN*data(I,1+P*frames:1+P*frames+frames-1),colors(mod(P,length(colors))+1)); ymaxm = ymax; % ymin = 0.01; % ymaxm = 10.^ceil(log(ymax)/log(10.)); % if ymaxm/2. > ymax, % ymaxm = ymaxm/2.; % end; axis([xmin xmax ymin ymaxm]); % set axis values if P==datasets-1, % on last trace if I==floor((chans+1)/2), % draw +/0 on lowest left plot signx = xmin-0.04*xdiff; axis('off');h=text(signx,ymax,['+' num2str(ymax,3)]); set(h,'FontSize',TICKFONTSIZE); set(h,'HorizontalAlignment','right','Clipping','off'); axis('off');h=text(signx,0,'0'); set(h,'FontSize',TICKFONTSIZE); set(h,'HorizontalAlignment','right','Clipping','off'); end; if I==chans, % draw freq scale on lowest right plot ytick = -0.25*ymax; tick = [num2str(round(10*xmin)/10) ]; h=text(xmin,ytick,tick); set(h,'FontSize',TICKFONTSIZE); set(h,'HorizontalAlignment','center','Clipping','off'); tick = [xlabel]; h=text(xmin+xdiff/2,ytick,tick); set(h,'FontSize',TICKFONTSIZE); set(h,'HorizontalAlignment','center','Clipping','off'); tick = [num2str(round(10*xmax)/10) ]; h=text(xmax,ytick,tick); set(h,'FontSize',TICKFONTSIZE); set(h,'HorizontalAlignment','center','Clipping','off'); end; % if last chan end % if last data end; % if ~ISSPEC %%%%%%%%%%%%%%%%%%%%%%% Print channel names and lines %%%%%%%%%%%%%%%%%%%%%%%%%% if P==datasets-1 if ~ISSPEC axis('off'); plot([0 0],[ymin ymax],'color',axislcolor); % draw vert %%CJH % axis at time 0 else % ISSPEC axis('off');plot([xmin xmin],[0 ymax],'color',axislcolor); end % secondx = 200; % draw second vert axis % axis('off');plot([secondx secondx],[ymin ymax],'color',axislcolor); axis('off'); plot([xmin xmax],[0 0],'color',axislcolor); % draw horizontal axis if ~isempty(channels), % print channames if ~ISSPEC if ymin <= 0 & ymax >= 0, yht = 0; else yht = nan_mean(SIGN*data(I,1+P*frames:1+P*frames+frames-1)); end axis('off'),h=text(xmin-0.04*xdiff,double(yht),[channames(I,:)]); set(h,'HorizontalAlignment','right'); % print before traces set(h,'FontSize',FONTSIZE); % choose font size % axis('off'),h=text(xmax+0.10*xdiff,yht,[channames(I,:)]); % set(h,'HorizontalAlignment','left'); % print after traces else % ISSPEC axis('off'),h=text(xmin-0.04*xdiff,ymax/2,[channames(I,:)]); set(h,'HorizontalAlignment','right'); % print before traces set(h,'FontSize',FONTSIZE); % choose font size % axis('off'),h=text(xmax+0.10*xdiff,ymax/2,[channames(I,:)]); % set(h,'HorizontalAlignment','left'); % print after traces end; end; end; fprintf(' %d',I); end; % subplot end; % dataset fprintf('\n'); % %%%%%%%%%%%%%%%%%% Make printed figure fill page %%%%%%%%%%%%%%%%%%%%%%%%%%% % curfig = gcf; h=figure(curfig); % set(h,'PaperPosition',[0.2 0.3 7.6 10]); % stretch out the plot on the page % %%%%%%%%%%%%%%%%%% Restore plot environment %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % set(h,'DefaultAxesYLim',aylim); % restore previous plotting parameters % set(h,'DefaultAxesXLim',axlim); % set(h,'DefaultAxesFontSize',axfont); %%%%%%%%%%%%%%%%%% Add axcopy %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if plottitle h = textsc(plottitle, 'title'); set(h, 'fontsize', FONTSIZE); end; axcopy(gcf, 'axis on'); if 0, % START DETOUR XXXXXXXXXXXXX % %%%%%%%%%%%%%%%%%% Save plot to disk if asked %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if plotfile ~= '', % n=0; y=1; answer = input('plotdata: Save plot as Postscript file? (y/n) '); if answer==1, fprintf('\nSaving figure as %s ... ',plotfile); curfig = gcf; h=figure(curfig); % set(h,'PaperPosition',[0.2 0.3 7.6 10]); % stretch out the plot on the page eval (['print -dpsc ' plotfile]); fprintf('saved. Move or remove file!\n'); unix(ls_plotfile); end end end % END DETOUR XXXXXXXXXXXXX function out = nan_mean(in) nans = find(isnan(in)); in(nans) = 0; sums = sum(in); nonnans = ones(size(in)); nonnans(nans) = 0; nonnans = sum(nonnans); nononnans = find(nonnans==0); nonnans(nononnans) = 1; out = sum(in)./nonnans; out(nononnans) = NaN;
github
ZijingMao/baselineeegtest-master
snapread.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/snapread.m
5,372
utf_8
acab56fb5681e5c05feaebf418734cad
% snapread() - Read data in Snap-Master Standard Binary Data File Format % Reads Snap-Master header and data matrix (nchans,nframes). % Ref: Users Guide, Snap-Master for Windows (1997) p. 4-19 % Usage: % >> data = snapread(filename); % read .SMA file data % >> [data,params,events,head] = snapread(filename,seekframes); % % save parameters, event list % Inputs: % filename = string containing whole filename of .SMA file to read % seekframes = skip this many initial time points {default 0} % Output: % data = data matrix, size(nchans,nframes) % params = [nchannels, nframes, srate] % events = vector of event frames (lo->hi transitions on event channel); % See source to set EVENT_CHANNEL and EVENT_THRESH. % head = complete char file header % % Authors: Scott Makeig & Tzyy-Ping Jung, SCCN/INC/UCSD, La Jolla, January 31, 2000 % Copyright (C) January 31, 2000 from plotdata() Scott Makeig & Tzyy-Ping Jung, SCCN/INC/UCSD, % [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % Scott Makeig & Tzyy-Ping Jung, CNL / Salk Institute / January 31, 2000 % 7-13-00 fixed fprintf count print bug -sm % 7-13-00 added arg seekframes -sm & ss % 7-13-00 added test for file length -sm & ss % 2-15-02 change close('all') to fclose('all') -ad % 2-15-02 reformated help & license -ad function [data,params,events,head] = snapread(file,seekframes) EVENT_CHANNEL = 1; % This channel assumed to store event pulses only! EVENT_THRESH = 2.3; % Default event threshold (may need to adjust!!!!) if nargin < 2 seekframes = 0; end data = []; events = []; params = []; head = []; % %%%%%%%%%%%%%%%%%%%%%%%%%% Open file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fid = fopen(file,'r', 'ieee-le'); if fid<1 fprintf('\nsnapread(): Could not open file %s.\n\n',file) return else fprintf('\n Opened file %s for reading...\n',file); end % %%%%%%%%%%%%%%%%%%%%%%%%%% Read header %%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Read header and extract info numbegin=0; head = []; while ~numbegin, line =fgets(fid); head = [head line]; if (length(line)>=8 & line(1:8)=='"NCHAN%"') nchans=str2num(line(findstr(line,'=')+1:end-1)); end if (length(line)>= 12 & line(1:12)=='"NUM.POINTS"') nframes=str2num(line(findstr(line,'=')+1:end-1)); end if (length(line)>= 10 & line(1:10)=='"ACT.FREQ"') srate=str2num(line(findstr(line,'=')+1:end-1)); end if (length(line)>= 4 & line(1:4)=='"TR"') head = head(1:length(head)-length(line)); line =fgets(fid); % get the time and date stamp line numbegin=1; end end params = [nchans, nframes, srate]; fprintf(' Number of channels: %d\n',nchans); fprintf(' Number of data points: %d\n',nframes); fprintf(' Sampling rate: %3.1f Hz\n',srate); fseek(fid,1,0); % skip final hex-AA char % %%%%%%%%%%%%%%%%%%% Test for correct file length %%%%%%%%%%%%%%%%%%%% % datstart = ftell(fid); % save current position in file fseek(fid,0,'eof'); % go to file end datend = ftell(fid); % report position discrep = (datend-datstart) - nchans*nframes*4; if discrep ~= 0 fprintf(' ***> Note: File length does not match header information!\n') fprintf(' Difference: %g frames\n',discrep/(4*nchans)); end fseek(fid,datstart,'bof'); % seek back to data start % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Read data %%%%%%%%%%%%%%%%%%%%%%%%%% % if seekframes > 0 fprintf(' Omitting first %d frames of data.\n',seekframes) fprintf('moving %d bytes\n',seekframes*nchans*4); fsq = fseek(fid,seekframes*nchans*4,'cof') if fsq<0 fsqerr = ferror(fid); fprintf('fseek() error: %s\n',fsqerr); return end end [data count] = fread(fid,[nchans,nframes],'float'); % read data frame if count<nchans*(nframes-seekframes) fprintf('\nsnapread(): Could not read %d data frames.\n Only %g read.\n\n',... nframes,count/nchans); return else fprintf('\n Read %d frames, each one sync channel(%d) and %d data channels.\n',... nframes,EVENT_CHANNEL,nchans-1); end if nargout>2 fprintf(' Finding event transitions (>%g) on channel %d ...\n',... EVENT_THRESH,EVENT_CHANNEL); events = zeros(EVENT_CHANNEL,nframes); for n=2:nframes if abs(data(EVENT_CHANNEL,n-1)) < EVENT_THRESH ... & abs(data(EVENT_CHANNEL,n)) > EVENT_THRESH events(n) = 1; end end fprintf(' Total of %d events found.\n',sum(events)); data = data(2:nchans,:); % eliminate channel 1 fprintf(' Event channel %d removed from output.\n',EVENT_CHANNEL); params(1) = nchans-1; end fprintf('\n'); fclose('all');
github
ZijingMao/baselineeegtest-master
cart2topo.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/cart2topo.m
5,225
utf_8
7ae7263796eecb060729861c9dd9b2fd
% cart2topo() - convert xyz-cartesian channel coordinates % to polar topoplot() coordinates. Input data % are points on a sphere centered at (0,0,0) % or at optional input 'center'. This function % is now DEPRECATED! See Important warning below. % % Usage: >> [th r] = cart2topo(xyz); % 3-column [x y z] position data % >> [th r] = cart2topo(x,y,z); % separate x,y,z vectors % >> [th r x y z] = cart2topo(xyz,'key', 'val', ...); % >> [th r x y z] = cart2topo(x,y,z,'key', 'val', ...); % % Optional inputs: % 'center' = [X Y Z] use a known sphere center {Default: [0 0 0]} % 'squeeze' = plotting squeeze factor (0[default]->1). -1 -> optimize % the squeeze factor automatically so that maximum radius is 0.5. % 'optim' = [0|1] find the best-fitting sphere center minimizing the % standard deviation of the radius values. % 'gui' = ['on'|'off'] pops up a gui for optional arguments. % Default is off. % % Example: >> [th r] = cart2topo(xyz,[1 0 4]); % % Notes: topoplot() does not plot channels with radius>0.5 % Shrink radii to within this range to plot all channels. % [x y z] are returned after the optimization of the center % and optionally squeezing r towards it by factor 'squeeze' % % Important: % DEPRECATED: cart2topo() should NOT be used if elevation angle is less than 0 % (for electrodes below zero plane) since then it returns INNACURATE results. % SUBSTITUTE: Use cart2topo = cart2sph() -> sph2topo(). % % Authors: Scott Makeig, Luca Finelli & Arnaud Delorme SCCN/INC/UCSD, % La Jolla, 11/1999-03/2002 % % See also: topo2sph(), sph2topo(), chancenter() % Copyright (C) 11/1999 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 3-16-00 improved help message -sm % 1-25-02 put spherror subfunction inside cart2topo -ad % 1-25-02 help pops-up if no arguments -ad % 01-25-02 reformated help & license -ad % 02-13-02 now center fitting works, need spherror outside cart2topo -lf % 02-14-02 radii are squeezed of squeeze in to fit topoplot circle -lf % 03-31-02 center fitting is optional % 04-01-02 automatic squeeze calculation -ad & sm function [th,r,xx,yy,zz] = cart2topo(x,varargin) if nargin<1 help cart2topo return; end; if nargin >= 2 if ~ischar(varargin{1}) y = varargin{1}; z = varargin{2}; varargin = varargin(3:end); end; end; if exist('y') ~= 1 if size(x,2)==3 % separate 3-column data z = x(:,3); y = x(:,2); x = x(:,1); else error('Insufficient data in first argument'); end end; g = []; if ~isempty(varargin) try, g = struct(varargin{:}); catch, error('Argument error in the {''param'', value} sequence'); end; end; try, g.optim; catch, g.optim = 0; end; try, g.squeeze; catch, g.squeeze = 0; end; try, g.center; catch, g.center = [0 0 0]; end; try, g.gui; catch, g.gui = 'off'; end; if g.squeeze>1 fprintf('Warning: Squeeze must be less than 1.\n'); return end if ~isempty(g.center) & size(g.center,2) ~= 3 fprintf('Warning: Center must be [x y z].\n'); return end % convert to columns x = -x(:); % minus os for consistency between measures y = -y(:); z = z(:); if any(z < 0) disp('WARNING: some electrodes lie below the z=0 plane, result may be innacurate') disp(' Instead use cart2sph() then sph2topo().') end; if strcmp(g.gui, 'on') [x y z newcenter] = chancenter(x, y, z, [], 1); else if g.optim == 1 [x y z newcenter] = chancenter(x, y, z, []); else [x y z newcenter] = chancenter(x, y, z, g.center); end; end; radius = (sqrt(x.^2+y.^2+z.^2)); % assume xyz values are on a sphere xx=-x; yy=-y; zz=z; x = x./radius; % make radius 1 y = y./radius; z = z./radius; r = x; th=x; for n=1:size(x,1) if x(n)==0 & y(n)==0 r(n) = 0; else r(n) = pi/2-atan(z(n)./sqrt(x(n).^2+y(n).^2)); end end r = r/pi; % scale r to max 0.500 if g.squeeze < 0 g.squeeze = 1 - 0.5/max(r); %(2*max(r)-1)/(2*rmax); fprintf('Electrodes will be squeezed together by %2.3g to show all\n', g.squeeze); end; r = r-g.squeeze*r; % squeeze electrodes in squeeze*100% to have all inside for n=1:size(x,1) if abs(y(n))<1e-6 if x(n)>0 th(n) = -90; else % x(n) <= 0 th(n) = 90; end else th(n) = atan(x(n)./y(n))*180/pi+90; if y(n)<0 th(n) = th(n)+180; end end if th(n)>180 th(n) = th(n)-360; end if th(n)<-180 th(n) = th(n)+360; end end
github
ZijingMao/baselineeegtest-master
spec.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/spec.m
3,687
utf_8
02cf60598edf850b8ac8f112277a5be7
% spec() - power spectrum. This function replaces psd() function if the signal % processing toolbox is not present. It uses the timef() function. % % Usage: % >> [power freqs] = spec(X); % >> [power freqs] = spec(X, nfft, fs, win, overlap); % % Inputs: % X - data % nfft - zero padding to length nfft % fs - sampling frequency % win - window size % overlap - window overlap % % Outputs: % power - spectral estimate (amplitude not dB) % freqs - frequency array % % Note: this function is just an approximation of the psd() (not pwelch) % method. We strongly recommend to use the psd function if you have % access to it. % % Known problems: % 1) normalization formula was determined manually by comparing % with the output of the psd function on about 100 examples. % 2) In case only one time window is necessary, the overlapping factor % will be increased so that at least 2 windows are presents (the % timef function cannot use a single time window). % 3) FOR FILTERED DATA, THE POWER OVER THE FILTERED REGION IS WRONG % (TOO HIGH) % 4) the result of this function differs (in scale) from the pwelch % function since the normalization is different for pwelch. % % Author: Arnaud Delorme, SCCN, Dec 2, 2003 % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [power, freqs] = spec(X, nfft, fs, win, overlap); if nargin < 1 help spec; return; end; % default parameters % ------------------ if nargin < 2 nfft = 256; else nfft = pow2(nextpow2(nfft)); end; nfft = min(length(X), nfft); if nargin < 3 fs = 2; end; if nargin < 4 win = nfft; else win = pow2(nextpow2(win)); end; if win > length(X) win = length(X); end; if log2(win) ~= round(log2(win)) win = pow2(floor(log2(win))); end; if nargin < 5 overlap = 0; end; % compute corresponding parameters for timef % ------------------------------------------ padratio = pow2(nextpow2(nfft/win)); timesout = floor(length(X)/(win-overlap)); if timesout <= 1, timesout = 2; end; [ersp itc mbase times freqs] = timef(X(:)', length(X), [0 length(X)]/fs*1000, fs, ... 0, 'padratio', padratio, 'timesout', timesout, 'winsize', win, 'maxfreq', fs/2, ... 'plotersp', 'off', 'plotitc', 'off', 'baseline', NaN, 'verbose', 'off'); ersp = 10.^(ersp/10); % back to amplitude power = mean(ersp,2)*2.7/win; % this formula is a best approximation (I couldn't find the actual one) % in practice the difference with psd is less than 0.1 dB %power = 10*log10(power); if nargout < 1 hold on; h = plot(freqs, 10*log10(power)); set(h, 'linewidth', 2); end; return; figure; stdv = std(ersp, [], 2); h = plot(freqs, power+stdv, 'r:'); set(h, 'linewidth', 2); h = plot(freqs, power-stdv, 'r:'); set(h, 'linewidth', 2); xlabel('Frequency (Hz)'); ylabel('Power (log)');
github
ZijingMao/baselineeegtest-master
icavar.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/icavar.m
3,287
utf_8
20340418c38178274dabeb7cfd17572d
% icavar() - project ICA component activations through the ICA weight matrices % to reconstitute the observed data using selected ICA components. % Returns time course of variance on scalp for each component. % % Usage: >> [srcvar] = icavar(data,weights,sphere,compnums); % % Inputs: % data - data matrix returned by runica() % weights - weight matrix returned by runica() % sphere - sphere matrix returned by runica() (default|0 -> eye(ncomps)) % compnums - list of component numbers (default|0 -> all) % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 11-30-1996 % % See also: runica() % Copyright (C) 11-30-1996 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 04-03-97 made more efficient -sm % 05-20-97 debugged variance calculation and made it more efficient -sm % 06-07-97 changed order of args to conform to runica -sm % 07-23-97 do not add back datamean to projections -sm % 12-23-97 added compnums -sm % 02-25-98 changed activations input to data -sm % 07-20-98 use pinv() for inverting non-square weights -sm % 01-25-02 reformated help & license, added links -ad function [srcvar] = icavar(data,weights,sphere,compnums) if nargin<2 help icavar return end if size(weights,2) ~= size(sphere,1) | size(sphere,2) ~= size(data,1) fprintf('icavar() - sizes of weights, sphere, and data incompatible.\n') whos data weights sphere return end activations = weights*sphere*data; [ncomps,frames] = size(activations); [wr,chans] = size(weights); % Note: ncomps may < data chans if nargin<4 compnums = 0; end if compnums == 0, compnums = 1:ncomps; end srcvar = zeros(length(compnums),frames); if nargin < 3 sphere = 0; end if sphere == 0, sphere = eye(ncomps); end project = weights*sphere; if wr~=ncomps, fprintf('icavar: Number of rows in activations and weights must be equal.\n'); return end % if wr<chans, % fprintf('Filling out a square projection matrix with small noise.\n'); % for r=1:chans-wr, % project = [project;0.00001*randn(1,chans)]; % end % end % project = inv(project); % invert projection matrix if wr<chans project = pinv(project); else project = inv(project); end fprintf('Projecting ICA component '); nout = length(compnums); for i=1:nout % for each component comp = compnums(i); fprintf('%d ',comp); projdata = project(:,comp)*activations(comp,:); % reproject eeg data srcvar(i,:) = sum(projdata.*projdata)/(chans-1);% compute variance at each time point end fprintf('\n');
github
ZijingMao/baselineeegtest-master
eegrej.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/eegrej.m
5,344
utf_8
f3038cab2e3055aec9fb325966beb4c3
% eegrej() - reject/excise arbitrary periods from continuous EEG data % (e.g., EEG.data). % % Usage: % >> [outdata newt newevents boundevents] = ... % eegrej( indata, regions, timelength, eventlatencies); % % Inputs: % indata - input data (channels, frames). If indata is a string, % the function use the disk to perform the rejection % regions - array of regions to suppress. [beg end] x number of % regions. 'beg' and 'end' are expressed in term of points % in the input dataset. The size() of the array should be % (2, number of regions). % timelength - length in time (s) of the input data. Only used to compute % new total data length after rejections (newt). % eventlatencies - vector of event latencies in data points. % Default []=none. % % Outputs: % outdata - output dataset % newt - new total data length % newevents - new event latencies. If the event was in a removed % region, NaN is returned. % boundevents - boundary events latencies % % Exemple: % [outdat t] = eegrej( 'EEG.data', [1 100; 200 300]', [0 10]); % this command pick up two regions in EEG.data (from point 1 to % point 100, and point 200 to point 300) and put the result in % the EEG.data variable in the global workspace (thus allowing % to perform the operation even if EEG.data takes all the memory) % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [indata, times, newevents, boundevents] = eegrej( indata, regions, times, eventtimes ); if nargin < 2 help eegrej; return; end; if isstr(indata) datlen = evalin('base', [ 'size(' indata ',2)' ]); else datlen = size(indata, 2); end; reject = zeros(1,datlen); regions = round(regions); % Checking for extreme values in regions (correcting round) RMC if max(regions(:)) > size(indata, 2) IndxOut = find(regions(:) > size(indata, 2)); regions(IndxOut) = size(indata, 2); end regions = sortrows(sort(regions,2)); % Sorting regions %regions = sort(regions,1); RMC Izero = find(regions == 0); % Find regions index == 0 to adjust them if ~isempty(Izero), regions(Izero) = 1;end; % Fractional point below 1 adjusted to 1 for i=1:size(regions,1) try reject(regions(i,1):regions(i,2)) = 1; catch error(['Region ' int2str(i) ' out of bound']); end; end; % recompute event times % --------------------- newevents = []; if exist('eventtimes') == 1 if ~isempty(eventtimes) try rmevent = find( reject(min(length(reject),max(1,round(eventtimes)))) == 1); % cko: sometimes, events may have latencies < 0.5 or >= length(reject)+0.5 (e.g. after resampling) catch, error('Latency event out of bound'); end; eventtimes(rmevent) = NaN; newevents = eventtimes; for i=1:size(regions,1) for index=1:length( eventtimes ) if ~isnan(eventtimes(index)) if regions(i,2) < eventtimes(index) newevents(index) = newevents(index) - (regions(i,2)-regions(i,1)+1); end; end; end; end; end; end; % generate boundaries latencies % ----------------------------- boundevents = regions(:,1)-1; for i=1:size(regions,1) for index=i+1:size(regions) boundevents(index) = boundevents(index) - (regions(i,2)-regions(i,1)+1); end; end; boundevents = boundevents+0.5; if isstr(indata) disp('Using disk to reject data'); increment = 10000; global elecIndices; evalin('base', 'global elecIndices'); elecIndices = find(reject == 0); evalin('base', 'fid = fopen(''tmpeegrej.fdt'', ''w'')'); evalin('base', ['numberrow = size(' indata ',1)']); evalin('base', ['for indextmp=1:10000:length(elecIndices),', ... ' endtmp = min(indextmp+9999, length(elecIndices));' ... ' fwrite(fid,' indata '(:,elecIndices(indextmp:endtmp)), ''float'');'... 'end']); evalin('base', 'fclose(fid)'); evalin('base', 'clear global elecIndices'); evalin('base', [ indata '=[]; clear ' indata '']); evalin('base', 'fid = fopen(''tmpeegrej.fdt'', ''r'')'); evalin('base', [ indata '= fread(fid, [numberrow ' int2str(datlen) '], ''float'')']); evalin('base', 'fclose(fid)'); evalin('base', 'clear numberrow indextmp endtmp fid'); evalin('base', 'delete(''tmpeegrej.fdt'')'); else timeIndices = find(reject == 1); indata(:,timeIndices) = []; end; times = times * length(find(reject ==0)) / length(reject); return;
github
ZijingMao/baselineeegtest-master
sbplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/sbplot.m
4,612
utf_8
aac99a4963fad7c8aa7f4010998bc965
% sbplot() - create axes in arbitrary subplot grid positions and sizes % % Usage: >> axis_handle = sbplot(v,h,index) % >> axis_handle = sbplot(v,h,[index1 index2]) % >> axis_handle = sbplot(v,h,[index1 index2],axprop,..) % >> axis_handle = sbplot(v,h,[index1 index2],'ax',handle,axprop,..) % % Inputs: % v,h - Integers giving the vertical and horizontal ranks of the tiling. % index - Either a single subplot index, in which case the command % is equivalent to subplot, or a two-element vector giving % the indices of two corners of the sbplot() area according % to subplot() convention (e.g., left-to-right, top-to-bottom). % axprop - Any axes property(s), e.g., >> sbplot(3,3,3,'color','w') % handle - Following keyword 'ax', sbplot tiles the given axes handle % instead of the whole figure % % Output: % axis_handle - matlab axis handle % % Note: % sbplot is essentially the same as the subplot command except that % sbplot axes may span multiple tiles. Also, sbplot() will not erase % underlying axes. % % Examples: >> sbplot(3,3,6);plot(rand(1,10),'g'); % >> sbplot(3,3,[7 2]);plot(rand(1,10),'r'); % >> sbplot(8,7,47);plot(rand(1,10),'b'); % % Authors: Colin Humphries, Arnaud Delorme & Scott Makeig, SCCN/INC/UCSD, La Jolla, June, 1998 % Copyright (C) June 1998, Colin Humphries & Scott Makeig, SCCN/INC/UCSD, % [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % reformatted by Scott Makeig, 6/10/98 % 12/22/00 test nargin<3 -sm % 01/21/01 added (recursive) axes option 'ax' -sm % 01-25-02 reformated help & licence -ad function [out] = sbplot(m,n,gridpos,varargin) % varargin is std. matlab arg list if nargin<3 error(' requires >=3 arguments'); end if nargin>3 & strcmp(varargin{1},'ax') pos = get(varargin{2},'Position'); % sbplot(3,1,[2 3]) -> 0.4111 0.1100 0.4939 0.815 varargin = {varargin{3:end}}; else pos = get(gcf,'DefaultAxesPosition'); % [0.1300 0.1100 0.7750 0.815] end Xpad = pos(1); % lower-left distance from left side of figure Ypad = pos(2); % lower-left distance from bottom of figure Xlen = pos(3); % axes width Ylen = pos(4); % axes height if n == 2 xspace = Xlen*0.27/(n-0.27); % xspace between axes as per subplot else xspace = (0.9*Xlen)*0.27/(n-0.9*0.27); end if m == 2 yspace = Ylen*0.27/(m-0.27); % yspace between axes as per subplot else % WHY Xlen (.775) instead of Ylen (.815) ?? yspace = (0.9*Ylen)*0.27/(m-0.9*0.27); end xlength = (Xlen-xspace*(n-1))/n; % axes width ylength = (Ylen-yspace*(m-1))/m; % axes height % Convert tile indices to grid positions if length(gridpos) == 1 xgridpos(1) = mod(gridpos,n); % grid position if xgridpos(1) == 0 xgridpos(1) = n; end xgridpos(2) = 1; % grid length ygridpos(1) = m-ceil(gridpos/n)+1; % grid position ygridpos(2) = 1; % grid length else xgridpos(1) = mod(gridpos(1),n); if xgridpos(1) == 0 xgridpos(1) = n; end tmp = mod(gridpos(2),n); if tmp == 0 tmp = n; end if tmp > xgridpos(1) xgridpos(2) = tmp-xgridpos(1)+1; else xgridpos(2) = xgridpos(1)-tmp+1; xgridpos(1) = tmp; end ygridpos(1) = m-ceil(gridpos(1)/n)+1; tmp = m-ceil(gridpos(2)/n)+1; if tmp > ygridpos(1) ygridpos(2) = tmp-ygridpos(1)+1; else ygridpos(2) = ygridpos(1)-tmp+1; ygridpos(1) = tmp; end end % Calculate axes coordinates position(1) = Xpad+xspace*(xgridpos(1)-1)+xlength*(xgridpos(1)-1); position(2) = Ypad+yspace*(ygridpos(1)-1)+ylength*(ygridpos(1)-1)-0.03; position(3) = xspace*(xgridpos(2)-1)+xlength*xgridpos(2); position(4) = yspace*(ygridpos(2)-1)+ylength*ygridpos(2); % Create new axes ax = axes('Position',position,varargin{:}); % Output axes handle if nargout > 0 out = ax; end
github
ZijingMao/baselineeegtest-master
adjustlocs.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/adjustlocs.m
17,345
utf_8
540be08faa1b5d805504242c6d023cbb
% adjustlocs() - read neuroscan polar location file (.asc) % % Usage: % >> chanlocs = adjustlocs( chanlocs ); % >> chanlocs = adjustlocs( chanlocs, 'key1', val1, 'key2', val2, ...); % % Inputs: % chanlocs - EEGLAB channel location data structure. See % help readlocs() % % Optional inputs: % 'center' - [cell array] one or several electrode names to compute % center location (if several electrodes are provided, the % function use their iso-barycenter). Ex: { 'cz' } or % { 'fz' 'pz' }. % 'autocenter' - ['on'|'off'] attempt to automatically detect all symetrical % electrode in the 10-20 system to compute the center. % Default: 'on'. % 'rotate' - [cell array] name and planar angle of landmark electrodes % to use as template planar rotation. Ex: { 'c3', 90 }. % 'autorotate' - ['on'|'off'] attempt to automatically detect % electrode in the 10-20 system to compute the average % planar rotation. Default 'on'. % 'scale' - [cell array] name and phi angle of electrodes along % horizontal central line. Ex: { 'c3' 44 }. Scale uniformly % all direction. Use 'hscale' and 'vscale' for scaling x and % y axis independently. % 'hscale' - [cell array] name and phi angle of electrodes along % honrizontal central line. Ex: { 'c3' 44 }. % 'vscale' - [cell array] name and phi angle of one electrodes along % central vertical axis. Ex: { 'fz' 44 }. % 'autoscale' - ['on'|'off'] automatic scaling with 10-20 system used as % reference. Default is 'on'. % 'uniform' - ['on'|'off'] force the scaling to be uniform along the X % and the Y axis. Default is 'on'. % 'coordinates' - ['pol'|'sph'|'cart'] use polar coordinates ('pol'), sperical % coordinates ('sph') or cartesian ('cart'). Default is 'sph'. % (Note that using polar and spherical coordinates have the % same effect, except that units are different). % Default is 'sph'. % % Outputs: % chanlocs - EEGLAB channel location data structure. See % help readlocs() % % Note: operations are performed in the following order, first re-centering % then planar rotation and finally sperical re-scaling. % % Author: Arnaud Delorme, CNL / Salk Institute, 1 Dec 2003 % % See also: readlocs() % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function chanlocs = adjustlocs( chanlocs, varargin) if nargin < 1 help adjustlocs; return; end; % check input parameters % ---------------------- g = finputcheck( varargin, { 'hscale' 'cell' [] {}; 'vscale' 'cell' [] {}; 'scale' 'cell' [] {}; 'center' 'cell' [] {}; 'rotate' 'cell' [] {}; 'autoscale' 'string' { 'on','off' } 'off'; 'autocenter' 'string' { 'on','off' } 'on'; 'autorotate' 'string' { 'on','off' } 'on'; 'uniform' 'string' { 'on','off' } 'on'; 'coordinates' 'string' { 'pol','sph','cart' } 'sph' }); if ischar(g), error(g); end; names = { chanlocs.labels }; % auto center % ----------- if strcmpi(g.autocenter, 'on') & isempty(g.center) disp('Reading template 10-20 file'); locs1020 = readlocs('eeglab1020.ced'); % scan electrodes for horiz pos % ----------------------------- tmpnames = lower(names); tmpnames1020 = lower({ locs1020.labels }); [tmp indelec] = intersect_bc(tmpnames1020, tmpnames); % remove non-symetrical electrodes % -------------------------------- if ~isempty(indelec) if find(indelec == 79), indelec(end+1) = 80; end; % for Cz ind2remove = []; for index = 1:length(indelec) if mod(indelec(index),2) if ~ismember(indelec(index)+1, indelec) ind2remove = [ ind2remove index ]; end; else if ~ismember(indelec(index)-1, indelec) ind2remove = [ ind2remove index ]; end; end; end; indelec(ind2remove) = []; if find(indelec == 80), indelec(end) = []; end; % for Cz g.center = tmpnames1020(indelec); end; if isempty(g.center) disp('No electrodes found for auto-centering') else disp([ num2str(length(g.center)) ' landmark electrodes found for position auto-centering' ]) end; end; % auto rotate % ----------- if strcmpi(g.autorotate, 'on') & isempty(g.rotate) if exist('locs1020') ~= 1 disp('Reading template 10-20 file'); locs1020 = readlocs('eeglab1020.ced'); end; % scan electrodes for horiz pos % ----------------------------- tmpnames = lower(names); tmpnames1020 = lower({ locs1020.labels }); tmptheta1020 = { locs1020.theta }; [tmp indelec] = intersect_bc(tmpnames1020(1:end-1), tmpnames); % do not use cz g.rotate(1:2:2*length(indelec)) = tmpnames1020 (indelec); g.rotate(2:2:2*length(indelec)+1) = tmptheta1020(indelec); if isempty(g.rotate) disp('No electrodes found for auto planar rotation') else disp([ num2str(length(g.rotate)/2) ' landmark electrodes found for auto planar rotation' ]) end; end; % auto scale % ---------- if strcmpi(g.autoscale, 'on') & isempty(g.hscale) & isempty(g.vscale) if exist('locs1020') ~= 1 disp('Reading template 10-20 file'); locs1020 = readlocs('eeglab1020.ced'); end; if strcmpi(g.uniform, 'off') % remove all vertical electrodes for horizontal scaling % ----------------------------------------------------- theta = [ locs1020.theta ]; indxh = find(abs(theta) == 90); indxv = union_bc(find(theta == 0) , find(theta == 180)); locs1020horiz = locs1020(indxh); locs1020vert = locs1020(indxv); % scan electrodes for horiz pos % ----------------------------- tmpnames = lower(names); tmpnames1020 = lower({ locs1020horiz.labels }); tmpradius1020 = { locs1020horiz.radius }; [tmp indelec] = intersect_bc(tmpnames1020, tmpnames); if isempty(indelec) disp('No electrodes found for horiz. position spherical re-scaling') else disp([ num2str(length(indelec)) ' landmark electrodes found for horiz. position spherical re-scaling' ]); if strcmpi(g.coordinates, 'cart') g.hscale(2:2:2*length(indelec)+1) = [ locs1020horiz.Y ]; else g.hscale(2:2:2*length(indelec)+1) = tmpradius1020(indelec); end; end; % scan electrodes for vert. pos % ----------------------------- tmpnames1020 = lower({ locs1020vert.labels }); tmpradius1020 = { locs1020vert.radius }; [tmp indelec] = intersect_bc(tmpnames1020, tmpnames); if isempty(indelec) disp('No electrodes found for vertical position spherical re-scaling') else disp([ num2str(length(indelec)) ' landmark electrodes found for vertical spherical re-scaling' ]); g.vscale(1:2:2*length(indelec)) = tmpnames1020 (indelec); if strcmpi(g.coordinates, 'cart') g.vscale(2:2:2*length(indelec)+1) = [ locs1020vert.X ]; else g.vscale(2:2:2*length(indelec)+1) = tmpradius1020(indelec); end; end; else % uniform scaling % --------------- tmpnames = lower(names); tmpnames1020 = lower({ locs1020.labels }); tmpradius1020 = { locs1020.radius }; [tmp indelec] = intersect_bc(tmpnames1020, tmpnames); if isempty(indelec) disp('No electrodes found for uniform spherical re-scaling') else disp([ num2str(length(indelec)) ' landmark electrodes found for uniform spherical re-scaling' ]); g.scale(1:2:2*length(indelec)) = tmpnames1020 (indelec); if strcmpi(g.coordinates, 'cart') tmpabsxyz = mattocell(abs([ locs1020.X ]+j*[ locs1020.Y ])); g.scale(2:2:2*length(indelec)+1) = tmpabsxyz(indelec); else g.scale(2:2:2*length(indelec)+1) = tmpradius1020(indelec); end; end; end; if strcmpi(g.coordinates, 'sph') g.coordinates = 'pol'; % use polar coordinates for scaling end; end; % get X and Y coordinates % ----------------------- if strcmpi(g.coordinates, 'sph') | strcmpi(g.coordinates, 'pol') [X Y] = pol2cart( [ chanlocs.theta ]/180*pi, [ chanlocs.radius ]); Z = 1; if strcmpi(g.coordinates, 'sph') X = X/0.25*46; Y = Y/0.25*46; end; else X = [ chanlocs.X ]; Y = [ chanlocs.Y ]; Z = [ chanlocs.Z ]; end; % recenter % -------- if ~isempty(g.center) for index = 1:length(g.center) tmpindex = strmatch( lower(g.center{index}), lower(names), 'exact' ); if isempty(tmpindex) error(['Electrode ''' g.center{index} ''' not found for re-centering']); end; indexelec(index) = tmpindex; end; showmsg('Using electrode', 'for re-centering', g.center); centerx = mean(X(indexelec)); centery = mean(Y(indexelec)); X = X - centerx; Y = Y - centery; end; % planar rotation % --------------- if ~isempty(g.rotate) % find electrodes % --------------- clear elec; for index = 1:2:length(g.rotate) tmpindex = strmatch( lower(g.rotate{index}), lower(names), 'exact' ); if isempty(tmpindex) error(['Electrode ''' g.rotate{index} ''' not found for left-right scaling']); end; elec((index+1)/2) = tmpindex; end; vals = [ g.rotate{2:2:end} ]; % compute average scaling factor % ------------------------------ [ allangles tmp ] = cart2pol(X(elec), Y(elec)); allangles = allangles/pi*180; diffangle = allangles - vals; %diffangle2 = allangles + vals; %if abs(diffangle1) > abs(diffangle2), diffangle = diffangle2; %else diffangle = diffangle1; %end; tmpind = find(diffangle > 180); diffangle(tmpind) = diffangle(tmpind)-360; tmpind = find(diffangle < -180); diffangle(tmpind) = diffangle(tmpind)+360; anglerot = mean(diffangle); tmpcplx = (X+j*Y)*exp(-j*anglerot/180*pi); X = real(tmpcplx); Y = imag(tmpcplx); showmsg('Using electrode', ['for planar rotation (' num2str(anglerot,2) ' degrees)'], g.rotate(1:2:end)); end; % computing scaling factors % ------------------------- if ~isempty(g.scale) % find electrodes % --------------- clear elec; for index = 1:2:length(g.scale) tmpindex = strmatch( lower(g.scale{index}), lower(names), 'exact' ); if isempty(tmpindex) error(['Electrode ''' g.scale{index} ''' not found for left-right scaling']); end; elec((index+1)/2) = tmpindex; end; vals = [ g.scale{2:2:end} ]; % compute average scaling factor % ------------------------------ nonzero = find(vals > 0); hscalefact = mean(abs(Y(elec(nonzero))+j*X(elec(nonzero)))./vals(nonzero)); % *46/0.25; %/44/0.25; vscalefact = hscalefact; showmsg('Using electrode', ['for uniform spherical re-scaling (x' num2str(1/hscalefact,4) ')'], g.scale(1:2:end)); else if ~isempty(g.hscale) % find electrodes % --------------- clear elec; for index = 1:2:length(g.hscale) tmpindex = strmatch( lower(g.hscale{index}), lower(names), 'exact' ); if isempty(tmpindex) error(['Electrode ''' g.hscale{index} ''' not found for left-right scaling']); end; elec((index+1)/2) = tmpindex; end; vals = [ g.hscale{2:2:end} ]; showmsg('Using electrode', [ 'for left-right spherical re-scaling (x' num2str(1/hscalefact,4) ')'], g.hscale(1:2:end)); % compute average scaling factor % ------------------------------ hscalefact = mean(abs(Y(elec))./vals); % *46/0.25; %/44/0.25; if isempty(g.vscale) vscalefact = hscalefact; end; end; if ~isempty(g.vscale) % find electrodes % --------------- clear elec; for index = 1:2:length(g.vscale) tmpindex = strmatch( lower(g.vscale{index}), lower(names), 'exact' ); if isempty(tmpindex) error(['Electrode ''' g.vscale{index} ''' not found for rear-front scaling']); end; elec((index+1)/2) = tmpindex; end; vals = [ g.vscale{2:2:end} ]; showmsg('Using electrode', ['for rear-front spherical re-scaling (x' num2str(1/vscalefact,4) ')'], g.vscale(1:2:end)); % compute average scaling factor % ------------------------------ vscalefact = mean(abs(X(elec))./vals); % *46/0.25; %/44/0.25; if isempty(g.vscale) hscalefact = vscalefact; end; end; end; % uniform? % -------- if strcmpi(g.uniform, 'on') & ( ~isempty(g.vscale) | ~isempty(g.hscale)) disp('uniform scaling: averaging left-right and rear-front scaling factor'); hscalefact = mean([hscalefact vscalefact]); vscalefact = hscalefact; end; % scaling data % ------------ if ~isempty(g.vscale) | ~isempty(g.hscale) | ~isempty(g.scale) Y = Y/hscalefact; X = X/vscalefact; Z = Z/((hscalefact+vscalefact)/2); end; % updating structure % ------------------ if strcmpi(g.coordinates, 'sph') | strcmpi(g.coordinates, 'pol') [phi,theta] = cart2pol(Y, X); phi = phi/pi*180; if strcmpi(g.coordinates, 'pol') theta = theta/0.25*46; end; % convert to other types of coordinates % ------------------------------------- labels = names'; chanlocs = struct('labels', names, 'sph_theta_besa', mattocell(theta), ... 'sph_phi_besa', mattocell(phi), 'sph_radius', { chanlocs.sph_radius }); chanlocs = convertlocs( chanlocs, 'sphbesa2all'); else for index = 1:length(chanlocs) chanlocs(index).X = X(index); chanlocs(index).Y = Y(index); chanlocs(index).Z = Z(index); end; chanlocs = convertlocs(chanlocs, 'cart2all'); end; function showmsg(begmsg, endmsg, struct); if length(struct) <= 1 disp([ begmsg ' ''' struct{1} ''' ' endmsg]); elseif length(struct) <= 2 disp([ begmsg ' ''' struct{1} ''' and ''' struct{2} ''' ' endmsg]); elseif length(struct) <= 3 disp([ begmsg ' ''' struct{1} ''', ''' struct{2} ''' and ''' struct{3} ''' ' endmsg]); else disp([ begmsg ' ''' struct{1} ''', ''' struct{2} ''', ''' struct{3} ''' ... ' endmsg]); end;
github
ZijingMao/baselineeegtest-master
sph2topo.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/sph2topo.m
3,339
utf_8
44852faa1bc45208398680f08a50db29
% sph2topo() - Convert from a 3-column headplot file in spherical coordinates % to 3-column topoplot() locs file in polar (not cylindrical) coords. % Used for topoplot() and other 2-D topographic plotting programs. % Assumes a spherical coordinate system in which horizontal angles % have a range [-180,180] deg, with zero pointing to the right ear. % In the output polar coordinate system, zero points to the nose. % See >> help readlocs % Usage: % >> [chan_num,angle,radius] = sph2topo(input,shrink_factor,method); % % Inputs: % input = [channo,az,horiz] = chan_number, azumith (deg), horiz. angle (deg) % When az>0, horiz=0 -> right ear, 90 -> nose % When az<0, horiz=0 -> left ear, -90 -> nose % shrink_factor = arc_length shrinking factor>=1 (deprecated). % 1 -> plot edge is 90 deg azimuth {default}; % 1.5 -> plot edge is +/-135 deg azimuth See % >> help topoplot(). % method = [1|2], optional. 1 is for Besa compatibility, 2 is for % compatibility with Matlab function cart2sph(). Default is 2 % % Outputs: % channo = channel number (as in input) % angle = horizontal angle (0 -> nose; 90 -> right ear; -90 -> left ear) % radius = arc_lengrh from vertex (Note: 90 deg az -> 0.5/shrink_factor); % By topoplot() convention, radius=0.5 is the nasion-ear_canal plane. % Use topoplot() 'plotrad' to plot chans with abs(az) > 90 deg. % % Author: Scott Makeig & Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 6/12/98 % % See also: cart2topo(), topo2sph() % Copyright (C) 6/12/98 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % corrected left/right orientation mismatch, Blair Hicks 6/20/98 % changed name sph2pol() -> sph2topo() for compatibility -sm % 01-25-02 reformated help & license -ad % 01-25-02 changed computation so that it works with sph2topo -ad function [channo,angle,radius] = sph2topo(input,factor, method) chans = size(input,1); angle = zeros(chans,1); radius = zeros(chans,1); if nargin < 1 help sph2topo return end if nargin< 2 factor = 0; end if factor==0 factor = 1; end if factor < 1 help sph2topo return end if size(input,2) ~= 3 help sph2topo return end channo = input(:,1); az = input(:,2); horiz = input(:,3); if exist('method')== 1 & method == 1 radius = abs(az/180)/factor; i = find(az>=0); angle(i) = 90-horiz(i); i = find(az<0); angle(i) = -90-horiz(i); else angle = -horiz; radius = 0.5 - az/180; end;
github
ZijingMao/baselineeegtest-master
sobi.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/sobi.m
5,094
utf_8
ce6035ad7a3d7312fee7cf1a37d8e04e
% sobi() - Second Order Blind Identification (SOBI) by joint diagonalization of % correlation matrices. THIS CODE ASSUMES TEMPORALLY CORRELATED SIGNALS, % and uses correlations across times in performing the signal separation. % Thus, estimated time delayed covariance matrices must be nonsingular % for at least some time delays. % Usage: % >> winv = sobi(data); % >> [winv,act] = sobi(data,n,p); % Inputs: % data - data matrix of size [m,N] ELSE of size [m,N,t] where % m is the number of sensors, % N is the number of samples, % t is the number of trials (avoid epoch boundaries) % n - number of sources {Default: n=m} % p - number of correlation matrices to be diagonalized % {Default: min(100, N/3)} Note that for non-ideal data, % the authors strongly recommend using at least 100 time delays. % % Outputs: % winv - Matrix of size [m,n], an estimate of the *mixing* matrix. Its % columns are the component scalp maps. NOTE: This is the inverse % of the usual ICA unmixing weight matrix. Sphering (pre-whitening), % used in the algorithm, is incorporated into winv. i.e., % % >> icaweights = pinv(winv); icasphere = eye(m); % % act - matrix of dimension [n,N] an estimate of the source activities % % >> data = winv * act; % [size m,N] [size m,n] [size n,N] % >> act = pinv(winv) * data; % % Authors: A. Belouchrani and A. Cichocki (references: See function body) % Note: Adapted by Arnaud Delorme and Scott Makeig to process data epochs by % computing covariances while respecting epoch boundaries. % REFERENCES: % A. Belouchrani, K. Abed-Meraim, J.-F. Cardoso, and E. Moulines, ``Second-order % blind separation of temporally correlated sources,'' in Proc. Int. Conf. on % Digital Sig. Proc., (Cyprus), pp. 346--351, 1993. % % A. Belouchrani and K. Abed-Meraim, ``Separation aveugle au second ordre de % sources correlees,'' in Proc. Gretsi, (Juan-les-pins), % pp. 309--312, 1993. % % A. Belouchrani, and A. Cichocki, % Robust whitening procedure in blind source separation context, % Electronics Letters, Vol. 36, No. 24, 2000, pp. 2050-2053. % % A. Cichocki and S. Amari, % Adaptive Blind Signal and Image Processing, Wiley, 2003. function [H,S,D]=sobi(X,n,p), % Authors note: For non-ideal data, use at least p=100 the time-delayed covariance matrices. DEFAULT_LAGS = 100; [m,N,ntrials]=size(X); if nargin<1 | nargin > 3 help sobi elseif nargin==1, n=m; % Source detection (hum...) p=min(DEFAULT_LAGS,ceil(N/3)); % Number of time delayed correlation matrices to be diagonalized elseif nargin==2, p=min(DEFAULT_LAGS,ceil(N/3)); % Default number of correlation matrices to be diagonalized % Use < DEFAULT_LAGS delays if necessary for short data epochs end; % % Make the data zero mean % X(:,:)=X(:,:)-kron(mean(X(:,:)')',ones(1,N*ntrials)); % % Pre-whiten the data based directly on SVD % [UU,S,VV]=svd(X(:,:)',0); Q= pinv(S)*VV'; X(:,:)=Q*X(:,:); % Alternate whitening code % Rx=(X*X')/T; % if m<n, % assumes white noise % [U,D]=eig(Rx); % [puiss,k]=sort(diag(D)); % ibl= sqrt(puiss(n-m+1:n)-mean(puiss(1:n-m))); % bl = ones(m,1) ./ ibl ; % BL=diag(bl)*U(1:n,k(n-m+1:n))'; % IBL=U(1:n,k(n-m+1:n))*diag(ibl); % else % assumes no noise % IBL=sqrtm(Rx); % Q=inv(IBL); % end; % X=Q*X; % % Estimate the correlation matrices % k=1; pm=p*m; % for convenience for u=1:m:pm, k=k+1; for t = 1:ntrials if t == 1 Rxp=X(:,k:N,t)*X(:,1:N-k+1,t)'/(N-k+1)/ntrials; else Rxp=Rxp+X(:,k:N,t)*X(:,1:N-k+1,t)'/(N-k+1)/ntrials; end; end; M(:,u:u+m-1)=norm(Rxp,'fro')*Rxp; % Frobenius norm = end; % sqrt(sum(diag(Rxp'*Rxp))) % % Perform joint diagonalization % epsil=1/sqrt(N)/100; encore=1; V=eye(m); step_n=0; while encore, encore=0; for p=1:m-1, for q=p+1:m, % Perform Givens rotation g=[ M(p,p:m:pm)-M(q,q:m:pm) ; M(p,q:m:pm)+M(q,p:m:pm) ; i*(M(q,p:m:pm)-M(p,q:m:pm)) ]; [vcp,D] = eig(real(g*g')); [la,K]=sort(diag(D)); angles=vcp(:,K(3)); angles=sign(angles(1))*angles; c=sqrt(0.5+angles(1)/2); sr=0.5*(angles(2)-j*angles(3))/c; sc=conj(sr); oui = abs(sr)>epsil ; encore=encore | oui ; if oui , % Update the M and V matrices colp=M(:,p:m:pm); colq=M(:,q:m:pm); M(:,p:m:pm)=c*colp+sr*colq; M(:,q:m:pm)=c*colq-sc*colp; rowp=M(p,:); rowq=M(q,:); M(p,:)=c*rowp+sc*rowq; M(q,:)=c*rowq-sr*rowp; temp=V(:,p); V(:,p)=c*V(:,p)+sr*V(:,q); V(:,q)=c*V(:,q)-sc*temp; end%% if end%% q loop end%% p loop step_n=step_n+1; fprintf('%d step\n',step_n); end%% while % % Estimate the mixing matrix % H = pinv(Q)*V; % % Estimate the source activities % if nargout>1 S=V'*X(:,:); % estimated source activities end
github
ZijingMao/baselineeegtest-master
runica_ml.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/runica_ml.m
43,480
utf_8
62bb523264cef06666a2d818dea42918
% runica() - Perform Independent Component Analysis (ICA) decomposition % of input data using the logistic infomax ICA algorithm of % Bell & Sejnowski (1995) with the natural gradient feature % of Amari, Cichocki & Yang, or optionally the extended-ICA % algorithm of Lee, Girolami & Sejnowski, with optional PCA % dimension reduction. Annealing based on weight changes is % used to automate the separation process. % Usage: % >> [weights,sphere] = runica(data); % train using defaults % else % >> [weights,sphere,compvars,bias,signs,lrates,activations] ... % = runica(data,'Key1',Value1',...); % Input: % data = input data (chans,frames*epochs). % Note that if data consists of multiple discontinuous epochs, % each epoch should be separately baseline-zero'd using % >> data = rmbase(data,frames,basevector); % % Optional keywords [argument]: % 'extended' = [N] perform tanh() "extended-ICA" with sign estimation % N training blocks. If N > 0, automatically estimate the % number of sub-Gaussian sources. If N < 0, fix number of % sub-Gaussian comps to -N [faster than N>0] (default|0 -> off) % 'pca' = [N] decompose a principal component (default -> 0=off) % subspace of the data. Value is the number of PCs to retain. % 'ncomps' = [N] number of ICA components to compute (default -> chans or 'pca' arg) % using rectangular ICA decomposition % 'sphering' = ['on'/'off'] flag sphering of data (default -> 'on') % 'weights' = [W] initial weight matrix (default -> eye()) % (Note: if 'sphering' 'off', default -> spher()) % 'lrate' = [rate] initial ICA learning rate (<< 1) (default -> heuristic) % 'block' = [N] ICA block size (<< datalength) (default -> heuristic) % 'anneal' = annealing constant (0,1] (defaults -> 0.90, or 0.98, extended) % controls speed of convergence % 'annealdeg' = [N] degrees weight change for annealing (default -> 70) % 'stop' = [f] stop training when weight-change < this (default -> 1e-6 % if less than 33 channel and 1E-7 otherwise) % 'maxsteps' = [N] max number of ICA training steps (default -> 512) % 'bias' = ['on'/'off'] perform bias adjustment (default -> 'on') % 'momentum' = [0<f<1] training momentum (default -> 0) % 'specgram' = [srate loHz hiHz frames winframes] decompose a complex time/frequency % transform of the data (Note: winframes must divide frames) % (defaults [srate 0 srate/2 size(data,2) size(data,2)]) % 'posact' = make all component activations net-positive(default 'on'} % 'verbose' = give ascii messages ('on'/'off') (default -> 'on') % % Outputs: [Note: RO means output in reverse order of projected mean variance % unless starting weight matrix passed ('weights' above)] % weights = ICA weight matrix (comps,chans) [RO] % sphere = data sphering matrix (chans,chans) = spher(data) % Note that unmixing_matrix = weights*sphere {if sphering off -> eye(chans)} % compvars = back-projected component variances [RO] % bias = vector of final (ncomps) online bias [RO] (default = zeros()) % signs = extended-ICA signs for components [RO] (default = ones()) % [ -1 = sub-Gaussian; 1 = super-Gaussian] % lrates = vector of learning rates used at each training step [RO] % activations = activation time courses of the output components (ncomps,frames*epochs) % % Authors: Scott Makeig with contributions from Tony Bell, Te-Won Lee, % Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky, Delorme Arnaud, % CNL/The Salk Institute, La Jolla, 1996- % Uses: posact() % Reference (please cite): % % Makeig, S., Bell, A.J., Jung, T-P and Sejnowski, T.J., % "Independent component analysis of electroencephalographic data," % In: D. Touretzky, M. Mozer and M. Hasselmo (Eds). Advances in Neural % Information Processing Systems 8:145-151, MIT Press, Cambridge, MA (1996). % % Toolbox Citation: % % Makeig, Scott et al. "EEGLAB: ICA Toolbox for Psychophysiological Research". % WWW Site, Swartz Center for Computational Neuroscience, Institute of Neural % Computation, University of San Diego California % <www.sccn.ucsd.edu/eeglab/>, 2000. [World Wide Web Publication]. % % For more information: % http://www.sccn.ucsd.edu/eeglab/icafaq.html - FAQ on ICA/EEG % http://www.sccn.ucsd.edu/eeglab/icabib.html - mss. on ICA & biosignals % http://www.cnl.salk.edu/~tony/ica.html - math. mss. on ICA % Copyright (C) 1996 Scott Makeig et al, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %%%%%%%%%%%%%%%%%%%%%%%%%%% Edit history %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % runica() - by Scott Makeig with contributions from Tony Bell, Te-Won Lee % Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky et al. % CNL / Salk Institute 1996-00 % 04-30-96 built from icatest.m and ~jung/.../wtwpwica.m -sm % 07-28-97 new runica(), adds bias (default on), momentum (default off), % extended-ICA (Lee & Sejnowski, 1997), cumulative angledelta % (until lrate drops), keywords, signcount for speeding extended-ICA % 10-07-97 put acos() outside verbose loop; verbose 'off' wasn't stopping -sm % 11-11-97 adjusted help msg -sm % 11-30-97 return eye(chans) if sphering 'off' or 'none' (undocumented option) -sm % 02-27-98 use pinv() instead of inv() to rank order comps if ncomps < chans -sm % 04-28-98 added 'posact' and 'pca' flags -sm % 07-16-98 reduced length of randperm() for kurtosis subset calc. -se & sm % 07-19-98 fixed typo in weights def. above -tl & sm % 12-21-99 added 'specgram' option suggested by Michael Zibulevsky, UNM -sm % 12-22-99 fixed rand() sizing inefficiency on suggestion of Mike Spratling, UK -sm % 01-11-00 fixed rand() sizing bug on suggestion of Jack Foucher, Strasbourg -sm % 12-18-00 test for existence of Sig Proc Tlbx function 'specgram'; improve % 'specgram' option arguments -sm % 01-25-02 reformated help & license -ad % 01-25-02 lowered default lrate and block -ad % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [weights,sphere,meanvar,bias,signs,lrates,activations,y,loglik,wsave] = runica(data,p1,v1,p2,v2,p3,v3,p4,v4,p5,v5,p6,v6,p7,v7,p8,v8,p9,v9,p10,v10,p11,v11,p12,v12,p13,v13,p14,v14) if nargin < 1 help runica return end [chans frames] = size(data); % determine the data size urchans = chans; % remember original data channels datalength = frames; if chans<2 fprintf('\nrunica() - data size (%d,%d) too small.\n\n', chans,frames); return end % %%%%%%%%%%%%%%%%%%%%%% Declare defaults used below %%%%%%%%%%%%%%%%%%%%%%%% % MAX_WEIGHT = 1e8; % guess that weights larger than this have blown up DEFAULT_STOP = 1e-6; % stop training if weight changes below this DEFAULT_ANNEALDEG = 60; % when angle change reaches this value, DEFAULT_ANNEALSTEP = 0.95; % anneal by multiplying lrate by this DEFAULT_EXTANNEAL = 0.95; % or this if extended-ICA DEFAULT_MAXSTEPS = 500; % stop training after this many steps DEFAULT_MOMENTUM = 0.0; % default momentum weight DEFAULT_BLOWUP = 1000000000.0; % = learning rate has 'blown up' DEFAULT_BLOWUP_FAC = 0.8; % when lrate 'blows up,' anneal by this fac DEFAULT_RESTART_FAC = 0.9; % if weights blowup, restart with lrate % lower by this factor MIN_LRATE = 0.0001; % if weight blowups make lrate < this, quit MAX_LRATE = 0.1; % guard against uselessly high learning rate DEFAULT_LRATE = 0.00065/log(chans); % heuristic default - may need adjustment % for large or tiny data sets! % DEFAULT_BLOCK = floor(sqrt(frames/4)); % heuristic default DEFAULT_BLOCK = ceil(min(5*log(frames),0.3*frames)); % heuristic %DEFAULT_BLOCK = 10000; % heuristic % - may need adjustment! % Extended-ICA option: DEFAULT_EXTENDED = 1; % default off DEFAULT_EXTBLOCKS = 1; % number of blocks per kurtosis calculation DEFAULT_NSUB = 0; % initial default number of assumed sub-Gaussians % for extended-ICA DEFAULT_EXTMOMENTUM = 0.5; % momentum term for computing extended-ICA kurtosis MAX_KURTSIZE = 6000; % max points to use in kurtosis calculation MIN_KURTSIZE = 2000; % minimum good kurtosis size (flag warning) SIGNCOUNT_THRESHOLD = 25; % raise extblocks when sign vector unchanged % after this many steps SIGNCOUNT_STEP = 2; % extblocks increment factor DEFAULT_SPHEREFLAG = 'on'; % use the sphere matrix as the default % starting weight matrix DEFAULT_PCAFLAG = 'off'; % don't use PCA reduction DEFAULT_POSACTFLAG = 'on'; % use posact() DEFAULT_VERBOSE = 1; % write ascii info to calling screen DEFAULT_BIASFLAG = 0; % default to using bias in the ICA update rule % %%%%%%%%%%%%%%%%%%%%%%% Set up keyword default values %%%%%%%%%%%%%%%%%%%%%%%%% % if nargout < 2, fprintf('runica() - needs at least two output arguments.\n'); return end epochs = 1; % do not care how many epochs in data pcaflag = DEFAULT_PCAFLAG; sphering = DEFAULT_SPHEREFLAG; % default flags posactflag = DEFAULT_POSACTFLAG; verbose = DEFAULT_VERBOSE; block = DEFAULT_BLOCK; % heuristic default - may need adjustment! lrate = DEFAULT_LRATE; annealdeg = DEFAULT_ANNEALDEG; annealstep = 0; % defaults declared below nochange = NaN; momentum = DEFAULT_MOMENTUM; maxsteps = DEFAULT_MAXSTEPS; weights = 0; % defaults defined below ncomps = chans; biasflag = DEFAULT_BIASFLAG; extended = DEFAULT_EXTENDED; extblocks = DEFAULT_EXTBLOCKS; kurtsize = MAX_KURTSIZE; signsbias = 0.02; % bias towards super-Gaussian components extmomentum= DEFAULT_EXTMOMENTUM; % exp. average the kurtosis estimates nsub = DEFAULT_NSUB; wts_blowup = 0; % flag =1 when weights too large wts_passed = 0; % flag weights passed as argument % %%%%%%%%%% Collect keywords and values from argument list %%%%%%%%%%%%%%% % if (nargin> 1 & rem(nargin,2) == 0) fprintf('runica(): Even number of input arguments???') return end for i = 3:2:nargin % for each Keyword Keyword = eval(['p',int2str((i-3)/2 +1)]); Value = eval(['v',int2str((i-3)/2 +1)]); if ~isstr(Keyword) fprintf('runica(): keywords must be strings') return end Keyword = lower(Keyword); % convert upper or mixed case to lower if strcmp(Keyword,'weights') | strcmp(Keyword,'weight') if isstr(Value) fprintf(... 'runica(): weights value must be a weight matrix or sphere') return else weights = Value; wts_passed =1; end elseif strcmp(Keyword,'ncomps') if isstr(Value) fprintf('runica(): ncomps value must be an integer') return end if ncomps < urchans & ncomps ~= Value fprintf('runica(): Use either PCA or ICA dimension reduction'); return end ncomps = Value; if ~ncomps, ncomps = chans; end elseif strcmp(Keyword,'pca') if ncomps < urchans & ncomps ~= Value fprintf('runica(): Use either PCA or ICA dimension reduction'); return end if isstr(Value) fprintf(... 'runica(): pca value should be the number of principal components to retain') return end pcaflag = 'on'; ncomps = Value; if ncomps > chans | ncomps < 1, fprintf('runica(): pca value must be in range [1,%d]\n',chans) return end chans = ncomps; elseif strcmp(Keyword,'posact') if ~isstr(Value) fprintf('runica(): posact value must be on or off') return else Value = lower(Value); if ~strcmp(Value,'on') & ~strcmp(Value,'off'), fprintf('runica(): posact value must be on or off') return end posactflag = Value; end elseif strcmp(Keyword,'lrate') if isstr(Value) fprintf('runica(): lrate value must be a number') return end lrate = Value; if lrate>MAX_LRATE | lrate <0, fprintf('runica(): lrate value is out of bounds'); return end if ~lrate, lrate = DEFAULT_LRATE; end elseif strcmp(Keyword,'block') | strcmp(Keyword,'blocksize') if isstr(Value) fprintf('runica(): block size value must be a number') return end block = floor(Value); if ~block, block = DEFAULT_BLOCK; end elseif strcmp(Keyword,'stop') | strcmp(Keyword,'nochange') ... | strcmp(Keyword,'stopping') if isstr(Value) fprintf('runica(): stop wchange value must be a number') return end nochange = Value; elseif strcmp(Keyword,'maxsteps') | strcmp(Keyword,'steps') if isstr(Value) fprintf('runica(): maxsteps value must be an integer') return end maxsteps = Value; if ~maxsteps, maxsteps = DEFAULT_MAXSTEPS; end if maxsteps < 0 fprintf('runica(): maxsteps value (%d) must be a positive integer',maxsteps) return end elseif strcmp(Keyword,'anneal') | strcmp(Keyword,'annealstep') if isstr(Value) fprintf('runica(): anneal step value (%2.4f) must be a number (0,1)',Value) return end annealstep = Value; if annealstep <=0 | annealstep > 1, fprintf('runica(): anneal step value (%2.4f) must be (0,1]',annealstep) return end elseif strcmp(Keyword,'annealdeg') | strcmp(Keyword,'degrees') if isstr(Value) fprintf('runica(): annealdeg value must be a number') return end annealdeg = Value; if ~annealdeg, annealdeg = DEFAULT_ANNEALDEG; elseif annealdeg > 180 | annealdeg < 0 fprintf('runica(): annealdeg (%3.1f) is out of bounds [0,180]',... annealdeg); return end elseif strcmp(Keyword,'momentum') if isstr(Value) fprintf('runica(): momentum value must be a number') return end momentum = Value; if momentum > 1.0 | momentum < 0 fprintf('runica(): momentum value is out of bounds [0,1]') return end elseif strcmp(Keyword,'sphering') | strcmp(Keyword,'sphereing') ... | strcmp(Keyword,'sphere') if ~isstr(Value) fprintf('runica(): sphering value must be on, off, or none') return else Value = lower(Value); if ~strcmp(Value,'on') & ~strcmp(Value,'off') & ~strcmp(Value,'none'), fprintf('runica(): sphering value must be on or off') return end sphering = Value; end elseif strcmp(Keyword,'bias') if ~isstr(Value) fprintf('runica(): bias value must be on or off') return else Value = lower(Value); if strcmp(Value,'on') biasflag = 1; elseif strcmp(Value,'off'), biasflag = 0; else fprintf('runica(): bias value must be on or off') return end end elseif strcmp(Keyword,'specgram') | strcmp(Keyword,'spec') if ~exist('specgram') < 2 % if ~exist or defined workspace variable fprintf(... 'runica(): MATLAB Sig. Proc. Toolbox function "specgram" not found.\n') return end if isstr(Value) fprintf('runica(): specgram argument must be a vector') return end srate = Value(1); if (srate < 0) fprintf('runica(): specgram srate (%4.1f) must be >=0',srate) return end if length(Value)>1 loHz = Value(2); if (loHz < 0 | loHz > srate/2) fprintf('runica(): specgram loHz must be >=0 and <= srate/2 (%4.1f)',srate/2) return end else loHz = 0; % default end if length(Value)>2 hiHz = Value(3); if (hiHz < loHz | hiHz > srate/2) fprintf('runica(): specgram hiHz must be >=loHz (%4.1f) and <= srate/2 (%4.1f)',loHz,srate/2) return end else hiHz = srate/2; % default end if length(Value)>3 Hzframes = Value(5); if (Hzframes<0 | Hzframes > size(data,2)) fprintf('runica(): specgram frames must be >=0 and <= data length (%d)',size(data,2)) return end else Hzframes = size(data,2); % default end if length(Value)>4 Hzwinlen = Value(4); if rem(Hzframes,Hzwinlen) % if winlen doesn't divide frames fprintf('runica(): specgram Hzinc must divide frames (%d)',Hzframes) return end else Hzwinlen = Hzframes; % default end Specgramflag = 1; % set flag to perform specgram() elseif strcmp(Keyword,'extended') | strcmp(Keyword,'extend') if isstr(Value) fprintf('runica(): extended value must be an integer (+/-)') return else extended = 1; % turn on extended-ICA extblocks = fix(Value); % number of blocks per kurt() compute if extblocks < 0 nsub = -1*fix(extblocks); % fix this many sub-Gauss comps elseif ~extblocks, extended = 0; % turn extended-ICA off elseif kurtsize>frames, % length of kurtosis calculation kurtsize = frames; if kurtsize < MIN_KURTSIZE fprintf(... 'runica() warning: kurtosis values inexact for << %d points.\n',... MIN_KURTSIZE); end end end elseif strcmp(Keyword,'verbose') if ~isstr(Value) fprintf('runica(): verbose flag value must be on or off') return elseif strcmp(Value,'on'), verbose = 1; elseif strcmp(Value,'off'), verbose = 0; else fprintf('runica(): verbose flag value must be on or off') return end else fprintf('runica(): unknown flag') return end end % %%%%%%%%%%%%%%%%%%%%%%%% Initialize weights, etc. %%%%%%%%%%%%%%%%%%%%%%%% % if ~annealstep, if ~extended, annealstep = DEFAULT_ANNEALSTEP; % defaults defined above else annealstep = DEFAULT_EXTANNEAL; % defaults defined above end end % else use annealstep from commandline if ~annealdeg, annealdeg = DEFAULT_ANNEALDEG - momentum*90; % heuristic if annealdeg < 0, annealdeg = 0; end end if ncomps > chans | ncomps < 1 fprintf('runica(): number of components must be 1 to %d.\n',chans); return end if weights ~= 0, % initialize weights % starting weights are being passed to runica() from the commandline if verbose, fprintf('Using starting weight matrix named in argument list ...\n') end if chans>ncomps & weights ~=0, [r,c]=size(weights); if r~=ncomps | c~=chans, fprintf(... 'runica(): weight matrix must have %d rows, %d columns.\n', ... chans,ncomps); return; end end end; % %%%%%%%%%%%%%%%%%%%%% Check keyword values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if frames<chans, fprintf('runica(): data length (%d) < data channels (%d)!\n',frames,chans) return elseif block < 1, fprintf('runica(): block size %d too small!\n',block) return elseif block > frames, fprintf('runica(): block size exceeds data length!\n'); return elseif floor(epochs) ~= epochs, fprintf('runica(): data length is not a multiple of the epoch length!\n'); return elseif nsub > ncomps fprintf('runica(): there can be at most %d sub-Gaussian components!\n',ncomps); return end; % % adjust nochange if necessary % if isnan(nochange) if ncomps > 32 nochange = 1E-7; nochangeupdated = 1; % for fprinting purposes else nochangeupdated = 1; % for fprinting purposes nochange = DEFAULT_STOP; end; else nochangeupdated = 0; end; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Process the data %%%%%%%%%%%%%%%%%%%%%%%%%% % if verbose, fprintf( ... '\nInput data size [%d,%d] = %d channels, %d frames/n', ... chans,frames,chans,frames); if strcmp(pcaflag,'on') fprintf('After PCA dimension reduction,\n finding '); else fprintf('Finding '); end if ~extended fprintf('%d ICA components using logistic ICA.\n',ncomps); else % if extended fprintf('%d ICA components using extended ICA.\n',ncomps); if extblocks > 0 fprintf(... 'Kurtosis will be calculated initially every %d blocks using %d data points.\n',... extblocks, kurtsize); else fprintf(... 'Kurtosis will not be calculated. Exactly %d sub-Gaussian components assumed.\n',... nsub); end end fprintf('Decomposing %d frames per ICA weight ((%d)^2 = %d weights, %d frames)\n',... floor(frames/ncomps.^2),ncomps.^2,frames); fprintf('Initial learning rate will be %g, block size %d.\n',... lrate,block); if momentum>0, fprintf('Momentum will be %g.\n',momentum); end fprintf( ... 'Learning rate will be multiplied by %g whenever angledelta >= %g deg.\n', ... annealstep,annealdeg); if nochangeupdated fprintf('More than 32 channels: default stopping weight change 1E-7\n'); end; fprintf('Training will end when wchange < %g or after %d steps.\n', ... nochange,maxsteps); if biasflag, fprintf('Online bias adjustment will be used.\n'); else fprintf('Online bias adjustment will not be used.\n'); end end % %%%%%%%%%%%%%%%%%%%%%%%%% Remove overall row means %%%%%%%%%%%%%%%%%%%%%%%% % if verbose, fprintf('Removing mean of each channel ...\n'); end data = data - mean(data')'*ones(1,frames); % subtract row means if verbose, fprintf('Final training data range: %g to %g\n', ... min(min(data)),max(max(data))); end % %%%%%%%%%%%%%%%%%%% Perform PCA reduction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmp(pcaflag,'on') fprintf('Reducing the data to %d principal dimensions...\n',ncomps); [eigenvectors,eigenvalues,data] = pcsquash(data,ncomps); % make data its projection onto the ncomps-dim principal subspace end % %%%%%%%%%%%%%%%%%%% Perform specgram transformation %%%%%%%%%%%%%%%%%%%%%%% % if exist('Specgramflag') == 1 % [P F T] = SPECGRAM(A,NFFT,Fs,WINDOW,NOVERLAP) % MATLAB Sig Proc Toolbox % Hzwinlen = fix(srate/Hzinc); % CHANGED FROM THIS 12/18/00 -sm Hzfftlen = 2^(ceil(log(Hzwinlen)/log(2))); % make FFT length next higher 2^k Hzoverlap = 0; % use sequential windows % % Get freqs and times from 1st channel analysis % [tmp,freqs,tms] = specgram(data(1,:),Hzfftlen,srate,Hzwinlen,Hzoverlap); fs = find(freqs>=loHz & freqs <= hiHz); if isempty(fs) fprintf('runica(): specified frequency range too narrow!\n'); return end; specdata = reshape(tmp(fs,:),1,length(fs)*size(tmp,2)); specdata = [real(specdata) imag(specdata)]; % fprintf(' size(fs) = %d,%d\n',size(fs,1),size(fs,2)); % fprintf(' size(tmp) = %d,%d\n',size(tmp,1),size(tmp,2)); % % Loop through remaining channels % for ch=2:chans [tmp] = specgram(data(ch,:),Hzwinlen,srate,Hzwinlen,Hzoverlap); tmp = reshape((tmp(fs,:)),1,length(fs)*size(tmp,2)); specdata = [specdata;[real(tmp) imag(tmp)]]; % channels are rows end % % Print specgram confirmation and details % fprintf(... 'Converted data to %d channels by %d=2*%dx%d points spectrogram data.\n',... chans,2*length(fs)*length(tms),length(fs),length(tms)); if length(fs) > 1 fprintf(... ' Low Hz %g, high Hz %g, Hz incr %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),freqs(fs(2))-freqs(fs(1)),Hzwinlen); else fprintf(... ' Low Hz %g, high Hz %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),Hzwinlen); end % % Replace data with specdata % data = specdata; datalength=size(data,2); end % %%%%%%%%%%%%%%%%%%% Perform sphering %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmp(sphering,'on'), %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if verbose, fprintf('Computing the sphering matrix...\n'); end sphere = 2.0*inv(sqrtm(cov(data'))); % find the "sphering" matrix = spher() if ~weights, if verbose, fprintf('Starting weights are the identity matrix ...\n'); end weights = eye(ncomps,chans); % begin with the identity matrix else % weights given on commandline if verbose, fprintf('Using starting weights named on commandline ...\n'); end end if verbose, fprintf('Sphering the data ...\n'); end data = sphere*data; % actually decorrelate the electrode signals elseif strcmp(sphering,'off') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~weights if verbose, fprintf('Using the sphering matrix as the starting weight matrix ...\n'); fprintf('Returning the identity matrix in variable "sphere" ...\n'); end sphere = 2.0*inv(sqrtm(cov(data'))); % find the "sphering" matrix = spher() weights = eye(ncomps,chans)*sphere; % begin with the identity matrix sphere = eye(chans); % return the identity matrix else % weights ~= 0 if verbose, fprintf('Using starting weights named on commandline ...\n'); fprintf('Returning the identity matrix in variable "sphere" ...\n'); end sphere = eye(chans); % return the identity matrix end elseif strcmp(sphering,'none') sphere = eye(chans); % return the identity matrix if ~weights if verbose, fprintf('Starting weights are the identity matrix ...\n'); fprintf('Returning the identity matrix in variable "sphere" ...\n'); end weights = eye(ncomps,chans); % begin with the identity matrix else % weights ~= 0 if verbose, fprintf('Using starting weights named on commandline ...\n'); fprintf('Returning the identity matrix in variable "sphere" ...\n'); end end sphere = eye(chans,chans); if verbose, fprintf('Returned variable "sphere" will be the identity matrix.\n'); end end % %%%%%%%%%%%%%%%%%%%%%%%% Initialize ICA training %%%%%%%%%%%%%%%%%%%%%%%%% % lastt=fix((datalength/block-1)*block+1); BI=block*eye(ncomps,ncomps); delta=zeros(1,chans*ncomps); changes = []; degconst = 180./pi; startweights = weights; prevweights = startweights; oldweights = startweights; prevwtchange = zeros(chans,ncomps); oldwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); onesrow = ones(1,block); bias = zeros(ncomps,1); signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1 for k=1:nsub signs(k) = -1; end if extended & extblocks < 0 & verbose, fprintf('Fixed extended-ICA sign assignments: '); for k=1:ncomps fprintf('%d ',signs(k)); end; fprintf('\n'); end signs = diag(signs); % make a diagonal matrix oldsigns = zeros(size(signs));; signcount = 0; % counter for same-signs signcounts = []; urextblocks = extblocks; % original value, for resets old_kk = zeros(1,ncomps); % for kurtosis momemtum % %%%%%%%% ICA training loop using the logistic sigmoid %%%%%%%%%%%%%%%%%%% % if verbose, fprintf('Beginning ICA training ...'); if extended, fprintf(' first training step may be slow ...\n'); else fprintf('\n'); end end step=0; laststep=0; blockno = 1; % running block counter for kurtosis interrupts logstep = 1; % iterator over log likelihood record rand('state',sum(100*clock)); % set the random number generator state to cost_step = 1; % record cost every cost_step iterations % a position dependent on the system clock while step < maxsteps, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% permute=randperm(datalength); % shuffle data order at each step if mod(step,cost_step) == 0 & extended loglik(logstep) = 0; end for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%% pause(0); if ~isempty(get(0, 'currentfigure')) & strcmp(get(gcf, 'tag'), 'stop') close; error('USER ABORT'); end; if biasflag u=weights*data(:,permute(t:t+block-1)) + bias*onesrow; else u=weights*data(:,permute(t:t+block-1)); end if ~extended %%%%%%%%%%%%%%%%%%% Logistic ICA weight update %%%%%%%%%%%%%%%%%%% y=1./(1+exp(-u)); % weights = weights + lrate*(BI+(1-2*y)*u')*weights; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% else % Tanh extended-ICA weight update %%%%%%%%%%%%%%%%%%% Extended-ICA weight update %%%%%%%%%%%%%%%%%%% y=tanh(u); % weights = weights + lrate*(BI-signs*y*u'-u*u')*weights; % %%%%%%%%% Calculate log likelihood given our model %%%%%%%%% if mod(step,cost_step) == 0 subgcomp = find(diag(signs) == -1); supergcomp = find(diag(signs) == 1); if length(subgcomp) > 0 if biasflag loglik(logstep) = loglik(logstep) + (1/frames)*sum(sum(log(exp(-(1/2)*(u(subgcomp,:)-bias*ones(1,length(subgcomp))-1).^2) + exp(-(1/2)*(u(subgcomp,:)-bias*ones(1,length(subgcomp))+1).^2)))); else loglik(logstep) = loglik(logstep) + (1/frames)*sum(sum(log(exp(-(1/2)*(u(subgcomp,:)-1).^2) + exp(-(1/2)*(u(subgcomp,:)+1).^2)))); end end if length(supergcomp) > 0 if biasflag loglik(logstep) = loglik(logstep) + (1/frames)*sum(sum(-0.5*(u(supergcomp,:)-bias*ones(1,length(supergcomp))).^2 - 2*log(cosh(u(supergcomp,:)-bias*ones(1,length(supergcomp)))))); else loglik(logstep) = loglik(logstep) + (1/frames)*sum(sum(-0.5*u(supergcomp,:).^2 - 2*log(cosh(u(supergcomp,:))))); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end wsave{step+1} = weights; if biasflag if ~extended %%%%%%%%%%%%%%%%%%%%%%%% Logistic ICA bias %%%%%%%%%%%%%%%%%%%%%%% bias = bias + lrate*sum((1-2*y)')'; % for logistic nonlin. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% else % extended %%%%%%%%%%%%%%%%%%% Extended-ICA bias %%%%%%%%%%%%%%%%%%%%%%%%%%%% bias = bias + lrate*sum((-2*y)')'; % for tanh() nonlin. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end end if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%% weights = weights + momentum*prevwtchange; prevwtchange = weights-prevweights; prevweights = weights; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if max(max(abs(weights))) > MAX_WEIGHT wts_blowup = 1; change = nochange; end if extended & ~wts_blowup % %%%%%%%%%%% Extended-ICA kurtosis estimation %%%%%%%%%%%%%%%%%%%%% % if extblocks > 0 & rem(blockno,extblocks) == 0, % recompute signs vector using kurtosis if kurtsize < frames % 12-22-99 rand() size suggestion by M. Spratling rp = fix(rand(1,kurtsize)*datalength); % pick random subset % Accout for the possibility of a 0 generation by rand ou = find(rp == 0); while ~isempty(ou) % 1-11-00 suggestion by J. Foucher rp(ou) = fix(rand(1,length(ou))*datalength); ou = find(rp == 0); end partact=weights*data(:,rp(1:kurtsize)); else % for small data sets, partact=weights*data; % use whole data end m2=mean(partact'.^2).^2; m4= mean(partact'.^4); kk= (m4./m2)-3.0; % kurtosis estimates if extmomentum kk = extmomentum*old_kk + (1.0-extmomentum)*kk; % use momentum old_kk = kk; end signs=diag(sign(kk+signsbias)); % pick component signs if signs == oldsigns, signcount = signcount+1; else signcount = 0; end oldsigns = signs; signcounts = [signcounts signcount]; if signcount >= SIGNCOUNT_THRESHOLD, extblocks = fix(extblocks * SIGNCOUNT_STEP);% make kurt() estimation signcount = 0; % less frequent if sign end % is not changing end % extblocks > 0 & . . . end % if extended %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% blockno = blockno + 1; if wts_blowup break end end % training block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if mod(step,cost_step) == 0 & extended loglik(logstep) = loglik(logstep) + log(abs(det(weights))); logstep = logstep + 1; end if ~wts_blowup oldwtchange = weights-oldweights; step=step+1; % %%%%%%% Compute and print weight and update angle changes %%%%%%%%% % lrates(1,step) = lrate; angledelta=0.; delta=reshape(oldwtchange,1,chans*ncomps); change=delta*delta'; end % %%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%% % if wts_blowup | isnan(change)|isinf(change), % if weights blow up, fprintf(''); step = 0; % start again change = nochange; wts_blowup = 0; % re-initialize variables blockno = 1; lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate weights = startweights; % and original weight matrix oldweights = startweights; change = nochange; oldwtchange = zeros(chans,ncomps); delta=zeros(1,chans*ncomps); olddelta = delta; extblocks = urextblocks; prevweights = startweights; prevwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); bias = zeros(ncomps,1); if extended signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1 for k=1:nsub signs(k) = -1; end signs = diag(signs); % make a diagonal matrix oldsigns = zeros(size(signs));; end if lrate> MIN_LRATE r = rank(data); if r<ncomps fprintf('Data has rank %d. Cannot compute %d components.\n',... r,ncomps); return else fprintf(... 'Lowering learning rate to %g and starting again.\n',lrate); end else fprintf( ... 'runica(): QUITTING - weight matrix may not be invertible!\n'); return; end else % if weights in bounds % %%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%% % if step> 2 angledelta=acos((delta*olddelta')/sqrt(change*oldchange)); end if verbose, places = -floor(log10(nochange)); if step > 2, if ~extended, ps = sprintf('step %d - lrate %5f, wchange %%%d.%df, angledelta %4.1f deg\n', ... step, lrate, places+1,places, degconst*angledelta); else ps = sprintf('step %d - lrate %5f, wchange %%%d.%df, angledelta %4.1f deg, %d subgauss\n',... step, lrate, degconst*angledelta,... places+1,places, (ncomps-sum(diag(signs)))/2); end elseif ~extended ps = sprintf('step %d - lrate %5f, wchange %%%d.%df\n',... step, lrate, places+1,places ); else ps = sprintf('step %5d - lrate %5f, wchange %%%d.%df, %d subgauss\n',... step, lrate, places+1,places, (ncomps-sum(diag(signs)))/2); end % step > 2 fprintf('step %d - lrate %5f, wchange %8.8f, angledelta %5.1f deg, loglik %6.2f, nsub = %d\n', ... step, lrate, change, degconst*angledelta, loglik(step), sum(diag(signs)==-1)); % fprintf(ps,change); % <---- BUG !!!! end; % if verbose % %%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % changes = [changes change]; oldweights = weights; % %%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if degconst*angledelta > annealdeg, lrate = lrate*annealstep; % anneal learning rate olddelta = delta; % accumulate angledelta until oldchange = change; % annealdeg is reached elseif step == 1 % on first step only olddelta = delta; % initialize oldchange = change; end % %%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if step >2 & change < nochange, % apply stopping rule laststep=step; step=maxsteps; % stop when weights stabilize elseif change > DEFAULT_BLOWUP, % if weights blow up, lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying end; % with a smaller learning rate end; % end if weights in bounds end; % end training %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~laststep laststep = step; end; lrates = lrates(1,1:laststep); % truncate lrate history vector % %%%%%%%%%%%%%% Orient components towards max positive activation %%%%%% % if strcmp(posactflag,'on') [activations,winvout,weights] = posact(data,weights); % changes signs of activations and weights to make activations % net rms-positive else activations = weights*data; end % %%%%%%%%%%%%%% If pcaflag, compose PCA and ICA matrices %%%%%%%%%%%%%%% % if strcmp(pcaflag,'on') fprintf('Composing the eigenvector, weights, and sphere matrices\n'); fprintf(' into a single rectangular weights matrix; sphere=eye(%d)\n'... ,chans); weights= weights*sphere*eigenvectors(:,1:ncomps)'; sphere = eye(urchans); end % %%%%%% Sort components in descending order of max projected variance %%%% % if verbose, fprintf(... 'Sorting components in descending order of mean projected variance ...\n'); end % %%%%%%%%%%%%%%%%%%%% Find mean variances %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % meanvar = zeros(ncomps,1); % size of the projections if ncomps == urchans % if weights are square . . . winv = inv(weights*sphere); else fprintf('Using pseudo-inverse of weight matrix to rank order component projections.\n'); winv = pinv(weights*sphere); end for s=1:ncomps if verbose, fprintf('%d ',s); % construct single-component data matrix end % project to scalp, then add row means compproj = winv(:,s)*activations(s,:); meanvar(s) = mean(sum(compproj.*compproj)/(size(compproj,1)-1)); % compute mean variance end % at all scalp channels if verbose, fprintf('\n'); end % %%%%%%%%%%%%%% Sort components by mean variance %%%%%%%%%%%%%%%%%%%%%%%% % [sortvar, windex] = sort(meanvar); windex = windex(ncomps:-1:1); % order large to small meanvar = meanvar(windex); % %%%%%%%%%%%%%%%%%%%%% Filter data using final weights %%%%%%%%%%%%%%%%%% % if nargout>6, % if activations are to be returned if verbose, fprintf('Permuting the activation wave forms ...\n'); end activations = activations(windex,:); else clear activations end weights = weights(windex,:);% reorder the weight matrix bias = bias(windex); % reorder them signs = diag(signs); % vectorize the signs matrix signs = signs(windex); % reorder them % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % return if nargout > 7 u=weights*data + bias*ones(1,frames); y = zeros(size(u)); for c=1:chans for f=1:frames y(c,f) = 1/(1+exp(-u(c,f))); end end end
github
ZijingMao/baselineeegtest-master
runica_ml2.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/runica_ml2.m
43,331
utf_8
d9f5448e45ce40d04ca05b45c6a092c4
% runica() - Perform Independent Component Analysis (ICA) decomposition % of input data using the logistic infomax ICA algorithm of % Bell & Sejnowski (1995) with the natural gradient feature % of Amari, Cichocki & Yang, or optionally the extended-ICA % algorithm of Lee, Girolami & Sejnowski, with optional PCA % dimension reduction. Annealing based on weight changes is % used to automate the separation process. % Usage: % >> [weights,sphere] = runica(data); % train using defaults % else % >> [weights,sphere,compvars,bias,signs,lrates,activations] ... % = runica(data,'Key1',Value1',...); % Input: % data = input data (chans,frames*epochs). % Note that if data consists of multiple discontinuous epochs, % each epoch should be separately baseline-zero'd using % >> data = rmbase(data,frames,basevector); % % Optional keywords [argument]: % 'extended' = [N] perform tanh() "extended-ICA" with sign estimation % N training blocks. If N > 0, automatically estimate the % number of sub-Gaussian sources. If N < 0, fix number of % sub-Gaussian comps to -N [faster than N>0] (default|0 -> off) % 'pca' = [N] decompose a principal component (default -> 0=off) % subspace of the data. Value is the number of PCs to retain. % 'ncomps' = [N] number of ICA components to compute (default -> chans or 'pca' arg) % using rectangular ICA decomposition % 'sphering' = ['on'/'off'] flag sphering of data (default -> 'on') % 'weights' = [W] initial weight matrix (default -> eye()) % (Note: if 'sphering' 'off', default -> spher()) % 'lrate' = [rate] initial ICA learning rate (<< 1) (default -> heuristic) % 'block' = [N] ICA block size (<< datalength) (default -> heuristic) % 'anneal' = annealing constant (0,1] (defaults -> 0.90, or 0.98, extended) % controls speed of convergence % 'annealdeg' = [N] degrees weight change for annealing (default -> 70) % 'stop' = [f] stop training when weight-change < this (default -> 1e-6 % if less than 33 channel and 1E-7 otherwise) % 'maxsteps' = [N] max number of ICA training steps (default -> 512) % 'bias' = ['on'/'off'] perform bias adjustment (default -> 'on') % 'momentum' = [0<f<1] training momentum (default -> 0) % 'specgram' = [srate loHz hiHz frames winframes] decompose a complex time/frequency % transform of the data (Note: winframes must divide frames) % (defaults [srate 0 srate/2 size(data,2) size(data,2)]) % 'posact' = make all component activations net-positive(default 'on'} % 'verbose' = give ascii messages ('on'/'off') (default -> 'on') % % Outputs: [Note: RO means output in reverse order of projected mean variance % unless starting weight matrix passed ('weights' above)] % weights = ICA weight matrix (comps,chans) [RO] % sphere = data sphering matrix (chans,chans) = spher(data) % Note that unmixing_matrix = weights*sphere {if sphering off -> eye(chans)} % compvars = back-projected component variances [RO] % bias = vector of final (ncomps) online bias [RO] (default = zeros()) % signs = extended-ICA signs for components [RO] (default = ones()) % [ -1 = sub-Gaussian; 1 = super-Gaussian] % lrates = vector of learning rates used at each training step [RO] % activations = activation time courses of the output components (ncomps,frames*epochs) % % Authors: Scott Makeig with contributions from Tony Bell, Te-Won Lee, % Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky, Delorme Arnaud, % CNL/The Salk Institute, La Jolla, 1996- % Uses: posact() % Reference (please cite): % % Makeig, S., Bell, A.J., Jung, T-P and Sejnowski, T.J., % "Independent component analysis of electroencephalographic data," % In: D. Touretzky, M. Mozer and M. Hasselmo (Eds). Advances in Neural % Information Processing Systems 8:145-151, MIT Press, Cambridge, MA (1996). % % Toolbox Citation: % % Makeig, Scott et al. "EEGLAB: ICA Toolbox for Psychophysiological Research". % WWW Site, Swartz Center for Computational Neuroscience, Institute of Neural % Computation, University of San Diego California % <www.sccn.ucsd.edu/eeglab/>, 2000. [World Wide Web Publication]. % % For more information: % http://www.sccn.ucsd.edu/eeglab/icafaq.html - FAQ on ICA/EEG % http://www.sccn.ucsd.edu/eeglab/icabib.html - mss. on ICA & biosignals % http://www.cnl.salk.edu/~tony/ica.html - math. mss. on ICA % Copyright (C) 1996 Scott Makeig et al, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %%%%%%%%%%%%%%%%%%%%%%%%%%% Edit history %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % runica() - by Scott Makeig with contributions from Tony Bell, Te-Won Lee % Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky et al. % CNL / Salk Institute 1996-00 % 04-30-96 built from icatest.m and ~jung/.../wtwpwica.m -sm % 07-28-97 new runica(), adds bias (default on), momentum (default off), % extended-ICA (Lee & Sejnowski, 1997), cumulative angledelta % (until lrate drops), keywords, signcount for speeding extended-ICA % 10-07-97 put acos() outside verbose loop; verbose 'off' wasn't stopping -sm % 11-11-97 adjusted help msg -sm % 11-30-97 return eye(chans) if sphering 'off' or 'none' (undocumented option) -sm % 02-27-98 use pinv() instead of inv() to rank order comps if ncomps < chans -sm % 04-28-98 added 'posact' and 'pca' flags -sm % 07-16-98 reduced length of randperm() for kurtosis subset calc. -se & sm % 07-19-98 fixed typo in weights def. above -tl & sm % 12-21-99 added 'specgram' option suggested by Michael Zibulevsky, UNM -sm % 12-22-99 fixed rand() sizing inefficiency on suggestion of Mike Spratling, UK -sm % 01-11-00 fixed rand() sizing bug on suggestion of Jack Foucher, Strasbourg -sm % 12-18-00 test for existence of Sig Proc Tlbx function 'specgram'; improve % 'specgram' option arguments -sm % 01-25-02 reformated help & license -ad % 01-25-02 lowered default lrate and block -ad % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [weights,sphere,meanvar,bias,signs,lrates,activations,y,loglik,wsave] = runica(data,p1,v1,p2,v2,p3,v3,p4,v4,p5,v5,p6,v6,p7,v7,p8,v8,p9,v9,p10,v10,p11,v11,p12,v12,p13,v13,p14,v14) if nargin < 1 help runica return end [chans frames] = size(data); % determine the data size urchans = chans; % remember original data channels datalength = frames; if chans<2 fprintf('\nrunica() - data size (%d,%d) too small.\n\n', chans,frames); return end % %%%%%%%%%%%%%%%%%%%%%% Declare defaults used below %%%%%%%%%%%%%%%%%%%%%%%% % MAX_WEIGHT = 1e8; % guess that weights larger than this have blown up DEFAULT_STOP = 1e-6; % stop training if weight changes below this DEFAULT_ANNEALDEG = 60; % when angle change reaches this value, DEFAULT_ANNEALSTEP = 0.95; % anneal by multiplying lrate by this DEFAULT_EXTANNEAL = 0.95; % or this if extended-ICA DEFAULT_MAXSTEPS = 500; % stop training after this many steps DEFAULT_MOMENTUM = 0.0; % default momentum weight DEFAULT_BLOWUP = 1000000000.0; % = learning rate has 'blown up' DEFAULT_BLOWUP_FAC = 0.8; % when lrate 'blows up,' anneal by this fac DEFAULT_RESTART_FAC = 0.9; % if weights blowup, restart with lrate % lower by this factor MIN_LRATE = 0.0001; % if weight blowups make lrate < this, quit MAX_LRATE = 0.1; % guard against uselessly high learning rate DEFAULT_LRATE = 0.00065/log(chans); % heuristic default - may need adjustment % for large or tiny data sets! % DEFAULT_BLOCK = floor(sqrt(frames/4)); % heuristic default DEFAULT_BLOCK = ceil(min(5*log(frames),0.3*frames)); % heuristic %DEFAULT_BLOCK = 10000; % heuristic % - may need adjustment! % Extended-ICA option: DEFAULT_EXTENDED = 1; % default off DEFAULT_EXTBLOCKS = 1; % number of blocks per kurtosis calculation DEFAULT_NSUB = 0; % initial default number of assumed sub-Gaussians % for extended-ICA DEFAULT_EXTMOMENTUM = 0.5; % momentum term for computing extended-ICA kurtosis MAX_KURTSIZE = 6000; % max points to use in kurtosis calculation MIN_KURTSIZE = 2000; % minimum good kurtosis size (flag warning) SIGNCOUNT_THRESHOLD = 25; % raise extblocks when sign vector unchanged % after this many steps SIGNCOUNT_STEP = 2; % extblocks increment factor DEFAULT_SPHEREFLAG = 'on'; % use the sphere matrix as the default % starting weight matrix DEFAULT_PCAFLAG = 'off'; % don't use PCA reduction DEFAULT_POSACTFLAG = 'on'; % use posact() DEFAULT_VERBOSE = 1; % write ascii info to calling screen DEFAULT_BIASFLAG = 0; % default to using bias in the ICA update rule % %%%%%%%%%%%%%%%%%%%%%%% Set up keyword default values %%%%%%%%%%%%%%%%%%%%%%%%% % if nargout < 2, fprintf('runica() - needs at least two output arguments.\n'); return end epochs = 1; % do not care how many epochs in data pcaflag = DEFAULT_PCAFLAG; sphering = DEFAULT_SPHEREFLAG; % default flags posactflag = DEFAULT_POSACTFLAG; verbose = DEFAULT_VERBOSE; block = DEFAULT_BLOCK; % heuristic default - may need adjustment! lrate = DEFAULT_LRATE; annealdeg = DEFAULT_ANNEALDEG; annealstep = 0; % defaults declared below nochange = NaN; momentum = DEFAULT_MOMENTUM; maxsteps = DEFAULT_MAXSTEPS; weights = 0; % defaults defined below ncomps = chans; biasflag = DEFAULT_BIASFLAG; extended = DEFAULT_EXTENDED; extblocks = DEFAULT_EXTBLOCKS; kurtsize = MAX_KURTSIZE; signsbias = 0.02; % bias towards super-Gaussian components extmomentum= DEFAULT_EXTMOMENTUM; % exp. average the kurtosis estimates nsub = DEFAULT_NSUB; wts_blowup = 0; % flag =1 when weights too large wts_passed = 0; % flag weights passed as argument % %%%%%%%%%% Collect keywords and values from argument list %%%%%%%%%%%%%%% % if (nargin> 1 & rem(nargin,2) == 0) fprintf('runica(): Even number of input arguments???') return end for i = 3:2:nargin % for each Keyword Keyword = eval(['p',int2str((i-3)/2 +1)]); Value = eval(['v',int2str((i-3)/2 +1)]); if ~isstr(Keyword) fprintf('runica(): keywords must be strings') return end Keyword = lower(Keyword); % convert upper or mixed case to lower if strcmp(Keyword,'weights') | strcmp(Keyword,'weight') if isstr(Value) fprintf(... 'runica(): weights value must be a weight matrix or sphere') return else weights = Value; wts_passed =1; end elseif strcmp(Keyword,'ncomps') if isstr(Value) fprintf('runica(): ncomps value must be an integer') return end if ncomps < urchans & ncomps ~= Value fprintf('runica(): Use either PCA or ICA dimension reduction'); return end ncomps = Value; if ~ncomps, ncomps = chans; end elseif strcmp(Keyword,'pca') if ncomps < urchans & ncomps ~= Value fprintf('runica(): Use either PCA or ICA dimension reduction'); return end if isstr(Value) fprintf(... 'runica(): pca value should be the number of principal components to retain') return end pcaflag = 'on'; ncomps = Value; if ncomps > chans | ncomps < 1, fprintf('runica(): pca value must be in range [1,%d]\n',chans) return end chans = ncomps; elseif strcmp(Keyword,'posact') if ~isstr(Value) fprintf('runica(): posact value must be on or off') return else Value = lower(Value); if ~strcmp(Value,'on') & ~strcmp(Value,'off'), fprintf('runica(): posact value must be on or off') return end posactflag = Value; end elseif strcmp(Keyword,'lrate') if isstr(Value) fprintf('runica(): lrate value must be a number') return end lrate = Value; if lrate>MAX_LRATE | lrate <0, fprintf('runica(): lrate value is out of bounds'); return end if ~lrate, lrate = DEFAULT_LRATE; end elseif strcmp(Keyword,'block') | strcmp(Keyword,'blocksize') if isstr(Value) fprintf('runica(): block size value must be a number') return end block = floor(Value); if ~block, block = DEFAULT_BLOCK; end elseif strcmp(Keyword,'stop') | strcmp(Keyword,'nochange') ... | strcmp(Keyword,'stopping') if isstr(Value) fprintf('runica(): stop wchange value must be a number') return end nochange = Value; elseif strcmp(Keyword,'maxsteps') | strcmp(Keyword,'steps') if isstr(Value) fprintf('runica(): maxsteps value must be an integer') return end maxsteps = Value; if ~maxsteps, maxsteps = DEFAULT_MAXSTEPS; end if maxsteps < 0 fprintf('runica(): maxsteps value (%d) must be a positive integer',maxsteps) return end elseif strcmp(Keyword,'anneal') | strcmp(Keyword,'annealstep') if isstr(Value) fprintf('runica(): anneal step value (%2.4f) must be a number (0,1)',Value) return end annealstep = Value; if annealstep <=0 | annealstep > 1, fprintf('runica(): anneal step value (%2.4f) must be (0,1]',annealstep) return end elseif strcmp(Keyword,'annealdeg') | strcmp(Keyword,'degrees') if isstr(Value) fprintf('runica(): annealdeg value must be a number') return end annealdeg = Value; if ~annealdeg, annealdeg = DEFAULT_ANNEALDEG; elseif annealdeg > 180 | annealdeg < 0 fprintf('runica(): annealdeg (%3.1f) is out of bounds [0,180]',... annealdeg); return end elseif strcmp(Keyword,'momentum') if isstr(Value) fprintf('runica(): momentum value must be a number') return end momentum = Value; if momentum > 1.0 | momentum < 0 fprintf('runica(): momentum value is out of bounds [0,1]') return end elseif strcmp(Keyword,'sphering') | strcmp(Keyword,'sphereing') ... | strcmp(Keyword,'sphere') if ~isstr(Value) fprintf('runica(): sphering value must be on, off, or none') return else Value = lower(Value); if ~strcmp(Value,'on') & ~strcmp(Value,'off') & ~strcmp(Value,'none'), fprintf('runica(): sphering value must be on or off') return end sphering = Value; end elseif strcmp(Keyword,'bias') if ~isstr(Value) fprintf('runica(): bias value must be on or off') return else Value = lower(Value); if strcmp(Value,'on') biasflag = 1; elseif strcmp(Value,'off'), biasflag = 0; else fprintf('runica(): bias value must be on or off') return end end elseif strcmp(Keyword,'specgram') | strcmp(Keyword,'spec') if ~exist('specgram') < 2 % if ~exist or defined workspace variable fprintf(... 'runica(): MATLAB Sig. Proc. Toolbox function "specgram" not found.\n') return end if isstr(Value) fprintf('runica(): specgram argument must be a vector') return end srate = Value(1); if (srate < 0) fprintf('runica(): specgram srate (%4.1f) must be >=0',srate) return end if length(Value)>1 loHz = Value(2); if (loHz < 0 | loHz > srate/2) fprintf('runica(): specgram loHz must be >=0 and <= srate/2 (%4.1f)',srate/2) return end else loHz = 0; % default end if length(Value)>2 hiHz = Value(3); if (hiHz < loHz | hiHz > srate/2) fprintf('runica(): specgram hiHz must be >=loHz (%4.1f) and <= srate/2 (%4.1f)',loHz,srate/2) return end else hiHz = srate/2; % default end if length(Value)>3 Hzframes = Value(5); if (Hzframes<0 | Hzframes > size(data,2)) fprintf('runica(): specgram frames must be >=0 and <= data length (%d)',size(data,2)) return end else Hzframes = size(data,2); % default end if length(Value)>4 Hzwinlen = Value(4); if rem(Hzframes,Hzwinlen) % if winlen doesn't divide frames fprintf('runica(): specgram Hzinc must divide frames (%d)',Hzframes) return end else Hzwinlen = Hzframes; % default end Specgramflag = 1; % set flag to perform specgram() elseif strcmp(Keyword,'extended') | strcmp(Keyword,'extend') if isstr(Value) fprintf('runica(): extended value must be an integer (+/-)') return else extended = 1; % turn on extended-ICA extblocks = fix(Value); % number of blocks per kurt() compute if extblocks < 0 nsub = -1*fix(extblocks); % fix this many sub-Gauss comps elseif ~extblocks, extended = 0; % turn extended-ICA off elseif kurtsize>frames, % length of kurtosis calculation kurtsize = frames; if kurtsize < MIN_KURTSIZE fprintf(... 'runica() warning: kurtosis values inexact for << %d points.\n',... MIN_KURTSIZE); end end end elseif strcmp(Keyword,'verbose') if ~isstr(Value) fprintf('runica(): verbose flag value must be on or off') return elseif strcmp(Value,'on'), verbose = 1; elseif strcmp(Value,'off'), verbose = 0; else fprintf('runica(): verbose flag value must be on or off') return end else fprintf('runica(): unknown flag') return end end % %%%%%%%%%%%%%%%%%%%%%%%% Initialize weights, etc. %%%%%%%%%%%%%%%%%%%%%%%% % if ~annealstep, if ~extended, annealstep = DEFAULT_ANNEALSTEP; % defaults defined above else annealstep = DEFAULT_EXTANNEAL; % defaults defined above end end % else use annealstep from commandline if ~annealdeg, annealdeg = DEFAULT_ANNEALDEG - momentum*90; % heuristic if annealdeg < 0, annealdeg = 0; end end if ncomps > chans | ncomps < 1 fprintf('runica(): number of components must be 1 to %d.\n',chans); return end if weights ~= 0, % initialize weights % starting weights are being passed to runica() from the commandline if verbose, fprintf('Using starting weight matrix named in argument list ...\n') end if chans>ncomps & weights ~=0, [r,c]=size(weights); if r~=ncomps | c~=chans, fprintf(... 'runica(): weight matrix must have %d rows, %d columns.\n', ... chans,ncomps); return; end end end; % %%%%%%%%%%%%%%%%%%%%% Check keyword values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if frames<chans, fprintf('runica(): data length (%d) < data channels (%d)!\n',frames,chans) return elseif block < 1, fprintf('runica(): block size %d too small!\n',block) return elseif block > frames, fprintf('runica(): block size exceeds data length!\n'); return elseif floor(epochs) ~= epochs, fprintf('runica(): data length is not a multiple of the epoch length!\n'); return elseif nsub > ncomps fprintf('runica(): there can be at most %d sub-Gaussian components!\n',ncomps); return end; % % adjust nochange if necessary % if isnan(nochange) if ncomps > 32 nochange = 1E-7; nochangeupdated = 1; % for fprinting purposes else nochangeupdated = 1; % for fprinting purposes nochange = DEFAULT_STOP; end; else nochangeupdated = 0; end; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Process the data %%%%%%%%%%%%%%%%%%%%%%%%%% % if verbose, fprintf( ... '\nInput data size [%d,%d] = %d channels, %d frames/n', ... chans,frames,chans,frames); if strcmp(pcaflag,'on') fprintf('After PCA dimension reduction,\n finding '); else fprintf('Finding '); end if ~extended fprintf('%d ICA components using logistic ICA.\n',ncomps); else % if extended fprintf('%d ICA components using extended ICA.\n',ncomps); if extblocks > 0 fprintf(... 'Kurtosis will be calculated initially every %d blocks using %d data points.\n',... extblocks, kurtsize); else fprintf(... 'Kurtosis will not be calculated. Exactly %d sub-Gaussian components assumed.\n',... nsub); end end fprintf('Decomposing %d frames per ICA weight ((%d)^2 = %d weights, %d frames)\n',... floor(frames/ncomps.^2),ncomps.^2,frames); fprintf('Initial learning rate will be %g, block size %d.\n',... lrate,block); if momentum>0, fprintf('Momentum will be %g.\n',momentum); end fprintf( ... 'Learning rate will be multiplied by %g whenever angledelta >= %g deg.\n', ... annealstep,annealdeg); if nochangeupdated fprintf('More than 32 channels: default stopping weight change 1E-7\n'); end; fprintf('Training will end when wchange < %g or after %d steps.\n', ... nochange,maxsteps); if biasflag, fprintf('Online bias adjustment will be used.\n'); else fprintf('Online bias adjustment will not be used.\n'); end end % %%%%%%%%%%%%%%%%%%%%%%%%% Remove overall row means %%%%%%%%%%%%%%%%%%%%%%%% % if verbose, fprintf('Removing mean of each channel ...\n'); end data = data - mean(data')'*ones(1,frames); % subtract row means if verbose, fprintf('Final training data range: %g to %g\n', ... min(min(data)),max(max(data))); end % %%%%%%%%%%%%%%%%%%% Perform PCA reduction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmp(pcaflag,'on') fprintf('Reducing the data to %d principal dimensions...\n',ncomps); [eigenvectors,eigenvalues,data] = pcsquash(data,ncomps); % make data its projection onto the ncomps-dim principal subspace end % %%%%%%%%%%%%%%%%%%% Perform specgram transformation %%%%%%%%%%%%%%%%%%%%%%% % if exist('Specgramflag') == 1 % [P F T] = SPECGRAM(A,NFFT,Fs,WINDOW,NOVERLAP) % MATLAB Sig Proc Toolbox % Hzwinlen = fix(srate/Hzinc); % CHANGED FROM THIS 12/18/00 -sm Hzfftlen = 2^(ceil(log(Hzwinlen)/log(2))); % make FFT length next higher 2^k Hzoverlap = 0; % use sequential windows % % Get freqs and times from 1st channel analysis % [tmp,freqs,tms] = specgram(data(1,:),Hzfftlen,srate,Hzwinlen,Hzoverlap); fs = find(freqs>=loHz & freqs <= hiHz); if isempty(fs) fprintf('runica(): specified frequency range too narrow!\n'); return end; specdata = reshape(tmp(fs,:),1,length(fs)*size(tmp,2)); specdata = [real(specdata) imag(specdata)]; % fprintf(' size(fs) = %d,%d\n',size(fs,1),size(fs,2)); % fprintf(' size(tmp) = %d,%d\n',size(tmp,1),size(tmp,2)); % % Loop through remaining channels % for ch=2:chans [tmp] = specgram(data(ch,:),Hzwinlen,srate,Hzwinlen,Hzoverlap); tmp = reshape((tmp(fs,:)),1,length(fs)*size(tmp,2)); specdata = [specdata;[real(tmp) imag(tmp)]]; % channels are rows end % % Print specgram confirmation and details % fprintf(... 'Converted data to %d channels by %d=2*%dx%d points spectrogram data.\n',... chans,2*length(fs)*length(tms),length(fs),length(tms)); if length(fs) > 1 fprintf(... ' Low Hz %g, high Hz %g, Hz incr %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),freqs(fs(2))-freqs(fs(1)),Hzwinlen); else fprintf(... ' Low Hz %g, high Hz %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),Hzwinlen); end % % Replace data with specdata % data = specdata; datalength=size(data,2); end % %%%%%%%%%%%%%%%%%%% Perform sphering %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmp(sphering,'on'), %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if verbose, fprintf('Computing the sphering matrix...\n'); end sphere = 2.0*inv(sqrtm(cov(data'))); % find the "sphering" matrix = spher() if ~weights, if verbose, fprintf('Starting weights are the identity matrix ...\n'); end weights = eye(ncomps,chans); % begin with the identity matrix else % weights given on commandline if verbose, fprintf('Using starting weights named on commandline ...\n'); end end if verbose, fprintf('Sphering the data ...\n'); end data = sphere*data; % actually decorrelate the electrode signals elseif strcmp(sphering,'off') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~weights if verbose, fprintf('Using the sphering matrix as the starting weight matrix ...\n'); fprintf('Returning the identity matrix in variable "sphere" ...\n'); end sphere = 2.0*inv(sqrtm(cov(data'))); % find the "sphering" matrix = spher() weights = eye(ncomps,chans)*sphere; % begin with the identity matrix sphere = eye(chans); % return the identity matrix else % weights ~= 0 if verbose, fprintf('Using starting weights named on commandline ...\n'); fprintf('Returning the identity matrix in variable "sphere" ...\n'); end sphere = eye(chans); % return the identity matrix end elseif strcmp(sphering,'none') sphere = eye(chans); % return the identity matrix if ~weights if verbose, fprintf('Starting weights are the identity matrix ...\n'); fprintf('Returning the identity matrix in variable "sphere" ...\n'); end weights = eye(ncomps,chans); % begin with the identity matrix else % weights ~= 0 if verbose, fprintf('Using starting weights named on commandline ...\n'); fprintf('Returning the identity matrix in variable "sphere" ...\n'); end end sphere = eye(chans,chans); if verbose, fprintf('Returned variable "sphere" will be the identity matrix.\n'); end end % %%%%%%%%%%%%%%%%%%%%%%%% Initialize ICA training %%%%%%%%%%%%%%%%%%%%%%%%% % lastt=fix((datalength/block-1)*block+1); BI=block*eye(ncomps,ncomps); delta=zeros(1,chans*ncomps); changes = []; degconst = 180./pi; startweights = weights; prevweights = startweights; oldweights = startweights; prevwtchange = zeros(chans,ncomps); oldwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); onesrow = ones(1,block); bias = zeros(ncomps,1); signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1 for k=1:nsub signs(k) = -1; end if extended & extblocks < 0 & verbose, fprintf('Fixed extended-ICA sign assignments: '); for k=1:ncomps fprintf('%d ',signs(k)); end; fprintf('\n'); end signs = diag(signs); % make a diagonal matrix oldsigns = zeros(size(signs));; signcount = 0; % counter for same-signs signcounts = []; urextblocks = extblocks; % original value, for resets old_kk = zeros(1,ncomps); % for kurtosis momemtum % %%%%%%%% ICA training loop using the logistic sigmoid %%%%%%%%%%%%%%%%%%% % if verbose, fprintf('Beginning ICA training ...'); if extended, fprintf(' first training step may be slow ...\n'); else fprintf('\n'); end end step=0; laststep=0; blockno = 1; % running block counter for kurtosis interrupts logstep = 1; % iterator over log likelihood record rand('state',sum(100*clock)); % set the random number generator state to cost_step = 10; % record cost every cost_step iterations block = 10000; % a position dependent on the system clock while step < maxsteps, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% permute=randperm(datalength); % shuffle data order at each step if mod(step,cost_step) == 0 loglik(logstep) = 0; end for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%% pause(0); if ~isempty(get(0, 'currentfigure')) & strcmp(get(gcf, 'tag'), 'stop') close; error('USER ABORT'); end; if biasflag u=weights*data(:,permute(t:t+block-1)) + bias*onesrow; else u=weights*data(:,permute(t:t+block-1)); end if ~extended %%%%%%%%%%%%%%%%%%% Logistic ICA weight update %%%%%%%%%%%%%%%%%%% y=1./(1+exp(-u)); % weights = weights + lrate*(BI+(1-2*y)*u')*weights; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% else % Tanh extended-ICA weight update %%%%%%%%%%%%%%%%%%% Extended-ICA weight update %%%%%%%%%%%%%%%%%%% y=tanh(u); % weights = weights + lrate*(BI-signs*y*u'-u*u')*weights; % end wsave{step+1} = weights; if biasflag if ~extended %%%%%%%%%%%%%%%%%%%%%%%% Logistic ICA bias %%%%%%%%%%%%%%%%%%%%%%% bias = bias + lrate*sum((1-2*y)')'; % for logistic nonlin. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% else % extended %%%%%%%%%%%%%%%%%%% Extended-ICA bias %%%%%%%%%%%%%%%%%%%%%%%%%%%% bias = bias + lrate*sum((-2*y)')'; % for tanh() nonlin. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end end if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%% weights = weights + momentum*prevwtchange; prevwtchange = weights-prevweights; prevweights = weights; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if max(max(abs(weights))) > MAX_WEIGHT wts_blowup = 1; change = nochange; end if extended & ~wts_blowup % %%%%%%%%%%% Extended-ICA kurtosis estimation %%%%%%%%%%%%%%%%%%%%% % if extblocks > 0 & rem(blockno,extblocks) == 0, % recompute signs vector using kurtosis if kurtsize < frames % 12-22-99 rand() size suggestion by M. Spratling rp = fix(rand(1,kurtsize)*datalength); % pick random subset % Accout for the possibility of a 0 generation by rand ou = find(rp == 0); while ~isempty(ou) % 1-11-00 suggestion by J. Foucher rp(ou) = fix(rand(1,length(ou))*datalength); ou = find(rp == 0); end partact=weights*data(:,rp(1:kurtsize)); else % for small data sets, partact=weights*data; % use whole data end m2=mean(partact'.^2).^2; m4= mean(partact'.^4); kk= (m4./m2)-3.0; % kurtosis estimates if extmomentum kk = extmomentum*old_kk + (1.0-extmomentum)*kk; % use momentum old_kk = kk; end signs=diag(sign(kk+signsbias)); % pick component signs if signs == oldsigns, signcount = signcount+1; else signcount = 0; end oldsigns = signs; signcounts = [signcounts signcount]; if signcount >= SIGNCOUNT_THRESHOLD, extblocks = fix(extblocks * SIGNCOUNT_STEP);% make kurt() estimation signcount = 0; % less frequent if sign end % is not changing end % extblocks > 0 & . . . end % if extended %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% blockno = blockno + 1; if wts_blowup break end end % training block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if mod(step,cost_step) == 0 %%%%%%%%% Calculate log likelihood given our model %%%%%%%%% loglik(logstep) = log(abs(det(weights))); if extended subgcomp = find(diag(signs) == -1); supergcomp = find(diag(signs) == 1); acts = weights*data; if length(subgcomp) > 0 if biasflag loglik(logstep) = loglik(logstep) + (1/frames)*sum(sum(log(exp(-(1/2)*(acts(subgcomp,:)-bias*ones(1,length(subgcomp))-1).^2) + exp(-(1/2)*(acts(subgcomp,:)-bias*ones(1,length(subgcomp))+1).^2)))); else loglik(logstep) = loglik(logstep) + (1/frames)*sum(sum(log(exp(-(1/2)*(acts(subgcomp,:)-1).^2) + exp(-(1/2)*(acts(subgcomp,:)+1).^2)))); end end if length(supergcomp) > 0 if biasflag loglik(logstep) = loglik(logstep) + (1/frames)*sum(sum(-0.5*(acts(supergcomp,:)-bias*ones(1,length(supergcomp))).^2 - 2*log(cosh(acts(supergcomp,:)-bias*ones(1,length(supergcomp)))))); else loglik(logstep) = loglik(logstep) + (1/frames)*sum(sum(-0.5*acts(supergcomp,:).^2 - 2*log(cosh(acts(supergcomp,:))))); end end end logstep = logstep + 1; end if ~wts_blowup oldwtchange = weights-oldweights; step=step+1; % %%%%%%% Compute and print weight and update angle changes %%%%%%%%% % lrates(1,step) = lrate; angledelta=0.; delta=reshape(oldwtchange,1,chans*ncomps); change=delta*delta'; end % %%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%% % if wts_blowup | isnan(change)|isinf(change), % if weights blow up, fprintf(''); step = 0; % start again change = nochange; wts_blowup = 0; % re-initialize variables blockno = 1; lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate weights = startweights; % and original weight matrix oldweights = startweights; change = nochange; oldwtchange = zeros(chans,ncomps); delta=zeros(1,chans*ncomps); olddelta = delta; extblocks = urextblocks; prevweights = startweights; prevwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); bias = zeros(ncomps,1); if extended signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1 for k=1:nsub signs(k) = -1; end signs = diag(signs); % make a diagonal matrix oldsigns = zeros(size(signs));; end if lrate> MIN_LRATE r = rank(data); if r<ncomps fprintf('Data has rank %d. Cannot compute %d components.\n',... r,ncomps); return else fprintf(... 'Lowering learning rate to %g and starting again.\n',lrate); end else fprintf( ... 'runica(): QUITTING - weight matrix may not be invertible!\n'); return; end else % if weights in bounds % %%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%% % if step> 2 angledelta=acos((delta*olddelta')/sqrt(change*oldchange)); end if verbose, places = -floor(log10(nochange)); if step > 2, if ~extended, ps = sprintf('step %d - lrate %5f, wchange %%%d.%df, angledelta %4.1f deg\n', ... step, lrate, places+1,places, degconst*angledelta); else ps = sprintf('step %d - lrate %5f, wchange %%%d.%df, angledelta %4.1f deg, %d subgauss\n',... step, lrate, degconst*angledelta,... places+1,places, (ncomps-sum(diag(signs)))/2); end elseif ~extended ps = sprintf('step %d - lrate %5f, wchange %%%d.%df\n',... step, lrate, places+1,places ); else ps = sprintf('step %5d - lrate %5f, wchange %%%d.%df, %d subgauss\n',... step, lrate, places+1,places, (ncomps-sum(diag(signs)))/2); end % step > 2 fprintf('step %d - lrate %8.8f, wchange %8.8f, angledelta %3.1f deg, loglik %6.4f, nsub = %d\n', ... step, lrate, change, degconst*angledelta, loglik(step), sum(diag(signs)==-1)); % fprintf(ps,change); % <---- BUG !!!! end; % if verbose % %%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % changes = [changes change]; oldweights = weights; % %%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if degconst*angledelta > annealdeg, lrate = lrate*annealstep; % anneal learning rate olddelta = delta; % accumulate angledelta until oldchange = change; % annealdeg is reached elseif step == 1 % on first step only olddelta = delta; % initialize oldchange = change; end % %%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if step >2 & change < nochange, % apply stopping rule laststep=step; step=maxsteps; % stop when weights stabilize elseif change > DEFAULT_BLOWUP, % if weights blow up, lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying end; % with a smaller learning rate end; % end if weights in bounds end; % end training %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~laststep laststep = step; end; lrates = lrates(1,1:laststep); % truncate lrate history vector % %%%%%%%%%%%%%% Orient components towards max positive activation %%%%%% % if strcmp(posactflag,'on') [activations,winvout,weights] = posact(data,weights); % changes signs of activations and weights to make activations % net rms-positive else activations = weights*data; end % %%%%%%%%%%%%%% If pcaflag, compose PCA and ICA matrices %%%%%%%%%%%%%%% % if strcmp(pcaflag,'on') fprintf('Composing the eigenvector, weights, and sphere matrices\n'); fprintf(' into a single rectangular weights matrix; sphere=eye(%d)\n'... ,chans); weights= weights*sphere*eigenvectors(:,1:ncomps)'; sphere = eye(urchans); end % %%%%%% Sort components in descending order of max projected variance %%%% % if verbose, fprintf(... 'Sorting components in descending order of mean projected variance ...\n'); end % %%%%%%%%%%%%%%%%%%%% Find mean variances %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % meanvar = zeros(ncomps,1); % size of the projections if ncomps == urchans % if weights are square . . . winv = inv(weights*sphere); else fprintf('Using pseudo-inverse of weight matrix to rank order component projections.\n'); winv = pinv(weights*sphere); end for s=1:ncomps if verbose, fprintf('%d ',s); % construct single-component data matrix end % project to scalp, then add row means compproj = winv(:,s)*activations(s,:); meanvar(s) = mean(sum(compproj.*compproj)/(size(compproj,1)-1)); % compute mean variance end % at all scalp channels if verbose, fprintf('\n'); end % %%%%%%%%%%%%%% Sort components by mean variance %%%%%%%%%%%%%%%%%%%%%%%% % [sortvar, windex] = sort(meanvar); windex = windex(ncomps:-1:1); % order large to small meanvar = meanvar(windex); % %%%%%%%%%%%%%%%%%%%%% Filter data using final weights %%%%%%%%%%%%%%%%%% % if nargout>6, % if activations are to be returned if verbose, fprintf('Permuting the activation wave forms ...\n'); end activations = activations(windex,:); else clear activations end weights = weights(windex,:);% reorder the weight matrix bias = bias(windex); % reorder them signs = diag(signs); % vectorize the signs matrix signs = signs(windex); % reorder them % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % return if nargout > 7 u=weights*data + bias*ones(1,frames); y = zeros(size(u)); for c=1:chans for f=1:frames y(c,f) = 1/(1+exp(-u(c,f))); end end end
github
ZijingMao/baselineeegtest-master
writelocs.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/writelocs.m
10,300
utf_8
f0fb3a6c7068e5ae70ee752f60ad6a76
% writelocs() - write a file containing channel location, type and gain information % % Usage: % >> writelocs( chanstruct, filename ); % >> writelocs( chanstruct, filename, 'key', 'val' ); % % Inputs: % chanstruct - EEG.chanlocs data structure returned by readlocs() containing % channel location, type and gain information. % filename - File name for saving channel location, type and gain information % % Optional inputs: % 'filetype' - ['loc'|'sph'|'sfp'|'xyz'|'polhemus'|'besa'|'chanedit'|'custom'] % Type of the file to write. By default the file type is indicated % by the file extension. % 'loc' - An EEGLAB 2-D polar coordinates channel locations file % Coordinates are theta and radius (see definitions below). % 'sph' - A Matlab spherical coordinates file (Note: spherical % coordinates used by Matlab functions are different % from spherical coordinates used in BESA - see below). % 'sfp' - EGI cartesian coordinates (not Matlab cartesian - see below). % 'xyz' - MATLAB/EEGLAB cartesian coordinates (Not EGI cartesian; % z is toward nose; y is toward left ear; z is toward vertex). % 'polhemus' or 'polhemusx' - Polhemus electrode location file recorded with % 'X' on sensor pointing to subject (see below and readelp()). % 'polhemusy' - Polhemus electrode location file recorded with % 'Y' on sensor pointing to subject (see below and readelp()). % 'besa' - BESA'(.elp') spherical coordinate file. (Not MATLAB spherical % - see below). % 'chanedit' - EEGLAB channel location files created by pop_chanedit(). % 'custom' - Ascii files with columns in user-defined 'format' (see below). % 'format' - [cell array] Format of a 'custom' channel location file (see above). % Default if no file type is defined. The cell array contains % labels defining the meaning of each column of the input file. % 'channum' [positive integer] channel number % 'labels' [string] channel name (no spaces) % 'theta' [real degrees] 2-D angle in polar coordinates. % positive => rotating from nose (0) toward left ear % 'radius' [real] radius in 2-D polar coords (0.5 is disk limits) % 'X' [real] Matlab-cartesian X coordinate (to nose) % 'Y' [real] Matlab-cartesian Y coordinate (to left ear) % 'Z' [real] Matlab-cartesian Z coordinate (to vertex) % '-X','-Y','-Z' Matlab-cartesian coordinates pointing away from above % 'sph_theta' [real degrees] Matlab spherical horizontal angle. % positive => rotating from nose (0) toward left ear. % 'sph_phi' [real degrees] Matlab spherical elevation angle; % positive => rotating from horizontal (0) upwards. % 'sph_radius' [real] distance from head center (unused) % 'sph_phi_besa' [real degrees] BESA phi angle from vertical. % positive => rotating from vertex (0) towards right ear. % 'sph_theta_besa' [real degrees] BESA theta horiz/azimuthal angle. % positive => rotating from right ear (0) toward nose. % The input file may also contain other channel information fields % 'type' channel type: 'EEG', 'MEG', 'EMG', 'ECG', others ... % 'calib' [real near 1.0] channel calibration value. % 'gain' [real > 1] channel gain. % 'custom1' custom field #1. % 'custom2', 'custom3', 'custom4' more custom fields. % 'unicoord' - ['on'|'off'] Uniformize all coordinates. Default 'on'. % 'header' - ['on'|'off'] Add a header comment line with the name of each column. % Comment lines begin with '%'. Default is 'off'. % 'customheader' - [string] Add a custom header at the beginning of the file and % preceded by '%'. If used with 'header' set to 'on', % the column names will be insterted after the custom header. % 'elecind' - [integer array] Indices of channels to export. % Default is all channels. % % Note: for file formats, see readlocs() help (>> help readlocs) % % Author: Arnaud Delorme, Salk Institute, 16 Dec 2002 % % See also: readlocs(), readelp() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 28 Feb 2002 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function writelocs( chans, filename, varargin ); if nargin < 2 help writelocs; return; end; % get infos from readlocs % ----------------------- %[listtype formatinfo listcolformat formatskip] = readlocs('getinfos'); [chanformat listcolformat] = readlocs('getinfos'); indformat = []; for index = 1:length(chanformat), if ~isstr(chanformat(index).importformat) indformat = [ indformat index ]; end; if isempty(chanformat(index).skipline), chanformat(index).skipline = 0; end; end; listtype = { chanformat(indformat).type }; formatinfo = { chanformat(indformat).importformat }; formatskip = [ chanformat(indformat).skipline ]; g = finputcheck( varargin, ... { 'filetype' 'string' listtype 'loc'; 'header' 'string' { 'on','off' } 'off'; 'customheader' 'string' [] ''; 'elecind' 'integer' [1 Inf] []; 'unicoord' 'string' { 'on','off' } 'on'; 'format' 'cell' [] {} }, 'writelocs'); if isstr(g), error(g); end; if strcmpi(g.unicoord, 'on') disp('Uniformizing coordinates'); chans = convertlocs(chans, 'auto', 'verbose', 'off'); end; % select channels % --------------- if ~isempty(g.elecind) chans = chans(g.elecind); end; % finding types of input % ---------------------- if isempty(g.format) indexformat = strmatch(lower(g.filetype), listtype, 'exact'); g.format = formatinfo{indexformat}; g.skipline = formatskip(indexformat); else g.skipline = 0; end; % creating file % ------------- fid = fopen(filename, 'w'); % exporting header % ---------------- if ~isempty(g.customheader) allstrs = cellstr(g.customheader); for index=1:length(allstrs) fprintf(fid, '%s\n', allstrs{index}); end; end; if strcmpi(g.header, 'on') | g.skipline == 2 for index=1:length(g.format) fprintf(fid, '%8s\t', g.format{index}); end; fprintf(fid, '\n'); for index=1:length(g.format) fprintf(fid, '%8s\t', char(ones(1,8)*45)); end; fprintf(fid, '\n'); end; if g.skipline == 1 fprintf(fid, '%d\n', length(chans)); end; % writing infos % ------------- for indexchan = 1:length(chans) for index=1:length(g.format) [str, mult] = checkformat(g.format{index}); if strcmpi(str, 'channum') fprintf(fid, '%d', indexchan); else if ~isfield(chans, str) error([ 'Non-existant field: ''' str '''' ]); end; eval( [ 'chanval = chans(indexchan).' str ';' ] ); if isstr(chanval), fprintf(fid, '%8s', chanval); else if abs(mult*chanval) > 1E-10 fprintf(fid, '%8s', num2str(mult*chanval,5)); else fprintf(fid, '%8s', '0'); end; end; end; if index ~= length(g.format) fprintf(fid, '\t'); end; end; fprintf(fid, '\n'); end; fclose(fid); return; % check field format % ------------------ function [str, mult] = checkformat(str) mult = 1; if strcmpi(str, 'labels'), str = lower(str); return; end; if strcmpi(str, 'channum'), str = lower(str); return; end; if strcmpi(str, 'theta'), str = lower(str); return; end; if strcmpi(str, 'radius'), str = lower(str); return; end; if strcmpi(str, 'sph_theta'), str = lower(str); return; end; if strcmpi(str, 'sph_phi'), str = lower(str); return; end; if strcmpi(str, 'sph_radius'), str = lower(str); return; end; if strcmpi(str, 'sph_theta_besa'), str = lower(str); return; end; if strcmpi(str, 'sph_phi_besa'), str = lower(str); return; end; if strcmpi(str, 'gain'), str = lower(str); return; end; if strcmpi(str, 'calib'), str = lower(str); return; end; if strcmpi(str, 'type') , str = lower(str); return; end; if strcmpi(str, 'X'), str = upper(str); return; end; if strcmpi(str, 'Y'), str = upper(str); return; end; if strcmpi(str, 'Z'), str = upper(str); return; end; if strcmpi(str, '-X'), str = upper(str(2:end)); mult = -1; return; end; if strcmpi(str, '-Y'), str = upper(str(2:end)); mult = -1; return; end; if strcmpi(str, '-Z'), str = upper(str(2:end)); mult = -1; return; end; if strcmpi(str, 'custum1'), return; end; if strcmpi(str, 'custum2'), return; end; if strcmpi(str, 'custum3'), return; end; if strcmpi(str, 'custum4'), return; end; error(['writelocs: undefined field ''' str '''']);
github
ZijingMao/baselineeegtest-master
env.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/env.m
3,005
utf_8
40959ed7c77b4d587e2986bebd89b254
% env() - return envelope of rows of a data matrix, or optionally % of the data interpolated to a different sampling rate. % Usage: % >> envdata = env(data); % >> envdata = env(data, timelimits, timearray); % % Inputs: % data - (nchannels,ntimepoints) data array % % Optional Inputs: % timelimits - (start_time, end_time) timelimits (default: none required) % timearray - Optional times array to interpolate the data (default: none) % % Outputs: % envdata - A (2,timepoints) array containing the "envelope" of % a multichannel data set = the maximum and minimum values, % across all the channels, at each time point. That is, % >> envdata = [max(data');min(data')]; % % Author: Scott Makeig & Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: ENVTOPO % Scott Makeig & Arnaud Delorme - CNL / Salk Institute, La Jolla 8/8/97 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 2001 - extrapolation -ad % 01-25-02 reformated help & license -ad function envdata = env(data, timelimits, timearray ) maxdata = max(data); mindata = min(data); % extrapolate these values if necessary % ------------------------------------- if nargin > 2 timelimits = timelimits(:)'; % make row vector if size(timelimits,2)~=2 | size(timelimits,2)~=2 error('timelimits array must be a [start_time, end_time] vector') end X = linspace(timelimits(1),timelimits(2),length(maxdata)); % x-axis description (row vector) Y = ones(1,size(X,2)); if size(timearray,1)>1 & size(timearray,2)>1 error('timearray must be a vector') end Xi = timearray(:)'; % make a row vector Yi = ones(1,length(timearray)); try [tmp1,tmp2,Zi] = griddata(Y, X, maxdata, Yi, Xi, 'v4'); % interpolate data maxdata = Zi; [tmp1,tmp2,Zi] = griddata(Y, X, mindata, Yi, Xi, 'v4'); % interpolate data mindata = Zi; catch disp('Warning, "v4" interpolation failed, using linear interpolation instead (probably running Octave)'); [tmp1,tmp2,Zi] = griddata(Y, X, maxdata, Yi, Xi, 'linear'); % interpolate data maxdata = Zi; [tmp1,tmp2,Zi] = griddata(Y, X, mindata, Yi, Xi, 'linear'); % interpolate data mindata = Zi; end end; envdata = [maxdata;mindata]; return;
github
ZijingMao/baselineeegtest-master
uiputfile2.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/uiputfile2.m
2,674
utf_8
3b31fa4d223e9408a8660905b763639a
% uiputfile2() - same as uigputfile but remember folder location. % % Usage: >> uiputfile2(...) % % Inputs: Same as uiputfile % % Author: Arnaud Delorme & Hilit Serby, Scott Makeig, SCCN, UCSD, 2004 % Thanks to input from Bas Kortmann % % Copyright (C) Arnaud Delorme & Hilit Serby, Scott Makeig, SCCN, UCSD, 2004 % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function varargout = uiputfile2(varargin); if nargin < 1 help uiputfile2; return; end; % remember old folder %% search for the (mat) file which contains the latest used directory % ------------------- olddir = pwd; try, eeglab_options; if option_rememberfolder tmp_fld = getenv('TEMP'); if isempty(tmp_fld) & isunix if exist('/tmp') == 7 tmp_fld = '/tmp'; end; end; if exist(fullfile(tmp_fld,'eeglab.cfg')) load(fullfile(tmp_fld,'eeglab.cfg'),'Path','-mat'); s = ['cd([''' Path '''])']; if exist(Path) == 7, eval(s); end; end; end; catch, end; %% Show the open dialog and save the latest directory to the file % --------------------------------------------------------------- [varargout{1} varargout{2}] = uiputfile(varargin{:}); try, if option_rememberfolder if varargout{1} ~= 0 Path = varargout{2}; try, save(fullfile(tmp_fld,'eeglab.cfg'),'Path','-mat','-V6'); % Matlab 7 catch, try, save(fullfile(tmp_fld,'eeglab.cfg'),'Path','-mat'); catch, error('uigetfile2: save error, out of space or file permission problem'); end end if isunix eval(['cd ' tmp_fld]); system('chmod 777 eeglab.cfg'); end end; end; catch, end; cd(olddir)
github
ZijingMao/baselineeegtest-master
entropy_rej.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/entropy_rej.m
3,641
utf_8
e83760bd8d661f0883b5b955383fa06b
% entropy_rej() - calculation of entropy of a 1D, 2D or 3D array and % rejection of odd last dimension values of the input data array % using the discrete entropy of the values in that dimension % (and using the probability distribution of all columns). % % Usage: % >> [entropy rej] = entropy_rej( signal, threshold, entropy, normalize, discret); % % Inputs: % signal - one dimensional column vector of data values, two % dimensional column vector of values of size % sweeps x frames or three dimensional array of size % component x sweeps x frames. If three dimensional, % all components are treated independently. % threshold - Absolute threshold. If normalization is used then the % threshold is expressed in standard deviation of the % mean. 0 means no threshold. % entropy - pre-computed entropy_rej (only perform thresholding). Default % is the empty array []. % normalize - 0 = do not not normalize entropy. 1 = normalize entropy. % Default is 0. % discret - discretization variable for calculation of the % discrete probability density. Default is 1000 points. % % Outputs: % entropy - entropy (normalized or not) of the single data trials % (same size as signal without the last dimension) % rej - rejection matrix (0 and 1, size of number of rows) % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: realproba() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [ent, rej] = entropy_rej( signal, threshold, oldentropy_rej, normalize, discret ); if nargin < 1 help entropy_rej; return; end; if nargin < 2 threshold = 0; end; if nargin < 3 oldentropy_rej = []; end; if nargin < 4 normalize = 0; end; if nargin < 5 discret = 1000; end; % threshold = erfinv(threshold); if size(signal,2) == 1 % transpose if necessary signal = signal'; end; [nbchan pnts sweeps] = size(signal); ent = zeros(nbchan,sweeps); if ~isempty( oldentropy_rej ) % speed up the computation ent = oldentropy_rej; else for rc = 1:nbchan % COMPUTE THE DENSITY FUNCTION % ---------------------------- [ dataProba sortbox ] = realproba( signal(rc, :), discret ); % compute all entropy % ------------------- for index=1:sweeps datatmp = dataProba((index-1)*pnts+1:index*pnts); ent(rc, index) = - sum( datatmp .* log( datatmp ) ); end; end; % normalize the last dimension % ---------------------------- if normalize switch ndims( signal ) case 2, ent = (ent-mean(ent)) / std(ent); case 3, ent = (ent-mean(ent,2)*ones(1,size(ent,2)))./ ... (std(ent,0,2)*ones(1,size(ent,2))); end; end; end % reject % ------ if threshold ~= 0 rej = abs(ent) > threshold; else rej = zeros(size(ent)); end; return;
github
ZijingMao/baselineeegtest-master
quantile.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/quantile.m
2,747
utf_8
1b58a5e543b13e76f3f75afd5f5f9219
% quantile() - computes the quantiles of the data sample from a distribution X % % Description: % If F is the cumulative distribution function (CDF) of X, % the p-th-quantile Qp of distribution X is the value for which holds % F(x) < p, for x < Qp, and % F(x) >= p, for x >= Qp. % for example, for p = 0.5, Qp is the median of X. p must be in [0..1]. % % Usage: % >> q = quantile( data, pc ); % % Inputs: % data - vector of observations % pc - the quantiles will be estimated at the values in pc [0..1] % % Outputs: % q - pc-th-quantiles of the distribution generating the observation % % Authors: Scott Makeig & Luca Finelli, CNL/Salk Institute-SCCN, August 21, 2002 % % Note: this function overload the function from the statistics toolbox. In % case the statistic toolbox is present, the function from the % statistics toolbox is being called instead. % % See also: % pop_sample(), eeglab() % Copyright (C) Scott Makeig & Luca Finelli, CNL/Salk Institute-SCCN, August 21, 2002 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function q = quantile(data,varargin); % detect overloaded method in stat toolbox curPath = fileparts(which('quantile')); rmpath(curPath); path2 = fileparts(which('quantile')); addpath(curPath); if ~isempty(path2) addpath(path2); q = quantile(data,varargin{:}); return; else pc = varargin{1}; end; if nargin < 2 help quantile; return; end; [prows pcols] = size(pc); if prows ~= 1 & pcols ~= 1 error('pc must be a scalar or a vector.'); end if any(pc > 1) | any(pc < 0) error('pc must be between 0 and 1'); end [i,j] = size(data); sortdata = sort(data); if i==1 | j==1 % if data is a vector i = max(i,j); j = 1; if i == 1, fprintf(' quantile() note: input data is a single scalar!\n') q = data*ones(length(pc),1); % if data is scalar, return it return; end sortdata = sortdata(:); end pt = [0 ((1:i)-0.5)./i 1]; sortdata = [min(data); sortdata; max(data)]; q = interp1(pt,sortdata,pc);
github
ZijingMao/baselineeegtest-master
eventlock.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/eventlock.m
6,609
utf_8
6794a0982011ab97d748d362169961d5
% eventlock() - DEPRECATED: Please use eegalign() instead. % eventlock() - Time lock data epochs to specified event frames or event x-values. % Use to timelock existing data epochs to reaction times or other events % % Usage: % >> [dataout,medval,shiftframes] = eventlock(data,frames,eventframes,medval); % >> [dataout,medval,shiftframes] = eventlock(data,xvals,eventvals,medval); % % Inputs for multi-channel data: % data = input data, size(chans,frames*epochs) % frames = scalar, frames per epoch {0 -> data length} % eventframes = time locking event frames, size(1,epochs) % medval = median eventframe to align to {default: median(eventvals)} % % Inputs for single-channel data: % data = input data, size(frames, epochs) % xvals = vector of epoch time-values, size(1,frames) % OR xvals = [startval nframes srate] (ms N Hz) % eventvals = x-values of time locking events, size(1,epochs) % medval = median event time to align to {default: median(eventvals)} % % Outputs: % dataout = shifted/sorted data out; size(dataout) = size(data) % medval = median eventval (time or frame). Data is aligned to this. % shifts = number of frames shifted for each epoch % (Note: shift > 0 means shift forward|right) % % Note: Missing values are filled with NaN. Some toolbox functions % ( timef(), crossf(), crosscoher() ) handle NaNs correctly. % To truncate to non-NaN values, use % >> dataout = matsel(dataout,frames,... % 1+max(shifts(find(shifts>=0))):frames+min(shifts(find(shifts<=0)))); % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 8/20/99 % Copyright (C) 8/20/99 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 8/23/99 debugged right shifts -sm % 8/25/99 allowed single- or multiple-channel data -sm % 3/9/00 fixed order of dims in help msg -sm & ev % 01-25-02 reformated help & license -ad function [data,medval,shifts] = eventlock(data,arg2,eventvals,medval) VERBOSE=0; % %%%%%%%%%%%%%% Reshape data to (frames,ntrials) %%%%%%%%%%%%% % if nargin < 3 help eventlock return end MULTICHANNEL = 0; if length(arg2) == 1 % then assume multi-channel: size(chans,epochs*frames) MULTICHANNEL = 1; if arg2==0 frames = length(eventvals); % default 1 epoch else frames = arg2; end xvals = 1:frames; else % assume single-channel: size(frames,epochs) MULTICHANNEL = 0; xvals = arg2; if length(xvals) ~= 3 frames = length(xvals); else frames = xvals(2); end end rows = size(data,1); if MULTICHANNEL ntrials = size(data,2)/frames; else ntrials = size(data,2); end if length(xvals) == 3 % assume [startval nvals srate] format srate = xvals(3); endval = xvals(1)+(xvals(2)-1)*xvals(3)+1e-16; xvals = xvals(1):1000/xvals(3):endval; xvals = xvals(1:frames); % make sure of length! else srate = 1000/(xvals(2)-xvals(1)); end if MULTICHANNEL if frames*ntrials ~= size(data,2) fprintf(... 'Input data length (%d) is not a multiple of the eventframes length (%d).\n',... size(data,2), frames); return end elseif frames~= size(data,1) fprintf(... 'Input data frames (%d) is not equal to xvals length (%d).\n',... size(data,1), length(xvals)); return end if length(eventvals) ~= ntrials fprintf(... 'eventlock(): Number of eventvals (%d) must equal number of trials (%d).\n',... length(eventvals), ntrials); return end if MULTICHANNEL fprintf('Input data is %d channels by %d frames * %d trials.\n',... rows,frames,ntrials); else fprintf('Input data is %d frames by %d trials.\n',... frames,ntrials); end % %%%%%%%%%%%%%%%%%%% Align data to eventvals %%%%%%%%%%%%%%%%%%% % if MULTICHANNEL frames = rows*frames; data = reshape(data,frames,ntrials); end % NB: data is now size((chans*)frames,ntrials) aligndata=repmat(nan,frames,ntrials); % begin with matrix of NaN's shifts = zeros(1,ntrials); if ~exist('medval') | isempty(medval) medval= median(eventvals); end [medval medx] = min(abs(medval-xvals)); medval = xvals(medx); if MULTICHANNEL fprintf('Aligning data to median event frame %g.\n',medval); else % SINGLE CHANNEL fprintf('Aligning data to median event time %g.\n',medval); end for i=1:ntrials, %%%%%%%%% foreach trial %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % idx = eventvals(i); % shft = round(medx-idx); [tmpx idx] = min(abs(xvals-eventvals(i))); shft = medx-idx; if VERBOSE;fprintf('Trial %d -shift = %d\n',i,shft);end shifts(i) = shft; if MULTICHANNEL shft = shft*rows; % shift in multiples of chans end if shft>0, % shift right %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if frames > shft aligndata((1+shft):end,i) = data(1:(end-shft),i); else fprintf('No eventlocked data for epoch %d - required shift too large!\n',i); end elseif shft < 0 % shift left %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if frames > -shft aligndata(1:(end+shft),i) = data((1-shft):end,i); else fprintf('No eventlocked data for epoch %d - required shift too large.\n',i); end else % shft == 0 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% aligndata(:,i) = data(:,i); end end % end trial %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fprintf('Shifted trials by %d to %d frames.\n',min(shifts),max(shifts)); if ~MULTICHANNEL fprintf(' %g to %g msec.\n',... 1000/srate*min(shifts),1000/srate*max(shifts)); end data = aligndata; % now data is aligned to sortvar if MULTICHANNEL data = reshape(data,rows,frames/rows*ntrials); % demultiplex channels end
github
ZijingMao/baselineeegtest-master
lookupchantemplate.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/lookupchantemplate.m
988
utf_8
16a6821223a3b7f6603677a26afeaecd
% lookupchantemplate - look up channel template. % % Usage: % [ found transform ] = lookupchantemplate( filename, template_struct); % % Inputs: % filename - channel location file name % template_struct - template strcuture as defined in dipfitdefs % % Outputs: % found - [0|1] 1 if a transformation was found for this template % transform - [array] tranditional tailairach transformation % % Author: Arnaud Delorme, SCCN, INC, 2007 function [allkeywordstrue, transform] = lookupchantemplate(chanfile, tmpl); if nargin < 2 help lookupchantemplate; return; end; allkeywordstrue = 0; transform = []; for ind = 1:length(tmpl) allkeywordstrue = 1; if isempty(tmpl(ind).keywords), allkeywordstrue = 0; end; for k = 1:length(tmpl(ind).keywords) if isempty(findstr(lower(chanfile), lower(tmpl(ind).keywords{k}))), allkeywordstrue = 0; end; end; if allkeywordstrue, transform = tmpl(ind).transform; break; end; end;
github
ZijingMao/baselineeegtest-master
readbdf.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/readbdf.m
3,261
utf_8
e0daaa58677f9efc8fade44506ade229
% readbdf() - Loads selected Records of an EDF or BDF File (European Data Format % for Biosignals) into MATLAB. This function is outdate % Use the functions sopen() and sread() instead % % This program is deprecated (obsolete). Use the sopen() and sread() % function instead % Version 2.11 % 03.02.1998 % Copyright (c) 1997,98 by Alois Schloegl % [email protected] % This program is free software; you can redistribute it and/or % modify it under the terms of the GNU General Public License % as published by the Free Software Foundation; either version 2 % of the License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This program has been modified from the original version for .EDF files % The modifications are to the number of bytes read on line 53 (from 2 to % 3) and to the type of data read - line 54 (from int16 to bit24). Finally the name % was changed from readedf to readbdf % T.S. Lorig Sept 6, 2002 % % Header modified for eeglab() compatibility - Arnaud Delorme 12/02 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [DAT,S]=readbdf(DAT,Records,Mode) disp('This function is outdated'); disp('Use the functions sopen() and sread() instead'); return; if nargin<3 Mode=0; end; EDF=DAT.Head; RecLen=max(EDF.SPR); S=NaN*zeros(RecLen,EDF.NS); DAT.Record=zeros(length(Records)*RecLen,EDF.NS); DAT.Valid=uint8(zeros(1,length(Records)*RecLen)); DAT.Idx=Records(:)'; for nrec=1:length(Records), NREC=(DAT.Idx(nrec)-1); if NREC<0 fprintf(2,'Warning READEDF: invalid Record Number %i \n',NREC);end; fseek(EDF.FILE.FID,(EDF.HeadLen+NREC*EDF.AS.spb*3),'bof'); [s, count]=fread(EDF.FILE.FID,EDF.AS.spb,'bit24'); try, S(EDF.AS.IDX2)=s; catch, error('File is incomplete (try reading begining of file)'); end; %%%%% Test on Over- (Under-) Flow % V=sum([(S'==EDF.DigMax(:,ones(RecLen,1))) + (S'==EDF.DigMin(:,ones(RecLen,1)))])==0; V=sum([(S(:,EDF.Chan_Select)'>=EDF.DigMax(EDF.Chan_Select,ones(RecLen,1))) + ... (S(:,EDF.Chan_Select)'<=EDF.DigMin(EDF.Chan_Select,ones(RecLen,1)))])==0; EDF.ERROR.DigMinMax_Warning(find(sum([(S'>EDF.DigMax(:,ones(RecLen,1))) + (S'<EDF.DigMin(:,ones(RecLen,1)))]')>0))=1; % invalid=[invalid; find(V==0)+l*k]; if floor(Mode/2)==1 for k=1:EDF.NS, DAT.Record(nrec*EDF.SPR(k)+(1-EDF.SPR(k):0),k)=S(1:EDF.SPR(k),k); end; else DAT.Record(nrec*RecLen+(1-RecLen:0),:)=S; end; DAT.Valid(nrec*RecLen+(1-RecLen:0))=V; end; if rem(Mode,2)==0 % Autocalib DAT.Record=[ones(RecLen*length(Records),1) DAT.Record]*EDF.Calib; end; DAT.Record=DAT.Record'; return;
github
ZijingMao/baselineeegtest-master
readedf.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/readedf.m
3,021
utf_8
ea5426379ee917d7284a0b83ba1885fe
% readedf() - read eeg data in EDF format. % % Usage: % >> [data,header] = readedf(filename); % % Input: % filename - file name of the eeg data % % Output: % data - eeg data in (channel, timepoint) % header - structured information about the read eeg data % header.length - length of header to jump to the first entry of eeg data % header.records - how many frames in the eeg data file % header.duration - duration (measured in second) of one frame % header.channels - channel number in eeg data file % header.channelname - channel name % header.transducer - type of eeg electrods used to acquire % header.physdime - details % header.physmin - details % header.physmax - details % header.digimin - details % header.digimax - details % header.prefilt - pre-filterization spec % header.samplerate - sampling rate % % Author: Jeng-Ren Duann, CNL/Salk Inst., 2001-12-21 % Copyright (C) Jeng-Ren Duann, CNL/Salk Inst., 2001-12-21 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 03-21-02 editing header, add help -ad function [data,header] = readedf(filename); if nargin < 1 help readedf; return; end; fp = fopen(filename,'r','ieee-le'); if fp == -1, error('File not found ...!'); return; end hdr = setstr(fread(fp,256,'uchar')'); header.length = str2num(hdr(185:192)); header.records = str2num(hdr(237:244)); header.duration = str2num(hdr(245:252)); header.channels = str2num(hdr(253:256)); header.channelname = setstr(fread(fp,[16,header.channels],'char')'); header.transducer = setstr(fread(fp,[80,header.channels],'char')'); header.physdime = setstr(fread(fp,[8,header.channels],'char')'); header.physmin = str2num(setstr(fread(fp,[8,header.channels],'char')')); header.physmax = str2num(setstr(fread(fp,[8,header.channels],'char')')); header.digimin = str2num(setstr(fread(fp,[8,header.channels],'char')')); header.digimax = str2num(setstr(fread(fp,[8,header.channels],'char')')); header.prefilt = setstr(fread(fp,[80,header.channels],'char')'); header.samplerate = str2num(setstr(fread(fp,[8,header.channels],'char')')); fseek(fp,header.length,-1); data = fread(fp,'int16'); fclose(fp); data = reshape(data,header.duration*header.samplerate(1),header.channels,header.records); temp = []; for i=1:header.records, temp = [temp data(:,:,i)']; end data = temp;
github
ZijingMao/baselineeegtest-master
loadeeg.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/loadeeg.m
10,210
utf_8
3148017a8fe87eb6fa0f26fb433c1800
% loadeeg() - load a binary data file in Neuroscan .eeg file format. % % Usage: % >> signal = loadeeg(filename); % >> [signal, accept, typeeeg, rt, response, chan_names, pnts, ... % ntrials, srate, xmin, xmax] = loadeeg( filename, chanlist, ... % triallist, typerange, accepttype, rtrange, responsetype); % % Inputs: % filename - [string] Input Neuroscan .eeg file % chanlist - [integer array] Only import selected channels % Ex: [3,4:10] {default: 'all'} % triallist - [integer array] Only import selected trials {default: import all} % typerange - [integer array] Only import trials of selected type % {default: import all} % accepttype - [integer array] Only import trials with the selected % 'accept' field values {default: import all} % rtrange - [float array] [min max] (ms) Only import trials with subject % reaction times in this range {default: import all} % responsetype - [integer array] Only import trials with selected % response type values {default: import all} % format - ['short'|'int32'|'auto'] data format. Neuroscan v4.3+ assume 32-bit data % while older versions assume 16-bit. {default: 'auto' = Determine} % % Outputs: % signal - Output signal of size (trials, points) % accept - [1/0] vector of values for the accept field (one per trial) % typeeeg - [Integer] values for the accept type (size 1,trials) % rt - [float] values for the accept rt (size trials) % response - [Integer] values for the accept response (size 1,trials) % chan_names - ['string' array] channel names % pnts - Number of time points per trial % ntrials - Number of trials % srate - Sampling rate (Hz) % xmin - Trial start latency (ms) % xmax - Trial end latency (ms) % % Example: % % Load .eeg data into an array named 'signal' % >> [signal]=loadeeg( 'test.eeg' ); % % Plot the signal in the first channel, first trial % >> plot( signal(1,:) ); % % Author: Arnaud Delorme, CNL, Salk Institute, 2001 % % See also: pop_loadeeg(), eeglab() % .eeg binary file format % data are organised into an array of Number_of_electrode x (Number_of_points_per_trial*Number_of_sweeps) % for a file with 32 electrodes, 700 points per trial and 300 sweeps, the resulting array is % of 32 collumn and 700*300 rows (300 consecutive blocs of 700 points) % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [signal, accept, typeeeg, rt, response, chan_names, pnts, ... nsweeps, rate, xmin, xmax]=loadeeg( FILENAME, chanlist, ... TrialList, typerange, acceptype, rtrange, responsetype, format) if nargin<1 fprintf('Not enought arguments\n'); help loadeeg return; end; if nargin<2 chanlist='all'; end; if nargin<3 TrialList='all'; end; if nargin<4 typerange='all'; end; if nargin<5 acceptype='all'; end; if nargin<6 rtrange ='all'; end; if nargin<7 responsetype='all'; end; if nargin<8 format='auto'; end; format = lower(format); if ~strcmpi(format, 'short') && ~strcmpi(format, 'int32') && ~strcmpi(format, 'auto'), error('loadeeg: format error'); end; % open file for reading % --------------------- fid=fopen(FILENAME,'r','ieee-le'); if fid<0 fprintf('Error LOADEEG: File %s not found\n', FILENAME); return; end; % determine the actual file format if auto is requested %------------------------------------------------------ if strcmpi(format, 'auto') format = 'short'; fseek(fid,12,'bof'); nextfile = fread(fid,1,'long'); if (nextfile > 0) fseek(fid,nextfile+52,'bof'); is32bit = fread(fid,1,'char'); if (is32bit == 1) format = 'int32' end; end; frewind(fid); end; % read general part of the erp header and set variables % ----------------------------------------------------- rev = char(fread(fid, 20, 'uchar'))'; % revision number erp = fread(fid, 342, 'uchar'); % skip the firsts 362 from BOF (368 bytes in orginal comment?) nsweeps = fread(fid, 1, 'ushort'); % number of sweeps erp = fread(fid, 4, 'uchar'); % skip 4 bytes pnts= fread(fid, 1, 'ushort'); % number of point per waveform chan= fread(fid, 1, 'ushort'); % number of channels erp = fread(fid, 4, 'uchar'); % skip 4 bytes rate= fread(fid, 1, 'ushort'); % sample rate (Hz) erp = fread(fid, 127, 'uchar'); % skip 127 bytes xmin= fread(fid, 1, 'float32'); % in s xmax= fread(fid, 1, 'float32'); % in s erp = fread(fid, 387, 'uchar'); % skip 387 bytes fprintf('number of channels : %d\n', chan); fprintf('number of points per trial : %d\n', pnts); fprintf('sampling rate (Hz) : %f\n', rate); fprintf('xmin (s) : %f\n', xmin); fprintf('xmax (s) : %f\n', xmax); % read electrode configuration % ---------------------------- fprintf('Electrode configuration\n'); for elec = 1:chan channel_label_tmp = fread(fid, 10, 'uchar'); chan_names(elec,:) = channel_label_tmp'; for index = 2:9 if chan_names(elec,index) == 0 chan_names(elec,index)=' '; end; end; erp = fread(fid, 47-10, 'uchar'); baseline(elec) = fread(fid, 1, 'ushort'); erp = fread(fid, 10, 'uchar'); sensitivity(elec) = fread(fid, 1, 'float32'); erp = fread(fid, 8, 'uchar'); calib(elec) = fread(fid, 1, 'float32'); fprintf('%s: baseline: %d\tsensitivity: %f\tcalibration: %f\n', ... char(chan_names(elec,1:4)), baseline(elec), sensitivity(elec), calib(elec)); factor(elec) = calib(elec) * sensitivity(elec) / 204.8; end; %fprintf('Electrode configuration\n'); %for elec = 1:chan % erp = fread(fid, 47, 'uchar'); % baseline(elec) = fread(fid, 1, 'ushort'); % erp = fread(fid, 10, 'uchar'); % sensitivity(elec) = fread(fid, 1, 'float32'); % erp = fread(fid, 8, 'uchar'); % calib(elec) = fread(fid, 1, 'float32'); % fprintf('baseline: %d\tsensitivity: %f\tcalibration: %f\n', baseline(elec), sensitivity(elec), calib(elec)); % factor(elec) = calib(elec) * sensitivity(elec) / 204.8; %end; xsize = chan * pnts; buf_size = chan * pnts ; % size in shorts % set tags for conditions % ----------------------- if isstr(chanlist) && strcmpi(chanlist, 'all'), chanlist = [1:chan]; end; if isstr(TrialList) && strcmpi(TrialList, 'all'), trialtagI = 1; else trialtagI = 0; end; if isstr(acceptype) && strcmpi(acceptype, 'all'), acceptagI = 1; else acceptagI = 0; end; if isstr(typerange) && strcmpi(typerange, 'all'), typetagI = 1; else typetagI = 0; end; if isstr(responsetype) && strcmpi(responsetype, 'all'), responsetagI = 1; else responsetagI = 0; end; if isstr(rtrange) && strcmpi(rtrange, 'all'), rttagI = 1; else rttagI = 0; end; count_selected = 1; fprintf('Reserving array (can take some time)\n'); if isstr(TrialList) signal = zeros( chan, pnts*nsweeps); else signal = zeros( chan, pnts*length(TrialList)); end; fprintf('Array reserved, scanning file\n'); for sweep = 1:nsweeps % read sweeps header % ------------------ s_accept = fread(fid, 1, 'uchar'); s_type = fread(fid, 1, 'ushort'); s_correct = fread(fid, 1, 'ushort'); s_rt = fread(fid, 1, 'float32'); s_response = fread(fid, 1, 'ushort'); s_reserved = fread(fid, 1, 'ushort'); unreaded_buf = 1; % store the sweep or reject the sweep % ----------------------------------- if trialtagI trialtag = 1; else trialtag = ismember_bc(sweep, TrialList); end; if acceptagI acceptag = 1; else acceptag = ismember(s_accept, acceptype); end; if typetagI typetag = 1; else typetag = ismember(s_type, typerange); end; if responsetagI responsetag = 1; else responsetag = ismember_bc(s_response, responsetype); end; if rttagI rttag = 1; else rttag = ismember(s_rt, rtrange); end; if typetag if trialtag if acceptag if responsetag if rttag buf = fread(fid, [chan pnts], format); unreaded_buf = 0; % copy information to array % ------------------------- accept(count_selected) = s_accept; typeeeg(count_selected) = s_type; rt(count_selected) = s_rt; response(count_selected) = s_response; % demultiplex the data buffer and convert to microvolts % ----------------------------------------------------- for elec = 1:chan buf(elec, :) = (buf(elec, :)-baseline(elec)-0.0)*factor(elec); end; try signal(:,[((count_selected-1)*pnts+1):count_selected*pnts]) = buf; count_selected = count_selected + 1; if not(mod(count_selected,10)) fprintf('%d sweeps selected out of %d\n', count_selected-1, sweep); end; catch, disp('Warning: File truncated, aborting file read.'); count_selected = count_selected + 1; break; end; end; end; end; end; end; if unreaded_buf if strcmpi(format, 'short'), fseek(fid, buf_size*2, 'cof'); else fseek(fid, buf_size*4, 'cof'); end; end; end; nsweeps = count_selected-1; fclose(fid); % restrincting array % --------------------------------------- fprintf('rereservation of variables\n'); signal = signal(chanlist, 1:(count_selected-1)*pnts); chan_names = chan_names(chanlist,:); return;
github
ZijingMao/baselineeegtest-master
textsc.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/textsc.m
1,965
utf_8
8c2c0fcfccd2bafb12b0c76ab0e73b0c
% textsc() - places text in screen coordinates and places % a title at the top of the figure. % % Usage: % H = textsc(X,Y,TXT) places the text string, TXT % at the normalized coordinates X and Y. H is the % handle to the text object. % % H = textsc(TXT,'title') places a title at the top % of the figure window. This is useful when you % want to place a single title above multiple % subplots. % % Notes: textsc creates an invisible AXES which occupies % the entire FIGURE. The units of the AXES are % normalized (range from 0 to 1). textsc checks % all the children of the current FIGURE to determine % if an AXES exist which meets these criteria already % exist. If one does, then it places the text relative % to that AXES. % % Author: John L. Galenski, January 21, 1994 % Written by John L. Galenski III % All Rights Reserved January 21, 1994 % LDM031695jlg function H = textsc(x,y,txt); % Basic error checking if nargin < 2 y = 'title'; end % Check to see if AXES already exist ch = get(gcf,'Children'); if ~isempty(ch) try ind = cellfun(@(x)isequal('axes', x), get(ch, 'type')); catch ind = cellfun(@(x)isequal('axes', x), {get(ch, 'type')}); % fix Joe Dien bug 1538 end; if any(ind), ch = gca; end; end; ax = findobj(gcf,'Type','axes','Tag','TEXTSC'); if isempty(ax) ax = axes('Units','Normal','Position',[0 0 1 1], ... 'Visible','Off','Tag','TEXTSC'); else axes(ax) end % Place the text if isstr(y) && isstr(x) && strcmp(lower(y),'title') % Subplot title txt = x; x = .5; tmp = text('Units','normal','String','tmp','Position',[0 0 0]); ext = get(tmp,'Extent'); delete(tmp) H = ext(4); y = 1 - .60*H; end h = text(x,y,txt,'VerticalAlignment','Middle', ... 'HorizontalAlignment','Center','interpreter', 'none' ); % Make the original AXES current if ~isempty(ch) set(gcf,'CurrentAxes',ch); end % Check for output if nargout == 1 H = h; end
github
ZijingMao/baselineeegtest-master
runica_mlb.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/runica_mlb.m
42,615
utf_8
84b622d9b09d26c3a20c36f5b695f9b6
% runica() - Perform Independent Component Analysis (ICA) decomposition % of input data using the logistic infomax ICA algorithm of % Bell & Sejnowski (1995) with the natural gradient feature % of Amari, Cichocki & Yang, or optionally the extended-ICA % algorithm of Lee, Girolami & Sejnowski, with optional PCA % dimension reduction. Annealing based on weight changes is % used to automate the separation process. % Usage: % >> [weights,sphere] = runica(data); % train using defaults % else % >> [weights,sphere,compvars,bias,signs,lrates,activations] ... % = runica(data,'Key1',Value1',...); % Input: % data = input data (chans,frames*epochs). % Note that if data consists of multiple discontinuous epochs, % each epoch should be separately baseline-zero'd using % >> data = rmbase(data,frames,basevector); % % Optional keywords [argument]: % 'extended' = [N] perform tanh() "extended-ICA" with sign estimation % N training blocks. If N > 0, automatically estimate the % number of sub-Gaussian sources. If N < 0, fix number of % sub-Gaussian comps to -N [faster than N>0] (default|0 -> off) % 'pca' = [N] decompose a principal component (default -> 0=off) % subspace of the data. Value is the number of PCs to retain. % 'ncomps' = [N] number of ICA components to compute (default -> chans or 'pca' arg) % using rectangular ICA decomposition % 'sphering' = ['on'/'off'] flag sphering of data (default -> 'on') % 'weights' = [W] initial weight matrix (default -> eye()) % (Note: if 'sphering' 'off', default -> spher()) % 'lrate' = [rate] initial ICA learning rate (<< 1) (default -> heuristic) % 'block' = [N] ICA block size (<< datalength) (default -> heuristic) % 'anneal' = annealing constant (0,1] (defaults -> 0.90, or 0.98, extended) % controls speed of convergence % 'annealdeg' = [N] degrees weight change for annealing (default -> 70) % 'stop' = [f] stop training when weight-change < this (default -> 1e-6 % if less than 33 channel and 1E-7 otherwise) % 'maxsteps' = [N] max number of ICA training steps (default -> 512) % 'bias' = ['on'/'off'] perform bias adjustment (default -> 'on') % 'momentum' = [0<f<1] training momentum (default -> 0) % 'specgram' = [srate loHz hiHz frames winframes] decompose a complex time/frequency % transform of the data (Note: winframes must divide frames) % (defaults [srate 0 srate/2 size(data,2) size(data,2)]) % 'posact' = make all component activations net-positive(default 'on'} % 'verbose' = give ascii messages ('on'/'off') (default -> 'on') % % Outputs: [Note: RO means output in reverse order of projected mean variance % unless starting weight matrix passed ('weights' above)] % weights = ICA weight matrix (comps,chans) [RO] % sphere = data sphering matrix (chans,chans) = spher(data) % Note that unmixing_matrix = weights*sphere {if sphering off -> eye(chans)} % compvars = back-projected component variances [RO] % bias = vector of final (ncomps) online bias [RO] (default = zeros()) % signs = extended-ICA signs for components [RO] (default = ones()) % [ -1 = sub-Gaussian; 1 = super-Gaussian] % lrates = vector of learning rates used at each training step [RO] % activations = activation time courses of the output components (ncomps,frames*epochs) % % Authors: Scott Makeig with contributions from Tony Bell, Te-Won Lee, % Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky, Delorme Arnaud, % CNL/The Salk Institute, La Jolla, 1996- % Uses: posact() % Reference (please cite): % % Makeig, S., Bell, A.J., Jung, T-P and Sejnowski, T.J., % "Independent component analysis of electroencephalographic data," % In: D. Touretzky, M. Mozer and M. Hasselmo (Eds). Advances in Neural % Information Processing Systems 8:145-151, MIT Press, Cambridge, MA (1996). % % Toolbox Citation: % % Makeig, Scott et al. "EEGLAB: ICA Toolbox for Psychophysiological Research". % WWW Site, Swartz Center for Computational Neuroscience, Institute of Neural % Computation, University of San Diego California % <www.sccn.ucsd.edu/eeglab/>, 2000. [World Wide Web Publication]. % % For more information: % http://www.sccn.ucsd.edu/eeglab/icafaq.html - FAQ on ICA/EEG % http://www.sccn.ucsd.edu/eeglab/icabib.html - mss. on ICA & biosignals % http://www.cnl.salk.edu/~tony/ica.html - math. mss. on ICA % Copyright (C) 1996 Scott Makeig et al, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %%%%%%%%%%%%%%%%%%%%%%%%%%% Edit history %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % runica() - by Scott Makeig with contributions from Tony Bell, Te-Won Lee % Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky et al. % CNL / Salk Institute 1996-00 % 04-30-96 built from icatest.m and ~jung/.../wtwpwica.m -sm % 07-28-97 new runica(), adds bias (default on), momentum (default off), % extended-ICA (Lee & Sejnowski, 1997), cumulative angledelta % (until lrate drops), keywords, signcount for speeding extended-ICA % 10-07-97 put acos() outside verbose loop; verbose 'off' wasn't stopping -sm % 11-11-97 adjusted help msg -sm % 11-30-97 return eye(chans) if sphering 'off' or 'none' (undocumented option) -sm % 02-27-98 use pinv() instead of inv() to rank order comps if ncomps < chans -sm % 04-28-98 added 'posact' and 'pca' flags -sm % 07-16-98 reduced length of randperm() for kurtosis subset calc. -se & sm % 07-19-98 fixed typo in weights def. above -tl & sm % 12-21-99 added 'specgram' option suggested by Michael Zibulevsky, UNM -sm % 12-22-99 fixed rand() sizing inefficiency on suggestion of Mike Spratling, UK -sm % 01-11-00 fixed rand() sizing bug on suggestion of Jack Foucher, Strasbourg -sm % 12-18-00 test for existence of Sig Proc Tlbx function 'specgram'; improve % 'specgram' option arguments -sm % 01-25-02 reformated help & license -ad % 01-25-02 lowered default lrate and block -ad % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [weights,sphere,meanvar,bias,signs,lrates,activations,y,loglik] = runica(data,p1,v1,p2,v2,p3,v3,p4,v4,p5,v5,p6,v6,p7,v7,p8,v8,p9,v9,p10,v10,p11,v11,p12,v12,p13,v13,p14,v14) if nargin < 1 help runica return end [chans frames] = size(data); % determine the data size urchans = chans; % remember original data channels datalength = frames; if chans<2 fprintf('\nrunica() - data size (%d,%d) too small.\n\n', chans,frames); return end % %%%%%%%%%%%%%%%%%%%%%% Declare defaults used below %%%%%%%%%%%%%%%%%%%%%%%% % MAX_WEIGHT = 1e8; % guess that weights larger than this have blown up DEFAULT_STOP = 1e-6; % stop training if weight changes below this DEFAULT_ANNEALDEG = 60; % when angle change reaches this value, DEFAULT_ANNEALSTEP = 0.98; % anneal by multiplying lrate by this DEFAULT_EXTANNEAL = 0.98; % or this if extended-ICA DEFAULT_MAXSTEPS = 500; % stop training after this many steps DEFAULT_MOMENTUM = 0.0; % default momentum weight DEFAULT_BLOWUP = 1000000000.0; % = learning rate has 'blown up' DEFAULT_BLOWUP_FAC = 0.8; % when lrate 'blows up,' anneal by this fac DEFAULT_RESTART_FAC = 0.9; % if weights blowup, restart with lrate % lower by this factor MIN_LRATE = 0.0001; % if weight blowups make lrate < this, quit MAX_LRATE = 0.1; % guard against uselessly high learning rate DEFAULT_LRATE = 0.00065/log(chans); % heuristic default - may need adjustment % for large or tiny data sets! % DEFAULT_BLOCK = floor(sqrt(frames/4)); % heuristic default DEFAULT_BLOCK = ceil(min(5*log(frames),0.3*frames)); % heuristic % - may need adjustment! % Extended-ICA option: DEFAULT_EXTENDED = 1; % default off DEFAULT_EXTBLOCKS = 1; % number of blocks per kurtosis calculation DEFAULT_NSUB = 0; % initial default number of assumed sub-Gaussians % for extended-ICA DEFAULT_EXTMOMENTUM = 0.5; % momentum term for computing extended-ICA kurtosis MAX_KURTSIZE = 6000; % max points to use in kurtosis calculation MIN_KURTSIZE = 2000; % minimum good kurtosis size (flag warning) SIGNCOUNT_THRESHOLD = 25; % raise extblocks when sign vector unchanged % after this many steps SIGNCOUNT_STEP = 2; % extblocks increment factor DEFAULT_SPHEREFLAG = 'on'; % use the sphere matrix as the default % starting weight matrix DEFAULT_PCAFLAG = 'off'; % don't use PCA reduction DEFAULT_POSACTFLAG = 'on'; % use posact() DEFAULT_VERBOSE = 1; % write ascii info to calling screen DEFAULT_BIASFLAG = 1; % default to using bias in the ICA update rule % %%%%%%%%%%%%%%%%%%%%%%% Set up keyword default values %%%%%%%%%%%%%%%%%%%%%%%%% % if nargout < 2, fprintf('runica() - needs at least two output arguments.\n'); return end epochs = 1; % do not care how many epochs in data pcaflag = DEFAULT_PCAFLAG; sphering = DEFAULT_SPHEREFLAG; % default flags posactflag = DEFAULT_POSACTFLAG; verbose = DEFAULT_VERBOSE; block = DEFAULT_BLOCK; % heuristic default - may need adjustment! lrate = DEFAULT_LRATE; annealdeg = DEFAULT_ANNEALDEG; annealstep = 0; % defaults declared below nochange = NaN; momentum = DEFAULT_MOMENTUM; maxsteps = DEFAULT_MAXSTEPS; weights = 0; % defaults defined below ncomps = chans; biasflag = DEFAULT_BIASFLAG; extended = DEFAULT_EXTENDED; extblocks = DEFAULT_EXTBLOCKS; kurtsize = MAX_KURTSIZE; signsbias = 0.02; % bias towards super-Gaussian components extmomentum= DEFAULT_EXTMOMENTUM; % exp. average the kurtosis estimates nsub = DEFAULT_NSUB; wts_blowup = 0; % flag =1 when weights too large wts_passed = 0; % flag weights passed as argument % %%%%%%%%%% Collect keywords and values from argument list %%%%%%%%%%%%%%% % if (nargin> 1 & rem(nargin,2) == 0) fprintf('runica(): Even number of input arguments???') return end for i = 3:2:nargin % for each Keyword Keyword = eval(['p',int2str((i-3)/2 +1)]); Value = eval(['v',int2str((i-3)/2 +1)]); if ~isstr(Keyword) fprintf('runica(): keywords must be strings') return end Keyword = lower(Keyword); % convert upper or mixed case to lower if strcmp(Keyword,'weights') | strcmp(Keyword,'weight') if isstr(Value) fprintf(... 'runica(): weights value must be a weight matrix or sphere') return else weights = Value; wts_passed =1; end elseif strcmp(Keyword,'ncomps') if isstr(Value) fprintf('runica(): ncomps value must be an integer') return end if ncomps < urchans & ncomps ~= Value fprintf('runica(): Use either PCA or ICA dimension reduction'); return end ncomps = Value; if ~ncomps, ncomps = chans; end elseif strcmp(Keyword,'pca') if ncomps < urchans & ncomps ~= Value fprintf('runica(): Use either PCA or ICA dimension reduction'); return end if isstr(Value) fprintf(... 'runica(): pca value should be the number of principal components to retain') return end pcaflag = 'on'; ncomps = Value; if ncomps > chans | ncomps < 1, fprintf('runica(): pca value must be in range [1,%d]\n',chans) return end chans = ncomps; elseif strcmp(Keyword,'posact') if ~isstr(Value) fprintf('runica(): posact value must be on or off') return else Value = lower(Value); if ~strcmp(Value,'on') & ~strcmp(Value,'off'), fprintf('runica(): posact value must be on or off') return end posactflag = Value; end elseif strcmp(Keyword,'lrate') if isstr(Value) fprintf('runica(): lrate value must be a number') return end lrate = Value; if lrate>MAX_LRATE | lrate <0, fprintf('runica(): lrate value is out of bounds'); return end if ~lrate, lrate = DEFAULT_LRATE; end elseif strcmp(Keyword,'block') | strcmp(Keyword,'blocksize') if isstr(Value) fprintf('runica(): block size value must be a number') return end block = floor(Value); if ~block, block = DEFAULT_BLOCK; end elseif strcmp(Keyword,'stop') | strcmp(Keyword,'nochange') ... | strcmp(Keyword,'stopping') if isstr(Value) fprintf('runica(): stop wchange value must be a number') return end nochange = Value; elseif strcmp(Keyword,'maxsteps') | strcmp(Keyword,'steps') if isstr(Value) fprintf('runica(): maxsteps value must be an integer') return end maxsteps = Value; if ~maxsteps, maxsteps = DEFAULT_MAXSTEPS; end if maxsteps < 0 fprintf('runica(): maxsteps value (%d) must be a positive integer',maxsteps) return end elseif strcmp(Keyword,'anneal') | strcmp(Keyword,'annealstep') if isstr(Value) fprintf('runica(): anneal step value (%2.4f) must be a number (0,1)',Value) return end annealstep = Value; if annealstep <=0 | annealstep > 1, fprintf('runica(): anneal step value (%2.4f) must be (0,1]',annealstep) return end elseif strcmp(Keyword,'annealdeg') | strcmp(Keyword,'degrees') if isstr(Value) fprintf('runica(): annealdeg value must be a number') return end annealdeg = Value; if ~annealdeg, annealdeg = DEFAULT_ANNEALDEG; elseif annealdeg > 180 | annealdeg < 0 fprintf('runica(): annealdeg (%3.1f) is out of bounds [0,180]',... annealdeg); return end elseif strcmp(Keyword,'momentum') if isstr(Value) fprintf('runica(): momentum value must be a number') return end momentum = Value; if momentum > 1.0 | momentum < 0 fprintf('runica(): momentum value is out of bounds [0,1]') return end elseif strcmp(Keyword,'sphering') | strcmp(Keyword,'sphereing') ... | strcmp(Keyword,'sphere') if ~isstr(Value) fprintf('runica(): sphering value must be on, off, or none') return else Value = lower(Value); if ~strcmp(Value,'on') & ~strcmp(Value,'off') & ~strcmp(Value,'none'), fprintf('runica(): sphering value must be on or off') return end sphering = Value; end elseif strcmp(Keyword,'bias') if ~isstr(Value) fprintf('runica(): bias value must be on or off') return else Value = lower(Value); if strcmp(Value,'on') biasflag = 1; elseif strcmp(Value,'off'), biasflag = 0; else fprintf('runica(): bias value must be on or off') return end end elseif strcmp(Keyword,'specgram') | strcmp(Keyword,'spec') if ~exist('specgram') < 2 % if ~exist or defined workspace variable fprintf(... 'runica(): MATLAB Sig. Proc. Toolbox function "specgram" not found.\n') return end if isstr(Value) fprintf('runica(): specgram argument must be a vector') return end srate = Value(1); if (srate < 0) fprintf('runica(): specgram srate (%4.1f) must be >=0',srate) return end if length(Value)>1 loHz = Value(2); if (loHz < 0 | loHz > srate/2) fprintf('runica(): specgram loHz must be >=0 and <= srate/2 (%4.1f)',srate/2) return end else loHz = 0; % default end if length(Value)>2 hiHz = Value(3); if (hiHz < loHz | hiHz > srate/2) fprintf('runica(): specgram hiHz must be >=loHz (%4.1f) and <= srate/2 (%4.1f)',loHz,srate/2) return end else hiHz = srate/2; % default end if length(Value)>3 Hzframes = Value(5); if (Hzframes<0 | Hzframes > size(data,2)) fprintf('runica(): specgram frames must be >=0 and <= data length (%d)',size(data,2)) return end else Hzframes = size(data,2); % default end if length(Value)>4 Hzwinlen = Value(4); if rem(Hzframes,Hzwinlen) % if winlen doesn't divide frames fprintf('runica(): specgram Hzinc must divide frames (%d)',Hzframes) return end else Hzwinlen = Hzframes; % default end Specgramflag = 1; % set flag to perform specgram() elseif strcmp(Keyword,'extended') | strcmp(Keyword,'extend') if isstr(Value) fprintf('runica(): extended value must be an integer (+/-)') return else extended = 1; % turn on extended-ICA extblocks = fix(Value); % number of blocks per kurt() compute if extblocks < 0 nsub = -1*fix(extblocks); % fix this many sub-Gauss comps elseif ~extblocks, extended = 0; % turn extended-ICA off elseif kurtsize>frames, % length of kurtosis calculation kurtsize = frames; if kurtsize < MIN_KURTSIZE fprintf(... 'runica() warning: kurtosis values inexact for << %d points.\n',... MIN_KURTSIZE); end end end elseif strcmp(Keyword,'verbose') if ~isstr(Value) fprintf('runica(): verbose flag value must be on or off') return elseif strcmp(Value,'on'), verbose = 1; elseif strcmp(Value,'off'), verbose = 0; else fprintf('runica(): verbose flag value must be on or off') return end else fprintf('runica(): unknown flag') return end end % %%%%%%%%%%%%%%%%%%%%%%%% Initialize weights, etc. %%%%%%%%%%%%%%%%%%%%%%%% % if ~annealstep, if ~extended, annealstep = DEFAULT_ANNEALSTEP; % defaults defined above else annealstep = DEFAULT_EXTANNEAL; % defaults defined above end end % else use annealstep from commandline if ~annealdeg, annealdeg = DEFAULT_ANNEALDEG - momentum*90; % heuristic if annealdeg < 0, annealdeg = 0; end end if ncomps > chans | ncomps < 1 fprintf('runica(): number of components must be 1 to %d.\n',chans); return end if weights ~= 0, % initialize weights % starting weights are being passed to runica() from the commandline if verbose, fprintf('Using starting weight matrix named in argument list ...\n') end if chans>ncomps & weights ~=0, [r,c]=size(weights); if r~=ncomps | c~=chans, fprintf(... 'runica(): weight matrix must have %d rows, %d columns.\n', ... chans,ncomps); return; end end end; % %%%%%%%%%%%%%%%%%%%%% Check keyword values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if frames<chans, fprintf('runica(): data length (%d) < data channels (%d)!\n',frames,chans) return elseif block < 1, fprintf('runica(): block size %d too small!\n',block) return elseif block > frames, fprintf('runica(): block size exceeds data length!\n'); return elseif floor(epochs) ~= epochs, fprintf('runica(): data length is not a multiple of the epoch length!\n'); return elseif nsub > ncomps fprintf('runica(): there can be at most %d sub-Gaussian components!\n',ncomps); return end; % % adjust nochange if necessary % if isnan(nochange) if ncomps > 32 nochange = 1E-7; nochangeupdated = 1; % for fprinting purposes else nochangeupdated = 1; % for fprinting purposes nochange = DEFAULT_STOP; end; else nochangeupdated = 0; end; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Process the data %%%%%%%%%%%%%%%%%%%%%%%%%% % if verbose, fprintf( ... '\nInput data size [%d,%d] = %d channels, %d frames/n', ... chans,frames,chans,frames); if strcmp(pcaflag,'on') fprintf('After PCA dimension reduction,\n finding '); else fprintf('Finding '); end if ~extended fprintf('%d ICA components using logistic ICA.\n',ncomps); else % if extended fprintf('%d ICA components using extended ICA.\n',ncomps); if extblocks > 0 fprintf(... 'Kurtosis will be calculated initially every %d blocks using %d data points.\n',... extblocks, kurtsize); else fprintf(... 'Kurtosis will not be calculated. Exactly %d sub-Gaussian components assumed.\n',... nsub); end end fprintf('Decomposing %d frames per ICA weight ((%d)^2 = %d weights, %d frames)\n',... floor(frames/ncomps.^2),ncomps.^2,frames); fprintf('Initial learning rate will be %g, block size %d.\n',... lrate,block); if momentum>0, fprintf('Momentum will be %g.\n',momentum); end fprintf( ... 'Learning rate will be multiplied by %g whenever angledelta >= %g deg.\n', ... annealstep,annealdeg); if nochangeupdated fprintf('More than 32 channels: default stopping weight change 1E-7\n'); end; fprintf('Training will end when wchange < %g or after %d steps.\n', ... nochange,maxsteps); if biasflag, fprintf('Online bias adjustment will be used.\n'); else fprintf('Online bias adjustment will not be used.\n'); end end % %%%%%%%%%%%%%%%%%%%%%%%%% Remove overall row means %%%%%%%%%%%%%%%%%%%%%%%% % if verbose, fprintf('Removing mean of each channel ...\n'); end data = data - mean(data')'*ones(1,frames); % subtract row means if verbose, fprintf('Final training data range: %g to %g\n', ... min(min(data)),max(max(data))); end % %%%%%%%%%%%%%%%%%%% Perform PCA reduction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmp(pcaflag,'on') fprintf('Reducing the data to %d principal dimensions...\n',ncomps); [eigenvectors,eigenvalues,data] = pcsquash(data,ncomps); % make data its projection onto the ncomps-dim principal subspace end % %%%%%%%%%%%%%%%%%%% Perform specgram transformation %%%%%%%%%%%%%%%%%%%%%%% % if exist('Specgramflag') == 1 % [P F T] = SPECGRAM(A,NFFT,Fs,WINDOW,NOVERLAP) % MATLAB Sig Proc Toolbox % Hzwinlen = fix(srate/Hzinc); % CHANGED FROM THIS 12/18/00 -sm Hzfftlen = 2^(ceil(log(Hzwinlen)/log(2))); % make FFT length next higher 2^k Hzoverlap = 0; % use sequential windows % % Get freqs and times from 1st channel analysis % [tmp,freqs,tms] = specgram(data(1,:),Hzfftlen,srate,Hzwinlen,Hzoverlap); fs = find(freqs>=loHz & freqs <= hiHz); if isempty(fs) fprintf('runica(): specified frequency range too narrow!\n'); return end; specdata = reshape(tmp(fs,:),1,length(fs)*size(tmp,2)); specdata = [real(specdata) imag(specdata)]; % fprintf(' size(fs) = %d,%d\n',size(fs,1),size(fs,2)); % fprintf(' size(tmp) = %d,%d\n',size(tmp,1),size(tmp,2)); % % Loop through remaining channels % for ch=2:chans [tmp] = specgram(data(ch,:),Hzwinlen,srate,Hzwinlen,Hzoverlap); tmp = reshape((tmp(fs,:)),1,length(fs)*size(tmp,2)); specdata = [specdata;[real(tmp) imag(tmp)]]; % channels are rows end % % Print specgram confirmation and details % fprintf(... 'Converted data to %d channels by %d=2*%dx%d points spectrogram data.\n',... chans,2*length(fs)*length(tms),length(fs),length(tms)); if length(fs) > 1 fprintf(... ' Low Hz %g, high Hz %g, Hz incr %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),freqs(fs(2))-freqs(fs(1)),Hzwinlen); else fprintf(... ' Low Hz %g, high Hz %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),Hzwinlen); end % % Replace data with specdata % data = specdata; datalength=size(data,2); end % %%%%%%%%%%%%%%%%%%% Perform sphering %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmp(sphering,'on'), %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if verbose, fprintf('Computing the sphering matrix...\n'); end sphere = 2.0*inv(sqrtm(cov(data'))); % find the "sphering" matrix = spher() if ~weights, if verbose, fprintf('Starting weights are the identity matrix ...\n'); end weights = eye(ncomps,chans); % begin with the identity matrix else % weights given on commandline if verbose, fprintf('Using starting weights named on commandline ...\n'); end end if verbose, fprintf('Sphering the data ...\n'); end data = sphere*data; % actually decorrelate the electrode signals elseif strcmp(sphering,'off') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~weights if verbose, fprintf('Using the sphering matrix as the starting weight matrix ...\n'); fprintf('Returning the identity matrix in variable "sphere" ...\n'); end sphere = 2.0*inv(sqrtm(cov(data'))); % find the "sphering" matrix = spher() weights = eye(ncomps,chans)*sphere; % begin with the identity matrix sphere = eye(chans); % return the identity matrix else % weights ~= 0 if verbose, fprintf('Using starting weights named on commandline ...\n'); fprintf('Returning the identity matrix in variable "sphere" ...\n'); end sphere = eye(chans); % return the identity matrix end elseif strcmp(sphering,'none') sphere = eye(chans); % return the identity matrix if ~weights if verbose, fprintf('Starting weights are the identity matrix ...\n'); fprintf('Returning the identity matrix in variable "sphere" ...\n'); end weights = eye(ncomps,chans); % begin with the identity matrix else % weights ~= 0 if verbose, fprintf('Using starting weights named on commandline ...\n'); fprintf('Returning the identity matrix in variable "sphere" ...\n'); end end sphere = eye(chans,chans); if verbose, fprintf('Returned variable "sphere" will be the identity matrix.\n'); end end % %%%%%%%%%%%%%%%%%%%%%%%% Initialize ICA training %%%%%%%%%%%%%%%%%%%%%%%%% % lastt=fix((datalength/block-1)*block+1); BI=block*eye(ncomps,ncomps); delta=zeros(1,chans*ncomps); changes = []; degconst = 180./pi; startweights = weights; prevweights = startweights; oldweights = startweights; prevwtchange = zeros(chans,ncomps); oldwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); onesrow = ones(1,block); bias = zeros(ncomps,1); signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1 for k=1:nsub signs(k) = -1; end if extended & extblocks < 0 & verbose, fprintf('Fixed extended-ICA sign assignments: '); for k=1:ncomps fprintf('%d ',signs(k)); end; fprintf('\n'); end signs = diag(signs); % make a diagonal matrix oldsigns = zeros(size(signs));; signcount = 0; % counter for same-signs signcounts = []; urextblocks = extblocks; % original value, for resets old_kk = zeros(1,ncomps); % for kurtosis momemtum % %%%%%%%% ICA training loop using the logistic sigmoid %%%%%%%%%%%%%%%%%%% % if verbose, fprintf('Beginning ICA training ...'); if extended, fprintf(' first training step may be slow ...\n'); else fprintf('\n'); end end step=0; laststep=0; blockno = 1; % running block counter for kurtosis interrupts logstep = 1; % iterator over log likelihood record rand('state',sum(100*clock)); % set the random number generator state to cost_step = 1; % record cost every cost_step iterations % a position dependent on the system clock while step < maxsteps, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% permute=randperm(datalength); % shuffle data order at each step loglik(logstep) = 0; for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%% pause(0); if ~isempty(get(0, 'currentfigure')) & strcmp(get(gcf, 'tag'), 'stop') close; error('USER ABORT'); end; if biasflag u=weights*data(:,permute(t:t+block-1)) + bias*onesrow; else u=weights*data(:,permute(t:t+block-1)); end if ~extended %%%%%%%%%%%%%%%%%%% Logistic ICA weight update %%%%%%%%%%%%%%%%%%% y=1./(1+exp(-u)); % weights = weights + lrate*(BI+(1-2*y)*u')*weights; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% else % Tanh extended-ICA weight update %%%%%%%%%%%%%%%%%%% Extended-ICA weight update %%%%%%%%%%%%%%%%%%% y=tanh(u); % weights = weights + lrate*(BI-signs*y*u'-u*u')*weights; % %%%%%%%%% Calculate log likelihood given our model %%%%%%%%% if mod(step,cost_step) == 0 subgcomp = find(diag(signs) == -1); supergcomp = find(diag(signs) == 1); loglik(logstep) = loglik(logstep) + sum(sum(log(exp(-(1/2)*(u(subgcomp,:)-1).^2) + exp(-(1/2)*(u(subgcomp,:)+1).^2)))); loglik(logstep) = loglik(logstep) + sum(sum(-0.5*u(supergcomp,:).^2 - 2*log(cosh(u(supergcomp,:))))); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end if biasflag if ~extended %%%%%%%%%%%%%%%%%%%%%%%% Logistic ICA bias %%%%%%%%%%%%%%%%%%%%%%% bias = bias + lrate*sum((1-2*y)')'; % for logistic nonlin. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% else % extended %%%%%%%%%%%%%%%%%%% Extended-ICA bias %%%%%%%%%%%%%%%%%%%%%%%%%%%% bias = bias + lrate*sum((-2*y)')'; % for tanh() nonlin. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end end if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%% weights = weights + momentum*prevwtchange; prevwtchange = weights-prevweights; prevweights = weights; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if max(max(abs(weights))) > MAX_WEIGHT wts_blowup = 1; change = nochange; end if extended & ~wts_blowup % %%%%%%%%%%% Extended-ICA kurtosis estimation %%%%%%%%%%%%%%%%%%%%% % if extblocks > 0 & rem(blockno,extblocks) == 0, % recompute signs vector using kurtosis if kurtsize < frames % 12-22-99 rand() size suggestion by M. Spratling rp = fix(rand(1,kurtsize)*datalength); % pick random subset % Accout for the possibility of a 0 generation by rand ou = find(rp == 0); while ~isempty(ou) % 1-11-00 suggestion by J. Foucher rp(ou) = fix(rand(1,length(ou))*datalength); ou = find(rp == 0); end partact=weights*data(:,rp(1:kurtsize)); else % for small data sets, partact=weights*data; % use whole data end m2=mean(partact'.^2).^2; m4= mean(partact'.^4); kk= (m4./m2)-3.0; % kurtosis estimates if extmomentum kk = extmomentum*old_kk + (1.0-extmomentum)*kk; % use momentum old_kk = kk; end signs=diag(sign(kk+signsbias)); % pick component signs if signs == oldsigns, signcount = signcount+1; else signcount = 0; end oldsigns = signs; signcounts = [signcounts signcount]; if signcount >= SIGNCOUNT_THRESHOLD, extblocks = fix(extblocks * SIGNCOUNT_STEP);% make kurt() estimation signcount = 0; % less frequent if sign end % is not changing end % extblocks > 0 & . . . end % if extended %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% blockno = blockno + 1; if wts_blowup break end end % training block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% loglik(logstep) = loglik(logstep) + log(abs(det(weights))); logstep = logstep + 1; if ~wts_blowup oldwtchange = weights-oldweights; step=step+1; % %%%%%%% Compute and print weight and update angle changes %%%%%%%%% % lrates(1,step) = lrate; angledelta=0.; delta=reshape(oldwtchange,1,chans*ncomps); change=delta*delta'; end % %%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%% % if wts_blowup | isnan(change)|isinf(change), % if weights blow up, fprintf(''); step = 0; % start again change = nochange; wts_blowup = 0; % re-initialize variables blockno = 1; lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate weights = startweights; % and original weight matrix oldweights = startweights; change = nochange; oldwtchange = zeros(chans,ncomps); delta=zeros(1,chans*ncomps); olddelta = delta; extblocks = urextblocks; prevweights = startweights; prevwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); bias = zeros(ncomps,1); if extended signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1 for k=1:nsub signs(k) = -1; end signs = diag(signs); % make a diagonal matrix oldsigns = zeros(size(signs));; end if lrate> MIN_LRATE r = rank(data); if r<ncomps fprintf('Data has rank %d. Cannot compute %d components.\n',... r,ncomps); return else fprintf(... 'Lowering learning rate to %g and starting again.\n',lrate); end else fprintf( ... 'runica(): QUITTING - weight matrix may not be invertible!\n'); return; end else % if weights in bounds % %%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%% % if step> 2 angledelta=acos((delta*olddelta')/sqrt(change*oldchange)); end if verbose, places = -floor(log10(nochange)); if step > 2, if ~extended, ps = sprintf('step %d - lrate %5f, wchange %%%d.%df, angledelta %4.1f deg\n', ... step, lrate, places+1,places, degconst*angledelta); else ps = sprintf('step %d - lrate %5f, wchange %%%d.%df, angledelta %4.1f deg, %d subgauss\n',... step, lrate, degconst*angledelta,... places+1,places, (ncomps-sum(diag(signs)))/2); end elseif ~extended ps = sprintf('step %d - lrate %5f, wchange %%%d.%df\n',... step, lrate, places+1,places ); else ps = sprintf('step %5d - lrate %5f, wchange %%%d.%df, %d subgauss\n',... step, lrate, places+1,places, (ncomps-sum(diag(signs)))/2); end % step > 2 fprintf('step %d - lrate %5f, wchange %8.8f, angledelta %5.1f deg, loglik %6.2f, nsub = %d\n', ... step, lrate, change, degconst*angledelta, loglik(step), sum(diag(signs)==-1)); % fprintf(ps,change); % <---- BUG !!!! end; % if verbose % %%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % changes = [changes change]; oldweights = weights; % %%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if degconst*angledelta > annealdeg, lrate = lrate*annealstep; % anneal learning rate olddelta = delta; % accumulate angledelta until oldchange = change; % annealdeg is reached elseif step == 1 % on first step only olddelta = delta; % initialize oldchange = change; end % %%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if step >2 & change < nochange, % apply stopping rule laststep=step; step=maxsteps; % stop when weights stabilize elseif change > DEFAULT_BLOWUP, % if weights blow up, lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying end; % with a smaller learning rate end; % end if weights in bounds end; % end training %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~laststep laststep = step; end; lrates = lrates(1,1:laststep); % truncate lrate history vector % %%%%%%%%%%%%%% Orient components towards max positive activation %%%%%% % if strcmp(posactflag,'on') [activations,winvout,weights] = posact(data,weights); % changes signs of activations and weights to make activations % net rms-positive else activations = weights*data; end % %%%%%%%%%%%%%% If pcaflag, compose PCA and ICA matrices %%%%%%%%%%%%%%% % if strcmp(pcaflag,'on') fprintf('Composing the eigenvector, weights, and sphere matrices\n'); fprintf(' into a single rectangular weights matrix; sphere=eye(%d)\n'... ,chans); weights= weights*sphere*eigenvectors(:,1:ncomps)'; sphere = eye(urchans); end % %%%%%% Sort components in descending order of max projected variance %%%% % if verbose, fprintf(... 'Sorting components in descending order of mean projected variance ...\n'); end % %%%%%%%%%%%%%%%%%%%% Find mean variances %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % meanvar = zeros(ncomps,1); % size of the projections if ncomps == urchans % if weights are square . . . winv = inv(weights*sphere); else fprintf('Using pseudo-inverse of weight matrix to rank order component projections.\n'); winv = pinv(weights*sphere); end for s=1:ncomps if verbose, fprintf('%d ',s); % construct single-component data matrix end % project to scalp, then add row means compproj = winv(:,s)*activations(s,:); meanvar(s) = mean(sum(compproj.*compproj)/(size(compproj,1)-1)); % compute mean variance end % at all scalp channels if verbose, fprintf('\n'); end % %%%%%%%%%%%%%% Sort components by mean variance %%%%%%%%%%%%%%%%%%%%%%%% % [sortvar, windex] = sort(meanvar); windex = windex(ncomps:-1:1); % order large to small meanvar = meanvar(windex); % %%%%%%%%%%%%%%%%%%%%% Filter data using final weights %%%%%%%%%%%%%%%%%% % if nargout>6, % if activations are to be returned if verbose, fprintf('Permuting the activation wave forms ...\n'); end activations = activations(windex,:); else clear activations end weights = weights(windex,:);% reorder the weight matrix bias = bias(windex); % reorder them signs = diag(signs); % vectorize the signs matrix signs = signs(windex); % reorder them % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % return % %%%%%%%%%%%%%%%%%% return nonlinearly-transformed data %%%%%%%%%%%%%%%% % if nargout > 7 u=weights*data + bias*ones(1,frames); y = zeros(size(u)); for c=1:chans for f=1:frames y(c,f) = 1/(1+exp(-u(c,f))); end end end
github
ZijingMao/baselineeegtest-master
eventalign.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/eventalign.m
1,247
utf_8
aae47eaea14a78b572fa7ac4a27e027d
% eventalign - function called by pop_importevent() to find the best % sampling rate ratio to align 2 arrays of data events. % % Author: Arnaud Delorme, SCCN/INC/UCSD, Dec 2003 % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 9 Feb 2002, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function mindiff = eventalign(factor, a, b, measure) diffarray = abs(factor*a-b)'; [allmins poss] = min(diffarray); if strcmpi(measure, 'mean') mindiff = mean(allmins); else mindiff = median(allmins); end;
github
ZijingMao/baselineeegtest-master
writecnt.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/writecnt.m
19,451
utf_8
2103534700b0526bc4c1e243609e91d9
% writecnt() - Write a Neuroscan continuous signal file. % % Usage: % >> writecnt(filename, CNT-dataset, varargin) % % Inputs: % filename - name of the file with extension % dataset - name of the CNT-dataset, a structure with the following fields % cntdataset.header % cntdataset.electloc % cntdataset.data % cntdataset.Teeg % cntdataset.event % cntdataset.tag % cntdataset.endtag % % optional fields % cntdataset.dataformat: 'int32' or 'int16' % % Optional inputs: % 'header': bool, write header. (default=true) % 'electrodes': bool, write electrode information. (default=true) % 'data': bool, write data (default=true) % 'eventtable': bool, write event table (default=true) % 'endtag': bool, write end tag (default=true) % 'append': bool, append requested information to end of file. % (default=false) Requires that file exists. % 't1' - start at time t1, default 0; ERROR WITH NONZERO VALUES % 'sample1' - start at sample1, default 0, overrides t1 ERROR WITH NONZERO VALUES % 'lddur' - duration of segment to load, default = whole file % 'ldnsamples' - number of samples to load, default = whole file, % overrides lddur % 'scale' - ['on'|'off'] scale data to microvolt (default:'on') % 'dataformat' - ['int16'|'int32'] default is 'int16' for 16-bit data. % Use 'int32' for 32-bit data. % % Outputs: % file - file containing NeuroScan CNT file with the continuous % data and other information % % Authors: Sean Fitzgibbon, Arnaud Delorme, Michiel Vestjens and % and Chris Bishop 2000-2014. Maintained by Chris Bishop % (cwbishop_at_ucdavis.edu). % % Known limitations: % For more see http://www.cnl.salk.edu/~arno/cntload/index.html % Copyright (C) 2000 Sean Fitzgibbon, <[email protected]> % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function f = writecnt(filename,cntdataset,varargin) if ~isempty(varargin) WriteOptions=struct(varargin{:}); else WriteOptions = []; end; try, WriteOptions.t1; catch, WriteOptions.t1=0; end try, WriteOptions.sample1; catch, WriteOptions.sample1=[]; end try, WriteOptions.lddur; catch, WriteOptions.lddur=[]; end try, WriteOptions.ldnsamples; catch, WriteOptions.ldnsamples=[]; end try, WriteOptions.scale; catch, WriteOptions.scale='on'; end try, WriteOptions.dataformat; catch, WriteOptions.dataformat='int16'; end %% CATCH FOR KNOWN ERRORS WITH NON ZERO T1 and SAMPLE1 if WriteOptions.t1~=0 || (~isempty(WriteOptions.sample1) && WriteOptions.sample1~=0) error('writecnt:NonzeroStartPosition', 'writecnt cannot deal with nonzero write positions.'); end % if WriteOptions %% ADDITIONAL CHECKS BY CWB % Set defaults for optional inputs if ~isfield(WriteOptions, 'header') || isempty(WriteOptions.header), WriteOptions.header=true; end if ~isfield(WriteOptions, 'electrodes') || isempty(WriteOptions.electrodes), WriteOptions.electrodes=true; end if ~isfield(WriteOptions, 'data') || isempty(WriteOptions.data), WriteOptions.data=true; end if ~isfield(WriteOptions, 'eventtable') || isempty(WriteOptions.eventtable), WriteOptions.eventtable=true; end if ~isfield(WriteOptions, 'append') || isempty(WriteOptions.append), WriteOptions.append=false; end if ~isfield(WriteOptions, 'endtag') || isempty(WriteOptions.endtag), WriteOptions.endtag=true; end %% SIZE OF EVENT DATA (differs based on version of SCAN) sizeEvent1 = 8 ; %%% 8 bytes for Event1 sizeEvent2 = 19 ; %%% 19 bytes for Event2 type='cnt'; if nargin ==1 scan=0; end h = cntdataset.header; e = cntdataset.electloc; dat = cntdataset.data; eT = cntdataset.Teeg; ev2 = cntdataset.event; t = cntdataset.tag; if ~isfield(cntdataset,'endtag') endtag=[]; else endtag=cntdataset.endtag; end %% APPEND DATA? % If not, then open data for general writing if WriteOptions.append fid=fopen(filename,'a+'); % display('Appending requested information ...'); else fid = fopen(filename,'w'); end % if WriteOptions.append % disp(['Writing file ' filename ' ...']) % HEADER : 900 bytes => Starts at 0h, finishes with 383h. if WriteOptions.header fwrite(fid,h.rev,'char'); fwrite(fid,h.nextfile,'long'); fwrite(fid,h.prevfile,'long'); fwrite(fid,h.type,'char'); fwrite(fid,h.id,'char'); fwrite(fid,h.oper,'char'); fwrite(fid,h.doctor,'char'); fwrite(fid,h.referral,'char'); fwrite(fid,h.hospital,'char'); fwrite(fid,h.patient,'char'); fwrite(fid,h.age,'short'); fwrite(fid,h.sex,'char'); fwrite(fid,h.hand,'char'); fwrite(fid,h.med,'char'); fwrite(fid,h.category,'char'); fwrite(fid,h.state,'char'); fwrite(fid,h.label,'char'); fwrite(fid,h.date,'char'); fwrite(fid,h.time,'char'); fwrite(fid,h.mean_age,'float'); fwrite(fid,h.stdev,'float'); fwrite(fid,h.n,'short'); fwrite(fid,h.compfile,'char'); fwrite(fid,h.spectwincomp,'float'); fwrite(fid,h.meanaccuracy,'float'); fwrite(fid,h.meanlatency,'float'); fwrite(fid,h.sortfile,'char'); fwrite(fid,h.numevents,'int'); fwrite(fid,h.compoper,'char'); fwrite(fid,h.avgmode,'char'); fwrite(fid,h.review,'char'); fwrite(fid,h.nsweeps,'ushort'); fwrite(fid,h.compsweeps,'ushort'); fwrite(fid,h.acceptcnt,'ushort'); fwrite(fid,h.rejectcnt,'ushort'); fwrite(fid,h.pnts,'ushort'); fwrite(fid,h.nchannels,'ushort'); fwrite(fid,h.avgupdate,'ushort'); fwrite(fid,h.domain,'char'); fwrite(fid,h.variance,'char'); fwrite(fid,h.rate,'ushort'); fwrite(fid,h.scale,'double'); fwrite(fid,h.veogcorrect,'char'); fwrite(fid,h.heogcorrect,'char'); fwrite(fid,h.aux1correct,'char'); fwrite(fid,h.aux2correct,'char'); fwrite(fid,h.veogtrig,'float'); fwrite(fid,h.heogtrig,'float'); fwrite(fid,h.aux1trig,'float'); fwrite(fid,h.aux2trig,'float'); fwrite(fid,h.heogchnl,'short'); fwrite(fid,h.veogchnl,'short'); fwrite(fid,h.aux1chnl,'short'); fwrite(fid,h.aux2chnl,'short'); fwrite(fid,h.veogdir,'char'); fwrite(fid,h.heogdir,'char'); fwrite(fid,h.aux1dir,'char'); fwrite(fid,h.aux2dir,'char'); fwrite(fid,h.veog_n,'short'); fwrite(fid,h.heog_n,'short'); fwrite(fid,h.aux1_n,'short'); fwrite(fid,h.aux2_n,'short'); fwrite(fid,h.veogmaxcnt,'short'); fwrite(fid,h.heogmaxcnt,'short'); fwrite(fid,h.aux1maxcnt,'short'); fwrite(fid,h.aux2maxcnt,'short'); fwrite(fid,h.veogmethod,'char'); fwrite(fid,h.heogmethod,'char'); fwrite(fid,h.aux1method,'char'); fwrite(fid,h.aux2method,'char'); fwrite(fid,h.ampsensitivity,'float'); fwrite(fid,h.lowpass,'char'); fwrite(fid,h.highpass,'char'); fwrite(fid,h.notch,'char'); fwrite(fid,h.autoclipadd,'char'); fwrite(fid,h.baseline,'char'); fwrite(fid,h.offstart,'float'); fwrite(fid,h.offstop,'float'); fwrite(fid,h.reject,'char'); fwrite(fid,h.rejstart,'float'); fwrite(fid,h.rejstop,'float'); fwrite(fid,h.rejmin,'float'); fwrite(fid,h.rejmax,'float'); fwrite(fid,h.trigtype,'char'); fwrite(fid,h.trigval,'float'); fwrite(fid,h.trigchnl,'char'); fwrite(fid,h.trigmask,'short'); fwrite(fid,h.trigisi,'float'); fwrite(fid,h.trigmin,'float'); fwrite(fid,h.trigmax,'float'); fwrite(fid,h.trigdir,'char'); fwrite(fid,h.autoscale,'char'); fwrite(fid,h.n2,'short'); fwrite(fid,h.dir,'char'); fwrite(fid,h.dispmin,'float'); fwrite(fid,h.dispmax,'float'); fwrite(fid,h.xmin,'float'); fwrite(fid,h.xmax,'float'); fwrite(fid,h.automin,'float'); fwrite(fid,h.automax,'float'); fwrite(fid,h.zmin,'float'); fwrite(fid,h.zmax,'float'); fwrite(fid,h.lowcut,'float'); fwrite(fid,h.highcut,'float'); fwrite(fid,h.common,'char'); fwrite(fid,h.savemode,'char'); fwrite(fid,h.manmode,'char'); fwrite(fid,h.ref,'char'); fwrite(fid,h.rectify,'char'); fwrite(fid,h.displayxmin,'float'); fwrite(fid,h.displayxmax,'float'); fwrite(fid,h.phase,'char'); fwrite(fid,h.screen,'char'); fwrite(fid,h.calmode,'short'); fwrite(fid,h.calmethod,'short'); fwrite(fid,h.calupdate,'short'); fwrite(fid,h.calbaseline,'short'); fwrite(fid,h.calsweeps,'short'); fwrite(fid,h.calattenuator,'float'); fwrite(fid,h.calpulsevolt,'float'); fwrite(fid,h.calpulsestart,'float'); fwrite(fid,h.calpulsestop,'float'); fwrite(fid,h.calfreq,'float'); fwrite(fid,h.taskfile,'char'); fwrite(fid,h.seqfile,'char'); fwrite(fid,h.spectmethod,'char'); fwrite(fid,h.spectscaling,'char'); fwrite(fid,h.spectwindow,'char'); fwrite(fid,h.spectwinlength,'float'); fwrite(fid,h.spectorder,'char'); fwrite(fid,h.notchfilter,'char'); fwrite(fid,h.headgain,'short'); fwrite(fid,h.additionalfiles,'int'); fwrite(fid,h.unused,'char'); fwrite(fid,h.fspstopmethod,'short'); fwrite(fid,h.fspstopmode,'short'); fwrite(fid,h.fspfvalue,'float'); fwrite(fid,h.fsppoint,'short'); fwrite(fid,h.fspblocksize,'short'); fwrite(fid,h.fspp1,'ushort'); fwrite(fid,h.fspp2,'ushort'); fwrite(fid,h.fspalpha,'float'); fwrite(fid,h.fspnoise,'float'); fwrite(fid,h.fspv1,'short'); fwrite(fid,h.montage,'char'); fwrite(fid,h.eventfile,'char'); fwrite(fid,h.fratio,'float'); fwrite(fid,h.minor_rev,'char'); fwrite(fid,h.eegupdate,'short'); fwrite(fid,h.compressed,'char'); fwrite(fid,h.xscale,'float'); fwrite(fid,h.yscale,'float'); fwrite(fid,h.xsize,'float'); fwrite(fid,h.ysize,'float'); fwrite(fid,h.acmode,'char'); fwrite(fid,h.commonchnl,'uchar'); fwrite(fid,h.xtics,'char'); fwrite(fid,h.xrange,'char'); fwrite(fid,h.ytics,'char'); fwrite(fid,h.yrange,'char'); fwrite(fid,h.xscalevalue,'float'); fwrite(fid,h.xscaleinterval,'float'); fwrite(fid,h.yscalevalue,'float'); fwrite(fid,h.yscaleinterval,'float'); fwrite(fid,h.scaletoolx1,'float'); fwrite(fid,h.scaletooly1,'float'); fwrite(fid,h.scaletoolx2,'float'); fwrite(fid,h.scaletooly2,'float'); fwrite(fid,h.port,'short'); fwrite(fid,h.numsamples,'ulong'); fwrite(fid,h.filterflag,'char'); fwrite(fid,h.lowcutoff,'float'); fwrite(fid,h.lowpoles,'short'); fwrite(fid,h.highcutoff,'float'); fwrite(fid,h.highpoles,'short'); fwrite(fid,h.filtertype,'char'); fwrite(fid,h.filterdomain,'char'); fwrite(fid,h.snrflag,'char'); fwrite(fid,h.coherenceflag,'char'); fwrite(fid,h.continuoustype,'char'); fwrite(fid,h.eventtablepos,'long'); fwrite(fid,h.continuousseconds,'float'); fwrite(fid,h.channeloffset,'long'); fwrite(fid,h.autocorrectflag,'char'); fwrite(fid,h.dcthreshold,'uchar'); % = 383H end % if WriteOptions.header % ELECT.DESCRIPTIONS : 75*n.channels bytes. % Starts with 384h, finishes with (899+75*nchannels)dec % 10 channels: 671h % 12 channels: 707h % 24 channels: A8Bh % 32 channels: CE3h % 64 channels: 1643h % 128 channels: 2903h if WriteOptions.electrodes for n = 1:h.nchannels lablength = fwrite(fid,e(n).lab,'char'); fwrite(fid,e(n).reference,'char',10-lablength); fwrite(fid,e(n).skip,'char'); fwrite(fid,e(n).reject,'char'); fwrite(fid,e(n).display,'char'); fwrite(fid,e(n).bad,'char'); fwrite(fid,e(n).n,'ushort'); fwrite(fid,e(n).avg_reference,'char'); fwrite(fid,e(n).clipadd,'char'); fwrite(fid,e(n).x_coord,'float'); fwrite(fid,e(n).y_coord,'float'); fwrite(fid,e(n).veog_wt,'float'); fwrite(fid,e(n).veog_std,'float'); fwrite(fid,e(n).snr,'float'); fwrite(fid,e(n).heog_wt,'float'); fwrite(fid,e(n).heog_std,'float'); fwrite(fid,e(n).baseline,'short'); fwrite(fid,e(n).filtered,'char'); fwrite(fid,e(n).fsp,'char'); fwrite(fid,e(n).aux1_wt,'float'); fwrite(fid,e(n).aux1_std,'float'); fwrite(fid,e(n).senstivity,'float'); fwrite(fid,e(n).gain,'char'); fwrite(fid,e(n).hipass,'char'); fwrite(fid,e(n).lopass,'char'); fwrite(fid,e(n).page,'uchar'); fwrite(fid,e(n).size,'uchar'); fwrite(fid,e(n).impedance,'uchar'); fwrite(fid,e(n).physicalchnl,'uchar'); fwrite(fid,e(n).rectify,'char'); fwrite(fid,e(n).calib,'float'); end % for end % if WriteOptions.electrodes %% SET FILE POINTER TO END OF HEADER INFORMATION % Need to advance the pointer in the event that the header and/or % electrodes have not been written (or have already been written to % file) since the file pointer position is used to determine the % beginning of the data. % % This is a bit clunky, but ensures that 'append' mode works properly % when calculated the number of data points to write. fseek(fid, 900+75*h.nchannels, 'bof'); % finding if 32-bits of 16-bits file % ---------------------------------- begdata = ftell(fid); enddata = h.eventtablepos; % after data if strcmpi(WriteOptions.dataformat, 'int16') nums = (enddata-begdata)/h.nchannels/2; else nums = (enddata-begdata)/h.nchannels/4; end; % number of sample to write % ------------------------- if ~isempty(WriteOptions.sample1) WriteOptions.t1 = WriteOptions.sample1/h.rate; else WriteOptions.sample1 = WriteOptions.t1*h.rate; end; if strcmpi(WriteOptions.dataformat, 'int16') startpos = WriteOptions.t1*h.rate*2*h.nchannels; else startpos = WriteOptions.t1*h.rate*4*h.nchannels; end; if isempty(WriteOptions.ldnsamples) if ~isempty(WriteOptions.lddur) WriteOptions.ldnsamples = round(WriteOptions.lddur*h.rate); else WriteOptions.ldnsamples = nums; end; end; % scaling data from microvolts % ---------------------------- if strcmpi(WriteOptions.scale, 'on') % disp('Scaling data .....') for i=1:h.nchannels bas=e(i).baseline; sen=e(i).senstivity; cal=e(i).calib; mf=sen*(cal/204.8); dat(i,:)=(dat(i,:)/mf)+bas; end end % write data % ---------- % disp('Writing data .....') if type == 'cnt' if WriteOptions.data channel_off = h.channeloffset/2; fseek(fid, startpos, 0); if channel_off <= 1 for temploop =1:WriteOptions.ldnsamples; fwrite(fid, dat(1:h.nchannels, temploop), WriteOptions.dataformat)'; end; else for temploop =1:h.nchannels; fwrite(fid, dat(temploop, 1:channel_off), WriteOptions.dataformat)'; end; counter = 1; while counter*channel_off < WriteOptions.ldnsamples for temploop =1:h.nchannels; fwrite(fid, dat(temploop, counter*channel_off+1:counter*channel_off+channel_off), WriteOptions.dataformat)'; end; counter = counter + 1; end; end; end % if WriteOptions.data if WriteOptions.eventtable % write event table % ----------------- frewind(fid); fseek(fid,h.eventtablepos,'bof'); disp('Writing Event Table...') fwrite(fid,eT.teeg,'uchar'); fwrite(fid,eT.size,'ulong'); fwrite(fid,eT.offset,'ulong'); if eT.teeg==2 nevents=eT.size/sizeEvent2; elseif eT.teeg==1 nevents=eT.size/sizeEvent1; else disp('No !!! teeg <> 2 and teeg <> 1'); ev2 = []; end % if eT.teeg==2 %%%% to change offset in points back to bytes if ~isempty(ev2) ev2p=ev2; ioff=900+(h.nchannels*75); %% initial offset : header + electordes desc % 140219 CWB: Writing events to file in byte form depends on % data precision. Need to select the correct data precision % here. if strcmpi(WriteOptions.dataformat, 'int16') NBYTES=2; elseif strcmpi(WriteOptions.dataformat, 'int32') NBYTES=4; end % if strcmpi for i=1:nevents ev2p(i).offset=((ev2p(i).offset + WriteOptions.sample1)*NBYTES*h.nchannels) +ioff; %% 2 short int end end ev2 = ev2p; end; % if ~isempty(ev2) if eT.teeg==2 nevents=eT.size/sizeEvent2; for i=1:nevents ev2(i).stimtype = fwrite(fid,ev2(i).stimtype,'ushort'); ev2(i).keyboard = fwrite(fid,ev2(i).keyboard,'char'); ev2(i).keypad_accept = fwrite(fid,ev2(i).keypad_accept,'char'); ev2(i).offset = fwrite(fid,ev2(i).offset,'long'); ev2(i).type = fwrite(fid,ev2(i).type,'short'); ev2(i).code = fwrite(fid,ev2(i).code,'short'); ev2(i).latency = fwrite(fid,ev2(i).latency,'float'); ev2(i).epochevent = fwrite(fid,ev2(i).epochevent,'char'); ev2(i).accept = fwrite(fid,ev2(i).accept,'char'); ev2(i).accuracy = fwrite(fid,ev2(i).accuracy,'char'); end % for i=1:nevents elseif eT.teeg==1 nevents=eT.size/sizeEvent1; for i=1:nevents ev2(i).stimtype = fwrite(fid,ev2(i).stimtype,'ushort'); ev2(i).keyboard = fwrite(fid,ev2(i).keyboard,'char'); ev2(i).keypad_accept = fwrite(fid,ev2(i).keypad_accept,'char'); ev2(i).offset = fwrite(fid,ev2(i).offset,'long'); end % for i=1:nevents else disp('No !!! teeg <> 2 and teeg <> 1'); ev2 = []; end %if/elseif/else end % if WriteOptions.eventtable end % if type=='cnt' %% WE ARE AT h.nextfile position here % So there has to be additional information at the end of the CNT file % that is NOT read in by loadcnt.m but we ultimately need in order to % rewrite the file. % % Ah, there IS more information that loadcnt is not actually reading, % although it depends on some of it to determine if the data are 16 or 32 % bit. % % CWB put this information in a junk field (cntdataset.junk) that can be % written if it's present. if WriteOptions.endtag if size(endtag,1)>1 fwrite(fid,endtag); else fwrite(fid,t,'char'); end end % if WriteOptions.endtag fclose(fid); % disp(['Finished writing file ' filename ' ...'])
github
ZijingMao/baselineeegtest-master
topo2sph.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/topo2sph.m
3,809
utf_8
e3c2ecaa32b502b60d330735ade6b95d
% topo2sph() - convert a topoplot() style 2-D polar-coordinate % channel locations file to a 3-D spherical-angle % file for use with headplot() % Usage: % >> [c h] = topo2sph('eloc_file','eloc_outfile', method, unshrink); % >> [c h] = topo2sph( topoarray, method, unshrink ); % % Inputs: % 'eloc_file' = filename of polar 2-D electrode locations file used by % topoplot(). See >> topoplot example or cart2topo() % 'eloc_outfile' = output file of 3-D electrode locations in spherical angle % coords. for use in headplot(). % topoarray = polar array of 2-D electrode locations, with polar angle % in the first column and radius in the second one. % method = [1|2] 1 is for Besa compatibility, 2 is for % compatibility with Matlab function cart2sph(). {default: 2} % unshrink = [0<real<1] unshrink factor. Enter a shrink factor used % to convert spherical to topo (see sph2topo()). Only % implemented for 'method' 1 (above). Electrode 'shrink' % is now deprecated. See >> help topoplot % Outputs: % c = coronal rotation % h = horizontal rotation % % Author: Scott Makeig & Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 1999 % % See also: sph2topo(), cart2topo() % Copyright (C) 1999 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 3-16-00 changed name to topo2sph() for compatibility with cart2topo() -sm % 01-25-02 reformated help & license -ad % 03-22-02 complete remodeling for returning arguments and taking arrays -ad function [c, h] = topo2sph(eloc_locs,eloc_angles, method, unshrink) MAXCHANS = 1024; if nargin < 1 help topo2sph; return; end; if nargin > 1 && ~isstr(eloc_angles) if nargin > 2 unshrink = method; end; method = eloc_angles; else method = 2; end; if isstr(eloc_locs) fid = fopen(eloc_locs); if fid<1, fprintf('topo2sph()^G: cannot open eloc_loc file (%s)\n',eloc_locs) return end E = fscanf(fid,'%d %f %f %s',[7 MAXCHANS]); E = E'; fclose(fid); else E = eloc_locs; E = [ ones(size(E,1),1) E ]; end; if nargin > 1 & isstr(eloc_angles) if exist(eloc_angles)==2, fprintf('topo2sph: eloc_angles file (%s) already exists and will be erased.\n',eloc_angles); end fid = fopen(eloc_angles,'a'); if fid<1, fprintf('topo2sph()^G: cannot open eloc_angles file (%s)\n',eloc_angles) return end end; if method == 2 t = E(:,2); % theta r = E(:,3); % radius h = -t; % horizontal rotation c = (0.5-r)*180; else for e=1:size(E,1) % (t,r) -> (c,h) t = E(e,2); % theta r = E(e,3); % radius r = r*unshrink; if t>=0 h(e) = 90-t; % horizontal rotation else h(e) = -(90+t); end if t~=0 c(e) = sign(t)*180*r; % coronal rotation else c(e) = 180*r; end end; t = t'; r = r'; end; for e=1:size(E,1) if nargin > 1 & isstr(eloc_angles) chan = E(e,4:7); fprintf('%d %g %g %s\n',E(e,1),c(e),h(e),chan); fprintf(fid,'%d %g %g %s\n',E(e,1),c(e),h(e),chan); end; end
github
ZijingMao/baselineeegtest-master
spher.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/spher.m
365
utf_8
0308dc258a2489d286651ab9504dbea9
% spher() - return the sphering matrix for given input data % % Usage: % % >> sphere_matrix = spher(data); % % Reference: T. Bell (1996) - - - % % S. Makeig CNL / Salk Institute, La Jolla CA 7-17-97 function sphere = spher(data) if nargin<1 | size(data,1)<1 help spher return end sphere = 2.0*inv(sqrtm(cov(data'))); % return the "sphering" matrix
github
ZijingMao/baselineeegtest-master
copyaxis.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/copyaxis.m
3,016
utf_8
ab1ad1b3dfa8e1a8ff4adaa6b8902625
% copyaxis() - helper function for axcopy() % % Usage: >> copyaxis(); % >> copyaxis( command ); % % Note: The optional command option (a string that will be evaluated % when the figure is created allows to customize display). % % Author: Tzyy-Ping Jung, SCCN/INC/UCSD, La Jolla, 2000 % % See also: axcopy() % Copyright (C) 3-16-2000 Tzyy-Ping Jung, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 02-16-02 added the ignore parent size option -ad % 03-11-02 remove size option and added command option -ad function copyaxis(command) OFF_STD = 0.25; % std dev of figure offset MIN_OFF = 0.15; % minimum offset for new figure BORDER = 0.04; % screen edge tolerance fig=gcf; sel=gca; % % Get position for new figure % set(fig,'Units','normalized'); place=get(fig,'Position'); axiscolor=get(fig,'Color'); cmap=colormap; newxy = (OFF_STD*randn(1,2))+place(1,1:2); newx=newxy(1);newy=newxy(2); if abs(newx-place(1,1))<MIN_OFF, newx=place(1,1)+sign(newx-place(1,1))*MIN_OFF;end if abs(newy-place(1,1))<MIN_OFF, newy=place(1,1)+sign(newy-place(1,1))*MIN_OFF;end if newx<BORDER, newx=BORDER; end if newy<BORDER, newy=BORDER; end if newx+place(3)>1-BORDER, newx=1-BORDER-place(3); end if newy+place(4)>1-BORDER, newy=1-BORDER-place(4); end newfig=figure('Units','Normalized','Position',[newx,newy,place(1,3:4)]); % % Copy object to new figure % set(newfig,'Color',axiscolor); copyobj(sel,newfig);set(gca,'Position',[0.130 0.110 0.775 0.815]); colormap(cmap); % % Increase font size % set(findobj('parent',newfig,'type','axes'),'FontSize',14); set(get(gca,'XLabel'),'FontSize',16) set(get(gca,'YLabel'),'FontSize',16) set(get(gca,'Title'),'Fontsize',16); % % Add xtick and ytick labels if missing % if strcmp(get(gca,'Box'),'on') set(gca,'xticklabelmode','auto') set(gca,'xtickmode','auto') set(gca,'yticklabelmode','auto') set(gca,'ytickmode','auto') end % % Turn on zoom in the new figure % zoom on; % % Turn off the axis copy for the new figure % hndl= findobj('parent',newfig,'type','axes'); set(hndl,'ButtonDownFcn','','Selected','off'); for a=1:length(hndl) % make all axes visible set(findobj('parent',hndl(a)),'ButtonDownFcn','','Selected','off'); end % % Execute additional command if present % if exist('command') == 1 eval(command); end;
github
ZijingMao/baselineeegtest-master
eegplot_readkey.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/eegplot_readkey.m
231
utf_8
a65a871257ff3e64f58f29ff2c190071
% eegplot helper function to read key strokes function eegplot_readkey(src,evnt) if strcmp(evnt.Key, 'rightarrow')==1 eegplot('drawp',4); elseif strcmp(evnt.Key, 'leftarrow')==1 eegplot('drawp',1); end
github
ZijingMao/baselineeegtest-master
moveaxes.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/moveaxes.m
2,214
utf_8
91a62b9d7772562c4900a56b35247ae9
% moveaxes() - move, resize, or copy Matlab axes using the mouse % % Usage: >> moveaxes % >> moveaxes(fig) % >> moveaxes off % % Note: clicking the left mouse button selects an axis % dragging the left mouse button resizes a selected axis % dragging the right mouse button copies a selected axis % clicking the middle mouse button deselects a selected axis % % Authors: Colin Humphries & Scott Makeig, CNL / Salk Institute, La Jolla % Copyright (C) Colin Humphries & Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad function moveaxes(fig) if nargin<1 fig = gcf; end if ~isstr(fig) tmp = findobj('tag','moveaxes'); if ~isempty(tmp) % turn off previous moveaxes Tags ax = get(tmp,'children'); set(ax,'ButtonDownFcn','','Selected','Off'); set(tmp,'Tag','','UserData',[]); end ax = findobj('parent',fig,'type','axes'); for a=1:length(ax) % make all axes visible axvis = get(ax(a),'visible'); set(ax(a),'visible','on','UserData',axvis); end set(ax,'ButtonDownFcn','selectmoveresize'); set(fig,'UserData',ax,'Tag','moveaxes'); elseif strcmp(fig,'off') fig=findobj('Tag','moveaxes'); ax = get(fig,'UserData'); for a=1:length(ax) % reset original axis visibility axvis= get(ax(a),'UserData') set(ax(a),'visible',axvis); end set(ax,'ButtonDownFcn','','Selected','off'); set(fig,'Tag','','UserData',[]); end
github
ZijingMao/baselineeegtest-master
parsetxt.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/parsetxt.m
1,595
utf_8
daf4054768bfdb3e9112cbb24966ca21
% parsetxt() - parse text input into cell array % % Usage: >> cellarray = parsetxt( txt, delims ); % % Inputs: % txt - input text % delims - optional char array of delimiters (default: [' ' ',' 9]); % % Note: commas, and simple quotes are ignored % % Author: Arnaud Delorme, CNL / Salk Institute, 18 April 2002 % Copyright (C) 18 April 2002 Arnaud Delorme, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function cellarray = parsetxt(txt, delims); if nargin < 1 help parsetxt; return; end; if nargin < 2 delims = [' ' ',' 9 '"' '''' ]; end; cellarray = {}; tmptxt = ''; for index =1:length(txt) if ~isempty(findstr(txt(index), delims)) if ~isempty(tmptxt), cellarray = { cellarray{:}, tmptxt }; end; tmptxt = ''; else tmptxt = [ tmptxt txt(index) ]; end; end; if ~isempty(tmptxt) cellarray = { cellarray{:}, tmptxt }; end; return;
github
ZijingMao/baselineeegtest-master
coregister.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/coregister.m
39,258
utf_8
30dc4502a571138ba3dc0f6d300295b3
% coregister() - Co-register measured or template electrode locations with a % a reference channel locations file. For instance if you % want to perform dipole modeling you have to coregister % (align) your channel electrodes with the model (and the % easiest way to do that is to coregister your channel % electrodes with the electrodes file associated with the % model. To use coregister(), one may for instance use the default % MNI head and 10-5 System locations from Robert Oostenveld, used in % the dipfit2() dipole modeling function as a reference. % Use coregister() to linearly align or nonlinearly warp % subsequently recorded or nominally identified (e.g., 'Cz') sets of % channel head locations to the reference locations. % Both channel locations and/or fiducial (non-electrode) % locations can then be used by coregister() to linearly align % or nonlinearly warp a given or measured montage to the reference % locations. In its (default) manual mode, coregister() produces % an interactive gui showing the imported and reference channel % locations on the imported head mesh (if any), allowing the user % to make additional manual adjustments using gui text entry boxes, % and to rotate the display using the mouse. % Usage: % >> coregister(EEG.chanlocs); % Show channel locations in the coregister() % % gui, for align, warp, or manual mode co-registration with the % % dipfit2() model head mesh and 10-5 System reference locations. % % Note: May need to scale channel x,y,z positions by 100 to see % % the imported locations in the default dipfit2() head mesh. % % >> [chanlocs_out transform] = coregister( chanlocs, reflocs, 'key', 'val' ) % % Perform custom co-registration to a reference locations and % % (optional) head mesh. If a ('warp' or 'alignfid') mode is % % specified, no gui window is produced. % Inputs: % chanlocs - (EEG.chanlocs) channel locations structure (or file) to align % For file structure, see >> headplot example % or >> headplot cartesian % reflocs - reference channel locations structure (or file) associated % with the head mesh ('mesh' below) {default|[] -> 10-5 System locs} % % Optional 'keywords' and arguments ([ ]): % 'mesh' - [cell array|string] head mesh. May contain {points triangles} % or {points triangles normals} (see >> help plotmesh % for details). May also be the name of a head mesh .mat % file (several formats recognized). By default, loads the % dipfit2() MNI head mesh file. Compare 'mheadnew.mat', the % mesh used by headplot(); 'mesh',[] shows no head mesh. % 'warpmethod' - ['rigidbody'|'globalrescale'|'traditional'|'nonlin1'| % 'nonlin2'|'nonlin3'|'nonlin4'|'nonlin5'] % 'traditional' calls the dipfit2.* function traditionaldipfit() % all others are enacted by electrodenormalize() % {default: 'traditional} % 'transform' - [real array] homogenous transformation matrix (>>help % electrodenormalize) or a 1x9 matrix containing traditional % 9-parameter "Talairach model" transformation (>> help traditional) % used to calculate locs_out. % 'chaninfo1' - [EEG.chaninfo struct] channel information structure for the % montage to be coregistered. May contain (no-electrode) fiducial % locations. % 'chaninfo2' - [EEG.chaninfo struct] channel information structure for % the reference montage. % 'helpmsg' - ['on'|'off'] pop-up help message when calling function. % {default: 'off'} % % Optional 'keywords' for MANUAL MODE (default): % 'manual' - ['on'|'off'] Pops up the coregister() gui window to % allow viewing the current alignment, performing 'alignfid' or % 'warp' mode co-registration, and making manual % adjustments. Default if 'on'. % % Optional 'keywords' for ALIGN MODE: % 'alignfid' - {cell array of strings} = labels of (fiducial) channels to use % as common landmarks for aligning the new channel locations to % the reference locations. These labels must be in both channel % locations (EEG.chanlocs) and/or EEG.chaninfo structures (see % 'chaninfo1' and 'chaninfo2' below). Will then apply a linear % transform including translation, rotation, and/or uniform % scaling so as to best match the two sets of landmarks. % See 'autoscale' below. % 'autoscale' - ['on'|'off'] autoscale electrode radius when aligning % fiducials. {default: 'on'} % % Optional 'keywords' for WARP MODE: % 'warp' - {cell array of strings} channel labels used for non-linear % warping of the new channel locations to reference locations. % For example: Specifying all 10-20 channel labels will % nonlinearly warp the 10-20 channel locations in the new % chanlocs to the 10-20 locations in the reference chanlocs. % Locations of other channels in the new chanlocs will be % adjusted so as to produce a smooth warp. Entering the % string 'auto' will automatically select the common channel % labels. % % Outputs: % chanlocs_out - transformed input channel locations (chanlocs) structure % transform - transformation matrix. Use traditionaldipfit() to convert % this to a homogenous transformation matrix used in % 3-D plotting functions such as headplot(). % % Note on how to create a template: % (1) Extract a head mesh from a subject MRI (possibly in % Matlab using the function isosurface). % (2) Measure reference locations on the subject's head. % (3) Align these locations to the extracted subject head mesh % (using the coregister() graphic interface). The aligned locations % then become reference locations for this mesh. % % Example: % % This return the coregistration matrix to the MNI brain % dipfitdefs; % [newlocs transform] = coregister(EEG.chanlocs, template_models(2).chanfile, ... % 'warp', 'auto', 'manual', 'off'); % % % This pops-up the coregistration window for the BEM (MNI) model % dipfitdefs; % [newlocs transform] = coregister(EEG.chanlocs, template_models(2).chanfile, ... % 'mesh', template_models(2).hdmfile); % % See also: traditionaldipfit(), headplot(), plotmesh(), electrodenormalize(). % % Note: Calls Robert Oostenveld's FieldTrip coregistration functions for % automatic coregistration. % % Author: Arnaud Delorme, SCCN/INC/UCSD, 2005-06 % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, 2005, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % Here we bypass channel info % 'chaninfo' - [struct] channel information structure for the first % dataset (may use a cell array { struct struct } to enter % channel location info for both channel location struct. % function [ chanlocs1, transformmat ] = coregister(chanlocs1, chanlocs2, varargin) if nargin < 1 help coregister error('Not enough inputs'); end if nargin < 2 chanlocs2 = []; end % manually for s1: transf = [4 0 -50 -0.3 0 -1.53 1.05 1.1 1.1] % manually for s2: transf = [-4 -6 -50 -0.37 0 -1.35 1.1 1.15 1.1] if isempty(chanlocs2) dipfitdefs; chanlocs2 = template_models(1).chanfile; end % undocumented commands run from GUI % ---------------------------------- if ischar(chanlocs1) if ~strcmpi(chanlocs1, 'redraw') & ~strcmpi(chanlocs1, 'fiducials') & ~strcmpi(chanlocs1, 'warp') chanlocs1 = readlocs(chanlocs1); else com = chanlocs1; fid = chanlocs2; % update GUI % ---------- if strcmpi(com, 'redraw'), redrawgui(fid); return; end; % select electrodes and warp montage % ---------------------------------- dat = get(fid, 'userdata'); if strcmpi(com, 'fiducials') [clist1 clist2] = pop_chancoresp( dat.elec1, dat.elec2, 'autoselect', 'fiducials'); try, [ tmp transform ] = align_fiducials(dat.elec1, dat.elec2, dat.elec1.label(clist1), dat.elec2.label(clist2)); if ~isempty(transform), dat.transform = transform; end; catch, warndlg2(strvcat('Transformation failed', lasterr)); end; elseif strcmpi(com, 'warp') [clist1 clist2] = pop_chancoresp( dat.elec1, dat.elec2, 'autoselect', 'all'); % copy electrode names if ~isempty(clist1) tmpelec2 = dat.elec2; for index = 1:length(clist2) tmpelec2.label{clist2(index)} = dat.elec1.label{clist1(index)}; end; %try, [ tmp dat.transform ] = warp_chans(dat.elec1, tmpelec2, tmpelec2.label(clist2), 'traditional'); %catch, % warndlg2(strvcat('Transformation failed', lasterr)); %end; end; end; set(fid, 'userdata', dat); redrawgui(fid); return; end; end; % check input arguments % --------------------- % defaultmesh = 'D:\matlab\eeglab\plugins\dipfit2.0\standard_BEM\standard_vol.mat'; defaultmesh = 'standard_vol.mat'; g = finputcheck(varargin, { 'alignfid' 'cell' {} {}; 'warp' { 'string','cell' } { {} {} } {}; 'warpmethod' 'string' {'rigidbody', 'globalrescale', 'traditional', 'nonlin1', 'nonlin2', 'nonlin3', 'nonlin4', 'nonlin5'} 'traditional'; 'chaninfo1' 'struct' {} struct('no', {}); % default empty structure 'chaninfo2' 'struct' {} struct('no', {}); 'transform' 'real' [] []; 'manual' 'string' { 'on','off' } 'on'; % -> pop up window 'autoscale' 'string' { 'on','off' } 'on'; 'helpmsg' 'string' { 'on','off' } 'off'; 'mesh' '' [] defaultmesh }); if ischar(g), error(g); end; % load mesh if any % ---------------- if ~isempty(g.mesh) if ischar(g.mesh) try g.mesh = load(g.mesh); catch, g.mesh = []; end; end; if ischar(g.mesh) if ~exist(g.mesh,'file') fprintf('coregister(): mesh file not found\n'); end end if ~isempty(g.mesh) if isstruct(g.mesh) if isfield(g.mesh, 'vol') if isfield(g.mesh.vol, 'r') [X Y Z] = sphere(50); dat.meshpnt = { X*max(g.mesh.vol.r) Y*max(g.mesh.vol.r) Z*max(g.mesh.vol.r) }; dat.meshtri = []; else dat.meshpnt = g.mesh.vol.bnd(1).pnt; dat.meshtri = g.mesh.vol.bnd(1).tri; end; elseif isfield(g.mesh, 'bnd') dat.meshpnt = g.mesh.bnd(1).pnt; dat.meshtri = g.mesh.bnd(1).tri; elseif isfield(g.mesh, 'TRI1') dat.meshpnt = g.mesh.POS; dat.meshtri = g.mesh.TRI1; elseif isfield(g.mesh, 'vertices') dat.meshpnt = g.mesh.vertices; dat.meshtri = g.mesh.faces; else error('Unknown Matlab mesh file'); end; else dat.meshpnt = g.mesh{1}; dat.meshtri = g.mesh{2}; end; else dat.meshpnt = []; dat.meshtri = []; end; else dat.meshpnt = []; dat.meshtri = []; end; % transform to arrays chanlocs1 % ------------------------- TMP = eeg_emptyset; [TMP.chanlocs tmp2 tmp3 ind1] = readlocs(chanlocs1); TMP.chaninfo = g.chaninfo1; TMP.nbchan = length(TMP.chanlocs); cfg = eeglab2fieldtrip(TMP, 'chanloc_withfid'); elec1 = cfg.elec; % transform to arrays chanlocs2 % ------------------------- if ~isempty(chanlocs2) TMP = eeg_emptyset; [TMP.chanlocs tmp2 tmp3 ind1] = readlocs(chanlocs2); TMP.chaninfo = g.chaninfo2; TMP.nbchan = length(TMP.chanlocs); cfg = eeglab2fieldtrip(TMP, 'chanloc_withfid'); elec2 = cfg.elec; else elec2 = []; dat.transform = [ 0 0 0 0 0 0 1 1 1 ]; end; % copy or compute alignment matrix % -------------------------------- if ~isempty(g.transform) dat.transform = g.transform; else % perfrom alignment % ----------------- if strcmpi(g.autoscale, 'on') avgrad1 = sqrt(sum(elec1.pnt.^2,2)); avgrad2 = sqrt(sum(elec2.pnt.^2,2)); ratio = mean(avgrad2)/mean(avgrad1); else ratio = 1; end; if ~isempty(g.alignfid) % autoscale % --------- [ electransf transform ] = align_fiducials(electmp, elec2, g.alignfid); if ~isempty(transform), dat.transform = [ transform(1:6)' ratio ratio ratio ]; end; elseif ~isempty(g.warp) if ischar(g.warp) [clist1 clist2] = pop_chancoresp( elec1, elec2, 'autoselect', 'all', 'gui', 'off'); % copy electrode names if isempty(clist1) disp('Warning: cannot wrap electrodes (no common channel labels)'); else tmpelec2 = elec2; for index = 1:length(clist2) tmpelec2.label{clist2(index)} = elec1.label{clist1(index)}; end; try, [ electransf dat.transform ] = warp_chans(elec1, tmpelec2, tmpelec2.label(clist2), 'traditional'); catch, warndlg2(strvcat('Transformation failed', lasterr)); end; end; else [ electransf dat.transform ] = warp_chans(elec1, elec2, g.warp, g.warpmethod); end; else dat.transform = [0 0 0 0 0 0 ratio ratio ratio]; end; end; % manual mode off % --------------- if strcmpi(g.manual, 'off'), transformmat = dat.transform; dat.elec1 = elec1; if size(dat.transform,1) > 1 dat.electransf.pnt = dat.transform*[ dat.elec1.pnt ones(size(dat.elec1.pnt,1),1) ]'; else dat.electransf.pnt = traditionaldipfit(dat.transform)*[ dat.elec1.pnt ones(size(dat.elec1.pnt,1),1) ]'; end; dat.electransf.pnt = dat.electransf.pnt(1:3,:)'; dat.electransf.label = dat.elec1.label; chanlocs1 = dat.electransf; return; end; % find common electrode names % --------------------------- dat.elec1 = elec1; dat.elec2 = elec2; dat.elecshow1 = 1:length(elec1.label); dat.elecshow2 = 1:length(elec2.label); dat.color1 = [0 1 0]; dat.color2 = [1 .75 .65]*.8; %dat.color2 = [1 0 0]; dat.label1 = 0; dat.label2 = 0; dat.meshon = 1; fid = figure('userdata', dat, 'name', 'coregister()', 'numbertitle', 'off'); try, icadefs; catch, end; if 1 header = 'dattmp = get(gcbf, ''userdata'');'; footer = 'set(gcbf, ''userdata'', dattmp); clear dattmp; coregister(''redraw'', gcbf);'; cbright = [ header 'dattmp.transform(1) = str2num(get(gcbo, ''string''));' footer ]; cbforward = [ header 'dattmp.transform(2) = str2num(get(gcbo, ''string''));' footer ]; cbup = [ header 'dattmp.transform(3) = str2num(get(gcbo, ''string''));' footer ]; cbpitch = [ header 'dattmp.transform(4) = str2num(get(gcbo, ''string''));' footer ]; cbroll = [ header 'dattmp.transform(5) = str2num(get(gcbo, ''string''));' footer ]; cbyaw = [ header 'dattmp.transform(6) = str2num(get(gcbo, ''string''));' footer ]; cbresizex = [ header 'dattmp.transform(7) = str2num(get(gcbo, ''string''));' footer ]; cbresizey = [ header 'dattmp.transform(8) = str2num(get(gcbo, ''string''));' footer ]; cbresizez = [ header 'dattmp.transform(9) = str2num(get(gcbo, ''string''));' footer ]; cb_ok = 'set(gcbo, ''userdata'', ''ok'')'; cb_warp = 'coregister(''warp'', gcbf);'; cb_fid = 'coregister(''fiducials'', gcbf);'; opt = { 'unit', 'normalized', 'position' }; h = uicontrol( opt{:}, [0 .15 1 .02], 'style', 'text', 'string', ''); h = uicontrol( opt{:}, [0 .1 .2 .05], 'style', 'text', 'string', 'Move right {mm}'); h = uicontrol( opt{:}, [0 .05 .2 .05], 'style', 'text', 'string', 'Move front {mm}' ); h = uicontrol( opt{:}, [0 0 .2 .05], 'style', 'text', 'string', 'Move up {mm}'); h = uicontrol( opt{:}, [0.2 .1 .1 .05], 'tag', 'right' , 'callback', cbright , 'style', 'edit', 'string', ''); h = uicontrol( opt{:}, [0.2 .05 .1 .05], 'tag', 'forward', 'callback', cbforward, 'style', 'edit', 'string', '' ); h = uicontrol( opt{:}, [0.2 0 .1 .05], 'tag', 'up' , 'callback', cbup , 'style', 'edit', 'string', ''); h = uicontrol( opt{:}, [0.3 .1 .15 .05], 'style', 'text', 'string', 'Pitch (rad)'); h = uicontrol( opt{:}, [0.3 .05 .15 .05], 'style', 'text', 'string', 'Roll (rad)' ); h = uicontrol( opt{:}, [0.3 0 .15 .05], 'style', 'text', 'string', 'Yaw (rad)'); h = uicontrol( opt{:}, [0.45 .1 .1 .05], 'tag', 'pitch', 'callback', cbpitch, 'style', 'edit', 'string', ''); h = uicontrol( opt{:}, [0.45 .05 .1 .05], 'tag', 'roll' , 'callback', cbroll , 'style', 'edit', 'string', '' ); h = uicontrol( opt{:}, [0.45 0 .1 .05], 'tag', 'yaw' , 'callback', cbyaw , 'style', 'edit', 'string', ''); h = uicontrol( opt{:}, [0.55 .1 .15 .05], 'style', 'text', 'string', 'Resize {x}'); h = uicontrol( opt{:}, [0.55 .05 .15 .05], 'style', 'text', 'string', 'Resize {y}' ); h = uicontrol( opt{:}, [0.55 0 .15 .05], 'style', 'text', 'string', 'Resize {z}'); h = uicontrol( opt{:}, [0.7 .1 .1 .05], 'tag', 'resizex', 'callback', cbresizex, 'style', 'edit', 'string', ''); h = uicontrol( opt{:}, [0.7 .05 .1 .05], 'tag', 'resizey', 'callback', cbresizey, 'style', 'edit', 'string', '' ); h = uicontrol( opt{:}, [0.7 0 .1 .05], 'tag', 'resizez', 'callback', cbresizez, 'style', 'edit', 'string', ''); h = uicontrol( opt{:}, [0.8 .1 .2 .05], 'style', 'pushbutton', 'string', 'Align fiducials', 'callback', cb_fid); h = uicontrol( opt{:}, [0.8 .05 .2 .05], 'style', 'pushbutton', 'string', 'Warp montage', 'callback', cb_warp ); h = uicontrol( opt{:}, [0.8 0 .1 .05], 'style', 'pushbutton', 'string', 'Cancel', 'callback', 'close(gcbf);' ); h = uicontrol( opt{:}, [0.9 0 .1 .05], 'style', 'pushbutton', 'string', 'Ok', 'tag', 'ok', 'callback', cb_ok); % put labels next to electrodes % ----------------------------- cb_label1 = [ 'tmp = get(gcbf, ''userdata'');' ... 'if tmp.label1, set(gcbo, ''string'', ''Labels on'');' ... 'else set(gcbo, ''string'', ''Labels off'');' ... 'end;' ... 'tmp.label1 = ~tmp.label1;' ... 'set(gcbf, ''userdata'', tmp);' ... 'clear tmp;' ... 'coregister(''redraw'', gcbf);' ]; cb_label2 = [ 'tmp = get(gcbf, ''userdata'');' ... 'if tmp.label2, set(gcbo, ''string'', ''Labels on'');' ... 'else set(gcbo, ''string'', ''Labels off'');' ... 'end;' ... 'tmp.label2 = ~tmp.label2;' ... 'set(gcbf, ''userdata'', tmp);' ... 'clear tmp;' ... 'coregister(''redraw'', gcbf);' ]; cb_mesh = [ 'tmp = get(gcbf, ''userdata'');' ... 'if tmp.meshon, set(gcbo, ''string'', ''Mesh on'');' ... 'else set(gcbo, ''string'', ''Mesh off'');' ... 'end;' ... 'tmp.meshon = ~tmp.meshon;' ... 'set(gcbf, ''userdata'', tmp);' ... 'clear tmp;' ... 'coregister(''redraw'', gcbf);' ]; cb_elecshow1 = [ 'tmp = get(gcbf, ''userdata'');' ... 'tmp.elecshow1 = pop_chansel( tmp.elec1.label, ''select'', tmp.elecshow1 );' ... 'if ~isempty(tmp.elecshow1), set(gcbf, ''userdata'', tmp);' ... 'coregister(''redraw'', gcbf); end; clear tmp;' ]; cb_elecshow2 = [ 'tmp = get(gcbf, ''userdata'');' ... 'tmpstrs = { ''21 elec (10/20 system)'' ''86 elec (10/10 system)'' ''all elec (10/5 system)'' };' ... 'tmpres = inputgui( ''uilist'', {{ ''style'' ''text'' ''string'' ''show only'' } ' ... ' { ''style'' ''listbox'' ''string'' strvcat(tmpstrs) }}, ' ... ' ''geometry'', { 1 1 }, ''geomvert'', [1 3] );' ... 'if ~isempty(tmpres), tmp.elecshow2 = tmpstrs{tmpres{1}}; end;' ... 'set(gcbf, ''userdata'', tmp);' ... 'clear tmp tmpres;' ... 'coregister(''redraw'', gcbf);' ]; h = uicontrol( opt{:}, [0 0.75 .13 .05], 'style', 'pushbutton', 'string', 'Mesh off', 'callback', cb_mesh ); % help message % ------------ cb_helpme = [ 'warndlg2(strvcat( ''User channels (sometimes hidden in the 3-D mesh) are in green, reference channels in brown.'',' ... '''Press "Warp" to automatically warp user channels to corresponding reference channels.'',' ... '''Then, if desired, further edit the transformation manually using the coregister gui buttons.'',' ... ''' '',' ... '''To use locations of corresponding reference channels (and discard current locations),'',' ... '''select "Edit > Channel locations" in the EEGLAB mensu and press, "Look up loc." Select a '',' ... '''head model. Then re-open "Tools > Locate dipoles using DIPFIT2 > Head model and settings"'',' ... '''in the EEGLAB menu and select the "No coreg" option.'',' ]; if ~isstruct(chanlocs2) if ~isempty(findstr(lower(chanlocs2), 'standard-10-5-cap385')) | ... ~isempty(findstr(lower(chanlocs2), 'standard_1005')), cb_helpme = [ cb_helpme '''Then re-open "Tools > Locate dipoles using DIPFIT2 > Head model and settings"'',' ... '''in the EEGLAB menu and select the "No coreg" option.''), ''Warning'');' ]; else cb_helpme = [ cb_helpme '''Then re-open the graphic interface function you were using.''), ''Warning'');' ]; end; end; h = uicontrol( opt{:}, [0.87 0.95 .13 .05], 'style', 'pushbutton', 'string', 'Help me', 'callback', cb_helpme); h = uicontrol( opt{:}, [0.87 0.90 .13 .05], 'style', 'pushbutton', 'string', 'Funct. help', 'callback', 'pophelp(''coregister'');' ); % change colors % ------------- hh = findobj('parent', gcf, 'style', 'text'); set(hh, 'Backgroundcolor', GUIBACKCOLOR); set(hh, 'foregroundcolor', GUITEXTCOLOR); hh = findobj('parent', gcf, 'style', 'edit'); set(hh, 'Backgroundcolor', GUIBACKCOLOR); set(hh, 'foregroundcolor', GUITEXTCOLOR); hh = findobj('parent', gcf, 'style', 'pushbutton'); set(hh, 'Backgroundcolor', GUIBACKCOLOR); set(hh, 'foregroundcolor', GUITEXTCOLOR); h = uicontrol( opt{:}, [0 0.95 .13 .05], 'style', 'pushbutton', 'backgroundcolor', dat.color1, 'string', 'Labels on', 'callback', cb_label1 ); h = uicontrol( opt{:}, [0 0.9 .13 .05], 'style', 'pushbutton', 'backgroundcolor', dat.color1, 'string', 'Electrodes', 'callback', cb_elecshow1 ); h = uicontrol( opt{:}, [0 0.85 .13 .05], 'style', 'pushbutton', 'backgroundcolor', dat.color2, 'string', 'Labels on', 'callback', cb_label2 ); h = uicontrol( opt{:}, [0 0.8 .13 .05], 'style', 'pushbutton', 'backgroundcolor', dat.color2, 'string', 'Electrodes', 'callback', cb_elecshow2 ); end; coregister('redraw', fid); try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end % wait until button press and return values % ----------------------------------------- waitfor( findobj('parent', fid, 'tag', 'ok'), 'userdata'); try, findobj(fid); % figure still exist ? catch, transformmat = []; chanlocs1 = []; return; end; dat = get(fid, 'userdata'); transformmat = dat.transform; chanlocs1 = dat.electransf; close(fid); % plot electrodes % --------------- function plotelec(elec, elecshow, color, tag); X1 = elec.pnt(elecshow,1); Y1 = elec.pnt(elecshow,2); Z1 = elec.pnt(elecshow,3); XL = xlim; YL = ylim; ZL = zlim; lim=max(1.05*max([X1;Y1;Z1]), max([XL YL ZL])); eps=lim/20; delete(findobj(gcf, 'tag', tag)); % make bigger if fiducial % ------------------------ fidlist = { 'nz' 'lpa' 'rpa' 'nazion' 'left' 'right' 'nasion' 'fidnz' 'fidt9' 'fidt10'}; [tmp fids ] = intersect_bc(lower(elec.label(elecshow)), fidlist); nonfids = setdiff_bc(1:length(elec.label(elecshow)), fids); h1 = plot3(X1(nonfids),Y1(nonfids),Z1(nonfids), 'o', 'color', color); hold on; set(h1, 'tag', tag, 'marker', '.', 'markersize', 20); if ~isempty(fids) h2 = plot3(X1(fids),Y1(fids),Z1(fids), 'o', 'color', color*2/3); hold on; set(h2, 'tag', tag, 'marker', '.', 'markersize', 35); % make bigger if fiducial end; % plot axis and labels %- ------------------- if isempty(findobj(gcf, 'tag', 'axlabels')) plot3([0.08 0.12],[0 0],[0 0],'r','LineWidth',4) % nose plot3([0 lim],[0 0],[0 0],'b--', 'tag', 'axlabels') % axis plot3([0 0],[0 lim],[0 0],'g--') plot3([0 0],[0 0],[0 lim],'r--') plot3(0,0,0,'b+') text(lim+eps,0,0,'X','HorizontalAlignment','center',... 'VerticalAlignment','middle','Color',[0 0 0],... 'FontSize',10) text(0,lim+eps,0,'Y','HorizontalAlignment','center',... 'VerticalAlignment','middle','Color',[0 0 0],... 'FontSize',10) text(0,0,lim+eps,'Z','HorizontalAlignment','center',... 'VerticalAlignment','middle','Color',[0 0 0],... 'FontSize',10) box on end; lim = abs(lim(1)); axis([-lim lim -lim lim -lim*0.5 lim]); axis equal; % decode labels for electrode caps % -------------------------------- % 86 channels function indices = decodelabels( chanlocs, strchan ); label1020 = { 'nz' 'lpa' 'rpa' 'Fp1', 'Fpz', 'Fp2', 'F7', 'F3', 'Fz', 'F4', 'F8', 'T7', 'C3', 'Cz', 'C4', 'T8', 'P7', 'P3', 'Pz', 'P4', 'P8', 'O1', 'Oz', 'O2'}'; % 21 channels label1010 = { 'nz' 'lpa' 'rpa' 'Fp1', 'Fpz', 'Fp2', 'AF9', 'AF7', 'AF5', 'AF3', 'AF1', 'AFz', 'AF2', 'AF4', 'AF6', 'AF8', 'AF10', 'F9', 'F7', 'F5', 'F3', 'F1', 'Fz', 'F2', 'F4', 'F6', 'F8', 'F10', 'FT9', 'FT7', 'FC5', 'FC3', 'FC1', 'FCz', 'FC2', 'FC4', 'FC6', 'FT8', 'FT10', 'T9', 'T7', 'C5', 'C3', 'C1', 'Cz', 'C2', ... 'C4', 'C6', 'T8', 'T10', 'TP9', 'TP7', 'CP5', 'CP3', 'CP1', 'CPz', 'CP2', 'CP4', 'CP6', 'TP8', 'TP10', 'P9', 'P7', 'P5', 'P3', 'P1', 'Pz', 'P2', 'P4', 'P6', 'P8', 'P10', 'PO9', 'PO7', 'PO5', 'PO3', 'PO1', 'POz', 'PO2', 'PO4', 'PO6', 'PO8', 'PO10', 'O1', 'Oz', 'O2', 'I1', 'Iz', 'I2'}'; ... if ~ischar(strchan), indices = strchan; return; end; switch strchan case '21 elec (10/20 system)', indices = pop_chancoresp( struct('labels', chanlocs.label), struct('labels', label1020), 'gui', 'off'); case '86 elec (10/10 system)', indices = pop_chancoresp( struct('labels', chanlocs.label), struct('labels', label1010), 'gui', 'off'); case 'all elec (10/5 system)', indices = 1:length(chanlocs.label); otherwise, error('Unknown option'); end; % plot electrode labels % --------------------- function plotlabels(elec, elecshow, color, tag); for i = 1:length(elecshow) coords = elec.pnt(elecshow(i),:); coords = coords*1.07; text(coords(1), coords(2), coords(3), elec.label{elecshow(i)},'HorizontalAlignment','center',... 'VerticalAlignment','middle','Color',color, 'FontSize',10, 'tag', tag) end % align fiducials % --------------- function [elec1, transf] = align_fiducials(elec1, elec2, fidnames1, fidnames2) % rename fiducials % ---------------- ind1 = strmatch(fidnames1{1}, elec1.label, 'exact'); elec1.label{ind1} = fidnames2{1}; ind2 = strmatch(fidnames1{2}, elec1.label, 'exact'); elec1.label{ind2} = fidnames2{2}; ind3 = strmatch(fidnames1{3}, elec1.label, 'exact'); elec1.label{ind3} = fidnames2{3}; cfg = []; cfg.elec = elec1; cfg.template = elec2; cfg.method = 'realignfiducial'; cfg.fiducial = fidnames2; elec3 = electroderealign(cfg); transf = homogenous2traditional(elec3.m); % test difference % --------------- diff1 = mean(mean(abs(elec3.m-traditionaldipfit(transf)))); transf(6) = -transf(6); diff2 = mean(mean(abs(elec3.m-traditionaldipfit(transf)))); if diff1 < diff2, transf(6) = -transf(6); end; diff1 = mean(mean(abs(elec3.m-traditionaldipfit(transf)))); transf(5) = -transf(5); diff2 = mean(mean(abs(elec3.m-traditionaldipfit(transf)))); if diff1 < diff2, transf(5) = -transf(5); end; diff1 = mean(mean(abs(elec3.m-traditionaldipfit(transf)))); transf(4) = -transf(4); diff2 = mean(mean(abs(elec3.m-traditionaldipfit(transf)))); if diff1 < diff2, transf(4) = -transf(4); end; % rescale if necessary % -------------------- coords1 = elec1.pnt([ind1 ind2 ind3],:); dist_coords1 = sqrt(sum(coords1.^2,2)); ind1 = strmatch(fidnames2{1}, elec2.label, 'exact'); ind2 = strmatch(fidnames2{2}, elec2.label, 'exact'); ind3 = strmatch(fidnames2{3}, elec2.label, 'exact'); coords2 = elec2.pnt([ind1 ind2 ind3],:); dist_coords2 = sqrt(sum(coords2.^2,2)); ratio = mean(dist_coords2./dist_coords1); transf(7:9) = ratio; transfmat = traditionaldipfit(transf); elec1.pnt = transfmat*[ elec1.pnt ones(size(elec1.pnt,1),1) ]'; elec1.pnt = elec1.pnt(1:3,:)'; % warp channels % ------------- function [elec1, transf] = warp_chans(elec1, elec2, chanlist, warpmethod) cfg = []; cfg.elec = elec1; cfg.template = elec2; cfg.method = warpmethod; %cfg.feedback = 'yes'; cfg.channel = chanlist; elec3 = electroderealign(cfg); [tmp ind1 ] = intersect_bc( lower(elec1.label), lower(chanlist) ); [tmp ind2 ] = intersect_bc( lower(elec2.label), lower(chanlist) ); transf = elec3.m; transf(4:6) = transf(4:6)/180*pi; if length(transf) == 6, transf(7:9) = 1; end; transf = checktransf(transf, elec1, elec2); dpre = mean(sqrt(sum((elec1.pnt(ind1,:) - elec2.pnt(ind2,:)).^2, 2))); transfmat = traditionaldipfit(transf); elec1.pnt = transfmat*[ elec1.pnt ones(size(elec1.pnt,1),1) ]'; elec1.pnt = elec1.pnt(1:3,:)'; dpost = mean(sqrt(sum((elec1.pnt(ind1,:) - elec2.pnt(ind2,:)).^2, 2))); fprintf('mean distance prior to warping %f, after warping %f\n', dpre, dpost); % test difference and invert axis if necessary % -------------------------------------------- function transf = checktransf(transf, elec1, elec2) [tmp ind1 ind2] = intersect_bc( elec1.label, elec2.label ); transfmat = traditionaldipfit(transf); tmppnt = transfmat*[ elec1.pnt ones(size(elec1.pnt,1),1) ]'; tmppnt = tmppnt(1:3,:)'; diff1 = tmppnt(ind1,:) - elec2.pnt(ind2,:); diff1 = mean(sum(diff1.^2,2)); transf(6) = -transf(6); % yaw angle is sometimes inverted transfmat = traditionaldipfit(transf); tmppnt = transfmat*[ elec1.pnt ones(size(elec1.pnt,1),1) ]'; tmppnt = tmppnt(1:3,:)'; diff2 = tmppnt(ind1,:) - elec2.pnt(ind2,:); diff2 = mean(sum(diff2.^2,2)); if diff1 < diff2, transf(6) = -transf(6); else diff1 = diff2; end; transf(4) = -transf(4); % yaw angle is sometimes inverted transfmat = traditionaldipfit(transf); tmppnt = transfmat*[ elec1.pnt ones(size(elec1.pnt,1),1) ]'; tmppnt = tmppnt(1:3,:)'; diff2 = tmppnt(ind1,:) - elec2.pnt(ind2,:); diff2 = mean(sum(diff2.^2,2)); if diff1 < diff2, transf(4) = -transf(4); end; % redraw GUI % ---------- function redrawgui(fid) dat = get(fid, 'userdata'); tmpobj = findobj(fid, 'tag', 'pitch'); set(tmpobj, 'string', num2str(dat.transform(4),4)); tmpobj = findobj(fid, 'tag', 'roll' ); set(tmpobj, 'string', num2str(dat.transform(5),4)); tmpobj = findobj(fid, 'tag', 'yaw' ); set(tmpobj, 'string', num2str(dat.transform(6),4)); tmpobj = findobj(fid, 'tag', 'right' ); set(tmpobj, 'string', num2str(dat.transform(1),4)); tmpobj = findobj(fid, 'tag', 'forward'); set(tmpobj, 'string', num2str(dat.transform(2),4)); tmpobj = findobj(fid, 'tag', 'up' ); set(tmpobj, 'string', num2str(dat.transform(3),4)); tmpobj = findobj(fid, 'tag', 'resizex'); set(tmpobj, 'string', num2str(dat.transform(7),4)); tmpobj = findobj(fid, 'tag', 'resizey'); set(tmpobj, 'string', num2str(dat.transform(8),4)); tmpobj = findobj(fid, 'tag', 'resizez'); set(tmpobj, 'string', num2str(dat.transform(9),4)); tmpview = view; if size(dat.transform,1) > 1 dat.electransf.pnt = dat.transform*[ dat.elec1.pnt ones(size(dat.elec1.pnt,1),1) ]'; else dat.electransf.pnt = traditionaldipfit(dat.transform)*[ dat.elec1.pnt ones(size(dat.elec1.pnt,1),1) ]'; end; dat.electransf.pnt = dat.electransf.pnt(1:3,:)'; dat.electransf.label = dat.elec1.label; set(fid, 'userdata', dat); h = findobj(fid, 'tag', 'plot3d'); if isempty(h) axis off; h = axes('unit', 'normalized', 'position', [0 0.2 1 0.75]); set(h, 'tag', 'plot3d'); axis off; else axes(h); %axis off; end; plotelec(dat.electransf, dat.elecshow1, dat.color1, 'elec1'); if ~isempty(dat.elec2) dat.elecshow2 = decodelabels( dat.elec2, dat.elecshow2 ); plotelec(dat.elec2, dat.elecshow2, dat.color2, 'elec2'); end; set(h, 'tag', 'plot3d'); % plot mesh % --------- if ~isempty(dat.meshpnt) & isempty(findobj(gcf, 'tag', 'mesh')) if ~isempty(dat.meshtri) p1 = plotmesh(dat.meshtri, dat.meshpnt, [], 1); set(p1, 'tag', 'mesh'); else facecolor(1,1,1) = 1; facecolor(1,1,2) = .75; facecolor(1,1,3) = .65; cdat = repmat( facecolor, [ size(dat.meshpnt{1}) 1]); h = mesh(dat.meshpnt{1}, dat.meshpnt{2}, dat.meshpnt{3}, ... 'cdata', cdat, 'tag', 'mesh', 'facecolor', squeeze(facecolor), 'edgecolor', 'none'); hidden off; lightangle(45,30); lightangle(45+180,30); lighting phong s = plotnose([85 0 -75 0 0 pi/2 10 10 40]); set(s, 'tag', 'mesh'); end; end; meshobj = findobj(gcf, 'tag', 'mesh'); if dat.meshon set( meshobj, 'visible', 'on'); else set( meshobj, 'visible', 'off'); end; % plot electrodes % --------------- delete(findobj(gcf, 'tag', 'elec1labels')); delete(findobj(gcf, 'tag', 'elec2labels')); if dat.label1 plotlabels(dat.electransf, dat.elecshow1, dat.color1, 'elec1labels'); end; if dat.label2 plotlabels(dat.elec2, dat.elecshow2, dat.color2*0.5, 'elec2labels'); end; %view(tmpview); rotate3d on % function to plot the nose % ------------------------- function s = plotnose(transf, col) if nargin < 1 transf = [0 0 0 0 0 0 1 1 1]; end; if nargin < 2 col = [1 0.75 0.65 ]; end; x=[ % cube NaN -1 1 NaN -1 -1 1 1 -1 -1 1 1 NaN -1 1 NaN NaN -1 1 NaN NaN NaN NaN NaN ]; y=[ % cube NaN -1 -1 NaN -1 -1 -1 -1 1 1 1 1 NaN 1 1 NaN NaN -1 -1 NaN NaN NaN NaN NaN ]; z=[ % cube NaN 0 0 NaN 0 1 1 0 0 1 1 0 NaN 0 0 NaN NaN 0 0 NaN NaN NaN NaN NaN ]; x=[ % noze NaN -1 1 NaN -1 0 0 1 -.3 0 0 .3 NaN -.3 .3 NaN NaN -1 1 NaN NaN NaN NaN NaN ]; y=[ % noze NaN -1 -1 NaN -1 -1 -1 -1 1 -1 -1 1 NaN 1 1 NaN NaN -1 -1 NaN NaN NaN NaN NaN ]; z=[ % noze NaN 0 0 NaN 0 1 1 0 0 1 1 0 NaN 0 0 NaN NaN 0 0 NaN NaN NaN NaN NaN ]; % apply homogenous transformation % ------------------------------- transfhom = traditionaldipfit( transf ); xyz = [ x(:) y(:) z(:) ones(length(x(:)),1) ]; xyz2 = transfhom * xyz'; x(:) = xyz2(1,:)'; y(:) = xyz2(2,:)'; z(:) = xyz2(3,:)'; % dealing with colors % ------------------- cc=zeros(8,3); cc(1,:) = col; cc(2,:) = col; cc(3,:) = col; cc(4,:) = col; cc(5,:) = col; cc(6,:) = col; cc(7,:) = col; cc(8,:) = col; cc(1,:)=[0 0 0]; % black cc(2,:)=[1 0 0]; % red cc(3,:)=[0 1 0]; % green cc(4,:)=[0 0 1]; % blue cc(5,:)=[1 0 1]; % magenta cc(6,:)=[0 1 1]; % cyan cc(7,:)=[1 1 0]; % yellow cc(8,:)=[1 1 1]; % white cs=size(x); c=repmat(zeros(cs),[1 1 3]); for i=1:size(cc,1) ix=find(x==cc(i,1) &... y==cc(i,2) &... z==cc(i,3)); [ir,ic]=ind2sub(cs,ix); for k=1:3 for m=1:length(ir) c(ir(m),ic(m),k)=cc(i,k); end end end % plotting surface % ---------------- facecolor = zeros(size(x,1), size(z,2), 3); facecolor(:,:,1) = 1; facecolor(:,:,2) = .75; facecolor(:,:,3) = .65; s=surf(x,y,z,facecolor); set(s, 'edgecolor', [0.5 0.5 0.5]);
github
ZijingMao/baselineeegtest-master
transformcoords.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/transformcoords.m
4,303
utf_8
5c18fcc7b4908f6238aee6106d85e43c
% transformcoords() - Select nazion and inion in anatomical MRI images. % % Usage: % mewcoords = transformcoords(coords, rotate, scale, center, reverse); % % Inputs: % coords - array of 3-D coordinates (3 by N or N by 3) % rotate - [pitch roll yaw] rotate in 3-D using pitch (x plane), % roll (y plane) and yaw (z plane). An empty array does % not perform any rotation. % scale - [scalex scaley scalez] scale axis. A single numeric % input scale all the dimentions the same. Default 1 % does not scale. % shifts - [x y z] shift coordinates (after rotation and scaling). % Default [0 0 0] does not move the center. % reverse - [0|1] when set to 1 perform the reverse transformation, % first moving to the old center, unscaling, and unrotating. % Default is 0. % % Output: % newcoords - coordinates after rotating, scaling and recentering % % Author: Arnaud Delorme, Salk, SCCN, UCSD, CA, March 23, 2004 % Copyright (C) 2004 Arnaud Delorme % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function coords = transformcoords(coords, rotate, scale, center, reverse); if nargin < 2 help transformcoords; return; end; if nargin < 3 scale =1; end; if nargin < 4 center = [0 0 0]; end; if nargin < 5 reverse = 0; end; if size(coords, 1) ~= 3 coords = coords'; trp = 1; else trp = 0; end; if size(coords, 1) ~= 3 error('Number of columns must be 3 for the coordinate input'); end; if length(rotate) > 0 & length(rotate) ~= 3 error('rotate parameter must have 3 values'); end; % decode parameters % ----------------- centx = -center(1); centy = -center(2); centz = -center(3); if length(scale) == 1 scale = [scale scale scale]; end; scalex = scale(1); scaley = scale(2); scalez = scale(3); if length(rotate) < 3 rotate = [0 0 0] end; pitch = rotate(1); roll = rotate(2); yaw = rotate(3); if ~reverse % pitch roll yaw rotation % ----------------------- % pitch (x-axis); roll = y axis rotation; yaw = z axis % see http://bishopw.loni.ucla.edu/AIR5/homogenous.html cp = cos(pitch); sp = sin(pitch); cr = cos(roll); sr = sin(roll); cy = cos(yaw); sy = sin(yaw); rot3d = [ cy*cr+sy*sp*sr sy*cr-cy*sp*sr cp*sr ; -sy*cp cy*cp sp ; sy*sp*cr-cy*sr -cy*sp*cr-sy*sr cp*cr ]; coords = rot3d*coords; % scaling and centering % --------------------- coords(1,:) = coords(1,:)*scalex-centx; coords(2,:) = coords(2,:)*scaley-centy; coords(3,:) = coords(3,:)*scalez-centz; else % unscaling and uncentering % ------------------------- coords(1,:) = (coords(1,:)+centx)/scalex; coords(2,:) = (coords(2,:)+centy)/scaley; coords(3,:) = (coords(3,:)+centz)/scalez; % pitch roll yaw rotation % ----------------------- cp = cos(-pitch); sp = sin(-pitch); cr = cos(-roll); sr = sin(-roll); cy = cos(-yaw); sy = sin(-yaw); rot3d = [ cy*cr+sy*sp*sr sy*cr-cy*sp*sr cp*sr ; -sy*cp cy*cp sp ; sy*sp*cr-cy*sr -cy*sp*cr-sy*sr cp*cr ]; coords = rot3d*coords; end; if trp coords = coords'; end;
github
ZijingMao/baselineeegtest-master
rejkurt.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/rejkurt.m
4,127
utf_8
871cc2da42fee9b970ec91508ece96fb
% rejkurt() - calculation of kutosis of a 1D, 2D or 3D array and % rejection of outliers values of the input data array % using the discrete kutosis of the values in that dimension. % % Usage: % >> [kurtosis rej] = rejkurt( signal, threshold, kurtosis, normalize); % % Inputs: % signal - one dimensional column vector of data values, two % dimensional column vector of values of size % sweeps x frames or three dimensional array of size % component x sweeps x frames. If three dimensional, % all components are treated independently. % threshold - Absolute threshold. If normalization is used then the % threshold is expressed in standard deviation of the % mean. 0 means no threshold. % kurtosis - pre-computed kurtosis (only perform thresholding). Default % is the empty array []. % normalize - 0 = do not not normalize kurtosis. 1 = normalize kurtosis. % 2 is 20% trimming (10% low and 10% high) kurtosis before % normalizing. Default is 0. % % Outputs: % kurtosis - normalized joint probability of the single trials % (same size as signal without the last dimension) % rej - rejected matrix (0 and 1, size: 1 x sweeps) % % Remarks: % The exact values of kurtosis depend on the size of a time % step and thus cannot be considered as absolute. % This function uses the kurtosis function from the statistival % matlab toolbox. If the statistical toolbox is not installed, % it uses the 'kurt' function of the ICA/EEG toolbox. % % See also: kurt(), kurtosis() % 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 [kurto, rej] = rejkurt( signal, threshold, oldkurtosis, normalize); if nargin < 1 help rejkurt; return; end; if nargin < 2 threshold = 0; end; if nargin < 4 normalize = 0; end; if nargin < 3 oldkurtosis = []; end; if size(signal,2) == 1 % transpose if necessary signal = signal'; end; nbchan = size(signal,1); pnts = size(signal,2); sweeps = size(signal,3); kurto = zeros(nbchan,sweeps); if ~isempty( oldkurtosis ) % speed up the computation kurto = oldkurtosis; else for rc = 1:nbchan % compute all kurtosis % -------------------- for index=1:sweeps try kurto(rc, index) = kurtosis(signal(rc,:,index)); catch kurto(rc, index) = kurt(signal(rc,:,index)); end; end; end; % normalize the last dimension % ---------------------------- if normalize tmpkurt = kurto; if normalize == 2, tmpkurt = sort(tmpkurt); minind = max(round(length(tmpkurt)*0.1),1); maxind = round(length(tmpkurt)-round(length(tmpkurt)*0.1)); if size(tmpkurt,2) == 1 tmpkurt = tmpkurt(minind:maxind); else tmpkurt = tmpkurt(:,minind:maxind); end; end; switch ndims( signal ) case 2, kurto = (kurto-mean(tmpkurt)) / std(tmpkurt); case 3, kurto = (kurto-mean(tmpkurt,2)*ones(1,size(kurto,2)))./ ... (std(tmpkurt,0,2)*ones(1,size(kurto,2))); end; end; end; % reject % ------ if threshold(1) ~= 0 if length(threshold) > 1 rej = (threshold(1) > kurto) | (kurto > threshold(2)); else rej = abs(kurto) > threshold; end; else rej = zeros(size(kurto)); end; return;
github
ZijingMao/baselineeegtest-master
readeetraklocs.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/readeetraklocs.m
2,399
utf_8
9e9ab75538baff3f8e51e2d15bcbbfc8
% readeetraklocs() - read 3-D location files saved using the EETrak % digitizing software. % Usage: % >> CHANLOCS = readeetraklocs( filename ); % % Inputs: % filename - [string] file name % % Outputs: % CHANLOCS - EEGLAB channel location data structure. % See help readlocs() % % Author: Arnaud Delorme, CNL / Salk Institute, Nov 2003 % % See also: readlocs() % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function chanlocs = readeetraklocs( filename ) if nargin < 1 help readeetraklocs; return; end; % read location file % ------------------ locs = loadtxt( filename ); % get label names % --------------- indlabels = []; indpos = []; for ind = 1:size(locs,1) if isstr(locs{ind,1}) if strcmpi(locs{ind,1}, 'Labels') indlabels = ind; end; if strcmpi(locs{ind,1}, 'Positions') indpos = ind; end; end; end; if isempty(indpos) | isempty(indlabels) error('Could not find ''Labels'' or ''Position'' tag in electrode file'); end; % get positions % ------------- positions = locs(indpos+1:indlabels-1,1:3); labels = locs(indlabels+1:end,:); % create structure % ---------------- for index = 1:length(labels) chanlocs(index).labels = labels{index}; chanlocs(index).X = positions{index,1}; chanlocs(index).Y = positions{index,2}; chanlocs(index).Z = positions{index,3}; end; chanlocs = convertlocs(chanlocs, 'cart2all');
github
ZijingMao/baselineeegtest-master
nan_mean.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/nan_mean.m
1,341
utf_8
e87ae15c116d4211709116e3c5abf693
% nan_mean() - Average, not considering NaN values % % Usage: same as mean() % Author: Arnaud Delorme, CNL / Salk Institute, 16 Oct 2002 % 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 out = nan_mean(in, dim) if nargin < 1 help nan_mean; return; end; if nargin < 2 if size(in,1) ~= 1 dim = 1; elseif size(in,2) ~= 1 dim = 2; else dim = 3; end; end; tmpin = in; tmpin(find(isnan(in(:)))) = 0; denom = sum(~isnan(in),dim); denom(find(~denom)) = nan; out = sum(tmpin, dim) ./ denom;
github
ZijingMao/baselineeegtest-master
dipoledensity.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/dipoledensity.m
22,135
utf_8
e26078ef7126108f2f7737b5c773de3d
% dipoledensity() - compute and optionally plot a measure of the 3-D spatial % (in)homogeneity of a specified (large) set of 1- or 2-dipole % component models, either as physical dipole density or as % dipole-position entropy across subjects. In either case, % take into account either all the dipoles, or only the nearest % dipole from each of the subjects. If no output arguments, % or if 'plot','on', paints a 3-D density|entropy brain image % on slices of the Montreal Neurological Institute (MNI) mean % MR brain image ('standard_BESA/avg152t1.mat'). Calls % dipplot(), % mri3dplot(), and Fieldtrip function find_inside_vol(). % Usage: % >> [dens3d mri] = dipoledensity( dipoles, 'key',val, ... ); % % Inputs: % dipoles - this may be either the same dipole structure given as input to % the dipplot() function, a 3 by n array of dipole localization or % a cell array containing arguments for the dipplot function. Note that % the 'coordformat' option below defines the coordinate space for these % dipoles (default is MNI). See help dipplot for more information. % % Optional 'key', val input pairs: % 'mri' - [string or struct] mri file (matlab format or file format read % by fcdc_read_mri). See dipplot.m help for more information. % 'method' - ['alldistance'|'distance'|'entropy'|'relentropy'] method for % computing density: % 'alldistance' - {default} take into account the gaussian-weighted % distances from each voxel to all the dipoles. See % 'methodparam' (below) to specify a standard deviation % (in mm) for the gaussian weight kernel. % 'distance' - take into account only the distances to the nearest % dipole for each subject. See 'methodparam' (below). % 'entropy' - taking into account only the nearest dipole to each % voxel for each subject. See 'methodparam' below. % 'relentropy' - as in 'entropy,' but take into account all the % dipoles for each subject. % 'methodparam' - [number] for 'distance'|'alldistance' methods (see above), the % standard deviation (in mm) of the 3-D gaussian smoothing kernel. % For 'entropy'|'relentropy' methods, the number of closest dipoles % to include {defaults: 20 mm | 20 dipoles } % 'subsample' - [integer] subsampling of native MNI image {default: 2 -> 2x2x2} % 'weight' - [(1,ncomps) array] for 'distance'|'alldistance' methods, the % relative weight of each component dipole {default: ones()} % 'coordformat' - ['mni'|'spherical'] coordinate format if dipole location or % a structure is given as input. Default is 'mni'. % 'subjind' - [(1,ncomps) array] subject index for each dipole model. If two % dipoles are in one component model, give only one subject index. % 'nsessions' - [integer] for 'alldistance' method, the number of sessions to % divide the output values by, so that the returned measure is % dipole density per session {default: 1} % 'plot' - ['on'|'off'] force plotting dipole density|entropy % {default: 'on' if no output arguments, else 'off'} % 'dipplot' - ['on'|'off'] plot the dipplot image (used for converting % coordinates (default is 'off') % 'plotargs' - {cell array} plotting arguments for mri3dplot() function. % 'volmesh_fname' - [string] precomputed mesh volume file name. If not % given as input the function will recompute it (it can take from % five to 20 minutes). By default this function save the volume file % mesh into a file named volmesh_local.mat in the current % folder. % 'norm2JointProb' - ['on'|'off'] Use joint probability (i.e. sum of all % voxel values == 1) instead of number of dipoles/cm^3. % Should be used for group comparison. (default 'off') % % Outputs: % dens3d - [3-D num array] density in dipoles per cubic centimeter. If output % is returned, no plot is produced unless 'plot','on' is specified. % mri - {MRI structure} used in mri3dplot(). % % Example: % >> fakedipoles = (rand(3,10)-0.5)*80; % >> [dens3d mri] = dipoledensity( fakedipoles, 'coordformat', 'mni'); % >> mri3dplot(dens3d,mri); % replot if no output is given above % % function is called automatically % % ------------------------------------ % NOTES: to do multiple subject causal-weighted density map, % (1) concatenate dipplot coord matrices for all subject % (2) make g.subjind vector [ones(1,ncompsS1) 2*ones(1,ncompsS2) ... N*ones(1,ncompssN)] % (3) concatenate normalized outflows for all subjects to form weight vector % (4) call dipoledensity function with method = 'entropy' or 'relentropy' % ------------------------------------ % % See also: % EEGLAB: dipplot(), mri3dplot(), Fieldtrip: find_inside_vol() % % Author: Arnaud Delorme & Scott Makeig, SCCN, INC, UCSD % 02/19/2013 'norm2JointProb' added by Makoto. % Copyright (C) Arnaud Delorme & Scott Makeig, SCCN/INC/UCSD, 2003- % % 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 [prob3d, mri] = dipoledensity(dipplotargs, varargin) % TO DO: return in dipplot() the real 3-D location of dipoles (in posxyz) % FIX the dimension order here prob3d = []; mri = []; if nargin < 1 help dipoledensity return end g = finputcheck(varargin, { 'subjind' 'integer' [] []; 'method' 'string' { 'relentropy','entropy','distance','alldistance' } 'alldistance'; 'methodparam' 'real' [] 20; 'weight' { 'real','cell' } [] []; 'smooth' 'real' [] 0; 'nsessions' 'integer' [] 1; 'subsample' 'integer' [] 2; 'plotargs' 'cell' [] {}; 'plot' 'string' { 'on','off' } fastif(nargout == 0, 'on', 'off'); 'dipplot' 'string' { 'on','off' } 'off'; 'coordformat' 'string' { 'mni','spherical' } 'mni'; 'normalization' 'string' { 'on','off' } 'on'; 'volmesh_fname' 'string' [] 'volmesh_local.mat'; 'mri' { 'struct','string' } [] ''; 'norm2JointProb' 'string' { 'on','off' } 'off'}); if isstr(g), error(g); end; if ~strcmpi(g.method, 'alldistance') & isempty(g.subjind) error('Subject indices are required for this method'); end; if ~iscell(g.weight), g.weight = { g.weight }; end; % plotting dipplot % ---------------- if ~iscell(dipplotargs) % convert input if ~isstruct(dipplotargs) if size(dipplotargs,1) == 3, dipplotargs = dipplotargs'; elseif size(dipplotargs,2) ~= 3 error('If an array of dipoles is given as entry, there must be 3 columns or 3 rows for x y z'); end; model = []; for idip = 1:length(dipplotargs) model(idip).posxyz = dipplotargs(idip,:); model(idip).momxyz = [1 0 0]; model(idip).rv = 0.5; end; dipplotargs = model; end; dipplotargs = { dipplotargs 'coordformat' g.coordformat }; else dipplotargs = { dipplotargs{:} 'coordformat' g.coordformat }; end; struct = dipplot(dipplotargs{:}, 'plot', g.dipplot); if nargout == 0 drawnow; end; % retrieve coordinates in MNI space % --------------------------------- if 0 % deprecated % find dipoles % ------------ hmesh = findobj(gcf, 'tag', 'mesh'); if isempty(hmesh), error('Current figure must contain dipoles'); end; hh = []; disp('Finding dipoles...'); dips = zeros(1,200); for index = 1:1000 hh = [ hh(:); findobj(gcf, 'tag', ['dipole' int2str(index) ]) ]; dips(index) = length(findobj(gcf, 'tag', ['dipole' int2str(index) ])); end; disp('Retrieving dipole positions ...'); count = 1; for index = 1:length(hh) tmp = get(hh(index), 'userdata'); if length(tmp) == 1 allx(count) = tmp.eleccoord(1,1); ally(count) = tmp.eleccoord(1,2); allz(count) = tmp.eleccoord(1,3); alli(count) = index; count = count + 1; end; end; end; % check weights % ------------- if ~isempty(g.weight{1}) if ~iscell(g.weight) if length(g.weight) ~= length(struct) error('There must be as many elements in the weight matrix as there are dipoles') end; else if length(g.weight{1}) ~= length(struct) || length(g.weight{1}) ~= length(g.weight{end}) error('There must be as many elements in the weight matrix as there are dipoles') end; end; else g.weight = { ones( 1, length(struct)) }; end; if ~isempty(g.subjind) if length(g.subjind) ~= length(struct) error('There must be as many element in the subject matrix as there are dipoles') end; else g.subjind = ones( 1, length(struct)); end; % decoding dipole locations % ------------------------- disp('Retrieving dipole positions ...'); count = 1; for index = 1:length(struct) dips = size(struct(index).eleccoord,1); for dip = 1:dips allx(count) = struct(index).eleccoord(dip,1); ally(count) = struct(index).eleccoord(dip,2); allz(count) = struct(index).eleccoord(dip,3); alli(count) = index; allw1(count) = g.weight{1}( index)/dips; allw2(count) = g.weight{end}(index)/dips; alls(count) = g.subjind(index); count = count + 1; end; end; g.weight{1} = allw1; g.weight{end} = allw2; g.subjind = alls; % read MRI file % ------------- if isempty(g.mri) % default MRI file dipfitdefs; load('-mat', template_models(1).mrifile); % load mri variable g.mri = mri; end if isstr(g.mri) try, mri = load('-mat', g.mri); mri = mri.mri; catch, disp('Failed to read Matlab file. Attempt to read MRI file using function read_fcdc_mri'); try, warning off; mri = read_fcdc_mri(g.mri); mri.anatomy = round(gammacorrection( mri.anatomy, 0.8)); mri.anatomy = uint8(round(mri.anatomy/max(reshape(mri.anatomy, prod(mri.dim),1))*255)); % WARNING: if using double instead of int8, the scaling is different % [-128 to 128 and 0 is not good] % WARNING: the transform matrix is not 1, 1, 1 on the diagonal, some slices may be % misplaced warning on; catch, error('Cannot load file using read_fcdc_mri'); end; end; g.mri = mri; % output the anatomic mri image end; % reserve array for density % ------------------------- prob3d = {zeros(ceil(g.mri.dim/g.subsample)) }; for i = 2:length(g.weight), prob3d{i} = prob3d{1}; end; % compute voxel size % ------------------ point1 = g.mri.transform * [ 1 1 1 1 ]'; point2 = g.mri.transform * [ 2 2 2 1 ]'; voxvol = sum((point1(1:3)-point2(1:3)).^2)*g.subsample^3; % in mm % compute global subject entropy if necessary % ------------------------------------------- vals = unique_bc(g.subjind); % the unique subject indices if strcmpi(g.method, 'relentropy') | strcmpi(g.method, 'entropy') %%%%% entropy %%%%%%% newind = zeros(size(g.subjind)); for index = 1:length(vals) % foreach subject in the cluster tmpind = find(g.subjind == vals(index)); % dipoles for the subject totcount(index) = length(tmpind); % store the number of subject dipoles newind(tmpind) = index; % put subject index into newind end; g.subjind = newind; gp = totcount/sum(totcount); globent = -sum(gp.*log(gp)); end; % compute volume inside head mesh % ------------------------------- dipfitdefs; % get the location of standard BEM volume file tmp = load('-mat',DIPOLEDENSITY_STDBEM); % load MNI mesh if isempty(g.volmesh_fname) % default filename = [ '/home/arno/matlab/MNI_VoxelTsearch' int2str(g.subsample) '.mat' ]; else filename = g.volmesh_fname; % end if ~exist(filename) disp('Computing volume within head mesh...'); [X Y Z] = meshgrid(g.mri.xgrid(1:g.subsample:end)+g.subsample/2, ... g.mri.ygrid(1:g.subsample:end)+g.subsample/2, ... g.mri.zgrid(1:g.subsample:end)+g.subsample/2); [indX indY indZ ] = meshgrid(1:length(g.mri.xgrid(1:g.subsample:end)), ... 1:length(g.mri.ygrid(1:g.subsample:end)), ... 1:length(g.mri.zgrid(1:g.subsample:end))); allpoints = [ X(:)' ; Y(:)' ; Z(:)' ]; allinds = [ indX(:)' ; indY(:)'; indZ(:)' ]; allpoints = g.mri.transform * [ allpoints ; ones(1, size(allpoints,2)) ]; allpoints(4,:) = []; olddir = pwd; tmppath = which('ft_electroderealign'); tmppath = fullfile(fileparts(tmppath), 'private'); cd(tmppath); [Inside Outside] = find_inside_vol(allpoints', tmp.vol); % from Fieldtrip cd(olddir); disp('Done.'); if 0 % old code using Delaunay %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% P = tmp.vol.bnd(1).pnt; T = delaunayn(P); % recompute triangularization (the original one is not compatible % with tsearchn) get coordinates of all points in the volume % search for points inside or ouside the volume (takes about 14 minutes!) IO = tsearchn(P, T, allpoints'); Inside = find(isnan(IO)); Outside = find(~isnan(IO)); disp('Done.'); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% try, save('-mat', filename, 'allpoints', 'allinds', 'Inside', 'Outside'); disp('Saving file containing inside/outide voxel indices...'); catch, end; else disp('Loading file containing inside/outide voxel indices...'); load('-mat',filename); end; InsidePoints = allpoints(:, Inside); InsideIndices = allinds(:, Inside); % scan grid and compute entropy at each voxel % ------------------------------------------- edges = [0.5:1:length(vals)+0.5]; if ~strcmpi(g.method, 'alldistance') fprintf('Computing (of %d):', size(InsideIndices,2)); % entropy calculation: have to scan voxels % ---------------------------------------- for i = 1:size(InsideIndices,2) alldists = (InsidePoints(1,i) - allx).^2 ... + (InsidePoints(2,i) - ally).^2 ... + (InsidePoints(3,i) - allz).^2; [tmpsort indsort] = sort(alldists); % sort dipoles by distance tmpweights{1} = g.weight{1}( indsort); tmpweights{end} = g.weight{end}(indsort); if strcmpi(g.method, 'relentropy') | strcmpi(g.method, 'entropy') %%%%% entropy %%%%%%% subjs = g.subjind(indsort(1:g.methodparam)); % get subject indices of closest dipoles p = histc(subjs, edges); if strcmpi(g.method, 'relentropy') p = p(1:end-1)./totcount; % this should be uniform if p conforms to global count for all subjects end; p = p/sum(p); p(find(p == 0)) = []; for tmpi = 1:length(g.weight) prob3d{1}(InsideIndices(1,i), InsideIndices(2,i), InsideIndices(3,i)) = -sum(p.*log(p)); end; else % distance to each subject ordsubjs = g.subjind(indsort); for index = 1:length(vals) % for each subject tmpind = find(ordsubjs == vals(index)); if strcmpi(g.method,'distance') use_dipoles(index) = tmpind(1); % find their nearest dipole end end; for tmpi = 1:length(g.weight) prob3d{tmpi}(InsideIndices(1,i), InsideIndices(2,i), InsideIndices(3,i)) = ... sum(tmpweights{tmpi}(use_dipoles).*exp(-tmpsort(use_dipoles)/ ... (2*g.methodparam^2))); % 3-D gaussian smooth end; end; if mod(i,100) == 0, fprintf('%d ', i); end; end; else % 'alldistance' % distance calculation: can scan dipoles instead of voxels (since linear) % -------------------------------------------------------- %alldists = allx.^2 + ally.^2 + allz.^2; %figure; hist(alldists); return; % look at distribution of distances fprintf('Computing (of %d):', size(allx,2)); for tmpi=1:length(g.weight) tmpprob{tmpi} = zeros(1, size(InsidePoints,2)); end; if length(g.weight) > 1, tmpprob2 = tmpprob; end; for i = 1:size(allx,2) alldists = (InsidePoints(1,:) - allx(i)).^2 + ... (InsidePoints(2,:) - ally(i)).^2 + ... (InsidePoints(3,:) - allz(i)).^2; % alldists = 1; % TM for tmpi=1:length(g.weight) tmpprob{tmpi} = tmpprob{tmpi} + g.weight{tmpi}(i)*exp(-alldists/(2*g.methodparam^2)); % 3-D gaussian smooth if any(isinf(tmpprob{tmpi})), error('Infinite value in probability calculation'); end; end; if mod(i,50) == 0, fprintf('%d ', i); end; end; % copy values to 3-D mesh % ----------------------- for i = 1:length(Inside) pnts = allinds(:,Inside(i)); for tmpi = 1:length(g.weight) prob3d{tmpi}(pnts(1), pnts(2), pnts(3)) = tmpprob{tmpi}(i); end; end; end; fprintf('\n'); % normalize for points inside and outside the volume % -------------------------------------------------- if strcmpi(g.method, 'alldistance') && strcmpi(g.normalization,'on') for i =1:length(g.weight) disp('Normalizing to dipole/mm^3'); if any(prob3d{i}(:)<0) fprintf('WARNING: Some probabilities are negative, this will likely cause problems when normalizing probabilities.\n'); fprintf('It is highly recommended to turn normaliziation off by using ''normalization'' key to ''off''.\n'); end; totval = sum(prob3d{i}(:)); % total values in the head switch g.norm2JointProb case 'off' totdip = size(allx,2); % number of dipoles voxvol; % volume of a voxel in mm^3 prob3d{i} = prob3d{i}/totval*totdip/voxvol*1000; % time 1000 to get cubic centimeters prob3d{i} = prob3d{i}/g.nsessions; case 'on' prob3d{i} = prob3d{i}/totval; end end; end; % resample matrix % ---------------- if g.subsample ~= 1 for i =1:length(g.weight) prob3d{i} = prob3d{i}/g.subsample; newprob3d = zeros(g.mri.dim); X = ceil(g.mri.xgrid/g.subsample); Y = ceil(g.mri.ygrid/g.subsample); Z = ceil(g.mri.zgrid/g.subsample); for index = 1:size(newprob3d,3) newprob3d(:,:,index) = prob3d{i}(X,Y,Z(index)); end; prob3d{i} = newprob3d; end; end; % 3-D smoothing % ------------- if g.smooth ~= 0 disp('Smoothing...'); for i =1:length(g.weight) prob3d{i} = smooth3d(prob3d{i}, g.smooth); end; end; % plotting % -------- if strcmpi(g.plot, 'off') close gcf; else mri3dplot( prob3d, g.mri, g.plotargs{:}); % plot the density using mri3dplot() end; return; %% function [inside, outside] = find_inside_vol(pos, vol); % FIND_INSIDE_VOL locates dipole locations inside/outside the source % compartment of a volume conductor model. % % [inside, outside] = find_inside_vol(pos, vol) % % This function is obsolete and its use in other functions should be replaced % by inside_vol % Copyright (C) 2003-2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ warning('find_inside_vol is obsolete and will be removed, please use ft_inside_vol'); inside = ft_inside_vol(pos, vol); % replace boolean vector with indexing vectors outside = find(~inside); inside = find(inside);
github
ZijingMao/baselineeegtest-master
icaproj.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/icaproj.m
5,346
utf_8
4a90dc72f4d7531154efd0ac71fb422c
% icaproj() - project ICA component activations through the % associated weight matrices to reconstitute the % observed data using only the selected ICA components. % Usage: % >> [icaprojdata] = icaproj(data,weights,compindex,[datameans],chansout); % % Inputs: % data - data matrix (chans, frames*epochs) % weights - unmixing weight matrix (e.g., weights*sphere from runica()) % compindex - vector of ICA component indices to project % % Optional inputs: % datamean - Optional ICA row means (for each epoch) from runica() % {default 0 -> distribute data offsets among the ICA components} % chansout - Optional vector of channel indices to output {default: all} % % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 11-30-96 % % See also: icavar(), runica() % Copyright (C) 11-30-96 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 11-30-96 Scott Makeig CNL / Salk Institute, La Jolla as icaproject.m % 12-24-96 added define for verbose -sm (V1.3) % 2-11-97 use outer product math when only one component in compindex -sm % 3-11-97 remove row means instead of grand mean -sm % 3-19-97 used datamean argument instead of frames/baseframes -sm % 4-03-97 changed name to icaproj() -sm % 6-07-97 changed order of args to conform to runica -sm % 6-10-97 fixed data mean handling -sm % 6-23-97 trying pseudo-inverse for non-square weights -sm % 7-23-97 distributed baseline offset (if any) among the activations -sm % 10-31-97 removed errcode -sm % 12-19-00 removed sphere, shifted order of args -sm % 05-29-01 added chansout, made more efficient -sm % 01-25-02 reformated help & license, added links -ad function [icaprojdata] = icaproj(data,weights,compindex,datamean,chansout) verbose = 0; % default no-verbose if nargin<3 % need 3 args help icaproj return end if nargin<4 datamean = 0; % default end if isempty(datamean) datamean = 0; % default end [chans,framestot] = size(data); if nargin<5 chansout = []; end if isempty(chansout) | chansout(1) == 0 chansout = 1:chans; end if min(chansout)<1 | max(chansout)> chans fprintf('icaproj(): chansout variable out of 1:chans range.\n') return end [mchans,epochs] = size(datamean); frames = floor(framestot/epochs); if epochs*frames ~= framestot | frames < 1, fprintf(... 'icaproj(): frames (%d) does not divide data length (%d)\n.',... frames,framestot); return end [ncomps,cols] = size(compindex); if cols>1, if ncomps==1, % if row vector, compindex = compindex'; % make col vector ncomps = cols; else fprintf('icaproj(): compindex must be a vector\n'); return end end if ncomps>chans, fprintf('icaproj(): compindex must have <= %d entries\n',chans); return end for a=1:ncomps-1 for b=a+1:ncomps if compindex(a,1)==compindex(b,1), fprintf('icaproj(): component index repeated in compindex\n.'); return end end end for a=1:ncomps if compindex(a)>chans | compindex(a)<1 fprintf('icaproj(): component index %d out of range!\n',compindex(a)); return break end end if nargin<4 datamean = 0; % default end if datamean ~= 0, % % Remove row means, e.g. those subtracted prior to ICA training by runica() % if verbose==1, fprintf('Removing data means of each channel and data epoch...\n'); end for e=1:epochs data(:,(e-1)*frames+1:e*frames) = ... data(:,(e-1)*frames+1:e*frames) - datamean(:,e)*ones(1,frames); end; end if verbose == 1 fprintf('Final input data range: %g to %g\n', ... min(min(data)),max(max(data))); end if size(weights,1) == size(weights,2) iweights = inv(weights); % inverse weight matrix else iweights = pinv(weights); % pseudo-inverse weight matrix end activations = weights(compindex,:)*data; % activation waveforms % at desired components if ncomps==1, % compute outer product only for single component projection if verbose==1, fprintf('icaproj(): Projecting data for ICA component %d\n',... compindex(1)); end else % if ncomps > 1 if verbose==1, fprintf('icaproj(): Projecting data for ICA components '); if ncomps<32 for n=1:ncomps % for each included component fprintf('%d ',compindex(n)); end else fprintf('specified.'); end fprintf('\n'); % copy selected activations end end icaprojdata = iweights(chansout,compindex)*activations; % reconstitute selected scalp data channels from selected ICA components
github
ZijingMao/baselineeegtest-master
epoch.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/epoch.m
7,001
utf_8
340a95a2503450e01dbd7c4c0dcc9951
% epoch() - Extract epochs time locked to specified events from continuous EEG data. % % Usage: % >> epocheddata = epoch( data, events, timelim); % >> [epocheddata, newtime, indices, rerefevent, rereflatencies ] = ... % epoch( data, events, timelim, 'key1', value1, ... ); % % Inputs: % data - input data (chan,frames). In the case, data is a % 3D array (chan, frames, epochs), epochs are extracted % only if their time windows fall within existing % pre-existing epochs. % events - vector events (expressed in seconds or points) % timelim - [init end] in second or points centered % on the events (i.e. [-1 2]) % % Optional inputs: % 'srate' - sampling rate in Hz for events expressed in seconds % 'valuelim' - [min max] data limits. If one positive value is given, % the opposite value is used for lower bound. For example, % use [-50 50] to remove artifactual epoch. Default: none. % 'verbose' - ['on'|'off']. Default is 'on'. % 'allevents' - event vector containing the latencies of all events % (not only those used for epoching). The function % return an array 'rerefevent' which contain the latency % of these events in each trials (assuming the events are % included in the trial time window). These events can % be in point or second but they must be in the same format % as the events used for epoching. % 'alleventrange' - for event selection, defines a time range [start end] (in % seconds or data points) relative to the time-locking events. % Default is same as 'timelim'. % % Outputs: % epocheddata - output (chan, frames, epochs) % indices - indices of accepted events % newtime - new time limits. See notes. % rerefevent - re-referenced event cell array (size nbepochs) of array % indices for each epochs (note that the number of events % per trial may vary). % rereflatencies - re-referenced latencies event cell array (same as above % but indicates event latencies in epochs instead of event % indices). % % Note: maximum time limit will be reduced by one point with comparison to the % input time limits. For instance at 100 Hz, 3 seconds last 300 points, % but if we assign time 0 to the first point, then we must assign time % 299 to the last point. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: pop_epoch(), 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 [epochdat, newtime, indexes, alleventout, alllatencyout, reallim] = epoch( data, events, lim, varargin ); if nargin < 2 help epoch; return; end; alleventout = {}; % create structure % ---------------- if ~isempty(varargin) try, g = struct(varargin{:}); catch, error('Epoch: wrong syntax in function arguments'); end; else g = []; end; try, g.srate; catch, g.srate = 1; end; try, g.valuelim; catch, g.valuelim = [-Inf Inf]; end; try, g.verbose; catch, g.verbose = 'on'; end; try, g.allevents; catch, g.allevents = []; end; try, g.alleventrange; catch, g.alleventrange = lim; end; % computing point limits % ---------------------- reallim(1) = round(lim(1)*g.srate); % compute offset reallim(2) = round(lim(2)*g.srate-1); % compute offset % epoching % -------- fprintf('Epoching...\n'); newdatalength = reallim(2)-reallim(1)+1; eeglab_options; if option_memmapdata == 1 epochdat = mmo([], [size(data,1), newdatalength, length(events)]); else epochdat = zeros( size(data,1), newdatalength, length(events) ); end; g.allevents = g.allevents(:)'; datawidth = size(data,2)*size(data,3); dataframes = size(data,2); indexes = zeros(length(events),1); alleventout = {}; alllatencyout = {}; for index = 1:length(events) pos0 = floor(events(index)*g.srate); % offset of time locking event posinit = pos0+reallim(1); % compute offset posend = pos0+reallim(2); % compute offset if floor((posinit-1)/dataframes) == floor((posend-1)/dataframes) && posinit >= 1 && posend <= datawidth % test if within boundaries tmpdata = data(:,posinit:posend); epochdat(:,:,index) = tmpdata; if ~isinf(g.valuelim(1)) || ~isinf(g.valuelim(2)) tmpmin = min(reshape(tmpdata, prod(size(tmpdata)),1)); tmpmax = max(reshape(tmpdata, prod(size(tmpdata)),1)); if (tmpmin > g.valuelim(1)) && (tmpmax < g.valuelim(2)) indexes(index) = 1; else switch g.verbose, case 'on', fprintf('Warning: event %d out of value limits\n', index); end; end; else indexes(index) = 1; end; else switch g.verbose, case 'on', fprintf('Warning: event %d out of data boundary\n', index); end; end; % rereference events % ------------------ if ~isempty(g.allevents) posinit = pos0 + g.alleventrange(1)*g.srate; % compute offset posend = pos0 + g.alleventrange(2)*g.srate; % compute offset eventtrial = intersect_bc( find(g.allevents*g.srate >= posinit), find(g.allevents*g.srate <= posend) ); alleventout{index} = eventtrial; alllatencyout{index} = g.allevents(eventtrial)*g.srate-pos0; end; end; newtime(1) = reallim(1)/g.srate; newtime(2) = reallim(2)/g.srate; epochdat(:,:,find(indexes == 0)) = []; indexes = find(indexes == 1); %epochdat = epochdat(:,:,indexes); if ~isempty(alleventout) alleventout = alleventout(indexes); alllatencyout= alllatencyout(indexes); end; reallim = reallim*g.srate; return; %% GENERATION OF NAN IN ARRAYS (old implementation) %% ------------------------------------------------ %alleventout(index,1:length(eventtrial) ) = eventtrial+1000000; %%then replace all zeros by Nan and subtract 1000000 %if ~isempty(alleventout) % alleventout( find( alleventout == 0) ) = nan; % alleventout = alleventout(indexes,:) - 1000000; % alllatencyout( find( alllatencyout == 0) ) = nan; % alllatencyout = alllatencyout(indexes,:) - 1000000; %end; function res = lat2point( lat, srate, pnts); res = lat*srate+1 + (epoch_array-1)*pnts;
github
ZijingMao/baselineeegtest-master
headplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/headplot.m
34,780
utf_8
df090bdd0b2bc2329ab6ebb70a00813d
% headplot() - plot a spherically-splined EEG field map on a semi-realistic % 3-D head model. Can 3-D rotate the head image using the left % mouse button. % Example: % >> headplot example % show an example spherical 'eloc_angles' file % >> headplot cartesian % show an example cartesian 'eloc_angles' file % % Setup usage (do only once for each scalp montage): % % >> headplot('setup', elocs, splinefile, 'Param','Value',...); % % % % NOTE: previous call format below is still supported % % >> headplot('setup', elocs, splinefile, comment, type); % % Required Setup-mode Inputs: % % elocs - file of electrode locations (compatible with readlocs()), % or EEG.chanlocs channel location structure. If the channel % file extension is not standard, use readlocs() to load the % data file, e.g. % >> headplot('setup', ... % readlocs('myfile.xxx', 'filetype', 'besa'),... % 'splinefile'); % splinefile - name of spline file to save spline info into. It is saved as a % *.mat file and should be given the extension .spl . % % Optional Setup-mode Inputs: % % 'meshfile' - ['string' or structure] Matlab files containing a mesh. The % mesh may be of different formats. It may be a Dipfit mesh as % defined in the file standard_vol.mat. It may contain % a structure with the fields 'vertices' and 'faces' or it % it may contain a structure with at least two fields: % POS - 3-D positions of vertices: % x=left-right; y=back-front; z=up-down % TRI1 - faces on which the scalp map should be computed % plus possible optional fields are: % center (optional) - 3-D center of head mesh % TRI2 (optional) - faces in skin color % NORM (optional) - normal for each vertex (better shading) % 'orilocs' - ['off'|'on'] use original electrode locations on the head % {default: 'off'} (extrapolated to spherical). Note that these % electrode locations must be coregisted with the head mesh. % 'transform' - [real array] Talairach-model transformation matrix to co-register % the electrode locations with the head mesh: % [shiftX shiftY shiftZ pitch roll yaw scaleX scaleY scaleZ] % The transform is applied in the order shift(rotate(scale(elocs))) % by the dipfit2.* plugin function traditionaldipfit.m % This array is returned by coregister(). % 'plotmeshonly' - [string] plot only mesh and electrode positions. Options are % 'head' to plot the standard head mesh; 'sphere' to plot the % texture of the head on a sphere; 'off' not to plot anything. % {default: 'off'} % 'comment' - ['string'] optional string containing comments for spline file % {default: []} % % Standard-mode Usage thereafter: % % >> headplot(values,'spline_file','Param','Value',...) % % Required Standard-mode Inputs: % % values - vector containing a data value at each electrode position % 'spline_file' - spline filename, computed and saved in 'setup' mode (above) % % Optional Standard-mode Inputs: % % 'meshfile' - [string] mesh file name. See file content in the setup-mode % description above. {default: the EEGLAB head template file}. % 'electrodes' - ['on'|'off'] -> show electrode positions {default 'on'} % 'title' - Plot title {default: none} % 'labels' - 2 -> plot stored electrode labels; % 1 -> plot channel numbers; 0 -> no labels {default 0} % 'cbar' - 0 -> Plot colorbar {default: no colorbar} % Note: standard jet colormap) red = +;blue = -;green=0 % h -> Colorbar axis handle (to specify headplot location) % 'view' - Camera viewpoint in deg. [azimuth elevation] % 'back'|'b'=[ 0 30]; 'front'|'f'=[180 30] % 'left'|'l'=[-90 30]; 'right'|'r'=[ 90 30]; % 'frontleft'|'bl','backright'|'br', etc., % 'top'=[0 90], Can rotate with mouse {default [143 18]} % 'maplimits' - 'absmax' -> make limits +/- the absolute-max % 'maxmin' -> scale to data range % [min,max] -> user-definined values % {default = 'absmax'} % 'lights' - (3,N) matrix whose rows give [x y z] pos. of each of % N lights {default: four lights at corners} % 'electrode3d' - ['on'|'off'] plot electrodes in 3-D. Default is 'off'. % 'lighting' - 'off' = show wire frame head {default 'on'} % 'material' - [see material function] {default 'dull'} % 'colormap' - 3-column colormap matrix {default: jet(64)} % 'verbose' - 'off' -> no msgs, no rotate3d {default: 'on'} % 'orilocs' - [channel structure or channel file name] Use original % channel locations instead of the one extrapolated from % spherical locations. Note that if you use 'orilocs' % during setup, this is not necessary here since the % original channel location have already been saved. % This option might be useful to show more channels than % the ones actually used for interpolating (e.g., fiducials). % 'transform' - [real array] homogeneous transformation matrix to apply % to the original locations ('orilocs') before plotting them. % % Note: if an error is generated, headplot() may close the current figure % % Authors: Arnaud Delorme, Colin Humphries, Scott Makeig, SCCN/INC/UCSD, % La Jolla, 1998- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Copyright (C) Arnaud Delorme, Colin Humphries and Scott Makeig, % CNL / Salk Institute, Feb. 1998 % % Spherical spline method: Perrin et al. (1989) Electroenceph clin Neurophys % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 12-12-98 changed electrode label lines to MarkerColor -sm % 12-12-98 added colorbar option -sm (still graphically marred by tan rect.) % 12-13-98 implemented colorbar option using enhanced cbar -sm % 12-13-98 implemented 'setup' comment option -sm % 03-20-00 added cartesian electrode locations option -sm % 07-14-00 fixed line in calgx() -sm from -ch % 03-23-01 documented 'cartesian' locfile option -sm % 01-25-02 reformated help & license, added links -ad % 03-21-02 added readlocs and the use of eloc input structure -ad function [HeadAxes, ColorbarHandle] = headplot(values, arg1, varargin) if nargin < 1 help headplot return end %%%%%%%%%%%%%%%%%%%%%%%%%% Set Defaults %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% icadefs % load definitions set(gca,'Color',BACKCOLOR); DEFAULT_MESH = ['mheadnew.mat']; % upper head model file (987K) DEFAULT_TRANSFORM = [0 -5 0 -0.1000 0 -1.5700 1040 800 950]; % stretching in different dimensions DEFAULT_TRANSFORM = [0 -10 0 -0.1000 0 -1.600 1100 1100 1100]; % keep spherical shape. %DEFAULT_MESH = '/home/arno/matlab/juliehiresmesh.mat'; %DEFAULT_MESH = ['/home/scott/matlab/old' '/newupper.mat']; % whole head model file (183K) DEFAULT_LIGHTS = [-125 125 80; ... 125 125 80; ... 125 -125 125; ... -125 -125 125]; % default lights at four corners HeadCenter = [0 0 30]; FaceColor = [.8 .55 .35]*1.1; % ~= ruddy Caucasian - pick your complexion! MAX_ELECTRODES = 1024; ElectDFac = 1.06; % plot electrode marker dots out from head surface plotelecopt.NamesDFac = 1.05; % plot electrode names/numbers out from markers plotelecopt.NamesColor = 'k'; % 'r'; plotelecopt.NamesSize = 10; % FontSize for electrode names plotelecopt.MarkerColor= [0.5 0.5 0.5]; plotelecopt.electrodes3d = 'off'; sqaxis = 1; % if non-zero, make head proportions anatomical title_font = 18; if isstr(values) values = lower(values); if strcmp(values,'setup') % %%%%%%%%%%%%%%%%%%% Perform splining file setup %%%%%%%%%%%%%%%%%%%%%%%%%%%% % if nargin < 3 help headplot; return; end; eloc_file = arg1; spline_file = varargin{1}; g = finputcheck(varargin(2:end), { 'orilocs' 'string' { 'on','off' } 'off'; 'plotmeshonly' 'string' { 'head','off','sphere' } 'off'; 'meshfile' { 'string','struct' } [] DEFAULT_MESH; 'chaninfo' 'struct' [] struct([]); 'plotchans' 'integer' [] []; 'ica' 'string' { 'on','off' } 'off'; 'transform' 'real' [] DEFAULT_TRANSFORM; 'comment' 'string' [] '' }, 'headplot', 'ignore'); if isstr(g), error(g); end; %%%%%%%%%%%%%%%%%%%%%%%%%%% % Open electrode file %%%%%%%%%%%%%%%%%%%%%%%%%%% [eloc_file labels Th Rd indices] = readlocs(eloc_file); indices = find(~cellfun('isempty', { eloc_file.X })); % channels to plot % ---------------- if isempty(g.plotchans), g.plotchans = [1:length(eloc_file)]; end; if ~isfield(g.chaninfo, 'nosedir'), g.chaninfo(1).nosedir = '+x'; end; indices = intersect_bc(g.plotchans, indices); % if ICA select subset of channels if necessary % --------------------------------------------- if ~isfield(g.chaninfo, 'icachansind'), g.chaninfo(1).icachansind = 1:length(eloc_file); end; if strcmpi(g.ica, 'on'), rmchans2 = setdiff_bc( g.chaninfo.icachansind, indices ); % channels to remove (non-plotted) newinds = 1:length(g.chaninfo.icachansind); allrm = []; % remove non-plotted channels from indices for index = 1:length(rmchans2) chanind = find(g.chaninfo.icachansind == rmchans2(index)); allrm = [ allrm chanind ]; end; newinds(allrm) = []; indices = newinds; eloc_file = eloc_file(g.chaninfo.icachansind); end; fprintf('Headplot: using existing XYZ coordinates\n'); ElectrodeNames = strvcat({ eloc_file.labels }); ElectrodeNames = ElectrodeNames(indices,:); Xeori = [ eloc_file(indices).X ]'; Yeori = [ eloc_file(indices).Y ]'; Zeori = [ eloc_file(indices).Z ]'; [newPOS POS TRI1 TRI2 NORM index1 center] = getMeshData(g.meshfile); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % rotate channel coordinates if necessary %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmpi(lower(g.chaninfo.nosedir), '+x') rotate = 0; else if strcmpi(lower(g.chaninfo.nosedir), '+y') rotate = 3*pi/2; elseif strcmpi(lower(g.chaninfo.nosedir), '-x') rotate = pi; else rotate = pi/2; end; allcoords = (Yeori + Xeori*sqrt(-1))*exp(sqrt(-1)*rotate); Xeori = imag(allcoords); Yeori = real(allcoords); end; newcoords = [ Xeori Yeori Zeori ]; %newcoords = transformcoords( [ Xe Ye Ze ], [0 -pi/16 -1.57], 100, -[6 0 46]); %newcoords = transformcoords( [ Xeori Yeori Zeori ], g.transform(4:6), g.transform(7:9), g.transform(1:3)); % same performed below with homogenous transformation matrix transmat = traditionaldipfit( g.transform ); % arno newcoords = transmat*[ newcoords ones(size(newcoords,1),1)]'; newcoords = newcoords(1:3,:)'; % original center was [6 0 16] but the center of the sphere is [0 0 30] % which compensate (see variable Headcenter) %newcoords = transformcoords( [ Xe Ye Ze ], -[0 0 -pi/6]); % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % normalize with respect to head center % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% newcoordsnorm = newcoords - ones(size(newcoords,1),1)*HeadCenter; tmpnorm = sqrt(sum(newcoordsnorm.^2,2)); Xe = newcoordsnorm(:,1)./tmpnorm; Ye = newcoordsnorm(:,2)./tmpnorm; Ze = newcoordsnorm(:,3)./tmpnorm; %plotchans3d([ Xe Ye Ze], cellstr(ElectrodeNames)); return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Calculate g(x) for electrodes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmpi(g.plotmeshonly, 'off') fprintf('Setting up splining matrix.\n'); enum = length(Xe); onemat = ones(enum,1); G = zeros(enum,enum); for i = 1:enum ei = onemat-sqrt((Xe(i)*onemat-Xe).^2 + (Ye(i)*onemat-Ye).^2 + ... (Ze(i)*onemat-Ze).^2); % default was /2 and no sqrt gx = zeros(1,enum); for j = 1:enum gx(j) = calcgx(ei(j)); end G(i,:) = gx; end end; fprintf('Calculating splining matrix...\n') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Open mesh file - contains POS and index1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Project head vertices onto unit sphere %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% spherePOS = newPOS-ones(size(newPOS,1),1)*HeadCenter; % recenter nPOSnorm = sqrt(sum(spherePOS.^2,2)); spherePOS(:,1) = spherePOS(:,1)./nPOSnorm; spherePOS(:,2) = spherePOS(:,2)./nPOSnorm; spherePOS(:,3) = spherePOS(:,3)./nPOSnorm; x = spherePOS(:,1); y = spherePOS(:,2); z = spherePOS(:,3); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Calculate new electrode positions on head %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmpi(g.orilocs, 'off') fprintf('Computing electrode locations on head...\n'); for i=1:length(Xe) elect = [Xe(i) Ye(i) Ze(i)]; dists = distance(elect,spherePOS'); [S,I] = sort(dists); npoints = I(1:3); % closest 3 points diffe = newPOS(npoints,:)-spherePOS(npoints,:); newElect(i,:) = elect+mean(diffe)*ElectDFac; %if Ze(i) < 0 % Plot superior electrodes only. % newElect(i,:) = [0 0 0]; % Mark lower electrodes as having %end % an electrode position not to be plotted end else fprintf('Using original electrode locations on head...\n'); newElect = newcoords; end; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % plot mesh and electrodes only % %%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~strcmpi(g.plotmeshonly, 'off') if strcmpi(g.plotmeshonly, 'sphere') newElect(:,1) = Xe; newElect(:,2) = Ye; newElect(:,3) = Ze; POS(index1,:) = spherePOS; HeadCenter = [ 0 0 0 ]; end; plotmesh(TRI1, POS, NORM); plotelecopt.labelflag = 0; plotelec(newElect, ElectrodeNames, HeadCenter, plotelecopt); rotate3d; return; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Calculate g(x) for sphere mesh vertices %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fprintf('Computing %d vertices. Should take a while (see wait bar)\n',... length(x)) fprintf(' but doesnt have to be done again for this montage...\n'); icadefs; gx = fastcalcgx(x,y,z,Xe,Ye,Ze); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Save spline file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% comment = g.comment; headplot_version = 2; transform = g.transform; try, save(spline_file, '-V6', '-mat', 'Xe', 'Ye', 'Ze', 'G', 'gx', 'newElect', ... 'ElectrodeNames', 'indices', 'comment', 'headplot_version', 'transform'); catch, try, save(spline_file, '-mat', 'Xe', 'Ye', 'Ze', 'G', 'gx', 'newElect', ... 'ElectrodeNames', 'indices', 'comment', 'headplot_version', 'transform'); catch, error('headplot: save spline file error, out of space or file permission problem'); end; end; tmpinfo = dir(spline_file); fprintf('Saving (%dk) file %s\n',round(tmpinfo.bytes/1000), spline_file); return elseif strcmp(values,'example') | strcmp(values,'demo') % %%%%%%%%%%%%%%%%%% Show an example electrode angles file %%%%%%%%%%%%%%%%%%%%%%%% % fprintf(['\nExample of a headplot() electrode angles file (spherical coords.)\n',... 'Fields: chan_num cor_deg horiz_deg channel_name\n\n',... ' 1 -90 -72 Fp1.\n',... ' 2 90 72 Fp2.\n',... ' 3 -62 -57 F3..\n',... ' 4 62 57 F4..\n',... ' 5 -45 0 C3..\n',... ' 6 45 0 C4..\n',... ' 7 -118 2 A1..\n',... ' 8 118 -2 A2..\n',... ' 9 -62 57 P3..\n',... ' 10 62 -57 P4..\n',... ' 11 -90 72 O1..\n',... ' 12 90 -72 O2..\n',... ' 13 -90 -36 F7..\n',... ' 14 90 36 F8..\n',... ' 15 -90 0 T3..\n',... ' 16 90 0 T4..\n',... ' 17 -90 36 T5..\n',... ' 18 90 -36 T6..\n',... ' 19 45 90 Fz..\n',... ' 20 0 0 Cz..\n',... ' 21 45 -90 Pz..\n',... '\nA 90 deg coronal rotation points to right ear, -90 to left.\n' ,... 'A positive horizontal rotation is counterclockwise from above.\n',... 'Use pol2sph() to convert from topoplot() format to spherical.\n',... 'Channel names should have 4 chars (. = space).\n',... 'See also >> headplot cartesian\n\n\n']); return elseif strcmp(values,'cartesian') % %%%%%%%%%%%%%%%%%% Show an example cartesian electrode file %%%%%%%%%%%%%%%%%%% % fprintf(['\nExample of a headplot() electrode location file (cartesian coords.)\n',... 'Fields: chan_num x y z channel_name\n\n',... ' 1 0.4528 0.8888 -0.0694 Fp1.\n',... 'Channel names should have 4 chars (. = space).\n',... 'See also >> headplot example\n\n\n']); return else fprintf('headplot(): Unknown first argument (%s).\n',values) help headplot end else % %%%%%%%%%%%%%%%%%%%%%%%%%% Make the plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if nargin < 2 help headplot return end spline_file = arg1; g = finputcheck( varargin, { ... 'cbar' 'real' [0 Inf] []; % Colorbar value must be 0 or axis handle.' 'lighting' 'string' { 'on','off' } 'on'; 'verbose' 'string' { 'on','off' } 'on'; 'maplimits' { 'string','real' } [] 'absmax'; 'title' 'string' [] ''; 'lights' 'real' [] DEFAULT_LIGHTS; 'view' { 'string','real' } [] [143 18]; 'colormap' 'real' [] jet(256); 'transform' 'real' [] []; 'meshfile' {'string','struct' } [] DEFAULT_MESH; 'electrodes' 'string' { 'on','off' } 'on'; 'electrodes3d' 'string' { 'on','off' } 'off'; 'material' 'string' [] 'dull'; 'orilocs' { 'string','struct' } [] ''; 'labels' 'integer' [0 1 2] 0 }, 'headplot'); if isstr(g) error(g); end; plotelecopt.electrodes3d = g.electrodes3d; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Open head mesh and electrode spline files %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~exist(spline_file) error(sprintf('headplot(): spline_file "%s" not found. Run headplot in "setup" mode\n',... spline_file)); end load(spline_file, '-mat'); if exist('indices'), try, values = values(indices); catch, error('problem of index or electrode number with splinefile'); end; end; enum = length(values); if enum ~= length(Xe) close; error('headplot(): Number of values in spline file should equal number of electrodes') end % change electrode if necessary % ----------------------------- if ~isempty(g.orilocs) eloc_file = readlocs( g.orilocs ); fprintf('Using original electrode locations on head...\n'); indices = find(~cellfun('isempty', { eloc_file.X } )); newElect(:,1) = [ eloc_file(indices).X ]'; % attention inversion before newElect(:,2) = [ eloc_file(indices).Y ]'; newElect(:,3) = [ eloc_file(indices).Z ]'; % optional transformation % ----------------------- if ~isempty(g.transform) transmat = traditionaldipfit( g.transform ); % arno newElect = transmat*[ newElect ones(size(newElect,1),1)]'; newElect = newElect(1:3,:)'; end; end; % -------------- % load mesh file % -------------- [newPOS POS TRI1 TRI2 NORM index1 center] = getMeshData(g.meshfile); %%%%%%%%%%%%%%%%%%%%%%%%%% % Perform interpolation %%%%%%%%%%%%%%%%%%%%%%%%%% meanval = mean(values); values = values - meanval; % make mean zero onemat = ones(enum,1); lamd = 0.1; C = pinv([(G + lamd);ones(1,enum)]) * [values(:);0]; % fixing division error P = zeros(1,size(gx,1)); for j = 1:size(gx,1) P(j) = dot(C,gx(j,:)); end P = P + meanval; %%%%%%%%%%%%%%%%%%%%%%%%%% % Plot surfaces %%%%%%%%%%%%%%%%%%%%%%%%%% cla % clear axis HeadAxes = gca; W = zeros(1,size(POS,1)); m = size(g.colormap,1); if size(g.maplimits) == [1,2] amin = g.maplimits(1); amax = g.maplimits(2); elseif strcmp(g.maplimits,'maxmin') | strcmp(g.maplimits,'minmax') amin = min(min(abs(P)))*1.02; % 2% shrinkage keeps within color bounds amax = max(max(abs(P)))*1.02; elseif strcmp(g.maplimits,'absmax') amin = min(min(abs(P)))*1.02; % 2% shrinkage keeps within color bounds amax = max(max(abs(P)))*1.02; amax = max(-amin, amax); amin = -amax; %amin = -max(max(abs(P)))*1.02; % 2% shrinkage keeps within color bounds %amax = -amin; end idx = min(m,round((m-1)*(P-amin)/(amax-amin))+1); % get colormap indices %subplot(1,2,1); hist(P(:)); %idx = round((m-1)*P/(amax-amin))+m/2; %idx = max(1,min(m,idx)); % get colormap indices %subplot(1,2,2); hist(idx(:)); %return; W(index1) = idx; colormap(g.colormap) p1 = patch('Vertices',POS,'Faces',TRI1,'FaceVertexCdata',W(:),... 'FaceColor','interp', 'cdatamapping', 'direct', 'tag', 'mesh'); %%%%%%%%% Plot scalp map %%%%%%%%% if exist('NORM') == 1 & ~isempty(NORM) set(p1, 'vertexnormals', NORM); end; if ~isempty(TRI2) FCmap = [g.colormap; g.colormap(end,:); FaceColor; FaceColor; FaceColor]; colormap(FCmap) W = ones(1,size(POS,1))*(m+2); p2 = patch('Vertices',POS,'Faces',TRI2,'FaceColor','interp',... 'FaceVertexCdata',W(:)); %%%%%%%% Plot face and lower head %%%%%% else p2 = []; end; axis([-125 125 -125 125 -125 125]) axis off % hide axis frame %%%%%%%%%%%%%%%%%%%%%%%%% % Draw colorbar - Note: uses enhanced cbar() function by Colin Humphries %%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(g.cbar) BACKCOLOR = get(gcf,'Color'); if g.cbar == 0 ColorbarHandle = cbar(0,3,[amin amax]); 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 ColorbarHandle = cbar(g.cbar,3,[amin amax]); end end axes(HeadAxes); %%%%%%%%%%%%%%%%%%%%%%%%% % Turn on lights %%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(g.lighting,'on') set([p1 p2],'EdgeColor','none') for i = 1:size(g.lights,1) hl(i) = light('Position',g.lights(i,:),'Color',[1 1 1],... 'Style','infinite'); end if ~isempty(p2) set(p2,'DiffuseStrength',.6,'SpecularStrength',0,... 'AmbientStrength',.4,'SpecularExponent',5) end; set(p1,'DiffuseStrength',.6,'SpecularStrength',0,... 'AmbientStrength',.3,'SpecularExponent',5) lighting phong % all this gives a matte reflectance material(g.material); end %%%%%%%%%%%%%%%%%%%%%%%%% % Set viewpoint %%%%%%%%%%%%%%%%%%%%%%%%% if isstr(g.view) switch lower(g.view) case {'front','f'} view(-180,30) case {'back','b'} view(0,30) case {'left','l'} view(-90,30) case {'right','r'} view(90,30) case {'frontright','fr'} view(135,30) case {'backright','br'} view(45,30) case {'frontleft','fl'} view(-135,30) case {'backleft','bl'} view(-45,30) case 'top' view(0,90) case 'bottom' % undocumented option! view(0,-90) Lights = [-125 125 80; ... 125 125 80; ... 125 -125 125; ... -125 -125 125; ... 0 10 -80]; % add light from below! otherwise close; error(['headplot(): Invalid View value %s',g.view]) end else if ~isstr(g.view) [h,a] = size(g.view); if h~= 1 | a~=2 close; error('headplot(): View matrix size must be (1,2).') end end view(g.view) % set camera viewpoint end if strcmp(g.electrodes,'on') % plot the electrode locations if exist('newElect') plotelecopt.labelflag = g.labels; plotelec(newElect, ElectrodeNames, HeadCenter, plotelecopt); else fprintf('Variable newElect not read from spline file.\n'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Turn on rotate3d, allowing rotation of the plot using the mouse %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(g.verbose,'on') rotate3d on; % Allow 3-D rotation of the plot by dragging the else % left mouse button while cursor is on the plot rotate3d off end % Make axis square if sqaxis axis image % keep the head proportions human and as large as possible end % Add a plot title if ~isempty(g.title); % title(['\n' g.title],'fontsize',title_font); title([g.title],'fontsize',title_font); % Note: \n not interpreted by matlab-5.2 end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % calcgx() - function used in 'setup' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [out] = calcgx(in) out = 0; m = 4; % 4th degree Legendre polynomial for n = 1:7 % compute 7 terms L = legendre(n,in); out = out + ((2*n+1)/(n^m*(n+1)^m))*L(1); end out = out/(4*pi); %%%%%%%%%%%%%%%%%%% function gx = fastcalcgx(x,y,z,Xe,Ye,Ze) onemat = ones(length(x),length(Xe)); EI = onemat - sqrt((repmat(x,1,length(Xe)) - repmat(Xe',length(x),1)).^2 +... (repmat(y,1,length(Xe)) - repmat(Ye',length(x),1)).^2 +... (repmat(z,1,length(Xe)) - repmat(Ze',length(x),1)).^2); % gx = zeros(length(x),length(Xe)); m = 4; icadefs; hwb = waitbar(0,'Computing spline file (only done once)...', 'color', BACKEEGLABCOLOR); hwbend = 7; for n = 1:7 L = legendre(n,EI); gx = gx + ((2*n+1)/(n^m*(n+1)^m))*squeeze(L(1,:,:)); waitbar(n/hwbend,hwb); end gx = gx/(4*pi); close(hwb); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % distance() - function used in 'setup' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [out] = distance(w,p) % w is a matrix of row vectors % p is a matrix of column vectors l1 = size(w,1); l2 = size(p,2); out = zeros(l1,l2); for i = 1:l1 x = w(i,:)'*ones(1,l2); out(i,:) = sum((x-p).^2).^.5; end % %%%%%%%%%%%%%%% % plot electrodes % %%%%%%%%%%%%%%% function plotelec(newElect, ElectrodeNames, HeadCenter, opt); newNames = newElect*opt.NamesDFac; % Calculate electrode label positions for i = 1:size(newElect,1) if newElect(i,:) ~= [0 0 0] % plot radial lines to electrode sites if strcmpi(opt.electrodes3d, 'off') line([newElect(i,1) HeadCenter(1)],[newElect(i,2) HeadCenter(2)],... [newElect(i,3) HeadCenter(3)],'color',opt.MarkerColor,'linewidth',1); end; if opt.labelflag == 1 % plot electrode numbers t=text(newNames(i,1),newNames(i,2),newNames(i,3),int2str(i)); set(t,'Color',opt.NamesColor,'FontSize',opt.NamesSize,'FontWeight','bold',... 'HorizontalAlignment','center'); elseif opt.labelflag == 2 % plot electrode names if exist('ElectrodeNames') name = sprintf('%s',ElectrodeNames(i,:)); t=text(newNames(i,1),newNames(i,2),newNames(i,3),name); set(t,'Color',opt.NamesColor,'FontSize',opt.NamesSize,'FontWeight','bold',... 'HorizontalAlignment','center'); else fprintf('Variable ElectrodeNames not read from spline file.\n'); end else % plot electrode markers if strcmpi(opt.electrodes3d, 'off') line(newElect(:,1),newElect(:,2),newElect(:,3),'marker',... '.','markersize',20,'color',opt.MarkerColor,'linestyle','none'); else [xc yc zc] = cylinder( 2, 10); [xs ys zs] = sphere(10); xc = [ xc; -xs(7:11,:)*2 ]; yc = [ yc; -ys(7:11,:)*2 ]; zc = [ zc; zs(7:11,:)*0.2+1 ]; hold on; cylinderSize = 3; colorarray = repmat(reshape(opt.MarkerColor, 1,1,3), [size(zc,1) size(zc,2) 1]); handles = surf(xc*cylinderSize, yc*cylinderSize, zc*cylinderSize, colorarray, 'edgecolor', 'none', ... 'backfacelighting', 'lit', 'facecolor', 'interp', 'facelighting', ... 'phong', 'ambientstrength', 0.3); cylnderHeight = 1; if newElect(i,3) < 10, addZ = -30; else addZ = 0; end; if newElect(i,3) < -20, addZ = -60; else addZ = 0; end; xx = newElect(i,1) - ( newElect(i,1)-HeadCenter(1) ) * 0.01 * cylnderHeight; xxo1 = newElect(i,1) + ( newElect(i,1)-HeadCenter(1) ) * 0.01 * cylnderHeight; yy = newElect(i,2) - ( newElect(i,2)-HeadCenter(2) ) * 0.01 * cylnderHeight; yyo1 = newElect(i,2) + ( newElect(i,2)-HeadCenter(2) ) * 0.01 * cylnderHeight; zz = newElect(i,3) - ( newElect(i,3)-HeadCenter(3)-addZ ) * 0.01 * cylnderHeight; zzo1 = newElect(i,3) + ( newElect(i,3)-HeadCenter(3)-addZ ) * 0.01 * cylnderHeight; [xc yc zc] = adjustcylinder2( handles, [xx yy zz], [xxo1 yyo1 zzo1] ); end; end end end; % get mesh information % -------------------- function [newPOS POS TRI1 TRI2 NORM index1 center] = getMeshData(meshfile); if ~isstruct(meshfile) if ~exist(meshfile) error(sprintf('headplot(): mesh file "%s" not found\n',meshfile)); end fprintf('Loaded mesh file %s\n',meshfile); try meshfile = load(meshfile,'-mat'); catch, meshfile = []; meshfile.POS = load('mheadnewpos.txt', '-ascii'); meshfile.TRI1 = load('mheadnewtri1.txt', '-ascii'); % upper head %try, TRI2 = load('mheadnewtri2.txt', '-ascii'); catch, end; % lower head %index1 = load('mheadnewindex1.txt', '-ascii'); meshfile.center = load('mheadnewcenter.txt', '-ascii'); end; end; if isfield(meshfile, 'vol') if isfield(meshfile.vol, 'r') [X Y Z] = sphere(50); POS = { X*max(meshfile.vol.r) Y*max(meshfile.vol.r) Z*max(meshfile.vol.r) }; TRI1 = []; else POS = meshfile.vol.bnd(1).pnt; TRI1 = meshfile.vol.bnd(1).tri; end; elseif isfield(meshfile, 'bnd') POS = meshfile.bnd(1).pnt; TRI1 = meshfile.bnd(1).tri; elseif isfield(meshfile, 'TRI1') POS = meshfile.POS; TRI1 = meshfile.TRI1; try TRI2 = meshfile.TRI2; end % NEW try center = meshfile.center; end % NEW elseif isfield(meshfile, 'vertices') POS = meshfile.vertices; TRI1 = meshfile.faces; else error('Unknown Matlab mesh file'); end; if exist('index1') ~= 1, index1 = sort(unique(TRI1(:))); end; if exist('TRI2') ~= 1, TRI2 = []; end; if exist('NORM') ~= 1, NORM = []; end; if exist('TRI1') ~= 1, error('Variable ''TRI1'' not defined in mesh file'); end; if exist('POS') ~= 1, error('Variable ''POS'' not defined in mesh file'); end; if exist('center') ~= 1, center = [0 0 0]; disp('Using [0 0 0] for center of head mesh'); end; newPOS = POS(index1,:);
github
ZijingMao/baselineeegtest-master
eegfiltfft.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/eegfiltfft.m
4,093
utf_8
7a24c770da0253fdd7c37b4d445adada
% eegfiltfft() - (high|low|band)-pass filter data using inverse fft % (without using the Matlab signal processing toolbox) % Usage: % >> [smoothdata] = eegfiltfft(data,srate,locutoff,hicutoff); % >> [smoothdata] = eegfiltfft(data,srate,locutoff,hicutoff,epochframes,filtorder,revfilt); % % Inputs: % data = (channels,frames*epochs) data to filter % srate = data sampling rate (Hz) % locutoff = low-edge frequency in pass band (Hz) {0 -> lowpass} % hicutoff = high-edge frequency in pass band (Hz) {0 -> highpass} % % Optional inputs: % epochframes = frames per epoch (filter each epoch separately {def/0: data is 1 epoch} % filtorder = argument not used (but required for symetry with eegfilt() function). % revfilt = [0|1] reverse filter (i.e. bandpass filter to notch filter). {0} % % Outputs: % smoothdata = smoothed data % % Known problems: % The signal drop off is much smaller compared to standard filtering methods % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2003 % % See also: eegfilt() % inspired from a ggogle group message % http://groups.google.com/groups?q=without+%22the+signal+processing+toolbox%22&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=f56893ae.0311141025.3069d4f8%40posting.google.com&rnum=8 % Copyright (C) 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 smoothdata = eegfiltfft(data, fs, lowcut, highcut, epochframes, filtorder, revfilt); if nargin < 4 help eegfiltfft; end; [chans frames] = size(data); if nargin < 5 | epochframes == 0 epochframes = frames; end if nargin < 7 revfilt = 0; end; epochs = frames/epochframes; if epochs ~= round(epochs) error('Epochframes does not divide the total number of frames'); end; fv=reshape([0:epochframes-1]*fs/epochframes,epochframes,1); % Frequency vector for plotting %figure; %plot(fv, 20*log(abs(X))/log(10)) % Plot power spectrum in dB scale %xlabel('Frequency [Hz]') %ylabel('Signal power [dB]') % find closest freq in fft decomposition % -------------------------------------- if lowcut ~= 0 [tmp idxl]=min(abs(fv-lowcut)); % Find the entry in fv closest to 5 kHz else idxl = 0; end; if highcut ~= 0 [tmp idxh]=min(abs(fv-highcut)); % Find the entry in fv closest to 5 kHz else idxh = ceil(length(fv)/2); end; % filter the data % --------------- smoothdata = zeros(chans,frames); for e = 1:epochs % filter each epoch, channel for c=1:chans X=fft(data(c,(e-1)*epochframes+1:e*epochframes)); if revfilt X(idxl+1:idxh-1)=0; if mod(length(X),2) == 0 X(end/2:end)=0; else X((end+1)/2:end)=0; end; else X(1:idxl)=complex(0); X(end-idxl:end)=complex(0); X(idxh:end)=complex(0); end; smoothdata(c,(e-1)*epochframes+1:e*epochframes) = 2*real(ifft(X)); if epochs == 1 if rem(c,20) ~= 0 fprintf('.'); else fprintf('%d',c); end end end end fprintf('\n');
github
ZijingMao/baselineeegtest-master
rejstatepoch.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/rejstatepoch.m
17,342
utf_8
284e9677ee175d6c99cf0d443ddc1676
% rejstatepoch() - reject bad eeg trials based a statistical measure. Can % be applied either to the raw eeg data or the ICA % component activity. This is an interactive function. % % Usage: % >> [ Irej, Irejdetails, n, threshold, thresholdg] = ... % rejstatepoch( signal, rej, 'key1', value1...); % % Inputs: % signal - 3 dimensional data array channel x points x trials % (instead of channels, one might also use independent % components). % rej - rejection array, one value per trial and per channel or % component (size channel x trials). % By default, values are normalized by this % function and trehshold is expressed in term of standard % deviation of the mean. % % Optional inputs: % 'plot' - ['on'|'off'] interactive mode or just rejection. % In the interactive mode, it plots the normalized % entropy of original signal (blue) and the limits % (red) (default:'on') % 'threshold' - percentage error threshold (default 1-0.25/nb_trials) % for individual trials of individual channel/component. % This treshold is expressed in term of standart % deviation from the mean (default 5). % 'global' - ['on'|'off'], also perform threshold on the global % measure (by default, the mean over all channel or % electrodes). % 'rejglob' - rejection array, one value per trials. Use this % argument when the global measure for all channels or % does not correspond to their mean. % 'thresholdg' - global threshold for the reunion of all channels % or components. By default, it is equal to 'threshold'. % 'normalize' - ['on'|'off'], normalize values before applying the % treshold. Default is 'on'. % 'plotcom' - sting command to plot single trials. Default % is none. % 'title' - title of the graph. Default is none. % 'labels' - labels for electrodes (array not cell). % % Outputs: % Irej - indexes of trials to be rejected % Irejdetails - array for rejected components or channel (nb_rejected x % nb_channel or nb_rejected x nb_components) % n - number of trials rejected % threshold - percentage error threshold % thresholdg - percentage error threshold for global rejection % % See also: eeglab() % Algorithm: % normalise the measure given as input and reject trials based on % an uniform distribution of the data % 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 % userdata % gcf : plotsig - signal to plot in the pop_out window % pnts - number of points per epoch % Irej - rejection of trials % Irejelec - rejection of trials and electrodes % labels - labels for curves % plotwin : rej1 - rejection array (with all electrodes x trials) % rej2 - global rejection array (size trials) % thr1 - threshold (electrodes) % thr2 - threshold global function [ Irej, Irejdetails, n, threshold, thresholdg] = rejstatepoch( signal, ... rej, varargin); % pnts, th_E, th_rejg, command, commandplot, typetitle, E, rejg); if nargin < 1 help rejstatepoch; return; end; if ~isstr( signal ) if nargin < 2 help rejstatepoch; return; end; if ~isempty( varargin ), g=struct(varargin{:}); else g= []; end; try, g.plot; catch, g.plot='on'; end; try, g.threshold; catch, g.threshold=5; end; try, g.thresholdg; catch, g.thresholdg=5; end; try, g.global; catch, g.global='on'; end; try, g.rejglob; catch, g.rejglob=[]; end; try, g.normalize; catch, g.normalize='on'; end; try, g.plotcom; catch, g.plotcom=''; end; try, g.title; catch, g.title=''; end; try, g.labels; catch, g.labels=''; end; g.rej = rej; clear rej switch lower(g.plot) case {'on', 'off'} ; otherwise disp('Error: Plot must be either ''on'' or ''off'''); return; end; switch lower(g.global) case {'on', 'off'} ; otherwise disp('Error: Global must be either ''on'' or ''off'''); return; end; switch lower(g.normalize) case {'on', 'off'} ; otherwise disp('Error: Normalize must be either ''on'' or ''off'''); return; end; if ~isstr(g.plotcom) disp('Error: Plotcom must be a string to evaluate'); return; end; if ~isstr(g.title) disp('Error: Title must be a string'); return; end; try, g.threshold*2; catch, disp('Error: Threhsold must be a number'); return; end; try, g.thresholdg*2; catch, disp('Error: Threhsoldg must be a number'); return; end; if length(g.threshold(:)) > 1 disp('Error: Threhsold must be a single number'); return; end; if length(g.thresholdg(:)) > 1 disp('Error: Threhsoldg must be a single number'); return; end; if ~isempty(g.rejglob) if length(g.rejglob) ~= size(g.rej,2) disp('Error: Rejglob must be have the same length as rej columns'); return; end; else switch lower(g.global), case 'on', g.rejglob = sum(g.rej,1); end; end; if size(signal,3) ~= size(g.rej,2) disp('Error: Signal must be have the same number of element in 3rd dimension as rej have columns'); return; end; if isempty(g.labels) for index = 1:size(g.rej,1) g.labels(index,:) = sprintf('%3d', index); end; if ~isempty(g.rejglob) g.labels(index+2,:) = 'g. '; end; end; switch lower(g.normalize), case 'on', g.rej = (g.rej-mean(g.rej,2)*ones(1, size(g.rej,2)))./ (std(g.rej, 0, 2)*ones(1, size(g.rej,2))); switch lower(g.global), case 'on', g.rejglob = (g.rejglob(:)-mean(g.rejglob(:)))./ std(g.rejglob(:)); end; end; switch lower(g.global), case 'off',g.rejglob = []; end; % plot the buttons % ---------------- try, icadefs; catch, GUIBUTTONCOLOR = [0.8 0.8 0.8]; BACKCOLOR = [0.8 0.8 0.8]; end; figure('color', BACKCOLOR); set(gcf, 'name', 'Rejectrials'); pos = get(gca,'position'); % plot relative to current axes set( gca, 'tag', 'mainaxis'); q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]./100; % allow to use normalized position [0 100] for x and y axis('off'); plotsig = sum(abs(signal(:,:)),1); set(gcf, 'userdata', { plotsig, size(signal, 2), [], [] }); % the two last arguments are the rejection % Create axis % ----------- h6 = axes('Units','Normalized', 'tag', 'Plotwin', 'Position',[-10 12 120 84].*s+q); title(g.title); set( h6, 'userdata', { g.rej g.rejglob g.threshold g.thresholdg g.labels }); % g.rej was put twice because it is used to compute the global entropy % CANCEL button % ------------- h = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'Cancel', 'Units','Normalized','Position',... [-15 -6 15 6].*s+q, 'callback', 'close(gcf);', 'backgroundcolor', GUIBUTTONCOLOR); % Entropy component text and threshold % ------------------------------------ makebutton( 'Single-channel', 'Plotwin' , [3 -6 27 6].*s+q, [30 -6 15 6].*s+q, 3, g.threshold, GUIBUTTONCOLOR); makebutton( 'All-channel', 'Plotwin' , [50 -6 27 6].*s+q, [77 -6 15 6].*s+q, 4, g.thresholdg, GUIBUTTONCOLOR); % EEGPLOT button % -------------- if ~isempty(g.plotcom) h = uicontrol(gcf, 'backgroundcolor', GUIBUTTONCOLOR, 'Style', 'pushbutton', 'string', 'EEGPLOT', 'Units','Normalized','Position',[95 -2 15 6].*s+q, ... 'callback',['TMPEEG = get(gcbf, ''userdata'');' ... 'TMPREJ = TMPEEG{3};' ... 'TMPREJELEC = TMPEEG{4};' ... g.plotcom ] ); posaccept = [95 -10 15 6]; else posaccept = [95 -6 15 6]; end; % ACCEPT button % ------------- command = 'fprintf(''Rejection indices has been put in the matrix TMPREJ\n'')'; haccept = uicontrol(gcf, 'backgroundcolor', GUIBUTTONCOLOR, 'Style', 'pushbutton', 'string', 'UPDATE', 'Units','Normalized','Position', posaccept.*s+q, ... 'callback', [ 'set(gcbo, ''userdata'', 1);' ... %signal to signify termination 'TMPEEG = get(gcbf, ''userdata'');' ... 'TMPREJ = TMPEEG{3};' ... 'TMPREJELEC = TMPEEG{4};' ... command ] ); command = [ 'entwin = get(gcbf, ''currentobject'');' ... 'tmptype = get(entwin,''type'');' ... 'if tmptype(1) == ''l'' entwin = get(entwin, ''parent''); end;' ... 'tagwin = get(entwin,''tag'');' ... % either entropy or kurtosis 'switch tagwin,' ... ' case ''Plotwin'',' ... % check if the user clicked on the right window ' alldata = get(gcf, ''userdata'');' ... ' plotsig = alldata{1};' ... ' pnts = alldata{2};' ... ' fig = figure(''position'', [100 300 600 400],''color'', [1 1 1]);' ... ' I = alldata{3};' ... ' sweeps = size(plotsig,2) /pnts;' ... ' h1 = axes(''parent'', fig, ''Units'',''Normalized'', ''Position'',[0.6 0.11 0.27 0.815]);' ... ' pos = get(entwin, ''currentpoint'');' ... ' component = round(pos(1) / sweeps + 0.5);' ... % determine the component number ' alldata = get(entwin, ''userdata'');' ... ' rej = alldata{1};' ... ' if component <= size(rej,1)' ... % component ' rej_threshold = alldata{3};' ... ' component = max(1,min(component, size(rej,1))); ' ... ' rej = rej(component, :);' ... ' titlegraph = sprintf(''' g.title ' #%d'', component);' ... ' colorgraph = ''b'';' ... ' else' ... % global ' rej = alldata{2};' ... ' rej_threshold = alldata{4};' ... ' titlegraph = sprintf(''' g.title ' global'');' ... ' colorgraph = ''g'';' ... ' end;' ... ' plot([1:length(rej)], rej, ''color'', colorgraph);' ... ' ss = get(h1, ''xlim'');' ... ' set(h1, ''view'', [90 90]);' ... ' set(h1, ''xdir'', ''reverse'');' ... ' set(h1, ''XLim'', ss);' ... ' hold on;' ... % plot component ' yl = get(h1, ''ylim'');' ... ' set(h1, ''xtickmode'', ''manual'', ''xtick'', sweeps/2, ''xticklabel'', component, ''xlim'', [ 0 sweeps ]);' ... ' title( titlegraph );' ... ' plot( get(h1, ''xlim''), [rej_threshold rej_threshold], ''r'');' ... % plot limit ' plot( get(h1, ''xlim''), [-rej_threshold -rej_threshold], ''r'');' ... % plot limit ' set(h1, ''xticklabel'', []);' ... ' hold on;' ... ' h2 = axes(''parent'', fig,''Units'',''Normalized'', ''Position'',[0.13 0.11 0.27 0.815]);' ... ' erpimage( plotsig, ones(1,size(plotsig,2)/pnts), [0:1/(pnts-1):1], '''', 3, 1, ''nosort'', ''noplot'');' ... ' title(''Currentset all chans''); xlabel(''''); ylabel(''''); ' ... ' set(gca, ''xticklabel'', []);' ... ' hold on;' ... ' h3 = axes(''parent'', fig,''Units'',''Normalized'', ''Position'',[0.45 0.11 0.1 0.815]);' ... ' if any(I ~= 0)' ... ' rejImage = (I'' * ones(1, 10))'';' ... ' imagesc( rejImage'' );' ... ' set(gca, ''ydir'', ''normal'');' ... ' end;' ... ' title(''Rejected (all)''); xlabel(''''); ylabel('''');' ... ' set(gca, ''xticklabel'', [], ''yticklabel'', []);' ... 'end;' ... 'clear fig tmptype tagwin alldata rej rejImage plotsig sweeps pnts rej_threshold ss q s h1 h2 h3 pos component yl;' ]; % ' erpimage( rejImage(:)'', ones(1,size(I,2)), [0:1/(10-1):1], '''', 1, 0, ''nosort'', ''noplot'');' ... set(gcf, 'WindowButtonDownFcn', command); rejstatepoch('draw'); switch g.plot, case 'on', waitfor( haccept, 'userdata'); drawnow; end; threshold = g.threshold; thresholdg = g.thresholdg; Irej = []; Irejdetails = []; n = 0; try TMPEEG = get(gcf, 'userdata'); Irej = TMPEEG{3}; Irejdetails = TMPEEG{4}; n = length(find(Irej == 1)); plothandler = findobj( 'parent', gcf, 'tag', 'Plotwin'); TMPEEG = get(plothandler, 'userdata'); threshold = TMPEEG{3}; thresholdg = TMPEEG{4}; close(gcf); catch, end; else %if signal is a string draw everything % retreive data % ------------- gcfdata = get(gcf, 'userdata'); plotsig = gcfdata {1}; pnts = gcfdata {2}; sweeps = size(plotsig,2)/pnts; h6 = findobj('parent', gcf, 'tag', 'Plotwin'); alldata = get(h6, 'userdata'); g.rej = alldata {1}; g.rejg = alldata {2}; g.threshold = alldata {3}; g.thresholdg = alldata {4}; set(h6, 'userdata', alldata); nbchans = size(g.rej,1); % reject trials % ------------- rejelec = abs(g.rej) > g.threshold; rej = max(rejelec,[],1); n1 = sum(rej(:)); if ~isempty( g.rejg ) rej2 = abs(g.rejg) > g.thresholdg; n2 = sum(rej2(:)); rej = rej | rej2(:)'; end; fprintf('%d trials rejected (single:%d, all:%d)\n', sum(rej(:)), n1, n2); gcfdata {3} = rej; gcfdata {4} = rejelec; set(gcf, 'userdata', gcfdata); % plot the sorted entropy curve % ----------------------------- plotstat( 'Plotwin'); end; return; function plotstat( id ); % plot the sorted entropy curve % ----------------------------- h6 = findobj('parent', gcf, 'tag', id); axes(h6); cla; ttmp = get(gca, 'title'); oldtitle = get(ttmp, 'string'); % get datas % --------- alldata = get(gca, 'userdata'); g.rej = alldata {1}; g.rejg = alldata {2}; g.threshold = alldata {3}; g.thresholdg = alldata {4}; g.labels = alldata {5}; nbchans = size(g.rej,1); sweeps = size(g.rej,2); % plot datas % ---------- g.rej = g.rej'; plot(g.rej(:)); g.rej = g.rej'; hold on; yl = get(gca, 'ylim'); % plot vertival bars to separate components and the trehsold % ---------------------------------------------------------- set( gca, 'tag', id, 'ylimmode', 'manual'); set(gca, 'xtickmode', 'manual', 'xtick', [0:sweeps:(size(g.rej(:),1)-1+2*sweeps)] + sweeps/2, ... 'xticklabel', g.labels, 'xlim', [ 0 (size(g.rej(:),1)-1+2*sweeps)]); plot( [1 size(g.rej(:),1)], [-g.threshold -g.threshold], 'r'); % plot threshold plot( [1 size(g.rej(:),1)], [g.threshold g.threshold], 'r'); % plot threshold if ~isempty(g.rejg) % plot global ? plot([size(g.rej(:),1)+sweeps:size(g.rej(:),1)+2*sweeps-1], g.rejg(:), 'g'); pp = patch([size(g.rej(:),1) size(g.rej(:),1) size(g.rej(:),1)+sweeps size(g.rej(:),1)+sweeps], [yl(1)-1 yl(2)+1 yl(2)+1 yl(1)-1], get(gcf, 'color'), 'clipping', 'off'); set(pp, 'EdgeColor', get(gcf, 'color')); plot( [size(g.rej(:),1)+sweeps length(g.rejg)+size(g.rej(:),1)+sweeps], [-g.thresholdg -g.thresholdg], 'r'); % plot threshold plot( [size(g.rej(:),1)+sweeps length(g.rejg)+size(g.rej(:),1)+sweeps], [g.thresholdg g.thresholdg], 'r'); % plot threshold plot([size(g.rej(:),1)+sweeps size(g.rej(:),1)+sweeps], yl, 'k'); else pp = patch([size(g.rej(:),1) size(g.rej(:),1) size(g.rej(:),1)+2*sweeps size(g.rej(:),1)+2*sweeps], [yl(1)-1 yl(2)+1 yl(2)+1 yl(1)-1], get(gcf, 'color'), 'clipping', 'off'); set(pp, 'EdgeColor', get(gcf, 'color')); end; for index = 0:sweeps:size(g.rej(:),1); plot([index index], yl, 'k'); end; % restore properties title(oldtitle); set(h6, 'userdata', alldata); return; function makebutton( string, ax, pos1, pos2, userindex, init, GUIBUTTONCOLOR ); h = uicontrol(gcf , 'backgroundcolor', GUIBUTTONCOLOR, 'Style', 'radiobutton', 'string', string, 'value', fastif(init == 0, 0, 1), 'Units','Normalized', 'Position', pos1, ... 'callback', [ 'textresh = findobj(''parent'', gcbf, ''tag'', ''' string ''');' ... 'checkstatus = get(gcbo, ''value'');' ... 'ax = findobj(''parent'', gcbf, ''tag'', ''' ax ''');' ... 'tmpdat = get(ax, ''userdata'');' ... 'if checkstatus' ... % change status of the textbox ' set(textresh, ''enable'', ''on'');' ... ' tmpdat{' int2str(userindex) '} = str2num(get(textresh, ''string''));' ... 'else' ... ' set(textresh, ''enable'', ''off'');' ... ' tmpdat{' int2str(userindex) '} = 0;' ... 'end;' ... 'set(ax, ''userdata'' , tmpdat);' ... 'rejstatepoch(''draw'');' ... 'clear tmpdat ax checkstatus textresh;' ] ); h = uicontrol(gcf, 'Style', 'edit', 'backgroundcolor', [1 1 1], 'tag', string, 'string', num2str(init), 'enable', fastif(init == 0, 'off', 'on'), 'Units','Normalized', 'Position', pos2, ... 'callback', [ 'ax = findobj(''parent'', gcbf, ''tag'', ''' ax ''');' ... 'tmpdat = get(ax, ''userdata'');' ... 'tmpdat{' int2str(userindex) '} = str2num(get(gcbo, ''string''));' ... 'set(ax, ''userdata'' , tmpdat);' ... 'rejstatepoch(''draw'');' ... 'clear tmpdat ax;' ] ); return;
github
ZijingMao/baselineeegtest-master
binica.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/binica.m
13,069
utf_8
e1bfb70b5edae53d01116b6f9cf42d51
% binica() - Run stand-alone binary version of runica() from the % Matlab command line. Saves time and memory relative % to runica(). If stored in a float file, data are not % read into Matlab, and so may be larger than Matlab % can handle owing to memory limitations. % Usage: % >> [wts,sph] = binica( datavar, 'key1', arg1, 'key2', arg2 ...); % else % >> [wts,sph] = binica('datafile', chans, frames, 'key1', arg1, ...); % % Inputs: % datavar - (chans,frames) data matrix in the Matlab workspace % datafile - quoted 'filename' of float data file multiplexed by channel % channels - number of channels in datafile (not needed for datavar) % frames - number of frames (time points) in datafile (only) % % Optional flag,argument pairs: % 'extended' - int>=0 [0 default: assume no subgaussian comps] % Search for subgaussian comps: 'extended',1 is recommended % 'pca' - int>=0 [0 default: don't reduce data dimension] % NB: 'pca' reduction not recommended unless necessary % 'sphering' - 'on'/'off' first 'sphere' the data {default: 'on'} % 'lrate' - (0<float<<1) starting learning rate {default: 1e-4} % 'blocksize' - int>=0 [0 default: heuristic, from data size] % 'maxsteps' - int>0 {default: 512} % 'stop' - (0<float<<<1) stopping learning rate {default: 1e-7} % NB: 'stop' <= 1e-7 recommended % 'weightsin' - Filename string of inital weight matrix of size % (comps,chans) floats, else a weight matrix variable % in the current Matlab workspace (copied to a local % .inwts files). You may want to reduce the starting % 'lrate' arg (above) when resuming training, and/or % to reduce the 'stop' arg (above). By default, binary % ica begins with the identity matrix after sphering. % 'verbose' - 'on'/'off' {default: 'off'} % 'filenum' - the number to be used in the name of the output files. % Otherwise chosen randomly. Will choose random number % if file with that number already exists. % % Less frequently used input flags: % 'posact' - ('on'/'off') Make maximum value for each comp positive. % NB: 'off' recommended. {default: 'off'} % 'annealstep' - (0<float<1) {default: 0.98} % 'annealdeg' - (0<n<360) {default: 60} % 'bias' - 'on'/'off' {default: 'on'} % 'momentum' - (0<float<1) {default: 0 = off] % % Outputs: % wts - output weights matrix, size (ncomps,nchans) % sph - output sphere matrix, size (nchans,nchans) % Both files are read from float files left on disk % stem - random integer used in the names of the .sc, .wts, % .sph, and if requested, .intwts files % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 2000 % % See also: runica() % Calls binary translation of runica() by Sigurd Enghoff % Copyright (C) 2000 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 % 08/07/00 Added warning to update icadefs.m -sm % 09/08/00 Added tmpint to script, weights and sphere files to avoid % conflicts when multiple binica sessions run in the same pwd -sm % 10/07/00 Fixed bug in reading wts when 'pca' ncomps < nchans -sm % 07/18/01 replaced var ICA with ICABINARY to try to avoid Matlab6 bug -sm % 11/06/01 add absolute path of files (lines 157-170 & 198) -ad % 01-25-02 reformated help & license, added links -ad function [wts,sph,tmpint] = binica(data,var2,var3,var4,var5,var6,var7,var8,var9,var10,var11,var12,var13,var14,var15,var16,var17,var18,var19,var20,var21,var22,var23,var24,var25) if nargin < 1 | nargin > 25 more on help binica more off return end if size(data,3) > 1, data = reshape(data, size(data,1), size(data,2)*size(data,3) ); end; icadefs % import ICABINARY and SC if ~exist('SC') fprintf('binica(): You need to update your icadefs file to include ICABINARY and SC.\n') return end; if exist(SC) ~= 2 fprintf('binica(): No ica source file ''%s'' is in your Matlab path, check...\n', SC); return else SC = which(SC); fprintf('binica: using source file ''%s''\n', SC); end if exist(ICABINARY) ~= 2 fprintf('binica(): ica binary ''%s'' is not in your Matlab path, check\n', ICABINARY); return else ICABINARYdir = which(ICABINARY); if ~isempty(ICABINARYdir) fprintf('binica(): using binary ica file ''%s''\n', ICABINARYdir); else fprintf('binica(): using binary ica file ''\?/%s''\n', ICABINARY); end; end [flags,args] = read_sc(SC); % read flags and args in master SC file % % substitute the flags/args pairs in the .sc file % tmpint=[]; if ~ischar(data) % data variable given firstarg = 2; else % data filename given firstarg = 4; end arg = firstarg; if arg > nargin fprintf('binica(): no optional (flag, argument) pairs received.\n'); else if (nargin-arg+1)/2 > 1 fprintf('binica(): processing %d (flag, arg) pairs.\n',(nargin-arg+1)/2); else fprintf('binica(): processing one (flag, arg) pair.\n'); end while arg <= nargin %%%%%%%%%%%% process flags & args %%%%%%%%%%%%%%%% eval(['OPTIONFLAG = var' int2str(arg) ';']); % NB: Found that here Matlab var 'FLAG' is (64,3) why!?!? if arg == nargin fprintf('\nbinica(): Flag %s needs an argument.\n',OPTIONFLAG) return end eval(['Arg = var' int2str(arg+1) ';']); if strcmpi(OPTIONFLAG,'pca') ncomps = Arg; % get number of components out for reading wts. end if strcmpi(OPTIONFLAG,'weightsin') wtsin = Arg; if exist('wtsin') == 2 % file fprintf(' setting %s, %s\n','weightsin',Arg); elseif exist('wtsin') == 1 % variable nchans = size(data,1); % by nima if size(wtsin,2) ~= nchans fprintf('weightsin variable must be of width %d\n',nchans); return end else fprintf('weightsin variable not found.\n'); return end end if strcmpi(OPTIONFLAG,'filenum') tmpint = Arg; % get number for name of output files if ~isnumeric(tmpint) fprintf('\nbinica(): FileNum argument needs to be a number. Will use random number instead.\n') tmpint=[]; end; tmpint=int2str(tmpint); end arg = arg+2; nflags = length(flags); for f=1:nflags % replace SC arg with Arg passed from commandline if strcmp(OPTIONFLAG,flags{f}) args{f} = num2str(Arg); fprintf(' setting %s, %s\n',flags{f},args{f}); end end end end % % select random integer 1-10000 to index the binica data files % make sure no such script file already exists in the pwd % scriptfile = ['binica' tmpint '.sc']; while exist(scriptfile) tmpint = int2str(round(rand*10000)); scriptfile = ['binica' tmpint '.sc']; end fprintf('scriptfile = %s\n',scriptfile); nchans = 0; tmpdata = []; if ~ischar(data) % data variable given if ~exist('data') fprintf('\nbinica(): Variable name data not found.\n'); return end nchans = size(data,1); nframes = size(data,2); tmpdata = ['binica' tmpint '.fdt']; if strcmpi(computer, 'MAC') floatwrite(data,tmpdata,'ieee-be'); else floatwrite(data,tmpdata); end; datafile = tmpdata; else % data filename given if ~exist(data) fprintf('\nbinica(): File data not found.\n') return end datafile = data; if nargin<3 fprintf(... '\nbinica(): Data file name must be followed by chans, frames\n'); return end nchans = var2; nframes = var3; if ischar(nchans) | ischar(nframes) fprintf(... '\nbinica(): chans, frames args must be given after data file name\n'); return end end % % insert name of data files, chans and frames % for x=1:length(flags) if strcmp(flags{x},'DataFile') datafile = [pwd '/' datafile]; args{x} = datafile; elseif strcmp(flags{x},'WeightsOutFile') weightsfile = ['binica' tmpint '.wts']; weightsfile = [pwd '/' weightsfile]; args{x} = weightsfile; elseif strcmp(flags{x},'WeightsTempFile') weightsfile = ['binicatmp' tmpint '.wts']; weightsfile = [pwd '/' weightsfile]; args{x} = weightsfile; elseif strcmp(flags{x},'SphereFile') spherefile = ['binica' tmpint '.sph']; spherefile = [pwd '/' spherefile]; args{x} = spherefile; elseif strcmp(flags{x},'chans') args{x} = int2str(nchans); elseif strcmp(flags{x},'frames') args{x} = int2str(nframes); end end % % write the new .sc file % fid = fopen(scriptfile,'w'); for x=1:length(flags) fprintf(fid,'%s %s\n',flags{x},args{x}); end if exist('wtsin') % specify WeightsInfile from 'weightsin' flag, arg if exist('wtsin') == 1 % variable winfn = [pwd '/binica' tmpint '.inwts']; if strcmpi(computer, 'MAC') floatwrite(wtsin,winfn,'ieee-be'); else floatwrite(wtsin,winfn); end; fprintf(' saving input weights:\n '); weightsinfile = winfn; % weights in file name elseif exist(wtsin) == 2 % file weightsinfile = wtsin; weightsinfile = [pwd '/' weightsinfile]; else fprintf('binica(): weightsin file|variable not found.\n'); return end eval(['!ls -l ' weightsinfile]); fprintf(fid,'%s %s\n','WeightsInFile',weightsinfile); end fclose(fid); if ~exist(scriptfile) fprintf('\nbinica(): ica script file %s not written.\n',... scriptfile); return end % % %%%%%%%%%%%%%%%%%%%%%% run binary ica %%%%%%%%%%%%%%%%%%%%%%%%% % fprintf('\nRunning ica from script file %s\n',scriptfile); if exist('ncomps') fprintf(' Finding %d components.\n',ncomps); end eval_call = ['!' ICABINARY '<' pwd '/' scriptfile]; eval(eval_call); % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % read in wts and sph results. % if ~exist('ncomps') ncomps = nchans; end if strcmpi(computer, 'MAC') wts = floatread(weightsfile,[ncomps Inf],'ieee-be',0); sph = floatread(spherefile,[nchans Inf],'ieee-be',0); else wts = floatread(weightsfile,[ncomps Inf],[],0); sph = floatread(spherefile,[nchans Inf],[],0); end; if isempty(wts) fprintf('\nbinica(): weight matrix not read.\n') return end if isempty(sph) fprintf('\nbinica(): sphere matrix not read.\n') return end fprintf('\nbinary ica files left in pwd:\n'); eval(['!ls -l ' scriptfile ' ' weightsfile ' ' spherefile]); if exist('wtsin') eval(['!ls -l ' weightsinfile]); end fprintf('\n'); if ischar(data) whos wts sph else whos data wts sph end % % If created by binica(), rm temporary data file % NOTE: doesn't remove the .sc .wts and .fdt files if ~isempty(tmpdata) eval(['!rm -f ' datafile]); end % %%%%%%%%%%%%%%%%%%% included functions %%%%%%%%%%%%%%%%%%%%%% % function sout = rmcomment(s,symb) n =1; while s(n)~=symb % discard # comments n = n+1; end if n == 1 sout = []; else sout = s(1:n-1); end function sout = rmspace(s) n=1; % discard leading whitespace while n<length(s) & isspace(s(n)) n = n+1; end if n<length(s) sout = s(n:end); else sout = []; end function [word,sout] = firstword(s) n=1; while n<=length(s) & ~isspace(s(n)) n = n+1; end if n>length(s) word = []; sout = s; else word = s(1:n-1); sout = s(n:end); end function [flags,args] = read_sc(master_sc) % % read in the master ica script file SC % flags = []; args = []; fid = fopen(master_sc,'r'); if fid < 0 fprintf('\nbinica(): Master .sc file %s not read!\n',master_sc) return end % % read SC file info into flags and args lists % s = []; f = 0; % flag number in file while isempty(s) | s ~= -1 s = fgetl(fid); if s ~= -1 if ~isempty(s) s = rmcomment(s,'#'); if ~isempty(s) f = f+1; s = rmspace(s); [w s]=firstword(s); if ~isempty(s) flags{f} = w; s = rmspace(s); [w s]=firstword(s); args{f} = w; end end end end end fclose(fid);
github
ZijingMao/baselineeegtest-master
mattocell.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/mattocell.m
1,311
utf_8
bb1357cab390093724fa7887f66ebef3
% mattocell() - convert matrix to cell array % % Usage: >> C = mattocell( M ); % % Author: Arnaud Delorme, CNL / Salk Institute, Jan 25 2002 % % Note: this function overload the nnet toolbox function mattocell, % but does not have all its capacities. You can delete the current % function if you have the toolbox. % Copyright (C) Jan 25 2002 Arnaud Delorme, CNL / Salk Institute % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function C = mattocell( M, varargin ); if nargin < 1 help mattocell; return; end; if isempty(M) C = []; return; end; C = cell(size(M)); for i=1:size(M,1) for j=1:size(M,2) C{i,j} = M(i,j); end; end;
github
ZijingMao/baselineeegtest-master
readegihdr.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/readegihdr.m
3,589
utf_8
009a2ce2b93412350699c09bebfaeb4e
% readegihdr() - read header information from EGI (versions 2,3,4,5,6,7) data file. % % Usage: % >> [head] = readegihdr(fid,forceversion) % % Input: % fid - file identifier of EGI datafile % forceversion - optional integer input to override automatic reading of version number. % % Output: % head - structure containing header information. % Structure fields are: % version = 2,3,4,5,6,or 7 % samp_rate = sampling rate in samples/s % nchan = number of EEG channels % gain = gain of amplifier % bits = number of bits/sample % range = abs(max. value) % segments = number of epochs % categories = number of categories % catname = cell array of category names % segsamps = number of samples/segment % eventtypes = number of event types % eventcode = string array of event codes % % Author: Cooper Roddey, SCCN, 13 Nov 2002 % % Note: this code derived from C source code written by % Tom Renner at EGI, Inc. (www.egi.com) % % See also: readegi() % Copyright (C) 2002 , Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function head = readegihdr(fid,forceversion) if nargin < 1 help readegihdr; return; end; head.version = fread(fid,1,'integer*4'); if exist('forceversion') head.version = forceversion; end if ~( head.version >= 2 & head.version <= 7 ), error('EGI Simple Binary Versions 2-7 supported only.'); end; year = fread(fid,1,'integer*2'); month = fread(fid,1,'integer*2'); day = fread(fid,1,'integer*2'); hour = fread(fid,1,'integer*2'); minute = fread(fid,1,'integer*2'); second = fread(fid,1,'integer*2'); millisecond = fread(fid,1,'integer*4'); head.samp_rate = fread(fid,1,'integer*2'); head.nchan = fread(fid,1,'integer*2'); head.gain = fread(fid,1,'integer*2'); head.bits = fread(fid,1,'integer*2'); head.range = fread(fid,1,'integer*2'); head.samples = 0; head.segments = 0; head.segsamps = 0; head.eventtypes = 0; head.categories = 0; head.catname = {}; head.eventcode = ''; switch (head.version) case {2,4,6} head.samples = fread(fid, 1 ,'integer*4'); case {3,5,7} head.categories = fread(fid,1,'integer*2'); if (head.categories), for i=1:head.categories, catname_len(i) = fread(fid,1,'uchar'); head.catname{i} = char(fread(fid,catname_len(i),'uchar'))'; end end head.segments = fread(fid,1,'integer*2'); head.segsamps = fread(fid,1,'integer*4'); otherwise error('Invalid EGI version'); end head.eventtypes = fread(fid,1,'integer*2'); if isequal(head.eventtypes,0), head.eventcode(1,1:4) = 'none'; else for i = 1:head.eventtypes, head.eventcode(i,1:4) = fread(fid,[1,4],'uchar'); end end
github
ZijingMao/baselineeegtest-master
timtopo.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/timtopo.m
15,459
utf_8
a449d814e428e5d230cda9f0adfe661a
% timtopo() - plot all channels of a data epoch on the same axis % and map its scalp map(s) at selected latencies. % Usage: % >> timtopo(data, chan_locs); % >> timtopo(data, chan_locs, 'key', 'val', ...); % Inputs: % data = (channels,frames) single-epoch data matrix % chan_locs = channel location file or EEG.chanlocs structure. % See >> topoplot example for file format. % % Optional ordered inputs: % 'limits' = [minms maxms minval maxval] data limits for latency (in ms) and y-values % (assumes uV) {default|0 -> use [0 npts-1 data_min data_max]; % else [minms maxms] or [minms maxms 0 0] -> use % [minms maxms data_min data_max] % 'plottimes' = [vector] latencies (in ms) at which to plot scalp maps % {default|NaN -> latency of maximum variance} % 'title' = [string] plot title {default|0 -> none} % 'plotchans' = vector of data channel(s) to plot. Note that this does not % affect scalp topographies {default|0 -> all} % 'voffsets' = vector of (plotting-unit) distances vertical lines should extend % above the data (in special cases) {default -> all = standard} % % Optional keyword, arg pair inputs (must come after the above): % 'topokey','val' = optional topoplot() scalp map plotting arguments. See >> help topoplot % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 1-10-98 % % See also: envtopo(), topoplot() % Copyright (C) 1-10-98 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 5-31-00 added o-time line and possibility of plotting 1 channel -sm & mw % 11-02-99 added maplimits arg -sm % 01-22-01 added to help message -sm % 01-25-02 reformated help & license, added link -ad % 03-15-02 add all topoplot options -ad function M = timtopo(data, chan_locs, varargin) MAX_TOPOS = 24; if nargin < 1 %should this be 2? help timtopo; return end [chans,frames] = size(data); icadefs; % % if nargin > 2 % if ischar(limits) % varargin = { limits,plottimes,titl,plotchans,voffsets varargin{:} }; % % else % varargin = { 'limits' limits 'plottimes' plottimes 'title' titl 'plotchans' plotchans 'voffsets' voffsets varargin{:} }; % end; % end; if nargin > 2 && ~ischar(varargin{1}) options = {}; if length(varargin) > 0, options = { options{:} 'limits' varargin{1} }; end; if length(varargin) > 1, options = { options{:} 'plottimes' varargin{2} }; end; if length(varargin) > 2, options = { options{:} 'title' varargin{3} }; end; if length(varargin) > 3, options = { options{:} 'plotchans' varargin{4} }; end; if length(varargin) > 4, options = { options{:} 'voffsets' varargin{5} }; end; if length(varargin) > 5, options = { options{:} varargin{6:end} }; end; else options = varargin; end; fieldlist = { 'limits' 'real' [] 0; 'plottimes' 'real' [] []; 'title' 'string' [] ''; 'plotchans' 'integer' [1:size(data,1)] 0; 'voffsets' 'real' [] [] ;}; [g topoargs] = finputcheck(options, fieldlist, 'timtopo', 'ignore'); if ischar(g), error(g); end; %Set Defaults if isempty(g.title), g.title = ''; end; if isempty(g.voffsets) || g.voffsets == 0, g.voffsets = zeros(1,MAX_TOPOS); end; if isempty(g.plotchans) || isequal(g.plotchans,0), g.plotchans = 1:chans; end; plottimes_set=1; % flag variable if isempty(g.plottimes) || any(isnan(g.plottimes)), plottimes_set = 0;end; limitset = 0; %flag variable if isempty(g.limits), g.limits = 0; end; if length(g.limits)>1, limitset = 1; end; % if nargin < 7 | voffsets == 0 % voffsets = zeros(1,MAX_TOPOS); % end % % if nargin < 6 % plotchans = 0; % end % % if plotchans==0 % plotchans = 1:chans; % end % % if nargin < 5, % titl = ''; % DEFAULT NO TITLE % end % % plottimes_set=1; % flag variable % if nargin< 4 | isempty(plottimes) | any(isnan(plottimes)) % plottimes_set = 0; % end % % limitset = 0; % if nargin < 3, % limits = 0; % elseif length(limits)>1 % limitset = 1; % end if nargin < 2 %if first if-statement is changed to 2 should this be 3? chan_locs = 'chan.locs'; % DEFAULT CHAN_FILE end if isnumeric(chan_locs) && chan_locs == 0, chan_locs = 'chan.locs'; % DEFAULT CHAN_FILE end % %%%%%%%%%%%%%%%%%%%%%%% Read and adjust limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % defaults: limits == 0 or [0 0 0 0] if ( length(g.limits) == 1 & g.limits==0) | (length(g.limits)==4 & ~any(g.limits)) xmin=0; xmax=frames-1; ymin=min(min(data)); ymax=max(max(data)); elseif length(g.limits) == 2 % [minms maxms] only ymin=min(min(data)); ymax=max(max(data)); xmin = g.limits(1); xmax = g.limits(2); elseif length(g.limits) == 4 xmin = g.limits(1); xmax = g.limits(2); if any(g.limits([3 4])) ymin = g.limits(3); ymax = g.limits(4); else % both 0 ymin=min(min(data)); ymax=max(max(data)); end else fprintf('timtopo(): limits format not correct. See >> help timtopo.\n'); return end; if xmax == 0 & xmin == 0, x = (0:1:frames-1); xmin = 0; xmax = frames-1; else dx = (xmax-xmin)/(frames-1); x=xmin*ones(1,frames)+dx*(0:frames-1); % compute x-values end; if xmax<=xmin, fprintf('timtopo() - in limits, maxms must be > minms.\n') return end if ymax == 0 & ymin == 0, ymax=max(max(data)); ymin=min(min(data)); end if ymax<=ymin, fprintf('timtopo() - in limits, maxval must be > minmval.\n') return end sampint = (xmax-xmin)/(frames-1); % sampling interval = 1000/srate; x = xmin:sampint:xmax; % make vector of x-values % %%%%%%%%%%%%%%% Compute plot times/frames %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if plottimes_set == 0 [mx plotframes] = max(sum(data.*data)); % default plotting frame has max variance if nargin< 4 | isempty(g.plottimes) g.plottimes = x(plotframes); else g.plottimes(find(isnan(g.plottimes))) = x(plotframes); end; plottimes_set = 1; end; if plottimes_set == 1 ntopos = length(g.plottimes); if ntopos > MAX_TOPOS fprintf('timtopo(): too many plottimes - only first %d will be shown!\n',MAX_TOPOS); g.plottimes = g.plottimes(1:MAX_TOPOS); ntopos = MAX_TOPOS; end if max(g.plottimes) > xmax | min(g.plottimes)< xmin fprintf(... 'timtopo(): at least one plottimes value outside of epoch latency range - cannot plot.\n'); return end g.plottimes = sort(g.plottimes); % put map latencies in ascending order, % else map lines would cross. xshift = [x(2:frames) xmax+1]; % 5/22/2014 Ramon: '+1' was added to avoid errors when time== max(x) in line 231 plotframes = ones(size(g.plottimes)); for t = 1:ntopos time = g.plottimes(t); plotframes(t) = find(time>=x & time < xshift); end end vlen = length(g.voffsets); % extend voffsets if necessary i=1; while vlen< ntopos g.voffsets = [g.voffsets g.voffsets(i)]; i=i+1; vlen=vlen+1; end % %%%%%%%%%%%%%%%% Compute title and axes font sizes %%%%%%%%%%%%%%% % pos = get(gca,'Position'); axis('off') cla % clear the current axes if pos(4)>0.70 titlefont= 16; axfont = 16; elseif pos(4)>0.40 titlefont= 14; axfont = 14; elseif pos(4)>0.30 titlefont= 12; axfont = 12; elseif pos(4)>0.22 titlefont= 10; axfont = 10; else titlefont= 8; axfont = 8; end % %%%%%%%%%%%%%%%% Compute topoplot head width and separation %%%%%%%%%%%%%%% % head_sep = 0.2; topowidth = pos(3)/((6*ntopos-1)/5); % width of each topoplot if topowidth> 0.25*pos(4) % dont make too large (more than 1/4 of axes width)! topowidth = 0.25*pos(4); end halfn = floor(ntopos/2); if rem(ntopos,2) == 1 % odd number of topos topoleft = pos(3)/2 - (ntopos/2+halfn*head_sep)*topowidth; else % even number of topos topoleft = pos(3)/2 - ((halfn)+(halfn-1)*head_sep)*topowidth; end topoleft = topoleft - 0.01; % adjust left a bit for colorbar if max(plotframes) > frames | min(plotframes) < 1 fprintf('Requested map frame %d is outside data range (1-%d)\n',max(plotframes),frames); return end % %%%%%%%%%%%%%%%%%%%% Print times and frames %%%%%%%%%%%%%%%%%%%%%%%%%% % fprintf('Scalp maps will show latencies: '); for t=1:ntopos fprintf('%4.0f ',g.plottimes(t)); end fprintf('\n'); fprintf(' at frames: '); for t=1:ntopos fprintf('%4d ',plotframes(t)); end fprintf('\n'); % %%%%%%%%%%%%%%%%%%%%%%% Plot the data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % %%%%%%%%%%%% site the plot at bottom of the figure %%%%%%%%%%%%%%%%%% % axdata = axes('Units','Normalized','Position',[pos(1) pos(2) pos(3) 0.6*pos(4)],'FontSize',axfont); set(axdata,'Color',BACKCOLOR); g.limits = get(axdata,'Ylim'); set(axdata,'GridLineStyle',':') set(axdata,'Xgrid','off') set(axdata,'Ygrid','on') axes(axdata) axcolor = get(gcf,'Color'); set(axdata,'Color',BACKCOLOR); pl=plot(x,data(g.plotchans,:)'); % plot the data if length(g.plotchans)==1 set(pl,'color','k'); set(pl,'linewidth',2); end xl= xlabel('Latency (ms)'); set(xl,'FontSize',axfont); yl=ylabel('Potential (\muV)'); set(yl,'FontSize',axfont,'FontAngle','normal'); axis([xmin xmax ymin ymax]); hold on % %%%%%%%%%%%%%%%%%%%%%%%%% Plot zero time line %%%%%%%%%%%%%%%%%%%%%%%%%% % if xmin<0 & xmax>0 plot([0 0],[ymin ymax],'k:','linewidth',1.5); else fprintf('xmin %g and xmax %g do not cross time 0.\n',xmin,xmax) end % %%%%%%%%%%%%%%%%%%%%%%%%% Draw vertical lines %%%%%%%%%%%%%%%%%%%%%%%%%% % width = xmax-xmin; height = ymax-ymin; lwidth = 1.5; % increment line thickness for t=1:ntopos % dfraw vertical lines through the data at topoplot frames if length(g.plotchans)>1 | g.voffsets(t) l1 = plot([g.plottimes(t) g.plottimes(t)],... [min(data(g.plotchans,plotframes(t))) ... g.voffsets(t) + max(data(g.plotchans,plotframes(t)))],'w'); % white underline behind set(l1,'linewidth',2); l1 = plot([g.plottimes(t) g.plottimes(t)],... [min(data(g.plotchans,plotframes(t))) ... g.voffsets(t) + max(data(g.plotchans,plotframes(t)))],'b'); % blue line set(l1,'linewidth',lwidth); end end % %%%%%%%%%%%%%%%%%%%%%%%%% Draw oblique lines %%%%%%%%%%%%%%%%%%%%%%%%%% % axall = axes('Position',pos,... 'Visible','Off','FontSize',axfont); % whole-gca invisible axes axes(axall) set(axall,'Color',BACKCOLOR); axis([0 1 0 1]) axes(axall) axis([0 1 0 1]); set(gca,'Visible','off'); % make whole-figure axes invisible for t=1:ntopos % draw oblique lines through to the topoplots maxdata = max(data(:,plotframes(t))); % max data value at plotframe axtp = axes('Units','Normalized','Position',... [pos(1)+topoleft+(t-1)*(1+head_sep)*topowidth ... pos(2)+0.66*pos(4) ... topowidth ... topowidth*(1+head_sep)]); % this will be the topoplot axes % topowidth]); % this will be the topoplot axes axis([-1 1 -1 1]); from = changeunits([g.plottimes(t),maxdata],axdata,axall); % data axes to = changeunits([0,-0.74],axtp,axall); % topoplot axes delete(axtp); axes(axall); % whole figure axes l1 = plot([from(1) to(1)],[from(2) to(2)]); set(l1,'linewidth',lwidth); hold on set(axall,'Visible','off'); axis([0 1 0 1]); end % %%%%%%%%%%%%%%%%%%%%%%%%% Plot the topoplots %%%%%%%%%%%%%%%%%%%%%%%%%% % topoaxes = zeros(1,ntopos); for t=1:ntopos % [pos(3)*topoleft+pos(1)+(t-1)*(1+head_sep)*topowidth ... axtp = axes('Units','Normalized','Position',... [topoleft+pos(1)+(t-1)*(1+head_sep)*topowidth ... pos(2)+0.66*pos(4) ... topowidth topowidth*(1+head_sep)]); axes(axtp) % topoplot axes topoaxes(t) = axtp; % save axes handles cla if topowidth<0.12 topoargs = { topoargs{:} 'electrodes' 'off' }; end topoplot( data(:,plotframes(t)),chan_locs, topoargs{:}); % Else make a 3-D headplot % % headplot(data(:,plotframes(t)),'chan.spline'); timetext = [num2str(g.plottimes(t),'%4.0f')]; % timetext = [num2str(plottimes(t),'%4.0f') ' ms']; % add ' ms' text(0.00,0.80,timetext,'FontSize',axfont-3,'HorizontalAlignment','Center'); % ,'fontweight','bold'); end % %%%%%%%%%%%%%%%%%%% Plot a topoplot colorbar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % axcb = axes('Position',[pos(1)+pos(3)*0.995 pos(2)+0.62*pos(4) pos(3)*0.02 pos(4)*0.09]); h=cbar(axcb); % colorbar axes pos_cb = get(axcb,'Position'); set(h,'Ytick',[]); axes(axall) set(axall,'Color',axcolor); % %%%%%%%%%%%%%%%%%%%%% Plot the color bar '+' and '-' %%%%%%%%%%%%%%%%%%%%%%%%%% % text(0.986,0.695,'+','FontSize',axfont,'HorizontalAlignment','Center'); text(0.986,0.625,'-','FontSize',axfont,'HorizontalAlignment','Center'); % %%%%%%%%%%%%%%%%%%%%%%%%% Plot the plot title if any %%%%%%%%%%%%%%%%%%%%%%%%%% % % plot title between data panel and topoplots (to avoid crowding at top of % figure), on the left ttl = text(0.03,0.635,g.title,'FontSize',titlefont,'HorizontalAlignment','left'); % 'FontWeight','Bold'); % textent = get(ttl,'extent'); % titlwidth = textent(3); % ttlpos = get(ttl,'position'); % set(ttl,'position',[ ttlpos(2), ttlpos(3)]); axes(axall) set(axall,'layer','top'); % bring component lines to top for t = 1:ntopos set(topoaxes(t),'layer','top'); % bring topoplots to very top end if ~isempty(varargin) try, if ~isempty( strmatch( 'absmax', varargin)) text(0.86,0.624,'0','FontSize',axfont,'HorizontalAlignment','Center'); end; catch, end; end % % Turn on axcopy() % % clicking on ERP pop_up topoplot % ------------------------------- disp('Click on ERP waveform to show scalp map at specific latency'); dat.times = x; dat.erp = data; dat.chanlocs = chan_locs; dat.options = topoargs; dat.srate = (size(data,2)-1)/(x(end)-x(1))*1000; dat.axes = axtp; dat.line = l1; cb_code = [ 'tmppos = get(gca, ''currentpoint'');' ... 'dattmp = get(gcf, ''userdata'');' ... 'set(dattmp.line, ''visible'', ''off'');' ... 'axes(dattmp.axes); cla;' ... 'latpoint = round((tmppos(1)-dattmp.times(1))/1000*dattmp.srate);' ... 'topoplot(dattmp.erp(:,latpoint), dattmp.chanlocs, dattmp.options{:});' ... 'title(sprintf(''%.0f ms'', tmppos(1)));' ... 'clear latpoint dattmp;' ... ]; axcopy; set(gcf, 'userdata', dat); set(axdata, 'ButtonDownFcn', cb_code); %windowbuttondownfcn', cb_code); set(pl, 'ButtonDownFcn', cb_code); %axcopy(gcf, cb_code);
github
ZijingMao/baselineeegtest-master
rmbase.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/rmbase.m
3,813
utf_8
7f8fcb4d54c16b3482b307e2c8133cbb
% rmbase() - subtract basevector channel means from multi-epoch data matrix % % Usage: % >> [dataout] = rmbase(data); % remove whole-data channel means % >> [dataout datamean] = rmbase(data,frames,basevector); % % remove mean of basevector from each channel and epoch % Inputs: % data - data matrix (chans,frames*epochs) or (chans, frames, epochs); % frames - data points per epoch {[]|0|default->data length} % basevector - vector of baseline frames per epoch % Ex 1:128 {[]|0|default->whole epoch} % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 2-5-96 % Copyright (C) 2-5-96 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 07-30-97 converted to rmbase() -sm % 09-30-97 fixed! -sm % 05-10-01 caught empty input data -sm % 06-03-01 added test for length-1 basevector, added [] defaults -sm % 01-05-02 added check for negative basevector indices -Luca Finelli % 01-25-02 reformated help & license -ad function [dataout,datamean] = rmbase(data,frames,basevector) if nargin<3, basevector =0; end; if isempty(basevector) basevector =0; end; if length(basevector) == 1 & basevector(1) ~= 0 fprintf('rmbase(): basevector should be a vector of frame indices.\n'); return end if sum(basevector<0)~= 0 fprintf('rmbase(): basevector should be 0 or a vector of positive frame indices.\n'); return end if nargin < 2, frames = 0; end; if isempty(frames) frames =0; end; if nargin<1, help rmbase; fprintf('rmbase(): needs at least one argument.\n\n'); return end if isempty(data) fprintf('rmbase(): input data is empty.\n\n'); return end oridims = size(data); if ndims(data) == 3, data = reshape(data, size(data,1), size(data,2)*size(data,3)); reshape_flag=1; end [chans framestot]= size(data); if frames ==0, frames = framestot; end; epochs = fix(framestot/frames); if length(basevector)>framestot, fprintf('rmbase(): length(basevector) > frames per epoch.\n\n'); help rmbase; return end; datamean = zeros(chans,epochs); % fprintf('removing epoch means for %d epochs\n',epochs); dataout = data; for e=1:epochs for c=1:chans if basevector(1)~=0, rmeans = nan_mean(double(data(c,(e-1)*frames+basevector)')); else rmeans = nan_mean(double(data(c,(e-1)*frames+1:e*frames)')); %if e==1 % fprintf('rmbase(): whole-data channel means removed. \n\n'); %end end; datamean(c,e) = rmeans; dataout(c,(e-1)*frames+1:e*frames) = data(c,(e-1)*frames+1:e*frames) - rmeans; end; end; dataout = reshape(dataout, oridims); % function out = nan_mean(in) % % nans = find(isnan(in)); % in(nans) = 0; % sums = sum(in); % nonnans = ones(size(in)); % nonnans(nans) = 0; % nonnans = sum(nonnans); % nononnans = find(nonnans==0); % nonnans(nononnans) = 1; % out = sum(in)./nonnans; % out(nononnans) = NaN; %
github
ZijingMao/baselineeegtest-master
realproba.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/realproba.m
2,315
utf_8
f564644151c35bcc6b310d8e54773abd
% realproba() - compute the effective probability of the value % in the sample. % % Usage: % >> [probaMap, probaDist ] = realproba( data, discret); % % Inputs: % data - the data onto which compute the probability % discret - discretisation factor (default: (size of data)/5) % if 0 base the computation on a Gaussian % approximation of the data % % Outputs: % probaMap - the probabilities associated with the values % probaDist - the probabilities distribution % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [ probaMap, sortbox ] = realproba( data, bins ); if nargin < 1 help realproba; return; end; if nargin < 2 bins = round(size(data,1)*size(data,2)/5); end; if bins > 0 % COMPUTE THE DENSITY FUNCTION % ---------------------------- SIZE = size(data,1)*size(data,2); sortbox = zeros(1,bins); minimum = min(data(:)); maximum = max(data(:)); data = floor((data - minimum )/(maximum - minimum)*(bins-1))+1; if any(any(isnan(data))), warning('Binning failed - could be due to zeroed out channel'); end; for index=1:SIZE sortbox(data(index)) = sortbox(data(index))+1; end; probaMap = sortbox(data) / SIZE; sortbox = sortbox / SIZE; else % BASE OVER ERROR FUNCTION % ------------------------ data = (data-mean(data(:)))./std(data(:)); probaMap = exp(-0.5*( data.*data ))/(2*pi); probaMap = probaMap/sum(probaMap); % because the total surface under a normalized Gaussian is 2 sortbox = probaMap/sum(probaMap); end; return;
github
ZijingMao/baselineeegtest-master
eegfilt.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/eegfilt.m
8,031
utf_8
5d305e3ed98f5df8a36f43880470f905
% eegfilt() - (high|low|band)-pass filter data using two-way least-squares % FIR filtering. Optionally uses the window method instead of % least-squares. Multiple data channels and epochs supported. % Requires the MATLAB Signal Processing Toolbox. % Usage: % >> [smoothdata] = eegfilt(data,srate,locutoff,hicutoff); % >> [smoothdata,filtwts] = eegfilt(data,srate,locutoff,hicutoff, ... % epochframes,filtorder,revfilt,firtype,causal); % Inputs: % data = (channels,frames*epochs) data to filter % srate = data sampling rate (Hz) % locutoff = low-edge frequency in pass band (Hz) {0 -> lowpass} % hicutoff = high-edge frequency in pass band (Hz) {0 -> highpass} % epochframes = frames per epoch (filter each epoch separately {def/0: data is 1 epoch} % filtorder = length of the filter in points {default 3*fix(srate/locutoff)} % revfilt = [0|1] reverse filter (i.e. bandpass filter to notch filter). {default 0} % firtype = 'firls'|'fir1' {'firls'} % causal = [0|1] use causal filter if set to 1 (default 0) % % Outputs: % smoothdata = smoothed data % filtwts = filter coefficients [smoothdata <- filtfilt(filtwts,1,data)] % % See also: firls(), filtfilt() % Author: Scott Makeig, Arnaud Delorme, Clemens Brunner SCCN/INC/UCSD, La Jolla, 1997 % Copyright (C) 4-22-97 from bandpass.m 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 % 05-08-97 fixed frequency bound computation -sm % 10-22-97 added MINFREQ tests -sm % 12-05-00 added error() calls -sm % 01-25-02 reformated help & license, added links -ad % 03-20-12 added firtype option -cb function [smoothdata,filtwts] = eegfilt(data,srate,locutoff,hicutoff,epochframes,filtorder,revfilt,firtype,causal) if nargin<4 fprintf(''); help eegfilt return end %if ~exist('firls') % error('*** eegfilt() requires the signal processing toolbox. ***'); %end [chans frames] = size(data); if chans > 1 & frames == 1, help eegfilt error('input data should be a row vector.'); end nyq = srate*0.5; % Nyquist frequency %MINFREQ = 0.1/nyq; MINFREQ = 0; minfac = 3; % this many (lo)cutoff-freq cycles in filter min_filtorder = 15; % minimum filter length trans = 0.15; % fractional width of transition zones if locutoff>0 & hicutoff > 0 & locutoff > hicutoff, error('locutoff > hicutoff ???\n'); end if locutoff < 0 | hicutoff < 0, error('locutoff | hicutoff < 0 ???\n'); end if locutoff>nyq, error('Low cutoff frequency cannot be > srate/2'); end if hicutoff>nyq error('High cutoff frequency cannot be > srate/2'); end if nargin<6 filtorder = 0; end if nargin<7 revfilt = 0; end if nargin<8 firtype = 'firls'; end if nargin<9 causal = 0; end if strcmp(firtype, 'firls') warning('Using firls to estimate filter coefficients. We recommend that you use fir1 instead, which yields larger attenuation. In future, fir1 will be used by default!'); end if isempty(filtorder) | filtorder==0, if locutoff>0, filtorder = minfac*fix(srate/locutoff); elseif hicutoff>0, filtorder = minfac*fix(srate/hicutoff); end if filtorder < min_filtorder filtorder = min_filtorder; end end if nargin<5 epochframes = 0; end if epochframes ==0, epochframes = frames; % default end epochs = fix(frames/epochframes); if epochs*epochframes ~= frames, error('epochframes does not divide frames.\n'); end if filtorder*3 > epochframes, % Matlab filtfilt() restriction fprintf('eegfilt(): filter order is %d. ',filtorder); error('epochframes must be at least 3 times the filtorder.'); end if (1+trans)*hicutoff/nyq > 1 error('high cutoff frequency too close to Nyquist frequency'); end; if locutoff > 0 & hicutoff > 0, % bandpass filter if revfilt fprintf('eegfilt() - performing %d-point notch filtering.\n',filtorder); else fprintf('eegfilt() - performing %d-point bandpass filtering.\n',filtorder); end; fprintf(' If a message, ''Matrix is close to singular or badly scaled,'' appears,\n'); fprintf(' then Matlab has failed to design a good filter. As a workaround, \n'); fprintf(' for band-pass filtering, first highpass the data, then lowpass it.\n'); if strcmp(firtype, 'firls') f=[MINFREQ (1-trans)*locutoff/nyq locutoff/nyq hicutoff/nyq (1+trans)*hicutoff/nyq 1]; fprintf('eegfilt() - low transition band width is %1.1g Hz; high trans. band width, %1.1g Hz.\n',(f(3)-f(2))*srate/2, (f(5)-f(4))*srate/2); m=[0 0 1 1 0 0]; elseif strcmp(firtype, 'fir1') filtwts = fir1(filtorder, [locutoff, hicutoff]./(srate/2)); end elseif locutoff > 0 % highpass filter if locutoff/nyq < MINFREQ error(sprintf('eegfilt() - highpass cutoff freq must be > %g Hz\n\n',MINFREQ*nyq)); end fprintf('eegfilt() - performing %d-point highpass filtering.\n',filtorder); if strcmp(firtype, 'firls') f=[MINFREQ locutoff*(1-trans)/nyq locutoff/nyq 1]; fprintf('eegfilt() - highpass transition band width is %1.1g Hz.\n',(f(3)-f(2))*srate/2); m=[ 0 0 1 1]; elseif strcmp(firtype, 'fir1') filtwts = fir1(filtorder, locutoff./(srate/2), 'high'); end elseif hicutoff > 0 % lowpass filter if hicutoff/nyq < MINFREQ error(sprintf('eegfilt() - lowpass cutoff freq must be > %g Hz',MINFREQ*nyq)); end fprintf('eegfilt() - performing %d-point lowpass filtering.\n',filtorder); if strcmp(firtype, 'firls') f=[MINFREQ hicutoff/nyq hicutoff*(1+trans)/nyq 1]; fprintf('eegfilt() - lowpass transition band width is %1.1g Hz.\n',(f(3)-f(2))*srate/2); m=[ 1 1 0 0]; elseif strcmp(firtype, 'fir1') filtwts = fir1(filtorder, hicutoff./(srate/2)); end else error('You must provide a non-0 low or high cut-off frequency'); end if revfilt if strcmp(firtype, 'fir1') error('Cannot reverse filter using ''fir1'' option'); else m = ~m; end; end; if strcmp(firtype, 'firls') filtwts = firls(filtorder,f,m); % get FIR filter coefficients end smoothdata = zeros(chans,frames); for e = 1:epochs % filter each epoch, channel for c=1:chans try if causal smoothdata(c,(e-1)*epochframes+1:e*epochframes) = filter( filtwts,1,data(c,(e-1)*epochframes+1:e*epochframes)); else smoothdata(c,(e-1)*epochframes+1:e*epochframes) = filtfilt(filtwts,1,data(c,(e-1)*epochframes+1:e*epochframes)); end; catch, if causal smoothdata(c,(e-1)*epochframes+1:e*epochframes) = filter( filtwts,1,double(data(c,(e-1)*epochframes+1:e*epochframes))); else smoothdata(c,(e-1)*epochframes+1:e*epochframes) = filtfilt(filtwts,1,double(data(c,(e-1)*epochframes+1:e*epochframes))); end; end; if epochs == 1 if rem(c,20) ~= 0, fprintf('.'); else fprintf('%d',c); end end end end fprintf('\n');
github
ZijingMao/baselineeegtest-master
phasecoher.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/phasecoher.m
13,038
utf_8
2b8981e6f824cfb02a87b964d5e114e4
% phasecoher() - Implements inter-trial amp/coherence using Gaussian wavelets. % Returns same data length as input frames. % Plots results when nargin>6. Outputs have flat ends % at data indices [1:halfwin] and [frames-halfwin:frames]. % Usage: % >> [amps,cohers ] = phasecoher(data,frames,srate,freq,cycles); % >> [amps,cohers,cohsig,ampsig,allamps,allphs] ... % = phasecoher(data,frames,... % srate,freq,cycles,... % alpha,times,titl,... % warpframes, events); % Inputs: % data = input data, (1,frames*trials) or NB: (frames,trials) % frames = frames per trial % srate = sampling rate (in Hz) % freq = frequency to work on (in Hz) % cycles = cycles in Gaussian wavelet window (float) {3} % alpha = (0 0.1] significance probability threshold. Requires % >=3 output arguments. alpha=0 -> no signif {default: 0}. % times = vector of latencies (in ms) for plotting {default: no plot} % titl = [string] plot title {default none} % warpframes = frame numbers of warped events (below) % events = matrix of events in each trial, size (nevents, trials) % as frame numbers. % Outputs: % amps = mean amplitude at each time point % cohers = phase coherence at each time point [0,1] % cohsig = coherence significance threshold (bootstrap, alpha level) % ampsig = amplitude significance thresholds [lo high] (bootstrap, alpha level) % allamps = amplitudes at each trial and time point (frames,trials) % allphs = phase (deg) at each trial and time point (frames,trials) % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 5-5-98 % % See also: erpimage() % Copyright (C) 5-5-98 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 5-7-98 added frames, made input data format one-row -sm % 5-8-98 added MIN_AMP, times, PLOT_IT -sm % 10-27-98 added cohsig, alpha -sm % 07-24-99 added allamps -sm % 02-29-00 added ampsig -sm % 12-05-00 changed complex abs() to sqrt( .^2+ .^2) to avoid possible i ambiguity -sm & tpj % 12-31-00 added ...20...40... frames fprinting -sm % 08-17-01 added allphs option -sm % 08-18-01 debugged cohsig plotting line (302) -sm % 01-25-02 reformated help & license, added links -ad function [amps,cohers,cohsig,ampsig,allamps,allphs] = ... phasecoher(data, frames, srate, freq, cycles, alpha, times, titl, timeStretchRef, timeStretchMarks) MIN_AMP = 10^-6; DEFAULT_ALPHA = nan;% no bootstrap computed COHSIG_REPS = 500; % default number of bootstrap surrogate coherence values % to compute TITLEFONT= 18; TEXTFONT = 16; TICKFONT = 14; DEFAULT_CYCLES=3; ampsig = []; % initialize for null output cohsig = []; if nargin<4 help phasecoher return end if nargin<5 cycles = DEFAULT_CYCLES; end if nargin < 8 | isempty(titl) titl = ''; end if nargin < 7 | isempty(titl) | isempty(times) PLOT_IT = 0; elseif length(times) ~= frames fprintf('phasecoher(): times vector length must be same as frames.\n') return else PLOT_IT = 1; end if nargin < 6 alpha = nan; % no alpha given end if nargout > 2 & isnan(alpha) % if still want cohsig alpha = DEFAULT_ALPHA; elseif nargout > 2 if alpha < 0 | alpha > 0.1 help phasecoher fprintf('phasecoher(): alpha out of bounds.\n'); return end if alpha==0 alpha = nan; % no bootstrap end if alpha*COHSIG_REPS < 5 COHSIG_REPS = ceil(5/alpha); fprintf(' Computing %d bootstrap replications.\n',COHSIG_REPS); end elseif ~isnan(alpha) alpha = nan; % no cohsig calculation end if length(frames)>1 help phasecoher fprintf('phasecoher(): frames should be a single integer.\n'); return end if frames == 0, frames = size(data,1); end trials = size(data,1)*size(data,2)/frames; if floor(trials) ~= trials fprintf('phasecoher(): data length not divisible by %d frames.\n',frames); return end fprintf('phasecoher(): Analyzing %d data trials of %d frames ',trials,frames); if trials < 10 fprintf(... 'Low number of trials (%d) may not give accurate coherences.\n',trials) end if size(freq,1)*size(freq,2)~=1 fprintf('\nphasecoher(): only one frequency can be analyzed at a time.\n'); help phasecoher return end if size(data,1) == 1 data = reshape(data,frames,trials); % trials are columns end window = gauss(ceil(srate/freq*cycles),2); % gauss(std,+/-stds) winlength = length(window); halfwin = floor(winlength/2); fprintf('\n with a moving %d-frame analysis window...',winlength); if frames < winlength fprintf(... '\nProblem: Epoch length (%d frames) too short for analysis with %g cycles!\n',... frames, cycles); return end % % Extend the data to minimize edge effects % data = [data([halfwin+1:-1:1],:); ... data; ... data([frames:-1:frames+1-(winlength-halfwin)],:)]; % % Remove epoch means % %data = data - ones(frames+winlength+1,1)* mean(data); % remove column means angleinc = cycles*2*pi/winlength; cosx = cos(-cycles*pi:angleinc:cycles*pi); % sinusoids cosx = cosx(1:winlength); sinx = sin(-cycles*pi:angleinc:cycles*pi); sinx = sinx(1:winlength); coswin = window.*cosx; % window sinusoids sinwin = window.*sinx; coswin = coswin/(coswin*cosx'); % normalize windowed sinusoids sinwin = sinwin/(sinwin*sinx'); % figure;plot(coswin,'r');hold on; plot(sinwin,'b'); % iang = -cycles*pi:angleinc:cycles*pi; % iang = iang(1:winlength); % figure;plot(iang,[sinwin;coswin]); amps = zeros(1,frames); if nargout > 3 allamps = zeros(frames,trials); end if nargout > 5 allphs = zeros(frames,trials); end cohers = zeros(1,frames); ix = 0:winlength-1; % nsums = zeros(1,frames); % never called C = []; for f = 1:frames %%%%%%%%%%%%%%% frames %%%%%%%%%%%%%%%%%%%% epoch = data(ix+f,:); epoch = epoch - ones(winlength,1)*mean(epoch); % remove epoch means if rem(f,50)== 0 fprintf(' %d',f) end for t = 1:trials %%%%%%%%%%%%%%% trials %%%%%%%%%%%%%%%%%%% realpart = coswin*epoch(:,t); imagpart = sinwin*epoch(:,t); C(f,t) = complex(realpart, imagpart); end end allamps = sqrt(C.*conj(C)); %compute all amplitudes for all frames, all trials allphs = angle(C); %get the phase if exist('timeStretchRef') & exist('timeStretchMarks') & ... length(timeStretchRef) > 0 & length(timeStretchMarks) > 0 %Added -Jean for t=1:trials M = timewarp(timeStretchMarks(:,t)', timeStretchRef'); allamps(:,t) = M*allamps(:,t); allphs(:,t) = angtimewarp(timeStretchMarks(:,t)', timeStretchRef', ... allphs(:,t)); end end [amps, cohers, nsums]=getAmpCoh(allamps, allphs, MIN_AMP); % Old routine, for archeological purposes % $$$ realcoh = zeros(1,frames); % $$$ imagcoh = zeros(1,frames); % $$$ for f = 1:frames %%%%%%%%%%%%%%% frames %%%%%%%%%%%%%%%%%%%% % $$$ epoch = data(ix+f,:); % $$$ %epoch = epoch - ones(winlength,1)*mean(epoch); % remove epoch means % $$$ if rem(f,50)== 0 % $$$ fprintf(' %d',f) % $$$ end % $$$ for t = 1:trials %%%%%%%%%%%%%%% trials %%%%%%%%%%%%%%%%%%% % $$$ realpart = coswin*epoch(:,t); % $$$ imagpart = sinwin*epoch(:,t); % $$$ amp = sqrt(realpart.*realpart+imagpart.*imagpart); % $$$ if amp >= MIN_AMP % $$$ amps(f) = amps(f) + amp; % sum of amps % $$$ realcoh(f) = realcoh(f) + realpart/amp; % $$$ imagcoh(f) = imagcoh(f) + imagpart/amp; % $$$ nsums(f) = nsums(f)+1; % $$$ end % $$$ if nargout > 3 % $$$ if amp < MIN_AMP % $$$ amp = MIN_AMP; % $$$ end % $$$ allamps(f,t) = amp; % $$$ end % $$$ if nargout > 5 % $$$ allphs(f,t) = 180/pi*angle(realpart+i*imagpart); % $$$ end % $$$ end % $$$ if nsums(f)>0 % $$$ amps(f) = amps(f)/nsums(f); % $$$ realcoh(f) = realcoh(f)/nsums(f); % $$$ imagcoh(f) = imagcoh(f)/nsums(f); % $$$ else % $$$ amps(f) = 0; % $$$ realcoh(f) = 0; % $$$ imagcoh(f) = 0; % $$$ end % $$$ end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % $$$ cohers = sqrt(realcoh.^2+imagcoh.^2); fprintf('\n'); cohsig = []; if ~isnan(alpha) %%%%%%%%%%%%%% Compute cohsig/ampsig %%%%%%%%%%%%%% % ix = 0:winlength-1; % never called bootcoher = zeros(1,COHSIG_REPS); bootamp = zeros(1,COHSIG_REPS); bootallamps = zeros(COHSIG_REPS, trials); %Added -Jean bootallphs = zeros(COHSIG_REPS, trials); %Added -Jean fprintf('Computing %d bootstrap coherence values... ',COHSIG_REPS); for f = 1:COHSIG_REPS %%%%%%%%%%%%%%% Bootstrap replications %%%%%%%%%%% if rem(f,50) == 0 fprintf('%d ',f); end randoff = floor(rand(1,trials)*(frames-winlength))+1; % random offsets %Create randomized time-stretched allamps and allphs arrays (see above) for t = 1:trials bootallamps(f, t) = allamps(randoff(t), t); bootallphs(f, t) = allphs(randoff(t), t); end end [bootamp, bootcoher]=getAmpCoh(bootallamps, bootallphs, MIN_AMP); fprintf('\n'); bootcoher = sort(bootcoher); % sort low to high cohsig = bootcoher(round(COHSIG_REPS*(1.0-alpha))); bootamp = sort(bootamp); % sort low to high ampsig = [bootamp(round(COHSIG_REPS*(alpha))) ... bootamp(round(COHSIG_REPS*(1.0-alpha)))]; % keyboard end %%%%%%%%%%%%%%%%%%%%%%%%%%%% end cohsig %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for f=1:halfwin % pad amps, cohers to front of input data amps(f) = amps(halfwin+1); cohers(f) = cohers(halfwin+1); end for f=frames:-1:frames-halfwin % pad amps, cohers to end of input data amps(f) = amps(frames-halfwin); cohers(f) = cohers(frames-halfwin); end if PLOT_IT %%%%%%%%%%%%%% make two-panel plot of results %%%%%%%% subplot(2,1,1);plot(times,amps'); title(titl,'fontsize',TITLEFONT,'fontweight','bold'); ylabel(['Amplitude (' num2str(freq) ' Hz)'],... 'fontsize',TEXTFONT,'fontweight','bold'); ax = axis; hold on; plot([0 0],[0 1],'k'); % vertical line at time 0 axis([ax(1) ax(2) ax(3) ax(4)*1.25]); set(gca,'FontSize',TICKFONT); set(gca,'FontWeight','bold'); subplot(2,1,2);plot(times,cohers','r'); ylabel(['Intertrial Coherence (' num2str(freq) ' Hz)'],... 'fontsize',TEXTFONT,'fontweight','bold'); xlabel('Time (ms)','fontsize',TEXTFONT,'fontweight','bold'); hold on winstframe = floor(frames/7); winframes = [winstframe:winstframe+winlength-1]; wintimes = times(winframes); ax = axis; plot(wintimes,0.8+window*0.1,'k'); plot(wintimes,0.8-window*0.1,'k'); % ax2 = axis; % never called hold on; plot([0 0],[0 1000],'k'); % vertical line at time 0 axis([ax(1) ax(2) 0 1]); set(gca,'fontSize',TICKFONT); set(gca,'FontWeight','bold'); alpha if ~isnan(alpha) % plot coher significance plot([wintimes(1) wintimes(end)],[cohsig cohsig],'r'); % was [times(1) times(winframes)] !?? end end function [amps, cohers, nsums] = getAmpCoh(allamps, allphs, MIN_AMP) minampfilter = allamps >= MIN_AMP; nsums = sum(minampfilter,2); amps(find(nsums == 0)) = 0; %zero the amplitude if no trial shows %significant power at that frame cohers(find(nsums == 0)) = 0; %zero the coherence too if no trial shows %significant power at that frame %Now average out amplitudes over trials % allminamps is never used. TF 04/02/2007 %allminamps = allamps; % nargout is never greater than 3. Bug 262. TF 04/02/2007 %if nargout > 3 % allminamps(~minampfilter) = MIN_AMP; %end allzeramps = allamps .* minampfilter; allzeramps = allzeramps(find(nsums ~= 0),:); amps(find(nsums ~= 0)) = sum(allzeramps,2) ./ nsums(find(nsums ~= 0)); %Convert angles to complex for summing allzerphs = complex(cos(allphs), sin(allphs)) .* minampfilter; allzerphs = allzerphs(find(nsums ~= 0), :); cohers(find(nsums ~= 0)) = sum(allzerphs,2) ./ nsums(find(nsums ~= 0)); cohers = sqrt(cohers .* conj(cohers)); function outvec = gauss(frames,sds) outvec = []; if nargin < 2 help gauss return end if sds <=0 | frames < 1 help gauss return end incr = 2*sds/(frames-1); outvec = exp(-(-sds:incr:sds).^2);
github
ZijingMao/baselineeegtest-master
plotchans3d.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/plotchans3d.m
3,251
utf_8
8664823c760a1d16ba00362311f2de52
% plotchans3d() - Plots the 3-D configuration from a Polhemus ELP % file. The axes of the Cartesian coordinate system are % plotted. The nose is plotted as a bold red segment. % Usage: % >> plotchans3d( elpfile, zs); % >> plotchans3d( [X,Y,Z], elecnames, zs); % % Inputs: % elpfile - Polhemus ELP (electrode position) file % [X,Y,Z] - array of 3-D coordinates % elecnames - cell array containing the names of the electrodes % % Optional input: % zs - vector of electrode indices giving the subset to print labels for % in the plot % % Author: Luca A. Finelli, SCCN/INC/UCSD, La Jolla, 02/2002 % % See also: topoplot(), readlocs(), readelp(), % polhemus2topo(), pop_chanedit() % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 04/01/02 changed header for help2html compatibility -ad % 04/01/02 debuging zs -ad % 04/01/02 adding extra optional [X,Y,Z] argument -ad function plotchans3d(elpfile, arg2, arg3) if nargin<1 help plotchans3d; return; end; zs = []; if isstr(elpfile) if nargin > 1 zs = arg2; end; [elocstruct, elocname, X, Y, Z ] =readelp([elpfile]); else X = elpfile(:,1)'; Y = elpfile(:,2)'; Z = elpfile(:,3)'; if nargin > 1 elocname = arg2; else elocname = []; end; if nargin > 2 zs = arg3; end; end; if isempty(zs) zs = [1:length(elocname)]; end; %zs =[3 7 15 26 36 46 56 64 69 71 72]; figure lim=1.05*max([X Y Z]); eps=lim/20; plot3(X,Y,Z,'ro') hold on if ~isempty(elocname) plot3(X(zs),Y(zs),Z(zs),'b*') end; plot3([0.08 0.12],[0 0],[0 0],'r','LineWidth',4) % nose plot3([0 lim],[0 0],[0 0],'b--') % axis plot3([0 0],[0 lim],[0 0],'g--') plot3([0 0],[0 0],[0 lim],'r--') plot3(0,0,0,'b+') text(lim+eps,0,0,'X','HorizontalAlignment','center',... 'VerticalAlignment','middle','Color',[0 0 0],... 'FontSize',10) text(0,lim+eps,0,'Y','HorizontalAlignment','center',... 'VerticalAlignment','middle','Color',[0 0 0],... 'FontSize',10) text(0,0,lim+eps,'Z','HorizontalAlignment','center',... 'VerticalAlignment','middle','Color',[0 0 0],... 'FontSize',10) box on if ~isempty(elocname) for i = 1:length(zs) text(X(zs(i)),Y(zs(i)),Z(zs(i))+eps,elocname(zs(i)),'HorizontalAlignment','center',... 'VerticalAlignment','middle','Color',[0 0 0],... 'FontSize',10) end end; %axis(repmat([-lim lim],1,3)) axis([-lim lim -lim lim -lim*0.5 lim]) axis equal; rotate3d on try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end
github
ZijingMao/baselineeegtest-master
biosig2eeglab.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/biosig2eeglab.m
7,092
utf_8
0040e73db9c98de459467db8a08ed28e
% biosig2eeglab() - convert BIOSIG structue to EEGLAB structure % % Usage: % >> OUTEEG = pop_biosig2eeglab(hdr, data, interval); % % Inputs: % hdr - BIOSIG header % data - BIOSIG data array % % Optional input: % interval - BIOSIG does not remove event which are outside of % the data range when importing data range subsets. This % parameter helps fix this problem. % % Outputs: % OUTEEG - EEGLAB data structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, Oct. 29, 2009- % % 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 = biosig2eeglab(dat, DAT, interval, channels, importevent); if nargin < 2 help biosig2eeglab; return; end; if nargin < 3 interval = []; end; if nargin < 4 channels = []; end; if nargin < 5 importevent = 0; end; % import data % ----------- if abs(dat.NS - size(DAT,1)) > 1 DAT = DAT'; end; EEG = eeg_emptyset; % 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: ' dat.FileName ]; EEG.xmin = 0; nepoch = dat.NRec; EEG.trials = nepoch; EEG.pnts = size(EEG.data,2)/nepoch; if isfield(dat,'T0') EEG.etc.T0 = dat.T0; % added sjo end if isfield(dat, 'Label') & ~isempty(dat.Label) if isstr(dat.Label) EEG.chanlocs = struct('labels', cellstr(char(dat.Label(dat.InChanSelect)))); % 5/8/2104 insert (dat.InChanSelect) Ramon else % EEG.chanlocs = struct('labels', dat.Label(1:min(length(dat.Label), size(EEG.data,1)))); EEG.chanlocs = struct('labels', dat.Label(dat.InChanSelect)); % sjo added 120907 to avoid error below % 5/8/2104 insert (dat.InChanSelect) Ramon end; if length(EEG.chanlocs) > EEG.nbchan, EEG.chanlocs = EEG.chanlocs(1:EEG.nbchan); end; end EEG = eeg_checkset(EEG); % extract events % this part I totally revamped to work... JO % -------------- 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; % if strcmp(dat.TYPE,'EDF') % sjo added 120907 % disp('filetype EDF does not support events'); % importevent = 0; % end if importevent if isfield(dat, 'BDF') if dat.BDF.Status.Channel <= size(EEG.data,1) EEG.data(dat.BDF.Status.Channel,:) = []; end; EEG.nbchan = size(EEG.data,1); if ~isempty(EEG.chanlocs) && dat.BDF.Status.Channel <= length(EEG.chanlocs) EEG.chanlocs(dat.BDF.Status.Channel,:) = []; end; elseif isempty(dat.EVENT.POS) disp('Extracting events from last EEG channel...'); %Modifieded by Andrey (Aug.5,2008) to detect all non-zero codes: if length(unique(EEG.data(end, 1:100))) > 20 disp('Warning: event extraction failure, the last channel contains data'); elseif length(unique(EEG.data(end, :))) > 1000 disp('Warning: event extraction failure, the last channel contains data'); else thiscode = 0; for p = 1:size(EEG.data,2)*size(EEG.data,3)-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; EEG.data(end,:) = []; EEG.chanlocs(end) = []; end; % recreate the epoch field if necessary % ------------------------------------- if EEG.trials > 1 for i = 1:length(EEG.event) EEG.event(i).epoch = ceil(EEG.event(i).latency/EEG.pnts); end; end; EEG = eeg_checkset(EEG, 'eventconsistency'); end; if ~isempty(dat.EVENT.POS) if isfield(dat, 'out') % Alois fix for event interval does not work if isfield(dat.out, 'EVENT') dat.EVENT = dat.out.EVENT; end; end; EEG.event = biosig2eeglabevent(dat.EVENT, interval); % Toby's fix % recreate the epoch field if necessary % ------------------------------------- if EEG.trials > 1 for i = 1:length(EEG.event) EEG.event(i).epoch = ceil(EEG.event(i).latency/EEG.pnts); end; end; EEG = eeg_checkset(EEG, 'eventconsistency'); elseif isempty(EEG.event) 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; end; % convert data to single if necessary % ----------------------------------- EEG = eeg_checkset(EEG,'makeur'); % Make EEG.urevent field EEG = eeg_checkset(EEG);
github
ZijingMao/baselineeegtest-master
changeunits.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/changeunits.m
4,318
utf_8
94064327606cc4ebb997d7e5e58d4bfe
% changeunits() - Takes one or more points in one axes and gives its position % in another axes. Useful for drawing lines between % sbplots (see sbplot()). % % Usage: >> newpoint(s) = changeunits(point(s),curaxhandle,newaxhandle) % % Inputs: % point(s) - two-column vector of current [x y] data point locations % curaxhandle - the point's current axes % newaxhandle - the new axes handle. If figure handle or absent, returns % the coordinates of the points in the whole figure % % Output: % newpoint(s) - the coordinates of the same point(s) in the new axes % % Example: % >> figure % >> small1 = sbplot(4,4,10); % small axes in lower left % >> plot(0.3,0.4,'ro'); % mark point [0.3 0.4] in small1 axes % >> axis([0 1 0 1]); % set axes limits % % >> small2 = sbplot(4,4,7); % small axes in upper right % >> plot(0.6,0.7,'ro'); % mark point [0.6 0.7] in small2 axes % >> axis([0 1 0 1]); % set axes limits % % >> large = sbplot(1,1,1); % normal whole figure axes % >> % Now draw line from point [0.3 0.4] in small1 axes % >> % to point [0.6 0.7] in small2 axes % >> from = changeunits([0.3 0.4],small1,large); % point in small1 axes % >> to = changeunits([0.6 0.7],small2,large); % point in small2 axes % >> plot([from(1) to(1)],[from(2) to(2)]) % >> axis([0 1 0 1]); % set large axes limits % >> axis off % finally, hide large axes % % Author: Colin Humphries, Salk Institute, La Jolla CA, Jan. 1998 % Copyright (C) 1998 Colin Humphries, Salk Institute, La Jolla CA, Jan. 1998 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 02-01-01 added default 3rd arg, multiple points, example -Scott Makeig % 01-25-02 reformated help & license -ad function [newpnts] = changeunits(pnts,ax1,ax2) curax = gca; curfig = gcf; if nargin<2 help changeunits error('Must have at least 2 arguments'); end if size(pnts,2) ~= 2 help changeunits error('Points must be 2-column'); end if ~strcmp(get(ax1,'type'),'axes') error('Second argument must be an axes handle') end if nargin<3 figh = get(ax1,'Parent'); figure(figh); ax2 = axes('Units','Normal','Position',[0 0 1 1],'Visible','Off'); % whole figure axes in ax1 figure end if strcmp(get(ax2,'type'),'axes') figh = get(ax1,'Parent'); if figh ~= get(ax2,'Parent') error('Axes must be in the same figure.') end units1 = get(ax1,'Units'); units2 = get(ax2,'Units'); set(ax1,'Units','normalized') set(ax2,'Units','normalized') axpos1 = get(ax1,'Position'); axpos2 = get(ax2,'Position'); xlim1 = get(ax1,'Xlim'); xlim2 = get(ax2,'Xlim'); ylim1 = get(ax1,'Ylim'); ylim2 = get(ax2,'Ylim'); l1 = [xlim1(1) ylim1(1)]; l2 = [xlim1(2) ylim1(2)]; p1 = axpos1([1,2]); p2 = axpos1([3,4]); ll1 = [xlim2(1) ylim2(1)]; ll2 = [xlim2(2) ylim2(2)]; pp1 = axpos2([1,2]); pp2 = axpos2([3,4]); newpnts = zeros(size(pnts)); for p = 1:size(pnts,1) figpnt = (((pnts(p,:)-l1)./(l2-l1)).*p2) + p1; newpnts(p,:) = (((figpnt-pp1)./pp2).*(ll2-ll1)) + ll1; end set(ax1,'Units',units1) set(ax2,'Units',units2) elseif strcmp(get(ax2,'type'),'figure') axpos1 = get(ax1,'Position'); xlim1 = get(ax1,'Xlim'); % value limits in ax1 ylim1 = get(ax1,'Ylim'); l1 = [xlim1(1) ylim1(1)]; l2 = [xlim1(2) ylim1(2)]; p1 = axpos1([1,2]); p2 = axpos1([3,4]); newpnts = zeros(size(pnts)); for p = 1:size(pnts,1) % unnecessary loop? newpnts(p,:) = (((pnts(p,:)-l1)./(l2-l1)).*p2) + p1; end end if nargin<3 delete(ax2) end figure(curfig); % restore gcf axes(curax); % restore gca
github
ZijingMao/baselineeegtest-master
ploterp.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/ploterp.m
3,923
utf_8
86b19356589f4063b6895c62ff72609c
% ploterp() - plot a selected multichannel data epoch on a common timebase % % Usage: >> ploterp(data,frames,epoch,[limits],'title',[plotchans]); % % Inputs: % data = EEG/ERP data epoch (chans,frames) % frames = frames per epoch {default: data length} % epoch = epoch to plot {default: 1} % [limits] = [xmin xmax ymin ymax] (x's in ms) % {def|0 or both y's 0 -> data limits} % 'title' = plot title {default|0 -> none} % plotchans = data channels to plot {default|0 -> all} % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 6-11-98 % % See also: timtopo() % Copyright (C) 6-11-98 from plotdata() Scott Makeig, SCCN/INC/UCSD, % [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license, added links -ad function plot_handl = ploterp(data,frames,epoch,limits,titl,plotchans) LABELFONT = 16; TICKFONT = 14; TITLEFONT = 16; if nargin < 1 help ploterp return end [chans,framestot] = size(data); icadefs; if nargin < 6 plotchans = 0; end if plotchans==0 plotchans = 1:chans; end if nargin < 5, titl = ''; % DEFAULT TITLE end if nargin < 4, limits = 0; end if nargin < 3 epoch = 0; end if epoch == 0 epoch = 1; end if nargin<2 frames = 0; end if frames == 0 frames = size(data,2); end if floor(framestot/frames)*frames ~= framestot fprintf('ploterp(): frames argument does not divide data length.\n'); return end if epoch*frames > framestot fprintf('ploterp(): data does not contain %d epochs of %d frames.\n',epoch,frames); return end % %%%%%%%%%%%%%%%%%%%%%%% Read and adjust limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if limits==0, % == 0 or [0 0 0 0] xmin=0; xmax=frames-1; ymin=min(min(data)); ymax=max(max(data)); else if length(limits)~=4, fprintf( ... 'ploterp: limits should be 0 or an array [xmin xmax ymin ymax].\n'); return end; xmin = limits(1); xmax = limits(2); ymin = limits(3); ymax = limits(4); end; if xmax == 0 & xmin == 0, x = (0:1:frames-1); xmin = 0; xmax = frames-1; else dx = (xmax-xmin)/(frames-1); x=xmin*ones(1,frames)+dx*(0:frames-1); % compute x-values end; if xmax<=xmin, fprintf('ploterp() - xmax must be > xmin.\n') return end if ymax == 0 & ymin == 0, ymax=max(max(data)); ymin=min(min(data)); end if ymax<=ymin, fprintf('ploterp() - ymax must be > ymin.\n') return end sampint = (xmax-xmin)/(frames-1); % sampling interval = 1000/srate; x = xmin:sampint:xmax; % make vector of x-values % %%%%%%%%%%%%%%%%%%%%%%% Plot the data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % cla % clear the current figure axes set(gca,'YColor',BACKCOLOR); % set the background color set(gca,'Color',BACKCOLOR); set(gca,'GridLineStyle',':') set(gca,'Xgrid','off') set(gca,'Ygrid','on') set(gca,'Color',BACKCOLOR,'FontSize',TICKFONT,'FontWeight','bold'); plot_handl=plot(x,data(plotchans,(epoch-1)*frames+1:epoch*frames)); % plot the data title(titl,'fontsize',TITLEFONT,'FontWeight','bold'); l= xlabel('Time (ms)'); set(l,'FontSize',LABELFONT,'FontWeight','bold'); l=ylabel('Potential (uV)'); set(l,'FontSize',LABELFONT,'FontWeight','bold'); axis([xmin xmax ymin ymax]);
github
ZijingMao/baselineeegtest-master
forcelocs.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/forcelocs.m
7,010
utf_8
a97dcbb735eedf75d6f3a7e5590deaee
% forcelocs() - rotate location in 3-D so specified electrodes % match specified locations. % CAUTION: Only for use on electrodes in % and remaining in the upper spherical hemisphere, % otherwise it will work improperly. Written primarily for % adjusting all electrodes homogenously with Cz. % % Usage: % >> chanlocs = forcelocs( chanlocs ); % pop-up window mode % >> chanlocs = forcelocs( chanlocs, loc1, loc2, ... ); % Example: % >> chanlocs = forcelocs( chanlocs, { 0.78, 'x', 'A1' }, { 0.023, 'x', ... % 'B1','B2','Cz' } ); % % Inputs: % chanlocs - EEGLAB channel structure. See help readlocs() % % Optional inputs: % loc1 - cell array: { location, axis, channame1, channame2, .. } % 'location' is new cartesian coordinate of channame1 along 'axis' % 'axis' is either % 'X' New x-coordinate of mean of channame1, channame2, % etc. Used to calculate the X-Z plane angle by % which to rotate all channels. % Note that all rotations are to the corresponding positive % Z-value, since theta=atan(z/x). % 'Y' New x-coordinate of mean of channame1, channame2, % etc. % % 'channame#' Name of channel(s) to be rotated, as they appear in % chanlocs.label % loc2 - same as loc1 % % Outputs: % chanlocs - updated EEGLAB channel structure. % % % Author: Arnaud Delorme, CNL / Salk Institute, 15 April 2003 % % See also: readlocs() % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [chanlocs,options] = forcelocs( chanlocs, varargin) NENTRY = 1; % number of lines in GUI FIELDS = { 'X' 'Y' }; options = []; if nargin < 1 help forcelocs; return; end; if nargin < 2 geom = { [0.4 1 1 0.3] }; uilist = { { 'style' 'text' 'string' 'X/Y value' 'tag' 'valstr' } ... { 'style' 'text' 'string' 'Coordinate' } ... { 'style' 'text' 'string' 'Electrode list' } ... { } }; for index = 1:NENTRY tag = [ 'c' int2str(index) ]; geom = { geom{:} [0.3 1 1 0.3] }; uilist = { uilist{:},{ 'style' 'edit' 'string' fastif(index==1, '0','') }, ... { 'style' 'listbox' 'string' 'X (rotate X-Z plane)|Y (rotate Y-Z plane)' ... 'callback' [ 'if get(gco, ''value'') == 1,' ... ' set(findobj(gcbf, ''tag'', ''valstr''), ''string'', ''Y value'');' ... 'else set(findobj(gcbf, ''tag'', ''valstr''), ''string'', ''X value'');' ... 'end;' ] }, ... { 'style' 'edit' 'string' fastif(index==1, 'Cz','') 'tag' tag }, ... { 'style' 'pushbutton' 'string' 'Pick' ... 'callback', [ 'tmp3 = get(gcbf, ''userdata'');' ... '[tmp1 tmp2] = pop_chansel({tmp3.labels}, ''selectionmode'', ''single'');' ... 'if ~isempty(tmp1) set(findobj(gcbf, ''tag'', ''' tag '''), ''string'', tmp2); end;' ... 'clear tmp1 tmp2;' ] } }; end; results = inputgui( geom, uilist, 'pophelp(''forcelocs'');', 'Force electrode location -- forcelocs()', chanlocs ); if length(results) == 0, return; end; options = {}; for index = 1:NENTRY tmpi = 3*(index-1)+1; if ~isempty(results{tmpi}) tmpchans = parsetxt(results{tmpi+2}); options = { options{:},{ str2num(results{tmpi}) FIELDS{results{tmpi+1}} tmpchans{:} }}; end; end; else options = varargin; end; % scan all locations % ------------------ channelnames = lower(strvcat({chanlocs.labels})); for index = 1:length(options) val = options{index}{1}; type = options{index}{2}; chans = getchans(options{index}(3:end), channelnames); % rotate X-Z plane % ---------------- if strcmpi(type, 'x') curx = mean([ chanlocs(chans).X ]); curz = mean([ chanlocs(chans).Z ]); newx = val; rotangle = solvesystem(curx, curz, newx); for chanind = 1:length(chanlocs) [chanlocs(chanind).X chanlocs(chanind).Z]= rotation(chanlocs(chanind).X, chanlocs(chanind).Z, rotangle); end; chanlocs = convertlocs(chanlocs, 'cart2all'); end; % rotate Y-Z plane % ---------------- if strcmpi(type, 'y') cury = mean([ chanlocs(chans).Y ]); curz = mean([ chanlocs(chans).Z ]); newy = val; rotangle = solvesystem(cury, curz, newy); for chanind = 1:length(chanlocs) [chanlocs(chanind).Y chanlocs(chanind).Z]= rotation(chanlocs(chanind).Y, chanlocs(chanind).Z, rotangle); end; chanlocs = convertlocs(chanlocs, 'cart2all'); end; end; % get channel indices % ------------------- function chanlist = getchans(chanliststr, channelnames); chanlist = []; for index = 1:length(chanliststr) i = strmatch (lower(chanliststr{index}), channelnames, 'exact'); chanlist = [chanlist i]; end; % function rotate coordinates % --------------------------- function [X,Y] = rotation(x,y,rotangle) X = real((x+j*y)*exp(j*rotangle)); Y = imag((x+j*y)*exp(j*rotangle)); % function solvesyst % ------------------ function theta = solvesystem(x,y,nx) % Original Solution %eq(1,:) = [x -y]; res(1) = nx; %eq(2,:) = [y x]; res(2) = sqrt(x^2+y^2-nx^2); %sol = eq\res'; %theta = atan2(sol(2), sol(1)); % simplified solution ny = sqrt(x^2+y^2-nx^2); ang1 = angle(x+j*y); ang2 = angle(nx+j*ny); theta = ang2-ang1; % Even simpler solution Toby 03/05/2007 % theta = atan(y/x);
github
ZijingMao/baselineeegtest-master
rejtrend.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/rejtrend.m
3,677
utf_8
9196ccbe2b666079d926f2bbbdc7fa83
% rejtrend() - detect linear trends in EEG activity and reject the % epoched trials based on the accuracy of the linear % fit. % Usage: % >> [rej rejE] = rejtrend( signal, winsize, maxslope, minR, step); % % Inputs: % signal - 3 dimensional signal (channels x frames x trials) % winsize - integer determining the number of consecutive points % for the detection of linear patterns % maxslope - maximum acceptable absolute slope of the linear trend. If the slope % of the line fitted to a data epoch is greater than or equal to % maxslope, that epoch is rejected (assuming a sufficient R^2 value, % see minR below). % minR - minimal R^2 (coefficient of determination between % 0 and 1). The R^2 value reflects how well the data epoch is % approximated by a line. An epoch is not rejected unless its R^2 % value is greater than minR. % step - step for the window. Default is 1 point (2 points % will divide by two the computation time) % % Outputs: % rej - rejected trials. Array with 0 or 1 for each trial. % rejE - rejected rows of the rejected trials % % Algorithm: % Looked for all possible windows of size 'winsize' of each trial if % the linear fit have minimum slope and R^2 % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [rej, rejE] = rejtrend( signal, pointrange, maxslope, minstd, step); % This is to avoid divide-by-zero and machine errors. SST_TOLERANCE = 1000*pointrange*1.1921e-07; if nargin < 3 help rejtrend; return; end; if nargin < 5 step = pointrange; end; [chans pnts trials] = size(signal); rejE = zeros( chans, trials); x = linspace( 1/pointrange, 1, pointrange ); %waitbarhandle = waitbar(0,'rejtrend.m Please wait...'); for c = 1:chans for t = 1:trials for w = 1:step:(pnts-pointrange+1) y = signal(c, [w:w+pointrange-1], t); coef = polyfit(x,y,1); if abs(coef(1)) >= maxslope ypred = polyval(coef,x); % predictions dev = y - mean(y); % deviations - measure of spread SST = sum(dev.^2); % total variation to be accounted for if SST < SST_TOLERANCE % make sure SST is not too close to zero SST = SST_TOLERANCE; end resid = y - ypred; % residuals - measure of mismatch SSE = sum(resid.^2); % variation NOT accounted for Rsq = 1 - SSE/SST; % percent of error explained if Rsq > minstd rejE( c, t ) = 1; end % see the page http://www.facstaff.bucknell.edu/maneval/help211/fitting.html end end end %waitbar(c/chans); end %close(waitbarhandle); rej = max( rejE, [], 1); return;
github
ZijingMao/baselineeegtest-master
slider.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/slider.m
5,310
utf_8
da3f7a317a05c2c37254282f6d2b6bac
% slider() - add slider to a figure % % Usage: % >> slider( handler, horiz, vert, horizmag, vertmag); % % Inputs: % handler - figure handler (for the current figure, use gcf) % horiz - [0|1] add a horizontal slider % vert - [0|1] add a horizontal slider % horizmag - magnify the width of the figure before adding the slider. % Default is 1. % vertmag - magnify the height of the figure before adding the slider. % Default is 1. % allowsup - [0|1] allow suppression of slider by the 'x' button. % Default is 1. % % Note: % clicking on the 'x' the right corner restores the original setting % % Example: figure; plot(1:10); slider(gcf, 1, 1, 2, 2); % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function slider( handler, horiz, vert, horizmag, vertmag, allowsup); if nargin < 2 help slider; return; end; if nargin < 3 vert = 0; end; if nargin < 4 horizmag = 1; end; if nargin < 5 vertmag = 1; end; if nargin < 6 allowsup = 1; end; pos = get(gcf, 'position'); width = 5/pos(3)*400; height = 5/pos(4)*400; pos = get(gca,'position'); % plot relative to current axes q = [0.13 0.11 0 0]; s = [0.0077 0.0081 0.0077 0.0081]; if vert h = uicontrol('Parent',handler, ... 'style', 'slider', 'Units','Normalized', 'userdata', 1, 'value', 1, ... 'Position', [113-width -9 width 119].*s+q, 'tag', 'winslider', ... 'string','vertslider', 'callback', ... ['if isempty(gcbf), fig = gcf; else fig = gcbf; end;' ... 'h = findobj(''parent'', fig);' ... 'h2 = findobj(''parent'', fig, ''tag'', ''winslider'');' ... 'h = setdiff_bc( h, h2);' ... 'curobj = findobj(''parent'', fig, ''string'', ''vertslider'');' ... 'shift = get(curobj, ''userdata'') - get(curobj, ''value'');' ... 'set( curobj, ''userdata'', get(curobj, ''value''));' ... 'for i = 1:length(h),' ... ' curpos = get( h(i), ''position'');' ... ' set( h(i), ''position'', [ curpos(1) curpos(2)+' num2str(vertmag-1) '*shift curpos(3:end)]);' ... 'end;' ... 'clear h2 h shift i curpos fig curobj;'] ); end; if horiz hz = uicontrol('Parent',handler, ... 'style', 'slider', 'Units','Normalized', 'userdata', 1, 'value', 1, ... 'Position', [-17 -19+height 125 height].*s+q, 'tag', 'winslider', ... 'string','horizslider', 'callback', ... ['if isempty(gcbf), fig = gcf; else fig = gcbf; end;' ... 'h = findobj(''parent'', fig);' ... 'h2 = findobj(''parent'', fig, ''tag'', ''winslider'');' ... 'h = setdiff_bc( h, h2);' ... 'curobj = findobj(''parent'', fig, ''string'', ''horizslider'');' ... 'shift = get(curobj, ''userdata'') - get(curobj, ''value'');' ... 'set( curobj, ''userdata'', get(curobj, ''value''));' ... 'for i = 1:length(h),' ... ' curpos = get( h(i), ''position'');' ... ' set( h(i), ''position'', [ curpos(1)+' num2str(horizmag-1) '*shift curpos(2:end)]);' ... 'end;' ... 'clear h2 h shift i curpos fig curobj;'] ); end; % button to remove the slider % --------------------------- but = uicontrol( 'style', 'pushbutton', 'Units','Normalized', ... 'string', 'x', 'position', [113-width -19+height width height].*s+q, 'tag', 'winslider', 'callback', ... ['hx = findobj(''parent'', gcbf, ''tag'', ''winslider'');' ... % put slider to their extremities 'hx = setdiff_bc(hx, gcbo);' ... 'set(hx, ''value'', 1);' ... 'eval(get(hx(1), ''callback''));' ... 'if length(hx) >1, eval(get(hx(2), ''callback'')); end;' ... 'h = findobj(''parent'', gcbf);' ... % recompute positions 'for i = 1:length(h),' ... ' curpos = get( h(i), ''position'');' ... ' set( h(i), ''position'', [(curpos(1)+(' num2str(horizmag) '-1))/' num2str(horizmag) ' (curpos(2)+(' num2str(vertmag) '-1))/' num2str(vertmag) ' curpos(3)/' num2str(horizmag) ' curpos(4)/' num2str(vertmag) ']);' ... 'end;' ... 'clear h hx curpos;' ... 'delete( findobj(''parent'', gcbf, ''tag'', ''winslider'') );' ]); if ~allowsup set(but, 'enable', 'off'); end; % magnify object in the window % ---------------------------- h = findobj('parent', handler); set( h, 'units', 'normalized'); h2 = findobj('parent', handler, 'tag', 'winslider'); h = setdiff_bc( h, h2); for i = 1:length(h) curpos = get( h(i), 'position'); set( h(i), 'position', [curpos(1)*horizmag-(horizmag-1) curpos(2)*vertmag-(vertmag-1) curpos(3)*horizmag curpos(4)*vertmag]); end; if horiz % set the horizontal axis to 0 % ---------------------------- set(hz, 'value', 0); eval(get(hz, 'callback')); end; return;
github
ZijingMao/baselineeegtest-master
loadcnt.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/loadcnt.m
29,097
utf_8
5e1876613970ecc4b37123e6cf44f648
% loadcnt() - Load a Neuroscan continuous signal file. % % Usage: % >> cnt = loadcnt(file, varargin) % % Inputs: % filename - name of the file with extension % % Optional inputs: % 't1' - start at time t1, default 0. Warning, events latency % might be innacurate (this is an open issue). % 'sample1' - start at sample1, default 0, overrides t1. Warning, % events latency might be innacurate. % 'lddur' - duration of segment to load, default = whole file % 'ldnsamples' - number of samples to load, default = whole file, % overrides lddur % 'scale' - ['on'|'off'] scale data to microvolt (default:'on') % 'dataformat' - ['int16'|'int32'] default is 'int16' for 16-bit data. % Use 'int32' for 32-bit data. % 'blockread' - [integer] by default it is automatically determined % from the file header, though sometimes it finds an % incorect value, so you may want to enter a value manually % here (1 is the most standard value). % '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. % 'precision': string describing data precision during loading % process. ['single' | 'double']. If this field is % ommitted, program will attempt to check eeglab_options. % If that doesn't work, then it will default to 'single' % % Outputs: % cnt - structure with the continuous data and other informations % cnt.header % cnt.electloc % cnt.data % cnt.tag % % Authors: Sean Fitzgibbon, Arnaud Delorme, 2000- % % Note: function original name was load_scan41.m % % Known limitations: % For more see http://www.cnl.salk.edu/~arno/cntload/index.html % Copyright (C) 2000 Sean Fitzgibbon, <[email protected]> % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [f,lab,ev2p] = loadcnt(filename,varargin) if ~isempty(varargin) r=struct(varargin{:}); else r = []; end; try, r.t1; catch, r.t1=0; end try, r.sample1; catch, r.sample1=[]; end try, r.lddur; catch, r.lddur=[]; end try, r.ldnsamples; catch, r.ldnsamples=[]; end try, r.scale; catch, r.scale='on'; end try, r.blockread; catch, r.blockread = []; end try, r.dataformat; catch, r.dataformat = 'auto'; end try, r.memmapfile; catch, r.memmapfile = ''; end %% DATA PRECISION CHECK if ~isfield(r, 'precision') || isempty(r.precision) % Try loading eeglab defaults. Otherwise, go with single precision. try eeglab_options; if option_single==1 r.precision='single'; else r.precision='double'; end % if option_single catch r.precision='single'; end % try catch end % ~isfield(... sizeEvent1 = 8 ; %%% 8 bytes for Event1 sizeEvent2 = 19 ; %%% 19 bytes for Event2 sizeEvent3 = 19 ; %%% 19 bytes for Event3 type='cnt'; if nargin ==1 scan=0; end fid = fopen(filename,'r', 'l'); % disp(['Loading file ' filename ' ...']) h.rev = fread(fid,12,'char'); h.nextfile = fread(fid,1,'long'); h.prevfile = fread(fid,1,'ulong'); h.type = fread(fid,1,'char'); h.id = fread(fid,20,'char'); h.oper = fread(fid,20,'char'); h.doctor = fread(fid,20,'char'); h.referral = fread(fid,20,'char'); h.hospital = fread(fid,20,'char'); h.patient = fread(fid,20,'char'); h.age = fread(fid,1,'short'); h.sex = fread(fid,1,'char'); h.hand = fread(fid,1,'char'); h.med = fread(fid,20, 'char'); h.category = fread(fid,20, 'char'); h.state = fread(fid,20, 'char'); h.label = fread(fid,20, 'char'); h.date = fread(fid,10, 'char'); h.time = fread(fid,12, 'char'); h.mean_age = fread(fid,1,'float'); h.stdev = fread(fid,1,'float'); h.n = fread(fid,1,'short'); h.compfile = fread(fid,38,'char'); h.spectwincomp = fread(fid,1,'float'); h.meanaccuracy = fread(fid,1,'float'); h.meanlatency = fread(fid,1,'float'); h.sortfile = fread(fid,46,'char'); h.numevents = fread(fid,1,'int'); h.compoper = fread(fid,1,'char'); h.avgmode = fread(fid,1,'char'); h.review = fread(fid,1,'char'); h.nsweeps = fread(fid,1,'ushort'); h.compsweeps = fread(fid,1,'ushort'); h.acceptcnt = fread(fid,1,'ushort'); h.rejectcnt = fread(fid,1,'ushort'); h.pnts = fread(fid,1,'ushort'); h.nchannels = fread(fid,1,'ushort'); h.avgupdate = fread(fid,1,'ushort'); h.domain = fread(fid,1,'char'); h.variance = fread(fid,1,'char'); h.rate = fread(fid,1,'ushort'); % A USER CLAIMS THAT SAMPLING RATE CAN BE h.scale = fread(fid,1,'double'); % FRACTIONAL IN NEUROSCAN WHICH IS h.veogcorrect = fread(fid,1,'char'); % OBVIOUSLY NOT POSSIBLE HERE (BUG 606) h.heogcorrect = fread(fid,1,'char'); h.aux1correct = fread(fid,1,'char'); h.aux2correct = fread(fid,1,'char'); h.veogtrig = fread(fid,1,'float'); h.heogtrig = fread(fid,1,'float'); h.aux1trig = fread(fid,1,'float'); h.aux2trig = fread(fid,1,'float'); h.heogchnl = fread(fid,1,'short'); h.veogchnl = fread(fid,1,'short'); h.aux1chnl = fread(fid,1,'short'); h.aux2chnl = fread(fid,1,'short'); h.veogdir = fread(fid,1,'char'); h.heogdir = fread(fid,1,'char'); h.aux1dir = fread(fid,1,'char'); h.aux2dir = fread(fid,1,'char'); h.veog_n = fread(fid,1,'short'); h.heog_n = fread(fid,1,'short'); h.aux1_n = fread(fid,1,'short'); h.aux2_n = fread(fid,1,'short'); h.veogmaxcnt = fread(fid,1,'short'); h.heogmaxcnt = fread(fid,1,'short'); h.aux1maxcnt = fread(fid,1,'short'); h.aux2maxcnt = fread(fid,1,'short'); h.veogmethod = fread(fid,1,'char'); h.heogmethod = fread(fid,1,'char'); h.aux1method = fread(fid,1,'char'); h.aux2method = fread(fid,1,'char'); h.ampsensitivity = fread(fid,1,'float'); h.lowpass = fread(fid,1,'char'); h.highpass = fread(fid,1,'char'); h.notch = fread(fid,1,'char'); h.autoclipadd = fread(fid,1,'char'); h.baseline = fread(fid,1,'char'); h.offstart = fread(fid,1,'float'); h.offstop = fread(fid,1,'float'); h.reject = fread(fid,1,'char'); h.rejstart = fread(fid,1,'float'); h.rejstop = fread(fid,1,'float'); h.rejmin = fread(fid,1,'float'); h.rejmax = fread(fid,1,'float'); h.trigtype = fread(fid,1,'char'); h.trigval = fread(fid,1,'float'); h.trigchnl = fread(fid,1,'char'); h.trigmask = fread(fid,1,'short'); h.trigisi = fread(fid,1,'float'); h.trigmin = fread(fid,1,'float'); h.trigmax = fread(fid,1,'float'); h.trigdir = fread(fid,1,'char'); h.autoscale = fread(fid,1,'char'); h.n2 = fread(fid,1,'short'); h.dir = fread(fid,1,'char'); h.dispmin = fread(fid,1,'float'); h.dispmax = fread(fid,1,'float'); h.xmin = fread(fid,1,'float'); h.xmax = fread(fid,1,'float'); h.automin = fread(fid,1,'float'); h.automax = fread(fid,1,'float'); h.zmin = fread(fid,1,'float'); h.zmax = fread(fid,1,'float'); h.lowcut = fread(fid,1,'float'); h.highcut = fread(fid,1,'float'); h.common = fread(fid,1,'char'); h.savemode = fread(fid,1,'char'); h.manmode = fread(fid,1,'char'); h.ref = fread(fid,10,'char'); h.rectify = fread(fid,1,'char'); h.displayxmin = fread(fid,1,'float'); h.displayxmax = fread(fid,1,'float'); h.phase = fread(fid,1,'char'); h.screen = fread(fid,16,'char'); h.calmode = fread(fid,1,'short'); h.calmethod = fread(fid,1,'short'); h.calupdate = fread(fid,1,'short'); h.calbaseline = fread(fid,1,'short'); h.calsweeps = fread(fid,1,'short'); h.calattenuator = fread(fid,1,'float'); h.calpulsevolt = fread(fid,1,'float'); h.calpulsestart = fread(fid,1,'float'); h.calpulsestop = fread(fid,1,'float'); h.calfreq = fread(fid,1,'float'); h.taskfile = fread(fid,34,'char'); h.seqfile = fread(fid,34,'char'); h.spectmethod = fread(fid,1,'char'); h.spectscaling = fread(fid,1,'char'); h.spectwindow = fread(fid,1,'char'); h.spectwinlength = fread(fid,1,'float'); h.spectorder = fread(fid,1,'char'); h.notchfilter = fread(fid,1,'char'); h.headgain = fread(fid,1,'short'); h.additionalfiles = fread(fid,1,'int'); h.unused = fread(fid,5,'char'); h.fspstopmethod = fread(fid,1,'short'); h.fspstopmode = fread(fid,1,'short'); h.fspfvalue = fread(fid,1,'float'); h.fsppoint = fread(fid,1,'short'); h.fspblocksize = fread(fid,1,'short'); h.fspp1 = fread(fid,1,'ushort'); h.fspp2 = fread(fid,1,'ushort'); h.fspalpha = fread(fid,1,'float'); h.fspnoise = fread(fid,1,'float'); h.fspv1 = fread(fid,1,'short'); h.montage = fread(fid,40,'char'); h.eventfile = fread(fid,40,'char'); h.fratio = fread(fid,1,'float'); h.minor_rev = fread(fid,1,'char'); h.eegupdate = fread(fid,1,'short'); h.compressed = fread(fid,1,'char'); h.xscale = fread(fid,1,'float'); h.yscale = fread(fid,1,'float'); h.xsize = fread(fid,1,'float'); h.ysize = fread(fid,1,'float'); h.acmode = fread(fid,1,'char'); h.commonchnl = fread(fid,1,'uchar'); h.xtics = fread(fid,1,'char'); h.xrange = fread(fid,1,'char'); h.ytics = fread(fid,1,'char'); h.yrange = fread(fid,1,'char'); h.xscalevalue = fread(fid,1,'float'); h.xscaleinterval = fread(fid,1,'float'); h.yscalevalue = fread(fid,1,'float'); h.yscaleinterval = fread(fid,1,'float'); h.scaletoolx1 = fread(fid,1,'float'); h.scaletooly1 = fread(fid,1,'float'); h.scaletoolx2 = fread(fid,1,'float'); h.scaletooly2 = fread(fid,1,'float'); h.port = fread(fid,1,'short'); h.numsamples = fread(fid,1,'ulong'); h.filterflag = fread(fid,1,'char'); h.lowcutoff = fread(fid,1,'float'); h.lowpoles = fread(fid,1,'short'); h.highcutoff = fread(fid,1,'float'); h.highpoles = fread(fid,1,'short'); h.filtertype = fread(fid,1,'char'); h.filterdomain = fread(fid,1,'char'); h.snrflag = fread(fid,1,'char'); h.coherenceflag = fread(fid,1,'char'); h.continuoustype = fread(fid,1,'char'); h.eventtablepos = fread(fid,1,'ulong'); h.continuousseconds = fread(fid,1,'float'); h.channeloffset = fread(fid,1,'long'); h.autocorrectflag = fread(fid,1,'char'); h.dcthreshold = fread(fid,1,'uchar'); for n = 1:h.nchannels e(n).lab = deblank(char(fread(fid,10,'char')')); e(n).reference = fread(fid,1,'char'); e(n).skip = fread(fid,1,'char'); e(n).reject = fread(fid,1,'char'); e(n).display = fread(fid,1,'char'); e(n).bad = fread(fid,1,'char'); e(n).n = fread(fid,1,'ushort'); e(n).avg_reference = fread(fid,1,'char'); e(n).clipadd = fread(fid,1,'char'); e(n).x_coord = fread(fid,1,'float'); e(n).y_coord = fread(fid,1,'float'); e(n).veog_wt = fread(fid,1,'float'); e(n).veog_std = fread(fid,1,'float'); e(n).snr = fread(fid,1,'float'); e(n).heog_wt = fread(fid,1,'float'); e(n).heog_std = fread(fid,1,'float'); e(n).baseline = fread(fid,1,'short'); e(n).filtered = fread(fid,1,'char'); e(n).fsp = fread(fid,1,'char'); e(n).aux1_wt = fread(fid,1,'float'); e(n).aux1_std = fread(fid,1,'float'); e(n).senstivity = fread(fid,1,'float'); e(n).gain = fread(fid,1,'char'); e(n).hipass = fread(fid,1,'char'); e(n).lopass = fread(fid,1,'char'); e(n).page = fread(fid,1,'uchar'); e(n).size = fread(fid,1,'uchar'); e(n).impedance = fread(fid,1,'uchar'); e(n).physicalchnl = fread(fid,1,'uchar'); e(n).rectify = fread(fid,1,'char'); e(n).calib = fread(fid,1,'float'); end % finding if 32-bits of 16-bits file % ---------------------------------- begdata = ftell(fid); if strcmpi(r.dataformat, 'auto') % Chris Bishop 14/01/15 % Auto detection relies on a single byte of data that is not written % with writecnt.m. Consequently, a CNT file read in using loadcnt and % written using writecnt cannot automatically detect data precision. % However, we can use other, more robust information to achieve this. % % 14/02/19 CWB: % Actually, this information may not be reliable for some file types % (e.g., those supplied by Arno D. for testing purposes). A try catch % is probably the safest bet with an additional safeguard. % If two bytes (16 bit) or 4 bytes (32 bit). If we can't tell, throw an % error. try % This approach relies on sensible headers. CWB has used this on % many 32-bit datasets from SCAN 4.5, but earlier versions and % testing 16-bit testing materials seem to have non-sensicle % headers. So this won't work every time. % DataPointsPerChannel dppc=(h.eventtablepos-begdata)./h.nchannels; if dppc/2==h.numsamples r.dataformat='int16'; elseif dppc/4==h.numsamples r.dataformat='int32'; else error('loadcnt:AutoDetectionFailure', 'loadcnt failed to automatically detect data precision'); end % if dppc./2 ... catch % original code commented out by CWB r.dataformat = 'int16'; if (h.nextfile > 0) % Grab informative byte that tells us if this is 32 or 16 bit % data. Note, however, that this is *not* available in files % generated from writecnt.m. Thus, the try statement above is % necessary. fseek(fid,h.nextfile+52,'bof'); is32bit = fread(fid,1,'char'); if (is32bit == 1) r.dataformat = 'int32'; end; fseek(fid,begdata,'bof'); end; % if (h.nextfile)>0 end % try/catch end; % if strcmpi ... enddata = h.eventtablepos; % after data if strcmpi(r.dataformat, 'int16') nums = floor((enddata-begdata)/h.nchannels/2); % floor due to bug 1254 else nums = floor((enddata-begdata)/h.nchannels/4); end; % number of sample to read % ------------------------ if ~isempty(r.sample1) r.t1 = r.sample1/h.rate; else r.sample1 = r.t1*h.rate; end; if strcmpi(r.dataformat, 'int16') startpos = r.t1*h.rate*2*h.nchannels; else startpos = r.t1*h.rate*4*h.nchannels; end; if isempty(r.ldnsamples) if ~isempty(r.lddur) r.ldnsamples = round(r.lddur*h.rate); else r.ldnsamples = nums; end; end; %% CWB SAMPLE NUMBER CHECK % Verifies that the number of samples we'll load later does not exceed % the total number of available data samples. CWB ran across this error % when he accidentally entered a total sample number larger than the % total number of available data points. % % This throws a shoe with 16-bit data. if r.ldnsamples-r.sample1 > h.numsamples-r.sample1 && strcmpi(r.dataformat, 'int32') tldnsamples=r.ldnsamples; r.ldnsamples=h.numsamples-r.sample1; warning('loadcnt:SampleError', ['User requested ' num2str(tldnsamples) ' loaded beginning at sample ' num2str(r.sample1) '.\n' ... 'Too few samples in data (' num2str(h.numsamples-r.sample1) '). Loaded samples adjusted to ' num2str(r.ldnsamples) '.']); clear tldnsamples; end % r.ldnsamples-r.sample1 ... % channel offset % -------------- if ~isempty(r.blockread) h.channeloffset = r.blockread; end; if h.channeloffset > 1 fprintf('WARNING: reading data in blocks of %d, if this fails, try using option "''blockread'', 1"\n', ... h.channeloffset); end; % disp('Reading data .....') if type == 'cnt' % while (ftell(fid) +1 < h.eventtablepos) %d(:,i)=fread(fid,h.nchannels,'int16'); %end fseek(fid, startpos, 0); % **** This marks the beginning of the code modified for reading % large .cnt files % Switched to r.memmapfile for continuity. Check to see if the % variable exists. If it does, then the user has indicated the % file is too large to be processed in memory. If the variable % is blank, the file is processed in memory. if (~isempty(r.memmapfile)) % open a file for writing foutid = fopen(r.memmapfile, 'w') ; % This portion of the routine reads in a section of the EEG file % and then writes it out to the harddisk. samples_left = h.nchannels * r.ldnsamples ; % the size of the data block to be read is limited to 4M % samples. This equates to 16MB and 32MB of memory for % 16 and 32 bit files, respectively. data_block = 4000000 ; % max_rows = data_block / h.nchannels ; max_rows=floor(data_block / h.nchannels ); % bug 1539 %warning off ; max_written = h.nchannels * uint32(max_rows) ; %warning on ; % This while look tracks the remaining samples. The % data is processed in chunks rather than put into % memory whole. while (samples_left > 0) % Check to see if the remaining data is smaller than % the general processing block by looking at the % remaining number of rows. to_read = max_rows ; if (data_block > samples_left) to_read = samples_left / h.nchannels ; end ; % Read data in a relatively small chunk temp_dat = fread(fid, [h.nchannels to_read], r.dataformat) ; % The data is then scaled using the original routine. % In the original routine, the entire data set was scaled % after being read in. For this version, scaling occurs % after every chunk is read. if strcmpi(r.scale, 'on') disp('Scaling data .....') %%% scaling to microvolts for i=1:h.nchannels bas=e(i).baseline;sen=e(i).senstivity;cal=e(i).calib; mf=sen*(cal/204.8); temp_dat(i,:)=(temp_dat(i,:)-bas).*mf; end end % Write out data in float32 form to the file name % supplied by the user. written = fwrite (foutid, temp_dat, 'float32') ; if (written ~= max_written) samples_left = 0 ; else samples_left = samples_left - written ; end ; end ; fclose (foutid) ; % Set the dat variable. This gets used later by other % EEGLAB functions. dat = r.memmapfile ; % This variable tracks how the data should be read. bReadIntoMemory = false ; else % The memmapfile variable is empty, read into memory. bReadIntoMemory = true ; end % This ends the modifications made to read large files. % Everything contained within the following if statement is the % original code. if (bReadIntoMemory == true) if h.channeloffset <= 1 %% CWB: % EEGLAB first loads the whole file and then truncates % based on a few criteria. However, this does not work % well with large datasets that simply CANNOT be loaded % into memory. Modifying this section to just load in the % appropriate section of data. dat=fread(fid, [h.nchannels r.ldnsamples], r.dataformat); %% CONVERT TO PROPER DATA PRECISION % Change to single precision if necessary. Or double if % the data type is not already a double. if strcmpi(r.precision, 'single') dat=single(dat); elseif strcmpi(r.precision, 'double') && ~isa(dat, 'double') dat=double(dat); end % if strcmpi % original code % CWB commented this out. % dat=fread(fid, [h.nchannels Inf], r.dataformat); % if size(dat,2) < r.ldnsamples % dat=single(dat); % r.ldnsamples = size(dat,2); % else % dat=single(dat(:,1:r.ldnsamples)); % end; else warning('CWB has not tested this section of code, so use with caution'); h.channeloffset = h.channeloffset/2; % reading data in blocks dat = zeros( h.nchannels, r.ldnsamples, 'single'); dat(:, 1:h.channeloffset) = fread(fid, [h.channeloffset h.nchannels], r.dataformat)'; counter = 1; while counter*h.channeloffset < r.ldnsamples dat(:, counter*h.channeloffset+1:counter*h.channeloffset+h.channeloffset) = ... fread(fid, [h.channeloffset h.nchannels], r.dataformat)'; counter = counter + 1; end; end ; % ftell(fid) if strcmpi(r.scale, 'on') % disp('Scaling data .....') %%% scaling to microvolts for i=1:h.nchannels bas=e(i).baseline;sen=e(i).senstivity;cal=e(i).calib; mf=sen*(cal/204.8); dat(i,:)=(dat(i,:)-bas).*mf; end % end for i=1:h.nchannels end; % end if (strcmpi(r.scale, 'on') end ; ET_offset = (double(h.prevfile) * (2^32)) + double(h.eventtablepos); % prevfile contains high order bits of event table offset, eventtablepos contains the low order bits fseek(fid, ET_offset, 'bof'); % disp('Reading Event Table...') eT.teeg = fread(fid,1,'uchar'); eT.size = fread(fid,1,'ulong'); eT.offset = fread(fid,1,'ulong'); if eT.teeg==2 nevents=eT.size/sizeEvent2; if nevents > 0 ev2(nevents).stimtype = []; for i=1:nevents ev2(i).stimtype = fread(fid,1,'ushort'); ev2(i).keyboard = fread(fid,1,'char'); temp = fread(fid,1,'uint8'); ev2(i).keypad_accept = bitand(15,temp); ev2(i).accept_ev1 = bitshift(temp,-4); ev2(i).offset = fread(fid,1,'long'); ev2(i).type = fread(fid,1,'short'); ev2(i).code = fread(fid,1,'short'); ev2(i).latency = fread(fid,1,'float'); ev2(i).epochevent = fread(fid,1,'char'); ev2(i).accept = fread(fid,1,'char'); ev2(i).accuracy = fread(fid,1,'char'); end else ev2 = []; end; elseif eT.teeg==3 % type 3 is similar to type 2 except the offset field encodes the global sample frame nevents=eT.size/sizeEvent3; if nevents > 0 ev2(nevents).stimtype = []; if r.dataformat == 'int32' bytes_per_samp = 4; % I only have 32 bit data, unable to check whether this is necessary, else % perhaps there is no type 3 file with 16 bit data bytes_per_samp = 2; end for i=1:nevents ev2(i).stimtype = fread(fid,1,'ushort'); ev2(i).keyboard = fread(fid,1,'char'); temp = fread(fid,1,'uint8'); ev2(i).keypad_accept = bitand(15,temp); ev2(i).accept_ev1 = bitshift(temp,-4); os = fread(fid,1,'ulong'); ev2(i).offset = os * bytes_per_samp * h.nchannels; ev2(i).type = fread(fid,1,'short'); ev2(i).code = fread(fid,1,'short'); ev2(i).latency = fread(fid,1,'float'); ev2(i).epochevent = fread(fid,1,'char'); ev2(i).accept = fread(fid,1,'char'); ev2(i).accuracy = fread(fid,1,'char'); end else ev2 = []; end; elseif eT.teeg==1 nevents=eT.size/sizeEvent1; if nevents > 0 ev2(nevents).stimtype = []; for i=1:nevents ev2(i).stimtype = fread(fid,1,'ushort'); ev2(i).keyboard = fread(fid,1,'char'); % modified by Andreas Widmann 2005/05/12 14:15:00 %ev2(i).keypad_accept = fread(fid,1,'char'); temp = fread(fid,1,'uint8'); ev2(i).keypad_accept = bitand(15,temp); ev2(i).accept_ev1 = bitshift(temp,-4); % end modification ev2(i).offset = fread(fid,1,'long'); end; else ev2 = []; end; else disp('Skipping event table (tag != 1,2,3 ; theoritically impossible)'); ev2 = []; end %% AT h.nextfile here. % There's additional information at the end of this that needs to be % written to file using writecnt in order to figure out what the % precision is (32 or 16 bit) when reading in the file again. % % With modified auto precision detection above, this is no longer % necessary. % f.junk=fread(fid); % f.junk=f.junk(1:end-1); % exclude the tag %% SAVE DATAFORMAT % Potentially useful when writing data later, otherwise things have to be % hardcoded. f.dataformat=r.dataformat; %% GET ENDTAG fseek(fid, -1, 'eof'); t = fread(fid,'char'); f.header = h; f.electloc = e; f.data = dat; f.Teeg = eT; f.event = ev2; f.tag=t; % Surgical addition of number of samples f.ldnsamples = r.ldnsamples ; %%%% channels labels for i=1:h.nchannels plab=sprintf('%c',f.electloc(i).lab); if i>1 lab=str2mat(lab,plab); else lab=plab; end end %%%% to change offest in bytes to points if ~isempty(ev2) if r.sample1 ~= 0 warning('Events imported with a time shift might be innacurate'); % fprintf(2,'Warning: events imported with a time shift might be innacurate\n'); end; ev2p=ev2; ioff=900+(h.nchannels*75); %% initial offset : header + electordes desc if strcmpi(r.dataformat, 'int16') for i=1:nevents ev2p(i).offset=(ev2p(i).offset-ioff)/(2*h.nchannels) - r.sample1; %% 2 short int end end else % 32 bits for i=1:nevents ev2p(i).offset=(ev2p(i).offset-ioff)/(4*h.nchannels) - r.sample1; %% 4 short int end end end; f.event = ev2p; end; frewind(fid); fclose(fid); end
github
ZijingMao/baselineeegtest-master
icaact.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/icaact.m
2,583
utf_8
e90b9a3cfaabf4e09cf26a0a692344e4
% icaact() - compute ICA activation waveforms = weights*sphere*(data-meandata) % % Usage: >> [activations] = icaact(data,weights,datamean); % % Inputs: % data = input data (chans,frames) % weights = unmixing matrix (runica() weights*sphere) % datamean = 0 or mean(data') (default 0); % % Note: If datamean==0, data means are distributed over activations. % Use this form for plotting component projections. % % Output: % activations = ICA component activation waveforms % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 4-3-97 % % See also: runica(), icaproj(), icavar() % Copyright (C) 4-3-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 % 6-17-97 extended to non-square weight matrices -sm % 1-12-01 removed sphere argument -sm % 01-25-02 reformated help & license, added links -ad function [activations] = icaact(data,weights,datamean) if nargin < 4 datamean = 0; elseif nargin < 3 help icaact return end [chans, framestot] = size(data); if datamean == 0, datamean = zeros(chans,1); % single-epoch 0s end if size(datamean,1) == 1 % if row vector datamean = datamean'; % make a column vector end [meanchans,epochs] = size(datamean); if epochs < 1, fprintf('icaact(): datamean empty.\n'); return end frames = fix(framestot/epochs); if frames < 1, fprintf('icaact(): data empty.\n'); return end if frames*epochs ~= framestot fprintf(... 'icaact(): datamean epochs %d does not divide data length %d.\n',... epochs, framestot); return end if size(datamean,1) ~= chans fprintf('icaact(): datamean channels ~= data channels.\n'); return end w = weights; activations = zeros(size(w,1),size(data,2)); for e=1:epochs activations(:,(e-1)*frames+1:e*frames) = ... w*(data(:,(e-1)*frames+1:e*frames) - datamean(:,e)*ones(1,frames)); end
github
ZijingMao/baselineeegtest-master
gettempfolder.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/gettempfolder.m
1,470
utf_8
71281778d892c5545193292a61509dd9
% gettempfolder() - return the temporary folder % % Usage: >> folder = gettempfolder; % % Output: a string containing the folder if a temporary folder can be found. % Empty if the folder cannot be found. % % Author: Arnaud Delorme, SCCN, UCSD, 2012 % % 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 tmp_fld = gettempfolder(errorflag); if nargin < 1 errorflag = 0; end; tmp_fld = getenv('TEMP'); if isempty(tmp_fld) && isunix if is_sccn && exist('/var/tmp') tmp_fld = '/var/tmp'; elseif exist('/tmp') == 7 tmp_fld = '/tmp'; else try mkdir('/tmp'); tmp_fld = '/tmp'; catch, end; end; end; if isempty(tmp_fld) && errorflag error('Cannot find a temporary folder to store data files'); end;
github
ZijingMao/baselineeegtest-master
loadtxt.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/loadtxt.m
6,712
utf_8
6bb912af759266869498c019520fc4c9
% loadtxt() - load ascii text file into numeric or cell arrays % % Usage: % >> array = loadtxt( filename, 'key', 'val' ...); % % Inputs: % filename - name of the input file % % Optional inputs % 'skipline' - number of lines to skip {default:0}. If this number is % negative the program will only skip non-empty lines % (can be usefull for files transmitted from one platform % to an other, as CR may be inserted at every lines). % 'convert' - 'on' standard text conversion, see note 1 % 'off' no conversion, considers text only % 'force' force conversion, NaN are returned % for non-numeric inputs {default:'on'} % 'delim' - ascii character for delimiters. {default:[9 32] % i.e space and tab}. It is also possible to enter % strings, Ex: [9 ' ' ',']. % 'blankcell' - ['on'|'off'] extract blank cells {default:'on'} % 'verbose' - ['on'|'off'] {default:'on'} % 'convertmethod' - ['str2double'|'str2num'] default is 'str2double' % 'nlines' - [integer] number of lines to read {default: all file} % % Outputs: % array - cell array. If the option 'force' is given, the function % retrun a numeric array. % % Notes: 1) Since it uses cell arrays, the function can handle text input. % The function reads each token and then try to convert it to a % number. If the conversion is unsucessfull, the string itself % is included in the array. % 2) The function adds empty entries for rows that contains % fewer columns than others. % % Author: Arnaud Delorme, CNL / Salk Institute, 29 March 2002 % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 29 March 2002 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function array = loadtxt( filename, varargin ); if nargin < 1 help loadtxt; return; end; if ~isempty(varargin) try, g = struct(varargin{:}); catch, disp('Wrong syntax in function arguments'); return; end; else g = []; end; g = finputcheck( varargin, { 'convert' 'string' { 'on';'off';'force' } 'on'; 'skipline' 'integer' [0 Inf] 0; 'verbose' 'string' { 'on';'off' } 'on'; 'uniformdelim' 'string' { 'on';'off' } 'off'; 'blankcell' 'string' { 'on';'off' } 'on'; 'convertmethod' 'string' { 'str2double';'str2num' } 'str2double'; 'delim' { 'integer';'string' } [] [9 32]; 'nlines' 'integer' [] Inf }); if isstr(g), error(g); end; if strcmpi(g.blankcell, 'off'), g.uniformdelim = 'on'; end; g.convert = lower(g.convert); g.verbose = lower(g.verbose); g.delim = char(g.delim); % open the file % ------------- if exist(filename) ~=2, error( ['file ' filename ' not found'] ); end; fid=fopen(filename,'r','ieee-le'); if fid<0, error( ['file ' filename ' found but error while opening file'] ); end; index = 0; while index < abs(g.skipline) tmpline = fgetl(fid); if g.skipline > 0 | ~isempty(tmpline) index = index + 1; end; end; % skip lines --------- inputline = fgetl(fid); linenb = 1; if strcmp(g.verbose, 'on'), fprintf('Reading file (lines): '); end; while isempty(inputline) | inputline~=-1 colnb = 1; if ~isempty(inputline) tabFirstpos = 1; % convert all delimiter to the first one if strcmpi(g.uniformdelim, 'on') for index = 2:length(g.delim) inputline(find(inputline == g.delim(index))) = g.delim(1); end; end; while ~isempty(deblank(inputline)) if strcmpi(g.blankcell,'off'), inputline = strtrim(inputline); end; if tabFirstpos && length(inputline) > 1 && all(inputline(1) ~= g.delim), tabFirstpos = 0; end; [tmp inputline tabFirstpos] = mystrtok(inputline, g.delim, tabFirstpos); switch g.convert case 'off', array{linenb, colnb} = tmp; case 'on', if strcmpi(g.convertmethod, 'str2double') tmp2 = str2double(tmp); if isnan( tmp2 ) , array{linenb, colnb} = tmp; else array{linenb, colnb} = tmp2; end; else tmp2 = str2num(tmp); if isempty( tmp2 ) , array{linenb, colnb} = tmp; else array{linenb, colnb} = tmp2; end; end; case 'force', array{linenb, colnb} = str2double(tmp); end; colnb = colnb+1; end; linenb = linenb +1; end; inputline = fgetl(fid); if linenb > g.nlines inputline = -1; end; if ~mod(linenb,10) & strcmp(g.verbose, 'on'), fprintf('%d ', linenb); end; end; if strcmp(g.verbose, 'on'), fprintf('%d\n', linenb-1); end; if strcmp(g.convert, 'force'), array = [ array{:} ]; end; fclose(fid); % problem strtok do not consider tabulation % ----------------------------------------- function [str, strout, tabFirstpos] = mystrtok(strin, delim, tabFirstpos); % remove extra spaces at the beginning while any(strin(1) == delim) && strin(1) ~= 9 && strin(1) ~= ',' strin = strin(2:end); end; % for tab and coma, consider empty cells if length(strin) > 1 && any(strin(1) == delim) if tabFirstpos || any(strin(2) == delim) str = ''; strout = strin(2:end); if strin(2) ~= 9 && strin(2) ~= ',' tabFirstpos = 0; strout = strtrim(strout); end; else [str, strout] = strtok(strin, delim); end; else [str, strout] = strtok(strin, delim); end;
github
ZijingMao/baselineeegtest-master
plotmesh.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/plotmesh.m
3,071
utf_8
410ee4c8c435cc7b221f29efa3696d21
% plotmesh() - plot mesh defined by faces and vertex % % Usage: % plotmesh(faces, vertex); % % Input: % faces - array of N x 3. Each row defines a triangle. The 3 points % in each row are row indices in the matrix below. % vertex - array of M x 3 points, (x = first colum; y=second colum % z=3rd column). Each row defines a point in 3-D. % % Optional input: % normal - normal orientation for each face (for better lighting) % % Author: Arnaud Delorme, SCCN/INC/UCSD, 2003 % Copyright (C) May 6, 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 p1 = plotmesh(faces, vertex, normal, newfig) if nargin < 2 help plotmesh; return; end; FaceColor = [.8 .55 .35]*1.1; % ~= ruddy Caucasian - pick your complexion! if any(any(faces == 0)), faces = faces+1; end; %vertex(:,3) = -vertex(:,3); %FCmap = [jet(64); FaceColor; FaceColor; FaceColor]; %colormap(FCmap) %W = ones(1,size(vertex,1))*(size(FCmap,1)-1); %W = ones(1,size(vertex,1))' * FaceColor; %size(W) if nargin < 4 newfig = figure; end; if nargin < 3 normal = []; end; if isempty(normal) p1 = patch('vertices', vertex, 'faces', faces, ... 'facecolor', [1,.75,.65]); else p1 = patch('vertices', vertex, 'faces', faces, ... 'facecolor', [1,.75,.65], 'vertexnormals', normal); end; % 'FaceVertexCdata',W(:), 'FaceColor','interp', 'vertexnormals', normal); set(p1,'EdgeColor','none') % Lights %Lights = [-125 125 80; ... % 125 125 80; ... % 125 -125 125; ... % -125 -125 125]; % default lights at four corners %for i = 1:size(Lights,1) % hl(i) = light('Position',Lights(i,:),'Color',[1 1 1],... % 'Style','infinite'); %end %camlight left; % lightangle(45,30); % lightangle(45+180,30); %set(gcf, 'renderer', 'zbuffer'); % cannot use alpha then %set(hcap, 'ambientstrength', .6); set(p1, 'specularcolorreflectance', 0, 'specularexponent',50); set(p1,'DiffuseStrength',.6,'SpecularStrength',0,... 'AmbientStrength',.4,'SpecularExponent',5); axis equal view(18,8); rotate3d axis off; lighting phong;
github
ZijingMao/baselineeegtest-master
mri3dplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/mri3dplot.m
18,772
utf_8
710c890eda7ee5b1b19e7efefa357f7c
% mri3dplot() - plot 3-D density image translucently on top of the mean MR % brain image used in dipplot(). Plot brain slices in directions % 'top' (axial), or 'side' (sagittal), or 'rear' (coronal). % Creates a new figure(). Smoothing uses Matlab smooth3() % Usage: % >> [smoothed_3ddens, mriplanes] = mri3dplot(array3d, mri, 'key', 'val', ...); % % Input: % array3d - 3-D array to plot translucently on top of MRI image planes % (e.g., as returned by dipoledensity(), unit: dipoles/cc). % mri - [string or struct] base MR image structure (as returned by % dipoledensity.m or mri file (matlab format or file format read % by fcdc_read_mri. See dipplot.m help for more information. % % Optional inputs: % 'mriview' - ['top'|'side'|rear'] MR image slices to plot. 'axial', % 'coronal', and 'saggital' are also recognized keywords % {default|[]: 'top'|'axial'}. May also be a cell array % of such keyword (one per slice). % 'mrislices' - [real vector] MR slice plotting coordinates in 'mriview' % direction {default|[]: -50 to +50 in steps of 11 mm} % 'kernel' - 3-D smoothing ht, width, & depth in voxels {default|0: none} % > 0 -> uses gaussian kernel of std. dev. 0.65 voxels) % 'geom' - [rows, cols] geometry of slice array in figure output % {default: smallest enclosing near-square array} % 'rotate' - [0|90|180|270 deg] 2-D slice image rotation {default: 90} % 'cmap' - [float array] colormap for plotting the 3-D array % {default: 'hot'} % 'cmax' - [float] color palette max value {default: array3d max} % 'cmin' - [float] color palette min value {default: 0} % 'cbar' - ['on'|'off'] plot colorbar. Default is 'on'. % 'subplot' - ['on'|'off'] for single slice only, plot within a sub-plot % panel. If 'on', this automatically sets 'cbar' to 'off'. % Default is 'off'. % 'plotintersect' - ['on'|'off'] plot intersection between plotted slices. % Default is 'on'. % 'mixfact' - [float] factor for mixing the background image with the % array3d information. Default is 0.5. % 'mixmode' - ['add'|'overwrite'] 'add' will allow for trasnparency % while 'overwrite' will preserve the orginal MRI image % and overwrite the pixel showind density changes. % % Outputs: % smoothed_3ddens - the plotted (optionally smoothed) 3-D density matrix % mriplanes - cell array of the plotted MR image slices % % Author: Arnaud Delorme & Scott Makeig, SCCN, 10 June 2003 % % Example: % dipfitdefs; % load('-mat', template_models(1).mrifile); % load mri variable % array = gauss3d(91,109,91); % mri3dplot(array, mri); % % See also: plotmri() % Copyright (C) Arnaud Delorme, sccn, INC, UCSD, 2003- % 03/29/2013 Makoto. Line 370 added to avoid negative matrix indices. % % 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 [smoothprob3d, mriplanes] = mri3dplot(prob3d, mri, varargin) % REDUCEPATCH Reduce number of patch faces. if nargin < 1 help mri3dplot; return; end; DEFAULT_SPACING = 11; % default MR slice interval (in mm) translucency = 0.5; % default alpha value mri_lim = 85; % +/- axis limits of MNI head image g = finputcheck( varargin, { 'mriview' { 'string','cell' } { { 'sagital','axial','coronal','top','side','rear' } {} } 'top'; 'mixmode' 'string' { 'add','overwrite','min' } 'add'; 'mrislices' 'float' [] []; 'view' 'float' [] []; 'geom' 'float' [] []; 'cmap' 'float' [] jet(64); 'cmax' 'float' [] []; 'mixfact' 'float' [] 0.5; 'cmin' 'float' [] 0; 'plotintersect' 'string' { 'on','off' } 'on'; 'cbar' 'string' { 'on','off' } 'on'; 'subplot' 'string' { 'on','off' } 'off'; 'rotate' 'integer' { 0,90,180,270 } 90; 'kernel' 'float' [] 0; 'addrow' 'integer' [] 0; 'fighandle' 'integer' [] []}); if isstr(g), error(g); end; if isstr(g.mriview) == 1, g.plotintersect = 'off'; end; if strcmpi(g.mriview,'sagittal'), g.mriview = 'side'; elseif strcmpi(g.mriview,'axial'), g.mriview = 'top'; elseif strcmpi(g.mriview,'coronal'), g.mriview = 'rear'; end; if strcmpi(g.subplot, 'on') % plot colorbar g.cbar = 'off'; end; if isstr(mri) try, mri = load('-mat', mri); mri = mri.mri; catch, disp('Failed to read Matlab file. Attempt to read MRI file using function read_fcdc_mri'); try, warning off; mri = read_fcdc_mri(mri); mri.anatomy = round(gammacorrection( mri.anatomy, 0.8)); mri.anatomy = uint8(round(mri.anatomy/max(reshape(mri.anatomy, prod(mri.dim),1))*255)); % WARNING: if using double instead of int8, the scaling is different % [-128 to 128 and 0 is not good] % WARNING: the transform matrix is not 1, 1, 1 on the diagonal, some slices may be % misplaced warning on; catch, error('Cannot load file using read_fcdc_mri'); end; end; end; % normalize prob3d for 1 to ncolors and create 3-D dim % ---------------------------------------------------- if ~iscell(prob3d), prob3d = { prob3d }; end; if length(prob3d) > 1 if isempty(g.cmax), g.cmax = max(max(prob3d{1}(:)),max(prob3d{2}(:))); end; [newprob3d{1}] = prepare_dens(prob3d{1}, g, 'abscolor'); [newprob3d{2}] = prepare_dens(prob3d{2}, g, 'abscolor'); else if isempty(g.cmax), g.cmax = max(prob3d{1}(:)); end; [newprob3d{1} maxdens1] = prepare_dens(prob3d{1}, g, 'usecmap'); end; fprintf('Brightest color denotes a density of: %1.6f (presumed unit: dipoles/cc)\n', g.cmax); % plot MRI slices % --------------- if isempty(g.mrislices), g.mrislices = linspace(-50, 50, DEFAULT_SPACING); end; if strcmpi(g.cbar, 'on'), add1 = 1; else add1 = 0; end; if isempty(g.geom), g.geom = ceil(sqrt(length(g.mrislices)+add1)); g.geom(2) = ceil((length(g.mrislices)+add1)/g.geom)+g.addrow; end; if strcmpi(g.subplot, 'off') if isempty(g.fighandle) fig = figure; else fig = g.fighandle; clf(fig); end pos = get(fig, 'position'); set(fig, 'position', [ pos(1)+15 pos(2)+15 pos(3)/4*g.geom(1) pos(4)/3*g.geom(2) ]); end; disp('Plotting...'); % custom view for each slice if ~iscell( g.mriview ) g.mriview = { g.mriview }; g.mriview(2:length( g.mrislices )) = g.mriview(1); end; newprob3dori = newprob3d; for index = 1:length( g.mrislices ) %%%%%%% for each plotted MR image slice %%%%%%%% % plot intersection between plotted slices % ---------------------------------------- newprob3d = newprob3dori; if strcmpi(g.plotintersect, 'on') for index2 = setdiff_bc(1:length( g.mrislices ), index) switch g.mriview{index2} case 'side', coord = [ g.mrislices(index2) 0 0 1 ]; case 'top' , coord = [ 0 0 g.mrislices(index2) 1 ]; case 'rear', coord = [ 0 g.mrislices(index2) 0 1 ]; end; coord = round( pinv(mri.transform)*coord' )'; for i = 1:length(newprob3d) switch g.mriview{index2} case 'side', newprob3d{i}( coord(1), :, :, :) = 0; case 'top' , newprob3d{i}( :, :, coord(3), :) = 0; case 'rear', newprob3d{i}( :, coord(2), :, :) = 0; end; end; end; end; % create axis if necessary % ------------------------ if strcmpi(g.subplot, 'off') mysubplot(g.geom(1), g.geom(2), index); % get an image slice axis end; % find coordinate % --------------- switch g.mriview{index} case 'side', coord = [ g.mrislices(index) 0 0 1 ]; case 'top' , coord = [ 0 0 g.mrislices(index) 1 ]; case 'rear', coord = [ 0 g.mrislices(index) 0 1 ]; end; coord = round( pinv(mri.transform)*coord' )'; % get MRI slice % ------------- switch g.mriview{index} case 'side', mriplot = squeeze( mri.anatomy(coord(1), :, :) ); case 'top' , mriplot = squeeze( mri.anatomy(:, :, coord(3)) ); case 'rear', mriplot = squeeze( mri.anatomy(:, coord(2), :) ); end; mriplot(:,:,2) = mriplot(:,:,1); mriplot(:,:,3) = mriplot(:,:,1); mriplot = rotatemat( mriplot, g.rotate ); % get dipole density slice % ------------------------ for i = 1:length(newprob3d) switch g.mriview{index} case 'side', densplot{i} = squeeze( newprob3d{i}(coord(1), :, :, :) ); case 'top' , densplot{i} = squeeze( newprob3d{i}(:, :, coord(3), :) ); case 'rear', densplot{i} = squeeze( newprob3d{i}(:, coord(2), :, :) ); end; densplot{i} = rotatemat( densplot{i}, g.rotate ); end; if isa(mriplot, 'uint8') % check if densplot is in uint8 % if not - transform to uint8 for dlen = 1:length(densplot) if ~isa(densplot{dlen}, 'uint8') % check if multiply by 255 (when double % with values ranging from 0 - 1) and % then transform to uint8 checkval = densplot{dlen} >= 0 & densplot{dlen} <= 1; checkval = sum(checkval(:)) == numel(densplot{dlen}); if checkval densplot{dlen} = uint8(densplot{dlen} * 255); %#ok<AGROW> continue end % check if it's ok to transform % straight to int8 checkval = densplot{dlen} >= 0 & densplot{dlen} <= 255; checkval = sum(checkval(:)) == numel(densplot); testint = isequal(densplot{dlen}, round(densplot{dlen})); if checkval && testint densplot{dlen} = uint8(densplot{dlen}); %#ok<AGROW> end end end clear dlen checkval testint end; if length(densplot) == 1 densplot = densplot{1}; if strcmpi(g.mixmode, 'add') densplot(isnan(densplot)) = 0; % do not plot colors outside the brain, as indicated by NaNs mriplot = mriplot*g.mixfact + densplot*(1-g.mixfact); % Mix 1/2 MR image + 1/2 density image elseif strcmpi(g.mixmode, 'overwrite') indsnon0 = sum(densplot(:,:,:),3) > 0; tmpmri = mriplot(:,:,1); tmpdens = densplot(:,:,1); tmpmri(indsnon0) = tmpdens(indsnon0); mriplot(:,:,1) = tmpmri; tmpmri = mriplot(:,:,2); tmpdens = densplot(:,:,2); tmpmri(indsnon0) = tmpdens(indsnon0); mriplot(:,:,2) = tmpmri; tmpmri = mriplot(:,:,3); tmpdens = densplot(:,:,3); tmpmri(indsnon0) = tmpdens(indsnon0); mriplot(:,:,3) = tmpmri; elseif strcmpi(g.mixmode, 'min') densplot(isnan(densplot)) = 0; % do not plot colors outside the brain, as indicated by NaNs mriplot = min(mriplot, densplot); % min end; clear densplot; else densplot{1}(isnan(densplot{1})) = 0; % do not plot colors outside the brain, as indicated by NaNs densplot{2}(isnan(densplot{2})) = 0; % do not plot colors outside the brain, as indicated by NaNs if strcmpi(g.mixmode, 'add') mriplot(:,:,1) = mriplot(:,:,1)*g.mixfact + densplot{1}(:,:)*(1-g.mixfact); % min mriplot(:,:,3) = mriplot(:,:,3)*g.mixfact + densplot{2}(:,:)*(1-g.mixfact); % min mriplot(:,:,2) = mriplot(:,:,2)*g.mixfact; % min elseif strcmpi(g.mixmode, 'overwrite') indsnon01 = densplot{1}(:,:,:) > 0; indsnon02 = densplot{2}(:,:,:) > 0; tmpmri = mriplot(:,:,1); tmpdens = densplot{1}(:,:); tmpmri(indsnon01) = tmpdens(indsnon01); mriplot(:,:,1) = tmpmri; tmpmri = mriplot(:,:,2); tmpdens = densplot{2}(:,:); tmpmri(indsnon02) = tmpdens(indsnon02); mriplot(:,:,2) = tmpmri; else mriplot(:,:,1) = max(mriplot(:,:,1), densplot{1}); % min mriplot(:,:,2) = max(mriplot(:,:,2), densplot{2}); % min end; end; mriplanes{index} = mriplot; imagesc(mriplot); % plot [background MR image + density image] axis off; hold on; xl = xlim; yl = ylim; zl = zlim; % options = { 'FaceColor','texturemap', 'EdgeColor','none', 'CDataMapping', ... % 'scaled','facelighting', 'none', 'facealpha', translucency}; % h = surface( [xl(1) xl(2); xl(1) xl(2)], [yl(1) yl(1); yl(2) yl(2)], ... % [1 1; 1 1], densplot, options{:}); axis equal; if ~isempty(g.view), view(g.view); end; tit = title( [ int2str(g.mrislices(index)) ' mm' ]); if strcmpi(g.subplot, 'off'), set(tit, 'color', 'w'); end; end; % plot colorbar % ------------- if strcmpi(g.cbar, 'on') % plot colorbar h = mysubplot(g.geom(1), g.geom(2), length(g.mrislices)+1); pos = get(h, 'position'); pos(1) = pos(1)+pos(3)/3; pos(3) = pos(3)/6; pos(2) = pos(2)+pos(4)/5; pos(4) = pos(4)*3/5; axis off; h = axes('unit', 'normalized', 'position', pos); % position the colorbar if strcmpi(g.mixmode, 'add') tmpmap = g.cmap/2 + ones(size(g.cmap))/4; % restrict range to [1/4, 3/4] of cmap else tmpmap = g.cmap; %g.cmap/2 + ones(size(g.cmap))/4; % restrict range to [1/4, 3/4] of cmap end; colormap(tmpmap); cbar(h, [1:length(g.cmap)], [g.cmin g.cmax]); box off; set(h, 'ycolor', [0.7 0.7 0.7]); end; fprintf('\n'); if exist('fig') == 1 if length(prob3d) == 1 set(fig,'color', g.cmap(1,:)/2); else set(fig,'color', [0.0471 0.0471 0.0471]/1.3); end; end; return; function mat = rotatemat(mat, angle); if angle == 0, return; end; if ndims(mat) == 2 if angle >= 90, mat = rot90(mat); end; if angle >= 180, mat = rot90(mat); end; if angle >= 270, mat = rot90(mat); end; else if angle >= 90, newmat(:,:,1) = rot90(mat(:,:,1)); newmat(:,:,2) = rot90(mat(:,:,2)); newmat(:,:,3) = rot90(mat(:,:,3)); mat = newmat; end; if angle >= 180, newmat(:,:,1) = rot90(mat(:,:,1)); newmat(:,:,2) = rot90(mat(:,:,2)); newmat(:,:,3) = rot90(mat(:,:,3)); mat = newmat; end; if angle >= 270, newmat(:,:,1) = rot90(mat(:,:,1)); newmat(:,:,2) = rot90(mat(:,:,2)); newmat(:,:,3) = rot90(mat(:,:,3)); mat = newmat; end; end; function [newprob3d maxdens] = prepare_dens(prob3d, g, col); if g.kernel ~= 0 disp('Smoothing...'); smoothprob3d = smooth3(prob3d, 'gaussian', g.kernel); prob3d = smoothprob3d; end; maxdens = max(prob3d(:)); ncolors = size(g.cmap,1); prob3d = round((prob3d-g.cmin)/(g.cmax - g.cmin)*(ncolors-1))+1; % project desnity image into the color space: [1:ncolors] prob3d( find(prob3d > ncolors) ) = ncolors; prob3d( find(prob3d < 1)) = 1; % added by Makoto newprob3d = zeros(size(prob3d,1), size(prob3d,2), size(prob3d,3), 3); outOfBrainMask = find(isnan(prob3d)); % place NaNs in a mask, NaNs are assumed for points outside the brain prob3d(outOfBrainMask) = 1; if strcmpi(col, 'abscolor') newprob3d = prob3d/ncolors; else tmp = g.cmap(prob3d,1); newprob3d(:,:,:,1) = reshape(tmp, size(prob3d)); tmp = g.cmap(prob3d,2); newprob3d(:,:,:,2) = reshape(tmp, size(prob3d)); tmp = g.cmap(prob3d,3); newprob3d(:,:,:,3) = reshape(tmp, size(prob3d)); end; function h = mysubplot(geom1, geom2, coord); coord = coord-1; horiz_border = 0; vert_border = 0.1; coordy = floor(coord/geom1); coordx = coord - coordy*geom1; posx = coordx/geom1+horiz_border*1/geom1/2; posy = 1-(coordy/geom2+vert_border*1/geom2/2)-1/geom2; width = 1/geom1*(1-horiz_border); height = 1/geom2*(1- vert_border); h = axes('unit', 'normalized', 'position', [ posx posy width height ]); %h = axes('unit', 'normalized', 'position', [ coordx/geom1 1-coordy/geom2-1/geom2 1/geom1 1/geom2 ]);
github
ZijingMao/baselineeegtest-master
spherror.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/spherror.m
1,249
utf_8
c912e32a9b9351420468261b94d5b5e8
% spherror() - chancenter() sub function to compute minimum distance % of Cartesian coordinates to a sphere % % Author: Scott Makeig, CNL / Salk Institute, 2000 % Copyright (C) Scott Makeig, CNL / Salk Institute, 2000 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function wobble = spherror(center,x,y,z) % 03/14/02 corrected wobble calculation -lf x = x - center(1); % center the points at (0,0,0) y = y - center(2); z = z - center(3); radius = (sqrt(x.^2+y.^2+z.^2)); % distances from the center wobble = std(radius-mean(radius)); % test if xyz values are on a sphere
github
ZijingMao/baselineeegtest-master
envtopo.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/envtopo.m
46,366
utf_8
5673dd4fa49e7a6a1570b73be3106e45
% % envtopo() - Plot the envelope of a multichannel data epoch, plus envelopes and % scalp maps of specified or largest-contributing components. If a 3-D % input matrix, operates on the mean of the data epochs. Click on % individual axes to examine them in detail. The black lines represent % the max and min values across all channels at each time point. % The blue shading represents the max and min contributions of % the selected components tothose channels. The paired colored lines % represent the max and min contributions of the indicated component % across all channels. % Usage: % >> envtopo(data,weights,'chanlocs',file_or_struct); % >> [cmpvarorder,cmpvars,cmpframes,cmptimes,cmpsplotted,sortvar] ... % = envtopo(data, weights, 'key1', val1, ...); % Inputs: % data = single data epoch (chans,frames), else it a 3-D epoched data matrix % (chans,frames,epochs) -> processes the mean data epoch. % weights = linear decomposition (unmixing) weight matrix. The whole matrix % should be passed to the function here. % Ex: (EEG.icaweights*EEG.icasphere) % Required keyword: % 'chanlocs' = [string] channel location filename or EEG.chanlocs structure. % For more information, see >> topoplot example % % Optional inputs: % 'compnums' = [integer array] vector of component indices to use in the % calculations and to select plotted components from % {default|[]: all} % 'compsplot' = [integer] the number of largest contributing components to plot. % compnums in the latter case is restricted in size by the % internal variable MAXTOPOS (20) {default|[] -> 7} % 'subcomps' = [integer vector] indices of comps. to remove from the whole data % before plotting. 0 -> Remove none. [] -> If 'compnums' % also listed, remove *all* except 'compnums' {default: 0} % 'limits' = 0 or [minms maxms] or [minms maxms minuV maxuV]. Specify % start/end plot (x) limits (in ms) and min/max y-axis limits % (in uV). If 0, or if both minmx & maxms == 0 -> use latencies % from 'timerange' (else 0:frames-1). If both minuV and % maxuV == 0 -> use data uV limits {default: 0} % 'timerange' = start and end input data latencies (in ms) {default: from 'limits' % if any}. Note: Does NOT select a portion of the input data, % just makes time labels. % 'limcontrib' = [minms maxms] time range (in ms) in which to rank component % contribution (boundaries shown with thin dotted lines) % {default|[]|[0 0] -> plotting limits} % 'sortvar' = ['mp'|'pv'|'pp'|'rp'] {default:'mp'} % 'mp', sort components by maximum mean back-projected power % in the 'limcontrib' time range: mp(comp) = max(Mean(back_proj.^2)); % where back_proj = comp_map * comp_activation(t) for t in 'limcontrib' % 'pv', sort components by percent variance accounted for (eeg_pvaf()) % pvaf(comp) = 100-100*mean(var(data - back_proj))/mean(var(data)); % 'pp', sort components by percent power accounted for (ppaf) % ppaf(comp) = 100-100*Mean((data - back_proj).^2)/Mean(data.^2); % 'rp', sort components by relative power % rp(comp) = 100*Mean(back_proj.^2)/Mean(data.^2); % 'title' = [string] plot title {default|[] -> none} % 'plotchans' = [integer array] data channels to use in computing contributions and % envelopes, and also for making scalp topo plots % {default|[] -> all}, by calling topoplot(). % 'voffsets' = [float array] vertical line extentions above the data max to % disentangle plot lines (left->right heads, values in y-axis units) % {default|[] -> none} % 'colors' = [string] filename of file containing colors for envelopes, 3 chars % per line, (. = blank). First color should be "w.." (white) % Else, 'bold' -> plot default colors in thick lines. % {default|[] -> standard Matlab color order} % 'fillcomp' = int_vector>0 -> fill the numbered component envelope(s) with % solid color. Ex: [1] or [1 5] {default|[]|0 -> no fill} % 'vert' = vector of times (in ms) at which to plot vertical dashed lines % {default|[] -> none} % 'icawinv' = [float array] inverse weight matrix. Normally computed by inverting % the weights*sphere matrix (Note: If some components have been % removed, the pseudo-inverse does not represent component maps % accurately). % 'icaact' = [float array] component activations. {default: computed from the % input weight matrix} % 'envmode' = ['avg'|'rms'] compute the average envelope or the root mean square % envelope {default: 'avg'} % 'sumenv' = ['on'|'off'|'fill'] 'fill' -> show the filled envelope of the summed % projections of the selected components; 'on' -> show the envelope % only {default: 'fill'} % 'actscale' = ['on'|'off'] scale component scalp maps by maximum component activity % in the designated (limcontrib) interval. 'off' -> scale scalp maps % individually using +/- max(abs(map value)) {default: 'off'} % 'dispmaps' = ['on'|'off'] display component numbers and scalp maps {default: 'on'} % 'topoplotkey','val' = optional additional topoplot() arguments {default: none} % % Outputs: % % cmpvarorder = component numbers in decreasing order of max variance in data % cmpvars = ('sortvar') max power for all components tested, sorted % from highest to lowest. See 'sortvar' 'mp' % cmpframes = frames of comvars for each component plotted % cmptimes = times of compvars for each component plotted % cmpsplotted = indices of components plotted. % unsorted_compvars = compvars(compsplotted); % sortvar = The computed data used to sort components with. % See 'sortvar' option above. % % Notes: % To label maps with other than component numbers, put four-char strings into % a local (pwd) file named 'envtopo.labels' (using . = space) in time-order % of their projection maxima % % Authors: Scott Makeig & Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 3/1998 % % See also: timtopo() axcopy() % Copyright (C) 3-10-98 from timtopo.m 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 % Edit History: % 3-18-98 fixed bug in LineStyle for fifth component, topoplot maxproj with % correct orientations, give specified component number labels -sm % 4-28-98 plot largest components, ranked by max projected variance -sm % 4-30-98 fixed bug found in icademo() -sm % 5-08-98 fixed bug found by mw () -sm % 5-23-98 made vert. line styles for comps 6 & 11 correct -sm % 5-30-98 added 'envtopo.labels' option -sm % 5-31-98 implemented plotchans arg -sm % 7-13-98 gcf->gca to allow plotting in subplots -sm % 9-18-98 worked more to get plotting in subplot to work -- no luck yet! -sm % 2-22-99 draw oblique line to max env value if data clipped at max proj -sm % 2-22-99 added colorfile -sm % 4-17-99 added support for drawing in subplots -t-pj % 10-29-99 new versions restores search through all components for max 7 and adds % return variables (>7 if specified. Max of 7 comp envs still plotted. -sm % 11-17-99 debugged new version -sm % 12-27-99 improved help msg, moved new version to distribution -sm % 01-21-00 added 'bold' option for colorfile arg -sm % 02-28-00 added fill_comp_env arg -sm % 03-16-00 added axcopy() -sm & tpj % 05-02-00 added vert option -sm % 05-30-00 added option to show "envelope" of only 1 channel -sm % 09-07-00 added [-n] option for compnums, added BOLD_COLORS as default -sm % 12-19-00 updated icaproj() args -sm % 12-22-00 trying 'axis square' for topoplots -sm % 02-02-01 fixed bug in printing component 6 env line styles -sm % 04-11-01 added [] default option for args -sm % 01-25-02 reformated help & license, added links -ad % 03-15-02 added readlocs and the use of eloc input structure -ad % 03-16-02 added all topoplot options -ad function [compvarorder,compvars,compframes,comptimes,compsplotted,sortvar] = envtopo(data,weights,varargin) % icadefs; % read toolbox defaults sortvar = []; all_bold = 0; BOLD_COLORS = 1; % 1 = use solid lines for first 5 components plotted % 0 = use std lines according to component rank only FILL_COMP_ENV = 0; % default no fill FILLCOLOR = [.815 .94 1]; % use lighter blue for better env visibility % FILLCOLOR = [.66 .76 1]; MAXTOPOS = 20; % max topoplots to plot VERTWEIGHT = 2.0; % lineweight of specified vertical lines LIMCONTRIBWEIGHT = 1.2; % lineweight of limonctrib vertical lines MAX_FRAMES = 10000; % maximum frames to plot MAXENVPLOTCHANS = 10; myfig =gcf; % remember the current figure (for Matlab 7.0.0 bug) xmin = 0; xmax = 0; if nargin < 2 help envtopo return end if nargin <= 2 | isstr(varargin{1}) % 'key' 'val' sequences fieldlist = { 'chanlocs' '' [] [] ; 'title' 'string' [] ''; 'limits' 'real' [] 0; 'timerange' 'real' [] []; 'plotchans' 'integer' [1:size(data,1)] [] ; 'icawinv' 'real' [] pinv(weights) ; 'icaact' 'real' [] [] ; 'voffsets' 'real' [] [] ; 'vert' 'real' [] [] ; 'fillcomp' 'integer' [] 0 ; 'colorfile' 'string' [] '' ; 'colors' 'string' [] '' ; 'compnums' 'integer' [] []; 'compsplot' 'integer' [] 7; 'subcomps' 'integer' [] 0; 'envmode' 'string' {'avg','rms'} 'avg'; 'dispmaps' 'string' {'on','off'} 'on'; 'pvaf' 'string' {'mp','mv','on','rp','rv','pv','pvaf','pp','off',''} ''; 'sortvar' 'string' {'mp','mv','rp','rv','pv','pvaf','pp'} 'mp'; 'actscale' 'string' {'on','off'} 'off'; 'limcontrib' 'real' [] 0; 'topoarg' 'real' [] 0; 'sumenv' 'string' {'on','off','fill'} 'fill'}; % Note: Above, previous 'pvaf' arguments 'on' -> 'pv', 'off' -> 'rv' % for backwards compatibility 11/2004 -sm [g varargin] = finputcheck( varargin, fieldlist, 'envtopo', 'ignore'); if isstr(g), error(g); end; else % dprecated - old style input args if nargin > 3, g.chanlocs = varargin{1}; else g.chanlocs = []; end; if isstr(varargin{2}), help envtopo; return; end if nargin > 4, g.limits = varargin{2}; else g.limits = 0; % []; end; if isstr(varargin{3}), help envtopo; return; end if nargin > 5, g.compnums = varargin{3}; else g.compnums = []; end; if ~isstr(varargin{4}), help envtopo; return; end if nargin > 6, g.title = varargin{4}; else g.title = ''; end; if isstr(varargin{5}), help envtopo; return; end if nargin > 7, g.plotchans = varargin{5}; else g.plotchans = []; end; if isstr(varargin{6}), help envtopo; return; end if nargin > 8, g.voffsets = varargin{6}; else g.voffsets = []; end; if isstr(varargin{7}), help envtopo; return; end if nargin > 9, g.colorfile = varargin{7}; else g.colorfile = ''; g.colors = ''; end; if isstr(varargin{8}), help envtopo; return; end if nargin > 10, g.fillcomp = varargin{8}; else g.fillcom = 0; end; if isstr(varargin{9}), help envtopo; return; end if nargin > 11, g.vert = varargin{9}; else g.vert = []; end; if nargin > 12, varargin =varargin(10:end); end; g.sumenv = 'on'; g.sortvar = 'mp'; g.pvaf = []; g.timerange = []; g.icaact = []; g.limcontrib = 0; g.icawinv = pinv(weights); g.subcomps = 0; g.envmode = 'avg'; g.dispmaps = 'on'; end; if ~isempty(g.pvaf) g.sortvar = g.pvaf; % leave deprecated g.pvaf behind. end if strcmpi(g.sortvar,'on') | strcmpi(g.sortvar,'pvaf') | strcmpi(g.sortvar,'mv') g.sortvar = 'mp'; % update deprecated flags end if strcmpi(g.sortvar,'off') | strcmp(g.sortvar,'rv') g.sortvar = 'rp'; end % % Check input flags and arguments % if ndims(data) == 3 data = mean(data,3); % average the data if 3-D end; [chans,frames] = size(data); if frames > MAX_FRAMES error('number of data frames to plot too large!'); end if isstr(g.chanlocs) g.chanlocs = readlocs(g.chanlocs); % read channel location information if length(g.chanlocs) ~= chans fprintf(... 'envtopo(): locations for the %d data channels not in the channel location file.\n', ... chans); return end end if ~isempty(g.colors) g.colorfile = g.colors; % retain old usage 'colorfile' for 'colors' -sm 4/04 end if ~isempty(g.vert) g.vert = g.vert/1000; % convert from ms to s end % %%%%%% Collect information about the gca, then delete it %%%%%%%%%%%%% % uraxes = gca; % the original figure or subplot axes pos=get(uraxes,'Position'); axcolor = get(uraxes,'Color'); delete(gca) % %%% Convert g.timerange, g.limits and g.limcontrib to sec from ms %%%% % g.timerange = g.timerange/1000; % the time range of the input data g.limits(1) = g.limits(1)/1000; % the time range to plot if length(g.limits) == 1 % make g.limits at least of length 2 g.limits(1) = 0; g.limits(2) = 0; else g.limits(2) = g.limits(2)/1000; % end; g.limcontrib = g.limcontrib/1000; % the time range in which to select largest components % %%%%%%%%%%%% Collect time range information %%%%%%%%%%%%%%%%%%%%%%%%%% % if length(g.limits) == 3 | length(g.limits) > 4 % if g.limits wrong length fprintf('envtopo: limits should be 0, [minms maxms], or [minms maxms minuV maxuV].\n'); end xunitframes = 0; % flag plotting if xmin & xmax are in frames instead of sec if ~isempty(g.timerange) % if 'timerange' given if g.limits(1)==0 & g.limits(2)==0 g.limits(1) = min(g.timerange); % if no time 'limits g.limits(2) = max(g.timerange); % plot whole data epoch end else % if no 'timerange' given if g.limits(1)==0 & g.limits(2)==0 % if no time limits as well, fprintf('\nNOTE: No time limits given: using 0 to %d frames\n',frames-1); g.limits(1) = 0; g.limits(2) = frames-1; xunitframes = 1; % mark frames as time unit instead of sec end end if isempty(g.timerange) xmin = g.limits(1); % (xmin, xmax) are data limits in sec xmax = g.limits(2); else xmin = g.timerange(1); % (xmin, xmax) are data limits in sec xmax = g.timerange(2); end pmin = g.limits(1); % plot min and max sec if pmin < xmin pmin = xmin; % don't allow plotting beyond the data limits end pmax = g.limits(2); if pmax > xmax pmax = xmax; end dt = (xmax-xmin)/(frames-1); % sampling interval in sec times=xmin*ones(1,frames)+dt*(0:frames-1); % time points in sec % %%%%%%%%%%%%%%% Find limits of the component selection window %%%%%%%%% % if any(g.limcontrib ~= 0) if xunitframes g.limcontrib = g.limcontrib*1000; % if no time limits, interpret end % limcontrib as frames if g.limcontrib(1)<xmin g.limcontrib(1) = xmin; end if g.limcontrib(2)>xmax g.limcontrib(2) = xmax; end srate = (frames-1)/(xmax-xmin); limframe1 = round((g.limcontrib(1)-xmin)*srate)+1; limframe2 = round((g.limcontrib(2)-xmin)*srate)+1; g.vert(end+1) = g.limcontrib(1); g.vert(end+1) = g.limcontrib(2); else limframe1 = 1; limframe2 = frames; end; % %%%%%%%%%%%%%%%%%%%%% Read line color information %%%%%%%%%%%%%%%%%%%%% % ENVCOLORS = strvcat('w..','r..','g..','b..','m..','c..','r..','g..','b..','m..','c..','r..','g..','b..','m..','c..','r..','g..','b..','m..','c..','r..','g..','b..','m..','c..','r..','g..','b..','m..','c..','r..','g..','b..','m..','c..','r..','g..','b..','m..','c..','r..','g..','b..','m..','c..','r..','g..','b..','m..','c..','r..','g..','b..','m..','c..','r..','g..','b..','m..','c..','r..','g..','b..'); if isempty(g.colorfile) g.colorfile = ENVCOLORS; % use default color order above elseif ~isstr(g.colorfile) error('Color file name must be a string.'); end if strcmpi(g.colorfile,'bold') all_bold = 1; g.colorfile = ENVCOLORS; % default colors end if exist(g.colorfile) == 2 % if an existing file cid = fopen(g.colorfile,'r'); if cid <3, error('cannot open color file'); else colors = fscanf(cid,'%s',[3 MAXENVPLOTCHANS]); colors = colors'; end; else colors = g.colorfile; end [r c] = size(colors); for i=1:r for j=1:c if colors(i,j)=='.', if j==1 error('Color file should have color letter in 1st column.'); elseif j==2 colors(i,j)='-'; elseif j>2 colors(i,j)=' '; end; end; end; end; colors(1,1) = 'k'; % make sure 1st color (for data envelope) is black % %%%%%%%%%%%%%%%% Check other input variables %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % [wtcomps,wchans] = size(weights); if wchans ~= chans error('Sizes of weights and data do not agree'); end if wtcomps ~= chans fprintf('Number of components not the same as number of channels.\n'); fprintf(' - component scalp maps and time courses may not be correct.\n'); end if isempty(g.voffsets) | ( size(g.voffsets) == [1,1] & g.voffsets(1) == 0 ) g.voffsets = zeros(1,MAXTOPOS); end if isempty(g.plotchans) | g.plotchans(1)==0 g.plotchans = 1:chans; end if max(g.plotchans) > chans | min(g.plotchans) < 1 error('invalid ''plotchan'' index'); end if g.compsplot < 0 g.compsplot = abs(g.compsplot); end if g.compnums < 0 % legacy syntax g.compsplot = abs(g.compnums); g.compnums = []; end if isempty(g.compnums) | g.compnums(1) == 0 g.compnums = 1:wtcomps; % by default, select from all components end if g.compsplot > MAXTOPOS fprintf('Can only plot a maximum of %d components.\n',MAXTOPOS); return else MAXTOPOS = g.compsplot; end if max(g.compnums) > wtcomps | min(g.compnums)< 1 error('Keyword ''compnums'' out of range (1 to %d)', wtcomps); end g.subcomps = abs(g.subcomps); % don't pass negative channel numbers if max(g.subcomps) > wtcomps error('Keyword ''subcomps'' argument out of bounds'); end % %%%%%%%%%%%%%%% Subtract components from data if requested %%%%%%%%%%%%% % ncomps = length(g.compnums); if isempty(g.subcomps) % remove all but compnums g.subcomps = 1:wtcomps; g.subcomps(g.compnums) = []; else % g.subcomps 0 -> subtract no comps % list -> subtract subcomps list if min(g.subcomps) < 1 if length(g.subcomps) > 1 error('Keyword ''subcomps'' argument incorrect.'); end g.subcomps = []; % if subcomps contains a 0 (or <1), don't remove components elseif max(g.subcomps) > wtcomps error('Keyword ''subcomps'' argument out of bounds.'); end end g.icaact = weights*data; if ~isempty(g.subcomps) fprintf('Subtracting requested components from plotting data: '); for k = 1:length(g.subcomps) fprintf('%d ',g.subcomps(k)); if ~rem(k,32) fprintf('\n'); end end fprintf('\n'); g.icaact(g.subcomps,:) = zeros(length(g.subcomps),size(data,2)); end; % %%%%%%%%%%%%%%%%%%%%%%%%%%% Process components %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % for i=1:ncomps-1 if g.compnums(i) == 0 fprintf('Removing component number 0 from compnums.\n'); g.compnums(i)=[]; elseif g.compnums(i)>wtcomps fprintf('compnums(%d) > number of comps (%d)?\n',i,wtcomps); return end for j=i+1:ncomps if g.compnums(i)==g.compnums(j) fprintf('Removing repeated component number (%d) in compnums.\n',g.compnums(i)); g.compnums(j)=[]; end end end limitset = 0; if isempty(g.limits) g.limits = 0; end if length(g.limits)>1 limitset = 1; end % %%%%%%%%%%%%%%% Compute plotframes and envdata %%%%%%%%%%%%%%%%%%%%% % ntopos = length(g.compnums); if ntopos > MAXTOPOS ntopos = MAXTOPOS; % limit the number of topoplots to display end if max(g.compnums) > wtcomps | min(g.compnums)< 1 fprintf(... 'envtopo(): one or more compnums out of range (1,%d).\n',wtcomps); return end plotframes = ones(ncomps); % toby 2.16.2006: maxproj will now contain all channel info, in case % plotgrid is called in topoplot. % NOT maxproj = zeros(length(g.plotchans),ncomps); maxproj = zeros(chans,ncomps); % % first, plot the data envelope % envdata = zeros(2,frames*(ncomps+1)); envdata(:,1:frames) = envelope(g.icawinv(g.plotchans,:)*g.icaact, g.envmode); fprintf('Data epoch is from %.0f ms to %.0f ms.\n',1000*xmin,1000*xmax); fprintf('Plotting data from %.0f ms to %.0f ms.\n',1000*xmin,1000*xmax); fprintf('Comparing maximum projections for components: \n'); if ncomps>32 fprintf('\n'); end compvars = zeros(1,ncomps); mapsigns = zeros(1,ncomps); % % Compute frames to plot % sampint = (xmax-xmin)/(frames-1); % sampling interval in sec times = xmin:sampint:xmax; % make vector of data time values [v minf] = min(abs(times-pmin)); [v maxf] = min(abs(times-pmax)); pframes = minf:maxf; % frames to plot ptimes = times(pframes); % times to plot if limframe1 < minf limframe1 = minf; end if limframe2 > maxf limframe2 = maxf; end % %%%%%%%%%%%%%% find max variances and their frame indices %%%%%%%%%%% % if strcmp(g.sortvar,'pv') %Changed -Jean % Variance of the data in the interval, for calculating sortvar. vardat = mean(var(data(g.plotchans,limframe1:limframe2),1)); else % Compute data rms for sortvar powdat = mean(mean(data(g.plotchans,limframe1:limframe2).^2)); end for c = 1:ncomps if isempty(g.icaact) % make the back-projection of component c % Changed to include all channels in computation for use in % topoplot, particularly with plotgrid option. toby 2.16.2006 proj = g.icawinv(:,g.compnums(c))*weights(g.compnums(c),:)*data; else proj = g.icawinv(:,g.compnums(c))*g.icaact(g.compnums(c),:); end; % save the comp envelope for plotting component waveforms envdata(:,c*frames+1:(c+1)*frames) = envelope(proj(g.plotchans,:), g.envmode); % Find the frame (timepoint) of largest rms component value % and the relative value to those channels defined by plotchans. if length(g.plotchans) > 1 [maxval,maxi] = max(mean((proj(g.plotchans,limframe1:limframe2)).^2)); else % g.plotchans == 1 --> find absmax value [maxval,maxi] = max((abs(proj(g.plotchans,limframe1:limframe2)))); end maxi = maxi+limframe1-1; % plotframes and compvars are needed for plotting the lines indicating % the timepoint a topoplot refers to. plotframes(c) = maxi; compvars(c) = maxval; % find value of max variance for comp c maxproj(:,c) = proj(:,maxi); % maxproj now contains all channels, to handle % the 'plotchans'/topoplot'gridplot' conflict. % Toby 2.17.2006 % %%%%%% Calculate sortvar, used to sort the components %%%%%%%%%%% % if strcmpi(g.sortvar,'mp') % Maximum Power of backproj sortvar(c) = maxval; fprintf('IC%1.0f maximum mean power of back-projection: %g\n',c,sortvar(c)); elseif strcmpi(g.sortvar, 'pv') % Percent Variance % toby 2.19.2006: Changed to be consistent with eeg_pvaf(). sortvar(c) = 100-100*mean(var(data(g.plotchans,limframe1:limframe2)... - proj(g.plotchans,limframe1:limframe2),1))/vardat; fprintf('IC%1.0f percent variance accounted for(pvaf): %2.2f%%\n',c,sortvar(c)); elseif strcmpi(g.sortvar,'pp') % Percent Power sortvar(c) = 100-100*mean(mean((data(g.plotchans,limframe1:limframe2)... - proj(g.plotchans,limframe1:limframe2)).^2))/powdat; fprintf('IC%1.0f percent power accounted for(ppaf): %2.2f%%\n',c,sortvar(c)); elseif strcmpi(g.sortvar,'rp') % Relative Power sortvar(c) = 100*mean(mean((proj(g.plotchans,limframe1:limframe2)).^2))/powdat; fprintf('IC%1.0f relative power of back-projection: %g\n',c,sortvar(c)); else error('''sortvar'' argument unknown'); end; end % component c fprintf('\n'); % %%%%%%%%%%%%%%% Compute component selection criterion %%%%%%%%%%%%%%%%%%%%%%%%%% % % compute sortvar if ~xunitframes fprintf(' in the interval %3.0f ms to %3.0f ms.\n',... 1000*times(limframe1),1000*times(limframe2)); end [sortsortvar spx] = sort(sortvar); sortsortvar = sortsortvar(end:-1:1); spx = spx(end:-1:1); npercol = ceil(ncomps/3); % %%%%%%%%%%%%%%%%%%%%%%%%% Sort the components %%%%%%%%%%%%%%%%%%%%%%%%%%% % [tmp,compx] = sort(sortvar'); % sort compnums on sortvar (as defined by input % 'sortvar', default is 'mp'). compx = compx(ncomps:-1:1); % reverse order of sort compvars = compvars(ncomps:-1:1)';% reverse order of sort (output var) compvarorder = g.compnums(compx); % actual component numbers (output var) plotframes = plotframes(compx); % plotted comps have these max frames compframes = plotframes'; % frame of max variance in each comp (output var) comptimes = times(plotframes(compx)); % time of max variance in each comp (output var) compsplotted = compvarorder(1:ntopos); % (output var) % %%%%%%%%%%%%%%%%%%%%%%%% Reduce to ntopos %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % [plotframes,ifx] = sort(plotframes(1:ntopos));% sort plotframes on their temporal order plottimes = times(plotframes); % convert to times in ms compx = compx(ifx); % indices into compnums, in plotting order maporder = g.compnums(compx); % comp. numbers, in plotting order (l->r) maxproj = maxproj(:,compx); % maps in plotting order vlen = length(g.voffsets); % extend voffsets if necessary while vlen< ntopos g.voffsets = [g.voffsets g.voffsets(vlen)]; % repeat last offset given vlen=vlen+1; end head_sep = 1.2; topowidth = pos(3)/(ntopos+(ntopos-1)/5); % width of each topoplot if topowidth > 0.20 % adjust for maximum height topowidth = 0.2; end if rem(ntopos,2) == 1 % odd number of topos topoleft = pos(3)/2 - (floor(ntopos/2)*head_sep + 0.5)*topowidth; else % even number of topos topoleft = pos(3)/2 - (floor(ntopos/2)*head_sep)*topowidth; end % %%%%%%%%%%%%%%%%%%%% Print times and frames of comp maxes %%%%%%%%%%%%%% % % fprintf('\n'); fprintf('Plotting envelopes of %d component projections.\n',ntopos); if length(g.plotchans) ~= chans fprintf('Envelopes computed from %d specified data channels.\n',... length(g.plotchans)); end fprintf('Topo maps will show components: '); for t=1:ntopos fprintf('%4d ',maporder(t)); end fprintf('\n'); if ~xunitframes fprintf(' with max var at times (ms): '); for t=1:ntopos fprintf('%4.0f ',1000*plottimes(t)); end fprintf('\n'); end fprintf(' epoch frames: '); for t=1:ntopos fprintf('%4d ',limframe1-1+plotframes(t)); end fprintf('\n'); fprintf(' Component sortvar in interval: '); for t=1:ntopos fprintf('%4.2f ',sortvar(t)); end fprintf('\n'); sumproj = zeros(size(data(g.plotchans,:))); % toby 2.21.2006 REDUNDANT CALCULATIONS! for n = 1:ntopos if isempty(g.icaact) sumproj = sumproj + ... g.icawinv(g.plotchans,maporder(n))*weights(maporder(n),:)*data; else sumproj = sumproj + g.icawinv(g.plotchans,maporder(n))*g.icaact(maporder(n),:); % updated -sm 11/04 end; % Note: sumproj here has only g.plotchans end rmsproj = mean(mean((data(g.plotchans,limframe1:limframe2).^2))); % find data rms in interval if strcmpi(g.sortvar,'rp') sumppaf = mean(mean(sumproj(:,limframe1:limframe2).^2)); sumppaf = 100*sumppaf/rmsproj; ot = 'rp'; else sumppaf = mean(mean((data(g.plotchans,limframe1:limframe2) ... - sumproj(:,limframe1:limframe2)).^2)); sumppaf = 100-100*sumppaf/rmsproj; ot = 'ppaf'; end; if ~xunitframes fprintf(' Summed component ''%s'' in interval [%4g %4g] ms: %4.2f%%\n',... ot, 1000*times(limframe1),1000*times(limframe2), sumppaf); end % % Collect user-supplied Y-axis information % Edited and moved here from 'Collect Y-axis information' section below -Jean % if length(g.limits) == 4 if g.limits(3)~=0 | g.limits(4)~=0 % collect plotting limits from 'limits' ymin = g.limits(3); ymax = g.limits(4); ylimset = 1; end else ylimset = 0; % flag whether hard limits have been set by the user ymin = min(min(g.icawinv(g.plotchans,:)*g.icaact(:,pframes))); % begin by setting limits from plotted data ymax = max(max(g.icawinv(g.plotchans,:)*g.icaact(:,pframes))); end fprintf(' Plot limits (sec, sec, uV, uV) [%g,%g,%g,%g]\n\n',xmin,xmax, ymin,ymax); % %%%%%%%%%%%%%%%%%%%%% Plot the data envelopes %%%%%%%%%%%%%%%%%%%%%%%%% % BACKCOLOR = [0.7 0.7 0.7]; FONTSIZE=12; FONTSIZEMED=10; FONTSIZESMALL=8; newaxes=axes('position',pos); axis off set(newaxes,'FontSize',FONTSIZE,'FontWeight','Bold','Visible','off'); set(newaxes,'Color',BACKCOLOR); % set the background color delete(newaxes) %XXX % site the plot at bottom of the current axes axe = axes('Position',[pos(1) pos(2) pos(3) 0.6*pos(4)],... 'FontSize',FONTSIZE,'FontWeight','Bold'); g.limits = get(axe,'Ylim'); set(axe,'GridLineStyle',':') set(axe,'Xgrid','off') set(axe,'Ygrid','on') axes(axe) set(axe,'Color',axcolor); % %%%%%%%%%%%%%%%%% Plot the envelope of the summed selected components %%%%%%%%%%%%%%%%% % if BOLD_COLORS==1 mapcolors = 1:ntopos+1; else mapcolors = [1 maporder+1]; end if strcmpi(g.sumenv,'on') | strcmpi(g.sumenv,'fill') %%%%%%%% if 'sunvenv' %%%%%%%%% sumenv = envelope(sumproj(:,:), g.envmode); if ~ylimset & max(sumenv) > ymax, ymax = max(sumenv(1,:)); end if ~ylimset & min(sumenv) < ymin, ymin = min(sumenv(2,:)); end if strcmpi(g.sumenv,'fill') % % Plot the summed projection filled % mins = matsel(sumenv,frames,0,2,0); p=fill([times times(frames:-1:1)],... [matsel(sumenv,frames,0,1,0) mins(frames:-1:1)],FILLCOLOR); set(p,'EdgeColor',FILLCOLOR); hold on % % Overplot the data envelope so it is not covered by the fill()'d component % p=plot(times,matsel(envdata,frames,0,1,1),colors(mapcolors(1),1));% plot the max set(p,'LineWidth',2); % component order (if BOLD_COLORS==0) p=plot(times,matsel(envdata,frames,0,2,1),colors(mapcolors(1),1));% plot the min set(p,'LineWidth',2); % component order (if BOLD_COLORS==0) else % if no 'fill' tmp = matsel(sumenv,frames,0,2,0); p=plot(times,tmp);% plot the min hold on set(p,'color',FILLCOLOR); set(p,'linewidth',2); p=plot(times,matsel(sumenv,frames,0,1,0));% plot the max set(p,'linewidth',2); set(p,'color',FILLCOLOR); end end if strcmpi(g.sortvar,'rp') t = text(double(xmin+0.1*(xmax-xmin)), ... double(ymin+0.1*(ymax-ymin)), ... ['rp ' num2str(sumppaf,'%4.2f') '%']); else t = text(double(xmin+0.1*(xmax-xmin)), ... double(ymin+0.1*(ymax-ymin)), ... ['ppaf ' num2str(sumppaf,'%4.2f') '%']); end set(t,'fontsize',FONTSIZESMALL,'fontweight','bold') % % %%%%%%%%%%%%%%%%%%%%%%%% Plot the computed component envelopes %%%%%%%%%%%%%%%%%% % envx = [1;compx+1]; for c = 1:ntopos+1 curenv = matsel(envdata,frames,0,1,envx(c)); if ~ylimset & max(curenv) > ymax, ymax = max(curenv); end p=plot(times,curenv,colors(mapcolors(c),1));% plot the max set(gca,'FontSize',FONTSIZESMALL,'FontWeight','Bold') if c==1 % Note: use colors in original set(p,'LineWidth',2); % component order (if BOLD_COLORS==0) else set(p,'LineWidth',1); end if all_bold > 0 set(p,'LineStyle','-','LineWidth',3); elseif mapcolors(c)>15 % thin/dot 16th-> comp. envs. set(p,'LineStyle',':','LineWidth',1); elseif mapcolors(c)>10 % set(p,'LineStyle',':','LineWidth',2); elseif mapcolors(c)>6 % dot 6th-> comp. envs. set(p,'LineStyle',':','LineWidth',3); elseif mapcolors(c)>1 set(p,'LineStyle',colors(mapcolors(c),2),'LineWidth',1); if colors(mapcolors(c),2) == ':' set(l1,'LineWidth',2); % embolden dotted env lines end end hold on curenv = matsel(envdata,frames,0,2,envx(c)); if ~ylimset & min(curenv) < ymin, ymin = min(curenv); end p=plot(times,curenv,colors(mapcolors(c),1));% plot the min if c==1 set(p,'LineWidth',2); else set(p,'LineWidth',1); end if all_bold > 0 set(p,'LineStyle','-','LineWidth',3); elseif mapcolors(c)>15 % thin/dot 11th-> comp. envs. set(p,'LineStyle',':','LineWidth',1); elseif mapcolors(c)>10 set(p,'LineStyle',':','LineWidth',2); elseif mapcolors(c)>6 % dot 6th-> comp. envs. set(p,'LineStyle',':','LineWidth',3); elseif mapcolors(c)>1 set(p,'LineStyle',colors(mapcolors(c),2),'LineWidth',1); if colors(mapcolors(c),2) == ':' set(l1,'LineWidth',2); % embolden dotted env lines end end if c==1 & ~isempty(g.vert) for v=1:length(g.vert) vl=plot([g.vert(v) g.vert(v)], [-1e10 1e10],'k--'); % plot specified vertical lines if any(g.limcontrib ~= 0) & v>= length(g.vert)-1; set(vl,'linewidth',LIMCONTRIBWEIGHT); set(vl,'linestyle',':'); else set(vl,'linewidth',VERTWEIGHT); set(vl,'linestyle','--'); end end end if g.limits(1) <= 0 & g.limits(2) >= 0 % plot vertical line at time zero vl=plot([0 0], [-1e10 1e10],'k'); set(vl,'linewidth',2); end % % plot the n-th component filled % if g.fillcomp(1)>0 & find(g.fillcomp==c-1) fprintf('filling the envelope of component %d\n',c-1); mins = matsel(envdata,frames,0,2,envx(c)); p=fill([times times(frames:-1:1)],... [matsel(envdata,frames,0,1,envx(c)) mins(frames:-1:1)],... colors(mapcolors(c),1)); % % Overplot the data envlope again so it is not covered by the fill()'d component % p=plot(times,matsel(envdata,frames,0,1,envx(1)),colors(mapcolors(1),1));% plot the max set(p,'LineWidth',2); % component order (if BOLD_COLORS==0) p=plot(times,matsel(envdata,frames,0,2,envx(1)),colors(mapcolors(1),1));% plot the min set(p,'LineWidth',2); % component order (if BOLD_COLORS==0) end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %%%%%%%%%%%%%%%%%%%%%%% Extend y limits by 5% %%%%%%%%%%%%%%%%%%%%%%%%%% % if ~ylimset datarange = ymax-ymin; ymin = ymin-0.05*datarange; ymax = ymax+0.05*datarange; end axis([pmin pmax ymin ymax]); % %%%%%%%%%%%%%%%%%%%%%% Label axes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % set(axe,'Color',axcolor); if ~xunitframes l= xlabel('Time (s)'); else % xunitframes == 1 l= xlabel('Data (time points)'); end set(l,'FontSize',FONTSIZEMED,'FontWeight','Bold'); if strcmpi(g.envmode, 'avg') l=ylabel('Potential (uV)'); else l=ylabel('RMS of uV'); end; set(l,'FontSize',FONTSIZEMED,'FontWeight','Bold'); % %%%%%%%%%%%%%% Draw maps and oblique/vertical lines %%%%%%%%%%%%%%%%%%%%% % % axall = axes('Units','Normalized','Position',pos,... axall = axes('Position',pos,... 'Visible','Off','Fontsize',FONTSIZE); % whole-figure invisible axes axes(axall) set(axall,'Color',axcolor); axis([0 1 0 1]) width = xmax-xmin; pwidth = pmax-pmin; height = ymax-ymin; if strcmpi(g.dispmaps, 'on') for t=1:ntopos % draw oblique lines from max env vals (or plot top) % to map bases, in left to right order % %%%%%%%%%%%%%%%%%%% draw oblique lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if BOLD_COLORS==1 linestyles = 1:ntopos; else linestyles = maporder; end axes(axall) axis([0 1 0 1]); set(axall,'Visible','off'); maxenv = matsel(envdata,frames,plotframes(t),1,compx(t)+1); % max env val data_y = 0.6*(g.voffsets(t)+maxenv-ymin)/height; if (data_y > pos(2)+0.6*pos(4)) data_y = pos(2)+0.6*pos(4); end l1 = plot([(plottimes(t)-pmin)/pwidth ... topoleft + 1/pos(3)*(t-1)*1.2*topowidth + (topowidth*0.6)],... [data_y 0.68], ... colors(linestyles(t)+1)); % 0.68 is bottom of topo maps if all_bold > 0 set(l1,'LineStyle','-','LineWidth',3); elseif linestyles(t)>15 % thin/dot 11th-> comp. envs. set(l1,'LineStyle',':','LineWidth',1); elseif linestyles(t)>10 set(l1,'LineStyle',':','LineWidth',2); elseif linestyles(t)>5 % dot 6th-> comp. envs. set(l1,'LineStyle',':','LineWidth',3); elseif linestyles(t)>1 set(l1,'LineStyle',colors(linestyles(t)+1,2),'LineWidth',1); if colors(linestyles(t)+1,2) == ':' set(l1,'LineStyle',colors(linestyles(t)+1,2),'LineWidth',2); end end hold on % %%%%%%%%%%%%%%%%%%%% add specified vertical lines %%%%%%%%%%%%%%%%%%%%%%%%% % if g.voffsets(t) > 0 l2 = plot([(plottimes(t)-xmin)/width ... (plottimes(t)-xmin)/width],... [0.6*(maxenv-ymin)/height ... 0.6*(g.voffsets(t)+maxenv-ymin)/height],... colors(linestyles(t)+1)); if all_bold > 0 set(l2,'LineStyle','-','LineWidth',3); elseif linestyles(t)>15 % thin/dot 11th-> comp. envs. set(l2,'LineStyle',':','LineWidth',1); elseif linestyles(t)>10 set(l2,'LineStyle',':','LineWidth',2); elseif linestyles(t)>5 % dot 6th-> comp. envs. set(l2,'LineStyle',':','LineWidth',3); else set(l1,'LineStyle',colors(linestyles(t)+1,2),'LineWidth',1); if colors(linestyles(t)+1,2) == ':' set(l1,'LineWidth',2); end end end set(gca,'Visible','off'); axis([0 1 0 1]); end % t end; % if g.dispmaps == on % %%%%%%%%%%%%%%%%%%%%%%%%% Plot the topoplots %%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(g.dispmaps, 'on') % common scale for colors % ----------------------- if strcmpi(g.actscale, 'on') maxvolt = 0; for n=1:ntopos maxvolt = max(max(abs(maxproj(:,n))), maxvolt); end; end; [tmp tmpsort] = sort(maporder); [tmp tmpsort] = sort(tmpsort); for t=1:ntopos % left to right order (maporder) % axt = axes('Units','Normalized','Position',... axt = axes('Units','Normalized','Position',... [pos(3)*topoleft+pos(1)+(t-1)*head_sep*topowidth pos(2)+0.66*pos(4) ... topowidth topowidth*head_sep]); axes(axt) % topoplot axes cla if ~isempty(g.chanlocs) % plot the component scalp maps figure(myfig); if ~isempty(varargin) topoplot(maxproj(g.plotchans,t),g.chanlocs(g.plotchans), varargin{:}); else % if no varargin specified topoplot(maxproj(g.plotchans,t),g.chanlocs(g.plotchans),... 'style','both','emarkersize',3); end axis square set(gca, 'userdata', ... ['text(-0.6, -0.6, ''' g.sortvar ': ' sprintf('%6.2f', sortvar(tmpsort(t))) ''');']); else axis off; end; % %%%%%%%%%%%%% Scale colors %%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(g.actscale, 'on') caxis([-maxvolt maxvolt]); end; % %%%%%%%%%%%%%%%%%%%%%%%% label components %%%%%%%%%%%%%%%%%%%%%%% % if t==1 chid = fopen('envtopo.labels','r'); if chid <3, numlabels = 1; else fprintf('Will label scalp maps with labels from file %s\n',... 'envtopo.labels'); compnames = fscanf(chid,'%s',[4 MAXPLOTDATACHANS]); compnames = compnames'; [r c] = size(compnames); for i=1:r for j=1:c if compnames(i,j)=='.', compnames(i,j)=' '; end; end; end; numlabels=0; end end if numlabels == 1 complabel = int2str(maporder(t)); % label comp. numbers else complabel = compnames(t,:); % use labels in file end text(0.00,0.80,complabel,'FontSize',FONTSIZEMED,... 'FontWeight','Bold','HorizontalAlignment','Center'); % axt = axes('Units','Normalized','Position',[0 0 1 1],... axt = axes('Position',[0 0 1 1],... 'Visible','Off','Fontsize',FONTSIZE); set(axt,'Color',axcolor); % topoplot axes drawnow end % %%%%%%%%%%%%%%%%%%%%%%%%%%% Plot a colorbar %%%%%%%%%%%%%%%%%%%%%%%%%% % % axt = axes('Units','Normalized','Position',[.88 .58 .03 .10]); axt = axes('Position',[pos(1)+pos(3)*1.015 pos(2)+0.6055*pos(4) ... pos(3)*.02 pos(4)*0.09]); if strcmpi(g.actscale, 'on') h=cbar(axt, [1:64],[-maxvolt maxvolt],3); else h=cbar(axt); % colorbar axes set(h,'Ytick',[]); axes(axall) set(axall,'Color',axcolor); tmp = text(0.50,1.05,g.title,'FontSize',FONTSIZE,... 'HorizontalAlignment','Center',... 'FontWeight','Bold'); set(tmp, 'interpreter', 'none'); text(1,0.68,'+','FontSize',FONTSIZE,'HorizontalAlignment','Center'); % text(1,0.637,'0','FontSize',12,'HorizontalAlignment','Center',... % 'verticalalignment','middle'); text(1,0.61,'-','FontSize',FONTSIZE,'HorizontalAlignment','Center'); end; axes(axall) set(axall,'layer','top'); % bring component lines to top end; % %%%%%%%%%%%%%%%%%%%%%%%%% turn on axcopy %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % axcopy(gcf, ... 'if ~isempty(get(gca,''''userdata'''')), eval(get(gca,''''userdata''''));end;'); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function envdata = envelope(data, envmode) % also in release as env() if nargin < 2 envmode = 'avg'; end; if strcmpi(envmode, 'rms'); % return rms of pos and neg vals at each time point warning off; datnaeg = (data < 0).*data; % zero out positive values dataneg = -sqrt(sum(dataneg.^2,1) ./ sum(negflag,1)); datapos = (data > 0).*data; % zero out negative values datapos = sqrt(sum(datapos.^2,1) ./ sum(posflag,1)); envdata = [datapos;dataneg]; warning on; else % find max and min value at each time point if size(data,1)>1 maxdata = max(data); % max at each time point mindata = min(data); % min at each time point envdata = [maxdata;mindata]; else maxdata = max([data;data]); % max at each time point mindata = min([data;data]); % min at each time point envdata = [maxdata;mindata]; end end; return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
ZijingMao/baselineeegtest-master
runica.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/runica.m
64,114
utf_8
7b89cfe00edb4acd5ec7b313ee6292ba
% runica() - Perform Independent Component Analysis (ICA) decomposition % of input data using the logistic infomax ICA algorithm of % Bell & Sejnowski (1995) with the natural gradient feature % of Amari, Cichocki & Yang, or optionally the extended-ICA % algorithm of Lee, Girolami & Sejnowski, with optional PCA % dimension reduction. Annealing based on weight changes is % used to automate the separation process. % Usage: % >> [weights,sphere] = runica(data); % train using defaults % else % >> [weights,sphere,compvars,bias,signs,lrates,activations] ... % = runica(data,'Key1',Value1',...); % Input: % data = input data (chans,frames*epochs). % Note that if data consists of multiple discontinuous epochs, % each epoch should be separately baseline-zero'd using % >> data = rmbase(data,frames,basevector); % % Optional keywords [argument]: % 'extended' = [N] perform tanh() "extended-ICA" with sign estimation % N training blocks. If N > 0, automatically estimate the % number of sub-Gaussian sources. If N < 0, fix number of % sub-Gaussian comps to -N [faster than N>0] (default|0 -> off) % 'pca' = [N] decompose a principal component (default -> 0=off) % subspace of the data. Value is the number of PCs to retain. % 'sphering' = ['on'/'off'] flag sphering of data (default -> 'on') % 'weights' = [W] initial weight matrix (default -> eye()) % (Note: if 'sphering' 'off', default -> spher()) % 'lrate' = [rate] initial ICA learning rate (<< 1) (default -> heuristic) % 'block' = [N] ICA block size (<< datalength) (default -> heuristic) % 'anneal' = annealing constant (0,1] (defaults -> 0.90, or 0.98, extended) % controls speed of convergence % 'annealdeg' = [N] degrees weight change for annealing (default -> 70) % 'stop' = [f] stop training when weight-change < this (default -> 1e-6 % if less than 33 channel and 1E-7 otherwise) % 'maxsteps' = [N] max number of ICA training steps (default -> 512) % 'bias' = ['on'/'off'] perform bias adjustment (default -> 'on') % 'momentum' = [0<f<1] training momentum (default -> 0) % 'specgram' = [srate loHz hiHz frames winframes] decompose a complex time/frequency % transform of the data - though not optimally. (Note: winframes must % divide frames) (defaults [srate 0 srate/2 size(data,2) size(data,2)]) % 'posact' = make all component activations net-positive(default 'off'} % Requires time and memory; posact() may be applied separately. % 'verbose' = give ascii messages ('on'/'off') (default -> 'on') % 'logfile' = [filename] save all message in a log file in addition to showing them % on screen (default -> none) % 'interput' = ['on'|'off'] draw interupt figure. Default is off. % % Outputs: [Note: RO means output in reverse order of projected mean variance % unless starting weight matrix passed ('weights' above)] % weights = ICA weight matrix (comps,chans) [RO] % sphere = data sphering matrix (chans,chans) = spher(data) % Note that unmixing_matrix = weights*sphere {if sphering off -> eye(chans)} % compvars = back-projected component variances [RO] % bias = vector of final (ncomps) online bias [RO] (default = zeros()) % signs = extended-ICA signs for components [RO] (default = ones()) % [ -1 = sub-Gaussian; 1 = super-Gaussian] % lrates = vector of learning rates used at each training step [RO] % activations = activation time courses of the output components (ncomps,frames*epochs) % % Authors: Scott Makeig with contributions from Tony Bell, Te-Won Lee, % Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky, Delorme Arnaud, % CNL/The Salk Institute, La Jolla, 1996- % Uses: posact() % 'ncomps' = [N] number of ICA components to compute (default -> chans or 'pca' arg) % using rectangular ICA decomposition. This parameter may return % strange results. This is because the weight matrix is rectangular % instead of being square. Do not use except to try to fix the problem. % Reference (please cite): % % Makeig, S., Bell, A.J., Jung, T-P and Sejnowski, T.J., % "Independent component analysis of electroencephalographic data," % In: D. Touretzky, M. Mozer and M. Hasselmo (Eds). Advances in Neural % Information Processing Systems 8:145-151, MIT Press, Cambridge, MA (1996). % % Toolbox Citation: % % Makeig, Scott et al. "EEGLAB: ICA Toolbox for Psychophysiological Research". % WWW Site, Swartz Center for Computational Neuroscience, Institute of Neural % Computation, University of San Diego California % <www.sccn.ucsd.edu/eeglab/>, 2000. [World Wide Web Publication]. % % For more information: % http://www.sccn.ucsd.edu/eeglab/icafaq.html - FAQ on ICA/EEG % http://www.sccn.ucsd.edu/eeglab/icabib.html - mss. on ICA & biosignals % http://www.cnl.salk.edu/~tony/ica.html - math. mss. on ICA % Copyright (C) 1996 Scott Makeig et al, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %%%%%%%%%%%%%%%%%%%%%%%%%%% Edit history %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % runica() - by Scott Makeig with contributions from Tony Bell, Te-Won Lee % Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky et al. % CNL / Salk Institute 1996-00 % 04-30-96 built from icatest.m and ~jung/.../wtwpwica.m -sm % 07-28-97 new runica(), adds bias (default on), momentum (default off), % extended-ICA (Lee & Sejnowski, 1997), cumulative angledelta % (until lrate drops), keywords, signcount for speeding extended-ICA % 10-07-97 put acos() outside verbose loop; verbose 'off' wasn't stopping -sm % 11-11-97 adjusted help msg -sm % 11-30-97 return eye(chans) if sphering 'off' or 'none' (undocumented option) -sm % 02-27-98 use pinv() instead of inv() to rank order comps if ncomps < chans -sm % 04-28-98 added 'posact' and 'pca' flags -sm % 07-16-98 reduced length of randperm() for kurtosis subset calc. -se & sm % 07-19-98 fixed typo in weights def. above -tl & sm % 12-21-99 added 'specgram' option suggested by Michael Zibulevsky, UNM -sm % 12-22-99 fixed rand() sizing inefficiency on suggestion of Mike Spratling, UK -sm % 01-11-00 fixed rand() sizing bug on suggestion of Jack Foucher, Strasbourg -sm % 12-18-00 test for existence of Sig Proc Tlbx function 'specgram'; improve % 'specgram' option arguments -sm % 01-25-02 reformated help & license -ad % 01-25-02 lowered default lrate and block -ad % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [weights,sphere,meanvar,bias,signs,lrates,data,y] = runica(data,varargin) % NB: Now optionally returns activations as variable 'data' -sm 7/05 if nargin < 1 help runica return end [chans frames] = size(data); % determine the data size urchans = chans; % remember original data channels datalength = frames; if chans<2 fprintf('\nrunica() - data size (%d,%d) too small.\n\n', chans,frames); return end % %%%%%%%%%%%%%%%%%%%%%% Declare defaults used below %%%%%%%%%%%%%%%%%%%%%%%% % MAX_WEIGHT = 1e8; % guess that weights larger than this have blown up DEFAULT_STOP = 0.000001; % stop training if weight changes below this DEFAULT_ANNEALDEG = 60; % when angle change reaches this value, DEFAULT_ANNEALSTEP = 0.90; % anneal by multiplying lrate by this DEFAULT_EXTANNEAL = 0.98; % or this if extended-ICA DEFAULT_MAXSTEPS = 512; % ]top training after this many steps DEFAULT_MOMENTUM = 0.0; % default momentum weight DEFAULT_BLOWUP = 1000000000.0; % = learning rate has 'blown up' DEFAULT_BLOWUP_FAC = 0.8; % when lrate 'blows up,' anneal by this fac DEFAULT_RESTART_FAC = 0.9; % if weights blowup, restart with lrate % lower by this factor MIN_LRATE = 0.000001; % if weight blowups make lrate < this, quit MAX_LRATE = 0.1; % guard against uselessly high learning rate DEFAULT_LRATE = 0.00065/log(chans); % heuristic default - may need adjustment % for large or tiny data sets! % DEFAULT_BLOCK = floor(sqrt(frames/4)); % heuristic default DEFAULT_BLOCK = ceil(min(5*log(frames),0.3*frames)); % heuristic % - may need adjustment! % Extended-ICA option: DEFAULT_EXTENDED = 0; % default off DEFAULT_EXTBLOCKS = 1; % number of blocks per kurtosis calculation DEFAULT_NSUB = 1; % initial default number of assumed sub-Gaussians % for extended-ICA DEFAULT_EXTMOMENTUM = 0.5; % momentum term for computing extended-ICA kurtosis MAX_KURTSIZE = 6000; % max points to use in kurtosis calculation MIN_KURTSIZE = 2000; % minimum good kurtosis size (flag warning) SIGNCOUNT_THRESHOLD = 25; % raise extblocks when sign vector unchanged % after this many steps SIGNCOUNT_STEP = 2; % extblocks increment factor DEFAULT_SPHEREFLAG = 'on'; % use the sphere matrix as the default % starting weight matrix DEFAULT_INTERUPT = 'off'; % figure interuption DEFAULT_PCAFLAG = 'off'; % don't use PCA reduction DEFAULT_POSACTFLAG = 'off'; % don't use posact(), to save space -sm 7/05 DEFAULT_VERBOSE = 1; % write ascii info to calling screen DEFAULT_BIASFLAG = 1; % default to using bias in the ICA update rule % %%%%%%%%%%%%%%%%%%%%%%% Set up keyword default values %%%%%%%%%%%%%%%%%%%%%%%%% % if nargout < 2, fprintf('runica() - needs at least two output arguments.\n'); return end epochs = 1; % do not care how many epochs in data pcaflag = DEFAULT_PCAFLAG; sphering = DEFAULT_SPHEREFLAG; % default flags posactflag = DEFAULT_POSACTFLAG; verbose = DEFAULT_VERBOSE; logfile = []; block = DEFAULT_BLOCK; % heuristic default - may need adjustment! lrate = DEFAULT_LRATE; annealdeg = DEFAULT_ANNEALDEG; annealstep = 0; % defaults declared below nochange = NaN; momentum = DEFAULT_MOMENTUM; maxsteps = DEFAULT_MAXSTEPS; weights = 0; % defaults defined below ncomps = chans; biasflag = DEFAULT_BIASFLAG; interupt = DEFAULT_INTERUPT; extended = DEFAULT_EXTENDED; extblocks = DEFAULT_EXTBLOCKS; kurtsize = MAX_KURTSIZE; signsbias = 0.02; % bias towards super-Gaussian components extmomentum= DEFAULT_EXTMOMENTUM; % exp. average the kurtosis estimates nsub = DEFAULT_NSUB; wts_blowup = 0; % flag =1 when weights too large wts_passed = 0; % flag weights passed as argument % %%%%%%%%%% Collect keywords and values from argument list %%%%%%%%%%%%%%% % if (nargin> 1 & rem(nargin,2) == 0) fprintf('runica(): Even number of input arguments???') return end for i = 1:2:length(varargin) % for each Keyword Keyword = varargin{i}; Value = varargin{i+1}; if ~isstr(Keyword) fprintf('runica(): keywords must be strings') return end Keyword = lower(Keyword); % convert upper or mixed case to lower if strcmp(Keyword,'weights') | strcmp(Keyword,'weight') if isstr(Value) fprintf(... 'runica(): weights value must be a weight matrix or sphere') return else weights = Value; wts_passed =1; end elseif strcmp(Keyword,'ncomps') if isstr(Value) fprintf('runica(): ncomps value must be an integer') return end if ncomps < urchans & ncomps ~= Value fprintf('runica(): Use either PCA or ICA dimension reduction'); return end fprintf('*****************************************************************************************'); fprintf('************** WARNING: NCOMPS OPTION OFTEN DOES NOT RETURN ACCURATE RESULTS ************'); fprintf('************** WARNING: IF YOU FIND THE PROBLEM, PLEASE LET US KNOW ************'); fprintf('*****************************************************************************************'); ncomps = Value; if ~ncomps, ncomps = chans; end elseif strcmp(Keyword,'pca') if ncomps < urchans & ncomps ~= Value fprintf('runica(): Use either PCA or ICA dimension reduction'); return end if isstr(Value) fprintf(... 'runica(): pca value should be the number of principal components to retain') return end pcaflag = 'on'; ncomps = Value; if ncomps > chans | ncomps < 1, fprintf('runica(): pca value must be in range [1,%d]\n',chans) return end chans = ncomps; elseif strcmp(Keyword,'interupt') if ~isstr(Value) fprintf('runica(): interupt value must be on or off') return else Value = lower(Value); if ~strcmp(Value,'on') & ~strcmp(Value,'off'), fprintf('runica(): interupt value must be on or off') return end interupt = Value; end elseif strcmp(Keyword,'posact') if ~isstr(Value) fprintf('runica(): posact value must be on or off') return else Value = lower(Value); if ~strcmp(Value,'on') & ~strcmp(Value,'off'), fprintf('runica(): posact value must be on or off') return end posactflag = Value; end elseif strcmp(Keyword,'lrate') if isstr(Value) fprintf('runica(): lrate value must be a number') return end lrate = Value; if lrate>MAX_LRATE | lrate <0, fprintf('runica(): lrate value is out of bounds'); return end if ~lrate, lrate = DEFAULT_LRATE; end elseif strcmp(Keyword,'block') | strcmp(Keyword,'blocksize') if isstr(Value) fprintf('runica(): block size value must be a number') return end block = floor(Value); if ~block, block = DEFAULT_BLOCK; end elseif strcmp(Keyword,'stop') | strcmp(Keyword,'nochange') ... | strcmp(Keyword,'stopping') if isstr(Value) fprintf('runica(): stop wchange value must be a number') return end nochange = Value; elseif strcmp(Keyword,'logfile') if ~isstr(Value) fprintf('runica(): logfile value must be a string') return end logfile = Value; elseif strcmp(Keyword,'maxsteps') | strcmp(Keyword,'steps') if isstr(Value) fprintf('runica(): maxsteps value must be an integer') return end maxsteps = Value; if ~maxsteps, maxsteps = DEFAULT_MAXSTEPS; end if maxsteps < 0 fprintf('runica(): maxsteps value (%d) must be a positive integer',maxsteps) return end elseif strcmp(Keyword,'anneal') | strcmp(Keyword,'annealstep') if isstr(Value) fprintf('runica(): anneal step value (%2.4f) must be a number (0,1)',Value) return end annealstep = Value; if annealstep <=0 | annealstep > 1, fprintf('runica(): anneal step value (%2.4f) must be (0,1]',annealstep) return end elseif strcmp(Keyword,'annealdeg') | strcmp(Keyword,'degrees') if isstr(Value) fprintf('runica(): annealdeg value must be a number') return end annealdeg = Value; if ~annealdeg, annealdeg = DEFAULT_ANNEALDEG; elseif annealdeg > 180 | annealdeg < 0 fprintf('runica(): annealdeg (%3.1f) is out of bounds [0,180]',... annealdeg); return end elseif strcmp(Keyword,'momentum') if isstr(Value) fprintf('runica(): momentum value must be a number') return end momentum = Value; if momentum > 1.0 | momentum < 0 fprintf('runica(): momentum value is out of bounds [0,1]') return end elseif strcmp(Keyword,'sphering') | strcmp(Keyword,'sphereing') ... | strcmp(Keyword,'sphere') if ~isstr(Value) fprintf('runica(): sphering value must be on, off, or none') return else Value = lower(Value); if ~strcmp(Value,'on') & ~strcmp(Value,'off') & ~strcmp(Value,'none'), fprintf('runica(): sphering value must be on or off') return end sphering = Value; end elseif strcmp(Keyword,'bias') if ~isstr(Value) fprintf('runica(): bias value must be on or off') return else Value = lower(Value); if strcmp(Value,'on') biasflag = 1; elseif strcmp(Value,'off'), biasflag = 0; else fprintf('runica(): bias value must be on or off') return end end elseif strcmp(Keyword,'specgram') | strcmp(Keyword,'spec') if ~exist('specgram') < 2 % if ~exist or defined workspace variable fprintf(... 'runica(): MATLAB Sig. Proc. Toolbox function "specgram" not found.\n') return end if isstr(Value) fprintf('runica(): specgram argument must be a vector') return end srate = Value(1); if (srate < 0) fprintf('runica(): specgram srate (%4.1f) must be >=0',srate) return end if length(Value)>1 loHz = Value(2); if (loHz < 0 | loHz > srate/2) fprintf('runica(): specgram loHz must be >=0 and <= srate/2 (%4.1f)',srate/2) return end else loHz = 0; % default end if length(Value)>2 hiHz = Value(3); if (hiHz < loHz | hiHz > srate/2) fprintf('runica(): specgram hiHz must be >=loHz (%4.1f) and <= srate/2 (%4.1f)',loHz,srate/2) return end else hiHz = srate/2; % default end if length(Value)>3 Hzframes = Value(5); if (Hzframes<0 | Hzframes > size(data,2)) fprintf('runica(): specgram frames must be >=0 and <= data length (%d)',size(data,2)) return end else Hzframes = size(data,2); % default end if length(Value)>4 Hzwinlen = Value(4); if rem(Hzframes,Hzwinlen) % if winlen doesn't divide frames fprintf('runica(): specgram Hzinc must divide frames (%d)',Hzframes) return end else Hzwinlen = Hzframes; % default end Specgramflag = 1; % set flag to perform specgram() elseif strcmp(Keyword,'extended') | strcmp(Keyword,'extend') if isstr(Value) fprintf('runica(): extended value must be an integer (+/-)') return else extended = 1; % turn on extended-ICA extblocks = fix(Value); % number of blocks per kurt() compute if extblocks < 0 nsub = -1*fix(extblocks); % fix this many sub-Gauss comps elseif ~extblocks, extended = 0; % turn extended-ICA off elseif kurtsize>frames, % length of kurtosis calculation kurtsize = frames; if kurtsize < MIN_KURTSIZE fprintf(... 'runica() warning: kurtosis values inexact for << %d points.\n',... MIN_KURTSIZE); end end end elseif strcmp(Keyword,'verbose') if ~isstr(Value) fprintf('runica(): verbose flag value must be on or off') return elseif strcmp(Value,'on'), verbose = 1; elseif strcmp(Value,'off'), verbose = 0; else fprintf('runica(): verbose flag value must be on or off') return end else fprintf('runica(): unknown flag') return end end % %%%%%%%%%%%%%%%%%%%%%%%% Initialize weights, etc. %%%%%%%%%%%%%%%%%%%%%%%% % if ~annealstep, if ~extended, annealstep = DEFAULT_ANNEALSTEP; % defaults defined above else annealstep = DEFAULT_EXTANNEAL; % defaults defined above end end % else use annealstep from commandline if ~annealdeg, annealdeg = DEFAULT_ANNEALDEG - momentum*90; % heuristic if annealdeg < 0, annealdeg = 0; end end if ncomps > chans | ncomps < 1 fprintf('runica(): number of components must be 1 to %d.\n',chans); return end % %%%%%%%%%%%%%%%%%%%%% Check keyword values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if frames<chans, fprintf('runica(): data length (%d) < data channels (%d)!\n',frames,chans) return elseif block < 2, fprintf('runica(): block size %d too small!\n',block) return elseif block > frames, fprintf('runica(): block size exceeds data length!\n'); return elseif floor(epochs) ~= epochs, fprintf('runica(): data length is not a multiple of the epoch length!\n'); return elseif nsub > ncomps fprintf('runica(): there can be at most %d sub-Gaussian components!\n',ncomps); return end; if ~isempty(logfile) fid = fopen(logfile, 'w'); if fid == -1, error('Cannot open logfile for writing'); end; else fid = []; end; verb = verbose; if weights ~= 0, % initialize weights % starting weights are being passed to runica() from the commandline if chans>ncomps & weights ~=0, [r,c]=size(weights); if r~=ncomps | c~=chans, fprintf('runica(): weight matrix must have %d rows, %d columns.\n', ... chans,ncomps); return; end end icaprintf(verb,fid,'Using starting weight matrix named in argument list ...\n'); end; % % adjust nochange if necessary % if isnan(nochange) if ncomps > 32 nochange = 1E-7; nochangeupdated = 1; % for fprinting purposes else nochangeupdated = 1; % for fprinting purposes nochange = DEFAULT_STOP; end; else nochangeupdated = 0; end; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Process the data %%%%%%%%%%%%%%%%%%%%%%%%%% % icaprintf(verb,fid,'\nInput data size [%d,%d] = %d channels, %d frames/n', ... chans,frames,chans,frames); if strcmp(pcaflag,'on') icaprintf(verb,fid,'After PCA dimension reduction,\n finding '); else icaprintf(verb,fid,'Finding '); end if ~extended icaprintf(verb,fid,'%d ICA components using logistic ICA.\n',ncomps); else % if extended icaprintf(verb,fid,'%d ICA components using extended ICA.\n',ncomps); if extblocks > 0 icaprintf(verb,fid,'Kurtosis will be calculated initially every %d blocks using %d data points.\n',... extblocks, kurtsize); else icaprintf(verb,fid,'Kurtosis will not be calculated. Exactly %d sub-Gaussian components assumed.\n',nsub); end end icaprintf(verb,fid,'Decomposing %d frames per ICA weight ((%d)^2 = %d weights, %d frames)\n',... floor(frames/ncomps.^2),ncomps.^2,frames); icaprintf(verb,fid,'Initial learning rate will be %g, block size %d.\n',... lrate,block); if momentum>0, icaprintf(verb,fid,'Momentum will be %g.\n',momentum); end icaprintf(verb,fid,'Learning rate will be multiplied by %g whenever angledelta >= %g deg.\n', ... annealstep,annealdeg); if nochangeupdated icaprintf(verb,fid,'More than 32 channels: default stopping weight change 1E-7\n'); end; icaprintf(verb,fid,'Training will end when wchange < %g or after %d steps.\n', nochange,maxsteps); if biasflag, icaprintf(verb,fid,'Online bias adjustment will be used.\n'); else icaprintf(verb,fid,'Online bias adjustment will not be used.\n'); end % %%%%%%%%%%%%%%%%% Remove overall row means of data %%%%%%%%%%%%%%%%%%%%%%% % icaprintf(verb,fid,'Removing mean of each channel ...\n'); %BLGBLGBLG replaced % rowmeans = mean(data'); % data = data - rowmeans'*ones(1,frames); % subtract row means %BLGBLGBLG replacement starts rowmeans = mean(data,2)'; %BLG % data = data - rowmeans'*ones(1,frames); % subtract row means for iii=1:size(data,1) %avoids memory errors BLG data(iii,:)=data(iii,:)-rowmeans(iii); end %BLGBLGBLG replacement ends icaprintf(verb,fid,'Final training data range: %g to %g\n', min(min(data)),max(max(data))); % %%%%%%%%%%%%%%%%%%% Perform PCA reduction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmp(pcaflag,'on') icaprintf(verb,fid,'Reducing the data to %d principal dimensions...\n',ncomps); %BLGBLGBLG replaced %[eigenvectors,eigenvalues,data] = pcsquash(data,ncomps); % make data its projection onto the ncomps-dim principal subspace %BLGBLGBLG replacement starts %[eigenvectors,eigenvalues,data] = pcsquash(data,ncomps); % no need to re-subtract row-means, it was done a few lines above! PCdat2 = data'; % transpose data [PCn,PCp]=size(PCdat2); % now p chans,n time points PCdat2=PCdat2/PCn; PCout=data*PCdat2; clear PCdat2; [PCV,PCD] = eig(PCout); % get eigenvectors/eigenvalues [PCeigenval,PCindex] = sort(diag(PCD)); PCindex=rot90(rot90(PCindex)); PCEigenValues=rot90(rot90(PCeigenval))'; PCEigenVectors=PCV(:,PCindex); %PCCompressed = PCEigenVectors(:,1:ncomps)'*data; data = PCEigenVectors(:,1:ncomps)'*data; eigenvectors=PCEigenVectors; eigenvalues=PCEigenValues; %#ok<NASGU> clear PCn PCp PCout PCV PCD PCeigenval PCindex PCEigenValues PCEigenVectors %BLGBLGBLG replacement ends end % %%%%%%%%%%%%%%%%%%% Perform specgram transformation %%%%%%%%%%%%%%%%%%%%%%% % if exist('Specgramflag') == 1 % [P F T] = SPECGRAM(A,NFFT,Fs,WINDOW,NOVERLAP) % MATLAB Sig Proc Toolbox % Hzwinlen = fix(srate/Hzinc); % CHANGED FROM THIS 12/18/00 -sm Hzfftlen = 2^(ceil(log(Hzwinlen)/log(2))); % make FFT length next higher 2^k Hzoverlap = 0; % use sequential windows % % Get freqs and times from 1st channel analysis % [tmp,freqs,tms] = specgram(data(1,:),Hzfftlen,srate,Hzwinlen,Hzoverlap); fs = find(freqs>=loHz & freqs <= hiHz); icaprintf(verb,fid,'runica(): specified frequency range too narrow, exiting!\n'); specdata = reshape(tmp(fs,:),1,length(fs)*size(tmp,2)); specdata = [real(specdata) imag(specdata)]; % fprintf(' size(fs) = %d,%d\n',size(fs,1),size(fs,2)); % fprintf(' size(tmp) = %d,%d\n',size(tmp,1),size(tmp,2)); % % Loop through remaining channels % for ch=2:chans [tmp] = specgram(data(ch,:),Hzwinlen,srate,Hzwinlen,Hzoverlap); tmp = reshape((tmp(fs,:)),1,length(fs)*size(tmp,2)); specdata = [specdata;[real(tmp) imag(tmp)]]; % channels are rows end % % Print specgram confirmation and details % icaprintf(verb,fid,'Converted data to %d channels by %d=2*%dx%d points spectrogram data.\n',... chans,2*length(fs)*length(tms),length(fs),length(tms)); if length(fs) > 1 icaprintf(verb,fid,' Low Hz %g, high Hz %g, Hz incr %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),freqs(fs(2))-freqs(fs(1)),Hzwinlen); else icaprintf(verb,fid,' Low Hz %g, high Hz %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),Hzwinlen); end % % Replace data with specdata % data = specdata; datalength=size(data,2); end % %%%%%%%%%%%%%%%%%%% Perform sphering %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmp(sphering,'on'), %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% icaprintf(verb,fid,'Computing the sphering matrix...\n'); sphere = 2.0*inv(sqrtm(double(cov(data')))); % find the "sphering" matrix = spher() if ~weights, icaprintf(verb,fid,'Starting weights are the identity matrix ...\n'); weights = eye(ncomps,chans); % begin with the identity matrix else % weights given on commandline icaprintf(verb,fid,'Using starting weights named on commandline ...\n'); end icaprintf(verb,fid,'Sphering the data ...\n'); data = sphere*data; % decorrelate the electrode signals by 'sphereing' them elseif strcmp(sphering,'off') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~weights % is starting weights not given icaprintf(verb,fid,'Using the sphering matrix as the starting weight matrix ...\n'); icaprintf(verb,fid,'Returning the identity matrix in variable "sphere" ...\n'); sphere = 2.0*inv(sqrtm(cov(data'))); % find the "sphering" matrix = spher() weights = eye(ncomps,chans)*sphere; % begin with the identity matrix sphere = eye(chans); % return the identity matrix else % weights ~= 0 icaprintf(verb,fid,'Using starting weights from commandline ...\n'); icaprintf(verb,fid,'Returning the identity matrix in variable "sphere" ...\n'); sphere = eye(chans); % return the identity matrix end elseif strcmp(sphering,'none') sphere = eye(chans,chans);% return the identity matrix if ~weights icaprintf(verb,fid,'Starting weights are the identity matrix ...\n'); icaprintf(verb,fid,'Returning the identity matrix in variable "sphere" ...\n'); weights = eye(ncomps,chans); % begin with the identity matrix else % weights ~= 0 icaprintf(verb,fid,'Using starting weights named on commandline ...\n'); icaprintf(verb,fid,'Returning the identity matrix in variable "sphere" ...\n'); end icaprintf(verb,fid,'Returned variable "sphere" will be the identity matrix.\n'); end % %%%%%%%%%%%%%%%%%%%%%%%% Initialize ICA training %%%%%%%%%%%%%%%%%%%%%%%%% % lastt=fix((datalength/block-1)*block+1); BI=block*eye(ncomps,ncomps); delta=zeros(1,chans*ncomps); changes = []; degconst = 180./pi; startweights = weights; prevweights = startweights; oldweights = startweights; prevwtchange = zeros(chans,ncomps); oldwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); onesrow = ones(1,block); bias = zeros(ncomps,1); signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1 for k=1:nsub signs(k) = -1; end if extended & extblocks < 0, icaprintf(verb,fid,'Fixed extended-ICA sign assignments: '); for k=1:ncomps icaprintf(verb,fid,'%d ',signs(k)); end; icaprintf(verb,fid,'\n'); end signs = diag(signs); % make a diagonal matrix oldsigns = zeros(size(signs)); signcount = 0; % counter for same-signs signcounts = []; urextblocks = extblocks; % original value, for resets old_kk = zeros(1,ncomps); % for kurtosis momemtum % %%%%%%%% ICA training loop using the logistic sigmoid %%%%%%%%%%%%%%%%%%% % icaprintf(verb,fid,'Beginning ICA training ...'); if extended, icaprintf(verb,fid,' first training step may be slow ...\n'); else icaprintf(verb,fid,'\n'); end step=0; laststep=0; blockno = 1; % running block counter for kurtosis interrupts rand('state',sum(100*clock)); % set the random number generator state to % a position dependent on the system clock % interupt figure % --------------- if strcmpi(interupt, 'on') fig = figure('visible', 'off'); supergui( fig, {1 1}, [], {'style' 'text' 'string' 'Press button to interrupt runica()' }, ... {'style' 'pushbutton' 'string' 'Interupt' 'callback' 'setappdata(gcf, ''run'', 0);' } ); set(fig, 'visible', 'on'); setappdata(gcf, 'run', 1); if strcmpi(interupt, 'on') drawnow; end; end; %% Compute ICA Weights if biasflag & extended while step < maxsteps, %%% ICA step = pass through all the data %%%%%%%%% timeperm=randperm(datalength); % shuffle data order at each step for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%% if strcmpi(interupt, 'on') drawnow; flag = getappdata(fig, 'run'); if ~flag, if ~isempty(fid), fclose(fid); end; close; error('USER ABORT'); end; end; %% promote data block (only) to double to keep u and weights double u=weights*double(data(:,timeperm(t:t+block-1))) + bias*onesrow; y=tanh(u); weights = weights + lrate*(BI-signs*y*u'-u*u')*weights; bias = bias + lrate*sum((-2*y)')'; % for tanh() nonlin. if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%% weights = weights + momentum*prevwtchange; prevwtchange = weights-prevweights; prevweights = weights; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if max(max(abs(weights))) > MAX_WEIGHT wts_blowup = 1; change = nochange; end if ~wts_blowup % %%%%%%%%%%% Extended-ICA kurtosis estimation %%%%%%%%%%%%%%%%%%%%% %while step < maxsteps if extblocks > 0 & rem(blockno,extblocks) == 0, % recompute signs vector using kurtosis if kurtsize < frames % 12-22-99 rand() size suggestion by M. Spratling rp = fix(rand(1,kurtsize)*datalength); % pick random subset % Accout for the possibility of a 0 generation by rand ou = find(rp == 0); while ~isempty(ou) % 1-11-00 suggestion by J. Foucher rp(ou) = fix(rand(1,length(ou))*datalength); ou = find(rp == 0); end partact=weights*double(data(:,rp(1:kurtsize))); else % for small data sets, partact=weights*double(data); % use whole data end m2=mean(partact'.^2).^2; m4= mean(partact'.^4); kk= (m4./m2)-3.0; % kurtosis estimates if extmomentum kk = extmomentum*old_kk + (1.0-extmomentum)*kk; % use momentum old_kk = kk; end signs=diag(sign(kk+signsbias)); % pick component signs if signs == oldsigns, signcount = signcount+1; else signcount = 0; end oldsigns = signs; signcounts = [signcounts signcount]; if signcount >= SIGNCOUNT_THRESHOLD, extblocks = fix(extblocks * SIGNCOUNT_STEP);% make kurt() estimation signcount = 0; % less frequent if sign end % is not changing end % extblocks > 0 & . . . end % if extended & ~wts_blowup %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% blockno = blockno + 1; if wts_blowup break end end % for t=1:block:lastt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~wts_blowup oldwtchange = weights-oldweights; step=step+1; % %%%%%%% Compute and print weight and update angle changes %%%%%%%%% % lrates(1,step) = lrate; angledelta=0.; delta=reshape(oldwtchange,1,chans*ncomps); change=delta*delta'; end % %%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%% % if wts_blowup | isnan(change)|isinf(change), % if weights blow up, icaprintf(verb,fid,''); step = 0; % start again change = nochange; wts_blowup = 0; % re-initialize variables blockno = 1; lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate weights = startweights; % and original weight matrix oldweights = startweights; change = nochange; oldwtchange = zeros(chans,ncomps); delta=zeros(1,chans*ncomps); olddelta = delta; extblocks = urextblocks; prevweights = startweights; prevwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); bias = zeros(ncomps,1); signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1 for k=1:nsub signs(k) = -1; end signs = diag(signs); % make a diagonal matrix oldsigns = zeros(size(signs));; if lrate> MIN_LRATE r = rank(data); % determine if data rank is too low if r<ncomps icaprintf(verb,fid,'Data has rank %d. Cannot compute %d components.\n',... r,ncomps); return else icaprintf(verb,fid,... 'Lowering learning rate to %g and starting again.\n',lrate); end else icaprintf(verb,fid, ... 'runica(): QUITTING - weight matrix may not be invertible!\n'); return; end else % if weights in bounds % %%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%% % if step> 2 angledelta=acos((delta*olddelta')/sqrt(change*oldchange)); end places = -floor(log10(nochange)); icaprintf(verb,fid,'step %d - lrate %5f, wchange %8.8f, angledelta %4.1f deg\n', ... step, lrate, change, degconst*angledelta); % %%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % changes = [changes change]; oldweights = weights; % %%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if degconst*angledelta > annealdeg, lrate = lrate*annealstep; % anneal learning rate olddelta = delta; % accumulate angledelta until oldchange = change; % annealdeg is reached elseif step == 1 % on first step only olddelta = delta; % initialize oldchange = change; end % %%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if step >2 & change < nochange, % apply stopping rule laststep=step; step=maxsteps; % stop when weights stabilize elseif change > DEFAULT_BLOWUP, % if weights blow up, lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying end; % with a smaller learning rate end; % end if weights in bounds end; % end while step < maxsteps (ICA Training) %%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end %% Compute ICA Weights if biasflag & ~extended while step < maxsteps, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% timeperm=randperm(datalength); % shuffle data order at each step for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%% if strcmpi(interupt, 'on') drawnow; flag = getappdata(fig, 'run'); if ~flag, if ~isempty(fid), fclose(fid); end; close; error('USER ABORT'); end; end; u=weights*double(data(:,timeperm(t:t+block-1))) + bias*onesrow; y=1./(1+exp(-u)); weights = weights + lrate*(BI+(1-2*y)*u')*weights; bias = bias + lrate*sum((1-2*y)')'; % for logistic nonlin. % if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%% weights = weights + momentum*prevwtchange; prevwtchange = weights-prevweights; prevweights = weights; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if max(max(abs(weights))) > MAX_WEIGHT wts_blowup = 1; change = nochange; end blockno = blockno + 1; if wts_blowup break end end % for t=1:block:lastt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~wts_blowup oldwtchange = weights-oldweights; step=step+1; % %%%%%%% Compute and print weight and update angle changes %%%%%%%%% % lrates(1,step) = lrate; angledelta=0.; delta=reshape(oldwtchange,1,chans*ncomps); change=delta*delta'; end % %%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%% % if wts_blowup | isnan(change)|isinf(change), % if weights blow up, icaprintf(verb,fid,''); step = 0; % start again change = nochange; wts_blowup = 0; % re-initialize variables blockno = 1; lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate weights = startweights; % and original weight matrix oldweights = startweights; change = nochange; oldwtchange = zeros(chans,ncomps); delta=zeros(1,chans*ncomps); olddelta = delta; extblocks = urextblocks; prevweights = startweights; prevwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); bias = zeros(ncomps,1); if lrate> MIN_LRATE r = rank(data); % determine if data rank is too low if r<ncomps icaprintf(verb,fid,'Data has rank %d. Cannot compute %d components.\n',r,ncomps); return else icaprintf(verb,fid,'Lowering learning rate to %g and starting again.\n',lrate); end else icaprintf(verb,fid,'runica(): QUITTING - weight matrix may not be invertible!\n'); return; end else % if weights in bounds % %%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%% % if step> 2 angledelta=acos((delta*olddelta')/sqrt(change*oldchange)); end places = -floor(log10(nochange)); icaprintf(verb,fid,'step %d - lrate %5f, wchange %8.8f, angledelta %4.1f deg\n', ... step, lrate, change, degconst*angledelta); % %%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % changes = [changes change]; oldweights = weights; % %%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if degconst*angledelta > annealdeg, lrate = lrate*annealstep; % anneal learning rate olddelta = delta; % accumulate angledelta until oldchange = change; % annealdeg is reached elseif step == 1 % on first step only olddelta = delta; % initialize oldchange = change; end % %%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if step >2 & change < nochange, % apply stopping rule laststep=step; step=maxsteps; % stop when weights stabilize elseif change > DEFAULT_BLOWUP, % if weights blow up, lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying end; % with a smaller learning rate end; % end if weights in bounds end; % end while step < maxsteps (ICA Training) %%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end %% Compute ICA Weights if ~biasflag & extended while step < maxsteps, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% timeperm=randperm(datalength); % shuffle data order at each step through data for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%% if strcmpi(interupt, 'on') drawnow; flag = getappdata(fig, 'run'); if ~flag, if ~isempty(fid), fclose(fid); end; close; error('USER ABORT'); end; end; u=weights*double(data(:,timeperm(t:t+block-1))); % promote block to dbl y=tanh(u); % weights = weights + lrate*(BI-signs*y*u'-u*u')*weights; if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%% weights = weights + momentum*prevwtchange; prevwtchange = weights-prevweights; prevweights = weights; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if max(max(abs(weights))) > MAX_WEIGHT wts_blowup = 1; change = nochange; end if ~wts_blowup % %%%%%%%%%%% Extended-ICA kurtosis estimation %%%%%%%%%%%%%%%%%%%%% %while step < maxsteps if extblocks > 0 & rem(blockno,extblocks) == 0, % recompute signs vector using kurtosis if kurtsize < frames % 12-22-99 rand() size suggestion by M. Spratling rp = fix(rand(1,kurtsize)*datalength); % pick random subset % Accout for the possibility of a 0 generation by rand ou = find(rp == 0); while ~isempty(ou) % 1-11-00 suggestion by J. Foucher rp(ou) = fix(rand(1,length(ou))*datalength); ou = find(rp == 0); end partact=weights*double(data(:,rp(1:kurtsize))); else % for small data sets, partact=weights*double(data); % use whole data end m2=mean(partact'.^2).^2; m4= mean(partact'.^4); kk= (m4./m2)-3.0; % kurtosis estimates if extmomentum kk = extmomentum*old_kk + (1.0-extmomentum)*kk; % use momentum old_kk = kk; end signs=diag(sign(kk+signsbias)); % pick component signs if signs == oldsigns, signcount = signcount+1; else signcount = 0; end oldsigns = signs; signcounts = [signcounts signcount]; if signcount >= SIGNCOUNT_THRESHOLD, extblocks = fix(extblocks * SIGNCOUNT_STEP);% make kurt() estimation signcount = 0; % less frequent if sign end % is not changing end % extblocks > 0 & . . . end % if ~wts_blowup %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% blockno = blockno + 1; if wts_blowup break end end % for t=1:block:lastt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~wts_blowup oldwtchange = weights-oldweights; step=step+1; % %%%%%%% Compute and print weight and update angle changes %%%%%%%%% % lrates(1,step) = lrate; angledelta=0.; delta=reshape(oldwtchange,1,chans*ncomps); change=delta*delta'; end % %%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%% % if wts_blowup | isnan(change)|isinf(change), % if weights blow up, icaprintf(verb,fid,''); step = 0; % start again change = nochange; wts_blowup = 0; % re-initialize variables blockno = 1; lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate weights = startweights; % and original weight matrix oldweights = startweights; change = nochange; oldwtchange = zeros(chans,ncomps); delta=zeros(1,chans*ncomps); olddelta = delta; extblocks = urextblocks; prevweights = startweights; prevwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); bias = zeros(ncomps,1); signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1 for k=1:nsub signs(k) = -1; end signs = diag(signs); % make a diagonal matrix oldsigns = zeros(size(signs)); if lrate> MIN_LRATE r = rank(data); % find whether data rank is too low if r<ncomps icaprintf(verb,fid,'Data has rank %d. Cannot compute %d components.\n',... r,ncomps); return else icaprintf(verb,fid,... 'Lowering learning rate to %g and starting again.\n',lrate); end else icaprintf(verb,fid, ... 'runica(): QUITTING - weight matrix may not be invertible!\n'); return; end else % if weights in bounds % %%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%% % if step> 2 angledelta=acos((delta*olddelta')/sqrt(change*oldchange)); end places = -floor(log10(nochange)); icaprintf(verb,fid,'step %d - lrate %5f, wchange %8.8f, angledelta %4.1f deg\n', ... step, lrate, change, degconst*angledelta); % %%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % changes = [changes change]; oldweights = weights; % %%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if degconst*angledelta > annealdeg, lrate = lrate*annealstep; % anneal learning rate olddelta = delta; % accumulate angledelta until oldchange = change; % annealdeg is reached elseif step == 1 % on first step only olddelta = delta; % initialize oldchange = change; end % %%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if step >2 & change < nochange, % apply stopping rule laststep=step; step=maxsteps; % stop when weights stabilize elseif change > DEFAULT_BLOWUP, % if weights blow up, lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying end; % with a smaller learning rate end; % end if weights in bounds end; % end while step < maxsteps (ICA Training) %%%%%%%%%%%%%%%%%%%%%%%%% end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Compute ICA Weights if ~biasflag & ~extended while step < maxsteps, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% timeperm=randperm(datalength); % shuffle data order at each step for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%% if strcmpi(interupt, 'on') drawnow; flag = getappdata(fig, 'run'); if ~flag, if ~isempty(fid), fclose(fid); end; close; error('USER ABORT'); end; end; u=weights*double(data(:,timeperm(t:t+block-1))); y=1./(1+exp(-u)); % weights = weights + lrate*(BI+(1-2*y)*u')*weights; if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%% weights = weights + momentum*prevwtchange; prevwtchange = weights-prevweights; prevweights = weights; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if max(max(abs(weights))) > MAX_WEIGHT wts_blowup = 1; change = nochange; end blockno = blockno + 1; if wts_blowup break end end % for t=1:block:lastt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~wts_blowup oldwtchange = weights-oldweights; step=step+1; % %%%%%%% Compute and print weight and update angle changes %%%%%%%%% % lrates(1,step) = lrate; angledelta=0.; delta=reshape(oldwtchange,1,chans*ncomps); change=delta*delta'; end % %%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%% % if wts_blowup | isnan(change)|isinf(change), % if weights blow up, icaprintf(verb,fid,''); step = 0; % start again change = nochange; wts_blowup = 0; % re-initialize variables blockno = 1; lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate weights = startweights; % and original weight matrix oldweights = startweights; change = nochange; oldwtchange = zeros(chans,ncomps); delta=zeros(1,chans*ncomps); olddelta = delta; extblocks = urextblocks; prevweights = startweights; prevwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); bias = zeros(ncomps,1); if lrate> MIN_LRATE r = rank(data); % find whether data rank is too low if r<ncomps icaprintf(verb,fid,'Data has rank %d. Cannot compute %d components.\n',... r,ncomps); return else icaprintf(verb,fid,... 'Lowering learning rate to %g and starting again.\n',lrate); end else icaprintf(verb,fid, ... 'runica(): QUITTING - weight matrix may not be invertible!\n'); return; end else % if weights in bounds % %%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%% % if step> 2 angledelta=acos((delta*olddelta')/sqrt(change*oldchange)); end places = -floor(log10(nochange)); icaprintf(verb,fid,'step %d - lrate %5f, wchange %8.8f, angledelta %4.1f deg\n', ... step, lrate, change, degconst*angledelta); % %%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % changes = [changes change]; oldweights = weights; % %%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if degconst*angledelta > annealdeg, lrate = lrate*annealstep; % anneal learning rate olddelta = delta; % accumulate angledelta until oldchange = change; % annealdeg is reached elseif step == 1 % on first step only olddelta = delta; % initialize oldchange = change; end % %%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if step >2 & change < nochange, % apply stopping rule laststep=step; step=maxsteps; % stop when weights stabilize elseif change > DEFAULT_BLOWUP, % if weights blow up, lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying end; % with a smaller learning rate end; % end if weights in bounds end; % end while step < maxsteps (ICA Training) %%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end %% Finalize Computed Data for Output if strcmpi(interupt, 'on') close(fig); end; if ~laststep laststep = step; end; lrates = lrates(1,1:laststep); % truncate lrate history vector % %%%%%%%%%%%%%% Orient components towards max positive activation %%%%%% % if nargout > 6 | strcmp(posactflag,'on') % make activations from sphered and pca'd data; -sm 7/05 % add back the row means removed from data before sphering if strcmp(pcaflag,'off') sr = sphere * rowmeans'; for r = 1:ncomps data(r,:) = data(r,:)+sr(r); % add back row means end data = weights*data; % OK in single else ser = sphere*eigenvectors(:,1:ncomps)'*rowmeans'; for r = 1:ncomps data(r,:) = data(r,:)+ser(r); % add back row means end data = weights*data; % OK in single end; end % % NOTE: Now 'data' are the component activations = weights*sphere*raw_data % % %%%%%%%%%%%%%% If pcaflag, compose PCA and ICA matrices %%%%%%%%%%%%%%% % if strcmp(pcaflag,'on') icaprintf(verb,fid,'Composing the eigenvector, weights, and sphere matrices\n'); icaprintf(verb,fid,' into a single rectangular weights matrix; sphere=eye(%d)\n'... ,chans); weights= weights*sphere*eigenvectors(:,1:ncomps)'; sphere = eye(urchans); end % %%%%%% Sort components in descending order of max projected variance %%%% % icaprintf(verb,fid,'Sorting components in descending order of mean projected variance ...\n'); % %%%%%%%%%%%%%%%%%%%% Find mean variances %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % meanvar = zeros(ncomps,1); % size of the projections if ncomps == urchans % if weights are square . . . winv = inv(weights*sphere); else icaprintf(verb,fid,'Using pseudo-inverse of weight matrix to rank order component projections.\n'); winv = pinv(weights*sphere); end % % compute variances without backprojecting to save time and memory -sm 7/05 % meanvar = sum(winv.^2).*sum((data').^2)/((chans*frames)-1); % from Rey Ramirez 8/07 % %%%%%%%%%%%%%% Sort components by mean variance %%%%%%%%%%%%%%%%%%%%%%%% % [sortvar, windex] = sort(meanvar); windex = windex(ncomps:-1:1); % order large to small meanvar = meanvar(windex); % %%%%%%%%%%%% re-orient max(abs(activations)) to >=0 ('posact') %%%%%%%% % if strcmp(posactflag,'on') % default is now off to save processing and memory icaprintf(verb,fid,'Making the max(abs(activations)) positive ...\n'); [tmp ix] = max(abs(data')); % = max abs activations signsflipped = 0; for r=1:ncomps if sign(data(r,ix(r))) < 0 if nargout>6 % if activations are to be returned (only) data(r,:) = -1*data(r,:); % flip activations so max(abs()) is >= 0 end winv(:,r) = -1*winv(:,r); % flip component maps signsflipped = 1; end end if signsflipped == 1 weights = pinv(winv)*inv(sphere); % re-invert the component maps end % [data,winvout,weights] = posact(data,weights); % overwrite data with activations % changes signs of activations (now = data) and weights % to make activations (data) net rms-positive % can call this outside of runica() - though it is inefficient! end % %%%%%%%%%%%%%%%%%%%%% Filter data using final weights %%%%%%%%%%%%%%%%%% % if nargout>6, % if activations are to be returned icaprintf(verb,fid,'Permuting the activation wave forms ...\n'); data = data(windex,:); % data is now activations -sm 7/05 else clear data end weights = weights(windex,:);% reorder the weight matrix bias = bias(windex); % reorder them signs = diag(signs); % vectorize the signs matrix signs = signs(windex); % reorder them if ~isempty(fid), fclose(fid); end; % close logfile % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % return % printing functions % ------------------ function icaprintf(verb,fid, varargin); if verb if ~isempty(fid) fprintf(fid, varargin{:}); end; fprintf(varargin{:}); end;
github
ZijingMao/baselineeegtest-master
jader.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/jader.m
11,455
utf_8
8b74fa9e0345ee0857e1e564b74dd872
% jader() - blind separation of real signals using JADE (v1.5, Dec. 1997). % % Usage: % >> B = jader(X); % >> B = jader(X,m); % % Notes: % 1) If X is an nxT data matrix (n sensors, T samples) then % B=jader(X) is a nxn separating matrix such that S=B*X is an nxT % matrix of estimated source signals. % 2) If B=jader(X,m), then B has size mxn so that only m sources are % extracted. This is done by restricting the operation of jader % to the m first principal components. % 3) Also, the rows of B are ordered such that the columns of pinv(B) % are in order of decreasing norm; this has the effect that the % `most energetically significant' components appear first in the % rows of S=B*X. % % Author: Jean-Francois Cardoso ([email protected]) % Quick notes (more at the end of this file) % % o this code is for REAL-valued signals. An implementation of JADE % for both real and complex signals is also available from % http://sig.enst.fr/~cardoso/stuff.html % % o This algorithm differs from the first released implementations of % JADE in that it has been optimized to deal more efficiently % 1) with real signals (as opposed to complex) % 2) with the case when the ICA model does not necessarily hold. % % o There is a practical limit to the number of independent % components that can be extracted with this implementation. Note % that the first step of JADE amounts to a PCA with dimensionality % reduction from n to m (which defaults to n). In practice m % cannot be `very large' (more than 40, 50, 60... depending on % available memory) % % o See more notes, references and revision history at the end of % this file and more stuff on the WEB % http://sig.enst.fr/~cardoso/stuff.html % % o This code is supposed to do a good job! Please report any % problem to [email protected] % Copyright : Jean-Francois Cardoso. [email protected] function B = jadeR(X,m) verbose = 1 ; % Set to 0 for quiet operation % Finding the number of sources [n,T] = size(X); if nargin==1, m=n ; end; % Number of sources defaults to # of sensors if m>n , fprintf('jade -> Do not ask more sources than sensors here!!!\n'), return,end if verbose, fprintf('jade -> Looking for %d sources\n',m); end ; % Self-commenting code %===================== if verbose, fprintf('jade -> Removing the mean value\n'); end X = X - mean(X')' * ones(1,T); %%% whitening & projection onto signal subspace % =========================================== if verbose, fprintf('jade -> Whitening the data\n'); end [U,D] = eig((X*X')/T) ; [puiss,k] = sort(diag(D)) ; rangeW = n-m+1:n ; % indices to the m most significant directions scales = sqrt(puiss(rangeW)) ; % scales W = diag(1./scales) * U(1:n,k(rangeW))' ; % whitener iW = U(1:n,k(rangeW)) * diag(scales) ; % its pseudo-inverse X = W*X; %%% Estimation of the cumulant matrices. % ==================================== if verbose, fprintf('jade -> Estimating cumulant matrices\n'); end dimsymm = (m*(m+1))/2; % Dim. of the space of real symm matrices nbcm = dimsymm ; % number of cumulant matrices CM = zeros(m,m*nbcm); % Storage for cumulant matrices R = eye(m); %% Qij = zeros(m); % Temp for a cum. matrix Xim = zeros(1,m); % Temp Xjm = zeros(1,m); % Temp scale = ones(m,1)/T ; % for convenience %% I am using a symmetry trick to save storage. I should write a %% short note one of these days explaining what is going on here. %% Range = 1:m ; % will index the columns of CM where to store the cum. mats. for im = 1:m Xim = X(im,:) ; Qij = ((scale* (Xim.*Xim)) .* X ) * X' - R - 2 * R(:,im)*R(:,im)' ; CM(:,Range) = Qij ; Range = Range + m ; for jm = 1:im-1 Xjm = X(jm,:) ; Qij = ((scale * (Xim.*Xjm) ) .*X ) * X' - R(:,im)*R(:,jm)' - R(:,jm)*R(:,im)' ; CM(:,Range) = sqrt(2)*Qij ; Range = Range + m ; end ; end; %%% joint diagonalization of the cumulant matrices %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Init if 1, %% Init by diagonalizing a *single* cumulant matrix. It seems to save %% some computation time `sometimes'. Not clear if initialization is %% a good idea since Jacobi rotations are very efficient. if verbose, fprintf('jade -> Initialization of the diagonalization\n'); end [V,D] = eig(CM(:,1:m)); % For instance, this one for u=1:m:m*nbcm, % updating accordingly the cumulant set given the init CM(:,u:u+m-1) = CM(:,u:u+m-1)*V ; end; CM = V'*CM; else, %% The dont-try-to-be-smart init V = eye(m) ; % la rotation initiale end; seuil = 1/sqrt(T)/100; % A statistically significant threshold encore = 1; sweep = 0; updates = 0; g = zeros(2,nbcm); gg = zeros(2,2); G = zeros(2,2); c = 0 ; s = 0 ; ton = 0 ; toff = 0 ; theta = 0 ; %% Joint diagonalization proper if verbose, fprintf('jade -> Contrast optimization by joint diagonalization\n'); end while encore, encore=0; if verbose, fprintf('jade -> Sweep #%d\n',sweep); end sweep=sweep+1; for p=1:m-1, for q=p+1:m, Ip = p:m:m*nbcm ; Iq = q:m:m*nbcm ; %%% computation of Givens angle g = [ CM(p,Ip)-CM(q,Iq) ; CM(p,Iq)+CM(q,Ip) ]; gg = g*g'; ton = gg(1,1)-gg(2,2); toff = gg(1,2)+gg(2,1); theta = 0.5*atan2( toff , ton+sqrt(ton*ton+toff*toff) ); %%% Givens update if abs(theta) > seuil, encore = 1 ; updates = updates + 1; c = cos(theta); s = sin(theta); G = [ c -s ; s c ] ; pair = [p;q] ; V(:,pair) = V(:,pair)*G ; CM(pair,:) = G' * CM(pair,:) ; CM(:,[Ip Iq]) = [ c*CM(:,Ip)+s*CM(:,Iq) -s*CM(:,Ip)+c*CM(:,Iq) ] ; %% fprintf('jade -> %3d %3d %12.8f\n',p,q,s); end%%of the if end%%of the loop on q end%%of the loop on p end%%of the while loop if verbose, fprintf('jade -> Total of %d Givens rotations\n',updates); end %%% A separating matrix % =================== B = V'*W ; %%% We permut its rows to get the most energetic components first. %%% Here the **signals** are normalized to unit variance. Therefore, %%% the sort is according to the norm of the columns of A = pinv(B) if verbose, fprintf('jade -> Sorting the components\n',updates); end A = iW*V ; [vars,keys] = sort(sum(A.*A)) ; B = B(keys,:); B = B(m:-1:1,:) ; % Is this smart ? % Signs are fixed by forcing the first column of B to have % non-negative entries. if verbose, fprintf('jade -> Fixing the signs\n',updates); end b = B(:,1) ; signs = sign(sign(b)+0.1) ; % just a trick to deal with sign=0 B = diag(signs)*B ; return ; % To do. % - Implement a cheaper/simpler whitening (is it worth it?) % % Revision history: % %- V1.5, Dec. 24 1997 % - The sign of each row of B is determined by letting the first % element be positive. % %- V1.4, Dec. 23 1997 % - Minor clean up. % - Added a verbose switch % - Added the sorting of the rows of B in order to fix in some % reasonable way the permutation indetermination. See note 2) % below. % %- V1.3, Nov. 2 1997 % - Some clean up. Released in the public domain. % %- V1.2, Oct. 5 1997 % - Changed random picking of the cumulant matrix used for % initialization to a deterministic choice. This is not because % of a better rationale but to make the ouput (almost surely) % deterministic. % - Rewrote the joint diag. to take more advantage of Matlab's % tricks. % - Created more dummy variables to combat Matlab's loose memory % management. % %- V1.1, Oct. 29 1997. % Made the estimation of the cumulant matrices more regular. This % also corrects a buglet... % %- V1.0, Sept. 9 1997. Created. % % Main reference: % @article{CS-iee-94, % title = "Blind beamforming for non {G}aussian signals", % author = "Jean-Fran\c{c}ois Cardoso and Antoine Souloumiac", % HTML = "ftp://sig.enst.fr/pub/jfc/Papers/iee.ps.gz", % journal = "IEE Proceedings-F", % month = dec, number = 6, pages = {362-370}, volume = 140, year = 1993} % % Notes: % ====== % % Note 1) % % The original Jade algorithm/code deals with complex signals in % Gaussian noise white and exploits an underlying assumption that the % model of independent components actually holds. This is a % reasonable assumption when dealing with some narrowband signals. % In this context, one may i) seriously consider dealing precisely % with the noise in the whitening process and ii) expect to use the % small number of significant eigenmatrices to efficiently summarize % all the 4th-order information. All this is done in the JADE % algorithm. % % In this implementation, we deal with real-valued signals and we do % NOT expect the ICA model to hold exactly. Therefore, it is % pointless to try to deal precisely with the additive noise and it % is very unlikely that the cumulant tensor can be accurately % summarized by its first n eigen-matrices. Therefore, we consider % the joint diagonalization of the whole set of eigen-matrices. % However, in such a case, it is not necessary to compute the % eigenmatrices at all because one may equivalently use `parallel % slices' of the cumulant tensor. This part (computing the % eigen-matrices) of the computation can be saved: it suffices to % jointly diagonalize a set of cumulant matrices. Also, since we are % dealing with reals signals, it becomes easier to exploit the % symmetries of the cumulants to further reduce the number of % matrices to be diagonalized. These considerations, together with % other cheap tricks lead to this version of JADE which is optimized % (again) to deal with real mixtures and to work `outside the model'. % As the original JADE algorithm, it works by minimizing a `good set' % of cumulants. % % Note 2) % % The rows of the separating matrix B are resorted in such a way that % the columns of the corresponding mixing matrix A=pinv(B) are in % decreasing order of (Euclidian) norm. This is a simple, `almost % canonical' way of fixing the indetermination of permutation. It % has the effect that the first rows of the recovered signals (ie the % first rows of B*X) correspond to the most energetic *components*. % Recall however that the source signals in S=B*X have unit variance. % Therefore, when we say that the observations are unmixed in order % of decreasing energy, the energetic signature is found directly as % the norm of the columns of A=pinv(B). % % Note 3) % % In experiments where JADE is run as B=jadeR(X,m) with m varying in % range of values, it is nice to be able to test the stability of the % decomposition. In order to help in such a test, the rows of B can % be sorted as described above. We have also decided to fix the sign % of each row in some arbitrary but fixed way. The convention is % that the first element of each row of B is positive. % % % Note 4) % % Contrary to many other ICA algorithms, JADE (or least this version) % does not operate on the data themselves but on a statistic (the % full set of 4th order cumulant). This is represented by the matrix % CM below, whose size grows as m^2 x m^2 where m is the number of % sources to be extracted (m could be much smaller than n). As a % consequence, (this version of) JADE will probably choke on a % `large' number of sources. Here `large' depends mainly on the % available memory and could be something like 40 or so. One of % these days, I will prepare a version of JADE taking the `data' % option rather than the `statistic' option. % % % JadeR.m ends here.
github
ZijingMao/baselineeegtest-master
spectopo.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/spectopo.m
39,269
utf_8
d00f04d05186f8d52eacbe5b0edb6af6
% spectopo() - Plot the mean log spectrum of a set of data epochs at all channels % as a bundle of traces. At specified frequencies, plot the relative % topographic distribution of power. If available, uses pwelch() from % the Matlab signal processing toolbox, else the EEGLAB spec() function. % Plots the mean spectrum for all of the supplied data, not just % the pre-stimulus baseline. % Usage: % >> spectopo(data, frames, srate); % >> [spectra,freqs,speccomp,contrib,specstd] = ... % spectopo(data, frames, srate, 'key1','val1', 'key2','val2' ...); % Inputs: % data = If 2-D (nchans,time_points); % may be a continuous single epoch, % else a set of concatenated data epochs, else a 3-D set of data % epochs (nchans,frames,epochs) % frames = frames per epoch {default|0 -> data length} % srate = sampling rate per channel (Hz) % % Optional 'keyword',[argument] input pairs: % 'freq' = [float vector (Hz)] vector of frequencies at which to plot power % scalp maps, or else a single frequency at which to plot component % contributions at a single channel (see also 'plotchan'). % 'chanlocs' = [electrode locations filename or EEG.chanlocs structure]. % For format, see >> topoplot example % 'limits' = [xmin xmax ymin ymax cmin cmax] axis limits. Sets x, y, and color % axis limits. May omit final values or use NaNs. % Ex: [0 60 NaN NaN -10 10], [0 60], ... % Default color limits are symmetric around 0 and are different % for each scalp map {default|all NaN's: from the data limits} % 'title' = [quoted string] plot title {default: none} % 'freqfac' = [integer] ntimes to oversample -> frequency resolution {default: 2} % 'nfft' = [integer] length to zero-pad data to. Overwrites 'freqfac' above. % 'winsize' = [integer] window size in data points {default: from data} % 'overlap' = [integer] window overlap in data points {default: 0} % 'percent' = [float 0 to 100] percent of the data to sample for computing the % spectra. Values < 100 speed up the computation. {default: 100}. % 'freqrange' = [min max] frequency range to plot. Changes x-axis limits {default: % 1 Hz for the min and Nyquist (srate/2) for the max. If specified % power distribution maps are plotted, the highest mapped frequency % determines the max freq}. % 'reref' = ['averef'|'off'] convert data to average reference {default: 'off'} % 'mapnorm' = [float vector] If 'data' contain the activity of an independant % component, this parameter should contain its scalp map. In this case % the spectrum amplitude will be scaled to component RMS scalp power. % Useful for comparing component strengths {default: none} % 'boundaries' = data point indices of discontinuities in the signal {default: none} % 'plot' = ['on'|'off'] 'off' -> disable plotting {default: 'on'} % 'rmdc' = ['on'|'off'] 'on' -> remove DC {default: 'off'} % 'plotmean' = ['on'|'off'] 'on' -> plot the mean channel spectrum {default: 'off'} % 'plotchans' = [integer array] plot only specific channels {default: all} % % Optionally plot component contributions: % 'weights' = ICA unmixing matrix. Here, 'freq' (above) must be a single frequency. % ICA maps of the N ('nicamaps') components that account for the most % power at the selected frequency ('freq') are plotted along with % the spectra of the selected channel ('plotchan') and components % ('icacomps'). % 'plotchan' = [integer] channel at which to compute independent conmponent % contributions at the selected frequency ('freq'). If 0, plot RMS % power at all channels. {defatul|[] -> channel with highest power % at specified 'freq' (above)). Do not confuse with % 'plotchans' which select channels for plotting. % 'mapchans' = [int vector] channels to plot in topoplots {default: all} % 'mapframes'= [int vector] frames to plot {default: all} % 'nicamaps' = [integer] number of ICA component maps to plot {default: 4}. % 'icacomps' = [integer array] indices of ICA component spectra to plot ([] -> all). % 'icamode' = ['normal'|'sub'] in 'sub' mode, instead of computing the spectra of % individual ICA components, the function computes the spectrum of % the data minus their contributions {default: 'normal'} % 'icamaps' = [integer array] force plotting of selected ICA compoment maps % {default: [] = the 'nicamaps' largest contributing components}. % 'icawinv' = [float array] inverse component weight or mixing matrix. Normally, % this is computed by inverting the ICA unmixing matrix 'weights' (above). % However, if any components were removed from the supplied 'weights'mapchans % then the component maps will not be correctly drawn and the 'icawinv' % matrix should be supplied here {default: from component 'weights'} % 'memory' = ['low'|'high'] a 'low' setting will use less memory for computing % component activities, will take longer {default: 'high'} % % Replotting options: % 'specdata' = [freq x chan array ] spectral data % 'freqdata' = [freq] array of frequencies % % Topoplot options: % other 'key','val' options are propagated to topoplot() for map display % (See >> help topoplot) % % Outputs: % spectra = (nchans,nfreqs) power spectra (mean power over epochs), in dB % freqs = frequencies of spectra (Hz) % speccomp = component spectra (ncomps,nfreqs). Warning, only the function % only computes the spectrum of the components given as input using % the 'icacomps' parameter. Other component spectrum are filled % with 0. % contrib = contribution of each component (if 'icamode' is 'normal', relative % variance, if 'icamode' is 'sub', percent variance accounted for) % specstd = spectrum standard deviation in dB % % Notes: The original input format is still functional for backward compatibility. % psd() has been replaced by pwelch() (see Matlab note 24750 on their web site) % % Authors: Scott Makeig, Arnaud Delorme & Marissa Westerfield, % SCCN/INC/UCSD, La Jolla, 3/01 % % See also: timtopo(), envtopo(), tftopo(), topoplot() % Copyright (C) 3/01 Scott Makeig & Arnaud Delorme & Marissa Westerfield, 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-01 added limits arg -sm % 01-25-02 reformated help & license -ad % 02-15-02 scaling by epoch number line 108 - ad, sm & lf % 03-15-02 add all topoplot options -ad % 03-18-02 downsampling factor to speed up computation -ad % 03-27-02 downsampling factor exact calculation -ad % 04-03-02 added axcopy -sm % Uses: MATLAB pwelch(), changeunits(), topoplot(), textsc() function [eegspecdB,freqs,compeegspecdB,resvar,specstd] = spectopo(data,frames,srate,varargin) % formerly: ... headfreqs,chanlocs,limits,titl,freqfac, percent, varargin) icadefs; LOPLOTHZ = 1; % low Hz to plot FREQFAC = 2; % approximate frequencies/Hz (default) allcolors = { [0 0.7500 0.7500] [1 0 0] [0 0.5000 0] [0 0 1] [0.2500 0.2500 0.2500] [0.7500 0.7500 0] [0.7500 0 0.7500] }; % colors from real plots }; if nargin<3 help spectopo return end if nargin <= 3 | isstr(varargin{1}) % 'key' 'val' sequence fieldlist = { 'freq' 'real' [] [] ; 'specdata' 'real' [] [] ; 'freqdata' 'real' [] [] ; 'chanlocs' '' [] [] ; 'freqrange' 'real' [0 srate/2] [] ; 'memory' 'string' {'low','high'} 'high' ; 'plot' 'string' {'on','off'} 'off' ; 'plotmean' 'string' {'on','off'} 'off' ; 'title' 'string' [] ''; 'limits' 'real' [] [nan nan nan nan nan nan]; 'freqfac' 'integer' [] FREQFAC; 'percent' 'real' [0 100] 100 ; 'reref' 'string' { 'averef','off','no' } 'off' ; 'boundaries' 'integer' [] [] ; 'nfft' 'integer' [1 Inf] [] ; 'winsize' 'integer' [1 Inf] [] ; 'overlap' 'integer' [1 Inf] 0 ; 'icamode' 'string' { 'normal','sub' } 'normal' ; 'weights' 'real' [] [] ; 'mapnorm' 'real' [] [] ; 'plotchan' 'integer' [1:size(data,1)] [] ; 'plotchans' 'integer' [1:size(data,1)] [] ; 'nicamaps' 'integer' [] 4 ; 'icawinv' 'real' [] [] ; 'icacomps' 'integer' [] [] ; 'icachansind' 'integer' [] [1:size(data,1)] ; % deprecated 'icamaps' 'integer' [] [] ; 'rmdc' 'string' {'on','off'} 'off'; 'mapchans' 'integer' [1:size(data,1)] [] 'mapframes' 'integer' [1:size(data,2)] []}; [g varargin] = finputcheck( varargin, fieldlist, 'spectopo', 'ignore'); if isstr(g), error(g); end; if ~isempty(g.freqrange), g.limits(1:2) = g.freqrange; end; if ~isempty(g.weights) if isempty(g.freq) | length(g.freq) > 2 if ~isempty(get(0,'currentfigure')) & strcmp(get(gcf, 'tag'), 'spectopo'), close(gcf); end; error('spectopo(): for computing component contribution, one must specify a (single) frequency'); end; end; else if ~isnumeric(data) error('spectopo(): Incorrect call format (see >> help spectopo).') end if ~isnumeric(frames) | round(frames) ~= frames error('spectopo(): Incorrect call format (see >> help spectopo).') end if ~isnumeric(srate) % 3rd arg must be the sampling rate in Hz error('spectopo(): Incorrect call format (see >> help spectopo).') end if nargin > 3, g.freq = varargin{1}; else g.freq = []; end; if nargin > 4, g.chanlocs = varargin{2}; else g.chanlocs = []; end; if nargin > 5, g.limits = varargin{3}; else g.limits = [nan nan nan nan nan nan]; end; if nargin > 6, g.title = varargin{4}; else g.title = ''; end; if nargin > 7, g.freqfac = varargin{5}; else g.freqfac = FREQFAC; end; if nargin > 8, g.percent = varargin{6}; else g.percent = 100; end; if nargin > 10, g.reref = 'averef'; else g.reref = 'off'; end; g.weights = []; g.icamaps = []; end; if g.percent > 1 g.percent = g.percent/100; % make it from 0 to 1 end; if ~isempty(g.freq) & isempty(g.chanlocs) error('spectopo(): needs channel location information'); end; if isempty(g.weights) && ~isempty(g.plotchans) data = data(g.plotchans,:); if ~isempty(g.chanlocs) g.chanlocs = g.chanlocs(g.plotchans); end; end; if strcmpi(g.rmdc, 'on') data = data - repmat(mean(data,2), [ 1 size(data,2) 1]); end data = reshape(data, size(data,1), size(data,2)*size(data,3)); if frames == 0 frames = size(data,2); % assume one epoch end %if ~isempty(g.plotchan) & g.plotchan == 0 & strcmpi(g.icamode, 'sub') % if ~isempty(get(0,'currentfigure')) & strcmp(get(gcf, 'tag'), 'spectopo'), close(gcf); end; % error('Cannot plot data component at all channels (option not implemented)'); %end; if ~isempty(g.freq) & min(g.freq)<0 if ~isempty(get(0,'currentfigure')) & strcmp(get(gcf, 'tag'), 'spectopo'), close(gcf); end; fprintf('spectopo(): freqs must be >=0 Hz\n'); return end g.chanlocs2 = g.chanlocs; if ~isempty(g.specdata) eegspecdB = g.specdata; freqs = g.freqdata; else epochs = round(size(data,2)/frames); if frames*epochs ~= size(data,2) error('Spectopo: non-integer number of epochs'); end if ~isempty(g.weights) ncompsori = size(g.weights,1); if isempty(g.icawinv) g.icawinv = pinv(g.weights); % maps end; if ~isempty(g.icacomps) g.weights = g.weights(g.icacomps, :); g.icawinv = g.icawinv(:,g.icacomps); else g.icacomps = [1:size(g.weights,1)]; end; end; compeegspecdB = []; resvar = NaN; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute channel spectra using pwelch() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% epoch_subset = ones(1,epochs); if g.percent ~= 1 & epochs == 1 fprintf('Selecting the first %2.1f%% of data for analysis...\n', g.percent*100); frames = round(size(data,2)*g.percent); data = data(:, 1:frames); g.boundaries(find(g.boundaries > frames)) = []; if ~isempty(g.boundaries) g.boundaries(end+1) = frames; end; end; if g.percent ~= 1 & epochs > 1 epoch_subset = zeros(1,epochs); nb = ceil( g.percent*epochs); while nb>0 index = ceil(rand*epochs); if ~epoch_subset(index) epoch_subset(index) = 1; nb = nb-1; end; end; epoch_subset = find(epoch_subset == 1); fprintf('Randomly selecting %d of %d data epochs for analysis...\n', length(epoch_subset),epochs); else epoch_subset = find(epoch_subset == 1); end; if isempty(g.weights) %%%%%%%%%%%%%%%%%%%%%%%%%%% % compute data spectra %%%%%%%%%%%%%%%%%%%%%%%%%%% fprintf('Computing spectra') [eegspecdB freqs specstd] = spectcomp( data, frames, srate, epoch_subset, g); if ~isempty(g.mapnorm) % normalize by component map RMS power (if data contain 1 component disp('Scaling spectrum by component RMS of scalp map power'); eegspecdB = sqrt(mean(g.mapnorm.^4)) * eegspecdB; % the idea is to take the RMS of the component activity (compact) projected at each channel % spec = sqrt( power(g.mapnorm(1)*compact).^2 + power(g.mapnorm(2)*compact).^2 + ...) % spec = sqrt( g.mapnorm(1)^4*power(compact).^2 + g.mapnorm(1)^4*power(compact).^2 + ...) % spec = sqrt( g.mapnorm(1)^4 + g.mapnorm(1)^4 + ... )*power(compact) end; tmpc = find(eegspecdB(:,1)); % > 0 power chans tmpindices = find(eegspecdB(:,1) == 0); if ~isempty(tmpindices) zchans = int2str(tmpindices); % 0-power chans else zchans = []; end; if length(tmpc) ~= size(eegspecdB,1) fprintf('\nWarning: channels [%s] have 0 values, so will be omitted from the display', ... zchans); eegspecdB = eegspecdB(tmpc,:); if ~isempty(specstd), specstd = specstd(tmpc,:); end if ~isempty(g.chanlocs) g.chanlocs2 = g.chanlocs(tmpc); end end; eegspecdB = 10*log10(eegspecdB); specstd = 10*log10(specstd); fprintf('\n'); else % compute data spectrum if isempty(g.plotchan) | g.plotchan == 0 fprintf('Computing spectra') [eegspecdB freqs specstd] = spectcomp( data, frames, srate, epoch_subset, g); fprintf('\n'); % log below else fprintf('Computing spectra at specified channel') g.reref = 'off'; [eegspecdB freqs specstd] = spectcomp( data(g.plotchan,:), frames, srate, epoch_subset, g); fprintf('\n'); % log below end; g.reref = 'off'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % select channels and spectra %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isempty(g.plotchan) % find channel of minimum power [tmp indexfreq] = min(abs(g.freq-freqs)); [tmp g.plotchan] = min(eegspecdB(:,indexfreq)); fprintf('Channel %d has maximum power at %g\n', g.plotchan, g.freq); eegspecdBtoplot = eegspecdB(g.plotchan, :); elseif g.plotchan == 0 fprintf('Computing RMS power at all channels\n'); eegspecdBtoplot = sqrt(mean(eegspecdB.^2,1)); % RMS before log as for components else eegspecdBtoplot = eegspecdB; end; tmpc = find(eegspecdB(:,1)); % > 0 power chans zchans = int2str(find(eegspecdB(:,1) == 0)); % 0-power chans if length(tmpc) ~= size(eegspecdB,1) fprintf('\nWarning: channels [%s] have 0 values, so will be omitted from the display', ... zchans); eegspecdB = eegspecdB(tmpc,:); if ~isempty(specstd), specstd = specstd(tmpc,:); end if ~isempty(g.chanlocs) g.chanlocs2 = g.chanlocs(tmpc); end end; specstd = 10*log10(specstd); eegspecdB = 10*log10(eegspecdB); eegspecdBtoplot = 10*log10(eegspecdBtoplot); %%%%%%%%%%%%%%%%%%%%%%%%%%% % compute component spectra %%%%%%%%%%%%%%%%%%%%%%%%%%% newweights = g.weights; if strcmp(g.memory, 'high') & strcmp(g.icamode, 'normal') fprintf('Computing component spectra: ') [compeegspecdB freqs] = spectcomp( newweights*data(:,:), frames, srate, epoch_subset, g); else % in case out of memory error, multiply conmponent sequencially if strcmp(g.icamode, 'sub') & ~isempty(g.plotchan) & g.plotchan == 0 % scan all electrodes fprintf('Computing component spectra at each channel: ') for index = 1:size(data,1) g.plotchan = index; [compeegspecdB(:,:,index) freqs] = spectcomp( data, frames, srate, epoch_subset, g, newweights); end; g.plotchan = 0; else fprintf('Computing component spectra: ') [compeegspecdB freqs] = spectcomp( data, frames, srate, epoch_subset, g, newweights); end; end; fprintf('\n'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % rescale spectra with respect to projection (rms = root mean square) % all channels: component_i power = rms(inverseweigths(component_i)^2)*power(activation_component_i); % one channel: component_i power = inverseweigths(channel_j,component_i)^2)*power(activation_component_i); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmpi(g.icamode, 'normal') for index = 1:size(compeegspecdB,1) if g.plotchan == 0 % normalize by component scalp map power compeegspecdB(index,:) = 10*log10( sqrt(mean(g.icawinv(:,index).^4)) * compeegspecdB(index,:) ); else compeegspecdB(index,:) = 10*log10( g.icawinv(g.plotchan,index)^2 * compeegspecdB(index,:) ); end; end; else % already spectrum of data-components compeegspecdB = 10*log10( compeegspecdB ); end; %%%%%%%%%%%%%%%%%%%%%%%%%%% % select components to plot %%%%%%%%%%%%%%%%%%%%%%%%%%% if isempty(g.icamaps) [tmp indexfreq] = min(abs(g.freq-freqs)); g.icafreqsval = compeegspecdB(:, indexfreq); [g.icafreqsval g.icamaps] = sort(g.icafreqsval); if strcmp(g.icamode, 'normal') g.icamaps = g.icamaps(end:-1:1); g.icafreqsval = g.icafreqsval(end:-1:1); end; if g.nicamaps < length(g.icamaps), g.icamaps = g.icamaps(1:g.nicamaps); end; else [tmp indexfreq] = min(abs(g.freq-freqs)); g.icafreqsval = compeegspecdB(g.icamaps, indexfreq); end; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute axis and caxis g.limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if length(g.limits)<1 | isnan(g.limits(1)) g.limits(1) = LOPLOTHZ; end if ~isempty(g.freq) if length(g.limits)<2 | isnan(g.limits(2)) maxheadfreq = max(g.freq); if rem(maxheadfreq,5) ~= 0 g.limits(2) = 5*ceil(maxheadfreq/5); else g.limits(2) = maxheadfreq*1.1; end end g.freq = sort(g.freq); % Determine topoplot frequencies freqidx = zeros(1,length(g.freq)); % Do not interpolate between freqs for f=1:length(g.freq) [tmp fi] = min(abs(freqs-g.freq(f))); freqidx(f)=fi; end else % no freq specified if isnan(g.limits(2)) g.limits(2) = srate/2; end; end; [tmp maxfreqidx] = min(abs(g.limits(2)-freqs)); % adjust max frequency [tmp minfreqidx] = min(abs(g.limits(1)-freqs)); % adjust min frequency if length(g.limits)<3|isnan(g.limits(3)) reallimits(1) = min(min(eegspecdB(:,minfreqidx:maxfreqidx))); else reallimits(1) = g.limits(3); end if length(g.limits)<4|isnan(g.limits(4)) reallimits(2) = max(max(eegspecdB(:,minfreqidx:maxfreqidx))); dBrange = reallimits(2)-reallimits(1); % expand range a bit beyond data g.limits reallimits(1) = reallimits(1)-dBrange/7; reallimits(2) = reallimits(2)+dBrange/7; else reallimits(2) = g.limits(4); end if length(g.limits)<5 % default caxis plotting g.limits g.limits(5) = nan; end if length(g.limits)<6 g.limits(6) = nan; end if isnan(g.limits(5))+isnan(g.limits(6)) == 1 fprintf('spectopo(): limits 5 and 6 must either be given or nan\n'); return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % plot spectrum of each channel %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmpi(g.plot, 'on') mainfig = gca; axis off; if ~isempty(g.freq) specaxes = sbplot(3,4,[5 12], 'ax', mainfig); end; if isempty(g.weights) %pl=plot(freqs(1:maxfreqidx),eegspecdB(:,1:maxfreqidx)'); % old command if strcmpi(g.plotmean, 'on'), specdata = mean(eegspecdB,1); % average channels else specdata = eegspecdB; end; for index = 1:size(specdata,1) % scan channels tmpcol = allcolors{mod(index, length(allcolors))+1}; command = [ 'disp(''Channel ' int2str(index) ''')' ]; pl(index)=plot(freqs(1:maxfreqidx),specdata(index,1:maxfreqidx)', ... 'color', tmpcol, 'ButtonDownFcn', command); hold on; end; else for index = 1:size(eegspecdBtoplot,1) tmpcol = allcolors{mod(index, length(allcolors))+1}; command = [ 'disp(''Channel ' int2str(g.plotchan(index)) ''')' ]; pl(index)=plot(freqs(1:maxfreqidx),eegspecdBtoplot(index,1:maxfreqidx)', ... 'color', tmpcol, 'ButtonDownFcn', command); hold on; end; end; set(pl,'LineWidth',2); set(gca,'TickLength',[0.02 0.02]); try, axis([freqs(minfreqidx) freqs(maxfreqidx) reallimits(1) reallimits(2)]); catch, disp('Could not adjust axis'); end; xl=xlabel('Frequency (Hz)'); set(xl,'fontsize',AXES_FONTSIZE_L); % yl=ylabel('Rel. Power (dB)'); yl=ylabel('Power 10*log_{10}(\muV^{2}/Hz)'); set(yl,'fontsize',AXES_FONTSIZE_L); set(gca,'fontsize',AXES_FONTSIZE_L) box off; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % plot component contribution % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% colrs = {'r','b','g','m','c'}; % component spectra trace colors if ~isempty(g.weights) if strcmpi(g.plot, 'on') if strcmpi(g.icamode, 'sub') set(pl,'LineWidth',5, 'color', 'k'); else set(pl, 'linewidth', 2, 'color', 'k'); end; hold on; for f=1:length(g.icamaps) colr = colrs{mod((f-1),5)+1}; command = [ 'disp(''Component ' int2str(g.icamaps(f)) ''')' ]; pl2(index)=plot(freqs(1:maxfreqidx),compeegspecdB(g.icamaps(f),1:maxfreqidx)', ... 'color', colr, 'ButtonDownFcn', command); hold on; end othercomps = setdiff_bc(1:size(compeegspecdB,1), g.icamaps); if ~isempty(othercomps) for index = 1:length(othercomps) tmpcol = allcolors{mod(index, length(allcolors))+1}; command = [ 'disp(''Component ' int2str(othercomps(index)) ''')' ]; pl(index)=plot(freqs(1:maxfreqidx),compeegspecdB(othercomps(index),1:maxfreqidx)', ... 'color', tmpcol, 'ButtonDownFcn', command); hold on; end; end; if length(g.limits)<3|isnan(g.limits(3)) newaxis = axis; newaxis(3) = min(newaxis(3), min(min(compeegspecdB(:,1:maxfreqidx)))); newaxis(4) = max(newaxis(4), max(max(compeegspecdB(:,1:maxfreqidx)))); axis(newaxis); end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % indicate component contribution % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% maxdatadb = max(eegspecdBtoplot(:,freqidx(1))); [tmp indexfreq] = min(abs(g.freq-freqs)); for index = 1:length(g.icacomps) if strcmp(g.icamode, 'normal') % note: maxdatadb = eegspecdBtoplot (RMS power of data) resvar(index) = 100*exp(-(maxdatadb-compeegspecdB(index, indexfreq))/10*log(10)); fprintf('Component %d percent relative variance:%6.2f\n', g.icacomps(index), resvar(index)); else if g.plotchan == 0 resvartmp = []; for chan = 1:size(eegspecdB,1) % scan channels resvartmp(chan) = 100 - 100*exp(-(eegspecdB(chan,freqidx(1))-compeegspecdB(index, indexfreq, chan))/10*log(10)); end; resvar(index) = mean(resvartmp); % mean contribution for all channels stdvar(index) = std(resvartmp); fprintf('Component %d percent variance accounted for:%6.2f ± %3.2f\n', ... g.icacomps(index), resvar(index), stdvar(index)); else resvar(index) = 100 - 100*exp(-(maxdatadb-compeegspecdB(index, indexfreq))/10*log(10)); fprintf('Component %d percent variance accounted for:%6.2f\n', g.icacomps(index), resvar(index)); end; end; end; % for icamode=sub and plotchan == 0 -> take the RMS power of all channels % ----------------------------------------------------------------------- if ndims(compeegspecdB) == 3 compeegspecdB = exp( compeegspecdB/10*log(10) ); compeegspecdB = sqrt(mean(compeegspecdB.^2,3)); % RMS before log (dim1=comps, dim2=freqs, dim3=chans) compeegspecdB = 10*log10( compeegspecdB ); end; end; if ~isempty(g.freq) & strcmpi(g.plot, 'on') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % plot vertical lines through channel trace bundle at each headfreq %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isempty(g.weights) for f=1:length(g.freq) hold on; plot([freqs(freqidx(f)) freqs(freqidx(f))], ... [min(eegspecdB(:,freqidx(f))) max(eegspecdB(:,freqidx(f)))],... 'k','LineWidth',2.5); end; else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % plot vertical line at comp analysis freq %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% mincompdB = min([min(eegspecdB(:,freqidx(1))) min(compeegspecdB(:,freqidx(1)))]); maxcompdB = max([max(eegspecdB(:,freqidx(1))) max(compeegspecdB(:,freqidx(1)))]); hold on; plot([freqs(freqidx(1)) freqs(freqidx(1))],[mincompdB maxcompdB],'k', 'LineWidth',2.5); end %%%%%%%%%%%%%%%%%%%%%%%%%% % create axis for topoplot %%%%%%%%%%%%%%%%%%%%%%%%%% tmpmainpos = get(gca, 'position'); headax = zeros(1,length(g.freq)); for f=1:length(g.freq)+length(g.icamaps) headax(f) = sbplot(3,length(g.freq)+length(g.icamaps),f, 'ax', mainfig); axis([-1 1 -1 1]); %axis x coords and use tmppos = get(headax(f), 'position'); allaxcoords(f) = tmppos(1); allaxuse(f) = 0; end large = sbplot(1,1,1, 'ax', mainfig); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute relative positions on plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(g.weights) freqnormpos = tmpmainpos(1) + tmpmainpos(3)*(freqs(freqidx(1))-g.limits(1))/(g.limits(2)-g.limits(1)); for index = 1:length(g.icamaps)+1 [realpos(index) allaxuse] = closestplot( freqnormpos, allaxcoords, allaxuse ); end; % put the channel plot a liitle bit higher tmppos = get(headax(realpos(1)), 'position'); tmppos(2) = tmppos(2)+0.04; set(headax(realpos(1)), 'position', tmppos); else realpos = 1:length(g.freq); % indices giving order of plotting positions end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % plot connecting lines using changeunits() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for f=1:length(g.freq)+length(g.icamaps) if ~isempty(g.weights) if f>length(g.freq) % special case of ICA components from = changeunits([freqs(freqidx(1)),g.icafreqsval(f-1)],specaxes,large); %g.icafreqsval contains the sorted frequency values at the specified frequency else from = changeunits([freqs(freqidx(f)),maxcompdB],specaxes,large); end; else from = changeunits([freqs(freqidx(f)),max(eegspecdB(:,freqidx(f)))],specaxes,large); end; pos = get(headax(realpos(f)),'position'); to = changeunits([0,0],headax(realpos(f)),large)+[0 -min(pos(3:4))/2.5]; hold on; if f<=length(g.freq) colr = 'k'; else colr = colrs{mod((f-2),5)+1}; end li(realpos(f)) = plot([from(1) to(1)],[from(2) to(2)],colr,'LineWidth',PLOT_LINEWIDTH_S); axis([0 1 0 1]); axis off; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % plot selected channel head using topoplot() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fprintf('Plotting scalp distributions: ') for f=1:length(g.freq) axes(headax(realpos(f))); topodata = eegspecdB(:,freqidx(f))-nan_mean(eegspecdB(:,freqidx(f))); if isnan(g.limits(5)), maplimits = 'absmax'; else maplimits = [g.limits(5) g.limits(6)]; end; % % If 1 channel in g.plotchan % if ~isempty(g.plotchan) & g.plotchan ~= 0 % if ~isempty(varargin) % if there are extra topoplot() flags % topoplot(g.plotchan,g.chanlocs,'electrodes','off', ... % 'style', 'blank', 'emarkersize1chan', 10, varargin{:}); % else topoplot(g.plotchan,g.chanlocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10); % end if isstruct(g.chanlocs) tl=title(g.chanlocs(g.plotchan).labels); else tl=title([ 'c' int2str(g.plotchan)]); end; else % plot all channels in g.plotchans if isempty(g.mapframes) | g.mapframes == 0 g.mapframes = 1:size(eegspecdB,1); % default to plotting all chans end if ~isempty(varargin) topoplot(topodata(g.mapframes),g.chanlocs2,'maplimits',maplimits, varargin{:}); else topoplot(topodata(g.mapframes),g.chanlocs2,'maplimits',maplimits); end if f<length(g.freq) tl=title([num2str(freqs(freqidx(f)), '%3.1f')]); else tl=title([num2str(freqs(freqidx(f)), '%3.1f') ' Hz']); end end; set(tl,'fontsize',AXES_FONTSIZE_L); axis square; drawnow fprintf('.'); end; fprintf('\n'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % plot independent components %%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(g.weights) % use headaxe from 2 to end (reserved earlier) if realpos(1) == max(realpos), plotcolbar(g); end; % make the line with the scalp topoplot thicker than others set(li(realpos(1)), 'linewidth', 2.5); if isempty(g.mapchans) | g.mapchans == 0 g.mapchans = 1:size(g.icawinv,1); % default to plotting all chans end for index = 1:length(g.icamaps) axes(headax(realpos(index+1))); compnum = g.icamaps(index); topoplot(g.icawinv(g.mapchans,compnum).^2,g.chanlocs,varargin{:}); tl=title(int2str(g.icacomps(compnum))); set(tl,'fontsize',16); axis square; drawnow try, if strcmpi(g.icamode, 'normal') set(gca, 'userdata', ['text(-0.6, -0.6, ''Rel. Var.: ' sprintf('%6.2f', resvar(g.icacomps(compnum))) ''');'] ); else set(gca, 'userdata', ['text(-0.6, -0.6, ''PVAF: ' sprintf('%6.2f', resvar(g.icacomps(compnum))) ''');'] ); end; catch, end; if realpos(index+1) == max(realpos), plotcolbar(g); end; end; else plotcolbar(g); end; end; %%%%%%%%%%%%%%%% % Draw title %%%%%%%%%%%%%%%% if ~isempty(g.title) & strcmpi(g.plot, 'on') tl = textsc(g.title); set(tl,'fontsize',15) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % return component spectrum %%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(g.weights) & nargout >= 3 tmp = compeegspecdB; compeegspecdB = zeros(ncompsori, size(tmp,2)); compeegspecdB(g.icacomps,:) = tmp; end; %%%%%%%%%%%%%%%% % Turn on axcopy (disabled to allow to click on curves) %%%%%%%%%%%%%%%% if strcmpi(g.plot, 'on') disp('Click on each trace for channel/component index'); axcopy(gcf, 'if ~isempty(get(gca, ''''userdata'''')), eval(get(gca, ''''userdata'''')); end;'); % will not erase the commands for the curves end; %%%%%%%%%%%%%%%% % Plot color bar %%%%%%%%%%%%%%%% function plotcolbar(g) cb=cbar; pos = get(cb,'position'); set(cb,'position',[pos(1) pos(2) 0.03 pos(4)]); set(cb,'fontsize',12); try if isnan(g.limits(5)) ticks = get(cb,'ytick'); [tmp zi] = find(ticks == 0); ticks = [ticks(1) ticks(zi) ticks(end)]; set(cb,'ytick',ticks); set(cb,'yticklabel',strvcat('-',' ','+')); end catch, end; % in a single channel is plotted %%%%%%%%%%%%%%%%%%%%%%% % function closest plot %%%%%%%%%%%%%%%%%%%%%%% function [index, usedplots] = closestplot(xpos, xcentercoords, usedplots); notused = find(usedplots == 0); xcentercoords = xcentercoords(notused); [tmp index] = min(abs(xcentercoords-xpos)); index = notused(index); usedplots(index) = 1; return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function computing spectrum %%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [eegspecdB, freqs, specstd] = spectcomp( data, frames, srate, epoch_subset, g, newweights); if exist('newweights') == 1 nchans = size(newweights,1); else nchans = size(data,1); end; %fftlength = 2^round(log(srate)/log(2))*g.freqfac; if isempty(g.winsize) winlength = max(pow2(nextpow2(frames)-3),4); %*2 since diveded by 2 later winlength = min(winlength, 512); winlength = max(winlength, 256); winlength = min(winlength, frames); else winlength = g.winsize; end; if isempty(g.nfft) fftlength = 2^(nextpow2(winlength))*g.freqfac; else fftlength = g.nfft; end; % usepwelch = 1; usepwelch = license('checkout','Signal_Toolbox'); % 5/22/2014 Ramon % if ~license('checkout','Signal_Toolbox'), if ~usepwelch, fprintf('\nSignal processing toolbox (SPT) absent: spectrum computed using the pwelch()\n'); fprintf('function from Octave which is suposedly 100%% compatible with the Matlab pwelch function\n'); end; fprintf(' (window length %d; fft length: %d; overlap %d):\n', winlength, fftlength, g.overlap); for c=1:nchans % scan channels or components if exist('newweights') == 1 if strcmp(g.icamode, 'normal') tmpdata = newweights(c,:)*data; % component activity else % data - component contribution tmpdata = data(g.plotchan,:) - (g.icawinv(g.plotchan,c)*newweights(c,:))*data; end; else tmpdata = data(c,:); % channel activity end; if strcmp(g.reref, 'averef') tmpdata = averef(tmpdata); end; for e=epoch_subset if isempty(g.boundaries) if usepwelch [tmpspec,freqs] = pwelch(matsel(tmpdata,frames,0,1,e),... winlength,g.overlap,fftlength,srate); else [tmpspec,freqs] = spec(matsel(tmpdata,frames,0,1,e),fftlength,srate,... winlength,g.overlap); end; %[tmpspec,freqs] = psd(matsel(tmpdata,frames,0,1,e),fftlength,srate,... % winlength,g.overlap); if c==1 & e==epoch_subset(1) eegspec = zeros(nchans,length(freqs)); specstd = zeros(nchans,length(freqs)); end eegspec(c,:) = eegspec(c,:) + tmpspec'; specstd(c,:) = specstd(c,:) + tmpspec'.^2; else g.boundaries = round(g.boundaries); for n=1:length(g.boundaries)-1 if g.boundaries(n+1) - g.boundaries(n) >= winlength % ignore segments of less than winlength if usepwelch [tmpspec,freqs] = pwelch(tmpdata(e,g.boundaries(n)+1:g.boundaries(n+1)),... winlength,g.overlap,fftlength,srate); else [tmpspec,freqs] = spec(tmpdata(e,g.boundaries(n)+1:g.boundaries(n+1)),... fftlength,srate,winlength,g.overlap); end; if exist('eegspec') ~= 1 eegspec = zeros(nchans,length(freqs)); specstd = zeros(nchans,length(freqs)); end eegspec(c,:) = eegspec(c,:) + tmpspec'* ... ((g.boundaries(n+1)-g.boundaries(n)+1)/g.boundaries(end)); specstd(c,:) = eegspec(c,:) + tmpspec'.^2 * ... ((g.boundaries(n+1)-g.boundaries(n)+1)/g.boundaries(end)); end; end end; end fprintf('.') end n = length(epoch_subset); eegspecdB = eegspec/n; % normalize by the number of sections if n>1 % normalize standard deviation by the number of sections specstd = sqrt( (specstd + eegspec.^2/n)/(n-1) ); else specstd = []; end; return;
github
ZijingMao/baselineeegtest-master
loadavg.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/loadavg.m
10,977
utf_8
eab4ed6a06ccdcb41d04203ec4f0b489
% loadavg() - loading eeg average data file from Neuroscan into % matlab. % Usage: % >> [signal, variance, chan_names, ... % pnts, rate, xmin, xmax] = loadavg( filename, version ); % Input: % filename - input Neuroscan .avg file % version - [1 or 2] function version. Default is 2 which scales % the data properly. % % Output: % signal - output signal % variance - variance of the signal % chan_names - array that represent the name of the electrodes % pnts - number of data points % srate - sampling rate % xmin - ERP onset time % xmax - ERP final time % % Example: % % load data into the array named 'signal' % [signal]=loadavg( 'test.avg' ); % % plot the signal for the first electrode % plot( signal(1,:) ); % % Author: Arnaud Delorme (v1), Yang Zhang (v2) % 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 % Average binary file format % Average data is stored as 4-byte floats in vectored format for each % channel. Each channel has a 5-byte header that is no longer used. Thus, % after the main file header, there is an unused 5-byte header followed by % erp.pnts of 4-byte floating point numbers for the first channel; then a % 5-byte header for channel two followed by erp.pnts*sizeof(float) bytes, % etc. Therefore, the total number of bytes after the main header is: % erp.nchannels * (5 + erp.pnts*sizeof(float)). To scale a data point to % microvolts, multiply by the channel-specific calibration factor (i.e., for % electrode j: channel[j]->calib) and divide by the number of sweeps in the % average (i.e., channel[j]->n). function [signal, variance, chan_names, pnts, rate, xmin, xmax]=loadavg( FILENAME,version) if nargin<1 help loadavg return; end; if nargin < 2 || version == 2 disp('Reading using method 2'); [signal, variance, chan_names, pnts, rate, xmin, xmax]=loadavg_bcl( FILENAME ); signal = signal'; return; end; disp('Reading using method 1'); %if isempty(find(FILENAME=='.')) FILENAME=[FILENAME '.eeg']; end; BOOL='int16'; ULONG='int32'; FLOAT='float32'; fid=fopen(FILENAME,'r','ieee-le'); if fid<0 fprintf(2,['Error LOADEEG: File ' FILENAME ' not found\n']); return; end; S_nsweeps_offset_total = 362; S_nsweeps_offset_accepted = 364; S_pnts_offset = 368; S_nchans_offset = 370; S_variance_offset = 375; S_rate_offset = 376; S_xmin_offset = 505; S_xmax_offset = 509; packed_sizeof_SETUP = 900; % read general part of the erp header and set variables % ----------------------------------------------------- %erp = fread(fid, 362, 'uchar'); % skip the firsts 368 bytes %nsweeps = fread(fid, 1, 'ushort'); % number of sweeps %erp = fread(fid, 4, 'uchar'); % skip 4 bytes %pnts= fread(fid, 1, 'ushort'); % number of point per waveform %chan= fread(fid, 1, 'ushort'); % number of channels %erp = fread(fid, 4, 'uchar'); % skip 4 bytes %rate= fread(fid, 1, 'ushort'); % sample rate (Hz) %erp = fread(fid, 127, 'uchar'); % skip 125 bytes %xmin= fread(fid, 1, 'float32'); % in s %xmax= fread(fid, 1, 'float32'); % in s %erp = fread(fid, 387, 'uchar'); % skip 387 bytes % read # of channels, # of samples, variance flag, and real time bounds % --------------------------------------------------------------------- fseek(fid, S_nsweeps_offset_accepted, 'bof'); nsweeps = fread(fid, 1, 'ushort'); if nsweeps == 0 fseek(fid, S_nsweeps_offset_total, 'bof'); nsweeps = fread(fid, 1, 'ushort'); end; fseek(fid, S_pnts_offset, 'bof'); pnts = fread(fid, 1, 'ushort'); fseek(fid, S_nchans_offset, 'bof'); chan = fread(fid, 1, 'ushort'); fseek(fid, S_variance_offset, 'bof'); variance_flag = fread(fid, 1, 'uchar'); fseek(fid, S_rate_offset, 'bof'); rate = fread(fid, 1, 'ushort'); fseek(fid, S_xmin_offset, 'bof'); xmin = fread(fid, 1, 'float32'); fseek(fid, S_xmax_offset, 'bof'); xmax = fread(fid, 1, 'float32'); fseek(fid, packed_sizeof_SETUP, 'bof'); fprintf('number of channels : %d\n', chan); fprintf('number of points per trial : %d\n', pnts); fprintf('sampling rate (Hz) : %f\n', rate); fprintf('xmin (s) : %f\n', xmin); fprintf('xmax (s) : %f\n', xmax); fprintf('number of trials (s) : %d\n', nsweeps); if nsweeps == 0, nsweeps = 1; end; % read electrode configuration % ---------------------------- fprintf('Electrode configuration\n'); for elec = 1:chan channel_label_tmp = fread(fid, 10, 'uchar'); chan_names(elec,:) = channel_label_tmp'; for index = 2:9 if chan_names(elec,index) == 0 chan_names(elec,index)=' '; end; end; erp = fread(fid, 47-10, 'uchar'); baseline(elec) = fread(fid, 1, 'ushort'); erp = fread(fid, 10, 'uchar'); sensitivity(elec) = fread(fid, 1, 'float32'); erp = fread(fid, 8, 'uchar'); calib(elec) = fread(fid, 1, 'float32'); fprintf('%s: baseline: %d\tsensitivity: %f\tcalibration: %f\n', ... char(chan_names(elec,1:4)), baseline(elec), sensitivity(elec), calib(elec)); factor(elec) = calib(elec) * sensitivity(elec) / 204.8; end; xsize = chan * pnts; buf_size = chan * pnts ; % size in shorts count_selected = 1; fprintf('Reserving array (can take some time)\n'); signal = zeros( chan, pnts*nsweeps); fprintf('Array reserved, scanning file\n'); signal = zeros(pnts, chan); variance = zeros(pnts, chan); for elec = 1:chan % skip sweeps header and read data % -------------------------------- fseek(fid, 5, 'cof'); signal(:, elec) = fread(fid, pnts, 'float32') * factor(elec) / nsweeps; end; if variance_flag for elec = 1:chan variance(:, elec) = fread(fid, pnts, 'float32'); end; else variance = 'novariance'; end; signal = signal'; variance = variance'; fclose(fid); return; function [signal, variance, chan_names, pnts, rate, xmin, xmax]=loadavg_bcl(FILENAME,chanNameList) %writed by allen zhang based on EEGLAB's loadavg.m %2009-11-25 % NENU,CHANGCHUN,CHINA % update by Yang Zhang %2011-2-28 % NENU,Changchun, CHINA % revised by Yang Zhang % 2011-4-6 %using automatic routine to identifiy the type of the avg file to get the true nsweeps parameter if ~exist('chanNameList','var') chanNameList={'all'}; end try fid=fopen(FILENAME,'r','ieee-le'); % read general part of the erp header and set variables % ----------------------------------------------------- fseek(fid, 362, 'cof');% skip the firsts 362 from BOF (368 bytes in orginal comment?) % disp(ftell(fid));% 360 bytes % hdr.nsweeps = fread(fid, 1, 'ushort'); % disp(ftell(fid));% 362 % hdr.compsweeps = fread(fid, 1, 'ushort');% the exact sweep numbers for eeg and single subject avg file| in grand avg file it represents the number of subjects % hdr.acceptcnt = fread(fid, 1, 'ushort');% number of accepted sweeps also the exact sweep numbers for grand avg file % hdr.rejectcnt = fread(fid, 1, 'ushort');%number of rejected sweeps % disp(ftell(fid));% 368 compsweeps = fread(fid, 1, 'ushort');% the exact sweeps numbers for eeg file| in Grand avg file it represented number of subjects acceptcnt = fread(fid, 1, 'ushort');% number of accepted sweeps rejectcnt = fread(fid, 1, 'ushort');%number of rejected sweeps % determine the type of avg file and choose the right value for nsweeps if (rejectcnt+acceptcnt)~=compsweeps disp('It''s a grand average file!!!'); disp(['Subject number = ',num2str(compsweeps),'; sweeps = ',num2str(acceptcnt)]); nsweeps=compsweeps; else disp('It''s a single subject average file!!!'); disp(['nsweeps = ',num2str(compsweeps),'; Accepted sweeps = ',num2str(acceptcnt),'; Rejected sweeps = ',num2str(rejectcnt)]); nsweeps=acceptcnt; end pnts=fread(fid, 1, 'ushort'); % number of point per waveform chan=fread(fid, 1, 'ushort'); % number of channels fseek(fid, 3, 'cof'); % skip 3 bytes variance_flag=fread(fid, 1, 'uchar'); rate=fread(fid, 1, 'ushort'); % sample rate (Hz) fseek(fid, 127, 'cof'); % skip 127 bytes xmin=fread(fid, 1, 'float32'); % in s xmax=fread(fid, 1, 'float32'); % in s fseek(fid, 387, 'cof'); % skip 387 bytes % read electrode configuration % ---------------------------- for elec = 1:chan channel_label_tmp = fread(fid, 10, 'uchar'); electrodes(elec).tmp=channel_label_tmp; chan_names(elec,:) = channel_label_tmp'; %#ok<*AGROW> for index = 2:9 if chan_names(elec,index) == 0 chan_names(elec,index)=' '; end; end; fseek(fid, 61, 'cof');%skip 61 bytes electrodes(elec).calib= fread(fid, 1, 'float32'); % erp = fread(fid, 47-10, 'uchar'); % baseline(elec) = fread(fid, 1, 'ushort'); % erp = fread(fid, 10, 'uchar'); % sensitivity(elec) = fread(fid, 1, 'float32'); % erp = fread(fid, 8, 'uchar'); % electrodes(elec).calib= fread(fid, 1, 'float32'); % % fprintf('%s: baseline: %d\tsensitivity: %f\tcalibration: %f\n', ... % char(chan_names(elec,1:4)), baseline(elec), sensitivity(elec), electrodes(elec).calib); end; signal = zeros(pnts, chan); variance = zeros(pnts, chan); for elec = 1:chan % To scale a data point to % microvolts, multiply by the channel-specific calibration factor (i.e., for electrode j: % channel[j]->calib) and divide by the number of sweeps in the average (i.e., % channel[j]->n); % skip sweeps header and read data % -------------------------------- fseek(fid, 5, 'cof'); signal(:, elec) =fread(fid, pnts, 'float32')*electrodes(elec).calib/nsweeps; end; if variance_flag for elec = 1:chan variance(:, elec) = fread(fid, pnts, 'float32')*electrodes(elec).calib/nsweeps;% not sure end; else variance = 'novariance'; end; %% if ~strcmpi(chanNameList{1},'all') chanIDX=ones(1,chan); for ichanList=1:numel(chanNameList) for elec=1:chan if strcmpi(chanNameList{ichanList},char(chan_names(elec,1:numel(chanNameList{ichanList})))) chanIDX(elec)=0; break; end end end signal=signal(:,~chanIDX); if variance_flag variance=variance(:,~chanIDX); end chan_names=chan_names(~chanIDX,:); end % signal = signal'; % variance = variance'; fclose(fid); catch errorLOAD disp(FILENAME); rethrow(errorLOAD); end return;
github
ZijingMao/baselineeegtest-master
biosig2eeglabevent.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/biosig2eeglabevent.m
2,893
utf_8
e46fed3b39908dcd8fddac5e4c06235e
% biosig2eeglabevent() - convert biosig events to EEGLAB event structure % % Usage: % >> eeglabevent = biosig2eeglabevent( biosigevent, interval ) % % Inputs: % biosigevent - BioSig event structure % interval - Period to extract events for, in frames. % Default [] is all. % % Outputs: % eeglabevent - EEGLAB event structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2006- % Copyright (C) 13 2006- Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function event = biosig2eeglabevent(EVENT, interval) if nargin < 2 interval = []; end; event = []; disp('Importing data events...'); % If the interval variable is empty, import all events. if isempty(interval) if isfield(EVENT, 'Teeg') event = EVENT.Teeg; end if isfield(EVENT, 'TYP') for index = 1:length( EVENT.TYP ) event(index).type = EVENT.TYP(index); end end if isfield(EVENT, 'POS') for index = 1:length( EVENT.POS ) event(index).latency = EVENT.POS(index); end end if isfield(EVENT, 'DUR') if any( [ EVENT.DUR ] ) for index = 1:length( EVENT.DUR ) event(index).duration = EVENT.DUR(index); end end end if isfield(EVENT, 'CHN') if any( [ EVENT.CHN ] ) for index = 1:length( EVENT.CHN ) event(index).chanindex = EVENT.CHN(index); end end end % If a subinterval was specified, select only events that fall in that range, and % edit duration field if it exceeds that range. elseif isfield(EVENT,'POS') count = 1; for index = 1:length(EVENT.POS) pos_tmp = EVENT.POS(index) - interval(1) + 1; if pos_tmp > 0 & EVENT.POS(index) <= interval(2) event(count).latency = pos_tmp; if isfield(EVENT, 'TYP'), event(count).type = EVENT.TYP(index); end if isfield(EVENT, 'CHN'), event(count).chanindex = EVENT.CHN(index); end if isfield(EVENT, 'DUR') event(count).duration = min(EVENT.DUR(index), interval(2) - EVENT.POS(index)); end count = count + 1; end end end
github
ZijingMao/baselineeegtest-master
acsobiro.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/acsobiro.m
5,108
utf_8
bf3c7aaebcc622c2fabdabd6f5e763ce
% acsobiro() - A. Chickocki's robust Second-Order Blind Identification (SOBI) % by joint diagonalization of the time-delayed covariance matrices. % NOTE: THIS CODE ASSUMES TEMPORALLY CORRELATED SIGNALS. % Thus, the estimated time-delayed covariance matrices % for at least some time delays must be nonsingular. % % Usage: >> [H] = acsobiro(X); % >> [H,S] = acsobiro(X,n,p); % Inputs: % X - data matrix of dimension [m,N] where % m is the number of sensors % N is the number of samples % n - number of sources {Default: n=m} % p - number of correlation matrices to be diagonalized {default: 100} % For noisy data, use at least 100 time delays. % Outputs: % H - matrix of dimension [m,n] an estimate of the *mixing* matrix % S - matrix of dimension [n,N] an estimate of the source activities % where >> X [m,N] = H [m,n] * S [n,N] % % Authors: Implemented and improved by A. Cichocki on the basis of % the classical SOBI algorithm of Belouchrani and publications of: % A. Belouchrani et al., F. Cardoso et al., % S. Choi, S. Cruces, S. Amari, and P. Georgiev % For references: see function body % % Note: Extended by Arnaud Delorme and Scott Makeig to process data epochs % (computes the correlation matrix respecting epoch boundaries). % REFERENCES: % A. Belouchrani, K. Abed-Meraim, J.-F. Cardoso, and E. Moulines, ``Second-order % blind separation of temporally correlated sources,'' in Proc. Int. Conf. on % Digital Sig. Proc., (Cyprus), pp. 346--351, 1993. % % A. Belouchrani, and A. Cichocki, % Robust whitening procedure in blind source separation context, % Electronics Letters, Vol. 36, No. 24, 2000, pp. 2050-2053. % % A. Cichocki and S. Amari, % Adaptive Blind Signal and Image Processing, Wiley, 2003. function [H,S,D]=acsobiro(X,n,p), if nargin<1 || nargin > 3 help acsobiro return; end; [m,N,ntrials]=size(X); if nargin==1, DEFAULT_LAGS = 100; n=m; % source detection (hum...) p=min(DEFAULT_LAGS,ceil(N/3)); % number of time delayed correlation matrices to be diagonalized % Note: For noisy data, use at least p=100. elseif nargin==2, DEFAULT_LAGS = 100; p=min(DEFAULT_LAGS,ceil(N/3)); % number of correlation matrices to be diagonalized end; X(:,:)=X(:,:)-(mean(X(:,:)')'*ones(1,N*ntrials)); % Remove data means for t = 1:ntrials if t == 1 Rxx=(X(:,1:N-1,t)*X(:,2:N,t)')/(N-1)/ntrials; % Estimate the sample covariance matrix % for the time delay p=1, to reduce influence % of white noise. else Rxx=Rxx+(X(:,1:N-1,t)*X(:,2:N,t)')/(N-1)/ntrials; % Estimate the sample covariance matrix % for the time delay p=1, to reduce influence % of white noise. end; end; [Ux,Dx,Vx]=svd(Rxx); Dx=diag(Dx); if n<m, % under assumption of additive white noise and when the number % of sources is known, or can be estimated a priori Dx=Dx-real((mean(Dx(n+1:m)))); Q= diag(real(sqrt(1./Dx(1:n))))*Ux(:,1:n)'; else % under assumption of no additive noise and when the % number of sources is unknown n=max(find(Dx>1e-99)); % detect the number of sources fprintf('acsobiro(): Estimated number of sources is %d\n',n); Q= diag(real(sqrt(1./Dx(1:n))))*Ux(:,1:n)'; end; Xb = zeros(size(X)); Xb(:,:)=Q*X(:,:); % prewhitened data % Estimate the time delayed covariance matrices: k=1; pn=p*n; % for convenience for u=1:m:pn, k=k+1; for t = 1:ntrials if t == 1 Rxp=Xb(:,k:N,t)*Xb(:,1:N-k+1,t)'/(N-k+1)/ntrials; else Rxp=Rxp+Xb(:,k:N,t)*Xb(:,1:N-k+1,t)'/(N-k+1)/ntrials; end; end; M(:,u:u+m-1)=norm(Rxp,'fro')*Rxp; % Frobenius norm = end; % sqrt(sum(diag(Rxp'*Rxp))) % Approximate joint diagonalization: eps=1/sqrt(N)/100; encore=1; U=eye(n); while encore, encore=0; for p=1:n-1, for q=p+1:n, % Givens rotations: g=[ M(p,p:n:pn)-M(q,q:n:pn) ; M(p,q:n:pn)+M(q,p:n:pn) ; i*(M(q,p:n:pn)-M(p,q:n:pn))]; [Ucp,D] = eig(real(g*g')); [la,K]=sort(diag(D)); angles=Ucp(:,K(3));angles=sign(angles(1))*angles; c=sqrt(0.5+angles(1)/2); sr=0.5*(angles(2)-j*angles(3))/c; sc=conj(sr); asr = abs(sr)>eps ; encore=encore | asr ; if asr , % Update the M and U matrices: colp=M(:,p:n:pn); colq=M(:,q:n:pn); M(:,p:n:pn)=c*colp+sr*colq; M(:,q:n:pn)=c*colq-sc*colp; rowp=M(p,:); rowq=M(q,:); M(p,:)=c*rowp+sc*rowq; M(q,:)=c*rowq-sr*rowp; temp=U(:,p); U(:,p)=c*U(:,p)+sr*U(:,q); U(:,q)=c*U(:,q)-sc*temp; end %% if end %% q loop end %% p loop end %% while % Estimate the mixing matrix H H= pinv(Q)*U(1:n,1:n); % Estimate the source activities S if nargout>1 S=[]; W=U(1:n,1:n)'*Q; S= W*X(:,:); end
github
ZijingMao/baselineeegtest-master
metaplottopo.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/metaplottopo.m
13,145
utf_8
2f89761aa47cc2b3914162e988f6f1cc
% metaplottopo() - plot concatenated multichannel data epochs in a topographic or % rectangular array. Uses a channel location file with the same % format as topoplot(), or else plots data on a rectangular grid. % % Usage: % >> axes = metaplottopo(data, 'key1', 'val1', 'key2', 'val2') % % Inputs: % data = data consisting of consecutive epochs of (chans,frames) % or (chans,frames,n) % % Optional inputs: % 'chanlocs' = [struct] channel structure or file plot ERPs at channel % locations. See help readlocs() for data channel format. % 'geom' = [rows cols] plot ERP in grid (overwrite previous option). % Grid size for rectangular matrix. Example: [6 4]. % 'title' = [string] general plot title {def|'' -> none} % 'chans' = vector of channel numbers to plot {def|0 -> all} % 'axsize' = [x y] axis size {default [.07 .07]} % 'plotfunc' = [string] plot function name. If none is entered, axes % are created and returned. % 'plotargs' = [cell] plotting function arguments. % 'datapos' = [integer] position of data array in the function call. % Default is 1. % % Output: % Axes = [real] array of axes handles of the same length as the % number of plotted channels. % Channames = [cell] cell array of channel name for each plot % % Author: Arnaud Delorme, Scott Makeig, CERCO, CNRS, 2007- % % See also: plottopo() % Copyright (C) 2007, Arnaud Delorme, CERCO, [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 [Axes, outchannames ]= metaplottopo(data, varargin); % %%%%%%%%%%%%%%%%%%%%% Graphics Settings - can be customized %%%%%%%%%%%%%%%%%% % LINEWIDTH = 0.7; % data line widths (can be non-integer) FONTSIZE = 10; % font size to use for labels CHANFONTSIZE = 7; % font size to use for channel names TICKFONTSIZE = 8; % font size to use for axis labels TITLEFONTSIZE = 12; % font size to use for the plot title PLOT_WIDTH = 0.95; % 0.75, width and height of plot array on figure PLOT_HEIGHT = 0.88; % 0.88 gcapos = get(gca,'Position'); axis off; PLOT_WIDTH = gcapos(3)*PLOT_WIDTH; % width and height of gca plot array on gca PLOT_HEIGHT = gcapos(4)*PLOT_HEIGHT; MAXCHANS = 256; % can be increased curfig = gcf; % learn the current graphic figure number % %%%%%%%%%%%%%%%%%%%% Default settings - use commandline to override %%%%%%%%%%% % DEFAULT_AXWIDTH = 0.05; % DEFAULT_AXHEIGHT = 0.08; % DEFAULT_SIGN = -1; % Default - plot positive-up ISRECT = 0; % default ISSPEC = 0; % Default - not spectral data outchannames = {}; if nargin < 1 help metaplottopo return end if iscell(data), nchans = size(data{1},1); else nchans = size(data,1); end; g = finputcheck(varargin, { 'chanlocs' '' [] ''; 'chans' 'integer' [1 size(data,1)] [1:nchans]; 'geom' 'integer' [1 Inf] []; 'title' 'string' [] ''; 'plotfunc' 'string' [] ''; 'plotargs' 'cell' [] {}; 'datapos' 'integer' [] 1; 'calbar' 'real' [] []; 'axcopycom' 'string' [] ''; 'axsize' 'float' [0 1] [nan nan]}, 'metaplottopo' ); if isstr(g), error(g); end; if length(g.chans) == 1 & g.chans(1) ~= 0, error('can not plot a single ERP'); end; [chans,framestotal]=size(data); % data size % %%%%%%%%%%%%%%% Substitute defaults for missing parameters %%%%%%%%%%%%%%%% % if (isempty(g.chanlocs) || ~isfield(g.chanlocs, 'theta')) && isempty(g.geom) n = ceil(sqrt(length(g.chans))); g.geom = [n n]; end % %%%%%%%%%%%%%%%%%%%%%%%%%%% Test parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % axwidth = g.axsize(1); axheight = g.axsize(2); if ~isempty(g.geom) if isnan(axheight) % if not specified axheight = gcapos(4)/(g.geom(1)+1); axwidth = gcapos(3)/(g.geom(2)+1); end else axheight = DEFAULT_AXHEIGHT*(gcapos(4)*1.25); axwidth = DEFAULT_AXWIDTH*(gcapos(3)*1.3); end fprintf('Plotting data using axis size [%g,%g]\n',axwidth,axheight); % %%%%%%%%%%%%% Extend the size of the plotting area in the window %%%%%%%%%%%% % curfig = gcf; h=figure(curfig); set(h,'PaperUnits','normalized'); % use percentages to avoid US/A4 difference set(h,'PaperPosition',[0.0235308 0.0272775 0.894169 0.909249]); % equivalent orient portrait axis('normal'); axcolor= get(0,'DefaultAxesXcolor'); % find what the default x-axis color is vertcolor = 'k'; horicolor = vertcolor; % %%%%%%%%%%%%%%%%%%%%%%%%% Plot and label specified channels %%%%%%%%%%%%%%%%%% % if ~isempty(data) if iscell(data) data{1} = data{1}(g.chans,:); data{2} = data{2}(g.chans,:); else data = data(g.chans,:); end; end; % %%%%%%%%%%%%%%%%%%%%%%%%%% Print plot info %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % figure(curfig); h=gca;title(g.title); % title plot hold on axis('off') % %%%%%%%%%%%%%%%%%%%%%%%%%%% Read chan_locs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if isempty(g.chanlocs) || ~isfield(g.chanlocs, 'theta') % plot in a rectangular grid ISRECT = 1; ht = g.geom(1); wd = g.geom(2); if length(g.chans) > ht*wd fprintf('metaplottopo(): (%d) channels to be plotted > grid size [%d %d]\n',... length(g.chans),ht,wd); return end halfht = (ht-1)/2; halfwd = (wd-1)/2; xvals = zeros(ht*wd,1); yvals = zeros(ht*wd,1); dist = zeros(ht*wd,1); for j=1:ht for i=1:wd xvals(i+(j-1)*wd) = -halfwd+(i-1); yvals(i+(j-1)*wd) = halfht-(j-1); % dist(i+(j-1)*wd) = sqrt(xvals(j+(i-1)*ht).^2+yvals(j+(i-1)*ht).^2); end end % maxdist = max(dist); maxxvals = max(xvals); maxyvals = max(yvals); for j=1:ht for i=1:wd xvals(i+(j-1)*wd) = 0.499*xvals(i+(j-1)*wd)/maxxvals; yvals(i+(j-1)*wd) = 0.499*yvals(i+(j-1)*wd)/maxyvals; end end if ~exist('channames') channames = repmat(' ',ht*wd,4); for i=1:ht*wd channum = num2str(i); channames(i,1:length(channum)) = channum; end end else % read chan_locs file % read the channel location file % ------------------------------ if isstruct(g.chanlocs) nonemptychans = cellfun('isempty', { g.chanlocs.theta }); nonemptychans = find(~nonemptychans); [tmp channames Th Rd] = readlocs(g.chanlocs(nonemptychans)); channames = strvcat({ g.chanlocs.labels }); else [tmp channames Th Rd] = readlocs(g.chanlocs); channames = strvcat(channames); nonemptychans = [1:length(channames)]; end; Th = pi/180*Th; % convert degrees to radians Rd = Rd; if length(g.chans) > length(g.chanlocs), error('metaplottopo(): data channels must be <= ''chanlocs'' channels') end [yvalstmp,xvalstmp] = pol2cart(Th,Rd); % translate from polar to cart. coordinates xvals(nonemptychans) = xvalstmp; yvals(nonemptychans) = yvalstmp; % find position for other channels % -------------------------------- totalchans = length(g.chanlocs); emptychans = setdiff_bc(1:totalchans, nonemptychans); totalchans = floor(sqrt(totalchans))+1; for index = 1:length(emptychans) xvals(emptychans(index)) = 0.7+0.2*floor((index-1)/totalchans); yvals(emptychans(index)) = -0.4+mod(index-1,totalchans)/totalchans; end; channames = channames(g.chans,:); xvals = xvals(g.chans); yvals = yvals(g.chans); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % xvals = 0.5+PLOT_WIDTH*xvals; % controls width of plot array on page! % yvals = 0.5+PLOT_HEIGHT*yvals; % controls height of plot array on page! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if length(xvals) > 1 xvals = (xvals-mean([max(xvals) min(xvals)]))/(max(xvals)-min(xvals)); % recenter xvals = gcapos(1)+gcapos(3)/2+PLOT_WIDTH*xvals; % controls width of plot % array on current axes end; yvals = gcapos(2)+gcapos(4)/2+PLOT_HEIGHT*yvals; % controls height of plot % array on current axes % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Plot traces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Axes = []; fprintf('Plotting all channel...'); for c=1:length(g.chans), %%%%%%%% for each data channel %%%%%%%%%%%%%%%%%%%%%%%%%% xcenter = xvals(c); if isnan(xcenter), xcenter = 0.5; end; ycenter = yvals(c); if isnan(ycenter), ycenter = 0.5; end; Axes = [Axes axes('Units','Normal','Position', ... [xcenter-axwidth/2 ycenter-axheight/2 axwidth axheight])]; hold on; axis('off'); %axes('Units','Normal','Position', [xcenter-axwidth/2 ycenter-axheight/2 axwidth axheight]) %axis('off'); % %%%%%%%%%%%%%%%%%%%%%%% Plot data traces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if ~isempty( g.plotfunc ) %figure(curfig); eval( [ 'func = @' g.plotfunc ';' ] ); if iscell(data), tmp = { g.plotargs{1:g.datapos(1)-1} data{1}(c,:) g.plotargs{g.datapos(1):g.datapos(2)-1} data{2}(c,:) g.plotargs{g.datapos(2):end}}; else tmp = { g.plotargs{1:g.datapos-1} data(c,:) g.plotargs{g.datapos:end} }; end; tmp = { tmp{:} 'title' channames(c,:) 'plotmode' 'topo'}; feval(func, tmp{:}); end; outchannames{c} = deblank(channames(c,:)); end; % c, chans / subplot fprintf('\n'); % %%%%%%%%%%%%%%%%%%%%% Make time and amp cal bar %%%%%%%%%%%%%%%%%%%%%%%%% % if ~isempty(g.calbar) ax = axes('Units','Normal','Position', [0.85 0.1 axwidth axheight]); % FIX!!!! axes(ax) axis('off'); if g.calbar(3) < g.calbar(4), g.ydir = 1; else g.calbar(5) = g.calbar(3); g.calbar(3) = []; g.ydir = -1; end; [xmin xmax ymin ymax] = deal(g.calbar(1), g.calbar(2),g.calbar(3), g.calbar(4)); figure(curfig);p=plot([0 0],[ymin ymax],'color','k'); % draw vert axis at zero if g.ydir == -1 set(gca, 'ydir', 'reverse'); end; hold on figure(curfig);p=plot([xmin xmax],[0 0],'color','k'); % draw horizontal axis xlim([xmin xmax]); ylim([ymin ymax]); axis off; % draw text limits % ---------------- xdiff = xmax - xmin; ydiff = ymax - ymin; signx = xmin-0.15*xdiff; figure(curfig);axis('off');h=text(double(signx),double(ymin),num2str(ymin,3)); % text ymin set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','right','Clipping','off'); figure(curfig);axis('off');h=text(double(signx), double(ymax),['+' num2str(ymax,3)]); % text +ymax set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','right','Clipping','off'); ytick = g.ydir*(-ymax-0.3*ydiff); figure(curfig);tick = [int2str(xmin)]; h=text(double(xmin),double(ytick),tick); set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','center',... 'Clipping','off'); % center text tick = 'Time (ms)'; figure(curfig);h=text(double(xmin+xdiff/2),double(ytick-0.5*g.ydir*ydiff),tick); set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','center',... 'Clipping','off'); % center text tick = [int2str(xmax)]; figure(curfig);h=text(double(xmax),double(ytick),tick); set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','center',... 'Clipping','off'); % center text end; % 'set(gcbf, ''''unit'''', ''''pixel'''');' ... % 'tmp = get(gcbf, ''''position'''');' ... % 'tmp2 = get(0, ''''screensize'''');' ... % 'if tmp(2)+500 > tmp2(4), tmp(2) = tmp2(4)-500; end;' ... % 'set(gcbf, ''''position'''', [ tmp(1) tmp(2) 560 420]);' ... g.axcopycom = [ 'axis on;' ... 'tmp = get(gca, ''''userdata'''');' ... 'if ~isempty(tmp), xlabel(tmp{1});' ... 'ylabel(tmp{2});' ... 'legend(tmp{3}{:}); end; clear tmp tmp2;' ]; axcopy(gcf, g.axcopycom); % turn on popup feature icadefs; set(gca,'Color',BACKCOLOR); % set the background color
github
ZijingMao/baselineeegtest-master
blockave.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/blockave.m
2,707
utf_8
74345d9d3d97007ec7f3ef4dd137abd4
% blockave() - make block average of concatenated data sets of same size % Each data set is assumed to be of size (chans,frames). % Usage: % >> aveout = blockave(data,frames) % >> aveout = blockave(data,frames,epochs,weights) % Inputs: % data = data matrix of size (chans,frames*epochs) % frames = columns per data epoch % epochs = vector of epochs to average {default|0 -> all} % weights = vector of epoch weights {default|0 -> equal} % non-equal weights are normalized internally to sum=1 % Output: % aveout = averaged data of size (chans, frames) % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 1998 % Copyright (C) 1998 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 5-14-98 improved error checking, allowed 2 args -sm % 01-25-02 reformated help & license -ad function ave = blockave(data,frames,epochs,weights) if nargin < 2 help blockave return end if nargin<3 epochs = 0; end if nargin<4 weights = nan; end if nargin>4 help blockave end [chans,framestot]=size(data); nepochs = floor(framestot/frames); if nepochs*frames ~= framestot fprintf('blockave(): frames arg does not divide data length,\n'); return end if max(epochs) > nepochs help blockave return end if min(epochs) < 1 if size(epochs,1)>1 | size(epochs,2) > 1 help blockave return else epochs = 1:nepochs; end end if ~isnan(weights) if length(weights) ~= nepochs fprintf(... 'blockave(): number of weights (%d) must match number of epochs (%d).\n',... length(weights), nepochs); end weights = weights/sum(weights); % normalize end ave = zeros(chans,frames); epochs = epochs(:)'; % make epochs a row vector n = 1; for e=epochs if isnan(weights) ave = ave + data(:,(e-1)*frames+1:e*frames); else ave = ave + weights(n)*data(:,(e-1)*frames+1:e*frames); n = n+1; end end ave = ave/length(epochs);
github
ZijingMao/baselineeegtest-master
posact.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/posact.m
2,789
utf_8
485896d0a8c23f3b21a5d76bdb1209fe
% posact() - Make runica() activations all RMS-positive. % Adjust weights and inverse weight matrix accordingly. % % Usage: >> [actout,winvout,weightsout] = posact(data,weights,sphere) % % Inputs: % data = runica() input data % weights = runica() weights % sphere = runica() sphere {default|0 -> eye()} % % Outputs: % actout = activations reoriented to be RMS-positive % winvout = inv(weights*sphere) reoriented to match actout % weightsout = weights reoriented to match actout (sphere unchanged) % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 11/97 % Copyright (C) 11/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 % 01-25-02 reformated help & license, added links -ad function [actout,winvout,weightsout] = posact(data,weights,sphere) if nargin < 2 help posact return end if nargin < 3 sphere = 0; end [chans,frames]=size(data); [r,c]=size(weights); if sphere == 0 sphere = eye(chans); end [sr,sc] = size(sphere); if sc~= chans fprintf('posact(): Sizes of sphere and data do not agree.\n') return elseif c~=sr fprintf('posact(): Sizes of weights and sphere do not agree.\n') return end activations = weights*sphere*data; if r==c winv = inv(weights*sphere); else winv = pinv(weights*sphere); end [rows,cols] = size(activations); actout = activations; winvout = winv; fprintf('Inverting negative activations: '); for r=1:rows, pos = find(activations(r,:)>=0); posrms = sqrt(sum(activations(r,pos).*activations(r,pos))/length(pos)); neg = find(activations(r,:)<0); negrms = sqrt(sum(activations(r,neg).*activations(r,neg))/length(neg)); if negrms>posrms fprintf('-'); actout(r,:) = -1*activations(r,:); winvout(:,r) = -1*winv(:,r); end fprintf('%d ',r); end fprintf('\n'); if nargout>2 if r==c, weightsout = inv(winvout); else weightsout = pinv(winvout); end if nargin>2 % if sphere submitted weightsout = weightsout*inv(sphere); % separate out the sphering end end
github
ZijingMao/baselineeegtest-master
eegplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/eegplot.m
89,114
utf_8
ea5b855ef8a62ecd144b9b16482c639b
% eegplot() - Scroll (horizontally and/or vertically) through multichannel data. % Allows vertical scrolling through channels and manual marking % and unmarking of data stretches or epochs for rejection. % Usage: % >> eegplot(data, 'key1', value1 ...); % use interface buttons, etc. % else % >> eegplot('noui', data, 'key1', value1 ...); % no user interface; % % use for plotting % Menu items: % "Figure > print" - [menu] Print figure in portrait or landscape. % "Figure > Edit figure" - [menu] Remove menus and buttons and call up the standard % Matlab figure menu. Select "Tools > Edit" to format the figure % for publication. Command line equivalent: 'noui' % "Figure > Accept and Close" - [menu] Same as the bottom-right "Reject" button. % "Figure > Cancel and Close" - [menu] Cancel all editing, same as the "Cancel" button. % "Display > Marking color" > [Hide|Show] marks" - [menu] Show or hide patches of % background color behind the data. Mark stretches of *continuous* % data (e.g., for rejection) by dragging the mouse horizontally % over the activity. With *epoched* data, click on the selected epochs. % Clicked on a marked region to unmark it. Called from the % command line, marked data stretches or epochs are returned in % the TMPREJ variable in the global workspace *if/when* the "Reject" % button is pressed (see Outputs); called from pop_eegplot() or % eeglab(), the marked data portions are removed from the current % dataset, and the dataset is automatically updated. % "Display > Marking color > Choose color" - [menu] Change the background marking % color. The marking color(s) of previously marked trials are preserved. % Called from command line, subsequent functions eegplot2event() or % eegplot2trials() allow processing trials marked with different colors % in the TMPREJ output variable. Command line equivalent: 'wincolor'. % "Display > Grid > ..." - [menu] Toggle (on or off) time and/or channel axis grids % in the activity plot. Submenus allow modifications to grid aspects. % Command line equivalents: 'xgrid' / 'ygrid' % "Display > Show scale" - [menu] Show (or hide if shown) the scale on the bottom % right corner of the activity window. Command line equivalent: 'scale' % "Display > Title" - [menu] Change the title of the figure. Command line equivalent: % 'title' % "Settings > Time range to display" - [menu] For continuous EEG data, this item % pops up a query window for entering the number of seconds to display % in the activity window. For epoched data, the query window asks % for the number of epochs to display (this can be fractional). % Command line equivalent: 'winlength' % "Settings > Number of channels to display" - [menu] Number of channels to display % in the activity window. If not all channels are displayed, the % user may scroll through channels using the slider on the left % of the activity plot. Command line equivalent: 'dispchans' % "Settings > Channel labels > ..." - [menu] Use numbers as channel labels or load % a channel location file from disk. If called from the eeglab() menu or % pop_eegplot(), the channel labels of the dataset will be used. % Command line equivalent: 'eloc_file' % "Settings > Zoom on/off" - [menu] Toggle Matlab figure zoom on or off for time and % electrode axes. left-click to zoom (x2); right-click to reverse-zoom. % Else, draw a rectange in the activity window to zoom the display into % that region. NOTE: When zoom is on, data cannot be marked for rejection. % "Settings > Events" - [menu] Toggle event on or off (assuming events have been % given as input). Press "legend" to pop up a legend window for events. % % Display window interface: % "Activity plot" - [main window] This axis displays the channel activities. For % continuous data, the time axis shows time in seconds. For epoched % data, the axis label indicate time within each epoch. % "Cancel" - [button] Closes the window and cancels any data rejection marks. % "Event types" - [button] pop up a legend window for events. % "<<" - [button] Scroll backwards though time or epochs by one window length. % "<" - [button] Scroll backwards though time or epochs by 0.2 window length. % "Navigation edit box" - [edit box] Enter a starting time or epoch to jump to. % ">" - [button] Scroll forward though time or epochs by 0.2 window length. % ">>" - [button] Scroll forward though time or epochs by one window length. % "Chan/Time/Value" - [text] If the mouse is within the activity window, indicates % which channel, time, and activity value the cursor is closest to. % "Scale edit box" - [edit box] Scales the displayed amplitude in activity units. % Command line equivalent: 'spacing' % "+ / -" - [buttons] Use these buttons to +/- the amplitude scale by 10%. % "Reject" - [button] When pressed, save rejection marks and close the figure. % Optional input parameter 'command' is evaluated at that time. % NOTE: This button's label can be redefined from the command line % (see 'butlabel' below). If no processing command is specified % for the 'command' parameter (below), this button does not appear. % "Stack/Spread" - [button] "Stack" collapses all channels/activations onto the % middle axis of the plot. "Spread" undoes the operation. % "Norm/Denorm" - [button] "Norm" normalizes each channel separately such that all % channels have the same standard deviation without changing original % data/activations under EEG structure. "Denorm" undoes the operation. % % Required command line input: % data - Input data matrix, either continuous 2-D (channels,timepoints) or % epoched 3-D (channels,timepoints,epochs). If the data is preceded % by keyword 'noui', GUI control elements are omitted (useful for % plotting data for presentation). A set of power spectra at % each channel may also be plotted (see 'freqlimits' below). % Optional command line keywords: % 'srate' - Sampling rate in Hz {default|0: 256 Hz} % 'spacing' - Display range per channel (default|0: max(whole_data)-min(whole_data)) % 'eloc_file' - Electrode filename (as in >> topoplot example) to read % ascii channel labels. Else, % [vector of integers] -> Show specified channel numbers. Else, % [] -> Do not show channel labels {default|0 -> Show [1:nchans]} % 'limits' - [start end] Time limits for data epochs in ms (for labeling % purposes only). % 'freqs' - Vector of frequencies (If data contain spectral values). % size(data, 2) must be equal to size(freqs,2). % *** This option must be used ALWAYS with 'freqlimits' *** % 'freqlimits' - [freq_start freq_end] If plotting epoch spectra instead of data, frequency % limits to display spectrum. (Data should contain spectral values). % *** This option must be used ALWAYS with 'freqs' *** % 'winlength' - [value] Seconds (or epochs) of data to display in window {default: 5} % 'dispchans' - [integer] Number of channels to display in the activity window % {default: from data}. If < total number of channels, a vertical % slider on the left side of the figure allows vertical data scrolling. % 'title' - Figure title {default: none} % 'xgrid' - ['on'|'off'] Toggle display of the x-axis grid {default: 'off'} % 'ygrid' - ['on'|'off'] Toggle display of the y-axis grid {default: 'off'} % 'ploteventdur' - ['on'|'off'] Toggle display of event duration { default: 'off' } % 'data2' - [float array] identical size to the original data and % plotted on top of it. % % Additional keywords: % 'command' - ['string'] Matlab command to evaluate when the 'REJECT' button is % clicked. The 'REJECT' button is visible only if this parameter is % not empty. As explained in the "Output" section below, the variable % 'TMPREJ' contains the rejected windows (see the functions % eegplot2event() and eegplot2trial()). % 'butlabel' - Reject button label. {default: 'REJECT'} % 'winrej' - [start end R G B e1 e2 e3 ...] Matrix giving data periods to mark % for rejection, each row indicating a different period % [start end] = period limits (in frames from beginning of data); % [R G B] = specifies the marking color; % [e1 e2 e3 ...] = a (1,nchans) logical [0|1] vector giving % channels (1) to mark and (0) not mark for rejection. % 'color' - ['on'|'off'|cell array] Plot channels with different colors. % If an RGB cell array {'r' 'b' 'g'}, channels will be plotted % using the cell-array color elements in cyclic order {default:'off'}. % 'wincolor' - [color] Color to use to mark data stretches or epochs {default: % [ 0.7 1 0.9] is the default marking color} % 'events' - [struct] EEGLAB event structure (EEG.event) to use to show events. % 'submean' - ['on'|'off'] Remove channel means in each window {default: 'on'} % 'position' - [lowleft_x lowleft_y width height] Position of the figure in pixels. % 'tag' - [string] Matlab object tag to identify this eegplot() window (allows % keeping track of several simultaneous eegplot() windows). % 'children' - [integer] Figure handle of a *dependent* eegplot() window. Scrolling % horizontally in the master window will produce the same scroll in % the dependent window. Allows comparison of two concurrent datasets, % or of channel and component data from the same dataset. % 'scale' - ['on'|'off'] Display the amplitude scale {default: 'on'}. % 'mocap' - ['on'|'off'] Display motion capture data in a separate figure. % To run, select an EEG data period in the scolling display using % the mouse. Motion capture (mocap) data should be % under EEG.moredata.mocap.markerPosition in xs, ys and zs fields which are % (number of markers, number of time points) arrays. % {default: 'off'}. % 'selectcommand' - [cell array] list of 3 commands (strings) to run when the mouse % button is down, when it is moving and when the mouse button is up. % 'ctrlselectcommand' - [cell array] same as above in conjunction with pressing the % CTRL key. % Outputs: % TMPREJ - Matrix (same format as 'winrej' above) placed as a variable in % the global workspace (only) when the REJECT button is clicked. % The command specified in the 'command' keyword argument can use % this variable. (See eegplot2trial() and eegplot2event()). % % Author: Arnaud Delorme & Colin Humphries, CNL/Salk Institute, SCCN/INC/UCSD, 1998-2001 % % See also: eeg_multieegplot(), eegplot2event(), eegplot2trial(), eeglab() % deprecated % 'colmodif' - nested cell array of window colors that may be marked/unmarked. Default % is current color only. % Copyright (C) 2001 Arnaud Delorme & Colin Humphries, 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 % Note for programmers - Internal variable structure: % All in g. except for Eposition and Eg.spacingwhich are inside the boxes % gcf % 1 - winlength % 2 - srate % 3 - children % 'backeeg' axis % 1 - trialtag % 2 - g.winrej % 3 - nested call flag % 'eegaxis' % 1 - data % 2 - colorlist % 3 - submean % on or off, subtract the mean % 4 - maxfreq % empty [] if no gfrequency content % 'buttons hold other informations' Eposition for instance hold the current postition function [outvar1] = eegplot(data, varargin); % p1,p2,p3,p4,p5,p6,p7,p8,p9) % Defaults (can be re-defined): DEFAULT_PLOT_COLOR = { [0 0 1], [0.7 0.7 0.7]}; % EEG line color try, icadefs; DEFAULT_FIG_COLOR = BACKCOLOR; BUTTON_COLOR = GUIBUTTONCOLOR; catch DEFAULT_FIG_COLOR = [1 1 1]; BUTTON_COLOR =[0.8 0.8 0.8]; end; DEFAULT_AXIS_COLOR = 'k'; % X-axis, Y-axis Color, text Color DEFAULT_GRID_SPACING = 1; % Grid lines every n seconds DEFAULT_GRID_STYLE = '-'; % Grid line style YAXIS_NEG = 'off'; % 'off' = positive up DEFAULT_NOUI_PLOT_COLOR = 'k'; % EEG line color for noui option % 0 - 1st color in AxesColorOrder SPACING_EYE = 'on'; % g.spacingI on/off SPACING_UNITS_STRING = ''; % '\muV' for microvolt optional units for g.spacingI Ex. uV %MAXEVENTSTRING = 10; %DEFAULT_AXES_POSITION = [0.0964286 0.15 0.842 0.75-(MAXEVENTSTRING-5)/100]; % dimensions of main EEG axes ORIGINAL_POSITION = [50 50 800 500]; if nargin < 1 help eegplot return end % %%%%%%%%%%%%%%%%%%%%%%%% % Setup inputs % %%%%%%%%%%%%%%%%%%%%%%%% if ~isstr(data) % If NOT a 'noui' call or a callback from uicontrols try options = varargin; if ~isempty( varargin ), for i = 1:2:numel(options) g.(options{i}) = options{i+1}; end else g= []; end; catch disp('eegplot() error: calling convention {''key'', value, ... } error'); return; end; % Selection of data range If spectrum plot (Ramon) if isfield(g,'freqlimits') || isfield(g,'freqs') % % Check consistency of freqlimits % % Check consistency of freqs % Selecting data and freqs [temp, fBeg] = min(abs(g.freqs-g.freqlimits(1))); [temp, fEnd] = min(abs(g.freqs-g.freqlimits(2))); data = data(:,fBeg:fEnd); g.freqs = g.freqs(fBeg:fEnd); % Updating settings g.winlength = g.freqs(end) - g.freqs(1); g.srate = length(g.freqs)/(g.freqs(end)-g.freqs(1)); g.isfreq = 1; end % push button: create/remove window % --------------------------------- defdowncom = 'eegplot(''defdowncom'', gcbf);'; % push button: create/remove window defmotioncom = 'eegplot(''defmotioncom'', gcbf);'; % motion button: move windows or display current position defupcom = 'eegplot(''defupcom'', gcbf);'; defctrldowncom = 'eegplot(''topoplot'', gcbf);'; % CTRL press and motion -> do nothing by default defctrlmotioncom = ''; % CTRL press and motion -> do nothing by default defctrlupcom = ''; % CTRL press and up -> do nothing by default try, g.srate; catch, g.srate = 256; end; try, g.spacing; catch, g.spacing = 0; end; try, g.eloc_file; catch, g.eloc_file = 0; end; % 0 mean numbered try, g.winlength; catch, g.winlength = 5; end; % Number of seconds of EEG displayed try, g.position; catch, g.position = ORIGINAL_POSITION; end; try, g.title; catch, g.title = ['Scroll activity -- eegplot()']; end; try, g.trialstag; catch, g.trialstag = -1; end; try, g.winrej; catch, g.winrej = []; end; try, g.command; catch, g.command = ''; end; try, g.tag; catch, g.tag = 'EEGPLOT'; end; try, g.xgrid; catch, g.xgrid = 'off'; end; try, g.ygrid; catch, g.ygrid = 'off'; end; try, g.color; catch, g.color = 'off'; end; try, g.submean; catch, g.submean = 'off'; end; try, g.children; catch, g.children = 0; end; try, g.limits; catch, g.limits = [0 1000*(size(data,2)-1)/g.srate]; end; try, g.freqs; catch, g.freqs = []; end; % Ramon try, g.freqlimits; catch, g.freqlimits = []; end; try, g.dispchans; catch, g.dispchans = size(data,1); end; try, g.wincolor; catch, g.wincolor = [ 0.7 1 0.9]; end; try, g.butlabel; catch, g.butlabel = 'REJECT'; end; try, g.colmodif; catch, g.colmodif = { g.wincolor }; end; try, g.scale; catch, g.scale = 'on'; end; try, g.events; catch, g.events = []; end; try, g.ploteventdur; catch, g.ploteventdur = 'off'; end; try, g.data2; catch, g.data2 = []; end; try, g.plotdata2; catch, g.plotdata2 = 'off'; end; try, g.mocap; catch, g.mocap = 'off'; end; % nima try, g.selectcommand; catch, g.selectcommand = { defdowncom defmotioncom defupcom }; end; try, g.ctrlselectcommand; catch, g.ctrlselectcommand = { defctrldowncom defctrlmotioncom defctrlupcom }; end; try, g.datastd; catch, g.datastd = []; end; %ozgur try, g.normed; catch, g.normed = 0; end; %ozgur try, g.envelope; catch, g.envelope = 0; end;%ozgur try, g.maxeventstring; catch, g.maxeventstring = 10; end; % JavierLC try, g.isfreq; catch, g.isfreq = 0; end; % Ramon if strcmpi(g.ploteventdur, 'on'), g.ploteventdur = 1; else g.ploteventdur = 0; end; if ndims(data) > 2 g.trialstag = size( data, 2); end; gfields = fieldnames(g); for index=1:length(gfields) switch gfields{index} case {'spacing', 'srate' 'eloc_file' 'winlength' 'position' 'title' ... 'trialstag' 'winrej' 'command' 'tag' 'xgrid' 'ygrid' 'color' 'colmodif'... 'freqs' 'freqlimits' 'submean' 'children' 'limits' 'dispchans' 'wincolor' ... 'maxeventstring' 'ploteventdur' 'butlabel' 'scale' 'events' 'data2' 'plotdata2' 'mocap' 'selectcommand' 'ctrlselectcommand' 'datastd' 'normed' 'envelope' 'isfreq'},; otherwise, error(['eegplot: unrecognized option: ''' gfields{index} '''' ]); end; end; % g.data=data; % never used and slows down display dramatically - Ozgur 2010 if length(g.srate) > 1 disp('Error: srate must be a single number'); return; end; if length(g.spacing) > 1 disp('Error: ''spacing'' must be a single number'); return; end; if length(g.winlength) > 1 disp('Error: winlength must be a single number'); return; end; if isstr(g.title) > 1 disp('Error: title must be is a string'); return; end; if isstr(g.command) > 1 disp('Error: command must be is a string'); return; end; if isstr(g.tag) > 1 disp('Error: tag must be is a string'); return; end; if length(g.position) ~= 4 disp('Error: position must be is a 4 elements array'); return; end; switch lower(g.xgrid) case { 'on', 'off' },; otherwise disp('Error: xgrid must be either ''on'' or ''off'''); return; end; switch lower(g.ygrid) case { 'on', 'off' },; otherwise disp('Error: ygrid must be either ''on'' or ''off'''); return; end; switch lower(g.submean) case { 'on' 'off' }; otherwise disp('Error: submean must be either ''on'' or ''off'''); return; end; switch lower(g.scale) case { 'on' 'off' }; otherwise disp('Error: scale must be either ''on'' or ''off'''); return; end; if ~iscell(g.color) switch lower(g.color) case 'on', g.color = { 'k', 'm', 'c', 'b', 'g' }; case 'off', g.color = { [ 0 0 0.4] }; otherwise disp('Error: color must be either ''on'' or ''off'' or a cell array'); return; end; end; if length(g.dispchans) > size(data,1) g.dispchans = size(data,1); end; if ~iscell(g.colmodif) g.colmodif = { g.colmodif }; end; if g.maxeventstring>20 % JavierLC disp('Error: maxeventstring must be equal or lesser than 20'); return; end; % max event string; JavierLC % --------------------------------- MAXEVENTSTRING = g.maxeventstring; DEFAULT_AXES_POSITION = [0.0964286 0.15 0.842 0.75-(MAXEVENTSTRING-5)/100]; % convert color to modify into array of float % ------------------------------------------- for index = 1:length(g.colmodif) if iscell(g.colmodif{index}) tmpcolmodif{index} = g.colmodif{index}{1} ... + g.colmodif{index}{2}*10 ... + g.colmodif{index}{3}*100; else tmpcolmodif{index} = g.colmodif{index}(1) ... + g.colmodif{index}(2)*10 ... + g.colmodif{index}(3)*100; end; end; g.colmodif = tmpcolmodif; [g.chans,g.frames, tmpnb] = size(data); g.frames = g.frames*tmpnb; if g.spacing == 0 maxindex = min(1000, g.frames); stds = std(data(:,1:maxindex),[],2); g.datastd = stds; stds = sort(stds); if length(stds) > 2 stds = mean(stds(2:end-1)); else stds = mean(stds); end; g.spacing = stds*3; if g.spacing > 10 g.spacing = round(g.spacing); end if g.spacing == 0 | isnan(g.spacing) g.spacing = 1; % default end; end % set defaults % ------------ g.incallback = 0; g.winstatus = 1; g.setelectrode = 0; [g.chans,g.frames,tmpnb] = size(data); g.frames = g.frames*tmpnb; g.nbdat = 1; % deprecated g.time = 0; g.elecoffset = 0; % %%%%%%%%%%%%%%%%%%%%%%%% % Prepare figure and axes % %%%%%%%%%%%%%%%%%%%%%%%% figh = figure('UserData', g,... % store the settings here 'Color',DEFAULT_FIG_COLOR, 'name', g.title,... 'MenuBar','none','tag', g.tag ,'Position',g.position, ... 'numbertitle', 'off', 'visible', 'off'); pos = get(figh,'position'); % plot relative to current axes q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]./100; clf; % Background axis % --------------- ax0 = axes('tag','backeeg','parent',figh,... 'Position',DEFAULT_AXES_POSITION,... 'Box','off','xgrid','off', 'xaxislocation', 'top'); % Drawing axis % --------------- YLabels = num2str((1:g.chans)'); % Use numbers as default YLabels = flipud(str2mat(YLabels,' ')); ax1 = axes('Position',DEFAULT_AXES_POSITION,... 'userdata', data, ...% store the data here 'tag','eegaxis','parent',figh,...%(when in g, slow down display) 'Box','on','xgrid', g.xgrid,'ygrid', g.ygrid,... 'gridlinestyle',DEFAULT_GRID_STYLE,... 'Xlim',[0 g.winlength*g.srate],... 'xtick',[0:g.srate*DEFAULT_GRID_SPACING:g.winlength*g.srate],... 'Ylim',[0 (g.chans+1)*g.spacing],... 'YTick',[0:g.spacing:g.chans*g.spacing],... 'YTickLabel', YLabels,... 'XTickLabel',num2str((0:DEFAULT_GRID_SPACING:g.winlength)'),... 'TickLength',[.005 .005],... 'Color','none',... 'XColor',DEFAULT_AXIS_COLOR,... 'YColor',DEFAULT_AXIS_COLOR); if isstr(g.eloc_file) | isstruct(g.eloc_file) % Read in electrode names if isstruct(g.eloc_file) & length(g.eloc_file) > size(data,1) g.eloc_file(end) = []; % common reference channel location end; eegplot('setelect', g.eloc_file, ax1); end; % %%%%%%%%%%%%%%%%%%%%%%%%% % Set up uicontrols % %%%%%%%%%%%%%%%%%%%%%%%%% % positions of buttons posbut(1,:) = [ 0.0464 0.0254 0.0385 0.0339 ]; % << posbut(2,:) = [ 0.0924 0.0254 0.0288 0.0339 ]; % < posbut(3,:) = [ 0.1924 0.0254 0.0299 0.0339 ]; % > posbut(4,:) = [ 0.2297 0.0254 0.0385 0.0339 ]; % >> posbut(5,:) = [ 0.1287 0.0203 0.0561 0.0390 ]; % Eposition posbut(6,:) = [ 0.4744 0.0236 0.0582 0.0390 ]; % Espacing posbut(7,:) = [ 0.2762 0.01 0.0582 0.0390 ]; % elec posbut(8,:) = [ 0.3256 0.01 0.0707 0.0390 ]; % g.time posbut(9,:) = [ 0.4006 0.01 0.0582 0.0390 ]; % value posbut(14,:) = [ 0.2762 0.05 0.0582 0.0390 ]; % elec tag posbut(15,:) = [ 0.3256 0.05 0.0707 0.0390 ]; % g.time tag posbut(16,:) = [ 0.4006 0.05 0.0582 0.0390 ]; % value tag posbut(10,:) = [ 0.5437 0.0458 0.0275 0.0270 ]; % + posbut(11,:) = [ 0.5437 0.0134 0.0275 0.0270 ]; % - posbut(12,:) = [ 0.6 0.02 0.14 0.05 ]; % cancel posbut(13,:) = [-0.15 0.02 0.07 0.05 ]; % cancel posbut(17,:) = [-0.06 0.02 0.09 0.05 ]; % events types posbut(20,:) = [-0.17 0.15 0.015 0.8 ]; % slider posbut(21,:) = [0.738 0.87 0.06 0.048];%normalize posbut(22,:) = [0.738 0.93 0.06 0.048];%stack channels(same offset) posbut(:,1) = posbut(:,1)+0.2; % Five move buttons: << < text > >> u(1) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'Position', posbut(1,:), ... 'Tag','Pushbutton1',... 'string','<<',... 'Callback',['global in_callback;', ... 'if isempty(in_callback);in_callback=1;', ... ' try eegplot(''drawp'',1);', ... ' clear global in_callback;', ... ' catch error_struct;', ... ' clear global in_callback;', ... ' throw(error_struct);', ... ' end;', ... 'else;return;end;']);%James Desjardins 2013/Jan/22 u(2) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'Position', posbut(2,:), ... 'Tag','Pushbutton2',... 'string','<',... 'Callback',['global in_callback;', ... 'if isempty(in_callback);in_callback=1;', ... ' try eegplot(''drawp'',2);', ... ' clear global in_callback;', ... ' catch error_struct;', ... ' clear global in_callback;', ... ' throw(error_struct);', ... ' end;', ... 'else;return;end;']);%James Desjardins 2013/Jan/22 u(5) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'BackgroundColor',[1 1 1], ... 'Position', posbut(5,:), ... 'Style','edit', ... 'Tag','EPosition',... 'string', fastif(g.trialstag(1) == -1, '0', '1'),... 'Callback', 'eegplot(''drawp'',0);' ); u(3) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'Position',posbut(3,:), ... 'Tag','Pushbutton3',... 'string','>',... 'Callback',['global in_callback;', ... 'if isempty(in_callback);in_callback=1;', ... ' try eegplot(''drawp'',3);', ... ' clear global in_callback;', ... ' catch error_struct;', ... ' clear global in_callback;', ... ' throw(error_struct);', ... ' end;', ... 'else;return;end;']);%James Desjardins 2013/Jan/22 u(4) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'Position',posbut(4,:), ... 'Tag','Pushbutton4',... 'string','>>',... 'Callback',['global in_callback;', ... 'if isempty(in_callback);in_callback=1;', ... ' try eegplot(''drawp'',4);', ... ' clear global in_callback;', ... ' catch error_struct;', ... ' clear global in_callback;', ... ' error(error_struct);', ... ' end;', ... 'else;return;end;']);%James Desjardins 2013/Jan/22 % Text edit fields: ESpacing u(6) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'BackgroundColor',[1 1 1], ... 'Position', posbut(6,:), ... 'Style','edit', ... 'Tag','ESpacing',... 'string',num2str(g.spacing),... 'Callback', 'eegplot(''draws'',0);' ); % Slider for vertical motion u(20) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'Position', posbut(20,:), ... 'Style','slider', ... 'visible', 'off', ... 'sliderstep', [0.9 1], ... 'Tag','eegslider', ... 'callback', [ 'tmpg = get(gcbf, ''userdata'');' ... 'tmpg.elecoffset = get(gcbo, ''value'')*(tmpg.chans-tmpg.dispchans);' ... 'set(gcbf, ''userdata'', tmpg);' ... 'eegplot(''drawp'',0);' ... 'clear tmpg;' ], ... 'value', 0); % Channels, position, value and tag u(9) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'BackgroundColor',DEFAULT_FIG_COLOR, ... 'Position', posbut(7,:), ... 'Style','text', ... 'Tag','Eelec',... 'string',' '); u(10) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'BackgroundColor',DEFAULT_FIG_COLOR, ... 'Position', posbut(8,:), ... 'Style','text', ... 'Tag','Etime',... 'string','0.00'); u(11) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'BackgroundColor',DEFAULT_FIG_COLOR, ... 'Position',posbut(9,:), ... 'Style','text', ... 'Tag','Evalue',... 'string','0.00'); u(14)= uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'BackgroundColor',DEFAULT_FIG_COLOR, ... 'Position', posbut(14,:), ... 'Style','text', ... 'Tag','Eelecname',... 'string','Chan.'); % Values of time/value and freq/power in GUI if g.isfreq u15_string = 'Freq'; u16_string = 'Power'; else u15_string = 'Time'; u16_string = 'Value'; end u(15) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'BackgroundColor',DEFAULT_FIG_COLOR, ... 'Position', posbut(15,:), ... 'Style','text', ... 'Tag','Etimename',... 'string',u15_string); u(16) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'BackgroundColor',DEFAULT_FIG_COLOR, ... 'Position',posbut(16,:), ... 'Style','text', ... 'Tag','Evaluename',... 'string',u16_string); % ESpacing buttons: + - u(7) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'Position',posbut(10,:), ... 'Tag','Pushbutton5',... 'string','+',... 'FontSize',8,... 'Callback','eegplot(''draws'',1)'); u(8) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'Position',posbut(11,:), ... 'Tag','Pushbutton6',... 'string','-',... 'FontSize',8,... 'Callback','eegplot(''draws'',2)'); cb_normalize = ['g = get(gcbf,''userdata'');if g.normed, disp(''Denormalizing...''); else, disp(''Normalizing...''); end;'... 'hmenu = findobj(gcf, ''Tag'', ''Normalize_menu'');' ... 'ax1 = findobj(''tag'',''eegaxis'',''parent'',gcbf);' ... 'data = get(ax1,''UserData'');' ... 'if isempty(g.datastd), g.datastd = std(data(:,1:min(1000,g.frames),[],2)); end;'... 'if g.normed, '... 'for i = 1:size(data,1), '... 'data(i,:,:) = data(i,:,:)*g.datastd(i);'... 'if ~isempty(g.data2), g.data2(i,:,:) = g.data2(i,:,:)*g.datastd(i);end;'... 'end;'... 'set(gcbo,''string'', ''Norm'');set(findobj(''tag'',''ESpacing'',''parent'',gcbf),''string'',num2str(g.oldspacing));' ... 'else, for i = 1:size(data,1),'... 'data(i,:,:) = data(i,:,:)/g.datastd(i);'... 'if ~isempty(g.data2), g.data2(i,:,:) = g.data2(i,:,:)/g.datastd(i);end;'... 'end;'... 'set(gcbo,''string'', ''Denorm'');g.oldspacing = g.spacing;set(findobj(''tag'',''ESpacing'',''parent'',gcbf),''string'',''5'');end;' ... 'g.normed = 1 - g.normed;' ... 'eegplot(''draws'',0);'... 'set(hmenu, ''Label'', fastif(g.normed,''Denormalize channels'',''Normalize channels''));' ... 'set(gcbf,''userdata'',g);set(ax1,''UserData'',data);clear ax1 g data;' ... 'eegplot(''drawp'',0);' ... 'disp(''Done.'')']; % Button for Normalizing data u(21) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'Position',posbut(21,:), ... 'Tag','Norm',... 'string','Norm', 'callback', cb_normalize); cb_envelope = ['g = get(gcbf,''userdata'');'... 'hmenu = findobj(gcf, ''Tag'', ''Envelope_menu'');' ... 'g.envelope = ~g.envelope;' ... 'set(gcbf,''userdata'',g);'... 'set(gcbo,''string'',fastif(g.envelope,''Spread'',''Stack''));' ... 'set(hmenu, ''Label'', fastif(g.envelope,''Spread channels'',''Stack channels''));' ... 'eegplot(''drawp'',0);clear g;']; % Button to plot envelope of data u(22) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'Position',posbut(22,:), ... 'Tag','Envelope',... 'string','Stack', 'callback', cb_envelope); if isempty(g.command) tmpcom = 'fprintf(''Rejections saved in variable TMPREJ\n'');'; else tmpcom = g.command; end; acceptcommand = [ 'g = get(gcbf, ''userdata'');' ... 'TMPREJ = g.winrej;' ... 'if g.children, delete(g.children); end;' ... 'delete(gcbf);' ... tmpcom ... '; clear g;']; % quitting expression if ~isempty(g.command) u(12) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'Position',posbut(12,:), ... 'Tag','Accept',... 'string',g.butlabel, 'callback', acceptcommand); end; u(13) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'Position',posbut(13,:), ... 'string',fastif(isempty(g.command),'CLOSE', 'CANCEL'), 'callback', ... [ 'g = get(gcbf, ''userdata'');' ... 'if g.children, delete(g.children); end;' ... 'close(gcbf);'] ); if ~isempty(g.events) u(17) = uicontrol('Parent',figh, ... 'Units', 'normalized', ... 'Position',posbut(17,:), ... 'string', 'Event types', 'callback', 'eegplot(''drawlegend'', gcbf)'); end; for i = 1: length(u) % Matlab 2014b compatibility if isprop(eval(['u(' num2str(i) ')']),'Style') set(u(i),'Units','Normalized'); end end % %%%%%%%%%%%%%%%%%%%%%%%%%%% % Set up uimenus % %%%%%%%%%%%%%%%%%%%%%%%%%%% % Figure Menu %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% m(7) = uimenu('Parent',figh,'Label','Figure'); m(8) = uimenu('Parent',m(7),'Label','Print'); uimenu('Parent',m(7),'Label','Edit figure', 'Callback', 'eegplot(''noui'');'); uimenu('Parent',m(7),'Label','Accept and close', 'Callback', acceptcommand ); uimenu('Parent',m(7),'Label','Cancel and close', 'Callback','delete(gcbf)') % Portrait %%%%%%%% timestring = ['[OBJ1,FIG1] = gcbo;',... 'PANT1 = get(OBJ1,''parent'');',... 'OBJ2 = findobj(''tag'',''orient'',''parent'',PANT1);',... 'set(OBJ2,''checked'',''off'');',... 'set(OBJ1,''checked'',''on'');',... 'set(FIG1,''PaperOrientation'',''portrait'');',... 'clear OBJ1 FIG1 OBJ2 PANT1;']; uimenu('Parent',m(8),'Label','Portrait','checked',... 'on','tag','orient','callback',timestring) % Landscape %%%%%%% timestring = ['[OBJ1,FIG1] = gcbo;',... 'PANT1 = get(OBJ1,''parent'');',... 'OBJ2 = findobj(''tag'',''orient'',''parent'',PANT1);',... 'set(OBJ2,''checked'',''off'');',... 'set(OBJ1,''checked'',''on'');',... 'set(FIG1,''PaperOrientation'',''landscape'');',... 'clear OBJ1 FIG1 OBJ2 PANT1;']; uimenu('Parent',m(8),'Label','Landscape','checked',... 'off','tag','orient','callback',timestring) % Print command %%%%%%% uimenu('Parent',m(8),'Label','Print','tag','printcommand','callback',... ['RESULT = inputdlg2( { ''Command:'' }, ''Print'', 1, { ''print -r72'' });' ... 'if size( RESULT,1 ) ~= 0' ... ' eval ( RESULT{1} );' ... 'end;' ... 'clear RESULT;' ]); % Display Menu %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% m(1) = uimenu('Parent',figh,... 'Label','Display', 'tag', 'displaymenu'); % window grid %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % userdata = 4 cells : display yes/no, color, electrode yes/no, % trial boundary adapt yes/no (1/0) m(11) = uimenu('Parent',m(1),'Label','Data select/mark', 'tag', 'displaywin', ... 'userdata', { 1, [0.8 1 0.8], 0, fastif( g.trialstag(1) == -1, 0, 1)}); uimenu('Parent',m(11),'Label','Hide marks','Callback', ... ['g = get(gcbf, ''userdata'');' ... 'if ~g.winstatus' ... ' set(gcbo, ''label'', ''Hide marks'');' ... 'else' ... ' set(gcbo, ''label'', ''Show marks'');' ... 'end;' ... 'g.winstatus = ~g.winstatus;' ... 'set(gcbf, ''userdata'', g);' ... 'eegplot(''drawb''); clear g;'] ) % color %%%%%%%%%%%%%%%%%%%%%%%%%% if isunix % for some reasons, does not work under Windows uimenu('Parent',m(11),'Label','Choose color', 'Callback', ... [ 'g = get(gcbf, ''userdata'');' ... 'g.wincolor = uisetcolor(g.wincolor);' ... 'set(gcbf, ''userdata'', g ); ' ... 'clear g;'] ) end; % set channels %uimenu('Parent',m(11),'Label','Mark channels', 'enable', 'off', ... %'checked', 'off', 'Callback', ... %['g = get(gcbf, ''userdata'');' ... % 'g.setelectrode = ~g.setelectrode;' ... % 'set(gcbf, ''userdata'', g); ' ... % 'if ~g.setelectrode setgcbo, ''checked'', ''on''); ... % else set(gcbo, ''checked'', ''off''); end;'... % ' clear g;'] ) % trials boundaries %uimenu('Parent',m(11),'Label','Trial boundaries', 'checked', fastif( g.trialstag(1) == -1, 'off', 'on'), 'Callback', ... %['hh = findobj(''tag'',''displaywin'',''parent'', findobj(''tag'',''displaymenu'',''parent'', gcbf ));' ... % 'hhdat = get(hh, ''userdata'');' ... % 'set(hh, ''userdata'', { hhdat{1}, hhdat{2}, hhdat{3}, ~hhdat{4}} ); ' ... %'if ~hhdat{4} set(gcbo, ''checked'', ''on''); else set(gcbo, ''checked'', ''off''); end;' ... %' clear hh hhdat;'] ) % plot durations % -------------- if g.ploteventdur & isfield(g.events, 'duration') disp(['Use menu "Display > Hide event duration" to hide colored regions ' ... 'representing event duration']); end; if isfield(g.events, 'duration') uimenu('Parent',m(1),'Label',fastif(g.ploteventdur, 'Hide event duration', 'Plot event duration'),'Callback', ... ['g = get(gcbf, ''userdata'');' ... 'if ~g.ploteventdur' ... ' set(gcbo, ''label'', ''Hide event duration'');' ... 'else' ... ' set(gcbo, ''label'', ''Show event duration'');' ... 'end;' ... 'g.ploteventdur = ~g.ploteventdur;' ... 'set(gcbf, ''userdata'', g);' ... 'eegplot(''drawb''); clear g;'] ) end; % X grid %%%%%%%%%%%% m(3) = uimenu('Parent',m(1),'Label','Grid'); timestring = ['FIGH = gcbf;',... 'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',... 'if size(get(AXESH,''xgrid''),2) == 2' ... %on ' set(AXESH,''xgrid'',''off'');',... ' set(gcbo,''label'',''X grid on'');',... 'else' ... ' set(AXESH,''xgrid'',''on'');',... ' set(gcbo,''label'',''X grid off'');',... 'end;' ... 'clear FIGH AXESH;' ]; uimenu('Parent',m(3),'Label',fastif(strcmp(g.xgrid, 'off'), ... 'X grid on','X grid off'), 'Callback',timestring) % Y grid %%%%%%%%%%%%% timestring = ['FIGH = gcbf;',... 'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',... 'if size(get(AXESH,''ygrid''),2) == 2' ... %on ' set(AXESH,''ygrid'',''off'');',... ' set(gcbo,''label'',''Y grid on'');',... 'else' ... ' set(AXESH,''ygrid'',''on'');',... ' set(gcbo,''label'',''Y grid off'');',... 'end;' ... 'clear FIGH AXESH;' ]; uimenu('Parent',m(3),'Label',fastif(strcmp(g.ygrid, 'off'), ... 'Y grid on','Y grid off'), 'Callback',timestring) % Grid Style %%%%%%%%% m(5) = uimenu('Parent',m(3),'Label','Grid Style'); timestring = ['FIGH = gcbf;',... 'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',... 'set(AXESH,''gridlinestyle'',''--'');',... 'clear FIGH AXESH;']; uimenu('Parent',m(5),'Label','- -','Callback',timestring) timestring = ['FIGH = gcbf;',... 'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',... 'set(AXESH,''gridlinestyle'',''-.'');',... 'clear FIGH AXESH;']; uimenu('Parent',m(5),'Label','_ .','Callback',timestring) timestring = ['FIGH = gcbf;',... 'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',... 'set(AXESH,''gridlinestyle'','':'');',... 'clear FIGH AXESH;']; uimenu('Parent',m(5),'Label','. .','Callback',timestring) timestring = ['FIGH = gcbf;',... 'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',... 'set(AXESH,''gridlinestyle'',''-'');',... 'clear FIGH AXESH;']; uimenu('Parent',m(5),'Label','__','Callback',timestring) % Submean menu %%%%%%%%%%%%% cb = ['g = get(gcbf, ''userdata'');' ... 'if strcmpi(g.submean, ''on''),' ... ' set(gcbo, ''label'', ''Remove DC offset'');' ... ' g.submean =''off'';' ... 'else' ... ' set(gcbo, ''label'', ''Do not remove DC offset'');' ... ' g.submean =''on'';' ... 'end;' ... 'set(gcbf, ''userdata'', g);' ... 'eegplot(''drawp'', 0); clear g;']; uimenu('Parent',m(1),'Label',fastif(strcmp(g.submean, 'on'), ... 'Do not remove DC offset','Remove DC offset'), 'Callback',cb) % Scale Eye %%%%%%%%% timestring = ['[OBJ1,FIG1] = gcbo;',... 'eegplot(''scaleeye'',OBJ1,FIG1);',... 'clear OBJ1 FIG1;']; m(7) = uimenu('Parent',m(1),'Label','Show scale','Callback',timestring); % Title %%%%%%%%%%%% uimenu('Parent',m(1),'Label','Title','Callback','eegplot(''title'')') % Stack/Spread %%%%%%%%%%%%%%% cb = ['g = get(gcbf, ''userdata'');' ... 'hbutton = findobj(gcf, ''Tag'', ''Envelope'');' ... % find button 'if g.envelope == 0,' ... ' set(gcbo, ''label'', ''Spread channels'');' ... ' g.envelope = 1;' ... ' set(hbutton, ''String'', ''Spread'');' ... 'else' ... ' set(gcbo, ''label'', ''Stack channels'');' ... ' g.envelope = 0;' ... ' set(hbutton, ''String'', ''Stack'');' ... 'end;' ... 'set(gcbf, ''userdata'', g);' ... 'eegplot(''drawp'', 0); clear g;']; uimenu('Parent',m(1),'Label',fastif(g.envelope == 0, ... 'Stack channels','Spread channels'), 'Callback',cb, 'Tag', 'Envelope_menu') % Normalize/denormalize %%%%%%%%%%%%%%% cb_normalize = ['g = get(gcbf,''userdata'');if g.normed, disp(''Denormalizing...''); else, disp(''Normalizing...''); end;'... 'hbutton = findobj(gcf, ''Tag'', ''Norm'');' ... % find button 'ax1 = findobj(''tag'',''eegaxis'',''parent'',gcbf);' ... 'data = get(ax1,''UserData'');' ... 'if isempty(g.datastd), g.datastd = std(data(:,1:min(1000,g.frames),[],2)); end;'... 'if g.normed, '... ' for i = 1:size(data,1), '... ' data(i,:,:) = data(i,:,:)*g.datastd(i);'... ' if ~isempty(g.data2), g.data2(i,:,:) = g.data2(i,:,:)*g.datastd(i);end;'... ' end;'... ' set(hbutton,''string'', ''Norm'');set(findobj(''tag'',''ESpacing'',''parent'',gcbf),''string'',num2str(g.oldspacing));' ... ' set(gcbo, ''label'', ''Normalize channels'');' ... 'else, for i = 1:size(data,1),'... ' data(i,:,:) = data(i,:,:)/g.datastd(i);'... ' if ~isempty(g.data2), g.data2(i,:,:) = g.data2(i,:,:)/g.datastd(i);end;'... ' end;'... ' set(hbutton,''string'', ''Denorm'');'... ' set(gcbo, ''label'', ''Denormalize channels'');' ... ' g.oldspacing = g.spacing;set(findobj(''tag'',''ESpacing'',''parent'',gcbf),''string'',''5'');end;' ... 'g.normed = 1 - g.normed;' ... 'eegplot(''draws'',0);'... 'set(gcbf,''userdata'',g);set(ax1,''UserData'',data);clear ax1 g data;' ... 'eegplot(''drawp'',0);' ... 'disp(''Done.'')']; uimenu('Parent',m(1),'Label',fastif(g.envelope == 0, ... 'Normalize channels','Denormalize channels'), 'Callback',cb_normalize, 'Tag', 'Normalize_menu') % Settings Menu %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% m(2) = uimenu('Parent',figh,... 'Label','Settings'); % Window %%%%%%%%%%%% uimenu('Parent',m(2),'Label','Time range to display',... 'Callback','eegplot(''window'')') % Electrode window %%%%%%%% uimenu('Parent',m(2),'Label','Number of channels to display',... 'Callback','eegplot(''winelec'')') % Electrodes %%%%%%%% m(6) = uimenu('Parent',m(2),'Label','Channel labels'); timestring = ['FIGH = gcbf;',... 'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',... 'YTICK = get(AXESH,''YTick'');',... 'YTICK = length(YTICK);',... 'set(AXESH,''YTickLabel'',flipud(str2mat(num2str((1:YTICK-1)''),'' '')));',... 'clear FIGH AXESH YTICK;']; uimenu('Parent',m(6),'Label','Show number','Callback',timestring) uimenu('Parent',m(6),'Label','Load .loc(s) file',... 'Callback','eegplot(''loadelect'');') % Zooms %%%%%%%% zm = uimenu('Parent',m(2),'Label','Zoom off/on'); commandzoom = [ 'set(gcbf, ''windowbuttondownfcn'', [ ''zoom(gcbf,''''down''''); eegplot(''''zoom'''', gcbf, 1);'' ]);' ... 'tmpg = get(gcbf, ''userdata'');' ... 'set(gcbf, ''windowbuttonmotionfcn'', tmpg.commandselect{2}); clear tmpg tmpstr;']; %uimenu('Parent',zm,'Label','Zoom time', 'callback', ... % [ 'zoom(gcbf, ''xon'');' commandzoom ]); %uimenu('Parent',zm,'Label','Zoom channels', 'callback', ... % [ 'zoom(gcbf, ''yon'');' commandzoom ]); uimenu('Parent',zm,'Label','Zoom on', 'callback', commandzoom); uimenu('Parent',zm,'Label','Zoom off', 'separator', 'on', 'callback', ... ['zoom(gcbf, ''off''); tmpg = get(gcbf, ''userdata'');' ... 'set(gcbf, ''windowbuttondownfcn'', tmpg.commandselect{1});' ... 'set(gcbf, ''windowbuttonmotionfcn'', tmpg.commandselect{2});' ... 'set(gcbf, ''windowbuttonupfcn'', tmpg.commandselect{3});' ... 'clear tmpg;' ]); uimenu('Parent',figh,'Label', 'Help', 'callback', 'pophelp(''eegplot'');'); % Events %%%%%%%% zm = uimenu('Parent',m(2),'Label','Events'); complotevent = [ 'tmpg = get(gcbf, ''userdata'');' ... 'tmpg.plotevent = ''on'';' ... 'set(gcbf, ''userdata'', tmpg); clear tmpg; eegplot(''drawp'', 0);']; comnoevent = [ 'tmpg = get(gcbf, ''userdata'');' ... 'tmpg.plotevent = ''off'';' ... 'set(gcbf, ''userdata'', tmpg); clear tmpg; eegplot(''drawp'', 0);']; comeventmaxstring = [ 'tmpg = get(gcbf, ''userdata'');' ... 'tmpg.plotevent = ''on'';' ... 'set(gcbf, ''userdata'', tmpg); clear tmpg; eegplot(''emaxstring'');']; % JavierLC comeventleg = [ 'eegplot(''drawlegend'', gcbf);']; uimenu('Parent',zm,'Label','Events on' , 'callback', complotevent, 'enable', fastif(isempty(g.events), 'off', 'on')); uimenu('Parent',zm,'Label','Events off' , 'callback', comnoevent , 'enable', fastif(isempty(g.events), 'off', 'on')); uimenu('Parent',zm,'Label','Events'' string length' , 'callback', comeventmaxstring, 'enable', fastif(isempty(g.events), 'off', 'on')); % JavierLC uimenu('Parent',zm,'Label','Events'' legend', 'callback', comeventleg , 'enable', fastif(isempty(g.events), 'off', 'on')); % %%%%%%%%%%%%%%%%% % Set up autoselect % %%%%%%%%%%%%%%%%% g.commandselect{1} = [ 'if strcmp(get(gcbf, ''SelectionType''),''alt''),' g.ctrlselectcommand{1} ... 'else ' g.selectcommand{1} 'end;' ]; g.commandselect{2} = [ 'if strcmp(get(gcbf, ''SelectionType''),''alt''),' g.ctrlselectcommand{2} ... 'else ' g.selectcommand{2} 'end;' ]; g.commandselect{3} = [ 'if strcmp(get(gcbf, ''SelectionType''),''alt''),' g.ctrlselectcommand{3} ... 'else ' g.selectcommand{3} 'end;' ]; set(figh, 'windowbuttondownfcn', g.commandselect{1}); set(figh, 'windowbuttonmotionfcn', g.commandselect{2}); set(figh, 'windowbuttonupfcn', g.commandselect{3}); set(figh, 'WindowKeyPressFcn', @eegplot_readkey); set(figh, 'interruptible', 'off'); set(figh, 'busyaction', 'cancel'); % set(figh, 'windowbuttondownfcn', commandpush); % set(figh, 'windowbuttonmotionfcn', commandmove); % set(figh, 'windowbuttonupfcn', commandrelease); % set(figh, 'interruptible', 'off'); % set(figh, 'busyaction', 'cancel'); % prepare event array if any % -------------------------- if ~isempty(g.events) if ~isfield(g.events, 'type') | ~isfield(g.events, 'latency'), g.events = []; end; end; if ~isempty(g.events) if isstr(g.events(1).type) [g.eventtypes tmpind indexcolor] = unique_bc({g.events.type}); % indexcolor countinas the event type else [g.eventtypes tmpind indexcolor] = unique_bc([ g.events.type ]); end; g.eventcolors = { 'r', [0 0.8 0], 'm', 'c', 'k', 'b', [0 0.8 0] }; g.eventstyle = { '-' '-' '-' '-' '-' '-' '-' '--' '--' '--' '--' '--' '--' '--'}; g.eventwidths = [ 2.5 1 ]; g.eventtypecolors = g.eventcolors(mod([1:length(g.eventtypes)]-1 ,length(g.eventcolors))+1); g.eventcolors = g.eventcolors(mod(indexcolor-1 ,length(g.eventcolors))+1); g.eventtypestyle = g.eventstyle (mod([1:length(g.eventtypes)]-1 ,length(g.eventstyle))+1); g.eventstyle = g.eventstyle (mod(indexcolor-1 ,length(g.eventstyle))+1); % for width, only boundary events have width 2 (for the line) % ----------------------------------------------------------- indexwidth = ones(1,length(g.eventtypes))*2; if iscell(g.eventtypes) for index = 1:length(g.eventtypes) if strcmpi(g.eventtypes{index}, 'boundary'), indexwidth(index) = 1; end; end; end; g.eventtypewidths = g.eventwidths (mod(indexwidth([1:length(g.eventtypes)])-1 ,length(g.eventwidths))+1); g.eventwidths = g.eventwidths (mod(indexwidth(indexcolor)-1 ,length(g.eventwidths))+1); % latency and duration of events % ------------------------------ g.eventlatencies = [ g.events.latency ]+1; if isfield(g.events, 'duration') durations = { g.events.duration }; durations(cellfun(@isempty, durations)) = { NaN }; g.eventlatencyend = g.eventlatencies + [durations{:}]+1; else g.eventlatencyend = []; end; g.plotevent = 'on'; end; if isempty(g.events) g.plotevent = 'off'; end; set(figh, 'userdata', g); % %%%%%%%%%%%%%%%%%%%%%%%%%% % Plot EEG Data % %%%%%%%%%%%%%%%%%%%%%%%%%% axes(ax1) hold on % %%%%%%%%%%%%%%%%%%%%%%%%%% % Plot Spacing I % %%%%%%%%%%%%%%%%%%%%%%%%%% YLim = get(ax1,'Ylim'); A = DEFAULT_AXES_POSITION; axes('Position',[A(1)+A(3) A(2) 1-A(1)-A(3) A(4)],'Visible','off','Ylim',YLim,'tag','eyeaxes') axis manual if strcmp(SPACING_EYE,'on'), set(m(7),'checked','on') else set(m(7),'checked','off'); end eegplot('scaleeye', [], gcf); if strcmp(lower(g.scale), 'off') eegplot('scaleeye', 'off', gcf); end; eegplot('drawp', 0); eegplot('drawp', 0); if g.dispchans ~= g.chans eegplot('zoom', gcf); end; eegplot('scaleeye', [], gcf); h = findobj(gcf, 'style', 'pushbutton'); set(h, 'backgroundcolor', BUTTON_COLOR); h = findobj(gcf, 'tag', 'eegslider'); set(h, 'backgroundcolor', BUTTON_COLOR); set(figh, 'visible', 'on'); % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % End Main Function % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% else try, p1 = varargin{1}; p2 = varargin{2}; p3 = varargin{3}; catch, end; switch data case 'drawp' % Redraw EEG and change position % this test help to couple eegplot windows if exist('p3', 'var') figh = p3; figure(p3); else figh = gcf; % figure handle end; if strcmp(get(figh,'tag'),'dialog') figh = get(figh,'UserData'); end ax0 = findobj('tag','backeeg','parent',figh); % axes handle ax1 = findobj('tag','eegaxis','parent',figh); % axes handle g = get(figh,'UserData'); data = get(ax1,'UserData'); ESpacing = findobj('tag','ESpacing','parent',figh); % ui handle EPosition = findobj('tag','EPosition','parent',figh); % ui handle if ~isempty(EPosition) && ~isempty(ESpacing) if g.trialstag(1) == -1 g.time = str2num(get(EPosition,'string')); else g.time = str2num(get(EPosition,'string')); g.time = g.time - 1; end; g.spacing = str2num(get(ESpacing,'string')); end; if p1 == 1 g.time = g.time-g.winlength; % << subtract one window length elseif p1 == 2 g.time = g.time-fastif(g.winlength>=1, 1, g.winlength/5); % < subtract one second elseif p1 == 3 g.time = g.time+fastif(g.winlength>=1, 1, g.winlength/5); % > add one second elseif p1 == 4 g.time = g.time+g.winlength; % >> add one window length end if g.trialstag ~= -1 % time in second or in trials multiplier = g.trialstag; else multiplier = g.srate; end; % Update edit box % --------------- g.time = max(0,min(g.time,ceil((g.frames-1)/multiplier)-g.winlength)); if g.trialstag(1) == -1 set(EPosition,'string',num2str(g.time)); else set(EPosition,'string',num2str(g.time+1)); end; set(figh, 'userdata', g); lowlim = round(g.time*multiplier+1); highlim = round(min((g.time+g.winlength)*multiplier+2,g.frames)); % Plot data and update axes % ------------------------- if ~isempty(g.data2) switch lower(g.submean) % subtract the mean ? case 'on', meandata = mean(g.data2(:,lowlim:highlim)'); if any(isnan(meandata)) % 6/16/104 Ramon: meandata by memdata meandata = nan_mean(g.data2(:,lowlim:highlim)'); end; otherwise, meandata = zeros(1,g.chans); end; else switch lower(g.submean) % subtract the mean ? case 'on', meandata = mean(data(:,lowlim:highlim)'); if any(isnan(meandata)) meandata = nan_mean(data(:,lowlim:highlim)'); end; otherwise, meandata = zeros(1,g.chans); end; end; if strcmpi(g.plotdata2, 'off') axes(ax1) cla end; oldspacing = g.spacing; if g.envelope g.spacing = 0; end % plot data % --------- axes(ax1) hold on % plot channels whose "badchan" field is set to 1. % Bad channels are plotted first so that they appear behind the good % channels in the eegplot figure window. for i = 1:g.chans if strcmpi(g.plotdata2, 'on') tmpcolor = [ 1 0 0 ]; else tmpcolor = g.color{mod(i-1,length(g.color))+1}; end; if isfield(g, 'eloc_file') & ... isfield(g.eloc_file, 'badchan') & ... g.eloc_file(g.chans-i+1).badchan; tmpcolor = [ .85 .85 .85 ]; plot(data(g.chans-i+1,lowlim:highlim) -meandata(g.chans-i+1)+i*g.spacing + (g.dispchans+1)*(oldspacing-g.spacing)/2 +g.elecoffset*(oldspacing-g.spacing), ... 'color', tmpcolor, 'clipping','on') plot(1,mean(data(g.chans-i+1,lowlim:highlim) -meandata(g.chans-i+1)+i*g.spacing + (g.dispchans+1)*(oldspacing-g.spacing)/2 +g.elecoffset*(oldspacing-g.spacing),2),'<r','MarkerFaceColor','r','MarkerSize',6); end end % plot good channels on top of bad channels (if g.eloc_file(i).badchan = 0... or there is no bad channel information) for i = 1:g.chans if strcmpi(g.plotdata2, 'on') tmpcolor = [ 1 0 0 ]; else tmpcolor = g.color{mod(g.chans-i,length(g.color))+1}; end; % keyboard; if (isfield(g, 'eloc_file') & ... isfield(g.eloc_file, 'badchan') & ... ~g.eloc_file(g.chans-i+1).badchan) | ... (~isfield(g, 'eloc_file')) | ... (~isfield(g.eloc_file, 'badchan')); plot(data(g.chans-i+1,lowlim:highlim) -meandata(g.chans-i+1)+i*g.spacing + (g.dispchans+1)*(oldspacing-g.spacing)/2 +g.elecoffset*(oldspacing-g.spacing), ... 'color', tmpcolor, 'clipping','on') end end % draw selected channels % ------------------------ if ~isempty(g.winrej) & size(g.winrej,2) > 2 for tpmi = 1:size(g.winrej,1) % scan rows if (g.winrej(tpmi,1) >= lowlim & g.winrej(tpmi,1) <= highlim) | ... (g.winrej(tpmi,2) >= lowlim & g.winrej(tpmi,2) <= highlim) abscmin = max(1,round(g.winrej(tpmi,1)-lowlim)); abscmax = round(g.winrej(tpmi,2)-lowlim); maxXlim = get(gca, 'xlim'); abscmax = min(abscmax, round(maxXlim(2)-1)); for i = 1:g.chans if g.winrej(tpmi,g.chans-i+1+5) plot(abscmin+1:abscmax+1,data(g.chans-i+1,abscmin+lowlim:abscmax+lowlim) ... -meandata(g.chans-i+1)+i*g.spacing + (g.dispchans+1)*(oldspacing-g.spacing)/2 +g.elecoffset*(oldspacing-g.spacing), 'color','r','clipping','on') end; end end; end; end; g.spacing = oldspacing; set(ax1, 'Xlim',[1 g.winlength*multiplier+1],... 'XTick',[1:multiplier*DEFAULT_GRID_SPACING:g.winlength*multiplier+1]); if g.isfreq % Ramon set(ax1, 'XTickLabel', num2str((g.freqs(1):DEFAULT_GRID_SPACING:g.freqs(end))')); else set(ax1, 'XTickLabel', num2str((g.time:DEFAULT_GRID_SPACING:g.time+g.winlength)')); end % ordinates: even if all elec are plotted, some may be hidden set(ax1, 'ylim',[g.elecoffset*g.spacing (g.elecoffset+g.dispchans+1)*g.spacing] ); if g.children ~= 0 if ~exist('p2', 'var') p2 =[]; end; eegplot( 'drawp', p1, p2, g.children); figure(figh); end; % draw second data if necessary if ~isempty(g.data2) tmpdata = data; set(ax1, 'userdata', g.data2); g.data2 = []; g.plotdata2 = 'on'; set(figh, 'userdata', g); eegplot('drawp', 0); g.plotdata2 = 'off'; g.data2 = get(ax1, 'userdata'); set(ax1, 'userdata', tmpdata); set(figh, 'userdata', g); else eegplot('drawb'); end; case 'drawb' % Draw background ****************************************************** % Redraw EEG and change position ax0 = findobj('tag','backeeg','parent',gcf); % axes handle ax1 = findobj('tag','eegaxis','parent',gcf); % axes handle g = get(gcf,'UserData'); % Data (Note: this could also be global) % Plot data and update axes axes(ax0); cla; hold on; % plot rejected windows if g.trialstag ~= -1 multiplier = g.trialstag; else multiplier = g.srate; end; % draw rejection windows % ---------------------- lowlim = round(g.time*multiplier+1); highlim = round(min((g.time+g.winlength)*multiplier+1)); displaymenu = findobj('tag','displaymenu','parent',gcf); if ~isempty(g.winrej) & g.winstatus if g.trialstag ~= -1 % epoched data indices = find((g.winrej(:,1)' >= lowlim & g.winrej(:,1)' <= highlim) | ... (g.winrej(:,2)' >= lowlim & g.winrej(:,2)' <= highlim)); if ~isempty(indices) tmpwins1 = g.winrej(indices,1)'; tmpwins2 = g.winrej(indices,2)'; if size(g.winrej,2) > 2 tmpcols = g.winrej(indices,3:5); else tmpcols = g.wincolor; end; try, eval('[cumul indicescount] = histc(tmpwins1, (min(tmpwins1)-1):g.trialstag:max(tmpwins2));'); catch, [cumul indicescount] = myhistc(tmpwins1, (min(tmpwins1)-1):g.trialstag:max(tmpwins2)); end; count = zeros(size(cumul)); %if ~isempty(find(cumul > 1)), find(cumul > 1), end; for tmpi = 1:length(tmpwins1) poscumul = indicescount(tmpi); heightbeg = count(poscumul)/cumul(poscumul); heightend = heightbeg + 1/cumul(poscumul); count(poscumul) = count(poscumul)+1; h = patch([tmpwins1(tmpi)-lowlim tmpwins2(tmpi)-lowlim ... tmpwins2(tmpi)-lowlim tmpwins1(tmpi)-lowlim], ... [heightbeg heightbeg heightend heightend], ... tmpcols(tmpi,:)); % this argument is color set(h, 'EdgeColor', get(h, 'facecolor')) end; end; else event2plot1 = find ( g.winrej(:,1) >= lowlim & g.winrej(:,1) <= highlim ); event2plot2 = find ( g.winrej(:,2) >= lowlim & g.winrej(:,2) <= highlim ); event2plot3 = find ( g.winrej(:,1) < lowlim & g.winrej(:,2) > highlim ); event2plot = union_bc(union(event2plot1, event2plot2), event2plot3); for tpmi = event2plot(:)' if size(g.winrej,2) > 2 tmpcols = g.winrej(tpmi,3:5); else tmpcols = g.wincolor; end; h = patch([g.winrej(tpmi,1)-lowlim g.winrej(tpmi,2)-lowlim ... g.winrej(tpmi,2)-lowlim g.winrej(tpmi,1)-lowlim], ... [0 0 1 1], tmpcols); set(h, 'EdgeColor', get(h, 'facecolor')) end; end; end; % plot tags % --------- %if trialtag(1) ~= -1 & displaystatus % put tags at arbitrary places % for tmptag = trialtag % if tmptag >= lowlim & tmptag <= highlim % plot([tmptag-lowlim tmptag-lowlim], [0 1], 'b--'); % end; % end; %end; % draw events if any % ------------------ if strcmpi(g.plotevent, 'on') % JavierLC ############################### MAXEVENTSTRING = g.maxeventstring; if MAXEVENTSTRING<0 MAXEVENTSTRING = 0; elseif MAXEVENTSTRING>75 MAXEVENTSTRING=75; end AXES_POSITION = [0.0964286 0.15 0.842 0.75-(MAXEVENTSTRING-5)/100]; % JavierLC ############################### % find event to plot % ------------------ event2plot = find ( g.eventlatencies >=lowlim & g.eventlatencies <= highlim ); if ~isempty(g.eventlatencyend) event2plot2 = find ( g.eventlatencyend >= lowlim & g.eventlatencyend <= highlim ); event2plot3 = find ( g.eventlatencies < lowlim & g.eventlatencyend > highlim ); event2plot = union_bc(union(event2plot, event2plot2), event2plot3); end; for index = 1:length(event2plot) % draw latency line % ----------------- tmplat = g.eventlatencies(event2plot(index))-lowlim-1; tmph = plot([ tmplat tmplat ], ylim, 'color', g.eventcolors{ event2plot(index) }, ... 'linestyle', g.eventstyle { event2plot(index) }, ... 'linewidth', g.eventwidths( event2plot(index) ) ); % schtefan: add Event types text above event latency line % ------------------------------------------------------- EVENTFONT = ' \fontsize{10} '; ylims=ylim; evntxt = strrep(num2str(g.events(event2plot(index)).type),'_','-'); if length(evntxt)>MAXEVENTSTRING, evntxt = [ evntxt(1:MAXEVENTSTRING-1) '...' ]; end; % truncate try, tmph2 = text([tmplat], ylims(2)-0.005, [EVENTFONT evntxt], ... 'color', g.eventcolors{ event2plot(index) }, ... 'horizontalalignment', 'left',... 'rotation',90); catch, end; % draw duration is not 0 % ---------------------- if g.ploteventdur & ~isempty(g.eventlatencyend) ... & g.eventwidths( event2plot(index) ) ~= 2.5 % do not plot length of boundary events tmplatend = g.eventlatencyend(event2plot(index))-lowlim-1; if tmplatend ~= 0, tmplim = ylim; tmpcol = g.eventcolors{ event2plot(index) }; h = patch([ tmplat tmplatend tmplatend tmplat ], ... [ tmplim(1) tmplim(1) tmplim(2) tmplim(2) ], ... tmpcol ); % this argument is color set(h, 'EdgeColor', 'none') end; end; end; else % JavierLC MAXEVENTSTRING = 10; % default AXES_POSITION = [0.0964286 0.15 0.842 0.75-(MAXEVENTSTRING-5)/100]; end; if g.trialstag(1) ~= -1 % plot trial limits % ----------------- tmptag = [lowlim:highlim]; tmpind = find(mod(tmptag-1, g.trialstag) == 0); for index = tmpind plot([tmptag(index)-lowlim-1 tmptag(index)-lowlim-1], [0 1], 'b--'); end; alltag = tmptag(tmpind); % compute Xticks % -------------- tagnum = (alltag-1)/g.trialstag+1; set(ax0,'XTickLabel', tagnum,'YTickLabel', [],... 'Xlim',[0 g.winlength*multiplier],... 'XTick',alltag-lowlim+g.trialstag/2, 'YTick',[], 'tag','backeeg'); axes(ax1); tagpos = []; tagtext = []; if ~isempty(alltag) alltag = [alltag(1)-g.trialstag alltag alltag(end)+g.trialstag]; % add border trial limits else alltag = [ floor(lowlim/g.trialstag)*g.trialstag ceil(highlim/g.trialstag)*g.trialstag ]+1; end; nbdiv = 20/g.winlength; % approximative number of divisions divpossible = [ 100000./[1 2 4 5] 10000./[1 2 4 5] 1000./[1 2 4 5] 100./[1 2 4 5 10 20]]; % possible increments [tmp indexdiv] = min(abs(nbdiv*divpossible-(g.limits(2)-g.limits(1)))); % closest possible increment incrementpoint = divpossible(indexdiv)/1000*g.srate; % tag zero below is an offset used to be sure that 0 is included % in the absicia of the data epochs if g.limits(2) < 0, tagzerooffset = (g.limits(2)-g.limits(1))/1000*g.srate+1; else tagzerooffset = -g.limits(1)/1000*g.srate; end; if tagzerooffset < 0, tagzerooffset = 0; end; for i=1:length(alltag)-1 if ~isempty(tagpos) & tagpos(end)-alltag(i)<2*incrementpoint/3 tagpos = tagpos(1:end-1); end; if ~isempty(g.freqlimits) tagpos = [ tagpos linspace(alltag(i),alltag(i+1)-1, nbdiv) ]; else if tagzerooffset ~= 0 tmptagpos = [alltag(i)+tagzerooffset:-incrementpoint:alltag(i)]; else tmptagpos = []; end; tagpos = [ tagpos [tmptagpos(end:-1:2) alltag(i)+tagzerooffset:incrementpoint:(alltag(i+1)-1)]]; end; end; % find corresponding epochs % ------------------------- tagtext = eeg_point2lat(tagpos, floor((tagpos)/g.trialstag)+1, g.srate, g.limits, 1E-3); set(ax1,'XTickLabel', tagtext,'XTick', tagpos-lowlim); else set(ax0,'XTickLabel', [],'YTickLabel', [],... 'Xlim',[0 g.winlength*multiplier],... 'XTick',[], 'YTick',[], 'tag','backeeg'); axes(ax1); if g.isfreq % Ramon set(ax1, 'XTickLabel', num2str((g.freqs(1):DEFAULT_GRID_SPACING:g.freqs(end))'),... 'XTick',[1:multiplier*DEFAULT_GRID_SPACING:g.winlength*multiplier+1]); else set(ax1,'XTickLabel', num2str((g.time:DEFAULT_GRID_SPACING:g.time+g.winlength)'),... 'XTick',[1:multiplier*DEFAULT_GRID_SPACING:g.winlength*multiplier+1]); end set(ax1, 'Position', AXES_POSITION) % JavierLC set(ax0, 'Position', AXES_POSITION) % JavierLC end; % ordinates: even if all elec are plotted, some may be hidden set(ax1, 'ylim',[g.elecoffset*g.spacing (g.elecoffset+g.dispchans+1)*g.spacing] ); axes(ax1) case 'draws' % Redraw EEG and change scale ax1 = findobj('tag','eegaxis','parent',gcf); % axes handle g = get(gcf,'UserData'); data = get(ax1, 'userdata'); ESpacing = findobj('tag','ESpacing','parent',gcf); % ui handle EPosition = findobj('tag','EPosition','parent',gcf); % ui handle if g.trialstag(1) == -1 g.time = str2num(get(EPosition,'string')); else g.time = str2num(get(EPosition,'string'))-1; end; g.spacing = str2num(get(ESpacing,'string')); orgspacing= g.spacing; if p1 == 1 g.spacing= g.spacing+ 0.1*orgspacing; % increase g.spacing(5%) elseif p1 == 2 g.spacing= max(0,g.spacing-0.1*orgspacing); % decrease g.spacing(5%) end if round(g.spacing*100) == 0 maxindex = min(10000, g.frames); g.spacing = 0.01*max(max(data(:,1:maxindex),[],2),[],1)-min(min(data(:,1:maxindex),[],2),[],1); % Set g.spacingto max/min data end; % update edit box % --------------- set(ESpacing,'string',num2str(g.spacing,4)) set(gcf, 'userdata', g); eegplot('drawp', 0); set(ax1,'YLim',[0 (g.chans+1)*g.spacing],'YTick',[0:g.spacing:g.chans*g.spacing]) set(ax1, 'ylim',[g.elecoffset*g.spacing (g.elecoffset+g.dispchans+1)*g.spacing] ); % update scaling eye (I) if it exists % ----------------------------------- eyeaxes = findobj('tag','eyeaxes','parent',gcf); if ~isempty(eyeaxes) eyetext = findobj('type','text','parent',eyeaxes,'tag','thescalenum'); set(eyetext,'string',num2str(g.spacing,4)) end return; case 'window' % change window size % get new window length with dialog box % ------------------------------------- g = get(gcf,'UserData'); result = inputdlg2( { fastif(g.trialstag==-1,'New window length (s):', 'Number of epoch(s):') }, 'Change window length', 1, { num2str(g.winlength) }); if size(result,1) == 0 return; end; g.winlength = eval(result{1}); set(gcf, 'UserData', g); eegplot('drawp',0); return; case 'winelec' % change channel window size % get new window length with dialog box % ------------------------------------- fig = gcf; g = get(gcf,'UserData'); result = inputdlg2( ... { 'Number of channels to display:' } , 'Change number of channels to display', 1, { num2str(g.dispchans) }); if size(result,1) == 0 return; end; g.dispchans = eval(result{1}); if g.dispchans<0 | g.dispchans>g.chans g.dispchans =g.chans; end; set(gcf, 'UserData', g); eegplot('updateslider', fig); eegplot('drawp',0); eegplot('scaleeye', [], fig); return; case 'emaxstring' % change events' string length ; JavierLC % get dialog box % ------------------------------------- g = get(gcf,'UserData'); result = inputdlg2({ 'Max events'' string length:' } , 'Change events'' string length to display', 1, { num2str(g.maxeventstring) }); if size(result,1) == 0 return; end; g.maxeventstring = eval(result{1}); set(gcf, 'UserData', g); eegplot('drawb'); return; case 'loadelect' % load channels [inputname,inputpath] = uigetfile('*','Channel locations file'); if inputname == 0 return; end; if ~exist([ inputpath inputname ]) error('no such file'); end; AXH0 = findobj('tag','eegaxis','parent',gcf); eegplot('setelect',[ inputpath inputname ],AXH0); return; case 'setelect' % Set channels eloc_file = p1; axeshand = p2; outvar1 = 1; if isempty(eloc_file) outvar1 = 0; return end tmplocs = readlocs(eloc_file); YLabels = { tmplocs.labels }; YLabels = strvcat(YLabels); YLabels = flipud(str2mat(YLabels,' ')); set(axeshand,'YTickLabel',YLabels) case 'title' % Get new title h = findobj('tag', 'eegplottitle'); if ~isempty(h) result = inputdlg2( { 'New title:' }, 'Change title', 1, { get(h(1), 'string') }); if ~isempty(result), set(h, 'string', result{1}); end; else result = inputdlg2( { 'New title:' }, 'Change title', 1, { '' }); if ~isempty(result), h = textsc(result{1}, 'title'); set(h, 'tag', 'eegplottitle');end; end; return; case 'scaleeye' % Turn scale I on/off obj = p1; figh = p2; g = get(figh,'UserData'); % figh = get(obj,'Parent'); if ~isempty(obj) eyeaxes = findobj('tag','eyeaxes','parent',figh); children = get(eyeaxes,'children'); if isstr(obj) if strcmp(obj, 'off') set(children, 'visible', 'off'); set(eyeaxes, 'visible', 'off'); return; else set(children, 'visible', 'on'); set(eyeaxes, 'visible', 'on'); end; else toggle = get(obj,'checked'); if strcmp(toggle,'on') set(children, 'visible', 'off'); set(eyeaxes, 'visible', 'off'); set(obj,'checked','off'); return; else set(children, 'visible', 'on'); set(eyeaxes, 'visible', 'on'); set(obj,'checked','on'); end; end; end; eyeaxes = findobj('tag','eyeaxes','parent',figh); ax1 = findobj('tag','eegaxis','parent',gcf); % axes handle YLim = double(get(ax1, 'ylim')); ESpacing = findobj('tag','ESpacing','parent',figh); g.spacing= str2num(get(ESpacing,'string')); axes(eyeaxes); cla; axis off; set(eyeaxes, 'ylim', YLim); Xl = double([.35 .65; .5 .5; .35 .65]); Yl = double([ g.spacing g.spacing; g.spacing 0; 0 0] + YLim(1)); plot(Xl(1,:),Yl(1,:),'color',DEFAULT_AXIS_COLOR,'clipping','off', 'tag','eyeline'); hold on; plot(Xl(2,:),Yl(2,:),'color',DEFAULT_AXIS_COLOR,'clipping','off', 'tag','eyeline'); plot(Xl(3,:),Yl(3,:),'color',DEFAULT_AXIS_COLOR,'clipping','off', 'tag','eyeline'); text(.5,(YLim(2)-YLim(1))/23+Yl(1),num2str(g.spacing,4),... 'HorizontalAlignment','center','FontSize',10,... 'tag','thescalenum') text(Xl(2)+.1,Yl(1),'+','HorizontalAlignment','left',... 'verticalalignment','middle', 'tag', 'thescale') text(Xl(2)+.1,Yl(4),'-','HorizontalAlignment','left',... 'verticalalignment','middle', 'tag', 'thescale') if ~isempty(SPACING_UNITS_STRING) text(.5,-YLim(2)/23+Yl(4),SPACING_UNITS_STRING,... 'HorizontalAlignment','center','FontSize',10, 'tag', 'thescale') end text(.5,(YLim(2)-YLim(1))/10+Yl(1),'Scale',... 'HorizontalAlignment','center','FontSize',10, 'tag', 'thescale') set(eyeaxes, 'tag', 'eyeaxes'); case 'noui' if ~isempty(varargin) eegplot( varargin{:} ); fig = gcf; else fig = findobj('tag', 'EEGPLOT'); end; set(fig, 'menubar', 'figure'); % find button and text obj = findobj(fig, 'style', 'pushbutton'); delete(obj); obj = findobj(fig, 'style', 'edit'); delete(obj); obj = findobj(fig, 'style', 'text'); %objscale = findobj(obj, 'tag', 'thescale'); %delete(setdiff(obj, objscale)); obj = findobj(fig, 'tag', 'Eelec');delete(obj); obj = findobj(fig, 'tag', 'Etime');delete(obj); obj = findobj(fig, 'tag', 'Evalue');delete(obj); obj = findobj(fig, 'tag', 'Eelecname');delete(obj); obj = findobj(fig, 'tag', 'Etimename');delete(obj); obj = findobj(fig, 'tag', 'Evaluename');delete(obj); obj = findobj(fig, 'type', 'uimenu');delete(obj); case 'zoom' % if zoom fig = varargin{1}; ax1 = findobj('tag','eegaxis','parent',fig); ax2 = findobj('tag','backeeg','parent',fig); tmpxlim = get(ax1, 'xlim'); tmpylim = get(ax1, 'ylim'); tmpxlim2 = get(ax2, 'xlim'); set(ax2, 'xlim', get(ax1, 'xlim')); g = get(fig,'UserData'); % deal with abscissa % ------------------ if g.trialstag ~= -1 Eposition = str2num(get(findobj('tag','EPosition','parent',fig), 'string')); g.winlength = (tmpxlim(2) - tmpxlim(1))/g.trialstag; Eposition = Eposition + (tmpxlim(1) - tmpxlim2(1)-1)/g.trialstag; Eposition = round(Eposition*1000)/1000; set(findobj('tag','EPosition','parent',fig), 'string', num2str(Eposition)); else Eposition = str2num(get(findobj('tag','EPosition','parent',fig), 'string'))-1; g.winlength = (tmpxlim(2) - tmpxlim(1))/g.srate; Eposition = Eposition + (tmpxlim(1) - tmpxlim2(1)-1)/g.srate; Eposition = round(Eposition*1000)/1000; set(findobj('tag','EPosition','parent',fig), 'string', num2str(Eposition+1)); end; % deal with ordinate % ------------------ g.elecoffset = tmpylim(1)/g.spacing; g.dispchans = round(1000*(tmpylim(2)-tmpylim(1))/g.spacing)/1000; set(fig,'UserData', g); eegplot('updateslider', fig); eegplot('drawp', 0); eegplot('scaleeye', [], fig); % reactivate zoom if 3 arguments % ------------------------------ if exist('p2', 'var') == 1 set(gcbf, 'windowbuttondownfcn', [ 'zoom(gcbf,''down''); eegplot(''zoom'', gcbf, 1);' ]); set(gcbf, 'windowbuttonmotionfcn', g.commandselect{2}); end; case 'updateslider' % if zoom fig = varargin{1}; g = get(fig,'UserData'); sliider = findobj('tag','eegslider','parent',fig); if g.elecoffset < 0 g.elecoffset = 0; end; if g.dispchans >= g.chans g.dispchans = g.chans; g.elecoffset = 0; set(sliider, 'visible', 'off'); else set(sliider, 'visible', 'on'); set(sliider, 'value', g.elecoffset/g.chans, ... 'sliderstep', [1/(g.chans-g.dispchans) g.dispchans/(g.chans-g.dispchans)]); %'sliderstep', [1/(g.chans-1) g.dispchans/(g.chans-1)]); end; if g.elecoffset < 0 g.elecoffset = 0; end; if g.elecoffset > g.chans-g.dispchans g.elecoffset = g.chans-g.dispchans; end; set(fig,'UserData', g); eegplot('scaleeye', [], fig); case 'drawlegend' fig = varargin{1}; g = get(fig,'UserData'); if ~isempty(g.events) % draw vertical colored lines for events, add event name text above nleg = length(g.eventtypes); fig2 = figure('numbertitle', 'off', 'name', '', 'visible', 'off', 'menubar', 'none', 'color', DEFAULT_FIG_COLOR); pos = get(fig2, 'position'); set(fig2, 'position', [ pos(1) pos(2) 130 14*nleg+20]); for index = 1:nleg plot([10 30], [(index-0.5) * 10 (index-0.5) * 10], 'color', g.eventtypecolors{index}, 'linestyle', ... g.eventtypestyle{ index }, 'linewidth', g.eventtypewidths( index )); hold on; if iscell(g.eventtypes) th=text(35, (index-0.5)*10, g.eventtypes{index}, ... 'color', g.eventtypecolors{index}); else th=text(35, (index-0.5)*10, num2str(g.eventtypes(index)), ... 'color', g.eventtypecolors{index}); end; end; xlim([0 130]); ylim([0 nleg*10]); axis off; set(fig2, 'visible', 'on'); end; % motion button: move windows or display current position (channel, g.time and activation) % ---------------------------------------------------------------------------------------- case 'defmotioncom' fig = varargin{1}; g = get(fig,'UserData'); ax1 = findobj('tag','backeeg','parent',fig); tmppos = get(ax1, 'currentpoint'); if g.trialstag ~= -1, lowlim = round(g.time*g.trialstag+1); else, lowlim = round(g.time*g.srate+1); end; if g.incallback g.winrej = [g.winrej(1:end-1,:)' [g.winrej(end,1) tmppos(1)+lowlim g.winrej(end,3:end)]']'; set(fig,'UserData', g); eegplot('drawb'); else hh = findobj('tag','Etime','parent',fig); if g.trialstag ~= -1, set(hh, 'string', num2str(mod(tmppos(1)+lowlim-1,g.trialstag)/g.trialstag*(g.limits(2)-g.limits(1)) + g.limits(1))); else set(hh, 'string', num2str((tmppos(1)+lowlim-1)/g.srate)); % put g.time in the box end; ax1 = findobj('tag','eegaxis','parent',fig); tmppos = get(ax1, 'currentpoint'); tmpelec = round(tmppos(1,2) / g.spacing); tmpelec = min(max(double(tmpelec), 1),g.chans); labls = get(ax1, 'YtickLabel'); hh = findobj('tag','Eelec','parent',fig); % put electrode in the box if ~g.envelope set(hh, 'string', labls(tmpelec+1,:)); else set(hh, 'string', ' '); end hh = findobj('tag','Evalue','parent',fig); if ~g.envelope eegplotdata = get(ax1, 'userdata'); set(hh, 'string', num2str(eegplotdata(g.chans+1-tmpelec, min(g.frames,max(1,double(round(tmppos(1)+lowlim))))))); % put value in the box else set(hh,'string',' '); end end; % add topoplot % ------------ case 'topoplot' fig = varargin{1}; g = get(fig,'UserData'); if ~isstruct(g.eloc_file) || ~isfield(g.eloc_file, 'theta') || isempty( [ g.eloc_file.theta ]) return; end; ax1 = findobj('tag','backeeg','parent',fig); tmppos = get(ax1, 'currentpoint'); ax1 = findobj('tag','eegaxis','parent',fig); % axes handle % plot vertical line yl = ylim; plot([ tmppos tmppos ], yl, 'color', [0.8 0.8 0.8]); if g.trialstag ~= -1, lowlim = round(g.time*g.trialstag+1); else, lowlim = round(g.time*g.srate+1); end; data = get(ax1,'UserData'); datapos = max(1, round(tmppos(1)+lowlim)); datapos = min(datapos, g.frames); figure; topoplot(data(:,datapos), g.eloc_file); if g.trialstag == -1, latsec = (datapos-1)/g.srate; title(sprintf('Latency of %d seconds and %d milliseconds', floor(latsec), round(1000*(latsec-floor(latsec))))); else trial = ceil((datapos-1)/g.trialstag); latintrial = eeg_point2lat(datapos, trial, g.srate, g.limits, 0.001); title(sprintf('Latency of %d ms in trial %d', round(latintrial), trial)); end; return; % release button: check window consistency, add to trial boundaries % ------------------------------------------------------------------- case 'defupcom' fig = varargin{1}; g = get(fig,'UserData'); ax1 = findobj('tag','backeeg','parent',fig); g.incallback = 0; set(fig,'UserData', g); % early save in case of bug in the following if strcmp(g.mocap,'on'), g.winrej = g.winrej(end,:);end; % nima if ~isempty(g.winrej)', ... if g.winrej(end,1) == g.winrej(end,2) % remove unitary windows g.winrej = g.winrej(1:end-1,:); else if g.winrej(end,1) > g.winrej(end,2) % reverse values if necessary g.winrej(end, 1:2) = [g.winrej(end,2) g.winrej(end,1)]; end; g.winrej(end,1) = max(1, g.winrej(end,1)); g.winrej(end,2) = min(g.frames, g.winrej(end,2)); if g.trialstag == -1 % find nearest trials boundaries if necessary I1 = find((g.winrej(end,1) >= g.winrej(1:end-1,1)) & (g.winrej(end,1) <= g.winrej(1:end-1,2)) ); if ~isempty(I1) g.winrej(I1,2) = max(g.winrej(I1,2), g.winrej(end,2)); % extend epoch g.winrej = g.winrej(1:end-1,:); % remove if empty match else, I2 = find((g.winrej(end,2) >= g.winrej(1:end-1,1)) & (g.winrej(end,2) <= g.winrej(1:end-1,2)) ); if ~isempty(I2) g.winrej(I2,1) = min(g.winrej(I2,1), g.winrej(end,1)); % extend epoch g.winrej = g.winrej(1:end-1,:); % remove if empty match else, I2 = find((g.winrej(end,1) <= g.winrej(1:end-1,1)) & (g.winrej(end,2) >= g.winrej(1:end-1,1)) ); if ~isempty(I2) g.winrej(I2,:) = []; % remove if empty match end; end; end; end; end; end; set(fig,'UserData', g); eegplot('drawp', 0); if strcmp(g.mocap,'on'), show_mocap_for_eegplot(g.winrej); g.winrej = g.winrej(end,:); end; % nima % push button: create/remove window % --------------------------------- case 'defdowncom' show_mocap_timer = timerfind('tag','mocapDisplayTimer'); if ~isempty(show_mocap_timer), end; % nima fig = varargin{1}; g = get(fig,'UserData'); ax1 = findobj('tag','backeeg','parent',fig); tmppos = get(ax1, 'currentpoint'); if strcmp(get(fig, 'SelectionType'),'normal'); g = get(fig,'UserData'); % get data of backgroung image {g.trialstag g.winrej incallback} if g.incallback ~= 1 % interception of nestest calls if g.trialstag ~= -1, lowlim = round(g.time*g.trialstag+1); highlim = round(g.winlength*g.trialstag); else, lowlim = round(g.time*g.srate+1); highlim = round(g.winlength*g.srate); end; if (tmppos(1) >= 0) & (tmppos(1) <= highlim), if isempty(g.winrej) Allwin=0; else Allwin = (g.winrej(:,1) < lowlim+tmppos(1)) & (g.winrej(:,2) > lowlim+tmppos(1)); end; if any(Allwin) % remove the mark or select electrode if necessary lowlim = find(Allwin==1); if g.setelectrode % select electrode ax2 = findobj('tag','eegaxis','parent',fig); tmppos = get(ax2, 'currentpoint'); tmpelec = g.chans + 1 - round(tmppos(1,2) / g.spacing); tmpelec = min(max(tmpelec, 1), g.chans); g.winrej(lowlim,tmpelec+5) = ~g.winrej(lowlim,tmpelec+5); % set the electrode else % remove mark g.winrej(lowlim,:) = []; end; else if g.trialstag ~= -1 % find nearest trials boundaries if epoched data alltrialtag = [0:g.trialstag:g.frames]; I1 = find(alltrialtag < (tmppos(1)+lowlim) ); if ~isempty(I1) & I1(end) ~= length(alltrialtag), g.winrej = [g.winrej' [alltrialtag(I1(end)) alltrialtag(I1(end)+1) g.wincolor zeros(1,g.chans)]']'; end; else, g.incallback = 1; % set this variable for callback for continuous data if size(g.winrej,2) < 5 g.winrej(:,3:5) = repmat(g.wincolor, [size(g.winrej,1) 1]); end; if size(g.winrej,2) < 5+g.chans g.winrej(:,6:(5+g.chans)) = zeros(size(g.winrej,1),g.chans); end; g.winrej = [g.winrej' [tmppos(1)+lowlim tmppos(1)+lowlim g.wincolor zeros(1,g.chans)]']'; end; end; set(fig,'UserData', g); eegplot('drawp', 0); % redraw background end; end; end; otherwise error(['Error - invalid eegplot() parameter: ',data]) end end % function not supported under Mac % -------------------------------- function [reshist, allbin] = myhistc(vals, intervals); reshist = zeros(1, length(intervals)); allbin = zeros(1, length(vals)); for index=1:length(vals) minvals = vals(index)-intervals; bintmp = find(minvals >= 0); [mintmp indextmp] = min(minvals(bintmp)); bintmp = bintmp(indextmp); allbin(index) = bintmp; reshist(bintmp) = reshist(bintmp)+1; end;
github
ZijingMao/baselineeegtest-master
uigetfile2.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/uigetfile2.m
2,667
utf_8
a344bcefaca772c110df38301343a003
% uigetfile2() - same as uigetfile but remember folder location. % % Usage: >> uigetfile2(...) % % Inputs: Same as uigetfile % % Author: Arnaud Delorme & Hilit Serby, Scott Makeig, SCCN, UCSD, 2004 % Thanks to input from Bas Kortmann % % Copyright (C) Arnaud Delorme & Hilit Serby, Scott Makeig, SCCN, UCSD, 2004 % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function varargout = uigetfile2(varargin); if nargin < 1 help uigetfile2; return; end; % remember old folder %% search for the (mat) file which contains the latest used directory % ------------------- olddir = pwd; try, eeglab_options; if option_rememberfolder tmp_fld = getenv('TEMP'); if isempty(tmp_fld) & isunix if exist('/tmp') == 7 tmp_fld = '/tmp'; end; end; if exist(fullfile(tmp_fld,'eeglab.cfg')) load(fullfile(tmp_fld,'eeglab.cfg'),'Path','-mat'); s = ['cd([''' Path '''])']; if exist(Path) == 7, eval(s); end; end; end; catch, end; %% Show the open dialog and save the latest directory to the file % --------------------------------------------------------------- [varargout{1} varargout{2}] = uigetfile(varargin{:}); try, if option_rememberfolder if varargout{1} ~= 0 Path = varargout{2}; try, save(fullfile(tmp_fld,'eeglab.cfg'),'Path','-mat','-V6'); % Matlab 7 catch, try, save(fullfile(tmp_fld,'eeglab.cfg'),'Path','-mat'); catch, error('uigetfile2: save error, out of space or file permission problem'); end end if isunix eval(['cd ' tmp_fld]); system('chmod 777 eeglab.cfg'); end end; end; catch, end; cd(olddir)
github
ZijingMao/baselineeegtest-master
readelp.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/readelp.m
3,428
utf_8
2869dca997f92d27420c23c7cf912e6f
% readelp() - read electrode locations from an .elp (electrode positions) % file as generated, for example, by a Polhemus tracking device % Usage: % >> [eloc, elocnames, X, Y, Z] = readelp(filename); % % Inputs: % filename - name of the .elp file containing cartesian (XYZ) electrode % locations % Outputs: % eloc - structure containing the names and locations of the channels % elocnames - cell array containing the names of the electrodes % X,Y,Z - vectors containing the xyz locations of the electrodes % % Author: Arnaud Delorme, CNL / Salk Institute, 28 Feb 2002 % % Note: ignores comments and the sensor type field % Note: convert output XYZ locations to polar coordinates using cart2pol() % % See also: readlocs(), snapread(), floatread(), cart2pol() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 28 Feb 2002 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [eloc, names, x, y, z] = readelp( filename ); if nargin < 1 help readelp; return; end; % open file % --------- fid = fopen(filename, 'r'); if fid == -1 disp('Cannot open file'); return; end; index = 1; countfid = 1; fidlabels = { 'Nz' 'LPA' 'RPA' }; needToReadNumbers = 0; tmpstr = fgetl(fid); while 1 if needToReadNumbers==1 % Has sparsed $N. if (~isempty(str2num(tmpstr))) tmp = sscanf(tmpstr, '%f'); eloc(index).X = tmp(1); x(index) = tmp(1); eloc(index).Y = tmp(2); y(index) = tmp(2); eloc(index).Z = tmp(3); z(index) = tmp(3); eloc(index).type = 'EEG'; index = index + 1; needToReadNumbers = 0; end; elseif tmpstr(1) == '%' if tmpstr(2) == 'F' % fiducial tmp = sscanf(tmpstr(3:end), '%f'); eloc(index).labels = fidlabels{countfid}; eloc(index).X = tmp(1); x(index) = tmp(1); eloc(index).Y = tmp(2); y(index) = tmp(2); eloc(index).Z = tmp(3); z(index) = tmp(3); eloc(index).type = 'FID'; index = index + 1; countfid = countfid + 1; elseif tmpstr(2) == 'N' % regular channel nm = strtok(tmpstr(3:end)); if ~(strcmp(nm, 'Name') | strcmp(nm, 'Status')) eloc(index).labels = nm; needToReadNumbers = 1; end; end; end; % Get the next line tmpstr = fgetl(fid); while isempty(tmpstr) tmpstr = fgetl(fid); if ~isstr(tmpstr) & tmpstr == -1 break; end; end; if ~isstr(tmpstr) & tmpstr == -1 break; end; end; names = { eloc.labels }; fclose(fid); % close the file
github
ZijingMao/baselineeegtest-master
plottopo.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/plottopo.m
30,821
utf_8
eba3d347d7a02858e68b8395d284199f
% plottopo() - plot concatenated multichannel data epochs in a topographic % or % rectangular array. Uses a channel location file with the same % format as topoplot(), or else plots data on a rectangular grid. % If data are all positive, they are assumed to be spectra. % Usage: % >> plottopo(data, 'key1', 'val1', 'key2', 'val2') % Or % >> plottopo(data,'chan_locs',frames,limits,title,channels,... % axsize,colors,ydir,vert) % old function call % Inputs: % data = data consisting of consecutive epochs of (chans,frames) % or (chans,frames,n) % % Optional inputs: % 'chanlocs' = [struct] channel structure or file plot ERPs at channel % locations. See help readlocs() for data channel format. % 'geom' = [rows cols] plot ERP in grid (overwrite previous option). % Grid size for rectangular matrix. Example: [6 4]. % 'frames' = time frames (points) per epoch {def|0 -> data length} % 'limits' = [xmin xmax ymin ymax] (x's in ms or Hz) {def|0 % (or both y's 0) -> use data limits) % 'ylim' = [ymin ymax] y axis limits. Overwrite option above. % 'title' = [string] plot title {def|'' -> none} % 'chans' = vector of channel numbers to plot {def|0 -> all} % 'axsize' = [x y] axis size {default [.05 .08]} % 'legend' = [cell array] cell array of string for the legend. Note % the last element can be an integer to set legend % position. % 'showleg' = ['on'|'off'] show or hide legend. % 'colors' = [cell array] cell array of plot aspect. E.g. { 'k' 'k--' } % for plotting the first curve in black and the second one % in black dashed. Can also contain additional formating. % { { 'k' 'linewidth' 2 } 'k--' } same as above but % the first line is bolded. % 'ydir' = [1|-1] y-axis polarity (pos-up = 1; neg-up = -1) {def -> -1} % 'vert' = [vector] of times (in ms or Hz) to plot vertical lines % {def none} % 'hori' = [vector] plot horizontal line at given ordinate values. % 'regions' = [cell array] cell array of size nchan. Each cell contains a % float array of size (2,n) each column defining a time region % [low high] to be highlighted. % 'plotfunc' = [cell] use different function for plotting data. The format % is { funcname arg2 arg3 arg2 ... }. arg1 is taken from the % data. % % Author: Scott Makeig and Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 3-2-98 % % See also: plotdata(), topoplot() % Copyright (C) 3-2-98 from plotdata() Scott Makeig, SCCN/INC/UCSD, % [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 5-11-98 added channels arg -sm % 7-15-98 added ydir arg, made pos-up the default -sm % 7-23-98 debugged ydir arg and pos-up default -sm % 12-22-99 added grid size option, changed to sbplot() order -sm % 03-16-00 added axcopy() feature -sm & tpj % 08-21-00 debugged axheight/axwidth setting -sm % 01-25-02 reformated help & license, added links -ad % 03-11-02 change the channel names ploting position and cutomize pop-up -ad % 03-15-02 added readlocs and the use of eloc input structure -ad % 03-15-02 debuging chanlocs structure -ad & sm % 'chan_locs' = file of channel locations as in >> topoplot example {grid} % ELSE: [rows cols] grid size for rectangular matrix. Example: [6 4] % frames = time frames (points) per epoch {def|0 -> data length} % [limits] = [xmin xmax ymin ymax] (x's in ms or Hz) {def|0 % (or both y's 0) -> use data limits) % 'title' = plot title {def|0 -> none} % channels = vector of channel numbers to plot & label {def|0 -> all} % else, filename of ascii channel-name file % axsize = [x y] axis size {default [.07 .07]} % 'colors' = file of color codes, 3 chars per line % ( '.' = space) {0 -> default color order} % ydir = y-axis polarity (pos-up = 1; neg-up = -1) {def -> pos-up} % vert = [vector] of times (in ms or Hz) to plot vertical lines {def none} % hori = [vector] of amplitudes (in uV or dB) to plot horizontal lines {def none} % function plottopo(data, varargin); % %%%%%%%%%%%%%%%%%%%%% Graphics Settings - can be customized %%%%%%%%%%%%%%%%%% % LINEWIDTH = 0.7; % data line widths (can be non-integer) FONTSIZE = 10; % font size to use for labels CHANFONTSIZE = 7; % font size to use for channel names TICKFONTSIZE = 8; % font size to use for axis labels TITLEFONTSIZE = 12; % font size to use for the plot title PLOT_WIDTH = 0.95; % 0.75, width and height of plot array on figure PLOT_HEIGHT = 0.88; % 0.88 gcapos = get(gca,'Position'); axis off; PLOT_WIDTH = gcapos(3)*PLOT_WIDTH; % width and height of gca plot array on gca PLOT_HEIGHT = gcapos(4)*PLOT_HEIGHT; curfig = gcf; % learn the current graphic figure number % %%%%%%%%%%%%%%%%%%%% Default settings - use commandline to override %%%%%%%%%%% % DEFAULT_AXWIDTH = 0.05; % DEFAULT_AXHEIGHT = 0.08; % DEFAULT_SIGN = -1; % Default - plot positive-up ISRECT = 0; % default if nargin < 1 help plottopo return end if length(varargin) > 0 if length(varargin) == 1 | ~isstr(varargin{1}) | isempty(varargin{1}) | ... (length(varargin)>2 & ~isstr(varargin{3})) options = { 'chanlocs' varargin{1} }; if nargin > 2, options = { options{:} 'frames' varargin{2} }; end; if nargin > 3, options = { options{:} 'limits' varargin{3} }; end; if nargin > 5, options = { options{:} 'chans' varargin{5} }; end; if nargin > 6, options = { options{:} 'axsize' varargin{6} }; end; if nargin > 7, options = { options{:} 'colors' varargin{7} }; end; if nargin > 8, options = { options{:} 'ydir' varargin{8} }; end; if nargin > 9, options = { options{:} 'vert' varargin{9} }; end; if nargin > 10,options = { options{:} 'hori' varargin{10} }; end; if nargin > 4 & ~isequal(varargin{4}, 0), options = {options{:} 'title' varargin{4} }; end; % , chan_locs,frames,limits,plottitle,channels,axsize,colors,ydr,vert) else options = varargin; end; else options = varargin; end; g = finputcheck(options, { 'chanlocs' '' [] ''; 'frames' 'integer' [1 Inf] size(data,2); 'chans' { 'integer','string' } { [1 Inf] [] } 0; 'geom' 'integer' [1 Inf] []; 'channames' 'string' [] ''; 'limits' 'float' [] 0; 'ylim' 'float' [] []; 'title' 'string' [] ''; 'plotfunc' 'cell' [] {}; 'axsize' 'float' [0 1] [nan nan]; 'regions' 'cell' [] {}; 'colors' { 'cell','string' } [] {}; 'legend' 'cell' [] {}; 'showleg' 'string' {'on','off'} 'on'; 'ydir' 'integer' [-1 1] DEFAULT_SIGN; 'vert' 'float' [] []; 'hori' 'float' [] []}); if isstr(g), error(g); end; data = reshape(data, size(data,1), size(data,2), size(data,3)); %if length(g.chans) == 1 & g.chans(1) ~= 0, error('can not plot a single ERP'); end; [chans,framestotal]=size(data); % data size % %%%%%%%%%%%%%%% Substitute defaults for missing parameters %%%%%%%%%%%%%%%% % axwidth = g.axsize(1); if length(g.axsize) < 2 axheight = NaN; else axheight = g.axsize(2); end; if isempty(g.chans) | g.chans == 0 g.chans = 1:size(data,1); elseif ~isstr(g.chans) g.chans = g.chans; end nolegend = 0; if isempty(g.legend), nolegend = 1; end; if ~isempty(g.ylim) g.limits(3:4) = g.ylim; end; plotgrid = 0; if isempty(g.chanlocs) % plot in a rectangular grid plotgrid = 1; elseif ~isfield(g.chanlocs, 'theta') plotgrid = 1; end; if length(g.chans) < 4 & ~plotgrid disp('Not enough channels, does not use channel coordinate to plot axis'); plotgrid = 1; end; if plotgrid & isempty(g.geom) n = ceil(sqrt(length(g.chans))); g.geom = [n ceil(length(g.chans)/n)]; end if ~isempty(g.geom) plotgrid = 1; end; % %%%%%%%%%%%%%%%%%%%%%%%%%%% Test parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % icadefs; % read BACKCOLOR, MAXPLOTDATACHANS constant from icadefs.m if g.frames <=0, g.frames = framestotal; % default datasets=1; elseif g.frames==1, fprintf('plottopo: cannot plot less than 2 frames per trace.\n'); return datasets=1; else datasets = fix(framestotal/g.frames); % number of traces to overplot end; if max(g.chans) > chans fprintf('plottopo(): max channel index > %d channels in data.\n',... chans); return end if min(g.chans) < 1 fprintf('plottopo(): min channel index (%g) < 1.\n',... min(g.chans)); return end; if length(g.chans)>MAXPLOTDATACHANS, fprintf('plottopo(): not set up to plot more than %d traces.\n',... MAXPLOTDATACHANS); return end; if datasets>MAXPLOTDATAEPOCHS fprintf('plottopo: not set up to plot more than %d epochs.\n',... MAXPLOTDATAEPOCHS); return end; if datasets<1 fprintf('plottopo: cannot plot less than 1 epoch!\n'); return end; if ~isempty(g.geom) if isnan(axheight) % if not specified axheight = gcapos(4)/(g.geom(1)+1); axwidth = gcapos(3)/(g.geom(2)+1); end % if chan_locs(2) > 5 % axwidth = 0.66/(chan_locs(2)+1); % end else axheight = DEFAULT_AXHEIGHT; axwidth = DEFAULT_AXWIDTH; end fprintf('Plotting data using axis size [%g,%g]\n',axwidth,axheight); % %%%%%%%%%%%%% Extend the size of the plotting area in the window %%%%%%%%%%%% % curfig = gcf; h=figure(curfig); set(h,'PaperUnits','normalized'); % use percentages to avoid US/A4 difference set(h,'PaperPosition',[0.0235308 0.0272775 0.894169 0.909249]); % equivalent orient portrait axis('normal'); set(gca,'Color',BACKCOLOR); % set the background color axcolor= get(0,'DefaultAxesXcolor'); % find what the default x-axis color is vertcolor = 'k'; horicolor = vertcolor; % % % %%%%%%%%%%%%%%%%%%%% Read the channel names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % if isempty(g.channames) % if ~isstr(g.chans) % % g.channames = zeros(MAXPLOTDATACHANS,4); % % for c=1:length(g.chans), % % g.channames(c,:)= sprintf('%4d',g.chans(c)); % % end; % if length(g.chans) > 1 | g.chans(1) ~= 0 % g.channames = num2str(g.chans(:)); %%CJH % end; % else % isstr(g.chans) % chid = fopen(g.chans,'r'); % if chid <3, % fprintf('plottopo(): cannot open file %s.\n',g.chans); % return % else % fprintf('plottopo(): opened file %s.\n',g.chans); % end; % % %%%%%%% % % fid=fopen('fgetl.m'); % % while 1 % % line = fgetl(fid); % % if ~isstr(line), break, end % % disp(line) % % end % % end % % fclose(fid); % %%%%%%% % % g.channames = fscanf(chid,'%s',[4 MAXPLOTDATACHANS]); % g.channames = g.channames'; % [r c] = size(g.channames); % for i=1:r % for j=1:c % if g.channames(i,j)=='.', % g.channames(i,j)=' '; % end; % end; % end; % end; % setting g.channames % end; % % %%%%%%%%%%%%%%%%%%%%%%%%% Plot and label specified channels %%%%%%%%%%%%%%%%%% % data = data(g.chans,:); chans = length(g.chans); % %%%%%%%%%%%%%%%%%%%%%%%%% Read the color names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if isstr(g.colors) % filename for backward compatibility but not documented cid = fopen(g.colors,'r'); % fprintf('cid = %d\n',cid); if cid <3, fprintf('plottopo: cannot open file %s.\n',g.colors); return end; g.colors = fscanf(cid,'%s',[3 MAXPLOTDATAEPOCHS]); g.colors = g.colors'; [r c] = size(g.colors); for i=1:r for j=1:c if g.colors(i,j)=='.', g.colors(i,j)=' '; end; end; end; g.colors = cellstr(g.colors); for c=1:length(g.colors) % make white traces black unless axis color is white if g.colors{c}(1)=='w' & axcolor~=[1 1 1] g.colors{c}(1)='k'; end end else % use default color order (no yellow!) tmpcolors = { 'b' 'r' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' ... 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm'}; g.colors = {g.colors{:} tmpcolors{:}}; % make > 64 available end; % %%%%%%%%%%%%%%%%%%%%%%% Read and adjust limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if g.limits==0, % == 0 or [0 0 0 0] xmin=0; xmax=g.frames-1; % for abs max scaling: ymax=max(max(abs(data))); ymin=ymax*-1; % for data limits: %ymin=min(min(data)); %ymax=max(max(data)); else if length(g.limits)~=4, error('plottopo: limits should be 0 or an array [xmin xmax ymin ymax].\n'); end; xmin = g.limits(1); xmax = g.limits(2); ymin = g.limits(3); ymax = g.limits(4); end; if xmax == 0 & xmin == 0, x = (0:1:g.frames-1); xmin = 0; xmax = g.frames-1; else dx = (xmax-xmin)/(g.frames-1); x=xmin*ones(1,g.frames)+dx*(0:g.frames-1); % compute x-values end; if xmax<=xmin, fprintf('plottopo() - xmax must be > xmin.\n') return end if ymax == 0 & ymin == 0, % for abs max scaling: ymax=max(max(abs(data))); ymin=ymax*-1; % for data limits: %ymin=min(min(data)); %ymax=max(max(data)); end if ymax<=ymin, fprintf('plottopo() - ymax must be > ymin.\n') return end xlabel = 'Time (ms)'; % %%%%%%%%%%%%%%%%%%%%%% Set up plotting environment %%%%%%%%%%%%%%%%%%%%%%%%% % % h = gcf; % set(h,'YLim',[ymin ymax]); % set default plotting parameters % set(h,'XLim',[xmin xmax]); % set(h,'FontSize',18); % set(h,'DefaultLineLineWidth',1); % for thinner postscript lines % %%%%%%%%%%%%%%%%%%%%%%%%%% Print plot info %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % clf; % clear the current figure % print plottitle over (left) subplot 1 figure(curfig); h=gca;title(g.title,'FontSize',TITLEFONTSIZE); % title plot hold on msg = ['Plotting %d traces of %d frames with colors: ']; for c=1:datasets cind = mod(c-1, length(g.colors))+1; if iscell(g.colors{cind}) msg = [msg '''' g.colors{cind}{1} ''' ' ]; else msg = [msg '''' g.colors{cind} ''' ' ]; end; end msg = [msg '\n']; % print starting info on screen . . . fprintf('limits: [xmin,xmax,ymin,ymax] = [%4.1f %4.1f %4.2f %4.2f]\n',... xmin,xmax,ymin,ymax); fprintf(msg,datasets,g.frames); set(h,'FontSize',FONTSIZE); % choose font size set(h,'YLim',[ymin ymax]); % set default plotting parameters set(h,'XLim',[xmin xmax]); axis('off') % %%%%%%%%%%%%%%%%%%%%%%%%%%% Read chan_locs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if plotgrid ISRECT = 1; ht = g.geom(1); wd = g.geom(2); if chans > ht*wd fprintf('plottopo(): (%d) channels to be plotted > grid size [%d %d]\n',... chans,ht,wd); return end xvals = 0; yvals = 0; if isempty(g.channames) if isfield(g.chanlocs,'labels') && ~iscellstr({g.chanlocs.labels}) g.channames = strvcat(g.chanlocs.labels); else g.channames = repmat(' ',ht*wd,4); for i=1:ht*wd channum = num2str(i); g.channames(i,1:length(channum)) = channum; end end end else % read chan_locs file % read the channel location file % ------------------------------ if isstruct(g.chanlocs) nonemptychans = cellfun('isempty', { g.chanlocs.theta }); nonemptychans = find(~nonemptychans); [tmp g.channames Th Rd] = readlocs(g.chanlocs(nonemptychans)); g.channames = strvcat({ g.chanlocs.labels }); else [tmp g.channames Th Rd] = readlocs(g.chanlocs); g.channames = strvcat(g.channames); nonemptychans = [1:length(g.channames)]; end; Th = pi/180*Th; % convert degrees to radians Rd = Rd; if length(g.chans) > length(g.chanlocs), error('plottopo(): data channels must be <= ''chanlocs'' channels') end [yvalstmp,xvalstmp] = pol2cart(Th,Rd); % translate from polar to cart. coordinates xvals(nonemptychans) = xvalstmp; yvals(nonemptychans) = yvalstmp; % find position for other channels % -------------------------------- totalchans = length(g.chanlocs); emptychans = setdiff_bc(1:totalchans, nonemptychans); totalchans = floor(sqrt(totalchans))+1; for index = 1:length(emptychans) xvals(emptychans(index)) = 0.7+0.2*floor((index-1)/totalchans); yvals(emptychans(index)) = -0.4+mod(index-1,totalchans)/totalchans; end; g.channames = g.channames(g.chans,:); xvals = xvals(g.chans); yvals = yvals(g.chans); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % xvals = 0.5+PLOT_WIDTH*xvals; % controls width of plot array on page! % yvals = 0.5+PLOT_HEIGHT*yvals; % controls height of plot array on page! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if length(xvals) > 1 if length(unique(xvals)) > 1 xvals = (xvals-mean([max(xvals) min(xvals)]))/(max(xvals)-min(xvals)); % recenter xvals = gcapos(1)+gcapos(3)/2+PLOT_WIDTH*xvals; % controls width of plot % array on current axes end; end; yvals = gcapos(2)+gcapos(4)/2+PLOT_HEIGHT*yvals; % controls height of plot % array on current axes % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Plot traces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % xdiff=xmax-xmin; ydiff=ymax-ymin; Axes = []; for P=0:datasets-1, % for each data epoch fprintf('trace %d: ',P+1); for c=1:chans, %%%%%%%% for each data channel %%%%%%%%%%%%%%%%%%%%%%%%%% if P>0 % subsequent pages (Axes specified) axes(Axes(c)) hold on; % plot down left side of page first axis('off') else % first page, specify axes if plotgrid Axes = [ Axes sbplot(g.geom(1), g.geom(2), c)]; else xcenter = xvals(c); ycenter = yvals(c); Axes = [Axes axes('Units','Normal','Position', ... [xcenter-axwidth/2 ycenter-axheight/2 axwidth axheight])]; end; %axes(Axes(c)) axis('off') hold on; % plot down left side of page first % set(h,'YLim',[ymin ymax]); % set default plotting parameters % set(h,'XLim',[xmin xmax]); axislcolor = get(gca,'Xcolor'); %%CJH axis('off'); % secondx = 200; % draw second vert axis % axis('off');plot([secondx secondx],[ymin ymax],'color',axislcolor); % %%%%%%%%%%%%%%%%%%%%%%% Print channel names %%%%%%%%%%%%%%%%%%%%%%%%%% % NAME_OFFSET = -.25; NAME_OFFSETY = .2; if ymin <= 0 & ymax >= 0, yht = 0; else yht = mean(data(c,1+P*g.frames:1+P*g.frames+g.frames-1)); end if ~ISRECT % print before traces xt = double(xmin-NAME_OFFSET*xdiff); yt = double(yht-NAME_OFFSETY*ydiff); str = [g.channames(c,:)]; h=text(xt,yt,str); set(h,'HorizontalAlignment','right'); %set(h,'FontSize',CHANFONTSIZE); % choose font size else % ISRECT xmn = xdiff/2+xmin; h=text(double(xmn),double(ymax+0.05*ymax),[g.channames(c,:)]); set(h,'HorizontalAlignment','right'); %set(h,'FontSize',CHANFONTSIZE); % choose font size end % ISRECT % %%%%%%%%%%%%%%%%%%%%%%% Highlight regions %%%%%%%%%%%%%%%%%%%%%%%%%% % if ~isempty(g.regions) for index=1:size(g.regions{c},2) tmpreg = g.regions{c}(:,index); if tmpreg(1) ~= tmpreg(2) tmph = patch([tmpreg(1) tmpreg(2) tmpreg(2) tmpreg(1)], ... [-100 -100 100 100], [0.9 0.9 0.9]); hold on; set(tmph, 'edgecolor', [0.9 0.9 0.9]); %,'facealpha',0.5,'edgealpha',0.5); end; end; end; end; % P=0 % %%%%%%%%%%%%%%%%%%%%%%% Plot data traces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Pind = mod(P+1-1, length(g.colors))+1; if ~iscell( g.colors{Pind} ), tmpcolor = { g.colors{Pind} 'linewidth' LINEWIDTH }; else tmpcolor = g.colors{Pind}; end; ymn = min([ymax ymin]); ymx = max([ymax ymin]); if isempty(g.plotfunc) if isstr(tmpcolor{1}) & length(tmpcolor) > 1 plot(x,data(c,1+P*g.frames:1+P*g.frames+g.frames-1), tmpcolor{1}, tmpcolor{2:end}); else plot(x,data(c,1+P*g.frames:1+P*g.frames+g.frames-1), 'color', tmpcolor{:}); end; if g.ydir == -1 set(gca, 'ydir', 'reverse'); end; axis([xmin xmax ymn ymx]); % set axis bounds elseif P == 1 func = eval( [ '@' g.plotfunc{1} ] ); feval(func, data(c,:), g.plotfunc{2:end}); end; if P == datasets-1 % last pass % %%%%%%%%%%%%%%%%%%%%%%% Plot lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % plot([0 0],[ymin ymax],'color',axislcolor); % draw vert axis at time 0 axis('off'); plot([xmin xmax],[0 0],'color',axislcolor); % draw horizontal axis % %%%%%%%%%%%%%%%%%%%% plot vertical lines (optional) %%%%%%%%%%%%%%%%% % if isempty(g.vert) g.vert = [xmin xmax]; ymean = (ymin+ymax)/2; vmin = ymean-0.1*(ymean-ymin); vmax = vmin*-1; %ymean+0.2*(ymax-ymean); elseif ~isnan(g.vert) ymean = (ymin+ymax)/2; vmin = ymean-0.1*(ymean-ymin); vmax = vmin*-1; %ymean+0.2*(ymax-ymean); for v = g.vert plot([v v],[vmin vmax],'color',vertcolor); % draw vertical lines end end % %%%%%%%%%%%%%%%%%%%% plot horizontal lines (optional) %%%%%%%%%%%%%%% % if isempty(g.hori) g.hori = [ymin ymax]; end if ~isnan(g.hori) xmean = 0; hmin = xmean-0.2*(xmean-xmin); hmax = hmin*-1; %xmean+0.3*(xmax-xmean); for v = g.hori plot([hmin hmax],[v v], 'color',horicolor); % draw horizontal lines end end end; fprintf(' %d',c); % finished with channel plot end; % c, chans / subplot % handle legend if nolegend, g.legend{P+1} = ['Data ' int2str(P) ]; end; fprintf('\n'); end; % P / epoch % %%%%%%%%%%%%%%%%%%%%% Make time and amp cal bar %%%%%%%%%%%%%%%%%%%%%%%%% % ax = axes('Units','Normal','Position', ... [0.85 0.1 axwidth axheight]); % FIX!!!! axes(ax) axis('off'); if xmin <=0 figure(curfig);p=plot([0 0],[ymn ymx],'color','k'); % draw vert axis at zero else figure(curfig);p=plot([xmin xmin],[ymn ymx],'color','k'); % draw vert axis at zero end if g.ydir == -1 set(gca, 'ydir', 'reverse'); end; axis([xmin xmax ymn ymx]); % set axis values hold on %set(p, 'Clipping','off'); % center text figure(curfig);p=plot([xmin xmax],[0 0],'color',axislcolor); % draw horizontal axis axis([xmin xmax ymin ymax]); % set axis values % %%%%%%%%%%%%%%%%%%%% plot vertical lines (optional) %%%%%%%%%%%%%%%%% % if ~isnan(g.vert) for v = g.vert figure(curfig);plot([v v],[vmin vmax],'color',vertcolor); % draw vertical lines end end % %%%%%%%%%%%%%%%%%%%% plot horizontal lines (optional) %%%%%%%%%%%%%%%%% % if ~isnan(g.hori) xmean = 0; hmin = xmean-0.2*(xmean-xmin); hmax = hmin*-1; %xmean+0.3*(xmax-xmean); for v = g.hori figure(curfig);plot([hmin hmax],[v v], 'color',horicolor); % draw horizontal lines end end % secondx = 200; % draw second vert axis % axis('off');plot([secondx secondx],[ylo ymax],'color',axislcolor); % %%%%%%%%%%%%%%%%%%%%% Plot negative-up %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % signx = xmin-0.15*xdiff; figure(curfig);axis('off');h=text(double(signx),double(ymin),num2str(ymin,3)); % text ymin set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','right','Clipping','off'); figure(curfig);axis('off');h=text(double(signx), double(ymax),['+' num2str(ymax,3)]); % text +ymax set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','right','Clipping','off'); ytick = g.ydir*(-ymax-0.3*ydiff); figure(curfig);tick = [int2str(xmin)]; h=text(double(xmin),double(ytick),tick); set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','center',... 'Clipping','off'); % center text tick = [xlabel]; figure(curfig);h=text(double(xmin+xdiff/2),double(ytick-0.5*g.ydir*ydiff),tick); set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','center',... 'Clipping','off'); % center text tick = [int2str(xmax)]; figure(curfig);h=text(double(xmax),double(ytick),tick); set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','center',... 'Clipping','off'); % center text if length(g.legend) > 1 & strcmpi(g.showleg, 'on') tmpleg = vararg2str(g.legend); quotes = find(tmpleg == ''''); for index = length(quotes):-1:1 tmpleg(quotes(index)+1:end+1) = tmpleg(quotes(index):end); tmpleg(quotes(index)) = ''''; end; tmpleg = [ 'legend(' tmpleg ');' ]; else tmpleg = ''; end; com = [ 'axis on;' ... 'clear xlabel ylabel;' tmpleg ... 'xlabel(''''Time (ms)'''');' ... 'ylabel(''''Potential (\muV)'''');' ]; axcopy(gcf, com); % turn on popup feature % %%%%%%%%%%%%%%%%%% Make printed figure fill page %%%%%%%%%%%%%%%%%%%%%%%%%%% % orient tall % curfig = gcf; % h=figure(curfig); % set(h,'PaperPosition',[0.2 0.3 7.6 10]); % stretch out the plot on the page
github
ZijingMao/baselineeegtest-master
plotcurve.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/plotcurve.m
13,176
utf_8
b247086675025ad96d7229832935ff76
% plotcurve() - plot curve(s) with optional significance highlighting. % % Usage: >> plotcurve(times, data, 'key1', 'val1', 'key2', val2' ...); % % Required inputs: % times - [float] vector of time indices % data - [float] data array, size of [n x times]. If n>1 several % curves are plotted (unless 'plotmean' option is used). % % Optional inputs: % 'maskarray' = Input bootstrap limits. Can be 1-D [min max], 2-D (min % and max for all ordinate) or 3-D (min and max for all % ordinates at all time points). % 'val2mask' = Value to use for generating mask. By default use data. % 'plotmean' = ['on'|'off'] For 'curve' plots only. Average all % frequencies given as input. Default: 'on'. % 'highlightmode' = ['background'|'bottom'] For 'curve' plots only, % display significant time regions either in the plot % background or underneatht the curve. % 'xlabel' = [string] x label % 'ylabel' = [string] y label % 'legend' = [cell] legend. Cell array of string, with one string % per curve. % 'ylim' = [min max] or [min] limits for the ordinate axis. % 'title' = Optional figure title. If two conditions are given % as input, title can be a cell array with two text % string elements {none} % 'vert' = Latencies to mark with a dotted vertical line {none} % 'linewidth' = Line width for marktimes traces (thick=2, thin=1) {2} % 'chanlocs' = channel location structure. % 'plottopo' = [min max] plot topography within the time limits defined % in this function. If several lines are given as input, one % scalp map is plot for each line. % 'traceinfo' = [string|cell array] information shown on the command line % when the user click on a specific trace. Default none. % % Authors: Arnaud Delorme, 2004, Bhaktivedanta Institute % Copyright (C) 2004 Arnaud Delorme % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function plotcurve( times, R, varargin); if nargin < 2 help plotcurve; return; end; g = finputcheck( varargin, { 'maskarray' '' [] []; 'val2mask' 'real' [] R; 'highlightmode' 'string' { 'background','bottom' } 'background'; 'plotmean' 'string' { 'on','off' } 'off'; 'plotindiv' 'string' { 'on','off' } 'on'; 'traceinfo' { 'string' 'cell' } { { } {} } 'off'; 'logpval' 'string' { 'on','off' } 'off'; 'title' 'string' [] ''; 'xlabel' 'string' [] ''; 'plotmode' 'string' {'single','topo'} 'single'; 'ylabel' 'string' [] ''; 'legend' 'cell' [] {}; 'colors' 'cell' [] {}; 'plottopotitle' 'cell' [] {}; 'chanlocs' 'struct' [] struct; 'ylim' 'real' [] []; 'vert' 'real' [] []; 'plottopo' 'real' [] []; 'linewidth' 'real' [] 2; 'marktimes' 'real' [] [] }); if isstr(g), error(g); end; % keyboard; if isempty(g.colors), g.colors = { 'r' 'g' 'b' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' ... 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' }; end; if strcmpi(g.plotindiv, 'off'), g.plotmean = 'on'; end; if ~any(length(times) == size(R)) try, R = reshape(R, length(times), length(R)/length(times))'; catch, error('Size of time input and array input does not match'); end; end; % regions of significance % ----------------------- if ~isempty(g.maskarray) if length(unique(g.maskarray)) < 4 Rregions = g.maskarray; else Rregions = ones(size(g.val2mask)); switch dims(g.maskarray) case 3, Rregions (find(g.val2mask > g.maskarray(:,:,1) & (g.val2mask < g.maskarray(:,:,2)))) = 0; case 2, if size(g.val2mask,2) == size(g.maskarray,2) Rregions (find(g.val2mask < g.maskarray)) = 0; elseif size(g.val2mask,1) == size(g.maskarray,1) Rregions(find((g.val2mask > repmat(g.maskarray(:,1),[1 length(times)])) ... & (g.val2mask < repmat(g.maskarray(:,2),[1 length(times)])))) = 0; else Rregions(find((g.val2mask > repmat(g.maskarray(:,1),[1 length(times)])) ... & (g.val2mask < repmat(g.maskarray(:,2),[1 length(times)])))) = 0; end; case 1, Rregions (find(g.val2mask < repmat(g.maskarray(:),[1 size(g.val2mask,2)]))) = 0; end; Rregions = sum(Rregions,1); end; else Rregions = []; end % plotting % -------- if size(R,1) == length(times), R = R'; end; if strcmpi(g.plotmean, 'on') | strcmpi(g.plotindiv, 'off') if strcmpi(g.plotindiv, 'on') R = [ R; mean(R,1) ]; else R = mean(R,1); end; end; ax = gca; if ~isempty(g.maskarray) & strcmpi(g.highlightmode, 'bottom') pos = get(gca, 'position'); set(gca, 'position', [ pos(1)+pos(3)*0.1 pos(2)+pos(4)*0.1 pos(3)*0.9 pos(4)*0.85 ]); end; % plot topographies % ----------------- if ~isempty(g.plottopo) tmpax = gca; pos = get(gca, 'position'); set(gca, 'position', [ pos(1) pos(2) pos(3) pos(4)/2 ]); for index = 1:size(g.plottopo) axes('position', [ (index-1)*pos(3)/size(g.plottopo,1)+pos(1) pos(2)+pos(4)/2 pos(3)/size(g.plottopo,1) pos(4)/2 ]); %topoplot(g.plottopo(index,:), g.chanlocs, 'maplimits', 'minmax'); topoplot(g.plottopo(index,:), g.chanlocs); if ~isempty(g.plottopotitle) title(g.plottopotitle{index}, 'interpreter', 'none'); end; end; axes(tmpax); end; for ind = 1:size(R,1) if ind == size(R,1) & strcmpi(g.plotmean, 'on') & size(R,1) > 1 plot(times,R(ind,:), 'k', 'linewidth', 2); elseif ~isempty(g.colors), tmp = plot(times,R(ind,:), 'k'); tmpcol = g.colors{mod(ind-1, length(g.colors))+1}; if length(tmpcol) > 1, tmpstyle = tmpcol(2:end); tmpcol = tmpcol(1); else tmpstyle = '-'; end; set(tmp, 'color', tmpcol, 'linestyle', tmpstyle); if ~isempty(g.traceinfo) if isstr(g.traceinfo) && strcmpi(g.traceinfo, 'on') set(tmp, 'ButtonDownFcn', [ 'disp(''Trace ' int2str(ind) ''');' ]); elseif iscell(g.traceinfo) try set(tmp, 'ButtonDownFcn', g.traceinfo{ind}); catch, error('Trace info cell array does not contain the same number of element as trace in the graph') end; end; end; % change the line style when number of plots exceed number of colors in g.colors %lineStyles = {'-', '--',':','-.'}; %set(tmp,'LineStyle',lineStyles{min(ceil(ind/length(g.colors)),length(lineStyles))}); hold on; else plot(times,R(ind,:)); end; end; % ordinate limits % --------------- if isempty(g.ylim), yll = min(reshape(R, [1 prod(size(R))])); ylh = max(reshape(R, [1 prod(size(R))])); yll2 = yll - (ylh-yll)/10; ylh2 = ylh + (ylh-yll)/10; if ~isnan(yll), g.ylim = [yll2 ylh2]; end; end; if ~isempty(g.ylim) & length(g.ylim) == 2 if any(g.ylim) ylim(g.ylim); else ylim([0 1]); axis off; box off; end; elseif ~isempty(g.ylim) yl = ylim; ylim([g.ylim yl(2)]); end yl = ylim; % highlight regions % ----------------- if ~isempty(g.maskarray) axsignif = highlight(ax, times, Rregions, g.highlightmode, g.xlabel); % replot data (above highlighted regions) % --------- axes(ax); for ind = 1:size(R,1) if ind == size(R,1) & strcmpi(g.plotmean, 'on') & size(R,1) > 1 plot(times,R(ind,:), 'k', 'linewidth', 2); elseif ~isempty(g.colors), tmp = plot(times,R(ind,:), 'k'); set(tmp, 'color', g.colors{mod(ind-1, length(g.colors))+1} ); hold on; else plot(times,R(ind,:)); end; end; if strcmpi(g.highlightmode, 'bottom'), xlabel(''); set(ax, 'xtick', []); end; end; box on; ylim(yl); if strcmpi(g.logpval, 'on') set(gca, 'ytickmode', 'manual', 'yticklabel', round(10.^-get(gca, 'ytick')*1000)/1000, 'ydir', 'reverse'); end; % vertical lines % -------------- hold on xl = xlim; if ~isnan(g.marktimes) % plot marked time for mt = g.marktimes(:)' plot([mt mt],[yl(1) yl(2)],'--k','LineWidth',g.linewidth); end end hold off if ~isempty(g.vert) for index = 1:length(g.vert) line([g.vert(index), g.vert(index)], [yl(1) yl(2)], 'linewidth', 1, 'color', 'm'); end; end; xlim([times(1) times(end)]); % title and legend % ---------------- if strcmpi(g.plotmode, 'topo') % plot in scalp array NAME_OFFSETX = 0.1; NAME_OFFSETY = 0.2; xx = xlim; xmin = xx(1); xdiff = xx(2)-xx(1); xpos = double(xmin+NAME_OFFSETX*xdiff); yy = ylim; ymax = yy(2); ydiff = yy(2)-yy(1); ypos = double(ymax-NAME_OFFSETY*ydiff); t=text(xpos, ypos,g.title); axis off; line([0 0], [yl(1) yl(2)], 'linewidth', 1, 'color', 'k'); line([xl(1) xl(2)], [0 0], 'linewidth', 1, 'color', 'k'); set(ax, 'userdata', { g.xlabel g.ylabel g.legend }); else title(g.title, 'interpreter', 'none') if ~isempty(g.legend) hh = legend(g.legend(:)); set(hh, 'unit', 'pixels', 'interpreter', 'none') end; if isempty(g.maskarray) xlabel(g.xlabel); end; ylabel(g.ylabel) end; % ----------------- % highlight regions % ----------------- function axsignif = highlight(ax, times, regions, highlightmode, myxlabel); color1 = [0.75 0.75 0.75]; color2 = [0 0 0]; yl = ylim; yl(1) = yl(1)-max(abs(yl)); yl(2) = yl(2)+max(abs(yl)); if ~strcmpi(highlightmode, 'background') pos = get(ax, 'position'); set(gca, 'xtick', []); axsignif = axes('position', [pos(1) pos(2)-pos(4)*0.05 pos(3) pos(4)*0.05 ]); plot(times, times, 'w'); set(axsignif, 'ytick', []); yl2 = ylim; yl2(1) = yl2(1)-max(abs(yl2)); yl2(2) = yl2(2)+max(abs(yl2)); xlim([times(1) times(end)]); xlabel(myxlabel); else axsignif = []; xlabel(myxlabel); end; if ~isempty(regions) axes(ax); in_a_region = 0; for index=1:length(regions) if regions(index) & ~in_a_region tmpreg(1) = times(index); in_a_region = 1; end; if (~regions(index) | index == length(regions)) & in_a_region tmpreg(2) = times(index); in_a_region = 0; if strcmpi(highlightmode, 'background') tmph = patch([tmpreg(1) tmpreg(2) tmpreg(2) tmpreg(1)], ... [yl(1) yl(1) yl(2) yl(2)], color1); hold on; set(tmph, 'edgecolor', color1); else oldax = ax; axes(axsignif); tmph = patch([tmpreg(1) tmpreg(2) tmpreg(2) tmpreg(1)], ... [yl2(1) yl2(1) yl2(2) yl2(2)], color2); hold on; set(tmph, 'edgecolor', color2); axes(oldax); end; end; end; ylim(yl); end; function res = dims(array) res = min(ndims(array), max(size(array,2),size(array,3)));
github
ZijingMao/baselineeegtest-master
readneurolocs.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/readneurolocs.m
4,352
utf_8
a351981666e50fa3ac943a11a7799b84
% readneurolocs() - read neuroscan polar location file (.asc) % % Usage: % >> CHANLOCS = readneurolocs( filename ); % >> CHANLOCS = readneurolocs( filename, 'key1', val1, ...); % % Inputs: % filename - file name or matlab cell array { names x_coord y_coord } % % Optional inputs: % same as caliblocs() % note that if no optional input are provided, re-centering will be % performed automatically and re-scaling of coordinates will be % performed for '.asc' files (not '.dat' files). % % Outputs: % CHANLOCS - EEGLAB channel location data structure. See % help readlocs() % % Author: Arnaud Delorme, CNL / Salk Institute, 4 March 2003 % % See also: readlocs() % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function chanlocs = readneurolocs( filename, varargin) if nargin < 1 help readneurolocs; return; end; if nargin < 2 plottag = 0; end; % read location file % ------------------ if isstr(filename) locs = loadtxt( filename ); end; if ~isstr(filename) || locs{1,1}(1) == ';' || size(locs,2) < 5 if ~isstr(filename) names = filename{1}; x = filename{2}; y = filename{3}; else if locs{1,1}(1) == ';' % remove trailing control channels % -------------------------------- while isnumeric( locs{end,1} ) & locs{end,1} ~= 0 locs = locs(1:end-1,:); end; % find first numerical index % -------------------------- index = 1; while isstr( locs{index,1} ) index = index + 1; end; % extract location array % ---------------------- nchans = size( locs, 1 ) - index +1; chans = [locs{end-nchans+1:end, 1:5}]; chans = reshape(chans,nchans,5); %% Added this line in order to get x = chans(:,3) names = locs(end-nchans*2+1: end-nchans, 2); for index = 1:length(names) if ~isstr(names{index}) names{index} = int2str(names{index}); end; end; x = chans(:,3); y = -chans(:,4); else [tmp2 tmpind] = sort( [ locs{:,1} ]); locs = locs(tmpind,:); y = [ locs{:,end} ]; x = [ locs{:,end-1} ]; x = x/513.1617*44; y = y/513.1617*44; names = locs(:,end-2); end; end; % second solution using angle % --------------------------- [phi,theta] = cart2pol(x, y); phi = phi/pi*180; % convert to other types of coordinates % ------------------------------------- labels = names'; chanlocs = struct('labels', labels, 'sph_theta_besa', mattocell(theta)', 'sph_phi_besa', mattocell(phi)'); %% labels instead of labels(:) chanlocs = convertlocs( chanlocs, 'sphbesa2all'); for index = 1:length(chanlocs) chanlocs(index).labels = num2str(chanlocs(index).labels); end; % re-calibration % -------------- chanlocs = adjustlocs(chanlocs, 'autoscale', 'on', 'autorotate', 'off', varargin{:}); else % 5 rows, xyz positions try for index = 1:size(locs,1) locs{index,3} = - locs{index,3}; end; chanlocs = struct('labels', locs(:,1), 'type', locs(:,2), 'X', locs(:,4), 'Y', locs(:,3), 'Z', locs(:,5)); chanlocs = convertlocs( chanlocs, 'cart2all'); catch chanlocs = readlocs(filename, 'filetype', 'custom', 'format', { 'labels' 'ignore' '-Y' 'X' 'Z' }); end; end;