plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
lcnhappe/happe-master
rejkurt.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
readeetraklocs.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
nan_mean.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
dipoledensity.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
icaproj.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
epoch.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
headplot.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
eegfiltfft.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
rejstatepoch.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
binica.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
mattocell.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
readegihdr.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
timtopo.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
rmbase.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
realproba.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
eegfilt.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
phasecoher.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
plotchans3d.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
biosig2eeglab.m
.m
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/biosig2eeglab.m
7,146
utf_8
382204f79712220b2bbab12edc97455f
% 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 = length(dat.InChanSelect); %= size(DAT,1); EEG.srate = dat.SampleRate(1); EEG.data = DAT(dat.InChanSelect,:); %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
lcnhappe/happe-master
changeunits.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
ploterp.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
forcelocs.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
rejtrend.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
slider.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
loadcnt.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
icaact.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
gettempfolder.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
loadtxt.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
plotmesh.m
.m
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/plotmesh.m
3,048
utf_8
8345a3f062504b918e1d6e64dda75110
% 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 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
lcnhappe/happe-master
mri3dplot.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
spherror.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
envtopo.m
.m
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/envtopo.m
47,733
utf_8
31745f07983ae21a1a8d735d9a6e5a5e
% % 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; 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 ; 'figure' 'integer' [] [] ; '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.figure), figure(g.figure); end; % remember the current figure (for Matlab 7.0.0 bug) 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 % Checking dimension of chanlocs if length(g.chanlocs) > size(data,1) fprintf(2,['\n envtopo warning: Dimensions of data to plot and channel location are not consistent\n' ... ' As a result, the plots generated can be WRONG\n'... ' If you are providing the path to your channel location file. Make sure\n'... ' to load the file first, and to provide as an input only the channels that\n'... ' correspond to the data to be plotted, otherwise just provide a valid chanlocs\n ']); elseif length(g.chanlocs) > size(data,1) fprintf(2,['\n envtopo error: Dimensions of data to plot and channel location are not consistent\n' ... ' Check the dimension of the channel location provided\n'... ' Aborting plot ...\n']); exit; 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'; elseif strcmpi(g.sortvar,'pv') sumppaf = mean(var((data(g.plotchans,limframe1:limframe2) ... - sumproj(:,limframe1:limframe2)),1)); sumppaf = 100-100*sumppaf/vardat; ot = 'pvaf'; 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') '%']); elseif strcmpi(g.sortvar,'pv') t = text(double(xmin+0.1*(xmax-xmin)), ... double(ymin+0.1*(ymax-ymin)), ... ['pvaf ' 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 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
lcnhappe/happe-master
runica.m
.m
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/runica.m
64,868
utf_8
fa36c213fe0a11f1d407d1847d81bac0
% 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) % 'interupt' = ['on'|'off'] interrupt drawing of figure. Default is off. % 'reset_randomseed' - ['on'|'off'] reset random seed for each call. Default is 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() % '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 DEFAULT_RESETRANDOMSEED = true; % default to reset the random number generator to a 'random state' % %%%%%%%%%%%%%%%%%%%%%%% 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 reset_randomseed = DEFAULT_RESETRANDOMSEED; % %%%%%%%%%% 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 elseif strcmp(Keyword,'reset_randomseed') if ischar(Value) if strcmp(Value,'yes') || strcmp(Value,'on') reset_randomseed = true; elseif strcmp(Value,'no') || strcmp(Value,'off') reset_randomseed = false; else fprintf('runica(): not using the reset_randomseed flag, it should be ''yes'',''on'',''no'', ''off'',0, or 1'); end else reset_randomseed = Value; 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 if reset_randomseed rand('state',sum(100*clock)); % set the random number generator state to end % a position dependent on the system clock % interrupt 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
lcnhappe/happe-master
jader.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
spectopo.m
.m
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/spectopo.m
41,106
utf_8
1d8873878f4c3dc70942cc4aea480585
% spectopo() - Plot the power spectral density (PSD) of winsize length segments of data % epochs at all channels as a bundle of traces. At specified frequencies, % plot the relative topographic distribution of PSD. 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 (to adjust frequency resolution) {default: 1} % 'nfft' = [integer] Data points to zero-pad data windows to (overwrites 'freqfac') % 'winsize' = [integer] window size in data points {default: Sampling Rate} % '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}. % 'wintype' = ['hamming','blackmanharris'] Window type used on the power spectral % density estimation. The Blackman-Harris windows offers better attenuation % than Hamming windows, but lower spectral resolution. {default: 'hamming'} % 'blckhn' = [integer] Parameter to scale the windows length when Blackman-Harris % windows is used in 'wintype' {default: 2} % '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) % % Non-backward compatible change (Nov 15 2015): % Default winsize was set to the sampling rate (giving a default window % length of 1 sec). Also, the y-axis label in the plot was corrected % to read, "Log Power Spectral Density 10*log_{10}(\muV^{2}/Hz)' % Finally, when winsize is not a power of 2, it is no longer promoted to % the next higher power of 2. Thanks to Andreas Widmann for his comments. % % % 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 = 1; % 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'} 'on' ; '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)] [] ; 'wintype' 'string' {'hamming','blackmanharris'} 'hamming' ; 'blckhn' 'real' [] 2 ; '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('Log Power Spectral Density 10*log_{10}(\muV^{2}/Hz)');%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); usepwelch = license('checkout','Signal_Toolbox'); 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(srate, frames); else winlength = g.winsize; end; if strcmp(g.wintype,'blackmanharris') if usepwelch winlength = blackmanharris(round(winlength/g.blckhn)); else g.wintype = 'hamming'; fprintf('\nSignal processing toolbox (SPT) absent: unable to use Blackman-Harris window\n'); fprintf(' using pwelch function from Octave\n'); end end if isempty(g.nfft) && strcmp(g.wintype,'hamming') %fftlength = 2^(nextpow2(winlength))*g.freqfac; fftlength = winlength*g.freqfac; elseif ~isempty(g.nfft) && strcmp(g.wintype,'hamming') fftlength = g.nfft; elseif strcmp(g.wintype,'blackmanharris') fftlength = 2^(nextpow2(length(winlength)))*g.freqfac; end; 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
lcnhappe/happe-master
loadavg.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
biosig2eeglabevent.m
.m
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/biosig2eeglabevent.m
4,111
utf_8
9ecfe50ab1307bb14c583e5262750407
% biosig2eeglabevent() - convert biosig events to EEGLAB event structure % % Usage: % >> eeglabevent = biosig2eeglabevent( biosigevent, interval, mode) % % Inputs: % biosigevent - BioSig event structure % interval - Period to extract events for, in frames. % Default [] is all. % mode - [], 0: old behavior: event(i).type contains numeric event type % 1: new behavior: event(i).type may contain textual event annotation % % Outputs: % eeglabevent - EEGLAB event structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2006- % Copyright (C) 13 2006- Arnaud Delorme, Salk Institute, [email protected] % Copyright (C) 2016 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 function event = biosig2eeglabevent(EVENT, interval, mode) if nargin < 2 interval = []; end; if (nargin < 3) || isempty(mode) mode = 0; end; event = []; disp('Importing data events...'); EVT=sopen('eventcodes.txt');sclose(EVT); % 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 ) typ = EVENT.TYP(index); if (mode==0) event(index).type = typ; elseif (typ<256) event(index).type = EVENT.CodeDesc{typ}; elseif isfield(EVT, 'Event') && isfield(EVT.Event,'CodeIndex') && isfield(EVT.Event,'CodeDesc') event(index).type = EVENT.CodeDesc{EVENT.CodeIndex==typ}; else event(index).type = typ; end 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') typ = EVENT.TYP(index); if (mode==0) event(count).type = typ; elseif (typ<256) event(count).type = EVENT.CodeDesc{typ}; elseif isfield(EVT, 'Event') && isfield(EVT.Event,'CodeIndex') && isfield(EVT.Event,'CodeDesc') event(count).type = EVENT.CodeDesc{EVENT.CodeIndex==typ}; else event(count).type = typ; end 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
lcnhappe/happe-master
acsobiro.m
.m
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/acsobiro.m
5,108
utf_8
a67b95f026833f1e4dfeaf44fcd94335
% 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(:,:),2)*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
lcnhappe/happe-master
metaplottopo.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
blockave.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
posact.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
eegplot.m
.m
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/eegplot.m
91,576
utf_8
f16189ff1fb950bdd445c8f97db68826
% 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} % 'plottitle' - Plot 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 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 if ndims(data) == 2, g.winlength = g.freqs(end) - g.freqs(1); end 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.plottitle; catch, g.plottitle = ''; 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' 'plottitle' ... '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', 'Units', 'Normalized'); 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; % Plot title if provided if ~isempty(g.plottitle) h = findobj('tag', 'eegplottitle'); if ~isempty(h) set(h, 'string',g.plottitle); else h = textsc(g.plottitle, 'title'); set(h, 'tag', 'eegplottitle'); end; end % Background axis % --------------- ax0 = axes('tag','backeeg','parent',figh,... 'Position',DEFAULT_AXES_POSITION,... 'Box','off','xgrid','off', 'xaxislocation', 'top', 'Units', 'Normalized'); % 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'); if verLessThan('matlab','8.4.0') commandzoom = [ 'set(gcbf, ''WindowButtonDownFcn'', [ ''zoom(gcbf,''''down''''); eegplot(''''zoom'''', gcbf, 1);'' ]);' ... 'tmpg = get(gcbf, ''userdata'');' ... 'clear tmpg tmpstr;']; else % Temporary fix to avoid warning when setting a callback and the mode is active % This is failing for us http://undocumentedmatlab.com/blog/enabling-user-callbacks-during-zoom-pan commandzoom = [ 'wtemp = warning; warning off;set(gcbf, ''WindowButtonDownFcn'', [ ''zoom(gcbf); eegplot(''''zoom'''', gcbf, 1);'' ]);' ... 'tmpg = get(gcbf, ''userdata'');' ... 'warning(wtemp);'... 'clear wtemp tmpg tmpstr; ']; end %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, ''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 % NOTE: commandselect{2} option has been moved to a % subfunction to improve speed %%%%%%%%%%%%%%%%%%% g.commandselect{1} = [ 'if strcmp(get(gcbf, ''SelectionType''),''alt''),' g.ctrlselectcommand{1} ... 'else ' g.selectcommand{1} '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', {@defmotion,figh,ax0,ax1,u(10),u(11),u(9)}); 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)) 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) %Just repeat for the first one if index == 1 EVENTFONT = ' \fontsize{10} '; ylims=ylim; end % draw latency line % ----------------- tmplat = g.eventlatencies(event2plot(index))-lowlim-1; tmph = plot([ tmplat tmplat ], ylims, '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 = ylims; 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 % ------------------------- if ~g.isfreq tmplimit = g.limits; tpmorder = 1E-3; else tmplimit = g.freqlimits; tpmorder = 1; end tagtext = eeg_point2lat(tagpos, floor((tagpos)/g.trialstag)+1, g.srate, tmplimit,tpmorder); 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 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 if verLessThan('matlab','8.4.0') set(gcbf, 'windowbuttondownfcn', [ 'zoom(gcbf,''down''); eegplot(''zoom'', gcbf, 1);' ]); else % This is failing for us: http://undocumentedmatlab.com/blog/enabling-user-callbacks-during-zoom-pan % hManager = uigetmodemanager(gcbf); % [hManager.WindowListenerHandles.Enabled] = deal(false); % Temporary fix wtemp = warning; warning off; set(gcbf, 'WindowButtonDownFcn', [ 'zoom(gcbf); eegplot(''zoom'', gcbf, 1);' ]); warning(wtemp); end 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 moved as subfunction % 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'); fig = varargin{1}; g = get(fig,'UserData'); ax1 = findobj('tag','backeeg','parent',fig); tmppos = get(ax1, 'currentpoint'); 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; elseif strcmp(get(fig, 'SelectionType'),'normal'); end; otherwise error(['Error - invalid eegplot() parameter: ',data]) end end % Function to show the value and electrode at mouse position function defmotion(varargin) fig = varargin{3}; ax1 = varargin{4}; tmppos = get(ax1, 'currentpoint'); if all([tmppos(1,1) >= 0,tmppos(1,2)>= 0]) g = get(fig,'UserData'); 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 = varargin{6}; % h = findobj('tag','Etime','parent',fig); if g.trialstag ~= -1, tmpval = mod(tmppos(1)+lowlim-1,g.trialstag)/g.trialstag*(g.limits(2)-g.limits(1)) + g.limits(1); if g.isfreq, tmpval = tmpval/1000 + g.freqs(1); end set(hh, 'string', num2str(tmpval)); else tmpval = (tmppos(1)+lowlim-1)/g.srate; if g.isfreq, tmpval = tmpval+g.freqs(1); end set(hh, 'string', num2str(tmpval)); % put g.time in the box end; ax1 = varargin{5};% 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 = varargin{8}; % 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 = varargin{7}; % 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; 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
lcnhappe/happe-master
uigetfile2.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
readelp.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
plottopo.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
plotcurve.m
.m
happe-master/Packages/eeglab14_0_0b/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
lcnhappe/happe-master
readneurolocs.m
.m
happe-master/Packages/eeglab14_0_0b/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;
github
lcnhappe/happe-master
condstat.m
.m
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/condstat.m
11,329
utf_8
42bfdcd65fdf5e5de0ed089486888d0c
% condstat() - accumulate surrogate data for comparing two data conditions % % Usage: % >> [diffres, accres, res1, res2] = condstat(formula, naccu, alpha, ... % bootside, condboot, arg1, arg2 ...); % % Inputs: % formula - [string or cell array of strings] formula(s) to compute a given measure. % Takes arguments 'arg1', 'arg2' ... and X as inputs. e.g., % 'sum(arg1(:,:,X),3) ./ sqrt(sum(arg2(:,:,X))) ./ sqrt(sum(arg3(:,:,X)))' % naccu - [integer] number of accumulations of surrogate data. e.g., 200 % alpha - [float] significance level (0<alpha<0.5) % bootside - ['both'|'upper'] side of the surrogate distribution to % consider for significance. This parameter affect the size % of the last dimension of accumulation array 'accres' (size % is 2 for 'both' and 1 for 'upper'). % condboot - ['abs'|'angle'|'complex'|''] When comparing two conditions, compare % either absolute vales ('abs'), angles ('angles') or complex values % ('complex'). Either '' or 'complex' leave the formula unchanged; % 'abs' takes its norm before subtraction, and 'angle' normalizes % each value (to norm 1) before taking the difference. % arg1 - [cell_array] of two 1D,2D,or 3D matrices of values to compare. % The last dimension of the array is shuffled to accumulate data, the % other dimensions must be the same size across matrices. % e.g. size(arg1{1})=[100 200 500], size(arg1{2})=[100 200 395] % arg2 - same as arg1, note that it is compared only to itself, and has % nothing to do with arg1 besides using the same formula, alpha, etc. % ...argn - may call n number of arguement pairs % % Outputs: % diffres - difference array for the actual (non-shuffled) data, if more than one % arg pair is called, format is a cell array of matrices. % accres - [cell array of 3D numerical arrays] for shuffled data, one per formula. % res1 - result for first condition % res2 - result for second condition % % Authors: Arnaud Delorme & Scott Makeig % CNL/Salk Institute 1998-2001; SCCN/INC/UCSD, La Jolla, 2002- % % See also: timef(), crossf() % Copyright (C) 2002 Arnaud Delorme, Lars Kai Hansen & Scott Makeig, SCCN/INC/UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [diffres, accres, res1, res2] = condstat(formula, naccu, alpha, bootside, condboot, varargin); if nargin < 6 help condstat; return; end; if ~ischar(formula) & ~iscell(formula) error('The first argument must be a string formula or cell array of string'); end; if ischar(formula) formula = { formula }; end; if ischar(bootside) bootside = { bootside }; end; for index = 1:length(bootside) if ~strcmpi(bootside, 'both') & ~strcmpi(bootside, 'upper') error('Bootside must be either ''both'' or ''upper'''); end; end; if ischar(condboot) condboot = { condboot }; end; for index = 1:length(condboot) if isempty(condboot{index}), condboot{index} = 'complex'; end; end; for index = 1:length(varargin) if ~iscell(varargin) | length(varargin{index}) ~=2 error('Except for the first arguments, all other arguments given to the function must be cell arrays of two numerical array'); end; end; % accumulate coherence images (all arrays [nb_points x timesout x trials]) % --------------------------- for index=1:length(varargin) tmpvar1 = varargin{index}{1}; tmpvar2 = varargin{index}{2}; if index == 1 % Shouldn't this be recalculated for arg2, etc.? TF 2007.06.04 cond1trials = size(tmpvar1,ndims(tmpvar1)); cond2trials = size(tmpvar2,ndims(tmpvar2)); for tmpi = 1:length(formula) accres{tmpi} = zeros(size(tmpvar1,1), size(tmpvar1,2), naccu); end; end; if ndims(tmpvar1) == 2 eval( [ 'arg' int2str(index) '=zeros(size(tmpvar1,1), cond1trials+cond2trials);' ] ); eval( [ 'arg' int2str(index) '(:,1:cond1trials)=tmpvar1;' ] ); eval( [ 'arg' int2str(index) '(:,cond1trials+1:end)=tmpvar2;' ] ); else eval( [ 'arg' int2str(index) '=zeros(size(tmpvar1,1), size(tmpvar1,2), cond1trials+cond2trials);' ] ); eval( [ 'arg' int2str(index) '(:,:,1:cond1trials)=tmpvar1;' ] ); eval( [ 'arg' int2str(index) '(:,:,cond1trials+1:end)=tmpvar2;' ] ); end; end; fprintf('Accumulating permutation statistics:'); alltrials = [1:cond1trials+cond2trials]; % processing formulas % ------------------- formula1 = []; formula2 = []; for index = 1:length(formula) % updating formula % ---------------- switch lower(condboot{ min(length(condboot), index) }) case 'abs', formula{index} = [ 'abs(' formula{index} ')' ]; %case 'angle', formula{index} = [ 'exp(j*angle(' formula{index} '))' ]; case 'angle', formula{index} = [ 'angle(' formula{index} ')/(2*pi)' ]; case 'complex', ; otherwise, condboot, error('condstat argument must be either ''abs'', ''angle'', ''complex'' or empty'); end; % computing difference (non-shuffled) % ----------------------------------- X = 1:cond1trials; eval( [ 'res1{index} = ' formula{index} ';'] ); X = cond1trials+1:cond1trials+cond2trials; eval( [ 'res2{index} = ' formula{index} ';'] ); diffres{index} = res1{index}-res2{index}; % build formula to execute % ------------------------ arrayname = [ 'accres{' int2str(index) '}' ]; if ndims(tmpvar1) == 2 % 2 dimensions formula1 = [ formula1 arrayname '(:,index) = ' formula{index} ';']; formula2 = [ formula2 arrayname '(:,index) = ' arrayname '(:,index) - ' formula{index} ';']; else % 3 dimensions formula1 = [ formula1 arrayname '(:,:,index) = ' formula{index} ';']; formula2 = [ formula2 arrayname '(:,:,index) = ' arrayname '(:,:,index) - ' formula{index} ';']; end; end; % accumulating (shuffling) % ----------------------- for index=1:naccu if rem(index,10) == 0, fprintf(' %d',index); end if rem(index,120) == 0, fprintf('\n'); end alltrials = shuffle(alltrials); X = alltrials(1:cond1trials); eval( formula1 ); X = alltrials(cond1trials+1:end); eval( formula2 ); end; % significance level % ------------------ for index= 1:length(formula) accarray = accres{index}; % size = nb_points*naccu % size = nb_points*naccu*times if ~isreal(accarray) % might want to introduce a warning here: a complex % result may not be desirable, and a single complex value % in accarray could turn this from a 2-tail to 1-tail % bootstrap test, leading to false positives. Hard to % think of a meaningful warning though... % TF 2007.06.04 accarray = sqrt(accarray .* conj(accarray)); % faster than abs() end; % compute bootstrap significance level i = round(naccu*alpha); switch ndims(accarray) case 3, accarray = sort(accarray,3); % always sort on naccu (when 3D, naccu is the second dim) if strcmpi(bootside{min(length(bootside), index)}, 'upper'); accarray = mean(accarray(:,:,naccu-i+1:naccu),3); else accarray = accarray(:,:,[end:-1:1]); accarraytmp(:,:,2) = mean(accarray(:,:,1:i),3); accarraytmp(:,:,1) = mean(accarray(:,:,naccu-i+1:naccu),3); accarray = accarraytmp; end; case 2, accarray = sort(accarray,2); % always sort on naccu (when 3D, naccu is the second dim) if strcmpi(bootside{min(length(bootside), index)}, 'upper'); accarray = mean(accarray(:,naccu-i+1:naccu),2); else accarraytmp(:,2) = mean(accarray(:,1:i),2); accarraytmp(:,1) = mean(accarray(:,naccu-i+1:naccu),2); accarray = accarraytmp; end; case 1, accarray = sort(accarray,1); % always sort on naccu (when 3D, naccu is the second dim) if strcmpi(bootside{min(length(bootside), index)}, 'upper'); accarray = mean(accarray(naccu-i+1:naccu),1); else accarraytmp(2) = mean(accarray(1:i),1); accarraytmp(1) = mean(accarray(naccu-i+1:naccu),1); accarray = accarraytmp; end; end; accres{index} = accarray; end; if length(res1) == 1 res1 = res1{1}; res2 = res2{1}; diffres = diffres{1}; accres = accres{1}; end; fprintf('\n'); return; % writing a function % ------------------ % $$$ fid = fopen('tmpfunc.m', 'w'); % $$$ fprintf(fid, 'function [accres] = tmpfunc(alltrials, cond1trials, naccu,'); % $$$ for index=1:length(varargin) % $$$ fprintf(fid, 'arg%d', index); % $$$ if index ~=length(varargin), fprintf(fid,','); end; % $$$ end; % $$$ fprintf(fid, ')\n'); % $$$ commandstr = [ 'for index=1:naccu, ' ] % $$$ % 'if rem(index,10) == 0, disp(index); end;' ]; % $$$ % 'if rem(index,10) == 0, fprintf('' %d'',index); end;' ... % $$$ % 'if rem(index,120) == 0, fprintf(''\n''); end;' ]; % $$$ commandstr = [ commandstr 'shuffle(alltrials);' ]; % $$$ commandstr = [ commandstr 'X = alltrials(1:cond1trials);' ]; % $$$ if ndims(tmpvar1) == 2 % 2 dimensions % $$$ commandstr = [ commandstr 'accres(:,index) = ' formula ';']; % $$$ commandstr = [ commandstr 'X = alltrials(cond1trials+1:end);']; % $$$ commandstr = [ commandstr 'accres(:,index) = accres(:,index)-' formula ';end;']; % $$$ else % $$$ commandstr = [ commandstr 'res1 = ' formula ';' 10]; % $$$ commandstr = [ commandstr 'X = alltrials(cond1trials+1:end);' 10]; % $$$ commandstr = [ commandstr 'res2 = ' formula ';' 10]; % $$$ commandstr = [ commandstr 'accres(:,:,index) = res1 - res2; end;']; % $$$ end; % $$$ fprintf(fid, commandstr); % $$$ fclose(fid); % $$$ profile on; % $$$ accres = tmpfunc(alltrials, cond1trials, naccu, arg1); % $$$ profile report; % $$$ profile off; % $$$ return; % evaluating a command % -------------------- % $$$ commandstr = [ 'for index=1:naccu, ' ... % $$$ 'if rem(index,10) == 0, fprintf('' %d'',index); end;' ... % $$$ 'if rem(index,120) == 0, fprintf(''\n''); end;' ]; % $$$ commandstr = [ commandstr 'shuffle(alltrials);' ]; % $$$ commandstr = [ commandstr 'X = alltrials(1:cond1trials);' ]; % $$$ if ndims(tmpvar1) == 2 % 2 dimensions % $$$ commandstr = [ commandstr 'accres(:,index) = ' formula ';']; % $$$ commandstr = [ commandstr 'X = alltrials(cond1trials+1:end);']; % $$$ commandstr = [ commandstr 'accres(:,index) = accres(:,index)-' formula ';end;']; % $$$ else % $$$ commandstr = [ commandstr 'accres(:,:,index) = ' formula ';']; % $$$ commandstr = [ commandstr 'X = alltrials(cond1trials+1:end);']; % $$$ commandstr = [ commandstr 'accres(:,:,index) = accres(:,:,index)-' formula ';end;']; % $$$ end; % $$$ eval(commandstr); % $$$ return; % $$$
github
lcnhappe/happe-master
movav.m
.m
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/movav.m
7,664
utf_8
a7743cb15a5f70fdc8db72736287f7ec
% movav() - Perform a moving average of data indexed by xvals. % Supports use of a moving non-rectangular window. % Can be used to resample a data matrix to any size % (see xadv NOTE below) and to regularize sampling of % irregularly sampled data. % Usage: % >> [outdata,outx] = movav(data,xvals,xwidth,xadv,firstx,lastx,xwin,nonorm); % % Input: % data = input data (chans,frames) % % Optional inputs: % xvals = increasing x-values for data frames (columnsa). The default % [1:frames] is fastest {def|[]|0 -> 1:frames} % xwidth = smoothing-window width in xvals units {def|0->(hix-lox)/4} % xadv = window step size in xvals units. NOTE: To reduce yyy frames % to about xxx, xadv needs to be near yyy/xxx {default|0 -> 1} % firstx = low xval of first averaging window {def|[] -> min xvals} % lastx = high xval of last averaging window {def|[] -> max xvals} % xwin = vector of window values {def|0 -> ones() = square window} % May be long. NOTE: linear interp. is NOT used between values. % Example: gauss(1001,2) -> [0.018 ... 1.0 ... 0.018] % nonorm = [1|0] If non-zero, do not normalize the moving sum. If % all y values are 1s. this creates a moving histogram. % Ex: >> [oy,ox] = movav(ones(size(x)),x,xwd,xadv,[],[],0,1); % returns a moving histogram of xvals {default: 0} % Outputs: % outdata = smoothed output data (chans,outframes) % outx = xval midpoints of successive output windows % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 10-25-97 % Copyright (C) 10-25-97 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 3-20-98 fixed bug in multi-channel windowed averaging -sm % 6-10-98 changed mean() and sum() to nanmean() and nansum() -sm % 2-16-99 tested for stat toolbox functions nanmean() and nansum() -sm % 9-03-01 fixed gauss() example -sm % 01-25-02 reformated help & licenses -ad function [outdata,outx] = movav(data,xvals,xwidth,xadv,firstx,lastx,xwin,nonorm) MAXPRINT = 1; % max outframe numbers to print on tty NEARZERO = 1e-22; % DEFAULT_XADV = 1; % default xvals window step advance verbose = 0; % If 1, output process info nanexist = 0; if nargin<1 help movav return else [chans,frames]=size(data); end if chans>1 & frames == 1, data = data'; % make row vector tmp = chans; chans = frames; frames = tmp; end if frames < 4 error('data are too short'); return end flag_fastave = 0; if nargin<2 | isempty(xvals) | (numel(xvals)==1 & xvals == 0) xvals = 1:frames; % flag default xvals flag_fastave = 0; % TURNED OFF THIS FEATURE - LEADS TO ?? BUG AT ABOUT 287 end % -sm 3/6/07 if size(xvals,1)>1 & size(xvals,2)>1 error('xvals must be a vector'); end xvals = xvals(:)'; % make xvals a row vector if frames ~= length(xvals) error('lengths of xvals and data not equal'); end if nargin < 8 | isempty(nonorm) nonorm = 0; % default -> return moving mean end if abs(nonorm) > NEARZERO nonorm = 1; end if nargin < 7 | isempty(xwin) xwin = 0; end if nargin < 6 | isempty(lastx) lastx = []; end if isempty(lastx), if flag_fastave lastx = frames; else lastx = max(xvals); end end if nargin<5 | isempty(firstx) firstx = []; end if isempty(firstx), if flag_fastave firstx = 1; else firstx = min(xvals); end end if nargin<4 | isempty(xadv) xadv = 0; end if isempty(xadv) | xadv == 0, xadv = DEFAULT_XADV; end if nargin<3 | isempty(xwidth) | xwidth==0 xwidth = (lastx-firstx)/4; % DEFAULT XWIDTH end wlen = 1; % default; if flag_fastave==0 if length(xwin)==1 & (xwin~=0) & (xwin~=1), % should be a vector or 0 error('xwin not vector or 0'); elseif size(xwin,1)>1 & size(xwin,2)>1 % not a matrix error('xwin cannot be a matrix'); end if size(xwin,1)>1 xwin = xwin'; % make row vector end if xwin~=0 wlen = length(xwin); end end %outframes = floor(0.99999+((lastx-firstx+xadv)-xwidth)/xadv); outframes = floor(((lastx-firstx+xadv+1)-xwidth)/xadv); if verbose fprintf('movav() will output %d frames.\n',outframes); end if outframes < 1, outframes = 1; end outdata = zeros(chans,outframes); outx = zeros(1,outframes); outxval = firstx+xwidth/2; % %%%%%%%%%%%%%%%%%%%%%% Print header %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if verbose, fprintf('Performing moving averaging:\n') fprintf('Output will be %d chans by %d frames',chans,outframes); if wlen>1, fprintf(' using the specified width-%d window\n',wlen); else fprintf(' using a width-%d square window\n',xwidth); end fprintf(' and a window advance of %g\n',xadv); end % %%%%%%%%%%%%%%%%%%% Perform averaging %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % lox = firstx; i = 0; % flag_fastave default for f=1:outframes hix = lox+xwidth; outx(1,f)=outxval; outxval = outxval + xadv; if flag_fastave == 0 i = find(xvals>=lox & xvals < hix); end if length(i)==0, if f>1, outdata(:,f) = outdata(:,f-1); % If no data, replicate else outdata(:,f) = zeros(chans,1); % or else output zeros end elseif length(xwin)==1, if flag_fastave > 0 outdata(:,f) = nan_mean(data(:,round(lox):round(hix))')'; nix = length([round(lox):round(hix)]); else outdata(:,f) = nan_mean(data(:,i)')'; % Else average nix = length(i); end if nonorm & nix % undo division by number of elements summed outdata(:,f) = outdata(:,f)*nix; end % %%%%%%%%%%%%%%%%% Windowed averaging %%%%%%%%%%%%%%%%%%%%%%%%%%% % else % length(xwin) > 1 wadv=(hix-lox)/wlen; ix = floor((xvals(i)-lox)/wadv)+1; % AG fix 3/6/07 if length(xwin)>1 sumx = sum(xwin(ix)); else sumx=1; end % AG fix 3/6/7 outdata(:,f) = nan_sum((((ones(chans,1)*xwin(ix)).*data(:,i)))')'; if abs(sumx) > NEARZERO & nonorm == 0 outdata(:,f) = outdata(:,f)/sumx; end end lox = lox+xadv; if (outframes<MAXPRINT) fprintf('%d ',f); end end if verbose, fprintf('\n'); end % %%%%%%%%%%%%%%%%%%%%%%% function nan_mean() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % nan_mean() - take the column means of a matrix, ignoring NaN values % function out = nan_mean(in) nans = find(isnan(in)); in(nans) = 0; sums = sum(in); nonnans = ones(size(in)); nonnans(nans) = 0; nonnans = sum(nonnans,1); nononnans = find(nonnans==0); nonnans(nononnans) = 1; out = sum(in,1)./nonnans; out(nononnans) = NaN; % %%%%%%%%%%%%%%%%%%%%%%% function nan_sum() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % nan_sum() - take the column sums of a matrix, ignoring NaN values % function out = nan_sum(in) nans = find(isnan(in)); in(nans) = 0; out = sum(in,1); nonnans = ones(size(in)); nonnans(nans) = 0; nonnans = sum(nonnans,1); nononnans = find(nonnans==0); out(nononnans) = NaN;
github
lcnhappe/happe-master
readtxtfile.m
.m
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/readtxtfile.m
1,473
utf_8
884a7c06601ae6728761a5e03fd42521
% readtxtfile() - Read text file into a Matlab variable % % Usage: >> str = readtxtfile( filename ); % % Input: % filename - [string] name of the file. % % Output: % str - [string] content of the file. % % Author: Arnaud Delorme, SCCN / INC / UCSD, August 2009 % Copyright (C) Arnaud Delorme, August 2009 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function com = readtxtfile(filename) com = ''; if ~exist(filename) disp([ 'Cannot find option file ' filename ]); else fid = fopen(filename, 'r'); if fid == -1 disp([ 'Cannot open option file ' filename ]); else com = ''; while ~feof(fid) a = fgetl(fid); com = [ com 10 a ]; end; fclose(fid); end; end;
github
lcnhappe/happe-master
openbdf.m
.m
happe-master/Packages/eeglab14_0_0b/functions/sigprocfunc/openbdf.m
6,712
utf_8
1496f13e75bb80dd10e647e3497b1a52
% openbdf() - Opens an BDF File (European Data Format for Biosignals) in MATLAB (R) % % Usage: % >> EDF=openedf(FILENAME) % % Note: About EDF -> www.biosemi.com/faq/file_format.htm % % Author: Alois Schloegl, 5.Nov.1998 % % See also: readedf() % Copyright (C) 1997-1998 by Alois Schloegl % [email protected] % Ver 2.20 18.Aug.1998 % Ver 2.21 10.Oct.1998 % Ver 2.30 5.Nov.1998 % % For use under Octave define the following function % function s=upper(s); s=toupper(s); end; % V2.12 Warning for missing Header information % V2.20 EDF.AS.* changed % V2.30 EDF.T0 made Y2K compatible until Year 2090 % This program is free software; you can redistribute it and/or % modify it under the terms of the GNU General Public License % as published by the Free Software Foundation; either version 2 % of the License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. % Name changed for bdf files Sept 6,2002 T.S. Lorig % Header updated for EEGLAB format (update web link too) - Arnaud Delorme 14 Oct 2002 function [DAT,H1]=openbdf(FILENAME) SLASH='/'; % defines Seperator for Subdirectories BSLASH=setstr(92); cname=computer; if cname(1:2)=='PC' SLASH=BSLASH; end; fid=fopen(FILENAME,'r','ieee-le'); if fid<0 fprintf(2,['Error LOADEDF: File ' FILENAME ' not found\n']); return; end; EDF.FILE.FID=fid; EDF.FILE.OPEN = 1; EDF.FileName = FILENAME; PPos=min([max(find(FILENAME=='.')) length(FILENAME)+1]); SPos=max([0 find((FILENAME=='/') | (FILENAME==BSLASH))]); EDF.FILE.Ext = FILENAME(PPos+1:length(FILENAME)); EDF.FILE.Name = FILENAME(SPos+1:PPos-1); if SPos==0 EDF.FILE.Path = pwd; else EDF.FILE.Path = FILENAME(1:SPos-1); end; EDF.FileName = [EDF.FILE.Path SLASH EDF.FILE.Name '.' EDF.FILE.Ext]; H1=setstr(fread(EDF.FILE.FID,256,'char')'); % EDF.VERSION=H1(1:8); % 8 Byte Versionsnummer %if 0 fprintf(2,'LOADEDF: WARNING Version EDF Format %i',ver); end; EDF.PID = deblank(H1(9:88)); % 80 Byte local patient identification EDF.RID = deblank(H1(89:168)); % 80 Byte local recording identification %EDF.H.StartDate = H1(169:176); % 8 Byte %EDF.H.StartTime = H1(177:184); % 8 Byte EDF.T0=[str2num(H1(168+[7 8])) str2num(H1(168+[4 5])) str2num(H1(168+[1 2])) str2num(H1(168+[9 10])) str2num(H1(168+[12 13])) str2num(H1(168+[15 16])) ]; % Y2K compatibility until year 2090 if EDF.VERSION(1)=='0' if EDF.T0(1) < 91 EDF.T0(1)=2000+EDF.T0(1); else EDF.T0(1)=1900+EDF.T0(1); end; else ; % in a future version, this is hopefully not needed end; EDF.HeadLen = str2num(H1(185:192)); % 8 Byte Length of Header % reserved = H1(193:236); % 44 Byte EDF.NRec = str2num(H1(237:244)); % 8 Byte # of data records EDF.Dur = str2num(H1(245:252)); % 8 Byte # duration of data record in sec EDF.NS = str2num(H1(253:256)); % 8 Byte # of signals EDF.Label = setstr(fread(EDF.FILE.FID,[16,EDF.NS],'char')'); EDF.Transducer = setstr(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); EDF.PhysDim = setstr(fread(EDF.FILE.FID,[8,EDF.NS],'char')'); EDF.PhysMin= str2num(setstr(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.PhysMax= str2num(setstr(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.DigMin = str2num(setstr(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); % EDF.DigMax = str2num(setstr(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); % % check validity of DigMin and DigMax if (length(EDF.DigMin) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Digital Minimum\n'); EDF.DigMin = -(2^15)*ones(EDF.NS,1); end if (length(EDF.DigMax) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Digital Maximum\n'); EDF.DigMax = (2^15-1)*ones(EDF.NS,1); end if (any(EDF.DigMin >= EDF.DigMax)) fprintf(2,'Warning OPENEDF: Digital Minimum larger than Maximum\n'); end % check validity of PhysMin and PhysMax if (length(EDF.PhysMin) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Physical Minimum\n'); EDF.PhysMin = EDF.DigMin; end if (length(EDF.PhysMax) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Physical Maximum\n'); EDF.PhysMax = EDF.DigMax; end if (any(EDF.PhysMin >= EDF.PhysMax)) fprintf(2,'Warning OPENEDF: Physical Minimum larger than Maximum\n'); EDF.PhysMin = EDF.DigMin; EDF.PhysMax = EDF.DigMax; end EDF.PreFilt= setstr(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); % tmp = fread(EDF.FILE.FID,[8,EDF.NS],'char')'; % samples per data record EDF.SPR = str2num(setstr(tmp)); % samples per data record fseek(EDF.FILE.FID,32*EDF.NS,0); EDF.Cal = (EDF.PhysMax-EDF.PhysMin)./ ... (EDF.DigMax-EDF.DigMin); EDF.Off = EDF.PhysMin - EDF.Cal .* EDF.DigMin; tmp = find(EDF.Cal < 0); EDF.Cal(tmp) = ones(size(tmp)); EDF.Off(tmp) = zeros(size(tmp)); EDF.Calib=[EDF.Off';(diag(EDF.Cal))]; %EDF.Calib=sparse(diag([1; EDF.Cal])); %EDF.Calib(1,2:EDF.NS+1)=EDF.Off'; EDF.SampleRate = EDF.SPR / EDF.Dur; EDF.FILE.POS = ftell(EDF.FILE.FID); if EDF.NRec == -1 % unknown record size, determine correct NRec fseek(EDF.FILE.FID, 0, 'eof'); endpos = ftell(EDF.FILE.FID); EDF.NRec = floor((endpos - EDF.FILE.POS) / (sum(EDF.SPR) * 2)); fseek(EDF.FILE.FID, EDF.FILE.POS, 'bof'); H1(237:244)=sprintf('%-8i',EDF.NRec); % write number of records end; EDF.Chan_Select=(EDF.SPR==max(EDF.SPR)); for k=1:EDF.NS if EDF.Chan_Select(k) EDF.ChanTyp(k)='N'; else EDF.ChanTyp(k)=' '; end; if findstr(upper(EDF.Label(k,:)),'ECG') EDF.ChanTyp(k)='C'; elseif findstr(upper(EDF.Label(k,:)),'EKG') EDF.ChanTyp(k)='C'; elseif findstr(upper(EDF.Label(k,:)),'EEG') EDF.ChanTyp(k)='E'; elseif findstr(upper(EDF.Label(k,:)),'EOG') EDF.ChanTyp(k)='O'; elseif findstr(upper(EDF.Label(k,:)),'EMG') EDF.ChanTyp(k)='M'; end; end; EDF.AS.spb = sum(EDF.SPR); % Samples per Block bi=[0;cumsum(EDF.SPR)]; idx=[];idx2=[]; for k=1:EDF.NS, idx2=[idx2, (k-1)*max(EDF.SPR)+(1:EDF.SPR(k))]; end; maxspr=max(EDF.SPR); idx3=zeros(EDF.NS*maxspr,1); for k=1:EDF.NS, idx3(maxspr*(k-1)+(1:maxspr))=bi(k)+ceil((1:maxspr)'/maxspr*EDF.SPR(k));end; %EDF.AS.bi=bi; EDF.AS.IDX2=idx2; %EDF.AS.IDX3=idx3; DAT.Head=EDF; DAT.MX.ReRef=1; %DAT.MX=feval('loadxcm',EDF); return;
github
lcnhappe/happe-master
anova2rm_cell.m
.m
happe-master/Packages/eeglab14_0_0b/functions/statistics/anova2rm_cell.m
6,774
utf_8
37ad08d0dfb97a5ae59971a6becc90b7
% anova2rm_cell() - compute F-values in cell array using repeated measure % ANOVA. % % Usage: % >> [FC FR FI dfc dfr dfi] = anova2rm_cell( data ); % % Inputs: % data = data consisting of PAIRED arrays to be compared. The last % dimension of the data array is used to compute ANOVA. % Outputs: % FC - F-value for columns. % FR - F-value for rows. % FI - F-value for interaction. % dfc - degree of freedom for columns. % dfr - degree of freedom for rows. % dfi - degree of freedom for interaction. % % Note: this function is inspired from rm_anova available at % http://www.mathworks.se/matlabcentral/fileexchange/6874-two-way-rep % eated-measures-anova % It allows for fast computation of about 20 thousands ANOVA per % second. It is different from anova2_cell which mimics the ANOVA % fonction from the Matlab statistical toolbox. This function % computes true repeated measure ANOVA. % % Example: % a = { rand(1,10) rand(1,10) rand(1,10); rand(1,10) rand(1,10) rand(1,10) } % [FC FR FI dfc dfr dfi] = anova2rm_cell(a) % signifC = 1-fcdf(FC, dfc(1), dfc(2)) % signifR = 1-fcdf(FR, dfr(1), dfr(2)) % signifI = 1-fcdf(FI, dfi(1), dfi(2)) % % % for comparison % z = zeros(10,1); o = ones(10,1); t = ones(10,1)*2; % rm_anova2( [ a{1,1}';a{1,2}';a{1,3}';a{2,1}';a{2,2}';a{2,3}' ], ... % repmat([1:10]', [6 1]), [o;o;o;z;z;z], [z;o;t;z;o;t], {'a','b'}) % % c = { rand(200,400,10) rand(200,400,10); ... % rand(200,400,10) rand(200,400,10)}; % [FC FR FI dfc dfr dfi] = anova2rm_cell(c) % computes 200x400 ANOVAs % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2010 % Copyright (C) Arnaud Delorme % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [fA fB fAB dfApair dfBpair dfABpair] = anova2rm_cell(data) % compute all means and all std % ----------------------------- a = size(data,1); b = size(data,2); nd = myndims( data{1} ); n = size( data{1} ,nd); % only for paired stats % --------------------- if nd == 1 AB = zeros(a,b,'single'); AS = zeros(a,n,'single'); BS = zeros(b,n,'single'); sq = single(0); for ind1 = 1:a for ind2 = 1:b AB(ind1,ind2) = sum(data{ind1,ind2}); AS(ind1,:) = AS(ind1,:) + data{ind1,ind2}'; BS(ind2,:) = BS(ind2,:) + data{ind1,ind2}'; sq = sq + sum(data{ind1,ind2}.^2); end; end; dimA = 2; dimB = 1; elseif nd == 2 AB = zeros(size(data{1},1),a,b,'single'); AS = zeros(size(data{1},1),a,n,'single'); BS = zeros(size(data{1},1),b,n,'single'); sq = zeros(size(data{1},1),1,'single'); for ind1 = 1:a for ind2 = 1:b AB(:,ind1,ind2) = sum(data{ind1,ind2},nd); AS(:,ind1,:) = AS(:,ind1,:) + reshape(data{ind1,ind2},size(data{1},1),1,n); BS(:,ind2,:) = BS(:,ind2,:) + reshape(data{ind1,ind2},size(data{1},1),1,n); sq = sq + sum(data{ind1,ind2}.^2,nd); end; end; dimA = 3; dimB = 2; elseif nd == 3 AB = zeros(size(data{1},1),size(data{1},2),a,b,'single'); AS = zeros(size(data{1},1),size(data{1},2),a,n,'single'); BS = zeros(size(data{1},1),size(data{1},2),b,n,'single'); sq = zeros(size(data{1},1),size(data{1},2),'single'); for ind1 = 1:a for ind2 = 1:b AB(:,:,ind1,ind2) = sum(data{ind1,ind2},nd); AS(:,:,ind1,:) = AS(:,:,ind1,:) + reshape(data{ind1,ind2},size(data{1},1),size(data{1},2),1,n); BS(:,:,ind2,:) = BS(:,:,ind2,:) + reshape(data{ind1,ind2},size(data{1},1),size(data{1},2),1,n); sq = sq + sum(data{ind1,ind2}.^2,nd); end; end; dimA = 4; dimB = 3; elseif nd == 4 AB = zeros(size(data{1},1),size(data{1},2),size(data{1},3),a,b,'single'); AS = zeros(size(data{1},1),size(data{1},2),size(data{1},3),a,n,'single'); BS = zeros(size(data{1},1),size(data{1},2),size(data{1},3),b,n,'single'); sq = zeros(size(data{1},1),size(data{1},2),size(data{1},3),'single'); for ind1 = 1:a for ind2 = 1:b AB(:,:,:,ind1,ind2) = sum(data{ind1,ind2},nd); AS(:,:,:,ind1,:) = AS(:,:,:,ind1,:) + reshape(data{ind1,ind2},size(data{1},1),size(data{1},2),size(data{1},3),1,n); BS(:,:,:,ind2,:) = BS(:,:,:,ind2,:) + reshape(data{ind1,ind2},size(data{1},1),size(data{1},2),size(data{1},3),1,n); sq = sq + sum(data{ind1,ind2}.^2,nd); end; end; dimA = 5; dimB = 4; end; A = sum(AB,dimA); % sum across columns, so result is ax1 column vector B = sum(AB,dimB); % sum across rows, so result is 1xb row vector S = sum(AS,dimB); % sum across columns, so result is 1xs row vector T = sum(sum(A,dimB),dimA); % could sum either A or B or S, choice is arbitrary % degrees of freedom dfA = a-1; dfB = b-1; dfAB = (a-1)*(b-1); dfS = n-1; dfAS = (a-1)*(n-1); dfBS = (b-1)*(n-1); dfABS = (a-1)*(b-1)*(n-1); % bracket terms (expected value) expA = sum(A.^2,dimB)./(b*n); expB = sum(B.^2,dimA)./(a*n); expAB = sum(sum(AB.^2,dimA),dimB)./n; expS = sum(S.^2,dimA)./(a*b); expAS = sum(sum(AS.^2,dimB),dimA)./b; expBS = sum(sum(BS.^2,dimB),dimA)./a; expY = sq; %sum(Y.^2); expT = T.^2 / (a*b*n); % sums of squares ssA = expA - expT; ssB = expB - expT; ssAB = expAB - expA - expB + expT; ssS = expS - expT; ssAS = expAS - expA - expS + expT; ssBS = expBS - expB - expS + expT; ssABS = expY - expAB - expAS - expBS + expA + expB + expS - expT; ssTot = expY - expT; % mean squares msA = ssA / dfA; msB = ssB / dfB; msAB = ssAB / dfAB; msS = ssS / dfS; msAS = ssAS / dfAS; msBS = ssBS / dfBS; msABS = ssABS / dfABS; % f statistic fA = msA ./ msAS; fB = msB ./ msBS; fAB = msAB ./ msABS; dfApair = [dfA dfAS]; dfBpair = [dfB dfBS]; dfABpair = [dfAB dfABS]; function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end;
github
lcnhappe/happe-master
statcond.m
.m
happe-master/Packages/eeglab14_0_0b/functions/statistics/statcond.m
24,879
utf_8
8adfae55efd5defaad53dc2a93a6dc25
% statcond() - compare two or more data conditions statistically using % standard parametric or nonparametric permutation-based ANOVA % (1-way or 2-way) or t-test methods. Parametric testing uses % fcdf() from the Matlab Statistical Toolbox. % Usage: % >> [stats, df, pvals, surrog] = statcond( data, 'key','val'... ); % % Inputs: % data = one-or two-dimensional cell array of data matrices. % For nonparametric, permutation-based testing, the % last dimension of the data arrays (which may be of up to % 4 dimensions) is permuted across conditions, either in % a 'paired' fashion (not changing the, e.g., subject or % trial order in the last dimension) or in an umpaired % fashion (not respecting this order). If the number of % elements in the last dimension is not the same across % conditions, the 'paired' option is turned 'off'. Note: % All other dimensions MUST be constant across conditions. % For example, consider a (1,3) cell array of matrices % of size (100,20,x) each holding a (100,20) time/frequency % transform from each of x subjects. Only the last dimension % (here x, the number of subjects) may differ across the % three conditions. % The test used depends on the size of the data array input. % When the data cell array has 2 columns and the data are % paired, a paired t-test is performed; when the data are % unpaired, an unpaired t-test is performed. If 'data' % has only one row (paired or unpaired) and more than 2 % columns, a one-way ANOVA is performed. If the data cell % array contains several rows and columns, and the data is % paired, a two-way repeated measure ANOVA is performed. % NOTE THAT IF THE DATA is unpaired, EEGLAB will use a % balanced 1 or 2 way ANOVA and parametric results might not % be meaningful (bootstrap and permstatcondutation should be fine). % % Optional inputs: % 'paired' = ['on'|'off'] pair the data array {default: 'on' unless % the last dimension of data array is of different lengths}. % For two independent variables, this input is a cell array, % for example { 'on' 'off' } indicating that the first % independent variable is paired and the second is not. % 'method' = ['perm'|'bootstrap'|'param'] method for computing the p-values: % 'param' or 'parametric' = parametric testing (standard ANOVA % or t-test); % 'perm' or 'permutation' = non-parametric testing using % surrogate data % 'bootstrap' = non-parametric bootstrap % made by permuting the input data {default: 'param'} % 'naccu' = [integer] Number of surrogate data copies to use in 'perm' % or 'bootstrap' method estimation (see above) {default: 200}. % 'verbose' = ['on'|'off'] print info on the command line {default: 'on'}. % 'variance' = ['homegenous'|'inhomogenous'] this option is exclusively % for parametric statistics using unpaired t-test. It allows % to compute a more accurate value for the degree of freedom % using the formula for inhomogenous variance (see % ttest2_cell function). Default is 'inhomegenous'. % 'surrog' = surrogate data array (see output). % 'stats' = F- or T-value array (see output). % 'tail' = ['one'|'two'] run one-tailed (F-test) or two tailed % (T-test). This option is only relevant when using the % 'surrog' input. Otherwise it is ignored. % 'forceanova' = ['on'|'off'] force the use of ANOVA calculation even % for 2x1 designs. Default is 'off'. % 'alpha' = [float] p-value threshold value. Allow returning % confidence intervals and mask (requires structoutput below). % 'structoutput' = ['on'|'off'] return an output structure instead of % the regular output. Allow to output mask and confidence % intervals. % % Legacy parameters: % 'threshold' - now 'alpha' % 'mode' - now 'method' % % Outputs: % stats = F- or T-value array of the same size as input data without % the last dimension. A T value is returned only when the data % includes exactly two conditions. % df = degrees of freedom, a (2,1) vector, when F-values are returned % pvals = array of p-values. Same size as input data without the last % data dimension. All returned p-values are two-tailed. % surrog = surrogate data array (same size as input data with the last % dimension filled with a number ('naccu') of surrogate data sets. % % Important note: When a two-way ANOVA is performed, outputs are cell arrays % with three elements: output(1) = row effects; % output(2) = column effects; output(3) = interactions % between rows and columns. % % Examples: % >> a = { rand(1,10) rand(1,10)+0.5 }; % pseudo 'paired' data vectors % [t df pvals] = statcond(a); % perform paired t-test % pvals = % 5.2807e-04 % standard t-test probability value % % Note: for different rand() outputs, results will differ. % % [t df pvals surog] = statcond(a, 'method', 'perm', 'naccu', 2000); % pvals = % 0.0065 % nonparametric t-test using 2000 permuted data sets % % a = { rand(2,11) rand(2,10) rand(2,12)+0.5 }; % pseudo 'unpaired' % [F df pvals] = statcond(a); % perform an unpaired ANOVA % pvals = % 0.00025 % p-values for difference between columns % 0.00002 % for each data row % % a = { rand(3,4,10) rand(3,4,10) rand(3,4,10); ... % rand(3,4,10) rand(3,4,10) rand(3,4,10)+0.5 }; % % pseudo (2,3)-condition data array, each entry containing % % ten (3,4) data matrices % [F df pvals] = statcond(a); % perform a paired 2-way ANOVA % % Output: % pvals{1} % a (3,4) matrix of p-values; effects across rows % pvals{2} % a (3,4) matrix of p-values; effects across colums % pvals{3} % a (3,4) matrix of p-values; interaction effects % % across rows and columns % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005- % With thanks to Robert Oostenveld for fruitful discussions % and advice on this function. % % See also: anova1_cell(), anova2_cell(), anova2rm_cell, fcdf() % perform a paired t-test % ----------------------- % a = { rand(2,10) rand(2,10) }; % [t df pval] = statcond(a); pval % [h p t stat] = ttest( a{1}(1,:), a{2}(1,:)); p % [h p t stat] = ttest( a{1}(2,:), a{2}(2,:)); p % % compare significance levels % -------------------------- % a = { rand(1,10) rand(1,10) }; % [F df pval] = statcond(a, 'method', 'perm', 'naccu', 200); pval % [h p t stat] = ttest( a{1}(1,:), a{2}(1,:)); p % Copyright (C) Arnaud Delorme % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [ ori_vals, df, pvals, surrogval ] = statcond( data, varargin ); if nargin < 1 help statcond; return; end; try, warning('off', 'MATLAB:divideByZero'); catch, end; if exist('finputcheck') g = finputcheck( varargin, { 'naccu' 'integer' [1 Inf] 200; 'method' 'string' { 'param','parametric','perm','permutation','bootstrap' } 'param'; 'mode' 'string' { } ''; 'paired' 'string' { 'on','off' } 'on'; 'surrog' { 'real','cell' } [] []; 'stats' { 'real','cell' } [] []; 'structoutput' 'string' { 'on','off' } 'off'; 'forceanova' 'string' { 'on','off' } 'off'; 'arraycomp' 'string' { 'on','off' } 'on'; 'alpha' 'real' [] NaN; 'tail' 'string' { 'one','both','upper','lower'} 'both'; 'variance' 'string' { 'homogenous','inhomogenous' } 'inhomogenous'; 'returnresamplingarray' 'string' { 'on','off' } 'off'; 'verbose' 'string' { 'on','off' } 'on' }, 'statcond'); if isstr(g), error(g); end; else g = struct(varargin{:}); if ~isfield(g, 'naccu'), g.naccu = 200; end; if ~isfield(g, 'method'), g.method = 'param'; end; if ~isfield(g, 'paired'), g.paired = 'on'; end; if ~isfield(g, 'surrog'), g.surrog = []; end; if ~isfield(g, 'orivals'), g.orivals = []; end; if ~isfield(g, 'arraycomp'), g.arraycomp = 'on'; end; if ~isfield(g, 'verbose'), g.verbose = 'on'; end; if ~isfield(g, 'tail'), g.tail = 'both'; end; if ~isfield(g, 'variance'), g.variance = 'homogenous'; end; if ~isfield(g, 'structoutput'), g.structoutput = 'on'; end; if ~isfield(g, 'returnresamplingarray'), g.returnresamplingarray = 'off'; end; end; if ~isempty(g.mode), g.method = g.mode; end; if strcmpi(g.method, 'parametric'), g.method = 'param'; end; if strcmpi(g.method, 'permutation'), g.method = 'perm'; end; if strcmpi(g.verbose, 'on'), verb = 1; else verb = 0; end; if strcmp(g.method, 'param' ) && exist('fcdf') ~= 2 myfprintf('on',['statcond(): parametric testing requires fcdf() \n' ... ' from the Matlab StatsticaL Toolbox.\n' ... ' Running nonparametric permutation tests\n.']); g.method = 'perm'; end if size(data,2) == 1, data = transpose(data); end; % cell array transpose g.naccu = round(g.naccu); % reshape matrices % ---------------- nd = size(data{1}); nd = nd(1:end-1); for index = 1:prod(size(data)) data{index} = reshape(data{index}, [prod(nd) size(data{index},myndims(data{index}))]); end; if ~strcmpi(g.method, 'param') && isempty(g.surrog) tmpsize = size(data{1}); surrogval = zeros([ tmpsize(1:end-1) g.naccu ], 'single'); else surrogval = []; end; % check for NaNs or Inf % --------------------- for iDat = 1:length(data(:)) if any(isnan(reshape(data{iDat}, prod(size(data{iDat})),1))) || ... any(isinf(reshape(data{iDat}, prod(size(data{iDat})),1))) error('Statcond: One of the input array contains NaNs or Infinite values'); end; end; % bootstrap flag % -------------- if strcmpi(g.method, 'bootstrap'), bootflag = 1; else bootflag = 0; end; if isempty(g.surrog) % test if data can be paired % -------------------------- if length(unique(cellfun('size', data, ndims(data{1}) ))) > 1 g.paired = 'off'; end; if strcmpi(g.paired, 'on') pairflag = 1; else pairflag = 0; end; % return resampling array % ----------------------- if strcmpi(g.returnresamplingarray, 'on') [ datavals datalen datadims ] = concatdata( data ); if strcmpi(g.arraycomp, 'on') ori_vals = surrogdistrib( data, 'method', g.method, 'pairing', g.paired, 'naccu', g.naccu); else ori_vals = surrogdistrib( data, 'method', g.method, 'pairing', g.paired); end; return; end; % text output % ----------- myfprintf(verb,'%d x %d, ', size(data,1), size(data,2)); if strcmpi(g.paired, 'on') myfprintf(verb,'paired data, '); else myfprintf(verb,'unpaired data, '); end; if size(data,1) == 1 && size(data,2) == 2 myfprintf(verb,'computing T values\n'); else myfprintf(verb,'computing F values\n'); end; if size(data,1) > 1 if strcmpi(g.paired, 'on') myfprintf(verb,'Using 2-way repeated measure ANOVA\n'); else myfprintf(verb,'Using balanced 2-way ANOVA (not suitable for parametric testing, only bootstrap)\n'); end; elseif size(data,2) > 2 if strcmpi(g.paired, 'on') myfprintf(verb,'Using 1-way repeated measure ANOVA\n'); else myfprintf(verb,'Using balanced 1-way ANOVA (equivalent to Matlab anova1)\n'); end; else if strcmpi(g.paired, 'on') myfprintf(verb,'Using paired t-test\n'); else myfprintf(verb,'Using unpaired t-test\n'); end; end; if ~strcmpi(g.method, 'param') if bootflag, myfprintf(verb,'Bootstraps (of %d):', g.naccu); else myfprintf(verb,'Permutations (of %d):', g.naccu); end; end; end; tail = g.tail; if isempty(g.surrog) if size(data,1) == 1, % only one row if size(data,2) == 2 && strcmpi(g.forceanova, 'off') % paired t-test (very fast) % ------------- [ori_vals df] = ttest_cell_select(data, g.paired, g.variance); if strcmpi(g.method, 'param') % Check if exist tcd.m file from the Statistics Toolbox (Bug 1352 ) if exist('tcdf','file') == 2 & license('test', 'Statistics_Toolbox') pvals = 2*tcdf(-abs(ori_vals), df); else pvals = 2*mytcdf(-abs(ori_vals), df); end pvals = reshape(pvals, size(pvals)); else if strcmpi(g.arraycomp, 'on') try myfprintf(verb,'...'); res = surrogdistrib( data, 'method', g.method, 'pairing', g.paired, 'naccu', g.naccu); surrogval = ttest_cell_select( res, g.paired, g.variance); catch, lasterr myfprintf(verb,'\nSuperfast array computation failed because of memory limitation, reverting to standard computation'); g.arraycomp = 'off'; end; end; if strcmpi(g.arraycomp, 'off') [res precomp] = surrogdistrib( data, 'method', g.method, 'pairing', g.paired); for index = 1:g.naccu res = surrogdistrib( {}, 'precomp', precomp); if mod(index, 10) == 0, myfprintf(verb,'%d ', index); end; if mod(index, 100) == 0, myfprintf(verb,'\n'); end; if myndims(res{1}) == 1 surrogval(index) = ttest_cell_select(res, g.paired, g.variance); else surrogval(:,index) = ttest_cell_select(res, g.paired, g.variance); end; end; end; end; else % one-way ANOVA (paired) this is equivalent to unpaired t-test % ------------- tail = 'one'; [ori_vals df] = anova1_cell_select( data, g.paired ); if strcmpi(g.method, 'param') pvals = 1-fcdf(ori_vals, df(1), df(2)); else if strcmpi(g.arraycomp, 'on') try myfprintf(verb,'...'); res = surrogdistrib( data, 'method', g.method, 'pairing', g.paired, 'naccu', g.naccu); surrogval = anova1_cell_select( res, g.paired ); catch, myfprintf(verb,'\nSuperfast array computation failed because of memory limitation, reverting to standard computing'); g.arraycomp = 'off'; end; end; if strcmpi(g.arraycomp, 'off') [res precomp] = surrogdistrib( data, 'method', g.method, 'pairing', g.paired); for index = 1:g.naccu if mod(index, 10) == 0, myfprintf(verb,'%d ', index); end; if mod(index, 100) == 0, myfprintf(verb,'\n'); end; res = surrogdistrib( {}, 'precomp', precomp); if myndims(data{1}) == 1 surrogval(index) = anova1_cell_select( res, g.paired ); else surrogval(:,index) = anova1_cell_select( res, g.paired ); end; end; end; end; end; else % two-way ANOVA (paired or unpaired) % ---------------------------------- tail = 'one'; [ ori_vals{1} ori_vals{2} ori_vals{3} df{1} df{2} df{3} ] = anova2_cell_select( data, g.paired ); if strcmpi(g.method, 'param') pvals{1} = 1-fcdf(ori_vals{1}, df{1}(1), df{1}(2)); pvals{2} = 1-fcdf(ori_vals{2}, df{2}(1), df{2}(2)); pvals{3} = 1-fcdf(ori_vals{3}, df{3}(1), df{3}(2)); else surrogval = { surrogval surrogval surrogval }; dataori = data; if strcmpi(g.arraycomp, 'on') try myfprintf(verb,'...'); res = surrogdistrib( data, 'method', g.method, 'pairing', g.paired, 'naccu', g.naccu); [ surrogval{1} surrogval{2} surrogval{3} ] = anova2_cell_select( res, g.paired ); catch, myfprintf(verb,'\nSuperfast array computation failed because of memory limitation, reverting to standard computing'); g.arraycomp = 'off'; end; end; if strcmpi(g.arraycomp, 'off') [res precomp] = surrogdistrib( data, 'method', g.method, 'pairing', g.paired); for index = 1:g.naccu if mod(index, 10) == 0, myfprintf(verb,'%d ', index); end; if mod(index, 100) == 0, myfprintf(verb,'\n'); end; res = surrogdistrib( {}, 'precomp', precomp); if myndims(data{1}) == 1 [ surrogval{1}(index) surrogval{2}(index) surrogval{3}(index) ] = anova2_cell_select( res, g.paired ); else [ surrogval{1}(:,index) surrogval{2}(:,index) surrogval{3}(:,index) ] = anova2_cell_select( res, g.paired ); end; end; end; end; end; myfprintf(verb,'\n'); else surrogval = g.surrog; ori_vals = g.stats; df = []; end; % compute p-values % ---------------- if ~strcmpi(g.method, 'param') if iscell( surrogval ) pvals{1} = stat_surrogate_pvals(surrogval{1}, ori_vals{1}, tail); pvals{2} = stat_surrogate_pvals(surrogval{2}, ori_vals{2}, tail); pvals{3} = stat_surrogate_pvals(surrogval{3}, ori_vals{3}, tail); else pvals = stat_surrogate_pvals(surrogval, ori_vals, tail); end; try, warning('on', 'MATLAB:divideByZero'); catch, end; end; [ ori_vals, pvals ] = reshape_results( nd, ori_vals, pvals); [ surrogval ] = reshape_results( [nd g.naccu], surrogval); % confidence intervals % -------------------- if ~isnan(g.alpha) outputstruct.ci = stat_surrogate_ci(surrogval, g.alpha, tail); if strcmpi(g.structoutput, 'off') disp('Warning: returning confidence interval requires an output structure'); end; if iscell(pvals) for ind = 1:length(pvals) outputstruct.mask{ind} = pvals{ind} < g.alpha; end; else outputstruct.mask = pvals < g.alpha; end; end; % create a structure for outputing values % --------------------------------------- if strcmpi(g.structoutput, 'on') outputstruct.method = g.method; outputstruct.pval = pvals; outputstruct.df = df; outputstruct.surrog = surrogval; if length(data(:)) == 2 outputstruct.t = ori_vals; else outputstruct.f = ori_vals; end; outputstruct.stat = ori_vals; ori_vals = outputstruct; end; % compute ANOVA 2-way % ------------------- function [f1 f2 f3 df1 df2 df3] = anova2_cell_select( res, paired); if strcmpi(paired,'on') [f1 f2 f3 df1 df2 df3] = anova2rm_cell( res ); else [f1 f2 f3 df1 df2 df3] = anova2_cell( res ); end; % compute ANOVA 1-way % ------------------- function [f df] = anova1_cell_select( res, paired); if strcmpi(paired,'on') [f df] = anova1rm_cell( res ); else [f df] = anova1_cell( res ); end; % compute t-test % ------------------- function [t df] = ttest_cell_select( res, paired, homogenous); if strcmpi(paired,'on') [t df] = ttest_cell( res{1}, res{2}); else [t df] = ttest2_cell( res{1}, res{2}, homogenous); end; % function to compute the number of dimensions % -------------------------------------------- function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end; % function for verbose messages % ----------------------------- function myfprintf(verb, varargin) if verb fprintf(varargin{:}); end; % function to replace tcdf % ------------------------ function p = mytcdf(x,v) if length(v) == 1, v = repmat(v, size(x)); end; x2 = x.^2; inds1 = (v < x2); inds2 = (v >= x2); if any(inds1(:)), p(inds1) = betainc(v(inds1) ./ (v(inds1) + x2(inds1)), v(inds1)/2, 0.5, 'lower') / 2; end; if any(inds2(:)), p(inds2) = betainc(x2(inds2) ./ (v(inds2) + x2(inds2)), 0.5, v(inds2)/2, 'upper') / 2; end; inds = (x > 0); if any(inds) p(inds) = 1 - p(inds); end; inds = (v > 1e7); if any(inds(:)), p(inds) = normcum(x(inds)); end; p(x == 0) = 0.5; if isempty(p) p = ones(size(x)); else p = reshape(p, size(x)); end; function [p] = normcum(z) p = 0.5 * erfc(-z ./ sqrt(2)); % reshape results % --------------- function varargout = reshape_results(nd, varargin) if length(varargin) > 1 for index = 1:length(varargin) varargout{index} = reshape_results(nd, varargin{index}); end; elseif iscell(varargin{1}) for index = 1:length(varargin{1}) varargout{1}{index} = reshape_results(nd, varargin{1}{index}); end; else if ~isempty(varargin{1}) if length(nd) == 1, nd = [ nd 1 ]; end; varargout{1} = reshape(varargin{1}, nd); else varargout{1} = []; end; end;
github
lcnhappe/happe-master
surrogdistrib.m
.m
happe-master/Packages/eeglab14_0_0b/functions/statistics/surrogdistrib.m
5,888
utf_8
18526734957324ab037d603d38a328cf
% surrogdistrib - Build surrogate distribution % % surrog = surrogdistrib(data, varargin); % % Inputs: % data - [cell] data arrays for which to compute a surrogate % distribution. % % Optional inputs: % 'method' - ['bootstrap'|'perm'] use either 'bootstrap' or 'permutation' % method. Bootstrap performs draws with replacement and % permutation performs draws without replacement. Default % is 'perm'. % 'pairing' - ['on'|'off'] pair the data arrays. % 'naccu' - [integer] number of surrogate. Default is 1. % 'precomp' - cell array containing precomputed value for speeding up % mulitple calls % % Output: % surrog - surrogate distribution % precomp - cell array containing precomputed value for speeding up % mulitple calls % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005- % Copyright (C) Arnaud Delorme % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [res precomp ] = surrogdistrib(data, varargin) if nargin < 1 help surrogdistrib, return; end; if ~strcmpi(varargin{1}, 'precomp') opt = finputcheck(varargin, { 'naccu' 'integer' [1 Inf] 1; 'method' 'string' { 'perm','permutation','bootstrap' } 'perm'; 'pairing' 'string' { 'on','off' } 'on'; 'precomp' 'cell' {} {} }, 'surrogdistrib'); if isstr(opt), error(opt); end; if strcmpi(opt.method, 'permutation'), opt.method = 'perm'; end; if strcmpi(opt.method, 'bootstrap'), bootflag = 1; else bootflag = 0; end; if strcmpi(opt.pairing, 'on') pairflag = 1; else pairflag = 0; end; else opt.precomp = varargin{2}; end; % concatenate data % ---------------- if isempty(opt.precomp) [ datavals datalen datadims ] = concatdata( data ); precomp = { datavals datalen datadims bootflag pairflag opt.naccu}; else precomp = opt.precomp; datavals = precomp{1}; datalen = precomp{2}; datadims = precomp{3}; bootflag = precomp{4}; pairflag = precomp{5}; opt.naccu = precomp{6}; end; % compute surrogate distribution % ------------------------------ if opt.naccu > 1 res = supersurrogate( datavals, datalen, datadims, bootflag, pairflag, opt.naccu); else res = surrogate( datavals, datalen, datadims, bootflag, pairflag); end; function res = supersurrogate(dat, lens, dims, bootstrapflag, pairedflag, naccu); % for increased speed only shuffle half the indices % recompute indices in set and target cell indices % ------------------------------------------------ ncond = length(lens)-1; nsubj = lens(2); if bootstrapflag if pairedflag indswap = mod( repmat([1:lens(end)],[naccu 1]) + ceil(rand(naccu,lens(end))*length(lens))*lens(2)-1, lens(end) )+1; else indswap = ceil(rand(naccu,lens(end))*lens(end)); end; else if pairedflag [tmp idx] = sort(rand(naccu,nsubj,ncond),3); indswap = ((idx)-1)*nsubj + repmat( repmat([1:nsubj], [naccu 1 1]),[1 1 ncond]); indswap = reshape(indswap, [naccu lens(end)]); else [tmp indswap] = sort(rand(naccu, lens(end)),2); end; end; for i = 1:length(lens)-1 if myndims(dat) == 1 res{i} = reshape(dat(indswap(:,lens(i)+1:lens(i+1))), naccu, lens(i+1)-lens(i)); else res{i} = reshape(dat(:,indswap(:,lens(i)+1:lens(i+1))), size(dat,1), naccu, lens(i+1)-lens(i)); end; end; res = reshape(res, dims); function res = surrogate(dataconcat, lens, dims, bootstrapflag, pairedflag); % for increased speed only shuffle half the indices % recompute indices in set and target cell indices % ------------------------------------------------ if bootstrapflag if pairedflag indswap = mod( [1:lens(end)]+ ceil(rand(1,lens(end))*length(lens))*lens(2)-1, lens(end) )+1; else indswap = ceil(rand(1,lens(end))*lens(end)); end; else if pairedflag indswap = [1:lens(end)]; indswap = reshape(indswap, [lens(2) length(lens)-1]); for i = 1:size(indswap,1) % shuffle each row [tmp idx] = sort(rand(1,size(indswap,2))); indswap(i,:) = indswap(i,idx); end; indswap = reshape(indswap, [1 lens(2)*(length(lens)-1)]); else oriindices = [1:lens(end)]; % just shuffle indices [tmp idx] = sort(rand(1,length(oriindices))); indswap = oriindices(idx); end; end; res = {}; for i = 1:length(lens)-1 if myndims(dataconcat) == 1 res{i} = dataconcat(indswap(lens(i)+1:lens(i+1))); else res{i} = dataconcat(:,indswap(lens(i)+1:lens(i+1))); end; end; res = reshape(res, dims); function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end;
github
lcnhappe/happe-master
stat_surrogate_pvals.m
.m
happe-master/Packages/eeglab14_0_0b/functions/statistics/stat_surrogate_pvals.m
2,648
utf_8
74534793d4027376c995150218faf240
function pvals = stat_surrogate_pvals(distribution,observed,tail) % compute empirical p-vals under the null hypothesis that observed samples % come from a given surrogate distribution. P-values for Type I error in % rejecting the null hypothesis are obtained by finding the proportion of % samples in the distribution that % (a) are larger than the observed sample (one-sided test) % (b) are larger or smaller than the observed sample (two-sided test). % % This function is based on Arnaud Delorme's statcond:compute_pvals() % function from EEGLAB % % Inputs: % % distribution: [d1 x d2 x ... x dM x N] matrix of surrogate samples. % distribution(i,j,k,...,:) is a collection of N samples % from a surrogate distribution. % observed: [d1 x d2 x ... x dM] matrix of observations. % tail: can be 'one' or 'both' indicating a one-tailed or % two-tailed test % Outputs: % % pvals: [d1 x d2 x ... x dM] matrix of p-values specifying % probability of Type I error in rejecting the null % hypothesis % % Author: Tim Mullen and Arnaud Delorme, SCCN/INC/UCSD % This function is part of the Source Information Flow Toolbox (SIFT) % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 3 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA numDims = myndims(distribution); % append observed to last dimension of surrogate distribution distribution = cat(numDims,distribution,observed); numDims = myndims(distribution); % sort along last dimension (replications) [tmp idx] = sort( distribution, numDims,'ascend'); [tmp mx] = max( idx,[], numDims); len = size(distribution, numDims ); pvals = 1-(mx-0.5)/len; if strcmpi(tail, 'both') pvals = min(pvals, 1-pvals); pvals = 2*pvals; end; % get the number of dimensions in a matrix function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end;
github
lcnhappe/happe-master
anova1rm_cell.m
.m
happe-master/Packages/eeglab14_0_0b/functions/statistics/anova1rm_cell.m
3,731
utf_8
40890df8c96f1a41aca5846c8c9c4883
% anova1rm_cell() - compute F-values in cell array using repeated measure % ANOVA. % % Usage: % >> [FC dfc] = anova2rm_cell( data ); % % Inputs: % data = data consisting of PAIRED arrays to be compared. The last % dimension of the data array is used to compute ANOVA. % Outputs: % FC - F-value for columns % dfc - degree of freedom for columns % % Note: this function is inspired from rm_anova available at % http://www.mathworks.se/matlabcentral/fileexchange/6874-two-way-rep % eated-measures-anova % % Example: % a = { rand(1,10) rand(1,10) rand(1,10) } % [FC dfc] = anova1rm_cell(a) % signifC = 1-fcdf(FC, dfc(1), dfc(2)) % % % for comparison % [F1 F2 FI df1 df2 dfi] = anova1rm_cell(a); % F2 % % c = { rand(200,400,10) rand(200,400,10) }; % [FC dfc] = anova2rm_cell(c) % computes 200x400 ANOVAs % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2010 % Copyright (C) Arnaud Delorme % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [fA dfApair] = anova1rm_cell(data) % compute all means and all std % ----------------------------- a = length(data); nd = myndims( data{1} ); sz = size( data{1} ); n = size( data{1} ,nd); AS = zeros([ sz(1:nd-1) a n ], 'single'); sq = zeros([ sz(1:nd-1) 1], 'single'); % only for paired stats % --------------------- for ind1 = 1:a switch nd case 1, AS(ind1,:) = AS(ind1,:) + reshape(data{ind1},[sz(1:nd-1) 1 n]); case 2, AS(:,ind1,:) = AS(:,ind1,:) + reshape(data{ind1},[sz(1:nd-1) 1 n]); case 3, AS(:,:,ind1,:) = AS(:,:,ind1,:) + reshape(data{ind1},[sz(1:nd-1) 1 n]); case 4, AS(:,:,:,ind1,:) = AS(:,:,:,ind1,:) + reshape(data{ind1},[sz(1:nd-1) 1 n]); case 5, AS(:,:,:,:,ind1,:) = AS(:,:,:,:,ind1,:) + reshape(data{ind1},[sz(1:nd-1) 1 n]); case 6, AS(:,:,:,:,:,ind1,:) = AS(:,:,:,:,:,ind1,:) + reshape(data{ind1},[sz(1:nd-1) 1 n]); case 7, AS(:,:,:,:,:,:,ind1,:) = AS(:,:,:,:,:,:,ind1,:) + reshape(data{ind1},[sz(1:nd-1) 1 n]); otherwise error('Dimension not supported'); end; sq = sq + sum(data{ind1}.^2,nd); end; dimA = nd+1; dimB = nd; A = sum(AS,dimA); % sum across columns, so result is 1xs row vector S = sum(AS,dimB); % sum across columns, so result is 1xs row vector T = sum(sum(S,dimB),dimA); % could sum either A or B or S, choice is arbitrary % degrees of freedom dfA = a-1; dfAS = (a-1)*(n-1); % bracket terms (expected value) expA = sum(A.^2,dimB)./n; expS = sum(S.^2,dimA)./a; expAS = sum(sum(AS.^2,dimB),dimA); expT = T.^2 / (a*n); % sums of squares ssA = expA - expT; ssAS = expAS - expA - expS + expT; % mean squares msA = ssA / dfA; msAS = ssAS / dfAS; % f statistic fA = msA ./ msAS; dfApair = [dfA dfAS]; function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end;
github
lcnhappe/happe-master
teststat.m
.m
happe-master/Packages/eeglab14_0_0b/functions/statistics/teststat.m
20,505
utf_8
8521a1c623a39fbdaded6534e27d6c3c
% teststat - EEGLAB statistical testing function % % Statistics are critical for inference testing in Science. It is thus % primordial to make sure than all the statistics implemented are % robust and at least bug free. Statistical function using complex % formulas are inherently prone to bugs. EEGLAB functions are all the % more prone to bugs given that they only use complex Matlab code to % avoid loops and speed up computation. % % This test function does not garantee that EEGLAB statistical functions % are bug free. It does assure though that bugs are unlikely and minor % if they are present. % % This function test 3 things. % % * First, it checks that for vector inputs the EEGLAB functions return % the same output as other reference functions from the Matlab statistical % toolbox or from other packages tested against the SPSS software for % repeated measure ANOVA (rm_anova2 function). % % * Second, it checks that array inputs with different number of dimensions % (from 1 to 3) the EEGLAB function return the same output. % % * Third, it checks that the permutation and bootstrap methods shuffle % the data properly by running multiple tests. function teststat; % testing paired t-test % --------------------- a = { rand(1,10) rand(1,10)+0.5 }; [t df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on'); [h p tmp stats] = ttest(a{1}, a{2}); fprintf('Statistics paired statcond t-value %2.2f df=%d p=%0.4f\n', t, df, pvals); fprintf('Statistics paired ttest func. t-value %2.2f df=%d p=%0.4f\n', stats.tstat, stats.df, p); assertsame([t stats.tstat], [df stats.df], [pvals p]); disp('--------------------'); % testing unpaired t-test % ----------------------- [t df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off'); [h p tmp stats] = ttest2(a{1}, a{2}); fprintf('Statistics paired statcond t-value %2.2f df=%d p=%0.4f\n', t, df, pvals); fprintf('Statistics paired ttest2 func. t-value %2.2f df=%d p=%0.4f\n', stats.tstat, stats.df, p); assertsame([t stats.tstat], [df stats.df], [pvals p]); disp('--------------------'); % testing paired 1-way ANOVA % -------------------------- a = { rand(1,10) rand(1,10) rand(1,10)+0.2; rand(1,10) rand(1,10)+0.2 rand(1,10) }; [F df pvals surog] = statcond(a(1,:), 'mode', 'param', 'verbose', 'off', 'paired', 'on'); z = zeros(10,1); o = ones(10,1); t = ones(10,1)*2; stats = rm_anova2( [ a{1,1}';a{1,2}';a{1,3}'], repmat([1:10]', [3 1]), [o;o;o], [z;o;t], {'a','b'}); fprintf('Statistics 1-way paired statcond F-value %2.2f df1=%d df2=%d p=%0.4f\n', F, df(1), df(2), pvals); fprintf('Statistics 1-way paired rm_avova2 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{3,5}, stats{3,3}, stats{6,3}, stats{3,6}); assertsame([F stats{3,5}], [df(1) stats{3,3}], [df(2) stats{6,3}], [pvals stats{3,6}]); disp('--------------------'); % testing paired 2-way ANOVA % -------------------------- [F df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on'); z = zeros(10,1); o = ones(10,1); t = ones(10,1)*2; stats = rm_anova2( [ a{1,1}';a{1,2}';a{1,3}';a{2,1}';a{2,2}';a{2,3}' ], ... repmat([1:10]', [6 1]), [o;o;o;z;z;z], [z;o;t;z;o;t], {'a','b'}); fprintf('Statistics 2-way paired statcond F-value %2.2f df1=%d df2=%d p=%0.4f\n', F{3}, df{3}(1), df{3}(2), pvals{3}); fprintf('Statistics 2-way paired rm_avova2 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{4,5}, stats{4,3}, stats{7,3}, stats{4,6}); assertsame([F{3} stats{4,5}], [df{3}(1) stats{4,3}], [df{3}(2) stats{7,3}], [pvals{3} stats{4,6}]); disp('--------------------'); % testing 1-way unpaired ANOVA % ---------------------------- [F df pvals surog] = statcond(a(1,:), 'mode', 'param', 'verbose', 'off', 'paired', 'off'); [p stats] = anova1( [ a{1,1}' a{1,2}' a{1,3}' ],{}, 'off'); fprintf('Statistics 1-way unpaired statcond F-value %2.2f df1=%d df2=%d p=%0.4f\n', F, df(1), df(2), pvals); fprintf('Statistics 1-way unpaired anova1 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{2,5}, stats{2,3}, stats{3,3}, stats{2,6}); assertsame([F stats{2,5}], [df(1) stats{2,3}], [df(2) stats{3,3}], [pvals stats{2,6}]); disp('--------------------'); % testing 2-way unpaired ANOVA % ---------------------------- [F df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off'); [p stats] = anova2( [ a{1,1}' a{1,2}' a{1,3}'; a{2,1}' a{2,2}' a{2,3}' ], 10, 'off'); fprintf('Statistics 2-way paired statcond F-value %2.2f df1=%d df2=%d p=%0.4f\n', F{3}, df{3}(1), df{3}(2), pvals{3}); fprintf('Statistics 1-way unpaired anova2 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{4,5}, stats{4,3}, stats{5,3}, stats{4,6}); assertsame([F{3} stats{4,5}], [df{3}(1) stats{4,3}], [df{3}(2) stats{5,3}], [pvals{3} stats{4,6}]); disp('--------------------'); % testing different dimensions in statcond % ---------------------------------------- a = { rand(1,10) rand(1,10)+0.5 rand(1,10)}; b = { rand(10,10) rand(10,10)+0.5 rand(10,10)}; b{1}(4,:) = a{1}; b{2}(4,:) = a{2}; b{3}(4,:) = a{3}; c = { rand(5,10,10) rand(5,10,10)+0.5 rand(5,10,10)}; c{1}(2,4,:) = a{1}; c{2}(2,4,:) = a{2}; c{3}(2,4,:) = a{3}; d = { rand(2,5,10,10) rand(2,5,10,10)+0.5 rand(2,5,10,10)}; d{1}(1,2,4,:) = a{1}; d{2}(1,2,4,:) = a{2}; d{3}(1,2,4,:) = a{3}; [t1 df1 pvals1] = statcond(a(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on'); [t2 df2 pvals2] = statcond(b(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on'); [t3 df3 pvals3] = statcond(c(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on'); [t4 df4 pvals4] = statcond(d(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on'); fprintf('Statistics paired statcond t-test dim1 t-value %2.2f df=%d p=%0.4f\n', t1, df1, pvals1); fprintf('Statistics paired statcond t-test dim2 t-value %2.2f df=%d p=%0.4f\n', t2(4), df2, pvals2(4)); fprintf('Statistics paired statcond t-test dim3 t-value %2.2f df=%d p=%0.4f\n', t3(2,4), df3, pvals3(2,4)); fprintf('Statistics paired statcond t-test dim4 t-value %2.2f df=%d p=%0.4f\n', t4(1,2,4), df4, pvals4(1,2,4)); assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]); disp('--------------------'); [t1 df1 pvals1] = statcond(a(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off'); [t2 df2 pvals2] = statcond(b(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off'); [t3 df3 pvals3] = statcond(c(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off'); [t4 df4 pvals4] = statcond(d(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off'); fprintf('Statistics unpaired statcond t-test dim1 t-value %2.2f df=%d p=%0.4f\n', t1, df1, pvals1); fprintf('Statistics unpaired statcond t-test dim2 t-value %2.2f df=%d p=%0.4f\n', t2(4), df2, pvals2(4)); fprintf('Statistics unpaired statcond t-test dim3 t-value %2.2f df=%d p=%0.4f\n', t3(2,4), df3, pvals3(2,4)); fprintf('Statistics unpaired statcond t-test dim4 t-value %2.2f df=%d p=%0.4f\n', t4(1,2,4), df4, pvals4(1,2,4)); assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]); disp('--------------------'); [t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on'); [t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'on'); [t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'on'); [t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'on'); fprintf('Statistics paired statcond anova 1-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1, df1(1), df1(2), pvals1); fprintf('Statistics paired statcond anova 1-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2(4), df2(1), df2(2), pvals2(4)); fprintf('Statistics paired statcond anova 1-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3(2,4), df3(1), df3(2), pvals3(2,4)); fprintf('Statistics paired statcond anova 1-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4(1,2,4), df4(1), df4(2), pvals4(1,2,4)); assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]); disp('--------------------'); [t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off'); [t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'off'); [t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'off'); [t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'off'); fprintf('Statistics unpaired statcond anova 1-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1, df1(1), df1(2), pvals1); fprintf('Statistics unpaired statcond anova 1-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2(4), df2(1), df2(2), pvals2(4)); fprintf('Statistics unpaired statcond anova 1-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3(2,4), df3(1), df3(2), pvals3(2,4)); fprintf('Statistics unpaired statcond anova 1-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4(1,2,4), df4(1), df4(2), pvals4(1,2,4)); assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]); disp('--------------------'); a(2,:) = a; a{1} = a{1}/2; b(2,:) = b; b{1} = b{1}/2; c(2,:) = c; c{1} = c{1}/2; d(2,:) = d; d{1} = d{1}/2; [t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on'); [t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'on'); [t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'on'); [t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'on'); fprintf('Statistics paired statcond anova 2-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1{3}, df1{3}(1), df1{3}(2), pvals1{3}); fprintf('Statistics paired statcond anova 2-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2{3}(4), df2{3}(1), df2{3}(2), pvals2{3}(4)); fprintf('Statistics paired statcond anova 2-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3{3}(2,4), df3{3}(1), df3{3}(2), pvals3{3}(2,4)); fprintf('Statistics paired statcond anova 2-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4{3}(1,2,4), df4{3}(1), df4{3}(2), pvals4{3}(1,2,4)); assertsame([t1{3} t2{3}(4) t3{3}(2,4) t4{3}(1,2,4)], [df1{3}(1) df2{3}(1) df3{3}(1) df4{3}(1)], [df1{3}(2) df2{3}(2) df3{3}(2) df4{3}(2)], [pvals1{3} pvals2{3}(4) pvals3{3}(2,4) pvals4{3}(1,2,4)]); disp('--------------------'); [t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off'); [t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'off'); [t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'off'); [t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'off'); fprintf('Statistics unpaired statcond anova 2-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1{3}, df1{3}(1), df1{3}(2), pvals1{3}); fprintf('Statistics unpaired statcond anova 2-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2{3}(4), df2{3}(1), df2{3}(2), pvals2{3}(4)); fprintf('Statistics unpaired statcond anova 2-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3{3}(2,4), df3{3}(1), df3{3}(2), pvals3{3}(2,4)); fprintf('Statistics unpaired statcond anova 2-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4{3}(1,2,4), df4{3}(1), df4{3}(2), pvals4{3}(1,2,4)); assertsame([t1{3} t2{3}(4) t3{3}(2,4) t4{3}(1,2,4)], [df1{3}(1) df2{3}(1) df3{3}(1) df4{3}(1)], [df1{3}(2) df2{3}(2) df3{3}(2) df4{3}(2)], [pvals1{3} pvals2{3}(4) pvals3{3}(2,4) pvals4{3}(1,2,4)]); disp('--------------------'); % testing shuffling and permutation for bootstrap % ----------------------------------------------- clear a; m1 = [1:10]; m2 = [1:10]+100; m3 = [1:10]+1000; a{1} = { m1 m2 }; a{2} = { m1 m2 m3 }; a{3} = { [ zeros(9,10); m1] [ zeros(9,10); m2] }; a{4} = { [ zeros(9,10); m1] [ zeros(9,10); m2] [ zeros(9,10); m3] }; tmpa = zeros(9,8,10); tmpa(end,end,:) = m1; tmpb = zeros(9,8,10); tmpb(end,end,:) = m2; tmpc = zeros(9,8,10); tmpc(end,end,:) = m3; a{5} = { tmpa tmpb }; a{6} = { tmpa tmpb tmpc }; for method = 1:2 if method == 2, opt = {'arraycomp', 'off'}; else opt = {}; end; for dim = 1:length(a) [sa1] = statcond(a{dim}, 'mode', 'bootstrap', 'verbose', 'off', 'paired', 'on', 'returnresamplingarray', 'on', opt{:}, 'naccu', 10); [sa2] = statcond(a{dim}, 'mode', 'perm' , 'verbose', 'off', 'paired', 'on', 'returnresamplingarray', 'on', opt{:}, 'naccu', 10); [sa3] = statcond(a{dim}, 'mode', 'bootstrap', 'verbose', 'off', 'paired', 'off', 'returnresamplingarray', 'on', opt{:}, 'naccu', 10); [sa4] = statcond(a{dim}, 'mode', 'perm' , 'verbose', 'off', 'paired', 'off', 'returnresamplingarray', 'on', opt{:}, 'naccu', 10); % select data nd = ndims(sa1{1}); if nd == 2 && size(sa1{1},2) > 1 for t=1:length(sa1), sa1{t} = sa1{t}(end,:); sa2{t} = sa2{t}(end,:); sa3{t} = sa3{t}(end,:); sa4{t} = sa4{t}(end,:); end; elseif nd == 3 for t=1:length(sa1), sa1{t} = squeeze(sa1{t}(end,end,:)); sa2{t} = squeeze(sa2{t}(end,end,:)); sa3{t} = squeeze(sa3{t}(end,end,:)); sa4{t} = squeeze(sa4{t}(end,end,:)); end; elseif nd == 4 for t=1:length(sa1), sa1{t} = squeeze(sa1{t}(end,end,end,:)); sa2{t} = squeeze(sa2{t}(end,end,end,:)); sa3{t} = squeeze(sa3{t}(end,end,end,:)); sa4{t} = squeeze(sa4{t}(end,end,end,:)); end; end; % for paired bootstrap, we make sure that the resampling has only shuffled between conditions % for instance [101 2 1003 104 ...] is an acceptable sequence if all(rem(sa1{1}(:)',10) == [1:9 0]) && all(rem(sa1{2}(:)',10) == [1:9 0]) fprintf('Bootstrap paired dim%d resampling method %d Pass\n', dim, method); else error('Bootstrap paired resampling Error'); end; % for paired permutation, in addition, we make sure that the sum accross condition is constant % which is not true for bootstrap msa = meansa(sa2); msa = msa(:)-msa(1); if all(rem(sa1{1}(:)',10) == [1:9 0]) && all(rem(sa1{2}(:)',10) == [1:9 0]) && ... all(round(msa) == [0:9]') && length(unique(sa2{1})) == 10 && length(unique(sa2{2})) == 10 fprintf('Permutation paired dim%d resampling method %d Pass\n', dim, method); else error('Permutation paired resampling Error'); end; % for unpaired bootstrap, only make sure there are enough unique % values if length(unique(sa3{1})) > 3 && length(unique(sa3{2})) > 3 fprintf('Bootstrap unpaired dim%d reampling method %d Pass\n', dim, method); else error('Bootstrap unpaired reampling Error'); end; % for unpaired permutation, the number of unique values must be 10 % and the sum must be constant (not true for bootstrap) if length(unique(sa4{1})) == 10 && length(unique(sa4{2})) == 10 && ( floor(mean(meansa(sa4))) == 55 || floor(mean(meansa(sa4))) == 372 ) fprintf('Permutation unpaired dim%d reampling method %d Pass\n', dim, method); else error('Permutation unpaired reampling Error'); end; disp('------------------------'); end; end; % function to check function assertsame(varargin) for ind = 1:length(varargin) if length(varargin{1}) > 2 for tmpi = 1:length(varargin{1})-1 assertsame(varargin{1}(tmpi:tmpi+1)); end; return; else if (varargin{ind}(1)-varargin{ind}(2)) > abs(mean(varargin{ind}))*0.01 error('Test failed'); end; end; end; disp('Test pass'); function [meanmat] = meansa(mat) meanmat = zeros(size(mat{1})); for index = 1:length(mat) meanmat = meanmat+mat{index}/length(mat); end; function stats = rm_anova2(Y,S,F1,F2,FACTNAMES) % % function stats = rm_anova2(Y,S,F1,F2,FACTNAMES) % % Two-factor, within-subject repeated measures ANOVA. % For designs with two within-subject factors. % % Parameters: % Y dependent variable (numeric) in a column vector % S grouping variable for SUBJECT % F1 grouping variable for factor #1 % F2 grouping variable for factor #2 % F1name name (character array) of factor #1 % F2name name (character array) of factor #2 % % Y should be a 1-d column vector with all of your data (numeric). % The grouping variables should also be 1-d numeric, each with same % length as Y. Each entry in each of the grouping vectors indicates the % level # (or subject #) of the corresponding entry in Y. % % Returns: % stats is a cell array with the usual ANOVA table: % Source / ss / df / ms / F / p % % Notes: % Program does not do any input validation, so it is up to you to make % sure that you have passed in the parameters in the correct form: % % Y, S, F1, and F2 must be numeric vectors all of the same length. % % There must be at least one value in Y for each possible combination % of S, F1, and F2 (i.e. there must be at least one measurement per % subject per condition). % % If there is more than one measurement per subject X condition, then % the program will take the mean of those measurements. % % Aaron Schurger (2005.02.04) % Derived from Keppel & Wickens (2004) "Design and Analysis" ch. 18 % % % Revision history... % % 11 December 2009 (Aaron Schurger) % % Fixed error under "bracket terms" % was: expY = sum(Y.^2); % now: expY = sum(sum(sum(MEANS.^2))); % stats = cell(4,5); F1_lvls = unique_bc(F1); F2_lvls = unique_bc(F2); Subjs = unique_bc(S); a = length(F1_lvls); % # of levels in factor 1 b = length(F2_lvls); % # of levels in factor 2 n = length(Subjs); % # of subjects INDS = cell(a,b,n); % this will hold arrays of indices CELLS = cell(a,b,n); % this will hold the data for each subject X condition MEANS = zeros(a,b,n); % this will hold the means for each subj X condition % Calculate means for each subject X condition. % Keep data in CELLS, because in future we may want to allow options for % how to compute the means (e.g. leaving out outliers > 3stdev, etc...). for i=1:a % F1 for j=1:b % F2 for k=1:n % Subjs INDS{i,j,k} = find(F1==F1_lvls(i) & F2==F2_lvls(j) & S==Subjs(k)); CELLS{i,j,k} = Y(INDS{i,j,k}); MEANS(i,j,k) = mean(CELLS{i,j,k}); end end end % make tables (see table 18.1, p. 402) AB = reshape(sum(MEANS,3),a,b); % across subjects AS = reshape(sum(MEANS,2),a,n); % across factor 2 BS = reshape(sum(MEANS,1),b,n); % across factor 1 A = sum(AB,2); % sum across columns, so result is ax1 column vector B = sum(AB,1); % sum across rows, so result is 1xb row vector S = sum(AS,1); % sum across columns, so result is 1xs row vector T = sum(sum(A)); % could sum either A or B or S, choice is arbitrary % degrees of freedom dfA = a-1; dfB = b-1; dfAB = (a-1)*(b-1); dfS = n-1; dfAS = (a-1)*(n-1); dfBS = (b-1)*(n-1); dfABS = (a-1)*(b-1)*(n-1); % bracket terms (expected value) expA = sum(A.^2)./(b*n); expB = sum(B.^2)./(a*n); expAB = sum(sum(AB.^2))./n; expS = sum(S.^2)./(a*b); expAS = sum(sum(AS.^2))./b; expBS = sum(sum(BS.^2))./a; expY = sum(sum(sum(MEANS.^2))); %sum(Y.^2); expT = T^2 / (a*b*n); % sums of squares ssA = expA - expT; ssB = expB - expT; ssAB = expAB - expA - expB + expT; ssS = expS - expT; ssAS = expAS - expA - expS + expT; ssBS = expBS - expB - expS + expT; ssABS = expY - expAB - expAS - expBS + expA + expB + expS - expT; ssTot = expY - expT; % mean squares msA = ssA / dfA; msB = ssB / dfB; msAB = ssAB / dfAB; msS = ssS / dfS; msAS = ssAS / dfAS; msBS = ssBS / dfBS; msABS = ssABS / dfABS; % f statistic fA = msA / msAS; fB = msB / msBS; fAB = msAB / msABS; % p values pA = 1-fcdf(fA,dfA,dfAS); pB = 1-fcdf(fB,dfB,dfBS); pAB = 1-fcdf(fAB,dfAB,dfABS); % return values stats = {'Source','SS','df','MS','F','p';... FACTNAMES{1}, ssA, dfA, msA, fA, pA;... FACTNAMES{2}, ssB, dfB, msB, fB, pB;... [FACTNAMES{1} ' x ' FACTNAMES{2}], ssAB, dfAB, msAB, fAB, pAB;... [FACTNAMES{1} ' x Subj'], ssAS, dfAS, msAS, [], [];... [FACTNAMES{1} ' x Subj'], ssBS, dfBS, msBS, [], [];... [FACTNAMES{1} ' x ' FACTNAMES{2} ' x Subj'], ssABS, dfABS, msABS, [], []}; return
github
lcnhappe/happe-master
ttest2_cell.m
.m
happe-master/Packages/eeglab14_0_0b/functions/statistics/ttest2_cell.m
4,634
utf_8
cb20a27eff3e4cd6eb3c9ae82e863eed
% ttest2_cell() - compute unpaired t-test. Allow fast computation of % multiple t-test using matrix manipulation. % % Usage: % >> [F df] = ttest2_cell( { a b } ); % >> [F df] = ttest2_cell(a, b); % >> [F df] = ttest2_cell(a, b, 'inhomogenous'); % % Inputs: % a,b = data consisting of UNPAIRED arrays to be compared. The last % dimension of the data array is used to compute the t-test. % 'inhomogenous' = use computation for the degree of freedom using % inhomogenous variance. By default the computation of % the degree of freedom is done with homogenous % variances. % % Outputs: % T - T-value % df - degree of freedom (array) % % Example: % a = { rand(1,10) rand(1,10)+0.5 } % [T df] = ttest2_cell(a) % signif = 2*tcdf(-abs(T), df(1)) % % % for comparison, the same using the Matlab t-test function % [h p ci stats] = ttest2(a{1}', a{2}'); % [ stats.tstat' p] % % % fast computation (fMRI scanner volume 100x100x100 and 10 control % % subjects and 12 test subjects). The computation itself takes 0.5 % % seconds instead of half an hour using the standard approach (1000000 % % loops and Matlab t-test function) % a = rand(100,100,100,10); b = rand(100,100,100,10); % [F df] = ttest_cell({ a b }); % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005 % (thank you to G. Rousselet for providing the formula for % inhomogenous variances). % % Reference: % Schaum's outlines in statistics (3rd edition). 1999. Mc Graw-Hill. % Howel, Statistical Methods for Psychology. 2009. Wadsworth Publishing. % Copyright (C) Arnaud Delorme % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [tval, df] = ttest2_cell(a,b,c) % assumes equal variances if nargin < 1 help ttest2_cell; return; end; homogenous = 'homogenous'; if nargin > 1 && isstr(b) homogenous = b; end; if nargin > 2 && isstr(c) homogenous = c; end; if iscell(a), b = a{2}; a = a{1}; end; if ~strcmpi(homogenous, 'inhomogenous') && ~strcmpi(homogenous, 'homogenous') error('Value for homogenous parameter can only be ''homogenous'' or ''inhomogenous'''); end; nd = myndims(a); na = size(a, nd); nb = size(b, nd); meana = mymean(a, nd); meanb = mymean(b, nd); if strcmpi(homogenous, 'inhomogenous') % inhomogenous variance from Howel, 2009, "Statistical Methods for Psychology" % thank you to G. Rousselet for providing these formulas m = meana - meanb; s1 = var(a,0,nd) ./ na; s2 = var(b,0,nd) ./ nb; se = sqrt(s1 + s2); sd = sqrt([s1.*na, s2.*nb]); tval = m ./ se; df = ((s1 + s2).^2) ./ ((s1.^2 ./ (na-1) + s2.^2 ./ (nb-1))); else sda = mystd(a, [], nd); sdb = mystd(b, [], nd); sp = sqrt(((na-1)*sda.^2+(nb-1)*sdb.^2)/(na+nb-2)); tval = (meana-meanb)./sp/sqrt(1/na+1/nb); df = na+nb-2; end; % check values againg Matlab statistics toolbox % [h p ci stats] = ttest2(a', b'); % [ tval stats.tstat' ] function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end; function res = mymean( data, varargin) % deal with complex numbers res = mean( data, varargin{:}); if ~isreal(data) res = abs( res ); end; function res = mystd( data, varargin) % deal with complex numbers if ~isreal(data) res = std( abs(data), varargin{:}); else res = sqrt(sum( bsxfun(@minus, data, mean( data, varargin{2})).^2, varargin{2})/(size(data,varargin{2})-1)); % 8 percent speedup %res = std( data, varargin{:}); end;
github
lcnhappe/happe-master
concatdata.m
.m
happe-master/Packages/eeglab14_0_0b/functions/statistics/concatdata.m
4,076
utf_8
f9b1c761e3ea4846ea5891a0ac56a923
% concatdata - concatenate data stored into a cell array into a single % array. only concatenate along the last dimension % Usage: % [dataarray len dims] = concatata(cellarraydata); % % Input: % cellarraydata - cell array containing data % % Output: % dataarray - single array containing all data % len - limits of each array % dim - dimension of the orginal array % % Example: % a = rand(3, 4, 3, 10); % b = rand(3, 4, 3, 4); % c = rand(3, 4, 3, 3); % [ alldata len ] = concatdata({ a b c}); % % alldata is size [ 3 4 3 17 ] % % len contains [ 0 10 14 17 ] % % to access array number i, type "alldata(len(i)+1:len(i+1)) % % Author: Arnaud Delorme, CERCO/CNRS & SCCN/INC/UCSD, 2009- % Copyright (C) Arnaud Delorme % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [ datac, alllen, dims ] = concatdata(data); alllen = cellfun('size', data, myndims(data{1}) ); % by chance, pick up the last dimension dims = size(data); alllen = [ 0 alllen(:)' ]; switch myndims(data{1}) case 1, datac = zeros(sum(alllen),1, 'single'); for i = 1:prod(dims) alllen(i+1) = alllen(i+1) + alllen(i); datac(alllen(i)+1:alllen(i+1)) = data{i}; end; case 2, datac = zeros(size(data{1},1), sum(alllen), 'single'); for i = 1:prod(dims) alllen(i+1) = alllen(i+1) + alllen(i); datac(:,alllen(i)+1:alllen(i+1)) = data{i}; end; case 3, datac = zeros(size(data{1},1), size(data{1},2), sum(alllen), 'single'); for i = 1:prod(dims) alllen(i+1) = alllen(i+1) + alllen(i); datac(:,:,alllen(i)+1:alllen(i+1)) = data{i}; end; case 4, datac = zeros(size(data{1},1), size(data{1},2), size(data{1},3), sum(alllen), 'single'); for i = 1:prod(dims) alllen(i+1) = alllen(i+1) + alllen(i); datac(:,:,:,alllen(i)+1:alllen(i+1)) = data{i}; end; case 5, datac = zeros(size(data{1},1), size(data{1},2), size(data{1},3), size(data{1},4), sum(alllen), 'single'); for i = 1:prod(dims) alllen(i+1) = alllen(i+1) + alllen(i); datac(:,:,:,:,alllen(i)+1:alllen(i+1)) = data{i}; end; case 6, datac = zeros(size(data{1},1), size(data{1},2), size(data{1},3), size(data{1},4),size(data{1},5), sum(alllen), 'single'); for i = 1:prod(dims) alllen(i+1) = alllen(i+1) + alllen(i); datac(:,:,:,:,:,alllen(i)+1:alllen(i+1)) = data{i}; end; case 7, datac = zeros(size(data{1},1), size(data{1},2), size(data{1},3), size(data{1},4), size(data{1},5), size(data{1},6), sum(alllen), 'single'); for i = 1:prod(dims) alllen(i+1) = alllen(i+1) + alllen(i); datac(:,:,:,:,:,:,alllen(i)+1:alllen(i+1)) = data{i}; end; end; function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end;
github
lcnhappe/happe-master
ttest_cell.m
.m
happe-master/Packages/eeglab14_0_0b/functions/statistics/ttest_cell.m
3,107
utf_8
a669e2ffb5b0d990717a40eda3db4a2f
% ttest_cell() - compute paired t-test. Allow fast computation of % multiple t-test using matrix manipulation. % % Usage: % >> [F df] = ttest_cell( { a b } ); % >> [F df] = ttest_cell(a, b); % % Inputs: % a,b = data consisting of PAIRED arrays to be compared. The last % dimension of the data array is used to compute the t-test. % Outputs: % T - T-value % df - degree of freedom (array) % % Example: % a = { rand(1,10) rand(1,10)+0.5 } % [T df] = ttest_cell(a) % signif = 1-tcdf(T, df(1)) % % % for comparison, the same using the Matlab t-test function % [h p ci stats] = ttest(a{1}', b{1}'); % [ stats.tstat' p] % % % fast computation (fMRI scanner volume 100x100x100 and 10 subjects in % % two conditions). The computation itself takes 0.5 seconds instead of % % half an hour using the standard approach (1000000 loops and Matlab % % t-test function) % a = rand(100,100,100,10); b = rand(100,100,100,10); % [F df] = ttest_cell({ a b }); % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005 % % Reference: % Schaum's outlines in statistics (3rd edition). 1999. Mc Graw-Hill. % Copyright (C) Arnaud Delorme % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [tval, df] = ttest_cell(a,b) if nargin < 1 help ttest_cell; return; end; if iscell(a), b = a{2}; a = a{1}; end; tmpdiff = a-b; diff = mymean(tmpdiff, myndims(a)); sd = mystd( tmpdiff,[], myndims(a)); tval = diff./sd*sqrt(size(a, myndims(a))); df = size(a, myndims(a))-1; % check values againg Matlab statistics toolbox %[h p ci stats] = ttest(a', b'); % [ tval stats.tstat' ] function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end; function res = mymean( data, varargin) % deal with complex numbers res = mean( data, varargin{:}); if ~isreal(data) res = abs( res ); end; function res = mystd( data, varargin) % deal with complex numbers if ~isreal(data) res = std( abs(data), varargin{:}); else res = sqrt(sum( bsxfun(@minus, data, mean( data, varargin{2})).^2, varargin{2})/(size(data,varargin{2})-1)); % 8 percent speedup %res = std( data, varargin{:}); end;
github
lcnhappe/happe-master
statcondfieldtrip.m
.m
happe-master/Packages/eeglab14_0_0b/functions/statistics/statcondfieldtrip.m
15,781
utf_8
796460d89be7fccc4c28be4a80fc7dac
% statcondfiledtrip() - same as statcond except that it uses the fieldtrip % statistical functions. This is useful to perform % a wider variety of corrections for multiple % comparisons for instance. % Usage: % >> [stats, df, pvals, surrog] = statcond( data, 'key','val'... ); % Inputs: % data = same as for statcond() % % Optional inputs: % 'paired' = ['on'|'off'] pair the data array {default: 'on' unless % the last dimension of data array is of different lengths}. % 'method' = ['permutation'|'parametric'] method for computing the p-values: % 'parametric' = parametric testing (standard ANOVA or t-test); % 'permutation' = non-parametric testing using surrogate data % made by permuting the input data. Note that if 'bootstrap' % is given as input, it is interpreted as 'permutation' % Default is 'parametric'. Note that 'parametric' % corresponds to the 'analytic' method of Fieldtrip and % 'permutation' correspond to the 'montecarlo' method. % 'naccu' = this input is passed on as 'numrandomization' to Fieldtrip % 'neighbours' = Fieldtrip channel neighbour structure to perfom statistics % and cluster correction for multiple comparisons accross % channels. % 'alpha' = [float] p-value threshold value. Allow returning % confidence intervals and mask (requires structoutput below). % 'structoutput' = ['on'|'off'] return an output structure instead of % the regular output. Allow to output mask and confidence % intervals. % % Fieldtrip options: % Any option to the freqanalysis, the statistics_montecarlo, the % statistics_analysis, statistics_stat, statistics_glm may be used % using 'key', val argument pairs. % % Outputs: % stats = F- or T-value array of the same size as input data without % the last dimension. A T value is returned only when the data % includes exactly two conditions. % df = degrees of freedom, a (2,1) vector, when F-values are returned % pvals = array of p-values. Same size as input data without the last % data dimension. All returned p-values are two-tailed. % surrog = surrogate data array (same size as input data with the last % dimension filled with a number ('naccu') of surrogate data sets. % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005- % With thanks to Robert Oostenveld for fruitful discussions % and advice on this function. % % See also: freqanalysis(), statistics_montecarlol() % Copyright (C) Arnaud Delorme % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [ ori_vals, df, pvals ] = statcondfieldtrip( data, varargin ); if nargin < 1 help statcondfieldtrip; return; end; [g cfgparams] = finputcheck( varargin, { 'naccu' '' [] []; 'method' 'string' { } 'param'; 'mode' 'string' { } ''; % deprecated (old method) 'chanlocs' 'struct' { } struct([]); 'chandim' 'integer' [] 0; 'alpha' 'real' [] NaN; 'neighbours' 'struct' { } struct([]); 'structoutput' 'string' { 'on','off' } 'off'; % 'method' 'string' { } 'analytic'; % 'montecarlo','analytic','stat','glm' 'paired' 'string' { 'on','off' } 'on' }, 'statcond', 'ignore'); if isstr(g), error(g); end; if ~isempty(g.mode), g.method = g.mode; end; if strcmpi(g.method, 'parametric'), g.method = 'param'; end; if strcmpi(g.method, 'permutation'), g.method = 'montecarlo'; end; if ~isempty(g.neighbours) && isempty(g.chanlocs) g.chanlocs = struct('labels', { g.neighbours(:).label }); end; if size(data,2) == 1, data = transpose(data); end; % cell array transpose alphaset = fastif(isnan(g.alpha) || isempty(g.alpha), 0, 1); % remove first dimension for all input if necessary % necessary for scalp topographies which are given as 1 x nelec x subj % ------------------------------------------------- ndim = size(data{1}); if size(data{1},1) == 1 for index = 1:length(data(:)) data{index} = squeeze(data{index}); end; end; tmpsize = size(data{1}); % find the channel dimension if any % --------------------------------- if ~isempty(g.neighbours) && g.chandim == 0 for index = 1:ndims(data{1}) if size(data{1},index) == length(g.neighbours); if g.chandim == 0 g.chandim = index; else error('Multiple possibilities for the channel dimension, please specify manually'); end; end; end; end; % cfg configuration for Fieldtrip % ------------------------------- cfg = struct(cfgparams{:}); cfg.method = g.method; if strcmpi(g.method, 'param') || strcmpi(g.method, 'parametric') cfg.method = 'analytic'; elseif strcmpi(g.method, 'perm') && strcmpi(g.method, 'permutation') || strcmpi(g.method, 'bootstrap') cfg.method = 'montecarlo'; end; if ~isempty(g.neighbours) cfg.neighbours = g.neighbours; end; if isfield(cfg, 'mcorrect') if strcmpi(cfg.mcorrect, 'none') cfg.mcorrect = 'no'; end; cfg.correctm = cfg.mcorrect; else cfg.mcorrect = []; end; cfg.feedback = 'no'; cfg.ivar = 1; cfg.alpha = fastif(alphaset, g.alpha, 0.05); cfg.numrandomization = g.naccu; % test if data can be paired % -------------------------- if length(unique(cellfun('size', data, ndims(data{1}) ))) > 1 g.paired = 'off'; end; fprintf('%d x %d, ', size(data,1), size(data,2)); if strcmpi(g.paired, 'on') fprintf('paired data, '); else fprintf('unpaired data, '); end; if size(data,1) == 1 & size(data,2) == 2 fprintf('computing T values\n'); else fprintf('computing F values\n'); end; % set randomizations % ------------------ if strcmpi(cfg.method, 'montecarlo') && isempty(cfg.numrandomization) cfg.numrandomization = 200; if ~strcmpi(cfg.mcorrect, 'no'), cfg.numrandomization = cfg.numrandomization*20; end; end; cfg.correcttail = 'alpha'; if size(data,1) == 1, % only one row if size(data,2) == 2 & strcmpi(g.paired, 'on') % paired t-test (very fast) % ------------- cfg.statistic = 'depsamplesT'; [newdata design1 design2 design3] = makefieldtripdata(data, g.chandim, g.chanlocs); cfg.design = [ design1; design3 ]; cfg.uvar = 2; stat = ft_freqstatistics(cfg, newdata{:}); if isfield(stat, 'df') df = stat.df; else df = []; end; elseif size(data,2) == 2 & strcmpi(g.paired, 'off') % paired t-test (very fast) % ------------- cfg.statistic = 'indepsamplesT'; [newdata design1] = makefieldtripdata(data, g.chandim, g.chanlocs); cfg.design = design1; stat = ft_freqstatistics(cfg, newdata{:}); if isfield(stat, 'df') df = stat.df; else df = []; end; elseif strcmpi(g.paired, 'on') % one-way ANOVA (paired) this is equivalent to unpaired t-test % ------------- cfg.tail = 1; cfg.correcttail = 'no'; tmpP = fileparts(which('ft_freqstatistics')); if exist(fullfile(tmpP, 'statfun', 'ft_statfun_depsamplesFmultivariate.m')) cfg.statistic = 'depsamplesFunivariate'; else cfg.statistic = 'depsamplesF'; end; [newdata design1 design2 design3] = makefieldtripdata(data, g.chandim, g.chanlocs); cfg.design = [ design1; design3 ]; cfg.uvar = 2; stat = ft_freqstatistics(cfg, newdata{:}); if isfield(stat, 'dfnum') df = [stat.dfnum stat.dfdenom]; else df = []; end; else % one-way ANOVA (unpaired) % ------------- cfg.tail = 1; cfg.correcttail = 'no'; cfg.statistic = 'indepsamplesF'; [newdata design1] = makefieldtripdata(data, g.chandim, g.chanlocs); cfg.design = [ design1 ]; warning off; stat = ft_freqstatistics(cfg, newdata{:}); warning on; if isfield(stat, 'dfnum') df = [stat.dfnum stat.dfdenom]; else df = []; end; end; else if strcmpi(g.paired, 'on') % two-way ANOVA (paired) % ------------- cfg.tail = 1; cfg.correcttail = 'no'; cfg.statistic = 'depsamplesFmultivariate'; [newdata design1 design2 design3] = makefieldtripdata(data, g.chandim, g.chanlocs); cfg.design = [ design1; design2; design3 ]; cfg.ivar = [1 2]; cfg.uvar = 3; stat = ft_freqstatistics(cfg, newdata{:}); ori_vals = stat.stat; if isfield(stat, 'df') df = stat.df; else df = []; end; else % two-way ANOVA (unpaired) % ------------- cfg.tail = 1; cfg.correcttail = 'no'; cfg.statistic = 'indepsamplesF'; cfg.clustercritval = 4.5416; % 95 percentile of n =10000; a = { rand(n,10) rand(n,10); rand(n,10) rand(n,10) }; [F df p ] = statcondfieldtrip(a, 'paired', 'off'); [newdata design1 design2] = makefieldtripdata(data, g.chandim, g.chanlocs); if ~isempty(g.chanlocs) for index = 1:length(newdata) newdata{index}.powspctrm = squeeze(newdata{index}.powspctrm); newdata{index}.label = { g.chanlocs.labels }; newdata{index}.freq = 1; end; end; cfg newdata{1} cfg.design = [ design1; design2 ]; cfg.effect = 'X1*X2'; cfg.ivar = [1 2]; stat = ft_freqstatistics(cfg, newdata{:}); ori_vals = stat.stat; df = stat.df; end; end; ori_vals = stat.stat; pvals = stat.prob; if size(ori_vals,1) ~= size(data{1},1) && size(ori_vals,1) == 1 ori_vals = reshape(ori_vals, size(ori_vals,2), size(ori_vals,3), size(ori_vals,4)); pvals = reshape(pvals , size(pvals ,2), size(pvals ,3), size(pvals ,4)); if isfield(stat, 'mask') stat.mask = reshape(stat.mask , size(stat.mask ,2), size(stat.mask ,3), size(stat.mask ,4)); end; end; if strcmpi(g.structoutput, 'on') outputstruct.mask = stat.mask; outputstruct.pval = pvals; if length(data(:)) == 2 outputstruct.t = ori_vals; else outputstruct.f = ori_vals; end; outputstruct.stat = ori_vals; % outputstruct.method = g.method; % outputstruct.pval = pvals; % outputstruct.df = df; % outputstruct.surrog = surrogval; % if length(data(:)) == 2 % outputstruct.t = ori_vals; % else outputstruct.f = ori_vals; % end; ori_vals = outputstruct; end; function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end; function [newdata, design1, design2, design3] = makefieldtripdata(data, chandim, chanlocs); newdata = {}; swapdim = []; for i = 1:length(data(:)) newdata{i}.dimord = 'rpt_chan_freq_time'; switch myndims(data{1}) case 1, newdata{i}.powspctrm = data{i}; case 2, if chandim newdata{i}.powspctrm = transpose(data{i}); else newdata{i}.powspctrm = reshape(transpose(data{i}), size(data{i},2), 1, size(data{i},1)); end; case 3, if chandim == 2 % chandim can be 1 or 2 swapdim = [2 1]; end; if chandim newdata{i}.powspctrm = permute(data{i}, [3 1 2]); else newdata{i}.powspctrm = permute(data{i}, [3 4 1 2]); % 4 is a singleton dimension end; case 4, newdata{i}.powspctrm = permute(data{i}, [4 3 1 2 ]); % Fixed dimension from [4 1 2 3] end; newdata{i}.label = cell(1,size(newdata{i}.powspctrm,2)); newdata{i}.label(:) = { 'cz' }; for ic = 1:length(newdata{i}.label) newdata{i}.label{ic} = [ 'c' num2str(ic) ]; end; newdata{i}.freq = [1:size(newdata{i}.powspctrm,3)]; newdata{i}.time = [1:size(newdata{i}.powspctrm,4)]; % below in case channels are specified % not that statistics are done on time x frequencies or channels % so time x frequency x channels do not work yet here if ~isempty(chanlocs) newdata{i}.powspctrm = squeeze(newdata{i}.powspctrm); newdata{i}.label = { chanlocs.labels }; newdata{i}.freq = 1; newdata{i}.time = 1; end; if isempty(chanlocs) && size(newdata{i}.powspctrm,2) ~= 1 newdata{i}.dimord = 'rpt_freq_time'; end; end; design1 = []; design2 = []; design3 = []; for i = 1:size(data,2) for j = 1:size(data,1) nrepeat = size(data{i}, ndims(data{i})); ij = j+(i-1)*size(data,1); design1 = [ design1 ones(1, nrepeat)*i ]; design2 = [ design2 ones(1, nrepeat)*j ]; design3 = [ design3 [1:nrepeat] ]; end; end;
github
lcnhappe/happe-master
corrcoef_cell.m
.m
happe-master/Packages/eeglab14_0_0b/functions/statistics/corrcoef_cell.m
3,242
utf_8
0c78b817804b92c20e7a7a7b084134ab
% corrcoef_cell() - compute pairwise correlations using arrays and % cell array inputs. % % Usage: % >> c = corrcoef_cell( data ); % >> c = corrcoef_cell( data ); % % Inputs: % data - [cell array] data consisting of PAIRED arrays to be compared. % The last dimension of embeded data arrays is used to compute % correlation (see examples). % Outputs: % c - Correlation values. Same size as data without the last dimension. % % Note: the main advantage over the corrcoef Matlab function is the % capacity to compute millions of pairwise correlations per second. % % Example: % a = { rand(1,10) rand(1,10) }; % c1 = corrcoef_cell(a); % c2 = corrcoef(a{1}, a{2}); % % in this case, c1 is equal to c2(2) % % a = { rand(200,300,100) rand(200,300,100) }; % c = corrcoef_cell(a); % % the call above would require 200 x 300 calls to the corrcoef function % % and be about 1000 times slower % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2010 % Copyright (C) Arnaud Delorme % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function c = corrcoef_cell(a,b); if nargin < 1 help corrcoef_cell; return; end; if nargin < 2 b = a{2}; a = a{1}; end; nd = myndims(a); if nd == 1 aa = a-mean(a); bb = b-mean(b); cv = aa'*bb/(10-1); cva = aa'*aa/(10-1); cvb = bb'*bb/(10-1); c = cv/sqrt(cva*cvb); elseif nd == 2 % ND=2, 3, and 4 could be replaced with a single line aa = bsxfun(@minus, a, mean(a,2)); bb = bsxfun(@minus, b, mean(b,2)); %aa = a-repmat(mean(a,2),[1 size(a,2)]); %bb = b-repmat(mean(b,2),[1 size(a,2)]); cv = sum(aa.*bb,2); cva = sum(aa.*aa,2); cvb = sum(bb.*bb,2); c = cv./sqrt(cva.*cvb); elseif nd == 3 aa = bsxfun(@minus, a, mean(a,3)); bb = bsxfun(@minus, b, mean(b,3)); %aa = a-repmat(mean(a,3),[1 1 size(a,3)]); %bb = b-repmat(mean(b,3),[1 1 size(a,3)]); cv = sum(aa.*bb,3); cva = sum(aa.*aa,3); cvb = sum(bb.*bb,3); c = cv./sqrt(cva.*cvb); elseif nd == 4 aa = bsxfun(@minus, a, mean(a,4)); bb = bsxfun(@minus, b, mean(b,4)); %aa = a-repmat(mean(a,4),[1 1 1 size(a,4)]); %bb = b-repmat(mean(b,4),[1 1 1 size(a,4)]); cv = sum(aa.*bb,4); cva = sum(aa.*aa,4); cvb = sum(bb.*bb,4); c = cv./sqrt(cva.*cvb); end; function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end;
github
lcnhappe/happe-master
stat_surrogate_ci.m
.m
happe-master/Packages/eeglab14_0_0b/functions/statistics/stat_surrogate_ci.m
3,125
utf_8
cd001b0625997e12a9b2e0bd2accbfe5
% compute empirical p-vals under the null hypothesis that observed samples % come from a given surrogate distribution. P-values for Type I error in % rejecting the null hypothesis are obtained by finding the proportion of % samples in the distribution that % (a) are larger than the observed sample (one-sided test) % (b) are larger or smaller than the observed sample (two-sided test). % % Inputs: % distribution: [d1 x d2 x ... x dM x N] matrix of surrogate samples. % distribution(i,j,k,...,:) is a collection of N samples % from a surrogate distribution. % alpha: [float] alpha value. Default % tail: can be 'one' or 'both' indicating a one-tailed or % two-tailed test. Can also be 'lower' or 'upper'. % Outputs: % % ci: [2 x d1 x d2 x ... x dM] matrix of confidence interval % % Author: Tim Mullen and Arnaud Delorme, SCCN/INC/UCSD % This function is part of the Source Information Flow Toolbox (SIFT) % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 3 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function ci = stat_surrogate_ci(distribution,alpha,tail) if nargin<3 tail = 'both'; end if nargin<2 alpha = 0.05; end % reshape matrix % -------------- nd = size(distribution); if length(nd) == 2 && nd(2) == 1, nd(2) = []; end; ndori = nd; nd = nd(1:end-1); if isempty(nd), nd = 1; end; distribution = reshape(distribution, [prod(nd) size(distribution,myndims(distribution))]); % append observed to last dimension of surrogate distribution numDims = myndims(distribution); % number of samples N = size(distribution, numDims); % sort along last dimension (replications) [tmpsort idx] = sort( distribution, numDims,'ascend'); if strcmpi(tail, 'both'), alpha = alpha/2; end; low = round(alpha*N); high = N-low; switch lower(tail) case 'upper' cilow = mean(tmpsort, numDims); cihigh = tmpsort(:,high); case 'lower' cilow = tmpsort(:,low+1); cihigh = mean(tmpsort, numDims); case { 'both' 'one' } cilow = tmpsort(:,low+1); cihigh = tmpsort(:,high); otherwise error('Unknown tail option'); end ci = reshape(cilow, [1 size(cilow)]); ci(2,:) = cihigh; ci = reshape(ci, [2 ndori(1:end-1) 1]); % get the number of dimensions in a matrix function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end;
github
lcnhappe/happe-master
anova1_cell.m
.m
happe-master/Packages/eeglab14_0_0b/functions/statistics/anova1_cell.m
4,428
utf_8
60e8465ee6822f93b4e4d4bcad190d42
% anova1_cell() - compute F-values in cell array using ANOVA. % % Usage: % >> [F df] = anova1_cell( data ); % % Inputs: % data = data consisting of PAIRED arrays to be compared. The last % dimension of the data array is used to compute ANOVA. % Outputs: % F - F-value % df - degree of freedom (array) % % Note: the advantage over the ANOVA1 function of Matlab statistical % toolbox is that this function works on arrays (see examples). Note % also that you still need the statistical toolbox to assess % significance using the fcdf() function. The other advantage is that % this function will work with complex numbers. % % Example: % a = { rand(1,10) rand(1,10) rand(1,10) } % [F df] = anova1_cell(a) % signif = 1-fcdf(F, df(1), df(2)) % % % for comparison % anova1( [ a{1,1}' a{1,2}' a{1,3}' ]) % look in the graph for the F value % % b = { [ a{1,1}; a{1,1} ] [ a{1,2}; a{1,2} ] [ a{1,3}; a{1,3} ] } % [F df] = anova1_cell(b) % % c{1,1} = reshape(repmat(b{1,1}, [2 1]),2,2,10); % c{1,2} = reshape(repmat(b{1,2}, [2 1]),2,2,10); % c{1,3} = reshape(repmat(b{1,3}, [2 1]),2,2,10); % [F df] = anova1_cell(c) % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005 % % Reference: % Schaum's outlines in statistics (3rd edition). 1999. Mc Graw-Hill. % Copyright (C) Arnaud Delorme % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [F, df] = anova1_cell(data) % This function does not return % correct values (see bug 336) % It should be fixed with Schaum's outlines p363 % but requires some work. It now calls % anova2_cell which returns correct values warning off; [ F tmp tmp2 df] = anova2_cell(data); warning on; return; % compute all means and all std % ----------------------------- nd = myndims( data{1} ); if nd == 1 for i = 1:length(data) n( i) = length(data{i}); m( i) = mymean( data{i}); sd(i) = mystd( data{i}); end; nt = sum(n); n = n'; m = m'; sd = sd'; elseif nd == 2 for i = 1:length(data) n( :,i) = ones(size(data{i},1) * size(data{i},2), 'single'); m( :,i) = mymean( data{i},2); sd(:,i) = mystd( data{i},[],2); end; nt = sum(n(1,:)); elseif nd == 3 for i = 1:length(data) n( :,:,i) = ones(size(data{i},1),size(data{i},2) * size(data{i},3), 'single'); m( :,:,i) = mymean( data{i},3); sd(:,:,i) = mystd( data{i},[],3); end; nt = sum(n(1,1,:)); elseif nd == 4 for i = 1:length(data) n( :,:,:,i) = ones(size(data{i},1),size(data{i},2), size(data{i},3) * size(data{i},4), 'single'); m( :,:,:,i) = mymean( data{i},4); sd(:,:,:,i) = mystd( data{i},[],4); end; nt = sum(n(1,1,1,:)); end; mt = mean(m,nd); ng = length(data); % number of conditions VinterG = ( sum( n.*(m.^2), nd ) - nt*mt.^2 )/(ng-1); VwithinG = sum( (n-1).*(sd.^2), nd )/(nt-ng); F = VinterG./VwithinG; df = [ ng-1 ng*(size(data{1},nd)-1) ]; function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end; function res = mymean( data, varargin) % deal with complex numbers res = mean( data, varargin{:}); if ~isreal(data) res = abs( res ); end; function res = mystd( data, varargin) % deal with complex numbers res = std( abs(data), varargin{:});
github
lcnhappe/happe-master
fdr.m
.m
happe-master/Packages/eeglab14_0_0b/functions/statistics/fdr.m
2,273
utf_8
0339630d5b76067fde504d464d26a9bf
% fdr() - compute false detection rate mask % % Usage: % >> [p_fdr, p_masked] = fdr( pvals, alpha); % % Inputs: % pvals - vector or array of p-values % alpha - threshold value (non-corrected). If no alpha is given % each p-value is used as its own alpha and FDR corrected % array is returned. % fdrtype - ['parametric'|'nonParametric'] FDR type. Default is % 'parametric'. % % Outputs: % p_fdr - pvalue used for threshold (based on independence % or positive dependence of measurements) % p_masked - p-value thresholded. Same size as pvals. % % Author: Arnaud Delorme, SCCN, 2008- % Based on a function by Tom Nichols % % Reference: Bejamini & Yekutieli (2001) The Annals of Statistics % Copyright (C) 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [pID, p_masked] = fdr(pvals, q, fdrType); if nargin < 3, fdrType = 'parametric'; end; if isempty(pvals), pID = []; return; end; p = sort(pvals(:)); V = length(p); I = (1:V)'; cVID = 1; cVN = sum(1./(1:V)); if nargin < 2 pID = ones(size(pvals)); thresholds = exp(linspace(log(0.1),log(0.000001), 100)); for index = 1:length(thresholds) [tmp p_masked] = fdr(pvals, thresholds(index)); pID(p_masked) = thresholds(index); end; else if strcmpi(fdrType, 'parametric') pID = p(max(find(p<=I/V*q/cVID))); % standard FDR else pID = p(max(find(p<=I/V*q/cVN))); % non-parametric FDR end; end; if isempty(pID), pID = 0; end; if nargout > 1 p_masked = pvals<=pID; end;
github
lcnhappe/happe-master
anova2_cell.m
.m
happe-master/Packages/eeglab14_0_0b/functions/statistics/anova2_cell.m
8,530
utf_8
3f58b154b60557add57c3652a63d8b62
% anova2_cell() - compute F-values in cell array using ANOVA. % % Usage: % >> [FC FR FI dfc dfr dfi] = anova2_cell( data ); % % Inputs: % data = data consisting of PAIRED arrays to be compared. The last % dimension of the data array is used to compute ANOVA. % Outputs: % FC - F-value for columns. % FR - F-value for rows. % FI - F-value for interaction. % dfc - degree of freedom for columns. % dfr - degree of freedom for rows. % dfi - degree of freedom for interaction. % % Note: the advantage over the ANOVA2 function of Matlab statistical % toolbox is that this function works on arrays (see examples). Note % also that you still need the statistical toolbox to assess % significance using the fcdf() function. The other advantage is that % this function will work with complex numbers. % % Example: % a = { rand(1,10) rand(1,10) rand(1,10); rand(1,10) rand(1,10) rand(1,10) } % [FC FR FI dfc dfr dfi] = anova2_cell(a) % signifC = 1-fcdf(FC, dfc(1), dfc(2)) % signifR = 1-fcdf(FR, dfr(1), dfr(2)) % signifI = 1-fcdf(FI, dfi(1), dfi(2)) % % % for comparison % anova2( [ a{1,1}' a{1,2}' a{1,3}'; a{2,1}' a{2,2}' a{2,3}' ], 10) % % b = { [ a{1,1}; a{1,1} ] [ a{1,2}; a{1,2} ] [ a{1,3}; a{1,3} ]; % [ a{2,1}; a{2,1} ] [ a{2,2}; a{2,2} ] [ a{2,3}; a{2,3} ] } % [FC FR FI dfc dfr dfi] = anova2_cell(b) % % c{1,1} = reshape(repmat(b{1,1}, [2 1]),2,2,10); % c{1,2} = reshape(repmat(b{1,2}, [2 1]),2,2,10); % c{1,3} = reshape(repmat(b{1,3}, [2 1]),2,2,10); % c{2,3} = reshape(repmat(b{2,3}, [2 1]),2,2,10); % c{2,2} = reshape(repmat(b{2,2}, [2 1]),2,2,10); % c{2,1} = reshape(repmat(b{2,1}, [2 1]),2,2,10) % [FC FR FI dfc dfr dfi] = anova2_cell(c) % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005 % % Reference: % Schaum's outlines in statistics (3rd edition). 1999. Mc Graw-Hill. % Copyright (C) Arnaud Delorme % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [FC, FR, FI, freeC, freeR, freeI] = anova2_cell(data) % compute all means and all std % ----------------------------- a = size(data,1); b = size(data,2); nd = myndims( data{1} ); c = size(data{1}, nd); sz = size(data{1}); % dataabs if for complex data only % -------------------------------- dataabs = data; if ~isreal(data{1}) for i = 1:a for ii = 1:b dataabs{i,ii} = abs(data{i,ii}); end; end; end; VE = zeros( [ sz(1:end-1) 1], 'single' ); m = zeros( [ sz(1:end-1) size(data) ], 'single' ); for i = 1:a for ii = 1:b tmpm = mymean(data{i,ii}, nd); switch nd case 1, m(i,ii) = tmpm; case 2, m(:,i,ii) = tmpm; case 3, m(:,:,i,ii) = tmpm; case 4, m(:,:,:,i,ii) = tmpm; case 5, m(:,:,:,:,i,ii) = tmpm; case 6, m(:,:,:,:,:,i,ii) = tmpm; case 7, m(:,:,:,:,:,:,i,ii) = tmpm; otherwise error('Dimension not supported'); end; VE = VE+sum( bsxfun(@minus, dataabs{i,ii}, tmpm).^2, nd); end; end; X = mean(mean(m,nd+1),nd); Xj = mean(m,nd+1); Xk = mean(m,nd); VR = b*c*sum( bsxfun(@minus, Xj, X).^2, nd); VC = a*c*sum( bsxfun(@minus, Xk, X).^2, nd+1 ); VI = c*sum( sum( bsxfun(@plus, bsxfun(@minus, bsxfun(@minus, m, Xj), Xk), X).^2, nd+1 ), nd ); % before bsxfun % VR = b*c*sum( (Xj-repmat(X, [ones(1,nd-1) size(Xj,nd )])).^2, nd ); % VC = a*c*sum( (Xk-repmat(X, [ones(1,nd ) size(Xk,nd+1)])).^2, nd+1 ); % % Xj = repmat(Xj, [ones(1,nd) size(m,nd+1) ]); % Xk = repmat(Xk, [ones(1,nd-1) size(m,nd) 1]); % VI = c*sum( sum( ( m - Xj - Xk + repmat(X, [ones(1,nd-1) size(m,nd) size(m,nd+1)]) ).^2, nd+1 ), nd ); % if nd == 1 % % VE = 0; % m = zeros( size(data), 'single' ); % for i = 1:a % for ii = 1:b % m(i,ii) = mymean(data{i,ii}); % VE = VE+sum( (dataabs{i,ii}-m(i,ii)).^2 ); % end; % end; % X = mean(mean(m)); % Xj = mean(m,2); % Xk = mean(m,1); % VR = b*c*sum( (Xj-X).^2 ); % VC = a*c*sum( (Xk-X).^2 ); % % Xj = repmat(Xj, [1 size(m,2) ]); % Xk = repmat(Xk, [size(m,1) 1]); % VI = c*sum( sum( ( m - Xj - Xk + X ).^2 ) ); % % elseif nd == 2 % % VE = zeros( size(data{1},1),1, 'single'); % m = zeros( [ size(data{1},1) size(data) ], 'single' ); % for i = 1:a % for ii = 1:b % tmpm = mymean(data{i,ii}, 2); % m(:,i,ii) = tmpm; % VE = VE+sum( (dataabs{i,ii}-repmat(tmpm, [1 size(data{i,ii},2)])).^2, 2); % end; % end; % X = mean(mean(m,3),2); % Xj = mean(m,3); % Xk = mean(m,2); % VR = b*c*sum( (Xj-repmat(X, [1 size(Xj,2)])).^2, 2 ); % VC = a*c*sum( (Xk-repmat(X, [1 1 size(Xk,3)])).^2, 3 ); % % Xj = repmat(Xj, [1 1 size(m,3) ]); % Xk = repmat(Xk, [1 size(m,2) 1]); % VI = c*sum( sum( ( m - Xj - Xk + repmat(X, [1 size(m,2) size(m,3)]) ).^2, 3), 2 ); % % elseif nd == 3 % % VE = zeros( size(data{1},1), size(data{1},2), 'single' ); % m = zeros( [ size(data{1},1) size(data{1},2) size(data) ], 'single' ); % for i = 1:a % for ii = 1:b % tmpm = mymean(data{i,ii}, 3); % m(:,:,i,ii) = tmpm; % VE = VE+sum( (dataabs{i,ii}-repmat(tmpm, [1 1 size(data{i,ii},3)])).^2, 3); % end; % end; % X = mean(mean(m,4),3); % Xj = mean(m,4); % Xk = mean(m,3); % VR = b*c*sum( (Xj-repmat(X, [1 1 size(Xj,3) ])).^2, 3 ); % VC = a*c*sum( (Xk-repmat(X, [1 1 1 size(Xk,4)])).^2, 4 ); % % Xj = repmat(Xj, [1 1 1 size(m,4) ]); % Xk = repmat(Xk, [1 1 size(m,3) 1]); % VI = c*sum( sum( ( m - Xj - Xk + repmat(X, [1 1 size(m,3) size(m,4)]) ).^2, 4 ), 3 ); % % else % nd == 4 % % VE = zeros( size(data{1},1), size(data{1},2), size(data{1},3), 'single' ); % m = zeros( [ size(data{1},1) size(data{1},2) size(data{1},3) size(data) ], 'single' ); % for i = 1:a % for ii = 1:b % tmpm = mymean(data{i,ii}, 4); % m(:,:,:,i,ii) = tmpm; % VE = VE+sum( (dataabs{i,ii}-repmat(tmpm, [1 1 1 size(data{i,ii},4)])).^2, 4); % end; % end; % X = mean(mean(m,5),4); % Xj = mean(m,5); % Xk = mean(m,4); % VR = b*c*sum( (Xj-repmat(X, [1 1 1 size(Xj,4) ])).^2, 4 ); % VC = a*c*sum( (Xk-repmat(X, [1 1 1 1 size(Xk,5)])).^2, 5 ); % % Xj = repmat(Xj, [1 1 1 1 size(m,5) ]); % Xk = repmat(Xk, [1 1 1 size(m,4) 1]); % VI = c*sum( sum( ( m - Xj - Xk + repmat(X, [1 1 1 size(m,4) size(m,5)]) ).^2, 5 ), 4 ); % % end; SR2 = VR/(a-1); SC2 = VC/(b-1); SI2 = VI/(a-1)/(b-1); SE2 = VE/(a*b*(c-1)); FR = SR2./SE2; % rows FC = SC2./SE2; % columns FI = SI2./SE2; % interaction freeR = [ a-1 a*b*(c-1) ]; freeC = [ b-1 a*b*(c-1) ]; freeI = [ (a-1)*(b-1) a*b*(c-1) ]; function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end; function res = mymean( data, varargin) % deal with complex numbers res = mean( data, varargin{:}); if ~isreal(data) res = abs( res ); end;
github
lcnhappe/happe-master
pop_expica.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_expica.m
2,190
utf_8
de6256134d052dc2d501f1da80a85a5a
% pop_expica() - export ICA weights or inverse matrix % % Usage: % >> pop_expica( EEG, whichica); % a window pops up % >> pop_expica( EEG, whichica, filename ); % % Inputs: % EEG - EEGLAB dataset % whichica - ['weights'|'inv'] export ica 'weights' or ica inverse % matrix ('inv'). Note: for 'weights', the function % export the product of the sphere and weights matrix. % filename - text file name % % Author: Arnaud Delorme, CNL / Salk Institute, Mai 14, 2003 % % See also: pop_export() % Copyright (C) Mai 14, 2003, Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function com = pop_expica(EEG, whichica, filename); com = ''; if nargin < 1 help pop_expica; return; end; if nargin < 2 whichica = 'weights'; end; switch lower(whichica) case {'weights' 'inv'}, ; otherwise error('Unrecognized option for ''whichica'' parameter'); end; if nargin < 3 % ask user [filename, filepath] = uiputfile('*.*', [ 'File name for ' ... fastif(strcmpi(whichica, 'inv'), 'inverse', 'weight') ' matrix -- pop_expica()']); drawnow; if filename == 0 return; end; filename = [filepath filename]; end; % save datas % ---------- if strcmpi(whichica, 'inv') tmpmat = double(EEG.icawinv); else tmpmat = double(EEG.icaweights*EEG.icasphere); end; save(filename, '-ascii', 'tmpmat'); com = sprintf('pop_expica(%s, ''%s'', ''%s'');', inputname(1), whichica, filename); return;
github
lcnhappe/happe-master
pop_loadbci.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_loadbci.m
13,381
utf_8
471e8acb985f699ddd0e2e3b3a723d45
% pop_loadbci() - import a BCI2000 ascii file into EEGLAB % % Usage: % >> OUTEEG = pop_loadbci( filename, srate ); % % Inputs: % filename - file name % srate - sampling rate % % Outputs: % OUTEEG - EEGLAB data structure % % Author: Arnaud Delorme, CNL / Salk Institute, 9 July 2002 % % See also: eeglab() % Copyright (C) 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, command] = pop_loadbci(filename, srate); EEG = []; command = ''; if nargin < 1 % ask user [filename, filepath] = uigetfile('*.*', 'Choose a BCI file -- pop_loadbci'); drawnow; if filename == 0 return; end; filename = [filepath filename]; promptstr = { 'Sampling rate' }; inistr = { '256' }; result = inputdlg2( promptstr, 'Import BCI2000 data -- pop_loadbci()', 1, inistr, 'pop_loadbci'); if length(result) == 0 return; end; srate = eval( result{1} ); end; % import data % ----------- EEG = eeg_emptyset; fprintf('Pop_loadbci: importing BCI file...\n'); try % try to read as matlab % --------------------- bci = load( filename, '-mat'); allfields = fieldnames(bci); allfields = setdiff_bc(allfields, 'signal'); for index = 1:size(bci.signal,2) chanlabels{index} = [ 'C' int2str(index) ]; end; for index = 1:length(allfields) bci.signal(:,end+1) = getfield(bci, allfields{index}); end; EEG.chanlocs = struct('labels', { chanlabels{:} allfields{:} }); EEG.data = bci.signal'; EEG.nbchan = size(EEG.data, 1); EEG.pnts = size(EEG.data, 2); EEG.trials = 1; EEG.srate = srate; EEG.comments = [ 'Original file: ' filename ]; EEG = eeg_checkset(EEG); return; catch % get file names % -------------- fields = loadtxt(filename, 'nlines', 1, 'verbose', 'off'); if length(fields) > 300 error('Not a BCI ASCII file'); end; % read data % --------- fid = fopen(filename, 'r'); allcollumns = fgetl(fid); tmpdata = fscanf(fid, '%d', Inf); tmpdata = reshape(tmpdata, length(fields), length(tmpdata)/length(fields)); EEG.data = tmpdata; EEG.chanlocs = struct('labels', fields); EEG.nbchan = size(EEG.data, 1); EEG.pnts = size(EEG.data, 2); EEG.trials = 1; EEG.srate = srate; EEG = eeg_checkset(EEG); return; % data channel range % ------------------ indices = strmatch('ch', fields); bci = []; for index = setdiff_bc(1:length(fields), indices) bci = setfield(bci, fields{index}, tmpdata(index,:)); end; bci.signal = tmpdata(indices,:); end; % ask for which event to import % ----------------------------- geom = {[0.7 0.7 0.7]}; uilist = { { 'style' 'text' 'string' 'State name' 'fontweight' 'bold' } ... { 'style' 'text' 'string' ' Import' 'fontweight' 'bold' } ... { 'style' 'text' 'string' 'Type of' 'fontweight' 'bold' } }; allfields = setdiff_bc(fieldnames(bci), 'signal'); latencyfields = { '-----' }; for index = 1:length(allfields) if ~isempty(findstr( lower(allfields{index}), 'time')) latencyfields{end+1} = allfields{index}; end; end; for index = 1:length(allfields) geom = { geom{:} [1.3 0.3 0.3 0.3 1] }; uilist{end+1} = { 'style' 'text' 'string' allfields{index} }; if ~isempty(findstr( lower(allfields{index}), 'time')) uilist{end+1} = { 'style' 'checkbox' 'value' 0 }; uilist{end+1} = { }; uilist{end+1} = { }; uilist{end+1} = { }; else uilist{end+1} = { 'style' 'checkbox' }; uilist{end+1} = { }; uilist{end+1} = { }; uilist{end+1} = { 'style' 'listbox' 'string' strvcat(latencyfields) }; end; end; geom = { geom{:} [1] [0.08 1] }; uilist{end+1} = { }; uilist{end+1} = { 'style' 'checkbox' 'value' 0 }; uilist{end+1} = { 'style' 'text' 'string' 'Attempt to adjust event latencies using sourcetime?' }; result = inputgui( geom, uilist, 'pophelp(''pop_loadbci'')', 'Import BCI2000 data files - pop_loadbci()'); if isempty(result), return; end; % convert results to command line input % ------------------------------------- listimport = {}; count = 1; for index = 1:length(allfields) if ~isempty(findstr( lower(allfields{index}), 'time')) if result{count}, listimport{end+1} = 'event'; listimport{end+1} = { allfields{index} }; end; count = count+1; else if result{count} if result{count+1} ~= 1 listimport{end+1} = 'event'; listimport{end+1} = { allfields{index} allfields{result{count+1}-1} }; else listimport{end+1} = 'event'; listimport{end+1} = { allfields{index} }; end; end; count = count+2; end; end; if result{end}, adjust = 1; else adjust = 0; end; % decode command line input % ------------------------- count = 1; for index = 2:2:length(listimport) tmpindmatch = strmatch(listimport{index}{1}, allfields, 'exact'); if ~isempty(tmpindmatch), indeximport(count) = tmpindmatch; else error(['State ''' listimport{index}{1} ''' not found']); end; if length( listimport{index} ) > 1 tmpindmatch = strmatch(listimport{index}{2}, allfields, 'exact'); if ~isempty(tmpindmatch), corresp(count) = tmpindmatch; else error(['State ''' listimport{index}{2} ''' not found']); end; else corresp(count) = 0; end; count = count+1; end; % find block size % --------------- tmpevent = find( diff(getfield(bci, 'SourceTime')) ~= 0); diffevent = tmpevent(2:end)-tmpevent(1:end-1); blocksize = unique_bc(diffevent); if length(blocksize) > 1, error('Error in determining block size'); else fprintf('Blocksize: %d\n', blocksize); end; % find types % ---------- tmpcorresp = find(corresp); indexcorresp = corresp(tmpcorresp); indexcorrespval = indeximport(tmpcorresp); if length(tmpcorresp) ~= length(intersect(corresp, indeximport)) disp('Warning: correspondance problem, some information will be lost'); end; % remove type from latency array % ------------------------------ indeximport(tmpcorresp) = []; if adjust fprintf('Latency of event will be adjusted\n'); else fprintf('WARNING: Latency of event will not be adjusted (latency uncertainty %2.1f ms)\n', ... blocksize/srate*1000); end; % process events % -------------- fprintf('Pop_loadbci: importing events...\n'); counte = 1; % event counter events(10000).latency = 0; indexsource = strmatch('sourcetime', lower( allfields ), 'exact' ); sourcetime = getfield(bci, allfields{ indexsource }); for index = 1:length(indeximport) tmpdata = getfield(bci, allfields{indeximport(index)}); tmpevent = find( diff(tmpdata) > 0); tmpevent = tmpevent+1; tmpcorresp = find(indexcorresp == indeximport(index)); for tmpi = tmpevent' if ~isempty(tmpcorresp) events(counte).type = allfields{ indexcorrespval(tmpcorresp) }; else events(counte).type = allfields{ indeximport(index) }; end; if adjust baselatency = sourcetime(tmpi); % note that this is the first bin a block realtmpi = tmpi+blocksize; % jump to the end of the block+1 if curlatency < baselatency, curlatency = curlatency+65536; end; % in ms events(counte).latency = realtmpi+(curlatency-baselatency)/1000*srate; % (curlatency-baselatency)/1000*srate % there is still a potentially large error between baselatency <-> realtmpi else events(counte).latency = tmpi+(blocksize-1)/2; end; counte = counte+1; end; end; EEG.data = bci.signal'; EEG.nbchan = size(EEG.data, 1); EEG.pnts = size(EEG.data, 2); EEG.trials = 1; EEG.srate = srate; EEG = eeg_checkset(EEG); EEG.event = events(1:counte-1); EEG = eeg_checkset( EEG, 'eventconsistency' ); EEG = pop_editeventvals( EEG, 'sort', { 'latency', [0] } ); % $$$ % $$$ % $$$ % $$$ % $$$ % $$$ % $$$ % $$$ % $$$ % $$$ % $$$ % $$$ % $$$ % $$$ % $$$ dsffd % $$$ % $$$ % find electrode indices % $$$ % ---------------------- % $$$ indices = []; % $$$ for index = 1:length(colnames) % $$$ if strcmp( colnames{index}(1:2), 'ch') % $$$ indices = [indices index ]; % $$$ end; % $$$ end; % $$$ % $$$ EEG.data = tmpdata(indices,:); % $$$ EEG.nbchan = size(EEG.data, 1); % $$$ EEG.srate = srate; % $$$ try % $$$ eventindices = setdiff_bc(1:length(colnames), indices); % $$$ ISIind = eventindices(3 + 9); % $$$ eventindices(3 + [ 1 2 3 4 7 8 9 10 11 12]) = []; % $$$ eventindices(1:3) = []; % suppress these event % $$$ % $$$ % add the trial number % $$$ % -------------------- % $$$ tmptrial = find( diff(tmpdata(ISIind, :)) ~= 0); % $$$ tmptrial = tmptrial+1; % $$$ % $$$ % process events % $$$ % -------------- % $$$ fprintf('Pop_loadbci: importing events...\n'); % $$$ counte = 1; % event counter % $$$ events(10000).latency = 0; % $$$ for index = eventindices % $$$ counttrial = 1; % $$$ tmpevent = find( diff(tmpdata(index, :)) ~= 0); % $$$ tmpevent = tmpevent+1; % $$$ for tmpi = tmpevent % $$$ if tmpdata(index, tmpi) % $$$ events(counte).type = [ colnames{index} int2str(tmpdata(index, tmpi)) ]; % $$$ events(counte).latency = tmpi; % $$$ %events(counte).value = tmpdata(index, tmpi); % $$$ %while tmpi > tmptrial(counttrial) & counttrial < length(tmptrial) % $$$ % counttrial = counttrial+1; % $$$ %end; % $$$ %events(counte).trial = counttrial; % $$$ counte = counte+1; % $$$ %if mod(counte, 100) == 0, fprintf('%d ', counte); end; % $$$ end; % $$$ end; % $$$ end; % $$$ % $$$ % add up or down events % $$$ % --------------------- % $$$ EEG = eeg_checkset(EEG); % $$$ EEG.event = events(1:counte-1); % $$$ EEG = pop_editeventvals( EEG, 'sort', { 'latency', [0] } ); % $$$ for index=1:length(EEG.event) % $$$ if strcmp(EEG.event(index).type(1:6), 'Target') % $$$ targetcode = str2num(EEG.event(index).type(end)); % $$$ if targetcode == 1 % $$$ EEG.event(index).type = 'toptarget'; % $$$ else % $$$ EEG.event(index).type = 'bottomtarget'; % $$$ end; % $$$ else % $$$ if strcmp(EEG.event(index).type(1:6), 'Result') % $$$ resultcode = str2num(EEG.event(index).type(end)); % $$$ if resultcode == 1 % $$$ EEG.event(index).type = 'topresp'; % $$$ else % $$$ EEG.event(index).type = 'bottomresp'; % $$$ end; % $$$ EEG.event(end+1).latency = EEG.event(index).latency; % $$$ if (resultcode == targetcode) % $$$ EEG.event(end).type = 'correct'; % $$$ else % $$$ EEG.event(end).type = 'miss'; % $$$ end; % $$$ end; % $$$ end; % $$$ end; % $$$ EEG = pop_editeventvals( EEG, 'sort', { 'latency', [0] } ); % $$$ %EEG.data = tmpdata([72 73 75],:); % $$$ catch, disp('Failed to import data events'); % $$$ end; % $$$ % $$$ command = sprintf('EEG = pop_loadbci(''%s'', %f);',filename, srate); % $$$ return;
github
lcnhappe/happe-master
pop_fileio.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_fileio.m
7,131
utf_8
9330dd4ef5ede2f403e6e848748bfd57
% pop_fileio() - import data files into EEGLAB using FileIO % % Usage: % >> OUTEEG = pop_fileio; % pop up window % >> OUTEEG = pop_fileio( filename ); % % Inputs: % filename - [string] file name % % Optional inputs: % 'channels' - [integer array] list of channel indices % 'samples' - [min max] sample point limits for importing data. % 'trials' - [min max] trial's limit for importing data. % 'memorymapped' - ['on'|'off'] import memory mapped file (useful if % encountering memory errors). Default is 'off'. % % Outputs: % OUTEEG - EEGLAB data structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2008- % % Note: FILEIO toolbox must be installed. % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, command] = pop_fileio(filename, varargin); EEG = []; command = ''; if ~plugin_askinstall('Fileio', 'ft_read_data'), return; end; if nargin < 1 % ask user ButtonName = questdlg2('Do you want to import a file or a folder?', ... 'FILE-IO import', ... 'Folder', 'File', 'File'); if strcmpi(ButtonName, 'file') [filename, filepath] = uigetfile('*.*', 'Choose a file or header file -- pop_fileio()'); drawnow; if filename(1) == 0 return; end; filename = fullfile(filepath, filename); else filename = uigetfile('*.*', 'Choose a folder -- pop_fileio()'); drawnow; if filename(1) == 0 return; end; end; % open file to get infos % ---------------------- eeglab_options; mmoval = option_memmapdata; disp('Reading data file header...'); dat = ft_read_header(filename); uilist = { { 'style' 'text' 'String' 'Channel list (defaut all):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'String' [ 'Data range (in sample points) (default all [1 ' int2str(dat.nSamples) '])' ] } ... { 'style' 'edit' 'string' '' } }; geom = { [3 1] [3 1] }; if dat.nTrials > 1 uilist{end+1} = { 'style' 'text' 'String' [ 'Trial range (default all [1 ' int2str(dat.nTrials) '])' ] }; uilist{end+1} = { 'style' 'edit' 'string' '' }; geom = { geom{:} [3 1] }; end; uilist = { uilist{:} { 'style' 'checkbox' 'String' 'Import as memory mapped file (use in case of out of memory error)' 'value' option_memmapdata } }; geom = { geom{:} [1] }; result = inputgui( geom, uilist, 'pophelp(''pop_fileio'')', 'Load data using FILE-IO -- pop_fileio()'); if length(result) == 0 return; end; options = {}; if length(result) == 3, result = { result{1:2} '' result{3}}; end; if ~isempty(result{1}), options = { options{:} 'channels' eval( [ '[' result{1} ']' ] ) }; end; if ~isempty(result{2}), options = { options{:} 'samples' eval( [ '[' result{2} ']' ] ) }; end; if ~isempty(result{3}), options = { options{:} 'trials' eval( [ '[' result{3} ']' ] ) }; end; if result{4}, options = { options{:} 'memorymapped' fastif(result{4}, 'on', 'off') }; end; else dat = ft_read_header(filename); options = varargin; end; % decode imput parameters % ----------------------- g = finputcheck( options, { 'samples' 'integer' [1 Inf] []; 'trials' 'integer' [1 Inf] []; 'channels' 'integer' [1 Inf] []; 'memorymapped' 'string' { 'on';'off' } 'off' }, 'pop_fileio'); if isstr(g), error(g); end; % import data % ----------- EEG = eeg_emptyset; fprintf('Reading data ...\n'); dataopts = {}; if ~isempty(g.samples ), dataopts = { dataopts{:} 'begsample', g.samples(1), 'endsample', g.samples(2)}; end; if ~isempty(g.trials ), dataopts = { dataopts{:} 'begtrial', g.trials(1), 'endtrial', g.trials(2)}; end; if strcmpi(g.memorymapped, 'off') if ~isempty(g.channels), dataopts = { dataopts{:} 'chanindx', g.channels }; end; alldata = ft_read_data(filename, 'header', dat, dataopts{:}); else % read memory mapped file g.datadims = [ dat.nChans dat.nSamples dat.nTrials ]; disp('Importing as memory mapped array, this may take a while...'); if isempty(g.channels), g.channels = [1:g.datadims(1)]; end; if ~isempty(g.samples ), g.datadims(2) = g.samples(2) - g.samples(1); end; if ~isempty(g.trials ), g.datadims(3) = g.trials(2) - g.trials(1); end; g.datadims(1) = length(g.channels); alldata = mmo([], g.datadims); for ic = 1:length(g.channels) alldata(ic,:,:) = ft_read_data(filename, 'header', dat, dataopts{:}, 'chanindx', g.channels(ic)); end; end; % convert to seconds for sread % ---------------------------- EEG.srate = dat.Fs; EEG.nbchan = dat.nChans; EEG.data = alldata; EEG.setname = ''; EEG.comments = [ 'Original file: ' filename ]; EEG.xmin = -dat.nSamplesPre/EEG.srate; EEG.trials = dat.nTrials; EEG.pnts = dat.nSamples; if isfield(dat, 'label') && ~isempty(dat.label) EEG.chanlocs = struct('labels', dat.label); end % extract events % -------------- disp('Reading events...'); try event = ft_read_event(filename); catch, disp(lasterr); event = []; end; if ~isempty(event) subsample = 0; if ~isempty(g.samples), subsample = g.samples(1); end; for index = 1:length(event) offset = fastif(isempty(event(index).offset), 0, event(index).offset); EEG.event(index).type = event(index).value; EEG.event(index).value = event(index).type; EEG.event(index).latency = event(index).sample+offset+subsample; EEG.event(index).duration = event(index).duration; if EEG.trials > 1 EEG.event(index).epoch = ceil(EEG.event(index).latency/EEG.pnts); end; end; EEG = eeg_checkset(EEG, 'eventconsistency'); else disp('Warning: no event found. Events might be embeded in a data channel.'); disp(' To extract events, use menu File > Import Event Info > From data channel'); end; % convert data to single if necessary % ----------------------------------- EEG = eeg_checkset(EEG,'makeur'); % Make EEG.urevent field % history % ------- if isempty(options) command = sprintf('EEG = pop_fileio(''%s'');', filename); else command = sprintf('EEG = pop_fileio(''%s'', %s);', filename, vararg2str(options)); end;
github
lcnhappe/happe-master
pop_compareerps.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_compareerps.m
2,848
utf_8
d0e259f378ec39efae7121f2225f9cbf
% pop_compareerps() - Compare the (ERP) averages of two datasets. % % Usage: % >> pop_compareerps( ALLEEG, datasetlist, chansubset, title); % Inputs: % ALLEEG - array of datasets % datasetlist - list of datasets % chansubset - vector of channel subset % title - plot title % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab(), plottopo() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-11-02 added empty ALLEEG check -ad % 03-18-02 added channel subset -ad % 03-18-02 added title -ad & sm function com = pop_compareerps( ALLEEG, setlist, chansubset, plottitle); com = ''; if nargin < 1 help pop_compareerps; return; end; if isempty(ALLEEG) error('pop_compareerps: cannot process empty sets of data'); end; if exist('plottitle') ~= 1 plottitle = ''; end; if nargin < 2 % which set to save % ----------------- promptstr = { 'List of datasets to compare (ex: 1 3 4):' ... 'Channels subset to consider ([]=all):' ... 'Plot title ([]=automatic):' }; inistr = { '1' '' '' }; result = inputdlg2( promptstr, 'Compare dataset ERPs -- pop_compareerps()', 1, inistr, 'pop_compareerps'); if length(result) == 0 return; end; setlist = eval( [ '[' result{1} ']' ] ); chansubset = eval( [ '[' result{2} ']' ] ); if isempty( chansubset ), chansubset = 1:ALLEEG(setlist(1)).nbchan; end; plottitle = result{3}; if isempty(plottitle) plottitle = [ 'Compare datasets number (blue=first; red=sec.)' int2str(setlist) ]; end; figure; end; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; tracing = []; for setindex = setlist tracing = [ tracing squeeze(mean(ALLEEG(setindex).data,3))]; end; % save channel names % ------------------ plottopo( tracing, ALLEEG(setlist(1)).chanlocs, ALLEEG(setlist(1)).pnts, [ALLEEG(setlist(1)).xmin ALLEEG(setlist(1)).xmax 0 0]*1000, plottitle, chansubset ); com = sprintf('figure; pop_compareerps( %s, [%s], [%s], ''%s'');', inputname(1), num2str(setlist), num2str(chansubset), plottitle); return;
github
lcnhappe/happe-master
importevent.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/importevent.m
16,193
utf_8
3c5abc8a8b32a3fe9ba00144fbaed59d
% importevent() - Import experimental events from data file or Matlab % array into a structure. % % Usage: >> eventstruct = importevent( event, oldevent, srate); % >> eventstruct = importevent( event, oldevent, srate, 'key1', 'value1', ...); % % Input: % event - [ 'filename'|array ] Filename of a text file, or name of % Matlab array in the global workspace containing an % array of events in the folowing format: The first column of % the cell array is the type of the event, the second the latency. % The others are user-defined. The function can read % either numeric or text entries in ascii files. % oldevent - Old event structure. Used for aligning new events with old % ones. Enter [] is no such structure exist. % srate - Sampling rate of the underlying data. Event latencies are % expressed in terms of latency in sample point with respect % to the data. % % Optional file or array input: % 'fields' - [Cell array] List of the name of each user-defined column, % optionally followed by a description. Ex: { 'type', 'latency' } % 'skipline' - [Interger] Number of header rows to skip in the text file % 'timeunit' - [ latency unit rel. to seconds ]. Default unit is 1 = seconds. % NaN indicates that the latencies are given in time points. % 'delim' - [string] String of delimiting characters in the input file. % Default is tab|space. % % Optional oldevent input: % 'append' - ['yes'|'no'] 'yes' = Append events to the current events in % the EEG dataset {default}: 'no' = Erase the previous events. % 'indices' - {integer vector] Vector indicating the indices of the events to % modify. % 'align' - [num] Align the first event latency to the latency of existing % event number (num), and check latency consistency. % A value of 0 indicates that the first events of the pre-defined % events and imported events will be aligned. A positive value (num) % aligns the first event to the num-th pre-existing event. % A negative value can also be used; then event number (-num) % is aligned to the first pre-existing event. Default is 0. % (NaN-> no alignment). % 'optimmeas' - ['median'|'mean'] Uses either the median of the mean % distance to align events. Default is 'mean'. Median is % preferable if events are missing in the event file. % 'optimalign' - ['on'|'off'] Optimize the sampling rate of the new events so % they best align with old events. Default is 'on'. % % Outputs: % eventstruct - Event structure containing imported events % % Example: >> eventstruct = importevent( 'event_values.txt', [], 256, ... % 'fields', {'type', 'latency','condition' }, ... % 'append', 'no', 'align', 0, 'timeunit', 1E-3 ); % % This loads the ascii file 'event_values.txt' containing 3 columns % (event_type, latency, and condition). Latencies in the file are % in ms (1E-3). The first event latency is re-aligned with the % beginning of the dataset ('align', 0). Any previous events % are erased ('append', 'no'). % % Author: Arnaud Delorme & Scott Makeig, CNL / Salk Institute, 2004 % % See also: pop_importevent() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 2004, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %% REVISION HISTORY %% function definition, input check function event = importevent(event, oldevent, srate, varargin) if nargin < 1 help importevent; return; end; I = []; % remove the event field % ---------------------- if ~isempty(oldevent), allfields = fieldnames(oldevent); else allfields = {}; end; g = finputcheck( varargin, { 'fields' 'cell' [] {}; 'skipline' 'integer' [0 Inf] 0; 'indices' 'integer' [1 Inf] []; 'append' 'string' {'yes';'no';'''yes''';'''no''' } 'yes'; 'timeunit' 'real' [] 1; 'event' { 'cell';'real';'string' } [] []; 'align' 'integer' [] NaN; 'optimalign' 'string' { 'on';'off' } 'on'; 'optimmeas' 'string' { 'median';'mean' } 'mean'; 'delim' {'integer';'string'} [] char([9 32 44])}, 'importevent'); if isstr(g), error(g); end; if ~isempty(g.indices), g.append = 'yes'; end; g.delim = char(g.delim); % call from pop_importevent % ------------------------- if ~isempty(g.event) event = g.event; if ~isstr(event) if size(event,2) > size(event,1), event = event'; end; if iscell(event) eventStr = cellfun(@ischar, event); eventNum = cellfun(@isnumeric, event); if all(eventStr(1,:)) && ~all(eventStr(:,1)) event = event'; end; if all(eventNum(1,:)) && ~all(eventNum(:,1)) event = event'; end; end; end; end; g.event = event; % determine latency for old event alignment % ----------------------------------------- tmpalign = g.align; g.align = []; g.align.val = tmpalign; if ~isnan(g.align.val) if isempty(oldevent) error('Setevent: no pre-existing event, cannot perform alignment'); end; if ~isfield(oldevent, 'latency') error('Setevent: pre-existing events do not have a latency field for re-alignment'); end; switch g.append case {'yes' '''yes'''}, disp('Setevent warning: cannot align and append events at the same time; disabling event alignment'); end; if g.align.val < 0 g.align.event = oldevent(1).latency; else g.align.event = oldevent(g.align.val+1).latency; end g.align.nbevent = length(oldevent); g.oldevents = oldevent; g.align.txt = sprintf([ 'Check alignment between pre-existing (old) and loaded event' ... ' latencies:\nOld event latencies (10 first): %s ...\n' ], ... int2str([ oldevent(1:min(10, length(oldevent))).latency ])); else g.oldevents = []; end; tmpfields = fieldnames(g); event = oldevent; %% scan all the fields of g % ------------------------ for curfield = tmpfields' if ~isempty(event), allfields = fieldnames(event); else allfields = {}; end; switch lower(curfield{1}) case {'append', 'fields', 'skipline', 'indices', 'timeunit', 'align', 'delim' }, ; % do nothing now case 'event', % load an ascii file switch g.append case { '''no''' 'no' } % ''no'' for backward compatibility if isstr(g.event) && ~exist(g.event), g.event = evalin('caller', g.event); end; event = load_file_or_array( g.event, g.skipline, g.delim ); allfields = g.fields(1:min(length(g.fields), size(event,2))); event = eeg_eventformat(event, 'struct', allfields); % generate ori fields % ------------------- if ~isnan(g.timeunit) for index = 1:length(event) event(index).init_index = index; event(index).init_time = event(index).latency*g.timeunit; end; end; event = recomputelatency( event, 1:length(event), srate, ... g.timeunit, g.align, g.oldevents, g.optimalign, g.optimmeas); case { '''yes''' 'yes' } % match existing fields % --------------------- if isstr(g.event) && ~exist(g.event), g.event = evalin('caller', g.event); end; tmparray = load_file_or_array( g.event, g.skipline, g.delim ); if isempty(g.indices) g.indices = [1:size(tmparray,1)] + length(event); end; if length(g.indices) ~= size(tmparray,1) error('Set error: number of row in file does not match the number of event given as input'); end; % add field % --------- g.fields = getnewfields( g.fields, size(tmparray,2)-length(g.fields)); % add new values % --------------------- for eventfield = 1:size(tmparray,2) event = setstruct( event, g.fields{eventfield}, g.indices, { tmparray{:,eventfield} }); end; % generate ori fields % ------------------- offset = length(event)-size(tmparray,1); for index = 1:size(tmparray,1) event(index+offset).init_index = index; event(index+offset).init_time = event(index+offset).latency*g.timeunit; end; event = recomputelatency( event, g.indices, srate, g.timeunit, ... g.align, g.oldevents, g.optimalign, g.optimmeas); end; end; end; if isempty(event) % usefull 0xNB empty structure event = []; end; %% remove the events wit out-of-bound latencies % -------------------------------------------- if isfield(event, 'latency') try res = cellfun('isempty', { event.latency }); res = find(res); if ~isempty(res) fprintf( 'importevent warning: %d/%d event(s) have invalid latencies and were removed\n', ... length(res), length(event)); event( res ) = []; end; end; end; %% interpret the variable name % --------------------------- function array = load_file_or_array( varname, skipline, delim ); if isstr(varname) & exist(varname) == 2 % mean that it is a filename % -------------------------- array = loadtxt( varname, 'skipline', skipline, 'delim', delim, 'blankcell', 'off' ); else if ~iscell(varname) array = mattocell(varname); else array = varname; end; end; return; %% update latency values % --------------------- function event = recomputelatency( event, indices, srate, timeunit, align, oldevents, optimalign, optimmeas) % update time unit % ---------------- if ~isfield(event, 'latency'), if isfield(event, 'duration') error('A duration field cannot be defined if a latency field has not been defined'); end; return; end; if ~isnan(timeunit) for index = indices event(index).latency = event(index).latency*srate*timeunit; if isfield(event, 'duration') event(index).duration = event(index).duration*srate*timeunit; end; end; end; % alignment with old events % ------------------------- if ~isnan( align.val ) if align.val >= 0, alignlatency = event(1).latency; else alignlatency = event(-align.val+1).latency; end; for index = indices event(index).latency = event(index).latency-alignlatency+align.event; end; if length(event) ~= align.nbevent disp('Setevent warning: the number of pre-existing events do not correspond to the number of events'); disp(' that were read, so their latencies may have been wrongly re-aligned'); end; fprintf(align.txt); fprintf('New event latencies (10 first): %s ...\n', int2str(round([ event(1:min(10, length(event))).latency ]))); end; if strcmpi(optimalign, 'on') & ~isempty(oldevents) newlat = [ event.latency ]; oldlat = [ oldevents.latency ]; newlat = repmat(newlat, [length(oldlat) 1]); oldlat = repmat(oldlat', [1 size(newlat,2)]); if align.val >= 0 newlat = newlat-newlat(1); oldlat = oldlat-oldlat(1+align.val); else newlat = newlat-newlat(1-align.val); oldlat = oldlat-oldlat(1); end; try newfactor = fminsearch('eventalign',1,[],newlat, oldlat, optimmeas); catch newfactor = fminsearch('eventalign',1,[],[],newlat, oldlat, optimmeas); % Octave end; fprintf('Best sampling rate ratio found is %1.7f. Below latencies after adjustment\n', newfactor); if newfactor > 1.01 | newfactor < 0.99 disp('Difference is more than 1%, something is wrong; ignoring ratio'); newfactor = 1; else difference1 = eventalign( 1 , newlat, oldlat, optimmeas); difference2 = eventalign( newfactor, newlat, oldlat, optimmeas); fprintf('The average difference before correction was %f sample points\n', difference1); fprintf('The average difference after correction is %f sample points\n', difference2); end; %diffarray = abs(newfactor*newlat-oldlat)'; %[allmins poss] = min(diffarray); %figure; hist(allmins); else newfactor = 1; end; if ~isnan( align.val ) & newfactor ~= 1 if align.val >= 0 latfirstevent = event(1).latency; else latfirstevent = event(-align.val+1).latency; end; for index = setdiff_bc(indices, 1) event(index).latency = round(event(index).latency-latfirstevent)*newfactor+latfirstevent; end; if ~isempty(oldevents) fprintf('Old event latencies (10 first): %s ...\n', int2str(round([ oldevents(1:min(10, length(oldevents))).latency ]))); fprintf('New event latencies (10 first): %s ...\n', int2str(round([ event(1:min(10, length(event))).latency ]))); end; else % must add one (because first sample point has latency 0 % ------------------------------------------------------ if ~isnan(timeunit) for index = indices event(index).latency = round((event(index).latency+1)*1000*newfactor)/1000; end; end; end; %% create new field names % ---------------------- function epochfield = getnewfields( epochfield, nbfields ) count = 1; while nbfields > 0 if isempty( strmatch([ 'var' int2str(count) ], epochfield ) ) epochfield = { epochfield{:} [ 'var' int2str(count) ] }; nbfields = nbfields-1; else count = count+1; end; end return; %% % ---------------------- function var = setstruct( var, fieldname, indices, values ) if exist('indices') ~= 1, indices = 1:length(var); end if ~isempty(values) for index = 1:length(indices) var = setfield(var, {indices(index)}, fieldname, values{index}); end else for index = 1:length(indices) var = setfield(var, {indices(index)}, fieldname, ''); end end return;
github
lcnhappe/happe-master
pop_saveset.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_saveset.m
12,652
utf_8
f327353b0e7ee940640ebfd448f68f9d
% pop_saveset() - save one or more EEG dataset structures % % Usage: % >> pop_saveset( EEG ); % use an interactive pop-up window % >> EEG = pop_saveset( EEG, 'key', 'val', ...); % no pop-up % % Inputs: % EEG - EEG dataset structure. May only contain one dataset. % % Optional inputs: % 'filename' - [string] name of the file to save to % 'filepath' - [string] path of the file to save to % 'check' - ['on'|'off'] perform extended syntax check. Default 'off'. % 'savemode' - ['resave'|'onefile'|'twofiles'] 'resave' resave the % current dataset using the filename and path stored % in the dataset; 'onefile' saves the full EEG % structure in a Matlab '.set' file, 'twofiles' saves % the structure without the data in a Matlab '.set' file % and the transposed data in a binary float '.dat' file. % By default the option from the eeg_options.m file is % used. % 'version' - ['6'|'7.3'] save Matlab file as version 6 or % '7.3' (default; as defined in eeg_option file). % % Outputs: % EEG - saved dataset (after extensive syntax checks) % ALLEEG - saved datasets (after extensive syntax checks) % % Note: An individual dataset should be saved with a '.set' file extension % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: pop_loadset(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad function [EEG, com] = pop_saveset( EEG, varargin); com = ''; if nargin < 1 help pop_saveset; return; end; if isempty(EEG) , error('Cannot save empty datasets'); end; % empty filename (resave file) emptyfilename = 0; if nargin > 1 if isempty(varargin{1}) && isempty(EEG.filename), emptyfilename = 1; end; if strcmpi(varargin{1},'savemode') if length(EEG) == 1 if isempty(EEG(1).filename), varargin{2} = ''; emptyfilename = 1; end; else if any(cellfun(@isempty, { EEG.filename })) error('Cannot resave files who have not been saved previously'); end; end; end; end; if nargin < 2 || emptyfilename if length(EEG) >1, error('For reasons of consistency, this function does not save multiple datasets any more'); end; % pop up window to ask for file [filename, filepath] = uiputfile2('*.set', 'Save dataset with .set extension -- pop_saveset()'); if ~isstr(filename), return; end; drawnow; options = { 'filename' filename 'filepath' filepath }; else % account for old calling format % ------------------------------ if isempty(strmatch( lower(varargin{1}), { 'filename' 'filepath' 'savemode' 'check' })) options = { 'filename' varargin{1} }; if nargin > 2 options = { options{:} 'filepath' varargin{2} }; end; else options = varargin; end; end; % decode input parameters % ----------------------- eeglab_options; defaultSave = fastif(option_saveversion6, '6', '7.3'); g = finputcheck(options, { 'filename' 'string' [] ''; 'filepath' 'string' [] ''; 'version' 'string' { '6','7.3' } defaultSave; 'check' 'string' { 'on','off' } 'off'; 'savemode' 'string' { 'resave','onefile','twofiles','' } '' }); if isstr(g), error(g); end; % current filename without the .set % --------------------------------- if emptyfilename == 1, g.savemode = ''; end; [g.filepath filenamenoext ext] = fileparts( fullfile(g.filepath, g.filename) ); ext = '.set'; g.filename = [ filenamenoext ext ]; % performing extended syntax check % -------------------------------- if strcmpi(g.check, 'on') fprintf('Pop_saveset: Performing extended dataset syntax check...\n'); EEG = eeg_checkset(EEG, 'eventconsistency'); EEG = eeg_checkset(EEG); else EEG = eeg_checkset(EEG); end % check for change in saving mode % ------------------------------- if length(EEG) == 1 if strcmpi(g.savemode, 'resave') && isfield(EEG, 'datfile') && ~option_savetwofiles disp('Note that your memory options for saving datasets does not correspond') disp('to the format of the datasets on disk (ignoring memory options)') % $$$ but = questdlg2(strvcat('This dataset has an associated ''.dat'' file, but since you have', ... % $$$ 'changed of saving mode, all the data will now be saved within the', ... % $$$ 'Matlab file and the ''.dat'' file will be deleted.', ... % $$$ '(Note: Just press ''No'' if you do not know what you are doing)'), ... % $$$ 'Warning: saving mode changed', 'Cancel', 'No, save as before', 'Yes, do it', 'Yes, do it'); % $$$ switch but % $$$ case 'Cancel', return; % $$$ case 'No, save as before', % nothing % $$$ case 'Yes, do it', g.savemode = 'onefile'; % $$$ end; % $$$ g.filename = EEG.filename; % $$$ g.filepath = EEG.filepath; elseif strcmpi(g.savemode, 'resave') && ~isfield(EEG, 'datfile') && option_savetwofiles disp('Note that your memory options for saving datasets does not correspond') disp('to the format of the datasets on disk (ignoring memory options)') % $$$ but = questdlg2(strvcat('This dataset does not have yet an associated ''.dat'' file, but since you have', ... % $$$ 'changed of saving mode, all the data will now be saved within the ''.dat''', ... % $$$ 'file and not in the Matlab file (as it is currently the case).', ... % $$$ '(Note: Just press ''No'' if you do not know what you are doing)'), ... % $$$ 'Warning: saving mode changed', 'Cancel', 'No, save as before', 'Yes, do it', 'Yes, do it'); % $$$ switch but % $$$ case 'Cancel', return; % $$$ case 'No, save as before', % nothing % $$$ case 'Yes, do it', g.savemode = 'twofiles'; % $$$ end; % $$$ g.filename = EEG.filename; % $$$ g.filepath = EEG.filepath; end; end; % default saving otion % -------------------- save_as_dat_file = 0; data_on_disk = 0; if strcmpi(g.savemode, 'resave') % process multiple datasets % ------------------------- if length(EEG) > 1 for index = 1:length(EEG) pop_saveset(EEG(index), 'savemode', 'resave'); EEG(index).saved = 'yes'; end; com = sprintf('%s = pop_saveset( %s, %s);', inputname(1), inputname(1), vararg2str(options)); return; end; if strcmpi( EEG.saved, 'yes'), disp('Dataset has not been modified; No need to resave it.'); return; end; g.filename = EEG.filename; g.filepath = EEG.filepath; if isfield(EEG, 'datfile') if ~isempty(EEG.datfile) save_as_dat_file = 1; end; end; if isstr(EEG.data) & ~save_as_dat_file % data in .set file TMP = pop_loadset(EEG.filename, EEG.filepath); EEG.data = TMP.data; data_on_disk = 1; end; else if length(EEG) >1, error('For reasons of consistency, this function does not save multiple datasets any more'); end; if ~strcmpi(EEG.filename, g.filename) | ~strcmpi(EEG.filepath, g.filepath) EEG.datfile = ''; end; EEG.filename = g.filename; EEG.filepath = g.filepath; if isempty(g.savemode) if option_savematlab, g.savemode = 'onefile'; else g.savemode = 'twofiles'; end; end; if strcmpi(g.savemode, 'twofiles') save_as_dat_file = 1; EEG.datfile = [ filenamenoext '.fdt' ]; end; end; % Saving data as float and Matlab % ------------------------------- tmpica = EEG.icaact; EEG.icaact = []; if ~isstr(EEG.data) if ~strcmpi(class(EEG.data), 'memmapdata') && ~strcmpi(class(EEG.data), 'mmo') && ~strcmpi(class(EEG.data), 'single') tmpdata = single(reshape(EEG.data, EEG.nbchan, EEG.pnts*EEG.trials)); else tmpdata = EEG.data; end; no_resave_dat = 'no'; else no_resave_dat = 'yes'; end; v = version; try, fprintf('Saving dataset...\n'); EEG.saved = 'yes'; if save_as_dat_file if ~isstr(EEG.data) EEG.data = EEG.datfile; tmpdata = floatwrite( tmpdata, fullfile(EEG.filepath, EEG.data), 'ieee-le'); end; else if isfield(EEG, 'datfile') if ~isempty(EEG.datfile) if exist(fullfile(EEG.filepath, EEG.datfile)) try, delete(fullfile(EEG.filepath, EEG.datfile)); disp('Deleting .dat/.fdt file on disk (all data is within the Matlab file)'); catch, end; end; end; EEG.datfile = []; end; end; try if strcmpi(g.version, '6') save(fullfile(EEG.filepath, EEG.filename), '-v6', '-mat', 'EEG'); else save(fullfile(EEG.filepath, EEG.filename), '-v7.3', '-mat', 'EEG'); end; catch save(fullfile(EEG.filepath, EEG.filename), '-mat', 'EEG'); end; if save_as_dat_file & strcmpi( no_resave_dat, 'no' ) EEG.data = tmpdata; end; % save ICA activities % ------------------- % icafile = fullfile(EEG.filepath, [EEG.filename(1:end-4) '.icafdt' ]); % if isempty(EEG.icaweights) & exist(icafile) % disp('ICA activation file found on disk, but no more ICA activities. Deleting file.'); % delete(icafile); % end; % if ~option_saveica & exist(icafile) % disp('Options indicate not to save ICA activations. Deleting ICA activation file.'); % delete(icafile); % end; % if option_saveica & ~isempty(EEG.icaweights) % if ~exist('tmpdata') % TMP = eeg_checkset(EEG, 'loaddata'); % tmpdata = TMP.data; % end; % if isempty(tmpica) % tmpica2 = (EEG.icaweights*EEG.icasphere)*tmpdata(EEG.icachansind,:); % else tmpica2 = tmpica; % end; % tmpica2 = reshape(tmpica2, size(tmpica2,1), size(tmpica2,2)*size(tmpica2,3)); % floatwrite( tmpica2, icafile, 'ieee-le'); % clear tmpica2; % end; catch, rethrow(lasterror); end; % try to delete old .fdt or .dat files % ------------------------------------ tmpfilename = fullfile(EEG.filepath, [ filenamenoext '.dat' ]); if exist(tmpfilename) == 2 disp('Deleting old .dat file format detected on disk (now replaced by .fdt file)'); try, delete(tmpfilename); disp('Delete sucessfull.'); catch, disp('Error while attempting to remove file'); end; end; if save_as_dat_file == 0 tmpfilename = fullfile(EEG.filepath, [ filenamenoext '.fdt' ]); if exist(tmpfilename) == 2 disp('Old .fdt file detected on disk, deleting file the Matlab file contains all data...'); try, delete(tmpfilename); disp('Delete sucessfull.'); catch, disp('Error while attempting to remove file'); end; end; end; % recovering variables % -------------------- EEG.icaact = tmpica; if data_on_disk EEG.data = 'in set file'; end; if isnumeric(EEG.data) && v(1) < 7 EEG.data = double(reshape(tmpdata, EEG.nbchan, EEG.pnts, EEG.trials)); end; EEG.saved = 'justloaded'; com = sprintf('%s = pop_saveset( %s, %s);', inputname(1), inputname(1), vararg2str(options)); return; function num = popask( text ) ButtonName=questdlg2( text, ... 'Confirmation', 'Cancel', 'Yes','Yes'); switch lower(ButtonName), case 'cancel', num = 0; case 'yes', num = 1; end;
github
lcnhappe/happe-master
eeg_pv.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_pv.m
8,193
utf_8
23a0d260095460fdd46f49f5060dcf52
% eeg_pv() - Compute EEG.data 'percent variance ' (pv) of the whole EEG data versus the projections % of specified components. % Can omit specified components and channels from the computation. Can draw a plot % of the scalp distribution of pv, or progressively compute the pv for comps % 1:k, where k = 1 -> the total number of components. Note: pv's of spatially % non-orthogonal independent components may not add to 100%, and individual component % pv could be < 0%. % Usage: % >> [pv] = eeg_pv(EEG,comps); % >> [pv,pvs,vars] = eeg_pv(EEG,comps,artcomps,omitchans,fraction,'plot'); % Inputs: % EEG - EEGLAB dataset. Must have icaweights, icasphere, icawinv, icaact. % comps - vector of component indices to sum {default|[] -> progressive mode} % In progressive mode, comps is first [1], then [1 2], etc. up to % [1:size(EEG.icaweights,2)] (all components); here, the plot shows pv. % artcomps - vector of artifact component indices to remove from data before % computing pv {default|[]: none} % omitchans - channels to omit from the computation (e.g. off-head, etc) {default|[]: none} % fraction - (0<real<=1) fraction of the data to randomly select {default|[]: 1=all} % 'plot' - Plot scalp map of channel pvs. {default: Plot only if no output arguments} % % Outputs: % pv - (real) percent total variance accounted for by the summed back-projection of % the requested components. If comps is [], a vector of pvs for the sum of % components 1:k (k=1:ncomps). % pvs - (real vector) percent variance accounted for by the summed back-projection of % the requested components to each data channel. If comps is [], a matrix of % pvs (as for pv above). % vars - variances of the requested channels % % Fields: % Assumes existence of the following EEG fields: EEG.data, EEG.pnts, EEG.nbchan, EEG.trials, % EEG.icaact, EEG.icaweights, EEG.icasphere, EEG.icawinv, and for plot, EEG.chanlocs % % See also: eeg_pvaf() % % Author: from eeg_pvaf(), Scott Makeig, SCCN/INC/UCSD, 02/04/05 function [pv,pvs,pvall] = eeg_pv(EEG,comps,artcomps,omitchans,fraction,plotflag) if nargin < 1 | nargin > 6 help eeg_pv return end numcomps = size(EEG.icaact,1); plotit = 0; if nargin>5 | nargout < 1 plotit = 1; end if nargin<5 | isempty(fraction) fraction = 1; end if fraction>1 fprintf('eeg_pv(): considering all the data.\n'); fraction=1; end if round(fraction*EEG.pnts*EEG.trials)<1 error('fraction of data specified too small.') return end if nargin<4 | isempty(omitchans) omitchans = []; end if nargin<3|isempty(artcomps) artcomps=[]; end numchans = EEG.nbchan; chans = 1:numchans; if ~isempty(omitchans) if max(omitchans)>numchans help eeg_pv error('at least one channel to omit > number of channels in data'); end if min(omitchans)<1 help eeg_pv error('channel numbers to omit must be > 0'); end chans(omitchans) = []; end progressive = 0; % by default, progressive mode is off if nargin < 2 | isempty(comps)|comps==0 comps = []; progressive = 1; % turn progressive mode on end if isempty(EEG.icaweights) help eeg_pv return end if isempty(EEG.icasphere) help eeg_pv return end if isempty(EEG.icawinv) EEG.icawinv = pinv(EEG.icaweights*EEG.icasphere); end if isempty(EEG.icaact) help eeg_pv fprintf('EEG.icaact not present.\n'); % EEG.icaact = EEG.icaweights*EEG.icasphere*EEG.data; % remake it like this end if max(comps) > size(EEG.icawinv,1) help eeg_pv fprintf('Only %d components in this dataset. Cannot project component %d.\n',numcomps,max(comps)); error('bad comps input'); end if ~isempty(artcomps) & max(artcomps) > numcomps help eeg_pv fprintf('Only %d components in this dataset. Cannot project artcomp %d.\n',numcomps,max(artcomps)); error('bad artcomps input') end npts = EEG.trials*EEG.pnts; allcomps = 1:numcomps; if progressive fprintf('Considering components up to: '); cum_pv = zeros(1,numcomps); cum_pvs = zeros(numcomps,numchans); end for comp = 1:numcomps %%%%%%%%%%%%%%% progressive mode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if progressive comps = allcomps(1:comp); % summing components 1 to current comp fprintf('%d ',comp) end if ~isempty(artcomps) [a b c] = intersect_bc(artcomps,comps); if ~isempty(a) if ~progressive if length(a)>1 fprintf('eeg_pv(): not back-projecting %d comps already in the artcomps.\n',length(c)); else fprintf('eeg_pv(): not back-projecting comp %d already in the artcomps.\n',comps(c)); end end comps(c) = []; end end if ~isempty(artcomps) & min([comps artcomps]) < 1 error('comps and artcomps must contain component indices'); end % %%%%%%%%%%%%%%%%%%%%%%%% compute variance accounted for by specified components %%%%%%%%%%%%% % if ~progressive | comp == 1 % pare out omitchans and artcomps from EEG.data if ~isempty(artcomps) EEG.data = EEG.data(chans,:) - EEG.icawinv(chans,artcomps)*EEG.icaact(artcomps,:); else EEG.data = EEG.data(chans,:); end nsel = round(fraction*npts); varpts = randperm(npts); varwts = ones(size(varpts)); if nsel<npts varwts(varpts(nsel+1:npts)) = 0; end pvall = var(EEG.data(:,:)',varwts); end chans comps size(EEG.icawinv(chans,comps)) size(EEG.icaact(comps,:)') pvcomp = var((EEG.icawinv(chans,comps)*EEG.icaact(comps,:))', varwts); % %%%%%%%%%%%%%%%%%%%%%%%% compute percent variance %%%%%%%%%%%%%%% % pvs = pvcomp ./ pvall; pvs = 100*pvs; pv = sum(pvcomp) ./ sum(pvall); pv = 100*pv; if ~progressive break else cum_pv(comp) = pv; cum_pvs(comp,:) = pvs; end end %%%%%%%%%%%%%% end progressive forloop %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if progressive % output accumulated results fprintf('\n'); pv = cum_pv; pvs = cum_pvs; if plotit plot(1:numcomps,pv); xl = xlabel('Components Included (1:n)'); yl = ylabel('Percent Variance Accounted For (pv)'); set(xl,'fontsize',15); set(yl,'fontsize',15); set(gca,'fontsize',14); end elseif plotit % %%%%%%%%%%%%%%%%%%%%%%%% plot the scalp distribtion of pv %%%%%%%%%%%%% % if isfield(EEG,'chanlocs') chanlocs = EEG.chanlocs; if ~isempty(omitchans) chanlocs(omitchans) = []; end topoplot(pvs',chanlocs); % plot pv here if length(comps)>5 % add text legend if length(artcomps)>3 tlstr=sprintf('Pvaf by %d comps in data minus %d comps',length(comps),length(artcomps)); elseif isempty(artcomps) tlstr=sprintf('Pvaf by %d comps in data',length(comps)); elseif length(artcomps)==1 % < 4 artcomps, list them tlstr=sprintf('Pvaf by %d comps in data (less comp ',length(comps)); tlstr = [tlstr sprintf('%d ',artcomps) ')']; else tlstr=sprintf('Pvaf by %d comps in data (less comps ',length(comps)); tlstr = [tlstr sprintf('%d ',artcomps) ')']; end else % < 6 comps, list them if length(comps)>1 tlstr=sprintf('Pvaf by comps '); else tlstr=sprintf('Pvaf by comp '); end if length(artcomps)>3 tlstr = ... [tlstr sprintf('%d ',comps) sprintf('in data minus %d comps',length(comps),length(artcomps))]; else if isempty(artcomps) tlstr = [tlstr sprintf('%d ',comps) 'in data']; elseif length(artcomps)==1 tlstr = [tlstr sprintf('%d ',comps) 'in data (less comp ']; tlstr = [tlstr int2str(artcomps) ')']; else tlstr = [tlstr sprintf('%d ',comps) 'in data (less comps ']; tlstr = [tlstr sprintf('%d ',artcomps) ')']; end end end tl=title(tlstr); if max(pvs)>100, maxc=max(pvs) else maxc=100; end; pvstr=sprintf('Total pv: %3.1f%%',pv); tx=text(-0.9,-0.6,pvstr); caxis([-100 100]); cb=cbar('vert',33:64,[0 100]); % color bar showing >0 (green->red) only else fprintf('EEG.chanlocs not found - not plotting scalp pv\n'); end end % plotit
github
lcnhappe/happe-master
eeg_epoch2continuous.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_epoch2continuous.m
1,716
utf_8
79ffa71e29359c2ca1a0f21c2caf95cf
% eeg_epoch2continuous() - convert epoched dataset to continuous dataset % with data epochs separated by boundary events. % Usage: % >> EEGOUT = eeg_epoch2continuous(EEGIN); % % Inputs: % EEGIN - a loaded epoched EEG dataset structure. % % Inputs: % EEGOUT - a continuous EEG dataset structure. % % Authors: Arnaud Delorme, SCCN, INC, UCSD, January, 2012 % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 2012, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function EEG = eeg_epoch2continuous(EEG) if nargin < 1 help eeg_epoch2continuous; return; end; EEG.data = reshape(EEG.data, size(EEG.data,1), size(EEG.data,2)*size(EEG.data,3)); for index = 1:EEG.trials-1 EEG.event(end+1).type = 'boundary'; EEG.event(end ).latency = index*EEG.pnts-0.5; EEG.event(end ).duration = NaN; end; EEG.pnts = size(EEG.data,2); EEG.trials = 1; if ~isempty(EEG.event) && isfield(EEG.event, 'epoch') EEG.event = rmfield(EEG.event, 'epoch'); end; EEG = eeg_checkset(EEG);
github
lcnhappe/happe-master
eeg_interp.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_interp.m
14,002
utf_8
05337b7e8a6e06975f7173af18eec59a
% eeg_interp() - interpolate data channels % % Usage: EEGOUT = eeg_interp(EEG, badchans, method); % % Inputs: % EEG - EEGLAB dataset % badchans - [integer array] indices of channels to interpolate. % For instance, these channels might be bad. % [chanlocs structure] channel location structure containing % either locations of channels to interpolate or a full % channel structure (missing channels in the current % dataset are interpolated). % method - [string] method used for interpolation (default is 'spherical'). % 'invdist'/'v4' uses inverse distance on the scalp % 'spherical' uses superfast spherical interpolation. % 'spacetime' uses griddata3 to interpolate both in space % and time (very slow and cannot be interupted). % Output: % EEGOUT - data set with bad electrode data replaced by % interpolated data % % Author: Arnaud Delorme, CERCO, CNRS, Mai 2006- % Copyright (C) Arnaud Delorme, CERCO, 2006, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function EEG = eeg_interp(ORIEEG, bad_elec, method) if nargin < 2 help eeg_interp; return; end; EEG = ORIEEG; if nargin < 3 disp('Using spherical interpolation'); method = 'spherical'; end; % check channel structure tmplocs = ORIEEG.chanlocs; if isempty(tmplocs) || isempty([tmplocs.X]) error('Interpolation require channel location'); end; if isstruct(bad_elec) % add missing channels in interpolation structure % ----------------------------------------------- lab1 = { bad_elec.labels }; tmpchanlocs = EEG.chanlocs; lab2 = { tmpchanlocs.labels }; [tmp tmpchan] = setdiff_bc( lab2, lab1); tmpchan = sort(tmpchan); if ~isempty(tmpchan) newchanlocs = []; fields = fieldnames(bad_elec); for index = 1:length(fields) if isfield(bad_elec, fields{index}) for cind = 1:length(tmpchan) fieldval = getfield( EEG.chanlocs, { tmpchan(cind) }, fields{index}); newchanlocs = setfield(newchanlocs, { cind }, fields{index}, fieldval); end; end; end; newchanlocs(end+1:end+length(bad_elec)) = bad_elec; bad_elec = newchanlocs; end; if length(EEG.chanlocs) == length(bad_elec), return; end; lab1 = { bad_elec.labels }; tmpchanlocs = EEG.chanlocs; lab2 = { tmpchanlocs.labels }; [tmp badchans] = setdiff_bc( lab1, lab2); fprintf('Interpolating %d channels...\n', length(badchans)); if length(badchans) == 0, return; end; goodchans = sort(setdiff(1:length(bad_elec), badchans)); % re-order good channels % ---------------------- [tmp1 tmp2 neworder] = intersect_bc( lab1, lab2 ); [tmp1 ordertmp2] = sort(tmp2); neworder = neworder(ordertmp2); EEG.data = EEG.data(neworder, :, :); % looking at channels for ICA % --------------------------- %[tmp sorti] = sort(neworder); %{ EEG.chanlocs(EEG.icachansind).labels; bad_elec(goodchans(sorti(EEG.icachansind))).labels } % update EEG dataset (add blank channels) % --------------------------------------- if ~isempty(EEG.icasphere) [tmp sorti] = sort(neworder); EEG.icachansind = sorti(EEG.icachansind); EEG.icachansind = goodchans(EEG.icachansind); EEG.chaninfo.icachansind = EEG.icachansind; % TESTING SORTING %icachansind = [ 3 4 5 7 8] %data = round(rand(8,10)*10) %neworder = shuffle(1:8) %data2 = data(neworder,:) %icachansind2 = sorti(icachansind) %data(icachansind,:) %data2(icachansind2,:) end; % { EEG.chanlocs(neworder).labels; bad_elec(sort(goodchans)).labels } %tmpdata = zeros(length(bad_elec), size(EEG.data,2), size(EEG.data,3)); %tmpdata(goodchans, :, :) = EEG.data; % looking at the data % ------------------- %tmp1 = mattocell(EEG.data(sorti,1)); %tmp2 = mattocell(tmpdata(goodchans,1)); %{ EEG.chanlocs.labels; bad_elec(goodchans).labels; tmp1{:}; tmp2{:} } %EEG.data = tmpdata; EEG.chanlocs = bad_elec; else badchans = bad_elec; goodchans = setdiff_bc(1:EEG.nbchan, badchans); oldelocs = EEG.chanlocs; EEG = pop_select(EEG, 'nochannel', badchans); EEG.chanlocs = oldelocs; disp('Interpolating missing channels...'); end; % find non-empty good channels % ---------------------------- origoodchans = goodchans; chanlocs = EEG.chanlocs; nonemptychans = find(~cellfun('isempty', { chanlocs.theta })); [tmp indgood ] = intersect_bc(goodchans, nonemptychans); goodchans = goodchans( sort(indgood) ); datachans = getdatachans(goodchans,badchans); badchans = intersect_bc(badchans, nonemptychans); if isempty(badchans), return; end; % scan data points % ---------------- if strcmpi(method, 'spherical') % get theta, rad of electrodes % ---------------------------- tmpgoodlocs = EEG.chanlocs(goodchans); xelec = [ tmpgoodlocs.X ]; yelec = [ tmpgoodlocs.Y ]; zelec = [ tmpgoodlocs.Z ]; rad = sqrt(xelec.^2+yelec.^2+zelec.^2); xelec = xelec./rad; yelec = yelec./rad; zelec = zelec./rad; tmpbadlocs = EEG.chanlocs(badchans); xbad = [ tmpbadlocs.X ]; ybad = [ tmpbadlocs.Y ]; zbad = [ tmpbadlocs.Z ]; rad = sqrt(xbad.^2+ybad.^2+zbad.^2); xbad = xbad./rad; ybad = ybad./rad; zbad = zbad./rad; EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts*EEG.trials); %[tmp1 tmp2 tmp3 tmpchans] = spheric_spline_old( xelec, yelec, zelec, EEG.data(goodchans,1)); %max(tmpchans(:,1)), std(tmpchans(:,1)), %[tmp1 tmp2 tmp3 EEG.data(badchans,:)] = spheric_spline( xelec, yelec, zelec, xbad, ybad, zbad, EEG.data(goodchans,:)); [tmp1 tmp2 tmp3 badchansdata] = spheric_spline( xelec, yelec, zelec, xbad, ybad, zbad, EEG.data(datachans,:)); %max(EEG.data(goodchans,1)), std(EEG.data(goodchans,1)) %max(EEG.data(badchans,1)), std(EEG.data(badchans,1)) EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts, EEG.trials); elseif strcmpi(method, 'spacetime') % 3D interpolation, works but x10 times slower disp('Warning: if processing epoch data, epoch boundary are ignored...'); disp('3-D interpolation, this can take a long (long) time...'); tmpgoodlocs = EEG.chanlocs(goodchans); tmpbadlocs = EEG.chanlocs(badchans); [xbad ,ybad] = pol2cart([tmpbadlocs.theta],[tmpbadlocs.radius]); [xgood,ygood] = pol2cart([tmpgoodlocs.theta],[tmpgoodlocs.radius]); pnts = size(EEG.data,2)*size(EEG.data,3); zgood = [1:pnts]; zgood = repmat(zgood, [length(xgood) 1]); zgood = reshape(zgood,prod(size(zgood)),1); xgood = repmat(xgood, [1 pnts]); xgood = reshape(xgood,prod(size(xgood)),1); ygood = repmat(ygood, [1 pnts]); ygood = reshape(ygood,prod(size(ygood)),1); tmpdata = reshape(EEG.data, prod(size(EEG.data)),1); zbad = 1:pnts; zbad = repmat(zbad, [length(xbad) 1]); zbad = reshape(zbad,prod(size(zbad)),1); xbad = repmat(xbad, [1 pnts]); xbad = reshape(xbad,prod(size(xbad)),1); ybad = repmat(ybad, [1 pnts]); ybad = reshape(ybad,prod(size(ybad)),1); badchansdata = griddata3(ygood, xgood, zgood, tmpdata,... ybad, xbad, zbad, 'nearest'); % interpolate data else % get theta, rad of electrodes % ---------------------------- tmpchanlocs = EEG.chanlocs; [xbad ,ybad] = pol2cart([tmpchanlocs( badchans).theta],[tmpchanlocs( badchans).radius]); [xgood,ygood] = pol2cart([tmpchanlocs(goodchans).theta],[tmpchanlocs(goodchans).radius]); fprintf('Points (/%d):', size(EEG.data,2)*size(EEG.data,3)); badchansdata = zeros(length(badchans), size(EEG.data,2)*size(EEG.data,3)); for t=1:(size(EEG.data,2)*size(EEG.data,3)) % scan data points if mod(t,100) == 0, fprintf('%d ', t); end; if mod(t,1000) == 0, fprintf('\n'); end; %for c = 1:length(badchans) % [h EEG.data(badchans(c),t)]= topoplot(EEG.data(goodchans,t),EEG.chanlocs(goodchans),'noplot', ... % [EEG.chanlocs( badchans(c)).radius EEG.chanlocs( badchans(c)).theta]); %end; tmpdata = reshape(EEG.data, size(EEG.data,1), size(EEG.data,2)*size(EEG.data,3) ); if strcmpi(method, 'invdist'), method = 'v4'; end; [Xi,Yi,badchansdata(:,t)] = griddata(ygood, xgood , double(tmpdata(datachans,t)'),... ybad, xbad, method); % interpolate data end fprintf('\n'); end; tmpdata = zeros(length(bad_elec), EEG.pnts, EEG.trials); tmpdata(origoodchans, :,:) = EEG.data; %if input data are epoched reshape badchansdata for Octave compatibility... if length(size(tmpdata))==3 badchansdata = reshape(badchansdata,length(badchans),size(tmpdata,2),size(tmpdata,3)); end tmpdata(badchans,:,:) = badchansdata; EEG.data = tmpdata; EEG.nbchan = size(EEG.data,1); EEG = eeg_checkset(EEG); % get data channels % ----------------- function datachans = getdatachans(goodchans, badchans); datachans = goodchans; badchans = sort(badchans); for index = length(badchans):-1:1 datachans(find(datachans > badchans(index))) = datachans(find(datachans > badchans(index)))-1; end; % ----------------- % spherical splines % ----------------- function [x, y, z, Res] = spheric_spline_old( xelec, yelec, zelec, values); SPHERERES = 20; [x,y,z] = sphere(SPHERERES); x(1:(length(x)-1)/2,:) = []; x = [ x(:)' ]; y(1:(length(y)-1)/2,:) = []; y = [ y(:)' ]; z(1:(length(z)-1)/2,:) = []; z = [ z(:)' ]; Gelec = computeg(xelec,yelec,zelec,xelec,yelec,zelec); Gsph = computeg(x,y,z,xelec,yelec,zelec); % equations are % Gelec*C + C0 = Potential (C unknow) % Sum(c_i) = 0 % so % [c_1] % * [c_2] % [c_ ] % xelec [c_n] % [x x x x x] [potential_1] % [x x x x x] [potential_ ] % [x x x x x] = [potential_ ] % [x x x x x] [potential_4] % [1 1 1 1 1] [0] % compute solution for parameters C % --------------------------------- meanvalues = mean(values); values = values - meanvalues; % make mean zero C = pinv([Gelec;ones(1,length(Gelec))]) * [values(:);0]; % apply results % ------------- Res = zeros(1,size(Gsph,1)); for j = 1:size(Gsph,1) Res(j) = sum(C .* Gsph(j,:)'); end Res = Res + meanvalues; Res = reshape(Res, length(x(:)),1); function [xbad, ybad, zbad, allres] = spheric_spline( xelec, yelec, zelec, xbad, ybad, zbad, values); newchans = length(xbad); numpoints = size(values,2); %SPHERERES = 20; %[x,y,z] = sphere(SPHERERES); %x(1:(length(x)-1)/2,:) = []; xbad = [ x(:)']; %y(1:(length(x)-1)/2,:) = []; ybad = [ y(:)']; %z(1:(length(x)-1)/2,:) = []; zbad = [ z(:)']; Gelec = computeg(xelec,yelec,zelec,xelec,yelec,zelec); Gsph = computeg(xbad,ybad,zbad,xelec,yelec,zelec); % compute solution for parameters C % --------------------------------- meanvalues = mean(values); values = values - repmat(meanvalues, [size(values,1) 1]); % make mean zero values = [values;zeros(1,numpoints)]; C = pinv([Gelec;ones(1,length(Gelec))]) * values; clear values; allres = zeros(newchans, numpoints); % apply results % ------------- for j = 1:size(Gsph,1) allres(j,:) = sum(C .* repmat(Gsph(j,:)', [1 size(C,2)])); end allres = allres + repmat(meanvalues, [size(allres,1) 1]); % compute G function % ------------------ function g = computeg(x,y,z,xelec,yelec,zelec) unitmat = ones(length(x(:)),length(xelec)); EI = unitmat - sqrt((repmat(x(:),1,length(xelec)) - repmat(xelec,length(x(:)),1)).^2 +... (repmat(y(:),1,length(xelec)) - repmat(yelec,length(x(:)),1)).^2 +... (repmat(z(:),1,length(xelec)) - repmat(zelec,length(x(:)),1)).^2); g = zeros(length(x(:)),length(xelec)); %dsafds m = 4; % 3 is linear, 4 is best according to Perrin's curve for n = 1:7 if ismatlab L = legendre(n,EI); else % Octave legendre function cannot process 2-D matrices for icol = 1:size(EI,2) tmpL = legendre(n,EI(:,icol)); if icol == 1, L = zeros([ size(tmpL) size(EI,2)]); end; L(:,:,icol) = tmpL; end; end; g = g + ((2*n+1)/(n^m*(n+1)^m))*squeeze(L(1,:,:)); end g = g/(4*pi);
github
lcnhappe/happe-master
pop_editeventvals.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_editeventvals.m
25,793
utf_8
de89caf08acbbceb7572ea96a994e688
% pop_editeventvals() - Edit events contained in an EEG dataset structure. % If the dataset is the only input, a window pops up % allowing the user to insert the relevant parameter values. % % Usage: >> EEGOUT = pop_editeventvals( EEG, 'key1', value1, ... % 'key2', value2, ... ); % Input: % EEG - EEG dataset % % Optional inputs: % 'sort' - { field1 dir1 field2 dir2 } Sort events based on field1 % then on optional field2. Arg dir1 indicates the sort % direction (0 = increasing, 1 = decreasing). % 'changefield' - {num field value} Insert the given value into the specified % field in event num. (Ex: {34 'latency' 320.4}) % 'changeevent' - {num value1 value2 value3 ...} Change the values of % all fields in event num. % 'add','append','insert' - {num value1 value2 value3 ...} Insert event % before or at event num, and assign value to structure % fields. Note that the latency field must be in second % and will be converted to data sample. Note also that % the index of the event is often irrelevant, as events % will be automatically resorted by latencies. % 'delete' - vector of indices of events to delete % % Outputs: % EEGOUT - EEG dataset with the selected events only % % Ex: EEG = pop_editeventvals(EEG,'changefield', { 1 'type' 'target'}); % % set field type of event number 1 to 'target' % % Author: Arnaud Delorme & Hilit Serby, SCCN, UCSD, 15 March 2002 % % See also: pop_selectevent(), pop_importevent() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 15 March 2002, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 03-16-02 text interface editing -sm & ad % 03-18-02 automatic latency switching display (epoch/continuous) - ad & sm % 03-18-02 debug soring order - ad % 03-18-02 put latencies in ms - ad, lf & sm % 03-29-02 debug latencies in ms - ad & sm % 04-02-02 debuging test - ad & sm function [EEG, com] = pop_editeventvals(EEG, varargin); com =''; if nargin < 1 help pop_editeventvals; return; end; if nargin >= 2 | isstr(EEG) % interpreting command from GUI or command line if isstr(EEG) % GUI gui = 1; varargin = { EEG varargin{:} }; % user data % --------- userdata = get(gcf, 'userdata'); EEG = userdata{1}; oldcom = userdata{2}; allfields = fieldnames(EEG.event); tmpind = strmatch('urevent', allfields); allfields(tmpind) = []; % current event % ------------- objevent = findobj('parent', gcf, 'tag', 'numval'); valnum = str2num(get(objevent, 'string')); shift = 0; else % command line gui = 0; if isempty(EEG.event) disp('Getevent: cannot deal with empty event structure'); return; end; allfields = fieldnames(EEG.event); tmpind = strmatch('urevent', allfields); allfields(tmpind) = []; end; % retinterpret inputs (fix BUG 454) % -------------------------------- if ~gui newvararg = {}; for indfield = 1:2:length(varargin) com = varargin{ indfield }; tmpargs = varargin{ indfield+1 }; newvararg = { newvararg{:} com }; if any(strcmpi({'add','insert','append'},com)) evtind = tmpargs{1}; fields = fieldnames(EEG.event); emptycells = cell(1,length(fields)-1); newvararg = { newvararg{:}, { evtind emptycells{:} } }; if strcmpi(com, 'append'), evtind = evtind+1; end; for ind = 2:length( tmpargs ) if ~strcmpi(fields{ind-1}, 'urevent') newvararg = { newvararg{:},'changefield',{ evtind fields{ind-1} tmpargs{ind} } }; end; end; else newvararg = { newvararg{:} tmpargs }; end; end; varargin = newvararg; end; % scan inputs % ----------- for indfield = 1:2:length(varargin) if length(varargin) >= indfield+1 tmparg = varargin{ indfield+1 }; end; switch lower(varargin{indfield}) case 'goto', % ******************** GUI ONLY *********************** % shift time % ---------- shift = tmparg; valnum = valnum + shift; if valnum < 1, valnum = 1; end; if valnum > length(EEG.event), valnum = length(EEG.event); end; set(objevent, 'string', num2str(valnum,5)); % update fields % ------------- for index = 1:length(allfields) enable = 'on'; if isfield(EEG.event, 'type') if strcmpi(EEG.event(valnum).type, 'boundary'), enable = 'off'; end; end; if strcmp( allfields{index}, 'latency') & ~isempty(EEG.event(valnum).latency) if isfield(EEG.event, 'epoch') value = eeg_point2lat( EEG.event(valnum).latency, EEG.event(valnum).epoch, ... EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3); else value = (EEG.event(valnum).latency-1)/EEG.srate+EEG.xmin; end; elseif strcmp( allfields{index}, 'duration') & ~isempty(EEG.event(valnum).duration) if isfield(EEG.event, 'epoch') value = EEG.event(valnum).duration/EEG.srate*1000; % milliseconds else value = EEG.event(valnum).duration/EEG.srate; % seconds end; else value = getfield( EEG.event(valnum), allfields{index}); end; % update interface % ---------------- tmpobj = findobj('parent', gcf, 'tag', allfields{index}); set(tmpobj, 'string', num2str(value,5), 'enable', enable); end; % update original % --------------- tmpobj = findobj('parent', gcf, 'tag', 'original'); if isfield(EEG.event, 'urevent') & EEG.event(valnum).urevent ~= valnum set(tmpobj, 'string', [ 'originally ' int2str(EEG.event(valnum).urevent)], ... 'horizontalalignment', 'center'); else set(tmpobj, 'string', ' '); end; return; % NO NEED TO SAVE ANYTHING case { 'append' 'insert' 'add' }, % ********************************************************** if gui shift = tmparg; % shift is for adding before or after the event % add epoch number if data epoch % ------------------------------ tmpcell = cell(1,1+length(fieldnames(EEG.event))); tmpcell{1} = valnum; if EEG.trials > 1 indepoch = strmatch('epoch', fieldnames(EEG.event), 'exact'); if valnum > 1, tmpprevval = valnum-1; else tmpprevval = valnum+1; end; if tmpprevval <= length(EEG.event) tmpcell{indepoch+1} = EEG.event(tmpprevval).epoch; end; end; % update commands % --------------- if shift oldcom = { oldcom{:} 'append', tmpcell }; else oldcom = { oldcom{:} 'insert', tmpcell }; end; else if strcmpi(lower(varargin{indfield}), 'append') % not 'add' for backward compatibility shift = 1; else shift = 0; end; valnum = tmparg{1}; end; % find ur index % ------------- valnum = valnum + shift; if isfield(EEG.event, 'epoch'), curepoch = EEG.event(valnum).epoch; end; if isfield(EEG, 'urevent') & isfield(EEG.event, 'urevent') % find non empty urvalnum urvalnum = []; count = 0; while isempty(urvalnum) tmpindex = mod(valnum+count-1, length(EEG.event)+1)+1; urvalnum = EEG.event(valnum+count).urevent; count = count+1; end; if isfield(EEG.urevent, 'epoch'), urcurepoch = EEG.urevent(urvalnum).epoch; end; urvalnum = urvalnum; end; % update urevents % --------------- if isfield(EEG, 'urevent') & isfield(EEG.event, 'urevent') EEG.urevent(end+3) = EEG.urevent(end); EEG.urevent(urvalnum+1:end-2) = EEG.urevent(urvalnum:end-3); EEG.urevent(urvalnum) = EEG.urevent(end-1); EEG.urevent = EEG.urevent(1:end-2); if isfield(EEG.urevent, 'epoch'), EEG.urevent(urvalnum).epoch = urcurepoch; end; end; % update events % ------------- EEG.event(end+3) = EEG.event(end); EEG.event(valnum+1:end-2) = EEG.event(valnum:end-3); EEG.event(valnum) = EEG.event(end-1); EEG.event = EEG.event(1:end-2); if isfield(EEG.event, 'epoch'), EEG.event(valnum).epoch = curepoch; end; if isfield(EEG, 'urevent') & isfield(EEG.event, 'urevent') EEG.event(valnum).urevent = urvalnum; for index = valnum+1:length(EEG.event) EEG.event(index).urevent = EEG.event(index).urevent+1; end; end; % update type field % ----------------- for tmpind = 1:length(allfields) EEG.event = checkconsistency(EEG.event, valnum, allfields{tmpind}); end; case 'delete', % ********************************************************** if ~gui valnum = tmparg; end EEG.event(valnum) = []; if gui, valnum = min(valnum,length(EEG.event)); set(objevent, 'string', num2str(valnum)); % update commands % --------------- oldcom = { oldcom{:} 'delete', valnum }; end; case { 'assign' 'changefield' }, % ********************************************************** if gui, % GUI case field = tmparg; objfield = findobj('parent', gcf, 'tag', field); editval = get(objfield, 'string'); if ~isempty(editval) & ~isempty(str2num(editval)), editval = str2num(editval); end; % update history % -------------- oldcom = { oldcom{:},'changefield',{ valnum field editval }}; else % command line case valnum = tmparg{1}; field = tmparg{2}; editval = tmparg{3}; end; % latency and duration case % ------------------------- if strcmp( field, 'latency') & ~isempty(editval) if isfield(EEG.event, 'epoch') editval = eeg_lat2point( editval, EEG.event(valnum).epoch, ... EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3); else editval = (editval- EEG.xmin)*EEG.srate+1; end; end; if strcmp( field, 'duration') & ~isempty(editval) if isfield(EEG.event, 'epoch') editval = editval/1000*EEG.srate; % milliseconds else editval = editval*EEG.srate; % seconds end; end; % adapt to other formats % ---------------------- EEG.event(valnum) = setfield(EEG.event(valnum), field, editval); EEG.event = checkconsistency(EEG.event, valnum, field); % update urevents % --------------- if isfield(EEG, 'urevent') & isfield(EEG.event, 'urevent') urvalnum = EEG.event(valnum).urevent; % latency case % ------------ if strcmp( field, 'latency') & ~isempty(editval) if isfield(EEG.urevent, 'epoch') urepoch = EEG.urevent(urvalnum).epoch; % find closest event latency % -------------------------- if valnum<length(EEG.event) if EEG.event(valnum+1).epoch == urepoch urlatency = EEG.urevent(EEG.event(valnum+1).urevent).latency; latency = EEG.event(valnum+1).latency; end; end; if valnum>1 if EEG.event(valnum-1).epoch == urepoch urlatency = EEG.urevent(EEG.event(valnum-1).urevent).latency; latency = EEG.event(valnum-1).latency; end; end; % update event % ------------ if exist('urlatency') ~=1 disp('Urevent not updated: could not find other event in the epoch'); else editval = urlatency - ( latency - editval ); % new latency value end; else editval = eeg_urlatency(EEG.event, EEG.event(valnum).latency); end; elseif strcmp( field, 'latency') % empty editval EEG.event(valnum).latency = NaN; end; % duration case % ------------ if strcmp( field, 'duration') & ~isempty(editval) if isfield(EEG.event, 'epoch') editval = editval/1000*EEG.srate; % milliseconds -> point else editval = editval*EEG.srate; % seconds -> point end; end; EEG.urevent = setfield(EEG.urevent, {urvalnum}, field, editval); end; case 'sort', % ********************************************************** if gui % retrieve data field1 = get(findobj('parent', gcf, 'tag', 'listbox1'), 'value'); field2 = get(findobj('parent', gcf, 'tag', 'listbox2'), 'value'); dir1 = get(findobj('parent', gcf, 'tag', 'order1'), 'value'); dir2 = get(findobj('parent', gcf, 'tag', 'order2'), 'value'); if field1 > 1, field1 = allfields{field1-1}; else return; end; if field2 > 1, field1 = allfields{field2-1}; else field2 = []; end; % update history % -------------- oldcom = { oldcom{:},'sort',{ field1 dir1 field2 dir2 } }; else % command line field1 = tmparg{1}; if length(tmparg) < 2, dir1 = 0; else dir1 = tmparg{2}; end; if length(tmparg) < 3, field2 = []; else field2 = tmparg{3}; end; if length(tmparg) < 4, dir2 = 0; else dir2 = tmparg{4}; end; end; % Toby edit 11/16/2005 This section is scrambling the eeg.event % fields. Requires further investigation. if ~isempty(field2) tmpevent = EEG.event; if ~ischar(EEG.event(1).(field2)) tmparray = [ tmpevent.(field2) ]; else tmparray = { tmpevent.(field2) }; end % Commented out 11/18/2005, Toby % These lines were incorrectly sorting the event.latency field in % units of time (seconds) relevant to each event's relative % latency time as measured from the start of each epoch. It is % possible that there are occasions when it is desirable to do % so, but in the case of pop_mergset() it is not. %if strcmp(field2, 'latency') & EEG.trials > 1 % tmparray = eeg_point2lat(tmparray, {EEG.event.epoch}, EEG.srate, [EEG.xmin EEG.xmax], 1); %end; [X I] = mysort( tmparray ); if dir2 == 1, I = I(end:-1:1); end; events = EEG.event(I); else events = EEG.event; end; tmpevent = EEG.event; if ~ischar(EEG.event(1).(field1)) tmparray = [ tmpevent.(field1) ]; else tmparray = { tmpevent.(field1) }; end % Commented out 11/18/2005, Toby %if strcmp( field1, 'latency') & EEG.trials > 1 % tmparray = eeg_point2lat(tmparray, {events.epoch}, EEG.srate, [EEG.xmin EEG.xmax], 1); %end; [X I] = mysort( tmparray ); if dir1 == 1, I = I(end:-1:1); end; EEG.event = events(I); if gui % warn user % --------- warndlg2('Sorting done'); else noeventcheck = 1; % otherwise infinite recursion with eeg_checkset end; end; % end switch end; % end loop % save userdata % ------------- if gui userdata{1} = EEG; userdata{2} = oldcom; set(gcf, 'userdata', userdata); pop_editeventvals('goto', shift); else if ~exist('noeventcheck','var') EEG = eeg_checkset(EEG, 'eventconsistency'); EEG = eeg_checkset(EEG, 'checkur'); end; end; return; end; % ---------------------- % graphic interface part % ---------------------- if isempty(EEG.event) disp('Getevent: cannot deal with empty event structure'); return; end; allfields = fieldnames(EEG.event); tmpind = strmatch('urevent', allfields); allfields(tmpind) = []; if nargin<2 % add field values % ---------------- geometry = { [2 0.5] }; tmpstr = sprintf('Edit event field values (currently %d events)',length(EEG.event)); uilist = { { 'Style', 'text', 'string', tmpstr, 'fontweight', 'bold' } ... { 'Style', 'pushbutton', 'string', 'Delete event', 'callback', 'pop_editeventvals(''delete'');' }}; for index = 1:length(allfields) geometry = { geometry{:} [1 1 1 1] }; % input string % ------------ if strcmp( allfields{index}, 'latency') | strcmp( allfields{index}, 'duration') if EEG.trials > 1 inputstr = [ allfields{index} ' (ms)']; else inputstr = [ allfields{index} ' (sec)']; end; else inputstr = allfields{index}; end; % callback for displaying help % ---------------------------- if index <= length( EEG.eventdescription ) tmptext = EEG.eventdescription{ index }; if ~isempty(tmptext) if size(tmptext,1) > 15, stringtext = [ tmptext(1,1:15) '...' ]; else stringtext = tmptext(1,:); end; else stringtext = 'no-description'; tmptext = 'no-description'; end; else stringtext = 'no-description'; tmptext = 'no-description'; end; cbbutton = ['questdlg2(' vararg2str(tmptext) ... ',''Description of field ''''' allfields{index} ''''''', ''OK'', ''OK'');' ]; % create control % -------------- cbedit = [ 'pop_editeventvals(''assign'', ''' allfields{index} ''');' ]; uilist = { uilist{:}, { }, ... { 'Style', 'pushbutton', 'string', inputstr, 'callback',cbbutton }, ... { 'Style', 'edit', 'tag', allfields{index}, 'string', '', 'callback', cbedit } ... { } }; end; % add buttons % ----------- geometry = { geometry{:} [1] [1.2 0.6 0.6 1 0.6 0.6 1.2] [1.2 0.6 0.6 1 0.6 0.6 1.2] [2 1 2] }; tpappend = 'Append event after the current event'; tpinsert = 'Insert event before the current event'; tporigin = 'Original index of the event (in EEG.urevent table)'; uilist = { uilist{:}, ... { }, ... { },{ },{ }, {'Style', 'text', 'string', 'Event Num', 'fontweight', 'bold' }, { },{ },{ }, ... { 'Style', 'pushbutton', 'string', 'Insert event', 'callback', 'pop_editeventvals(''append'', 0);', 'tooltipstring', tpinsert }, ... { 'Style', 'pushbutton', 'string', '<<', 'callback', 'pop_editeventvals(''goto'', -10);' }, ... { 'Style', 'pushbutton', 'string', '<', 'callback', 'pop_editeventvals(''goto'', -1);' }, ... { 'Style', 'edit', 'string', '1', 'callback', 'pop_editeventvals(''goto'', 0);', 'tag', 'numval' }, ... { 'Style', 'pushbutton', 'string', '>', 'callback', 'pop_editeventvals(''goto'', 1);' }, ... { 'Style', 'pushbutton', 'string', '>>', 'callback', 'pop_editeventvals(''goto'', 10);' }, ... { 'Style', 'pushbutton', 'string', 'Append event', 'callback', 'pop_editeventvals(''append'', 1);', 'tooltipstring', tpappend }, ... { }, { 'Style', 'text', 'string', ' ', 'tag', 'original' 'horizontalalignment' 'center' 'tooltipstring' tporigin } { } }; % add sorting options % ------------------- listboxtext = 'No field selected'; for index = 1:length(allfields) listboxtext = [ listboxtext '|' allfields{index} ]; end; geometry = { geometry{:} [1] [1 1 1] [1 1 1] [1 1 1] }; uilist = { uilist{:}, ... { 'Style', 'text', 'string', 'Re-order events (for review only)', 'fontweight', 'bold' }, ... { 'Style', 'text', 'string', 'Main sorting field:' }, ... { 'Style', 'popupmenu', 'string', listboxtext, 'tag', 'listbox1' }, ... { 'Style', 'checkbox', 'string', 'Click for decreasing order', 'tag', 'order1' } ... { 'Style', 'text', 'string', 'Secondary sorting field:' }, ... { 'Style', 'popupmenu', 'string', listboxtext, 'tag', 'listbox2' }, ... { 'Style', 'checkbox', 'string', 'Click for decreasing order', 'tag', 'order2' }, ... { } { 'Style', 'pushbutton', 'string', 'Re-sort', 'callback', 'pop_editeventvals(''sort'');' }, ... { } }; userdata = { EEG {} }; inputgui( geometry, uilist, 'pophelp(''pop_editeventvals'');', ... 'Edit event values -- pop_editeventvals()', userdata, 'plot'); pop_editeventvals('goto', 0); % wait for figure % --------------- fig = gcf; waitfor( findobj('parent', fig, 'tag', 'ok'), 'userdata'); try, userdata = get(fig, 'userdata'); close(fig); % figure still exist ? catch, return; end; % transfer events % --------------- if ~isempty(userdata{2}) com = sprintf('%s = pop_editeventvals(%s,%s);', inputname(1), inputname(1), vararg2str(userdata{2})); end; if isempty(findstr('''sort''', com)) if ~isempty(userdata{2}) % some modification have been done EEG = userdata{1}; disp('Checking event consistency...'); EEG = eeg_checkset(EEG, 'eventconsistency'); EEG = eeg_checkset(EEG, 'checkur'); end; else com = ''; disp('WARNING: all edits discarded because of event resorting. The EEGLAB event structure'); disp(' must contain events sorted by latency (you may obtain an event structure'); disp(' with resorted event by calling this function from the command line).'); end; return; end; return; % format the output field % ----------------------- function strval = reformat( val, latencycondition, trialcondition, eventnum) if latencycondition if trialcondition strval = ['eeg_lat2point(' num2str(val) ', EEG.event(' int2str(eventnum) ').epoch, EEG.srate,[EEG.xmin EEG.xmax]*1000, 1E-3);' ]; else strval = [ '(' num2str(val) '-EEG.xmin)*EEG.srate+1;' ]; end; else if isstr(val), strval = [ '''' val '''' ]; else strval = num2str(val); end; end; % sort also empty values % ---------------------- function [X, I] = mysort(tmparray); if iscell(tmparray) if all(cellfun('isreal', tmparray)) tmpempty = cellfun('isempty', tmparray); tmparray(tmpempty) = { 0 }; tmparray = [ tmparray{:} ]; end; end; try, [X I] = sort(tmparray); catch, disp('Sorting failed. Check that selected fields contain uniform value format.'); X = tmparray; I = 1:length(X); end; % checkconsistency of new event % ----------------------------- function eventtmp = checkconsistency(eventtmp, valnum, field) otherval = mod(valnum+1, length(eventtmp))+1; if isstr(getfield(eventtmp(valnum), field)) & ~isstr(getfield(eventtmp(otherval), field)) eventtmp(valnum) = setfield(eventtmp(valnum), field, str2num(getfield(eventtmp(valnum), field))); end; if ~isstr(getfield(eventtmp(valnum), field)) & isstr(getfield(eventtmp(otherval), field)) eventtmp(valnum) = setfield(eventtmp(valnum), field, num2str(getfield(eventtmp(valnum), field))); end; if strcmpi(field, 'latency') & isempty(getfield(eventtmp(valnum), field)) eventtmp(valnum).latency = NaN; end;
github
lcnhappe/happe-master
pop_icathresh.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_icathresh.m
14,758
utf_8
365bfcb08f0dd1c0da09de203c810155
% pop_icathresh() - main menu for choosing threshold for component % rejection in EEGLAB. % % Usage: % >> [OUTEEG rej] = pop_icathresh(INEEG, threshval, rejmethod, % rejvalue, interact); % % Inputs: % INEEG - input dataset % threshval - values of thresholds for each of the 3 statistical % measures. Default is [] and the program uses the value % in the dataset. % rejmethod - either 'percent', 'dataset' or 'current'. 'percent' % will reject a given percentage of components with % the highest value in one or several statistical % measure. 'dataset' will use an other dataset for % calibration. 'current' will use the current dataset % for calibration. Default is 'current'. % rejvalue - percentage if rejmethod is 'percent', dataset number % if rejmethod is 'dataset' (no input if 'current'). If it % is a percentage, '25' for instance means that the 25% % independent components with the highest values of one % statistical measure are rejected. Note that, one can % also enter one percentage per statistical value (such as % 25 20 30). % interact - interactive windows or just rejection % % Inputs: % OUTEEG - output dataset with updated thresholds % rej - new rejection array % % Graphic interface: % The graphic interface is divided into 3 parts. On the top, the % experimenter chooses the basis for the component rejection (see % rejmethod input). On the middle panel, the user can tune thresholds % manually and plot the distribution of statistical values. Each time % that setting of one of these two top panels is modified, the curve % on the third panel are redrawn. % The third panel is composed of 3 graphs, one for each statistical % measure. The blue curve on each graph indicates the accuracy of the % measure to detect artifactual components and non-artifactual % components of a dataset. Note that 'artifactual components are % defined with the rejection methods fields on the top (if you use % the percentage methods, these artifactual components may not actually % be artifactual). For accurate rejection, one should first reject % artifactual component manually and then set up the threshold to % approximate this manual rejection. The green curve indicate the % rejection when all measure are considered. Points on the blue and % on the green curves indicate the position of the current threshold on % the parametric curve. Not that for the green cumulative curve, this % point is at the same location for all graphs. % How to tune the threshold? To tune the threshold, one should try to % maximize the detection of non-artifactual components (because it is % preferable to miss some artifactual components than to classify as % artifactual non-artifact components). % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %PROBLEM: when the % is set and we change manually yhe threshold, % the software comes back to the percentage rejection % 01-25-02 reformated help & license -ad function [EEG, rej, com] = pop_icathresh( EEG, threshval, rejmethod, rejvalue, interact); com = []; rej = EEG.reject.gcompreject; if nargin < 1 help pop_icathresh; return; end; if nargin < 2 threshval = []; end; if nargin < 3 rejmethod = 'current'; end; if nargin < 4 rejvalue = 25; end; if nargin < 5 interact = 1; end; if ~isempty(threshval) EEG.reject.threshentropy = threshval(1); EEG.reject.threshkurtact = threshval(2); EEG.reject.threshkurtdist = threshval(3); end; tagmenu = 'pop_icathresh'; if ~isempty( findobj('tag', tagmenu)) error('cannot open two identical windows, close the first one first'); end; % the current rejection will be stored in userdata of the figure % -------------------------------------------------------------- gcf = figure('visible', 'off', 'numbertitle', 'off', 'name', 'Choose thresholds', 'tag', tagmenu, 'userdata', rej); pos = get(gca, 'position'); q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]./100; axis off; % definition of callbacks % ----------------------- cb_cancel = [ 'userdat = get(gcbo, ''userdata'');' ... % restore thresholds 'EEG.reject.threshentropy = userdat{1};' ... 'EEG.reject.threshkurtact = userdat{2};' ... 'EEG.reject.threshkurtdist = userdat{3};' ... 'clear userdat; close(gcbf);' ]; drawgraphs = [ 'if isempty( gcbf ), fig = gcf; else fig = gcbf; end;' ... % determine the figure handler 'if get( findobj(''parent'', fig, ''tag'', ''Ipercent''), ''value'') == 1, ' ... % test if percentage ' perc = str2num(get( findobj(''parent'', fig, ''tag'', ''Ipercenttext''), ''String''));' ... ' if length(perc < 2), perc = [perc perc perc]; end;' ... ' perc = round((100-perc) * length( EEG.stats.compenta) / 100);' ... % convert the percentage ' method = zeros( size( EEG.stats.compenta ) );' ... ' [tmprej tmpindex] = sort(EEG.stats.compenta(:));' ... ' method( tmpindex(perc(1)+1:end) ) = 1;' ... ' set( findobj(''parent'', fig, ''tag'', ''entstring''), ''string'', num2str(tmprej(perc(1)+1)));' ... % update threshold ' [tmprej tmpindex] = sort(EEG.stats.compkurta(:));' ... ' method( tmpindex(perc(2)+1:end) ) = 1;' ... ' set( findobj(''parent'', fig, ''tag'', ''kurtstring''), ''string'', num2str(tmprej(perc(1)+1)));' ... % update threshold ' [tmprej tmpindex] = sort(EEG.stats.compkurtdist(:));' ... ' method( tmpindex(perc(3)+1:end) ) = 1;' ... ' set( findobj(''parent'', fig, ''tag'', ''kurtdiststring''), ''string'', num2str(tmprej(perc(1)+1)));' ... % update threshold ' allvalues = [EEG.stats.compenta(:) EEG.stats.compkurta(:) EEG.stats.compkurtdist(:) ];' ... ' clear perc tmprej tmpindex;' ... 'end;' ... 'if get( findobj(''parent'', fig, ''tag'', ''Iother''), ''value'') == 1, ' ... % test if other dataset ' di = str2num(get( findobj(''parent'', fig, ''tag'', ''Iothertext''), ''String''));' ... ' if isempty( di ), clear fig; return; end;' ... ' method = ALLEEG(di).reject.gcompreject'';' ... ' allvalues = [ALLEEG(di).stats.compenta(:) ALLEEG(di).stats.compkurta(:) ALLEEG(di).stats.compkurtdist(:) ];' ... ' clear di;' ... 'end;' ... 'if get( findobj(''parent'', fig, ''tag'', ''Icurrent''), ''value'') == 1, ' ... % test if current dataset ' method = EEG.reject.gcompreject'';' ... ' allvalues = [EEG.stats.compenta(:) EEG.stats.compkurta(:) EEG.stats.compkurtdist(:) ];' ... 'end;' ... 'axes( findobj( ''parent'', fig, ''tag'', ''graphent'')); cla;' ... '[tmp1 tmp2 tmp3] = drawproba( method, allvalues, [0 EEG.reject.threshkurtact EEG.reject.threshkurtdist ], ' ... ' { ''&'' ''|'' }, EEG.reject.threshentropy, ''Entropy of activity'',''Artifact detection (%)'', ''Non-artifact detection (%)'');' ... 'set(gca, ''tag'', ''graphent'');' ... 'axes( findobj( ''parent'', fig, ''tag'', ''graphkurt'')); cla;' ... '[tmp1 tmp2 tmp3] = drawproba( method, allvalues, [EEG.reject.threshentropy 0 EEG.reject.threshkurtdist ], ' ... ' { ''&'' ''|'' }, EEG.reject.threshkurtact, ''Kurtosis of activity'', ''Artifact detection (%)'', '''');' ... 'set(gca, ''tag'', ''graphkurt'');' ... 'axes( findobj( ''parent'', fig, ''tag'', ''graphkurtdist'')); cla;' ... '[tmp1 tmp2 tmp3] = drawproba( method, allvalues, [EEG.reject.threshentropy EEG.reject.threshkurtact 0 ], ' ... ' { ''&'' ''|'' }, EEG.reject.threshkurtdist, ''Kurtosis of topography'', ''Artifact detection (%)'', '''');' ... 'set(gca, ''tag'', ''graphkurtdist'');' ... 'clear method allvalues fig;' ... ]; cb_percent = [ 'if isempty( gcbf ), fig = gcf; else fig = gcbf; end;' ... % determine the figure handler 'set( findobj(''parent'', fig, ''tag'', ''Ipercent''), ''value'', 1);'... 'set( findobj(''parent'', fig, ''tag'', ''Iother''), ''value'', 0);' ... 'set( findobj(''parent'', fig, ''tag'', ''Icurrent''), ''value'', 0);' ... 'set( findobj(''parent'', fig, ''tag'', ''Ipercenttext''), ''enable'', ''on'');' ... 'set( findobj(''parent'', fig, ''tag'', ''Iothertext''), ''enable'', ''off''); clear fig;' drawgraphs ]; cb_other = [ 'if isempty( gcbf ), fig = gcf; else fig = gcbf; end;' ... % determine the figure handler 'set( findobj(''parent'', fig, ''tag'', ''Iother''), ''value'', 1);'... 'set( findobj(''parent'', fig, ''tag'', ''Ipercent''), ''value'', 0);' ... 'set( findobj(''parent'', fig, ''tag'', ''Icurrent''), ''value'', 0);' ... 'set( findobj(''parent'', fig, ''tag'', ''Ipercenttext''), ''enable'', ''off'');' ... 'set( findobj(''parent'', fig, ''tag'', ''Iothertext''), ''enable'', ''on''); clear fig;' drawgraphs ]; cb_current = [ 'if isempty( gcbf ), fig = gcf; else fig = gcbf; end;' ... % determine the figure handler 'set( findobj(''parent'', fig, ''tag'', ''Icurrent''), ''value'', 1);'... 'set( findobj(''parent'', fig, ''tag'', ''Iother''), ''value'', 0);' ... 'set( findobj(''parent'', fig, ''tag'', ''Ipercent''), ''value'', 0);' ... 'set( findobj(''parent'', fig, ''tag'', ''Ipercenttext''), ''enable'', ''off'');' ... 'set( findobj(''parent'', fig, ''tag'', ''Iothertext''), ''enable'', ''off''); clear fig;' drawgraphs ]; cb_entropy = [ 'EEG.reject.threshentropy = str2num(get(gcbo, ''string''));' ... drawgraphs ]; cb_kurtact = [ 'EEG.reject.threshkurtact = str2num(get(gcbo, ''string''));' ... drawgraphs ]; cb_kurtdist = [ 'EEG.reject.threshkurtdist = str2num(get(gcbo, ''string''));' ... drawgraphs ]; if interact cb_calrej = [ 'ButtonName=questdlg2( ''This will erase previous projections'', ''Confirmation'', ''CANCEL'', ''OK'', ''OK'');' ] else cb_calrej = [ 'ButtonName= ''OK''' ]; end; cb_calrej = [ cb_calrej ... 'switch ButtonName,' ... ' case ''OK'',' ... ' rej1 = find(EEG.stats.compenta > EEG.reject.threshentropy);' ... ' rej2 = find(EEG.stats.compkurta > EEG.reject.threshkurtact);' ... ' rej3 = find(EEG.stats.compkurtdist > EEG.reject.threshkurtdist);' ... ' EEG.reject.gcompreject = (rej1 & rej2) | rej3;' ... ' clear rej1 rej2 rej3;' ... 'end; clear ButtonName;' ]; % default value for rejection methods % ----------------------------------- rejvalother = ''; rejvalpercent = '25'; switch rejmethod case 'percent', rejvalpercent = num2str( rejvalue); case 'dataset', rejvalother = num2str( rejvalue); end; % ----------------------------------------------------- allh = supergui(gcf, { [1] ... [2 1] [2 1] [2 1] ... [1] ... [1] ... [1.5 0.5 1] [1.5 0.5 1] [1.5 0.5 1] ... [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] ... [1 1 1 1 1] ... }, [], ... { 'Style', 'text', 'string', 'Calibration method', 'FontSize', 13, 'fontweight', 'bold' }, ... ... { 'style', 'checkbox', 'String', '% of artifactual components (can also put one % per rejection)', 'tag', 'Ipercent', 'value', 1, 'callback', cb_percent}, ... { 'style', 'edit', 'String', rejvalpercent, 'tag', 'Ipercenttext', 'callback', drawgraphs }, ... ... { 'style', 'checkbox', 'String', 'Specific dataset (enter dataset number)', 'tag', 'Iother', 'value', 0, 'callback', cb_other}, ... { 'style', 'edit', 'String', rejvalother, 'tag', 'Iothertext', 'enable', 'off', 'callback', drawgraphs }, ... ... { 'style', 'checkbox', 'String', 'Current dataset', 'tag', 'Icurrent', 'value', 0, 'callback', cb_current}, ... { }, ... ... { }, ... ... { 'Style', 'text', 'string', 'Threshold values', 'FontSize', 13, 'fontweight', 'bold' }, ... ... { 'style', 'text', 'String', 'Entropy of activity threshold' }, ... { 'style', 'edit', 'String', num2str(EEG.reject.threshentropy), 'tag', 'entstring', 'callback', cb_entropy }, ... { 'style', 'pushbutton', 'String', 'Histogram', 'callback', 'figure; hist(EEG.stats.compenta,20); title(''Entropy of activity'');' }, ... ... { 'style', 'text', 'String', 'Kurtosis of activity threshold' }, ... { 'style', 'edit', 'String', num2str(EEG.reject.threshkurtact), 'tag', 'kurtstring', 'callback', cb_kurtact }, ... { 'style', 'pushbutton', 'String', 'Histogram', 'callback', 'figure; hist(EEG.stats.compkurta,200); title(''Kurtosis of activity'');' }, ... ... { 'style', 'text', 'String', 'Kurtosis of topography threshold' }, ... { 'style', 'edit', 'String', num2str(EEG.reject.threshkurtdist), 'tag', 'kurtdiststring', 'callback', cb_kurtdist }, ... { 'style', 'pushbutton', 'String', 'Histogram', 'callback', 'figure; hist(EEG.stats.compkurtdist,20); title(''Kurtosis of topography'');' }, ... ... { }, { }, { }, { }, { }, { }, { }, { }, { }, { }, ... ... { 'style', 'pushbutton', 'String', 'Cancel', 'callback', cb_cancel, 'userdata', { EEG.reject.threshentropy EEG.reject.threshkurtact EEG.reject.threshkurtdist }}, ... { 'style', 'pushbutton', 'String', 'Auto thresh' , 'callback', '', 'enable', 'off' }, ... { 'style', 'pushbutton', 'String', 'Help' , 'callback', 'pophelp(''pop_icathresh'');' }, ... { 'style', 'pushbutton', 'String', 'Accept thresh.' , 'callback', 'close(gcbf);' }, ... { 'style', 'pushbutton', 'String', 'Calc. rejection' , 'callback', 'close(gcbf);' } ... ... ); h = axes('position', [0 15 30 30].*s+q, 'tag', 'graphent'); h = axes('position', [35 15 30 30].*s+q, 'tag', 'graphkurt'); h = axes('position', [70 15 30 30].*s+q, 'tag', 'graphkurtdist'); rejmethod switch rejmethod case 'dataset', eval([ 'gcbf = [];' cb_other]); case 'current', eval([ 'gcbf = [];' cb_current]); otherwise, eval([ 'gcbf = [];' cb_percent]); end; return;
github
lcnhappe/happe-master
pop_eegthresh.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_eegthresh.m
10,919
utf_8
9d094caa6dcd548bca0d55978b85170a
% pop_eegthresh() - reject artifacts by detecting outlier values. This has % long been a standard method for selecting data to reject. % Applied either for electrode data or component activations. % Usage: % >> pop_eegthresh( INEEG, typerej); % pop-up interactive window % >> [EEG Indexes] = pop_eegthresh( INEEG, typerej, elec_comp, lowthresh, ... % upthresh, starttime, endtime, superpose, reject); % % Graphic interface: % "Electrode|Component indices(s)" - [edit box] indices of the electrode(s) or % component(s) to take into consideration. Same as the 'elec_comp' % parameter from the command line. % "Minimum rejection threshold(s)" - [edit box] lower threshold limit(s) % (in uV|std. dev.). Sets command line parameter 'lowthresh'. % "Maximum rejection threshold(s)" - [edit box] upper threshold limit(s) % (in uV|std. dev.). Sets command line parameter 'upthresh'. % "Start time limit(s)" - [edit box] starting time limit(s) (in seconds). % Sets command line parameter 'starttime'. % "End time limit(s)" - [edit box] ending time limit(s) (in seconds). % Sets command line parameter 'endtime'. % "Display previous rejection marks: " - [Checkbox]. Sets the command line % input option 'eegplotplotallrej'. % "Reject marked trials: " - [Checkbox] Sets the command line % input option 'eegplotreject'. % % Inputs: % INEEG - input EEG dataset % typerej - type of rejection (0 = independent components; 1 = raw % data). Default is 1. For independent components, before % thresholding the activations are normalized (to have std. dev. 1). % elec_comp - [e1 e2 ...] electrode|component numbers to take % into consideration for rejection % lowthresh - lower threshold limit (in uV|std. dev. For components, the % threshold(s) are in std. dev.). Can be an array if more than one % electrode|component number is given in elec_comp (above). % If fewer values than the number of electrodes|components, the % last value is used for the remaining electrodes|components. % upthresh - upper threshold limit (in uV|std dev) (see lowthresh above) % starttime - rejection window start time(s) in seconds (see lowthresh above) % endtime - rejection window end time(s) in seconds (see lowthresh) % superpose - [0|1] 0=do not superpose rejection markings on previous % rejection marks stored in the dataset: 1=show both current and % previously marked rejections using different colors. {Default: 0}. % reject - [1|0] 0=do not actually reject the marked trials (but store the % marks: 1=immediately reject marked trials. {Default: 1}. % Outputs: % Indexes - index of rejected trials % When eegplot() is called, modifications are applied to the current % dataset at the end of the call to eegplot() when the user presses % the 'Reject' button. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eegthresh(), eeglab(), eegplot(), pop_rejepoch() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-07-02 added srate argument to eegplot call -ad function [EEG, Irej, com] = pop_eegthresh( EEG, icacomp, elecrange, negthresh, posthresh, ... starttime, endtime, superpose, reject, topcommand); Irej = []; com = ''; if nargin < 1 help pop_eegthresh; return; end; if nargin < 2 icacomp = 1; end; if icacomp == 0 if isempty( EEG.icasphere ) disp('Error: you must run ICA first'); return; end; end; if exist('reject') ~= 1 reject = 1; end; if nargin < 3 % which set to save % ----------------- promptstr = { fastif(icacomp,'Electrode (indices(s), Ex: 2 4 5):' , 'Component (indices, Ex: 2 6:8 10):'), ... fastif(icacomp,'Minimum rejection threshold(s) (uV, Ex:-20 -10 -15):', 'Minimum rejection threshold(s) (std. dev, Ex: -3 -2.5 -2):'), ... fastif(icacomp,'Maximum rejection threshold(s) (uV, Ex: 20 10 15):' , 'Maximum rejection threshold(s) (std. dev, Ex: 2 2 2.5):'), ... 'Start time limit(s) (seconds, Ex -0.1 0.3):', ... 'End time limit(s) (seconds, Ex 0.2):', ... 'Display previous rejection marks', ... 'Reject marked trial(s)' }; inistr = { fastif(icacomp, ['1:' int2str(EEG.nbchan)], '1:5'), ... fastif(icacomp, '-10', '-20'), ... fastif(icacomp, '10', '20'), ... num2str(EEG.xmin), ... num2str(EEG.xmax), ... '0', ... '0' }; g1 = [1 0.1 0.75]; g2 = [1 0.22 0.85]; geometry = {g1 g1 g1 g1 g1 1 g2 g2}; uilist = {... { 'Style', 'text', 'string', promptstr{1}} {} { 'Style','edit' ,'string' ,inistr{1} 'tag' 'cpnum'}... { 'Style', 'text', 'string', promptstr{2}} {} { 'Style','edit' ,'string' ,inistr{2} 'tag' 'lowlim' }... { 'Style', 'text', 'string', promptstr{3}} {} { 'Style','edit' ,'string' ,inistr{3} 'tag' 'highlim'}... { 'Style', 'text', 'string', promptstr{4}} {} { 'Style','edit' ,'string' ,inistr{4} 'tag' 'starttime'}... { 'Style', 'text', 'string', promptstr{5}} {} { 'Style','edit' ,'string' ,inistr{5} 'tag' 'endtime'}... {}... { 'Style', 'text', 'string', promptstr{6}} {} { 'Style','checkbox' ,'string' ,' ' 'value' str2double(inistr{6}) 'tag','rejmarks' }... { 'Style', 'text', 'string', promptstr{7}} {} { 'Style','checkbox' ,'string' ,' ' 'value' str2double(inistr{7}) 'tag' 'rejtrials'} ... }; figname = fastif(icacomp == 0, 'Rejection abnormal comp. values -- pop_eegthresh()','Rejection abnormal elec. values -- pop_eegthresh()'); result = inputgui( geometry,uilist,'pophelp(''pop_eegthresh'');', figname); size_result = size( result ); if size_result(1) == 0 return; end; elecrange = result{1}; negthresh = result{2}; posthresh = result{3}; starttime = result{4}; endtime = result{5}; superpose = result{6}; reject = result{7}; end; if isstr(elecrange) % convert arguments if they are in text format calldisp = 1; elecrange = eval( [ '[' elecrange ']' ] ); negthresh = eval( [ '[' negthresh ']' ] ); posthresh = eval( [ '[' posthresh ']' ] ); if isstr(starttime) starttime = eval( [ '[' starttime ']' ] ); end; if isstr(endtime) endtime = eval( [ '[' endtime ']' ] ); end; else calldisp = 0; end; if any(starttime < EEG.xmin) fprintf('Warning : starttime inferior to minimum time, adjusted\n'); starttime(find(starttime < EEG.xmin)) = EEG.xmin; end; if any(endtime > EEG.xmax) fprintf('Warning : endtime superior to maximum time, adjusted\n'); endtime(find(endtime > EEG.xmax)) = EEG.xmax; end; if icacomp == 1 [Itmp Irej NS Erejtmp] = eegthresh( EEG.data, EEG.pnts, elecrange, negthresh, posthresh, [EEG.xmin EEG.xmax], starttime, endtime); tmpelecIout = zeros(EEG.nbchan, EEG.trials); tmpelecIout(elecrange,Irej) = Erejtmp; else icaacttmp = eeg_getdatact(EEG, 'component', elecrange); [Itmp Irej NS Erejtmp] = eegthresh( icaacttmp, EEG.pnts, 1:length(elecrange), negthresh, posthresh, [EEG.xmin EEG.xmax], starttime, endtime); tmpelecIout = zeros(size(EEG.icaweights,1), EEG.trials); tmpelecIout(elecrange,Irej) = Erejtmp; end; fprintf('%d channel selected\n', size(elecrange(:), 1)); fprintf('%d/%d trials marked for rejection\n', length(Irej), EEG.trials); tmprejectelec = zeros( 1, EEG.trials); tmprejectelec(Irej) = 1; rej = tmprejectelec; rejE = tmpelecIout; if calldisp if icacomp == 1 macrorej = 'EEG.reject.rejthresh'; macrorejE = 'EEG.reject.rejthreshE'; else macrorej = 'EEG.reject.icarejthresh'; macrorejE = 'EEG.reject.icarejthreshE'; end; colrej = EEG.reject.rejthreshcol; eeg_rejmacro; % script macro for generating command and old rejection arrays if icacomp == 1 eegplot( EEG.data(elecrange,:,:), 'srate', EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}); else eegplot( icaacttmp, 'srate', EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}); end; else if reject == 1 EEG = pop_rejepoch(EEG, rej, 0); end; end; if ~isempty(rej) if icacomp == 1 EEG.reject.rejthresh = rej; EEG.reject.rejthreshE = rejE; else EEG.reject.icarejthresh = rej; EEG.reject.icarejthreshE = rejE; end; end; %com = sprintf('Indexes = pop_eegthresh( %s, %d, [%s], [%s], [%s], [%s], [%s], %d, %d);', ... % inputname(1), icacomp, num2str(elecrange), num2str(negthresh), ... % num2str(posthresh), num2str(starttime ) , num2str(endtime), superpose, reject ); com = [ com sprintf('%s = pop_eegthresh(%s,%s);', inputname(1), ... inputname(1), vararg2str({icacomp,elecrange,negthresh,posthresh,starttime,endtime,superpose,reject})) ]; if nargin < 3 Irej = com; end; return; % reject artifacts in a sequential fashion to save memory (ICA ONLY) % ------------------------------------------------------- function [Irej, Erej] = thresh( data, elecrange, timerange, negthresh, posthresh, starttime, endtime); Irej = []; Erej = zeros(size(data,1), size(data,2)); for index = 1:length(elecrange) tmpica = data(index,:,:); tmpica = reshape(tmpica, 1, size(data,2)*size(data,3)); % perform the rejection % --------------------- tmpica = (tmpica-mean(tmpica,2)*ones(1,size(tmpica,2)))./ (std(tmpica,0,2)*ones(1,size(tmpica,2))); [I1 Itmprej NS Etmprej] = eegthresh( tmpica, size(data,2), 1, negthresh, posthresh, ... timerange, starttime, endtime); Irej = union_bc(Irej, Itmprej); Erej(elecrange(index),Itmprej) = Etmprej; end;
github
lcnhappe/happe-master
pop_timef.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_timef.m
8,964
utf_8
479d128417dbb0d8ab96a1795c580e3b
% pop_timef() - Returns estimates and plots of event-related (log) spectral % perturbation (ERSP) and inter-trial coherence (ITC) changes % timelocked to a set of input events in one data channel. % % Usage: % >> pop_timef(EEG, typeplot); % pop_up window % >> pop_timef(EEG, typeplot, lastcom); % pop_up window % >> pop_timef(EEG, typeplot, channel); % do not pop-up % >> pop_timef(EEG, typeproc, num, tlimits,cycles, % 'key1',value1,'key2',value2, ... ); % % Inputs: % INEEG - input EEG dataset % typeproc - type of processing. 1 process the raw % data and 0 the ICA components % num - component or channel number % tlimits - [mintime maxtime] (ms) sub-epoch time limits % cycles - >0 -> Number of cycles in each analysis wavelet % 0 -> Use FFTs (with constant window length) % % Optional inputs: % See the timef() function. % % Outputs: same as timef(), no outputs are returned when a % window pops-up to ask for additional arguments % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: timef(), eeglab() % Copyright (C) 2002 [email protected], Arnaud Delorme, CNL / Salk Institute % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-08-02 add eeglab option & optimize variable sizes -ad % 03-10-02 change timef call -ad % 03-18-02 added title -ad & sm % 04-04-02 added outputs -ad & sm function varargout = pop_timef(EEG, typeproc, num, tlimits, cycles, varargin ); varargout{1} = ''; % display help if not enough arguments % ------------------------------------ if nargin < 2 help pop_timef; return; end; lastcom = []; if nargin < 3 popup = 1; else popup = isstr(num) | isempty(num); if isstr(num) lastcom = num; end; end; % pop up window % ------------- if popup [txt vars] = gethelpvar('timef.m'); geometry = { [1 0.5 0.5] [1 0.5 0.5] [1 0.5 0.5] [0.92 0.1 0.78] [1 0.5 0.5] [1 0.8 0.2] [1] [1 1]}; uilist = { ... { 'Style', 'text', 'string', fastif(typeproc, 'Channel number', 'Component number'), 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,3,[],'1') } {} ... { 'Style', 'text', 'string', 'Epoch time range [min max] (msec)', 'fontweight', 'bold', ... 'tooltipstring', 'Sub epoch time limits' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,4,[],[ int2str(EEG.xmin*1000) ' ' int2str(EEG.xmax*1000) ]) } {} ... { 'Style', 'text', 'string', 'Wavelet cycles (0->FFT, see >> help timef)', 'fontweight', 'bold', ... 'tooltipstring', context('cycles',vars,txt) } ... { 'Style', 'edit', 'string', getkeyval(lastcom,5,[],'3 0.5') } {} ... { 'Style', 'text', 'string', '[set]->Linear coher / [unset]->Phase coher', 'fontweight', 'bold', ... 'tooltipstring', ['Compute linear inter-trial coherence (coher)' 10 ... 'OR Amplitude-normalized inter-trial phase coherence (phasecoher)'] } ... { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'phasecoher','present',1) } { } ... { 'Style', 'text', 'string', 'Bootstrap significance level (Ex: 0.01 -> 1%)', 'fontweight', 'bold', ... 'tooltipstring', context('alpha',vars,txt) } ... { 'Style', 'edit', 'string', getkeyval(lastcom,'alpha') } {} ... { 'Style', 'text', 'string', 'Optional timef() arguments (see Help)', 'fontweight', 'bold', ... 'tooltipstring', 'See timef() help via the Help button on the right...' } ... { 'Style', 'edit', 'string', '''padratio'', 4, ''plotphase'',''off''' } ... { 'Style', 'pushbutton', 'string', 'Help', 'callback', 'pophelp(''timef'');' } ... {} ... { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotersp','present',0), 'string', ... 'Plot Event Related Spectral Power', 'tooltipstring', ... 'Plot log spectral perturbation image in the upper panel' } ... { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotitc','present',0), 'string', ... 'Plot Inter Trial Coherence', 'tooltipstring', ... 'Plot the inter-trial coherence image in the lower panel' } ... }; % { 'Style', 'edit', 'string', '''padratio'', 4, ''plotphase'', ''off''' } ... %{ 'Style', 'text', 'string', '[set] -> Plot ITC phase sign', 'fontweight', 'bold', ... % 'tooltipstring', ['Plot the sign (+/-) of inter-trial coherence phase' 10 ... % 'as red (+) or blue (-)'] } ... % { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotphase','present',1) } { } ... result = inputgui( geometry, uilist, 'pophelp(''pop_timef'');', ... fastif(typeproc, 'Plot channel time frequency -- pop_timef()', ... 'Plot component time frequency -- pop_timef()')); if length( result ) == 0 return; end; num = eval( [ '[' result{1} ']' ] ); tlimits = eval( [ '[' result{2} ']' ] ); cycles = eval( [ '[' result{3} ']' ] ); if result{4} options = [ ',''type'', ''coher''' ]; else options = [',''type'', ''phasecoher''' ]; end; % add topoplot % ------------ if isfield(EEG.chanlocs, 'theta') if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end; if typeproc == 1 options = [options ', ''topovec'', ' int2str(num) ... ', ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ]; else options = [options ', ''topovec'', EEG.icawinv(:,' int2str(num) ... '), ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ]; end; end; % add title % --------- if isempty( findstr( '''title''', result{6})) if ~isempty(EEG.chanlocs) & typeproc chanlabel = EEG.chanlocs(num).labels; else chanlabel = int2str(num); end; switch lower(result{4}) case 'coher', options = [options ', ''title'',' fastif(typeproc, '''Channel ', '''Component ') chanlabel ... ' power and inter-trial coherence' fastif(~ isempty(EEG.setname), [' (' EEG.setname ')''' ], '''') ]; otherwise, options = [options ', ''title'',' fastif(typeproc, '''Channel ', '''Component ') chanlabel ... ' power and inter-trial phase coherence' fastif(~ isempty(EEG.setname), [' (' EEG.setname ')''' ], '''') ]; end; end; if ~isempty( result{5} ) options = [ options ', ''alpha'',' result{5} ]; end; if ~isempty( result{6} ) options = [ options ',' result{6} ]; end; if ~result{7} options = [ options ', ''plotersp'', ''off''' ]; end; if ~result{8} options = [ options ', ''plotitc'', ''off''' ]; end; figure; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; else options = [ ',' vararg2str(varargin) ]; end; % compute epoch limits % -------------------- if isempty(tlimits) tlimits = [EEG.xmin, EEG.xmax]*1000; end; pointrange1 = round(max((tlimits(1)/1000-EEG.xmin)*EEG.srate, 1)); pointrange2 = round(min((tlimits(2)/1000-EEG.xmin)*EEG.srate, EEG.pnts)); pointrange = [pointrange1:pointrange2]; % call function sample either on raw data or ICA data % --------------------------------------------------- if typeproc == 1 tmpsig = EEG.data(num,pointrange,:); else if ~isempty( EEG.icasphere ) tmpsig = eeg_getdatact(EEG, 'component', num, 'samples', pointrange); else error('You must run ICA first'); end; end; % outputs % ------- outstr = ''; if ~popup for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end; if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end; end; % plot the datas and generate output command % -------------------------------------------- if length( options ) < 2 options = ''; end; if nargin < 4 varargout{1} = sprintf('figure; pop_timef( %s, %d, %d, %s, %s %s);', inputname(1), typeproc, num, ... vararg2str({tlimits}), vararg2str({cycles}), options); end; com = sprintf('%s timef( tmpsig(:, :), length(pointrange), [tlimits(1) tlimits(2)], EEG.srate, cycles %s);', outstr, options); eval(com) return; % get contextual help % ------------------- function txt = context(var, allvars, alltext); loc = strmatch( var, allvars); if ~isempty(loc) txt= alltext{loc(1)}; else disp([ 'warning: variable ''' var ''' not found']); txt = ''; end;
github
lcnhappe/happe-master
eeg_chantype.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_chantype.m
2,353
utf_8
cc106eb578fad38a9d0ce04e66c68cc5
% eeg_chantype() - Returns the channel indices of the desired channel type(s). % % Usage: % >> indices = eeg_chantype(struct, types ) % % Inputs: % struct - EEG.chanlocs data structure returned by readlocs() containing % channel location, type and gain information. % % Optional input % types - [cell array] cell array containing types ... % % Output: % indices - % % Author: Toby Fernsler, Arnaud Delorme, Scott Makeig % % See also: topoplot() % Copyright (C) 2005 Toby Fernsler, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function indices = eeg_chantype(data,chantype) if nargin < 1 help eeg_chantype; end; if ischar(chantype), chantype = cellstr(chantype); end if ~iscell(chantype), error( 'chantype must be cell array, e.g. {''EEG'', ''EOG''}, or single character string, e.g.''EEG''.'); end % Define 'datatype' variable, listing the type of each channel. % ------------------------------------------------------------ if isfield(data,'type') datatype = {data.type}; elseif isfield(data,'chanlocs') & isfield(data.chanlocs,'type') datatype = {data.chanlocs.type}; else error('Incorrect ''data'' input. Should be ''EEG'' or ''loc_file'' structure variable in the format associated with EEGLAB.'); end % seach for types % --------------- k = 1; plotchans = []; for i = 1:length(chantype) for j = 1:length(datatype) if strcmpi(chantype{i},char(datatype{j})) plotchans(k) = j; k = k + 1; end; end end indices = sort(plotchans);
github
lcnhappe/happe-master
eeg_eegrej.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_eegrej.m
7,999
utf_8
3b125781cbf3005ebe8633b783f823ce
% eeg_eegrej() - reject porition of continuous data in an EEGLAB % dataset % % Usage: % >> EEGOUT = eeg_eegrej( EEGIN, regions ); % % Inputs: % INEEG - input dataset % regions - array of regions to suppress. number x [beg end] of % regions. 'beg' and 'end' are expressed in term of points % in the input dataset. Size of the array is % number x 2 of regions. % % Outputs: % INEEG - output dataset with updated data, events latencies and % additional boundary events. % % Author: Arnaud Delorme, CNL / Salk Institute, 8 August 2002 % % See also: eeglab(), eegplot(), pop_rejepoch() % Copyright (C) 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, com] = eeg_eegrej( EEG, regions); com = ''; if nargin < 2 help eeg_eegrej; return; end; if nargin<3 probadded = []; end if isempty(regions) return; end; % regions = sortrows(regions,3); % Arno and Ramon on 5/13/2014 for bug 1605 % Ramon on 5/29/2014 for bug 1619 if size(regions,2) > 2 regions = sortrows(regions,3); else regions = sortrows(regions,1); end; try % For AMICA probabilities...Temporarily add model probabilities as channels %----------------------------------------------------- if isfield(EEG.etc, 'amica') && ~isempty(EEG.etc.amica) && isfield(EEG.etc.amica, 'v_smooth') && ~isempty(EEG.etc.amica.v_smooth) && ~isfield(EEG.etc.amica,'prob_added') if isfield(EEG.etc.amica, 'num_models') && ~isempty(EEG.etc.amica.num_models) if size(EEG.data,2) == size(EEG.etc.amica.v_smooth,2) && size(EEG.data,3) == size(EEG.etc.amica.v_smooth,3) && size(EEG.etc.amica.v_smooth,1) == EEG.etc.amica.num_models EEG = eeg_formatamica(EEG); %------------------------------------------- [EEG com] = eeg_eegrej(EEG,regions); %------------------------------------------- EEG = eeg_reformatamica(EEG); EEG = eeg_checkamica(EEG); return; else disp('AMICA probabilities not compatible with size of data, probabilities cannot be epoched') disp('Load AMICA components before extracting epochs') disp('Resuming rejection...') end end end % ------------------------------------------------------ catch warnmsg = strcat('your dataset contains amica information, but the amica plugin is not installed. Continuing and ignoring amica information.'); warning(warnmsg) end if isfield(EEG.event, 'latency'), tmpevent = EEG.event; tmpdata = EEG.data; % REMOVE THIS, THIS IS FOR DEBUGGING % tmpalllatencies = [ tmpevent.latency ]; else tmpalllatencies = []; end; % handle regions from eegplot % --------------------------- if size(regions,2) > 2, regions = regions(:, 3:4); end; regions = combineregions(regions); [EEG.data, EEG.xmax, event2, boundevents] = eegrej( EEG.data, regions, EEG.xmax-EEG.xmin, EEG.event); oldEEGpnts = EEG.pnts; EEG.pnts = size(EEG.data,2); EEG.xmax = EEG.xmax+EEG.xmin; % add boundary events % ------------------- [ eventtmp ] = eeg_insertboundold(EEG.event, oldEEGpnts, regions); [ EEG.event ] = eeg_insertbound(EEG.event, oldEEGpnts, regions); EEG = eeg_checkset(EEG, 'eventconsistency'); % assess difference between old and new event latencies differs = 0; for iEvent=1:min(length(EEG.event), length(eventtmp)-1) if ~issameevent(EEG.event(iEvent), eventtmp(iEvent)) && ~issameevent(EEG.event(iEvent), eventtmp(iEvent+1)) differs = differs+1; end; end; if 100*differs/length(EEG.event) > 50 fprintf(['BUG 1971 WARNING: IF YOU ARE USING A SCRIPT WITTEN FOR A PREVIOUS VERSION OF\n' ... 'EEGLAB TO CALL THIS FUNCTION, BECAUSE YOU ARE REJECTING THE ONSET OF THE DATA,\n' ... 'EVENTS WERE CORRUPTED. EVENT LATENCIES ARE NOW CORRECT (SEE https://sccn.ucsd.edu/wiki/EEGLAB_bug1971);\n' ]); end; % double check event latencies % the function that insert boundary events and recompute latency is % delicate so we do it twice using different methods and check % the results. It is longer, but accuracy is paramount. if isfield(EEG.event, 'latency') alllats = [ EEG.event.latency ]; otherlatencies = [event2.latency]; if ~isequal(alllats, otherlatencies) error([ 'Discrepency when recomputing event latency.' 10 'Try to reproduce the problem and send us your dataset' ]); end; end; % double check boundary event latencies if ~isempty(EEG.event) && ischar(EEG.event(1).type) && isfield(EEG.event, 'duration') && isfield(event2, 'duration') indBound1 = strmatch('boundary', { EEG.event(:).type }); indBound2 = strmatch('boundary', { event2(:).type }); duration1 = [EEG.event(indBound1).duration]; duration1(isnan(duration1)) = []; duration2 = [event2(indBound2).duration]; duration2(isnan(duration2)) = []; if ~isequal(duration1, duration2) error(['Inconsistency in boundary event duration.' 10 'Try to reproduce the problem and send us your dataset' ]); end; end; % debuging code below % regions, n1 = 1525; n2 = 1545; n = n2-n1+1; % a = zeros(1,n); a(:) = 1; a(strmatch('boundary', { event2(n1:n2).type })') = 8; % [[n1:n2]' alllats(n1:n2)' [event2(n1:n2).latency]' alllats(n1:n2)'-[event2(n1:n2).latency]' otherorilatencies(n1:n2)' a'] % figure; ev = 17; range = [-1000:1000]; plot(EEG.data(1,EEG.event(ev).latency+range)); hold on; plot(tmpdata(1,tmpevent(EEG.event(ev).urevent).latency+range+696), 'r'); grid on; com = sprintf('%s = eeg_eegrej( %s, %s);', inputname(1), inputname(1), vararg2str({ regions })); % combine regions if necessary % it should not be necessary but a % bug in eegplot makes that it sometimes is % ---------------------------- % function newregions = combineregions(regions) % newregions = regions; % for index = size(regions,1):-1:2 % if regions(index-1,2) >= regions(index,1) % disp('Warning: overlapping regions detected and fixed in eeg_eegrej'); % newregions(index-1,:) = [regions(index-1,1) regions(index,2) ]; % newregions(index,:) = []; % end; % end; function res = issameevent(evt1, evt2) res = true; if isequal(evt1,evt2) return; elseif isfield(evt1, 'duration') && isnan(evt1.duration) && isfield(evt2, 'duration') && isnan(evt2.duration) evt1.duration = 1; evt2.duration = 1; if isequal(evt1,evt2) return; end; end; res = false; return; function newregions = combineregions(regions) % 9/1/2014 RMC regions = sortrows(sort(regions,2)); % Sorting regions allreg = [ regions(:,1)' regions(:,2)'; ones(1,numel(regions(:,1))) -ones(1,numel(regions(:,2)')) ].'; allreg = sortrows(allreg,1); % Sort all start and stop points (column 1), mboundary = cumsum(allreg(:,2)); % Rationale: regions will start always with 1 and close with 0, since starts=1 end=-1 indx = 0; count = 1; while indx ~= length(allreg) newregions(count,1) = allreg(indx+1,1); [tmp,I]= min(abs(mboundary(indx+1:end))); newregions(count,2) = allreg(I + indx,1); indx = indx + I ; count = count+1; end % Verbose if size(regions,1) ~= size(newregions,1) disp('Warning: overlapping regions detected and fixed in eeg_eegrej'); end
github
lcnhappe/happe-master
eeg_point2lat.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_point2lat.m
3,118
utf_8
e0dbc1311eceee071f6dcfb1dfcfb9bb
% eeg_point2lat() - convert latency in data points to latency in ms relative % to the time locking. Used in eeglab(). % Usage: % >> [newlat ] = eeg_point2lat( lat_array, [], srate); % >> [newlat ] = eeg_point2lat( lat_array, epoch_array,... % srate, timelimits, timeunit); % Inputs: % lat_array - latency array in data points assuming concatenated % data epochs (see eeglab() event structure) % epoch_array - epoch number corresponding to each latency value % srate - data sampling rate in Hz % timelimits - [min max] timelimits in 'timeunit' units (see below) % timeunit - time unit in second. Default is 1 = seconds. % % Outputs: % newlat - converted latency values (in 'timeunit' units) for each epoch % % Example: % tmpevent = EEG.event; % eeg_point2lat( [ tmpevent.latency ], [], EEG.srate, [EEG.xmin EEG.xmax]); % % returns the latency of all events in second for a continuous % % dataset EEG % % eeg_point2lat( [ tmpevent.latency ], [ tmpevent.epoch ], % EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3); % % returns the latency of all events in millisecond for a dataset % % containing data epochs. % % % Author: Arnaud Delorme, CNL / Salk Institute, 2 Mai 2002 % % See also: eeg_lat2point(), eeglab(), pop_editieventvals(), pop_loaddat() % Copyright (C) 2 Mai 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function newlat = eeg_point2lat( lat_array, epoch_array, srate, timewin, timeunit); if nargin <3 help eeg_point2lat; return; end; if isempty( epoch_array ) epoch_array = ones( size(lat_array) ); end; if nargin <4 timewin = 0; end; if nargin <5 timeunit = 1; end; if length(lat_array) ~= length(epoch_array) if length(epoch_array)~= 1 disp('eeg_point2lat: latency and epoch arrays must have the same length'); return; else epoch_array = ones(1,length(lat_array))*epoch_array; end; end; if length(timewin) ~= 2 disp('eeg_point2lat: timelimits array must have length 2'); return; end; if iscell(epoch_array) epoch_array = [ epoch_array{:} ]; end; if iscell(lat_array) lat_array = [ lat_array{:} ]; end timewin = timewin*timeunit; if length(timewin) == 2 pnts = (timewin(2)-timewin(1))*srate+1; else pnts = 0; end; newlat = ((lat_array - (epoch_array-1)*pnts-1)/srate+timewin(1))/timeunit; newlat = round(newlat*1E9)*1E-9;
github
lcnhappe/happe-master
pop_averef.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_averef.m
2,591
utf_8
13d6362c4bcdd4d0c831e5b62379549f
% pop_averef() - Convert an EEG dataset to average reference. % This function is obsolete. See pop_reref() instead. % % Usage: % >> EEGOUT = pop_averef( EEG ); % % Author: Arnaud Delorme, CNL / Salk Institute, 22 March 2002 % % See also: eeglab(), reref(), averef() % Copyright (C) 22 March 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, com] = pop_averef( EEG, confirm); [EEG, com] = pop_reref(EEG, []); return; com = ''; if nargin < 1 help pop_averef; return; end; if isempty(EEG.data) error('Pop_averef: cannot process empty data'); end; if nargin < 2 | confirm == 1 % which set to save % ----------------- ButtonName=questdlg2( strvcat('Convert the data to average reference?', ... 'Note: ICA activations will also be converted if they exist...'), ... 'Average reference confirmation -- pop_averef()', 'Cancel', 'Yes','Yes'); switch lower(ButtonName), case 'cancel', return; end; confirm = 0; end; EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts*EEG.trials); if ~isempty(EEG.icaweights) disp('pop_averef(): converting ICA weight matrix to average reference (see >> help averef)'); [EEG.data EEG.icaweights EEG.icasphere EEG.rmave] = averef(EEG.data,EEG.icaweights,EEG.icasphere); EEG.icawinv = []; if size(EEG.icaweights,1) > EEG.nbchan disp('Warning: one or more channels may have been removed; component weight re-referencing may be inaccurate'); end; if size(EEG.icasphere,1) < EEG.nbchan disp('Warning: one or more components may have been removed; component weight re-referencing could be inaccurate'); end; else EEG.data = averef(EEG.data); end; EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts, EEG.trials); EEG.averef = 'Yes'; EEG.icaact = []; EEG = eeg_checkset(EEG); com = sprintf('%s = pop_averef( %s, %d);', inputname(1), inputname(1), confirm); return;
github
lcnhappe/happe-master
eeg_matchchans.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_matchchans.m
5,088
utf_8
070c5b272529f4f74dc88932ce5baa77
% eeg_matchchans() - find closest channels in a larger EEGLAB chanlocs structure % to channels in a smaller chanlocs structure % Usage: % >> [selchans,distances,selocs] = eeg_matchchans(BIGlocs,smalllocs,'noplot'); % Inputs: % BIGlocs - larger (or equal-sized) EEG.chanlocs structure array % smalllocs - smaller (or equal-sized) EEG.chanlocs structure array % Optional inputs: % 'noplot' - [optional string 'noplot'] -> do not produce plots {default: % produce illustrative plots of the BIG and small locations} % Outputs: % selchans - indices of BIGlocs channels closest to the smalllocs channels % distances - vector of distances between the selected BIGlocs and smalllocs chans % selocs - EEG.chanlocs structure array containing nearest BIGlocs channels % to each smalllocs channel: 1, 2, 3,... n. This structure has % two extra fields: % bigchan - original channel index in BIGlocs % bigdist - distance between bigchan and smalllocs chan % ==> bigdist assumes both input locs have sph_radius 1. % % Author: Scott Makeig, SCCN/INC/UCSD, April 9, 2004 % Copyright (C) 2004 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % History: began Jan 27, 2004 as selectchans.m(?) -sm function [selchans,dists,selocs] = eeg_matchchans(bglocs,ltlocs,noplot) if nargin < 2 help eeg_matchchans return end no_plot = 0; % yes|no flag if nargin > 2 & strcmp(lower(noplot),'noplot') no_plot = 1; end if ~isstruct(bglocs) | ~isstruct(ltlocs) help eeg_matchchans end ltchans = length(ltlocs); bgchans = length(bglocs); if ltchans > bgchans fprintf('BIGlocs chans (%d) < smalllocs chans (%d)\n',bgchans,ltchans); return end selchans = zeros(ltchans,1); dists = zeros(ltchans,1); bd = zeros(bgchans,1); % %%%%%%%%%%%%%%%%% Compute the distances %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fprintf('BIG ltl Dist\n'); for c=1:ltchans for C=1:bgchans if ~isempty(ltlocs(c).X) & ~isempty(bglocs(C).X) bd(C) = sqrt((ltlocs(c).X/ltlocs(c).sph_radius - bglocs(C).X/bglocs(C).sph_radius)^2 + ... (ltlocs(c).Y/ltlocs(c).sph_radius - bglocs(C).Y/bglocs(C).sph_radius)^2 + ... (ltlocs(c).Z/ltlocs(c).sph_radius - bglocs(C).Z/bglocs(C).sph_radius)^2); end end % %%%%%%%%%%%%%%%%% Find the nearest BIGlocs channel %%%%%%%%%%%%%%%%%%%%%%% % [bd ix] = sort(bd); % find smallest distance c <-> C bglocs(1).bigchan = []; k=1; while ~isempty(bglocs(ix(k)).bigchan) & k<=bgchans % avoid empty channels k=k+1; end if k>bgchans fprintf('No match found for smalllocs channel %d - error!?\n',c); return % give up - should not reach here! end while k<length(ix) if c>1 & sum(ismember(ix(k),selchans(1:c-1)))>0 % avoid chans already chosen k = k+1; else break end end if k==length(ix) fprintf('NO available nearby channel for littlechan %d - using %d\n',... c,ix(k)); end selchans(c) = ix(k); % note the nearest BIGlocs channel dists(c) = bd(k); % note its distance bglocs(ix(k)).bigchan = selchans(c); % add this info to the output bglocs(ix(k)).bigdist = dists(c); fprintf('.bigchan %4d, c %4d, k %d, .bigdist %3.2f\n',... bglocs(ix(k)).bigchan,c,k,bglocs(ix(k)).bigdist); % commandline printout end; % c selocs = bglocs(selchans); % return the selected BIGlocs struct array subset % %%%%%%%%%%%%%%%%% Plot the results %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if ~no_plot figure; titlestring = sprintf('%d-channel subset closest to %d channel locations',ltchans,bgchans); tl=textsc(titlestring,'title'); set(tl,'fontweight','bold'); set(tl,'fontsize',15); sbplot(7,2,[3 13]); hist(dists,length(dists)); title('Distances between corresponding channels'); xlabel('Euclidian distance (sph. rad. 1)'); ylabel('Number of channels'); sbplot(7,5,[8,35]); topoplot(dists,selocs,'electrodes','numbers','style','both'); title('Distances'); clen = size(colormap,1); sbnull = sbplot(7,2,[10 12]) cb=cbar; cbar(cb,[clen/2+1:clen]); set(sbnull,'visible','off') axcopy; % turn on axcopy end
github
lcnhappe/happe-master
eeg_insertbound.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_insertbound.m
5,043
utf_8
a3e502740369f695218d0309e13a6578
% eeg_insertbound() - insert boundary event in an EEG event structure. % % Usage: % >> [eventout indnew] = eeg_insertbound( eventin, pnts, ... % abslatency, duration); % Required Inputs: % eventin - EEGLAB event structure (EEG.event) % pnts - data points in EEG dataset (EEG.pnts * EEG.trials) % abslatency - absolute latency of regions in original dataset. Can % also be an array of [beg end] latencies with one row % per region removed. Then 'lengths' argument is ignored. % Optional Inputs: % lengths - lengths of removed regions % % Outputs: % eventout - EEGLAB event output structure with added boundaries % indnew - Indices of the new events % % Notes: % This function performs the following: % 1) add boundary events to the 'event' structure; % remove nested boundaries; % recompute the latencies of all events. % 2) all latencies are given in (float) data points. % e.g., a latency of 2000.3 means 0.3 samples (at EEG.srate) % after the 2001st data frame (since first frame has latency 0). % % Author: Arnaud Delorme and Hilit Serby, SCCN, INC, UCSD, April, 19, 2004 % % See also: eeg_eegrej(), pop_mergeset() % Copyright (C) 2004 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [eventin, newind] = eeg_insertbound( eventin, pnts, regions, lengths) if nargin < 3 help eeg_insertbound; return; end; regions = round(regions); regions(regions < 1) = 1; regions(regions > pnts) = pnts; for i=2:size(regions,1) if regions(i-1,2) >= regions(i,1) regions(i,1) = regions(i-1,2)+1; end; end; if ~isempty(regions) fprintf('eeg_insertbound(): %d boundary (break) events added.\n', size(regions, 1)); else return; end; % recompute latencies of boundevents (in new dataset) % --------------------------------------------------- [tmp, tmpsort] = sort(regions(:,1)); regions = regions(tmpsort,:); lengths = regions(:,2)-regions(:,1)+1; if ~isempty(eventin) eventLatencies = [ eventin.latency ]; else eventLatencies = []; end; newEventLatencies = eventLatencies; oriLen = length(eventin); rmEvent = []; for iRegion = 1:size(regions,1) % sorted in decreasing order % find event succeding boundary to insert event % at the correct location in the event structure % ---------------------------------------------- tmpind = find( eventLatencies - regions(iRegion,1) > 0 ); newEventLatencies(tmpind) = newEventLatencies(tmpind)-lengths(iRegion); % insert event % ------------ [tmpnest, addlength ] = findnested(eventin, eventLatencies, regions(iRegion,:)); rmEvent = [ rmEvent tmpnest ]; if regions(iRegion,1)>1 eventin(end+1).type = 'boundary'; eventin(end).latency = regions(iRegion,1)-sum(lengths(1:iRegion-1))-0.5; eventin(end).duration = lengths(iRegion,1)+addlength; end; end % copy latencies % -------------- for iEvent = 1:oriLen eventin(iEvent).latency = newEventLatencies(iEvent); end; eventin(rmEvent) = []; % resort events % ------------- if ~isempty(eventin) && isfield(eventin, 'latency') eventin([ eventin.latency ] < 1) = []; alllatencies = [ eventin.latency ]; [tmp, sortind] = sort(alllatencies); eventin = eventin(sortind); newind = sortind(oriLen+1:end); end; if ~isempty(rmEvent) fprintf('eeg_insertbound(): event latencies recomputed and %d events removed.\n', length(rmEvent)); end; % look for nested events % retrun indices of nested events and % their total length % ----------------------------------- function [ indEvents, addlen ] = findnested(event, eventlat, region) indEvents = find( eventlat > region(1) & eventlat < region(2)); if ~isempty(event) && isstr(event(1).type) && isfield(event, 'duration') boundaryInd = strmatch('boundary', { event(indEvents).type }); addlen = sum( [ event(indEvents(boundaryInd)).duration ] ); else addlen = 0; end;
github
lcnhappe/happe-master
pop_reref.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_reref.m
12,991
utf_8
14d26bdeeaca5ad12a0890e8f01c25df
% pop_reref() - Convert an EEG dataset to average reference or to a % new common reference channel (or channels). Calls reref(). % Usage: % >> EEGOUT = pop_reref( EEG ); % pop up interactive window % >> EEGOUT = pop_reref( EEG, ref, 'key', 'val' ...); % % Graphic interface: % "Compute average reference" - [edit box] Checking this box (for 'yes') is % the same as giving an empty value for the commandline 'ref' % argument. Unchecked, the data are transformed to common reference. % "Re-reference data to channel(s)" - [checkbox] Checking this option % automatically unchecks the checkbox above, allowing reference % channel indices to be entered in the text edit box to its right % (No commandline equivalent). % "Retain old reference channels in data" - [checkbox] When re-referencing the % data, checking this checkbox includes the data for the % previous reference channel. % "Exclude channel indices (EMG, EOG)" - [edit box] exclude the given % channel indices from rereferencing. % "Add current reference channel back to the data" - [edit box] When % re-referencing the data, checking this checkbox % reconstitutes the data for the previous reference % channel. If the location for this channel was not % defined, it can be specified using the text box below. % Inputs: % EEG - input dataset % ref - reference: [] = convert to average reference % [int vector] = new reference electrode number(s) % Optional inputs: % 'exclude' - [integer array] List of channels to exclude. Default: none. % 'keepref' - ['on'|'off'] keep the reference channel. Default: 'off'. % 'refloc' - [structure] Previous reference channel structure. Default: none. % % Outputs: % EEGOUT - re-referenced output dataset % % Notes: % For other options, call reref() directly. See >> help reref % % Author: Arnaud Delorme, CNL / Salk Institute, 12 Nov 2002 % % See also: reref(), eeglab() % Copyright (C) 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, com] = pop_reref( EEG, ref, varargin); com = ''; if nargin < 1 help pop_reref; return; end; if isempty(EEG.data) error('Pop_reref: cannot process empty data'); end; % gui inputs % ---------- orichanlocs = EEG.chanlocs; orinbchan = EEG.nbchan; if nargin < 2 % find initial reference % ---------------------- if length(EEG.chanlocs) == EEG.nbchan+1 includeref = 1; end; geometry = { [1] [1] [1.8 1 0.3] [1] [1] [1.8 1 0.3] [1.8 1 0.3] }; cb_setref = [ 'set(findobj(''parent'', gcbf, ''tag'', ''refbr'') , ''enable'', ''on'');' ... 'set(findobj(''parent'', gcbf, ''tag'', ''reref'') , ''enable'', ''on'');' ... 'set(findobj(''parent'', gcbf, ''tag'', ''keepref'') , ''enable'', ''on'');' ]; cb_setave = [ 'set(findobj(''parent'', gcbf, ''tag'', ''refbr'') , ''enable'', ''off'');' ... 'set(findobj(''parent'', gcbf, ''tag'', ''reref'') , ''enable'', ''off'');' ... 'set(findobj(''parent'', gcbf, ''tag'', ''keepref'') , ''enable'', ''off'', ''value'', 0);' ]; cb_averef = [ 'set(findobj(''parent'', gcbf, ''tag'', ''rerefstr'') , ''value'', ~get(gcbo, ''value''));' ... 'if get(gcbo, ''value''),' cb_setave ... 'else,' cb_setref ... 'end;' ]; cb_ref = [ 'set(findobj(''parent'', gcbf, ''tag'', ''ave'') , ''value'', ~get(gcbo, ''value''));' ... 'if get(gcbo, ''value''),' cb_setref ... 'else,' cb_setave ... 'end;' ]; cb_chansel1 = 'tmpchanlocs = EEG(1).chanlocs; [tmp tmpval] = pop_chansel({tmpchanlocs.labels}, ''withindex'', ''on''); set(findobj(gcbf, ''tag'', ''reref'' ), ''string'',tmpval); clear tmpchanlocs tmp tmpval'; cb_chansel2 = 'tmpchanlocs = EEG(1).chanlocs; [tmp tmpval] = pop_chansel({tmpchanlocs.labels}, ''withindex'', ''on''); set(findobj(gcbf, ''tag'', ''exclude'' ), ''string'',tmpval); clear tmpchanlocs tmp tmpval'; cb_chansel3 = [ 'if ~isfield(EEG(1).chaninfo, ''nodatchans''), ' ... ' warndlg2(''There are no Reference channel defined, add it using the channel location editor'');' ... 'elseif isempty(EEG(1).chaninfo.nodatchans),' ... ' warndlg2(''There are no Reference channel defined, add it using the channel location editor'');' ... 'else,' ... ' tmpchaninfo = EEG(1).chaninfo; [tmp tmpval] = pop_chansel({tmpchaninfo.nodatchans.labels}, ''withindex'', ''on''); set(findobj(gcbf, ''tag'', ''refloc'' ), ''string'',tmpval); clear tmpchanlocs tmp tmpval;' ... 'end;' ]; if isempty(EEG.chanlocs), cb_chansel1 = ''; cb_chansel2 = ''; cb_chansel3 = ''; end; % find current reference (= reference most used) % ---------------------------------------------- if isfield(EEG(1).chanlocs, 'ref') tmpchanlocs = EEG(1).chanlocs; [curref tmp allinds] = unique_bc( { tmpchanlocs.ref }); maxind = 1; for ind = unique_bc(allinds) if length(find(allinds == ind)) > length(find(allinds == maxind)) maxind = ind; end; end; curref = curref{maxind}; if isempty(curref), curref = 'unknown'; end; else curref = 'unknown'; end; uilist = { { 'style' 'text' 'string' [ 'Current data reference state is: ' curref] } ... ... { 'style' 'checkbox' 'tag' 'ave' 'value' 1 'string' 'Compute average reference' 'callback' cb_averef } ... ... { 'style' 'checkbox' 'tag' 'rerefstr' 'value' 0 'string' 'Re-reference data to channel(s):' 'callback' cb_ref } ... { 'style' 'edit' 'tag' 'reref' 'string' '' 'enable' 'off' } ... { 'style' 'pushbutton' 'string' '...' 'callback' cb_chansel1 'enable' 'off' 'tag' 'refbr' } ... ... {} ... ... { 'style' 'checkbox' 'value' 0 'enable' 'off' 'tag' 'keepref' 'string' 'Retain old reference channels in data' } ... ... { 'style' 'text' 'string' 'Exclude channel indices (EMG, EOG)' } ... { 'style' 'edit' 'tag' 'exclude' 'string' '' } ... { 'style' 'pushbutton' 'string' '...' 'callback' cb_chansel2 } ... ... { 'style' 'text' 'tag' 'reflocstr' 'string' 'Add current reference channel back to the data' } ... { 'style' 'edit' 'tag' 'refloc' 'string' '' } ... { 'style' 'pushbutton' 'string' '...' 'callback' cb_chansel3 } }; [result tmp tmp2 restag] = inputgui(geometry, uilist, 'pophelp(''pop_reref'')', 'pop_reref - average reference or re-reference data'); if isempty(result), return; end; % decode inputs % ------------- options = {}; if ~isempty(restag.refloc), try tmpchaninfo = EEG.chaninfo; tmpallchans = lower({ tmpchaninfo.nodatchans.labels }); allelecs = parsetxt(lower(restag.refloc)); chanind = []; for iElec = 1:length(allelecs) chanind = [chanind strmatch( allelecs{iElec}, tmpallchans, 'exact') ]; end; options = { options{:} 'refloc' EEG.chaninfo.nodatchans(chanind) }; catch, disp('Error with old reference: ignoring it'); end; end; if ~isempty(restag.exclude), options = { options{:} 'exclude' eeg_chaninds(EEG, restag.exclude) }; end; if restag.keepref, options = { options{:} 'keepref' 'on' }; end; if restag.ave, ref = []; end; if restag.rerefstr if isempty(restag.reref) warndlg2('Abording: you must enter one or more reference channels'); return; else ref = eeg_chaninds(EEG, restag.reref); end; end; else options = varargin; end; optionscall = options; % include channel location file % ----------------------------- if ~isempty(EEG.chanlocs) optionscall = { optionscall{:} 'elocs' EEG.chanlocs }; end; nchans = EEG.nbchan; fprintf('Re-referencing data\n'); oldchanlocs = EEG.chanlocs; [EEG.data EEG.chanlocs refchan ] = reref(EEG.data, ref, optionscall{:}); g = struct(optionscall{:}); if ~isfield(g, 'exclude'), g.exclude = []; end; if ~isfield(g, 'keepref'), g.keepref = 'off'; end; if ~isfield(g, 'refloc') , g.refloc = []; end; % deal with reference % ------------------- if ~isempty(refchan) if ~isfield(EEG.chaninfo, 'nodatchans') EEG.chaninfo.nodatchans = refchan; elseif isempty(EEG.chaninfo.nodatchans) EEG.chaninfo.nodatchans = refchan; else allf = fieldnames(refchan); n = length(EEG.chaninfo.nodatchans); for ind = 1:length(allf) EEG.chaninfo.nodatchans = setfield(EEG.chaninfo.nodatchans, { n }, ... allf{ind}, getfield(refchan, allf{ind})); end; end; end; if ~isempty(g.refloc) allinds = []; tmpchaninfo = EEG.chaninfo; for iElec = 1:length(g.refloc) allinds = [allinds strmatch( g.refloc(iElec).labels, { tmpchaninfo.nodatchans.labels }) ]; end; EEG.chaninfo.nodatchans(allinds) = []; end; % legacy EEG.ref field % -------------------- if isfield(EEG, 'ref') if strcmpi(EEG.ref, 'common') && isempty(ref) EEG.ref = 'averef'; elseif strcmpi(EEG.ref, 'averef') && ~isempty(ref) EEG.ref = 'common'; end; end; EEG.nbchan = size(EEG.data,1); EEG = eeg_checkset(EEG); % include ICA or not % ------------------ if ~isempty(EEG.icaweights) if ~isempty(intersect(EEG.icachansind, g.exclude)) disp('Warning: some channels used for ICA were excluded from referencing'); disp(' the ICA decomposition has been removed'); EEG.icaweights = []; EEG.icasphere = []; elseif length(EEG.icachansind) ~= nchans - length(g.exclude) disp('Error: some channels not used for ICA decomposition are used for rereferencing'); disp(' the ICA decomposition has been removed'); EEG.icaweights = []; EEG.icasphere = []; else fprintf('Re-referencing ICA matrix\n'); if isempty(orichanlocs) error('Cannot re-reference ICA decomposition without channel locations') end; newICAchaninds = zeros(orinbchan, size(EEG.icawinv,2)); newICAchaninds(EEG.icachansind,:) = EEG.icawinv; [newICAchaninds newchanlocs] = reref(newICAchaninds, ref, optionscall{:}); % convert channel indices in icachanlocs (uses channel labels) % ------------------------------------------------------------ icachansind = EEG.icachansind; rminds = [1:size(newICAchaninds,1)]; for i=length(icachansind):-1:1 oldLabel = orichanlocs(icachansind(i)).labels; newLabelPos = strmatch(oldLabel, { newchanlocs.labels }, 'exact'); if ~isempty( newLabelPos ) icachansind(i) = newLabelPos; rminds(find(icachansind(i) == rminds)) = []; else icachansind(i) = []; end; end; newICAchaninds(rminds,:) = []; EEG.icawinv = newICAchaninds; EEG.icachansind = icachansind; if length(EEG.icachansind) ~= size(EEG.icawinv,1) warning('Wrong channel indices, removing ICA decomposition'); EEG.icaweights = []; EEG.icasphere = []; else EEG.icaweights = pinv(EEG.icawinv); EEG.icasphere = eye(length(icachansind)); end; end; EEG = eeg_checkset(EEG); end; % generate the output command % --------------------------- com = sprintf('%s = pop_reref( %s, %s);', inputname(1), inputname(1), vararg2str({ref, options{:}}));
github
lcnhappe/happe-master
eeg_dipselect.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_dipselect.m
2,895
utf_8
b9770dbf991cd2bc42e30f80792ce7a4
% eeg_dipselect() - select componet dipoles from an EEG dataset with % reisdual variance (rv) less than a selected threshold % and equivalent dipole location inside the brain volume. % Usage: % >> selctedComponents = eeg_dipselect(EEG, rvThreshold, selectionType, depthThreshold) % % Inputs: % EEG - EEGLAB dataset structure % % Optional Inputs % rvThreshold - residual variance threshold (%). Dipoles with residual variance % less than this value will be selected. {default = 15} % selectionType - criteria for selecting dipoles: % 'rv' = only by residual variance, % 'inbrain' = inside brain volume and residual variance. % {default = 'inbrain'} % % depthThreshold - maximum accepted distance outside brain volume (mm) {default = 1} % % Outputs: % selctedComponents - vector of selected components % % Example: % >> selctedComponents = eeg_dipselect(EEG) % select in-brain dipoles with rv less than 0.15 (default value) % >> selctedComponents = eeg_dipselect(EEG, 20,'rv') % select dipoles with rv less than 0.2 % % Author: Nima Bigdely Shamlo, Copyright (C) September 2007 % based on an script from Julie Onton and sourcedepth() function % provided by Robert Oostenveld. % % See also: sourcedepth() function brainComponents = eeg_dipselect(EEG, rvThreshold, selectionType, depthThreshold); if nargin<2 rvThreshold = 0.15; fprintf('Maximum residual variance for selected dipoles set to %1.2f (default).\n',rvThreshold); else rvThreshold = rvThreshold/100; % change from percent to value if rvThreshold>1 error('Error: residual variance threshold should be less than 1.\n'); end; end if nargin<4 depthThreshold = 1; end; % find components with low residual variance for ic = 1:length(EEG.dipfit.model) residualvariance(1,ic) =EEG.dipfit.model(ic).rv; end; compLowResidualvariance = find(residualvariance <rvThreshold); if isempty(compLowResidualvariance) || ( (nargin>=3) && strcmp(selectionType, 'rv')) % if only rv is requested (not in-brain) brainComponents = compLowResidualvariance; return; else if ~exist('ft_sourcedepth') selectionType = 'rv'; tmpWarning = warning('backtrace'); warning backtrace off; warning('You need to install the Fieldtrip extension to be able to select "in brain" dipoles'); warning(tmpWarning); brainComponents = compLowResidualvariance; return; end; load(EEG.dipfit.hdmfile); posxyz = []; for c = compLowResidualvariance posxyz = cat(1,posxyz,EEG.dipfit.model(c).posxyz(1,:)); end; depth = ft_sourcedepth(posxyz, vol); brainComponents = compLowResidualvariance(find(depth<=depthThreshold)); end;
github
lcnhappe/happe-master
pop_loadcnt.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_loadcnt.m
9,914
utf_8
196225b3e7d78dc84817620c2a7cffab
% pop_loadcnt() - load a neuroscan CNT file (pop out window if no arguments). % % Usage: % >> EEG = pop_loadcnt; % pop-up window mode % >> EEG = pop_loadcnt( filename, 'key', 'val', ...); % % Graphic interface: % "Data fomat" - [checkbox] 16-bits or 32-bits. We couldn't find in the % data file where this information was stored. Command % line equivalent in loadcnt() 'dataformat'. % "Time interval in seconds" - [edit box] specify time interval [min max] % to import portion of data. Command line equivalent % in loadcnt: 't1' and 'lddur' % "Import keystrokes" - [checkbox] set this option to import keystroke % event types in dataset. Command line equivalent % 'keystroke'. % "loadcnt() 'key', 'val' params" - [edit box] Enter optional loadcnt() % parameters. % % Inputs: % filename - file name % % Optional inputs: % 'keystroke' - ['on'|'off'] set the option to 'on' to import % keystroke event types. Default is off. % 'memmapfile' - ['memmapfile_name'] use this option if the .cnt file % is too large to read in conventially. The suffix of % the memmapfile_name must be .fdt. the memmapfile % functions process files based on their suffix and an % error will occur if you use a different suffix. % Same as loadcnt() function. % % Outputs: % EEG - EEGLAB data structure % % Note: % 1) This function extract all non-null event from the CNT data structure. % Null events are usually associated with internal signals (recalibrations...). % 2) The "Average reference" edit box had been remove since the re-referencing % menu of EEGLAB offers more options to re-reference data. % 3) The 'blockread' has been disabled since we found where this information % was stored in the file. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: loadcnt(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad function [EEG, command] = pop_loadcnt(filename, varargin); command = ''; EEG = []; if nargin < 1 % ask user [filename, filepath] = uigetfile('*.CNT;*.cnt', 'Choose a CNT file -- pop_loadcnt()'); drawnow; if filename == 0 return; end; % popup window parameters % ----------------------- callback16 = 'set(findobj(gcbf, ''tag'', ''B32''), ''value'', ~get(gcbo, ''value'')); set(findobj(gcbf, ''tag'', ''AD''), ''value'', ~get(gcbo, ''value''));'; callback32 = 'set(findobj(gcbf, ''tag'', ''B16''), ''value'', ~get(gcbo, ''value'')); set(findobj(gcbf, ''tag'', ''AD''), ''value'', ~get(gcbo, ''value''));'; callbackAD = 'set(findobj(gcbf, ''tag'', ''B16''), ''value'', ~get(gcbo, ''value'')); set(findobj(gcbf, ''tag'', ''B32''), ''value'', ~get(gcbo, ''value''));'; uigeom = { [1.3 0.5 0.5 0.5] [1 0.5] [1.09 0.13 0.4] [1 0.5] [1 0.5] 1 } ; uilist = { { 'style' 'text' 'string' 'Data format 16 or 32 bit (Default = Autodetect)' } ... { 'style' 'checkbox' 'tag' 'B16' 'string' '16-bits' 'value' 0 'callback' callback16 } ... { 'style' 'checkbox' 'tag' 'B32' 'string' '32-bits' 'value' 0 'callback' callback32 } ... { 'style' 'checkbox' 'tag' 'AD' 'string' 'Autodetect' 'value' 1 'callback' callbackAD } ... { 'style' 'text' 'string' 'Time interval in s (i.e. [0 100]):' } ... { 'style' 'edit' 'string' '' 'callback' 'warndlg2([ ''Events latency might be innacurate when'' 10 ''importing time intervals (this is an open issue)'']);' } ... { 'style' 'text' 'string' 'Check to Import keystrokes:' } ... { 'style' 'checkbox' 'string' '' } { } ... { 'style' 'text' 'string' 'loadcnt() ''key'', ''val'' params' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' [ 'Large files, enter a file name for memory mapping (xxx.fdt)' ] } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' ' Note: requires to enable memory mapping in EEGLAB memory options and only works for 32-bit files' } }; result = inputgui( uigeom, uilist, 'pophelp(''pop_loadcnt'')', 'Load a CNT dataset'); if length( result ) == 0 return; end; % decode parameters % ----------------- options = []; if result{1}, options = [ options ', ''dataformat'', ''int16''' ]; elseif result{2}, options = [ options ', ''dataformat'', ''int32''' ]; elseif result{3}, options = [ options ', ''dataformat'', ''auto''' ]; end; if ~isempty(result{4}), timer = eval( [ '[' result{4} ']' ]); options = [ options ', ''t1'', ' num2str(timer(1)) ', ''lddur'', ' num2str(timer(2)-timer(1)) ]; end; if result{5}, options = [ options ', ''keystroke'', ''on''' ]; end; if ~isempty(result{6}), options = [ options ',' result{6} ]; end; % Conditional pass if ~isempty(result{7}), options = ... % [options ', ''memmapfile''', result{7} ] ; end ; % Always pass the memmapfile paramter? options = [ options ', ''memmapfile'', ''', result{7} '''' ] ; else options = vararg2str(varargin); end; % load datas % ---------- EEG = eeg_emptyset; if exist('filepath') fullFileName = sprintf('%s%s', filepath, filename); else fullFileName = filename; end; if nargin > 0 if ~isempty(varargin) r = loadcnt( fullFileName, varargin{:}); else r = loadcnt( fullFileName); end; else eval( [ 'r = loadcnt( fullFileName ' options ');' ]); end; if isfield(r, 'dat') error('pop_loadcnt is not compatible with current loadcnt version, please use latest loadcnt() version'); end; % Check to see if data is in memory or in a file. EEG.data = r.data; EEG.comments = [ 'Original file: ' fullFileName ]; EEG.setname = 'CNT file'; EEG.nbchan = r.header.nchannels; % inport events % ------------- I = 1:length(r.event); if ~isempty(I) EEG.event(1:length(I),1) = [ r.event(I).stimtype ]; EEG.event(1:length(I),2) = [ r.event(I).offset ]+1; EEG.event = eeg_eventformat (EEG.event, 'struct', { 'type' 'latency' }); end; % modified by Andreas Widmann 2005/05/12 14:15:00 try, % this piece of code makes the function crash sometimes - Arnaud Delorme 2006/04/27 temp = find([r.event.accept_ev1] == 14 | [r.event.accept_ev1] == 11); % 14: Discontinuity, 11: DC reset if ~isempty(temp) disp('pop_loadcnt note: event field ''type'' set to ''boundary'' for data discontinuities'); for index = 1:length(temp) EEG.event(temp(index)).type = 'boundary'; end; end catch, end; % end modification % process keyboard entries % ------------------------ if ~isempty(findstr('keystroke', lower(options))) tmpkbd = [ r.event(I).keyboard ]; tmpkbd2 = [ r.event(I).keypad_accept ]; for index = 1:length(EEG.event) if EEG.event(index).type == 0 if r.event(index).keypad_accept, EEG.event(index).type = [ 'keypad' num2str(r.event(index).keypad_accept) ]; else EEG.event(index).type = [ 'keyboard' num2str(r.event(index).keyboard) ]; end; end; end; else % removeing keystroke events % -------------------------- rmind = []; for index = 1:length(EEG.event) if EEG.event(index).type == 0 rmind = [rmind index]; end; end; if ~isempty(rmind) fprintf('Ignoring %d keystroke events\n', length(rmind)); EEG.event(rmind) = []; end; end; % import channel locations (Neuroscan coordinates are not wrong) % ------------------------ %x = celltomat( { r.electloc.x_coord } ); %y = celltomat( { r.electloc.y_coord } ); for index = 1:length(r.electloc) names{index} = deblank(char(r.electloc(index).lab')); if size(names{index},1) > size(names{index},2), names{index} = names{index}'; end; end; EEG.chanlocs = struct('labels', names); %EEG.chanlocs = readneurolocs( { names x y } ); %disp('WARNING: Electrode locations imported from CNT files may not reflect true locations'); % Check to see if data is in a file or in memory % If in memory, leave alone % If in a file, use values set in loadcnt.m for nbchan and pnts. EEG.srate = r.header.rate; EEG.nbchan = size(EEG.data,1) ; EEG.nbchan = r.header.nchannels ; % EEG.nbchan = size(EEG.data,1); EEG.trials = 1; EEG.pnts = r.ldnsamples ; %size(EEG.data,2) %EEG.pnts = r.header.pnts %size(EEG.data,2); EEG = eeg_checkset(EEG, 'eventconsistency'); EEG = eeg_checkset(EEG, 'makeur'); if ((size(EEG.data,1) ~= EEG.nbchan) && (size(EEG.data,2) ~= EEG.pnts)) % Assume a data file EEG = eeg_checkset(EEG, 'loaddata'); end if length(options) > 2 command = sprintf('EEG = pop_loadcnt(''%s'' %s);',fullFileName, options); else command = sprintf('EEG = pop_loadcnt(''%s'');',fullFileName); end; return;
github
lcnhappe/happe-master
eeg_amplitudearea.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_amplitudearea.m
7,019
utf_8
712e8efc8565d2b601dd9ec225a4d36c
% eeg_amplitudearea() - Resamples an ERP average using spline interpolation % at a new sample rate (resrate) in Hz to get the exact limits % of the window of integration. Finely samples the window % and adds together very narrow rectangles capped by % right-angled triangles under the window. Output is in uV. % Trade-off between speed and number of resamples and number of % channels selected occurs. % Usage: % >> [channels, amplitude] = eeg_amplitudearea(EEG,channels, resrate, wstart, wend); % Inputs: % EEG - EEGLAB data struct containing a (3-D) epoched data matrix % channels - vector of channel indices % resrate - resampling rate for window of integration in Hz % wstart - start of window of integration in ms post stimulus-onset % wend - end of window of integration in ms post stimulus-onset % % Outputs: % channels - a vector of channel indices. % amplitude - 1-dimensional array in uV for the channels % % Example % >> [channels, amplitude] = eeg_amplitudearea(EEG,[12 18 25 29], 2000, 90.52, 120.52); % % Author: Tom Campbell, Helsinki Collegium for Advanced Studies, Biomag Laboratory, % Engineering Centre, Helsinki University Central Hospital Helsinki Brain % Research Centre ([email protected]) Spartam nanctus es: Hanc exorna. % Combined with amplitudearea_msuV() by Darren Weber, UCSF 28/1/05 % Retested and debugged Tom Campbell 2/2/05 % Reconceived, factored somewhat, tested and debugged Tom Campbell 13:24 23.3.2005 function [channels,overall_amplitude] = eeg_amplitudearea2(EEG, channels, resrate, wstart, wend) if wstart > wend error ('ERROR: wstart must be greater than wend') else [channels, overall_amplitude] = eeg_amplitudearea_msuV (EEG,channels, resrate, wstart, wend) overall_amplitude = overall_amplitude/(wend - wstart) end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [channels, overall_area] = eeg_amplitudearea_msuV (EEG, channels, resrate, wstart, wend) %if ndim(EEG.data) ~= 3 % error('EEG.data must be 3-D data epochs'); %end erp = mean(EEG.data,3); [tmp ind1] =min( abs( EEG.times - wstart ) ); % closest time index to wstart [tmp ind2] =min( abs( EEG.times - wend ) ); % closest time index to wend restep = 1/resrate if EEG.times(ind1) > wstart ind1= ind1 -1; end if EEG.times(ind2) < wend ind2= ind2 +1; end for x= ind1:ind2 t = (x -ind1)+1; tim(t) = EEG.times(x); end tr = 1 timr(tr) = wstart; while timr(tr) < wend tr = tr + 1; timr(tr) = timr(tr-1)+ restep; end for x = 1:size(channels,2) channel = channels(x) %resamples rerp(x, 1:tr) = spline(tim(:),erp(channel, ind1:ind2), timr(1:tr)) pent = timr(tr - 1) overall_area(x) = 0 for y = 1:(tr -1) v1 = rerp(x,(y)) v2 = rerp(x,(y+1)) if ((v1 > 0) & (v2 < 0)) | ((v1 < 0) & (v2 > 0)) if (y == (tr-1)) & (timr(y+1)> wend) area1 = zero_crossing_truncated(v1, v2, restep, wend, pent) else area1 = zero_crossing(v1, v2, restep) end else if( y == (tr-1)) & (timr(y+1)> wend) area1 = rect_tri_truncated(v1, v2, restep,wend,pent) else area1 = rect_tri(v1, v2, restep) end end overall_area(x) = overall_area(x) + area1 end end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [area] = zero_crossing(v1,v2,step) if (v1 > v2) T1 = v1 T2 = v2 else T1 = v2 T2 = v1 end tantheta = (abs(T1)+ abs(T2))/step if (v1 > v2) %decline z = abs(T1)/tantheta tr1= abs(T1)*(z/2) tr2= abs(T2)*((step-z)/2) else %incline z = abs(T2)/tantheta tr2= abs(T2)*(z/2) tr1= abs(T1)*((step-z)/2) end [area] = (tr1 - tr2) return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [area] = zero_crossing_truncated(v1,v2,step,wend,pent) if (v1 > v2) T1 = v1 T2 = v2 else T1 = v2 T2 = v1 end tantheta = (abs(T1)+ abs(T2))/step s = wend - pent if (v1 > v2) z = abs(T1)/tantheta if s < z %decline,truncated before zerocrossing t1 = tantheta * s r1 = abs(T1)-abs(t1) tr1= abs(t1)*(s/2) tr2= 0 rect1 = r1*s rect2 = 0 else %decline,truncated after zerocrossing t2= tantheta*(s-z) tr1= abs(T1)*(z/2) tr2 = abs(t2)*((s-z)/2) rect1 = 0 rect2 = 0 end else z = abs(T2)/tantheta if s < z %incline,truncated before zerocrossing t2 = tantheta * s r2 = abs(T2)-abs(t2) tr1= 0 tr2= abs(t2)*(s/2) rect1 = 0 rect2 = r2*s else %incline,truncated after zerocrossing t1= tantheta*(s-z) tr1 = abs(t1)*((s-z)/2) tr2 = abs(T2) * (z/2) rect1 = 0 rect2 = 0 end end [area] = ((rect1 + tr1) - (rect2 + tr2)) return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [area] = rect_tri(v1,v2,step) if (abs(v1) > abs(v2)) T = abs(v1)-abs(v2) R = abs(v2) else T = abs(v2)-abs(v1) R = abs(v1) end rect = R*step tri = T*(step/2) if v1 > 0 area = 1* (rect+tri) else area = -1 * (rect+tri) end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [area] = rect_tri_truncated(v1,v2,step,wend,pent) if (abs(v1) > abs(v2)) T = abs(v1)-abs(v2) R = abs(v2) else T = abs(v2)-abs(v1) R = abs(v1) end tantheta = abs(T)/step s = wend -pent if (v1>0) if v1 >v2 %positive decline t = tantheta*s e = abs(T)-abs(t) rect = s*R exrect = s*e tri = (s/2)*R else %positive incline t = tantheta*s rect = s*R exrect = 0 tri = (s/2)*R end else if v1 >v2 %negative decline t = tantheta*s rect = s*R exrect = 0 tri = (s/2)*R else %negative incline t = tantheta*s e = abs(T)-abs(t) rect = s*R exrect = s*e tri = (s/2)*R end end tri = T*(step/2) if v1 > 0 area = 1* (rect+exrect+tri) else area = -1 * (rect+exrect+tri) end return
github
lcnhappe/happe-master
pop_eegplot.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_eegplot.m
9,395
utf_8
694d3469c8e08a65956f474715744049
% pop_eegplot() - Visually inspect EEG data using a scrolling display. % Perform rejection or marking for rejection of visually % (and/or previously) selected data portions (i.e., stretches % of continuous data or whole data epochs). % Usage: % >> pop_eegplot( EEG ) % Scroll EEG channel data. Allow marking for rejection via % % button 'Update Marks' but perform no actual data rejection. % % Do not show or use marks from previous visual inspections % % or from semi-auotmatic rejection. % >> pop_eegplot( EEG, icacomp, superpose, reject ); % % Graphic interface: % "Add to previously marked rejections" - [edit box] Either YES or NO. % Command line equivalent: 'superpose'. % "Reject marked trials" - [edit box] Either YES or NO. Command line % equivalent 'reject'. % Inputs: % EEG - input EEG dataset % icacomp - type of rejection 0 = independent components; % 1 = data channels. {Default: 1 = data channels} % superpose - 0 = Show new marks only: Do not color the background of data portions % previously marked for rejection by visual inspection. Mark new data % portions for rejection by first coloring them (by dragging the left % mouse button), finally pressing the 'Update Marks' or 'Reject' % buttons (see 'reject' below). Previous markings from visual inspection % will be lost. % 1 = Show data portions previously marked by visual inspection plus % data portions selected in this window for rejection (by dragging % the left mouse button in this window). These are differentiated % using a lighter and darker hue, respectively). Pressing the % 'Update Marks' or 'Reject' buttons (see 'reject' below) % will then mark or reject all the colored data portions. % {Default: 0, show and act on new marks only} % reject - 0 = Mark for rejection. Mark data portions by dragging the left mouse % button on the data windows (producing a background coloring indicating % the extent of the marked data portion). Then press the screen button % 'Update Marks' to store the data portions marked for rejection % (stretches of continuous data or whole data epochs). No 'Reject' button % is present, so data marked for rejection cannot be actually rejected % from this eegplot() window. % 1 = Reject marked trials. After inspecting/selecting data portions for % rejection, press button 'Reject' to reject (remove) them from the EEG % dataset (i.e., those portions plottted on a colored background. % {default: 1, mark for rejection only} % % topcommand - Input deprecated. Kept for compatibility with other function calls % Outputs: % Modifications are applied to the current EEG dataset at the end of the % eegplot() call, when the user presses the 'Update Marks' or 'Reject' button. % NOTE: The modifications made are not saved into EEGLAB history. As of v4.2, % events contained in rejected data portions are remembered in the EEG.urevent % structure (see EEGLAB tutorial). % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab(), eegplot(), pop_rejepoch() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-07-02 added srate argument to eegplot call -ad % 03-27-02 added event latency recalculation for continuous data -ad function com = pop_eegplot( EEG, icacomp, superpose, reject, topcommand, varargin) com = ''; if nargin < 1 help pop_eegplot; return; end; if nargin < 2 icacomp = 1; end; if nargin < 3 superpose = 0; end; if nargin < 4 reject = 1; end; if icacomp == 0 if isempty( EEG.icasphere ) disp('Error: you must run ICA first'); return; end; end; if nargin < 3 & EEG.trials > 1 % which set to save % ----------------- uilist = { { 'style' 'text' 'string' 'Add to previously marked rejections? (checked=yes)'} , ... { 'style' 'checkbox' 'string' '' 'value' 1 } , ... { 'style' 'text' 'string' 'Reject marked trials? (checked=yes)'} , ... { 'style' 'checkbox' 'string' '' 'value' 0 } }; result = inputgui( { [ 2 0.2] [ 2 0.2]} , uilist, 'pophelp(''pop_eegplot'');', ... fastif(icacomp==0, 'Manual component rejection -- pop_eegplot()', ... 'Reject epochs by visual inspection -- pop_eegplot()')); size_result = size( result ); if size_result(1) == 0 return; end; if result{1}, superpose=1; end; if ~result{2}, reject=0; end; end; if EEG.trials > 1 if icacomp == 1 macrorej = 'EEG.reject.rejmanual'; macrorejE = 'EEG.reject.rejmanualE'; else macrorej = 'EEG.reject.icarejmanual'; macrorejE = 'EEG.reject.icarejmanualE'; end; if icacomp == 1 elecrange = [1:EEG.nbchan]; else elecrange = [1:size(EEG.icaweights,1)]; end; colrej = EEG.reject.rejmanualcol; rej = eval(macrorej); rejE = eval(macrorejE); eeg_rejmacro; % script macro for generating command and old rejection arrays else % case of a single trial (continuous data) %if icacomp, % command = ['if isempty(EEG.event) EEG.event = [eegplot2event(TMPREJ, -1)];' ... % 'else EEG.event = [EEG.event(find(EEG.event(:,1) ~= -1),:); eegplot2event(TMPREJ, -1, [], [0.8 1 0.8])];' ... % 'end;']; %else, command = ['if isempty(EEG.event) EEG.event = [eegplot2event(TMPREJ, -1)];' ... % 'else EEG.event = [EEG.event(find(EEG.event(:,1) ~= -2),:); eegplot2event(TMPREJ, -1, [], [0.8 1 0.8])];' ... % 'end;']; %end; %if reject % command = ... % [ command ... % '[EEG.data EEG.xmax] = eegrej(EEG.data, EEG.event(find(EEG.event(:,1) < 0),3:end), EEG.xmax-EEG.xmin);' ... % 'EEG.xmax = EEG.xmax+EEG.xmin;' ... % 'EEG.event = EEG.event(find(EEG.event(:,1) >= 0),:);' ... % 'EEG.icaact = [];' ... % 'EEG = eeg_checkset(EEG);' ]; eeglab_options; % changed from eeglaboptions 3/30/02 -sm if reject == 0, command = []; else command = ... [ '[EEGTMP LASTCOM] = eeg_eegrej(EEG,eegplot2event(TMPREJ, -1));' ... 'if ~isempty(LASTCOM),' ... ' [ALLEEG EEG CURRENTSET tmpcom] = pop_newset(ALLEEG, EEGTMP, CURRENTSET);' ... ' if ~isempty(tmpcom),' ... ' EEG = eegh(LASTCOM, EEG);' ... ' eegh(tmpcom);' ... ' eeglab(''redraw'');' ... ' end;' ... 'end;' ... 'clear EEGTMP tmpcom;' ]; if nargin < 4 res = questdlg2( strvcat('Mark stretches of continuous data for rejection', ... 'by dragging the left mouse button. Click on marked', ... 'stretches to unmark. When done,press "REJECT" to', ... 'excise marked stretches (Note: Leaves rejection', ... 'boundary markers in the event table).'), 'Warning', 'Cancel', 'Continue', 'Continue'); if strcmpi(res, 'Cancel'), return; end; end; end; eegplotoptions = { 'events', EEG.event }; if ~isempty(EEG.chanlocs) & icacomp eegplotoptions = { eegplotoptions{:} 'eloc_file', EEG.chanlocs }; end; end; if EEG.nbchan > 100 disp('pop_eegplot() note: Baseline subtraction disabled to speed up display'); eegplotoptions = { eegplotoptions{:} 'submean' 'off' }; end; if icacomp == 1 eegplot( EEG.data, 'srate', EEG.srate, 'title', 'Scroll channel activities -- eegplot()', ... 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}, varargin{:}); else tmpdata = eeg_getdatact(EEG, 'component', [1:size(EEG.icaweights,1)]); eegplot( tmpdata, 'srate', EEG.srate, 'title', 'Scroll component activities -- eegplot()', ... 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}, varargin{:}); end; com = [ com sprintf('pop_eegplot( %s, %d, %d, %d);', inputname(1), icacomp, superpose, reject) ]; return;
github
lcnhappe/happe-master
pop_editset.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_editset.m
29,573
utf_8
d0871f09de508485acd7c591ec9228ae
% pop_editset() - Edit EEG dataset structure fields. % % Usage: % >> EEGOUT = pop_editset( EEG ); % pops-up a data entry window % >> EEGOUT = pop_editset( EEG, 'key', val,...); % no pop-up window % % Graphic interface: % "Dataset name" - [Edit box] Name for the new dataset. % In the right column of the graphic interface, the "EEG.setname" % text indicates which field of the EEG structure this parameter % corresponds to (in this case, .'setname'). % Command line equivalent: 'setname'. % "Data sampling rate" - [Edit box] In Hz. Command line equivalent: 'srate' % "Time points per epoch" - [Edit box] Number of data frames (points) per epoch. % Changing this value will change the number of data epochs. % Command line equivalent: 'pnts'. % "Start time" - [Edit box] This edit box is only present for epoched data % and specifies the epoch start time in ms. Epoch end time % is automatically calculated. Command line equivalent: 'xmin' % "Number of channels" - [Edit box] Number of data channels. Command line % equivalent: 'nbchan'. This edit box cannot be edited. % "Ref. channel indices or mode" - [edit box] current reference. This edit box % cannot be edited. To change the data reference, use menu item, % 'Tools > Re-reference', calling function pop_reref(). The % reference can be either a string (channel name), 'common', % indicating an unknown common reference, 'averef' indicating % average reference, or an array of integers containing indices % of the reference channel(s). % "Subject code" - [Edit box] subject code. For example, 'S01'. The command % line equivalent is 'subject'. % "Task Condition" - [Edit box] task condition. For example, 'Targets'. % The command line equivalent 'condition'. % "Session number" - [Edit box] session number (from the same subject). % All datasets from the same subject and session will be % assumed to use the same ICA decomposition. The command % line equivalent 'session'. % "Subject group" - [Edit box] subject group. For example 'Patients' or % 'Control'. The command line equivalent is 'group'. % "About this dataset" - [Edit box] Comments about the dataset. Command line % equivalent is 'comments'. % "Channel locations file or array" - [Edit box] For channel data formats, see % >> readlocs help Command line equivalent: 'chanlocs' % "ICA weights array or text/binary file" - [edit box] Import ICA weights from % other decompositions (e.g., same session, different conditions). % To use the ICA weights from another loaded dataset (n), enter % ALLEEG(n).icaweights. Command line equivalent: 'icaweights' % "ICA sphere array or text/binary file" - [edit box] Import ICA sphere matrix. % In EEGLAB, ICA decompositions require a sphere matrix and % an unmixing weight matrix (see above). To use the sphere % matrix from a loaded dataset (n), enter ALLEEG(n).icasphere % Command line equivalent: 'icasphere'. % "From other dataset" - [push button] Press this button to enter the index % of another dataset. This will update the channel locations or % the ICA edit box. % Inputs: % EEG - EEG dataset structure % % Optional inputs: % 'setname' - Name of the EEG dataset % 'data' - ['varname'|'filename'] Import data from a Matlab variable or % mat file into an EEG data structure % 'dataformat' - ['array|matlab|ascii|float32le|float32be'] Input data format. % 'array' is a Matlab array in the global workspace. % 'matlab' is a Matlab file (containing a single variable). % 'ascii' is an ascii file. % 'float32le' and 'float32be' are 32-bit float data files % with little-endian and big-endian byte order, respectively. % Data must be organised as 2-D (channels, timepoints), i.e. % channels = rows, timepoints = columns; else as 3-D (channels, % timepoints, epochs). For convenience, the data file is % transposed if the number of rows is larger than the number % of columns, as the program assumes that there are more % channels than data points. % 'subject' - [string] subject code. For example, 'S01'. % {default: none -> each dataset from a different subject} % 'condition' - [string] task condition. For example, 'Targets' % {default: none -> all datasets from one condition} % 'group' - [string] subject group. For example 'Patients' or 'Control'. % {default: none -> all subjects in one group} % 'session' - [integer] session number (from the same subject). All datasets % from the same subject and session will be assumed to use the % same ICA decomposition {default: none -> each dataset from % a different session} % 'chanlocs' - ['varname'|'filename'] Import a channel location file. % For file formats, see >> help readlocs % 'nbchan' - [int] Number of data channels. % 'xmin' - [real] Data epoch start time (in seconds). % {default: 0} % 'pnts' - [int] Number of data points per data epoch. The number of % data trials is automatically calculated. % {default: length of the data -> continuous data assumed} % 'srate' - [real] Data sampling rate in Hz {default: 1Hz} % 'ref' - [string or integer] reference channel indices; 'averef' % indicates average reference. Note that this does not perform % referencing but only sets the initial reference when the data % are imported. % 'icaweight' - [matrix] ICA weight matrix. % 'icasphere' - [matrix] ICA sphere matrix. By default, the sphere matrix % is initialized to the identity matrix if it is left empty. % 'comments' - [string] Comments on the dataset, accessible through the % EEGLAB main menu using ('Edit > About This Dataset'). % Use this to attach background information about the % experiment or the data to the dataset. % Outputs: % EEGOUT - Modified EEG dataset structure % % Note: % To create a new dataset: % >> EEG = pop_editset( eeg_emptyset ); % eeg_emptyset() returns an empty dataset % % To erase a variable, use '[]'. The following suppresses channel locations: % >> EEG = pop_editset( EEG, 'chanlocs', '[]'); % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: pop_importdata(), pop_select(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-16-02 text interface editing -sm & ad % 03-16-02 remove EEG.xmax et EEG.xmin (for continuous) -ad & sm % 03-31-02 changed interface, reprogrammed all function -ad % 04-02-02 recompute event latencies when modifying xmin -ad function [EEGOUT, com] = pop_editset(EEG, varargin); com = ''; if nargin < 1 help pop_editset; return; end; EEGOUT = EEG; if nargin < 2 % if several arguments, assign values % popup window parameters % ----------------------- % popup window parameters % ----------------------- geometry = { [2 3.38] [1] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] ... [1] [1.4 0.7 .8 0.5] [1] [1.4 0.7 .8 0.5] [1.4 0.7 .8 0.5] [1.4 0.7 .8 0.5] }; editcomments = [ 'tmp = pop_comments(get(gcbf, ''userdata''), ''Edit comments of current dataset'');' ... 'if ~isempty(tmp), set(gcf, ''userdata'', tmp); end; clear tmp;' ]; commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ... 'if filename(1) ~=0,' ... ' set(findobj(''parent'', gcbf, ''tag'', tagtest), ''string'', [ filepath filename ]);' ... ' if strcmpi(tagtest, ''weightfile''),' ... ' set(findobj( ''parent'', gcbf, ''tag'', ''sphfile''), ''string'', ''eye(' num2str(EEG.nbchan) ')'');' ... ' end;' ... 'end;' ... 'clear filename filepath tagtest;' ]; commandselica = [ 'res = inputdlg2({ ''Enter dataset number'' }, ''Select ICA weights and sphere from other dataset'', 1, { ''1'' });' ... 'if ~isempty(res),' ... ' set(findobj( ''parent'', gcbf, ''tag'', ''weightfile''), ''string'', sprintf(''ALLEEG(%s).icaweights'', res{1}));' ... ' set(findobj( ''parent'', gcbf, ''tag'', ''sphfile'') , ''string'', sprintf(''ALLEEG(%s).icasphere'' , res{1}));' ... ' set(findobj( ''parent'', gcbf, ''tag'', ''icainds'') , ''string'', sprintf(''ALLEEG(%s).icachansind'' , res{1}));' ... 'end;' ]; commandselchan = [ 'res = inputdlg2({ ''Enter dataset number'' }, ''Select channel information from other dataset'', 1, { ''1'' });' ... 'if ~isempty(res),' ... ' set(findobj( ''parent'', gcbf, ''tag'', ''chanfile''), ' ... ' ''string'', sprintf(''{ ALLEEG(%s).chanlocs ALLEEG(%s).chaninfo ALLEEG(%s).urchanlocs }'', res{1}, res{1}, res{1}));' ... 'end;' ]; if isstr(EEGOUT.ref) curref = EEGOUT.ref; else if length(EEGOUT.ref) > 1 curref = [ int2str(abs(EEGOUT.ref)) ]; else curref = [ int2str(abs(EEGOUT.ref)) ]; end; end; uilist = { ... { 'Style', 'text', 'string', 'Dataset name', 'horizontalalignment', 'right', ... 'fontweight', 'bold' }, { 'Style', 'edit', 'string', EEG.setname }, { } ... ... { 'Style', 'text', 'string', 'Data sampling rate (Hz)', 'horizontalalignment', 'right', 'fontweight', ... 'bold' }, { 'Style', 'edit', 'string', num2str(EEGOUT.srate) }, ... { 'Style', 'text', 'string', 'Subject code', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', EEG.subject }, ... { 'Style', 'text', 'string', 'Time points per epoch (0->continuous)', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', num2str(EEGOUT.pnts) }, ... { 'Style', 'text', 'string', 'Task condition', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', EEG.condition }, ... { 'Style', 'text', 'string', 'Start time (sec) (only for data epochs)', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', num2str(EEGOUT.xmin) }, ... { 'Style', 'text', 'string', 'Session number', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', EEG.session }, ... { 'Style', 'text', 'string', 'Number of channels (0->set from data)', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', EEG.nbchan 'enable' 'off' }, ... { 'Style', 'text', 'string', 'Subject group', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', EEG.group }, ... { 'Style', 'text', 'string', 'Ref. channel indices or mode (see help)', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', curref 'enable' 'off' }, ... { 'Style', 'text', 'string', 'About this dataset', 'horizontalalignment', 'right', ... }, { 'Style', 'pushbutton', 'string', 'Enter comments' 'callback' editcomments }, ... { } ... { 'Style', 'text', 'string', 'Channel location file or info', 'horizontalalignment', 'right', 'fontweight', ... 'bold' }, {'Style', 'pushbutton', 'string', 'From other dataset', 'callback', commandselchan }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'chanfile' }, ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''chanfile'';' commandload ] }, ... ... { 'Style', 'text', 'string', ... ' Note: The file format may be auto-detected from its file extension. See menu "Edit > Channel locations" for other options.', ... 'horizontalalignment', 'right' }, ... ... { 'Style', 'text', 'string', 'ICA weights array or text/binary file (if any):', 'horizontalalignment', 'right' }, ... { 'Style', 'pushbutton' 'string' 'from other dataset' 'callback' commandselica }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'weightfile' }, ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''weightfile'';' commandload ] }, ... ... { 'Style', 'text', 'string', 'ICA sphere array:', 'horizontalalignment', 'right' }, ... { 'Style', 'pushbutton' 'string' 'from other dataset' 'callback' commandselica }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'sphfile' } ... { } ... ... { 'Style', 'text', 'string', 'ICA channel indices (by default all):', 'horizontalalignment', 'right' }, ... { 'Style', 'pushbutton' 'string' 'from other dataset' 'callback' commandselica }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'icainds' } ... { } }; [ results newcomments ] = inputgui( geometry, uilist, 'pophelp(''pop_editset'');', 'Edit dataset information - pop_editset()', ... EEG.comments); if length(results) == 0, return; end; args = {}; i = 1; if ~strcmp( results{i }, EEG.setname ) , args = { args{:}, 'setname', results{i } }; end; if ~strcmp( results{i+1}, num2str(EEG.srate) ) , args = { args{:}, 'srate', str2num(results{i+1}) }; end; if ~strcmp( results{i+2}, EEG.subject ) , args = { args{:}, 'subject', results{i+2} }; end; if ~strcmp( results{i+3}, num2str(EEG.pnts) ) , args = { args{:}, 'pnts', str2num(results{i+3}) }; end; if ~strcmp( results{i+4}, EEG.condition ) , args = { args{:}, 'condition', results{i+4} }; end; if ~strcmp( results{i+5}, num2str(EEG.xmin) ) , args = { args{:}, 'xmin', str2num(results{i+5}) }; end; if ~strcmp( results{i+6}, num2str(EEG.session) ) , args = { args{:}, 'session', str2num(results{i+6}) }; end; if ~strcmp( results{i+7}, num2str(EEG.nbchan) ) , args = { args{:}, 'nbchan', str2num(results{i+7}) }; end; if ~strcmp( results{i+8}, EEG.group ) , args = { args{:}, 'group', results{i+8} }; end; if ~strcmp( results{i+9}, num2str(EEG.ref) ) , args = { args{:}, 'ref', results{i+9} }; end; if ~strcmp(EEG.comments, newcomments) , args = { args{:}, 'comments' , newcomments }; end; if abs(str2num(results{i+5})) > 10, fprintf('WARNING: are you sure the epoch start time (%3.2f) is in seconds\n', str2num(results{i+5})); end; if ~isempty( results{i+12} ) , args = { args{:}, 'icachansind', results{i+13} }; end; if ~isempty( results{i+10} ) , args = { args{:}, 'chanlocs' , results{i+10} }; end; if ~isempty( results{i+11} ), args = { args{:}, 'icaweights', results{i+11} }; end; if ~isempty( results{i+12} ) , args = { args{:}, 'icasphere', results{i+12} }; end; else % no interactive inputs args = varargin; % Do not copy varargin % -------------------- %for index=1:2:length(args) % if ~isempty(inputname(index+2)) & ~isstr(args{index+1}) & length(args{index+1})>1, % args{index+1} = inputname(index+1); % end; %end; end; % create structure % ---------------- if ~isempty(args) try, g = struct(args{:}); catch, disp('Setevent: wrong syntax in function arguments'); return; end; else g = []; end; % test the presence of variables % ------------------------------ try, g.dataformat; catch, g.dataformat = 'ascii'; end; % assigning values % ---------------- tmpfields = fieldnames(g); for curfield = tmpfields' switch lower(curfield{1}) case {'dataformat' }, ; % do nothing now case 'setname' , EEGOUT.setname = getfield(g, {1}, curfield{1}); case 'subject' , EEGOUT.subject = getfield(g, {1}, curfield{1}); case 'condition' , EEGOUT.condition = getfield(g, {1}, curfield{1}); case 'group' , EEGOUT.group = getfield(g, {1}, curfield{1}); case 'session' , EEGOUT.session = getfield(g, {1}, curfield{1}); case 'setname' , EEGOUT.setname = getfield(g, {1}, curfield{1}); case 'setname' , EEGOUT.setname = getfield(g, {1}, curfield{1}); case 'pnts' , EEGOUT.pnts = getfield(g, {1}, curfield{1}); case 'comments' , EEGOUT.comments = getfield(g, {1}, curfield{1}); case 'nbchan' , tmp = getfield(g, {1}, curfield{1}); if tmp ~=0, EEGOUT.nbchan = tmp; end; case 'averef' , disp('The ''averef'' argument is obsolete; use function pop_reref() instead'); case 'ref' , EEGOUT.ref = getfield(g, {1}, curfield{1}); disp('WARNING: CHANGING REFERENCE DOES NOT RE-REFERENCE THE DATA, use menu Tools > Rereference instead'); if ~isempty(str2num( EEGOUT.ref )), EEG,ref = str2num(EEG.ref); end; case 'xmin' , oldxmin = EEG.xmin; EEGOUT.xmin = getfield(g, {1}, curfield{1}); if oldxmin ~= EEGOUT.xmin if ~isempty(EEG.event) if nargin < 2 if ~popask( ['Warning: changing the starting point of epochs will' 10 'lead to recomputing epoch event latencies, Continue?'] ) com = ''; warndlg2('pop_editset(): transformation cancelled by user'); return; end; end; if isfield(EEG.event, 'latency') for index = 1:length(EEG.event) EEG.event(index).latency = EEG.event(index).latency - (EEG.xmin-oldxmin)*EEG.srate; end; end; end; end; case 'srate' , EEGOUT.srate = getfield(g, {1}, curfield{1}); case 'chanlocs', varname = getfield(g, {1}, curfield{1}); if isempty(varname) EEGOUT.chanlocs = []; elseif isstr(varname) & exist( varname ) == 2 fprintf('pop_editset(): channel locations file ''%s'' found\n', varname); [ EEGOUT.chanlocs lab theta rad ind ] = readlocs(varname); elseif isstr(varname) EEGOUT.chanlocs = evalin('base', varname, 'fprintf(''pop_editset() warning: variable ''''%s'''' not found, ignoring\n'', varname)' ); if iscell(EEGOUT.chanlocs) if length(EEGOUT.chanlocs) > 1, EEGOUT.chaninfo = EEGOUT.chanlocs{2}; end; if length(EEGOUT.chanlocs) > 2, EEGOUT.urchanlocs = EEGOUT.chanlocs{3}; end; EEGOUT.chanlocs = EEGOUT.chanlocs{1}; end; else EEGOUT.chanlocs = varname; end; case 'icaweights', varname = getfield(g, {1}, curfield{1}); if isstr(varname) & exist( varname ) == 2 fprintf('pop_editset(): ICA weight matrix file ''%s'' found\n', varname); if ~isempty(EEGOUT.icachansind), nbcol = length(EEGOUT.icachansind); else nbcol = EEG.nbchan; end; try, EEGOUT.icaweights = load(varname, '-ascii'); EEGOUT.icawinv = []; catch, try EEGOUT.icaweights = floatread(varname, [1 Inf]); EEGOUT.icaweights = reshape( EEGOUT.icaweights, [length(EEGOUT.icaweights)/nbcol nbcol]); catch fprintf('pop_editset() warning: error while reading filename ''%s'' for ICA weight matrix\n', varname); end; end; else if isempty(varname) EEGOUT.icaweights = []; elseif isstr(varname) EEGOUT.icaweights = evalin('base', varname, 'fprintf(''pop_editset() warning: variable ''''%s'''' not found, ignoring\n'', varname)' ); EEGOUT.icawinv = []; else EEGOUT.icaweights = varname; EEGOUT.icawinv = []; end; end; if ~isempty(EEGOUT.icaweights) & isempty(EEGOUT.icasphere) EEGOUT.icasphere = eye(size(EEGOUT.icaweights,2)); end; case 'icachansind', varname = getfield(g, {1}, curfield{1}); if isempty(varname) EEGOUT.icachansind = []; elseif isstr(varname) EEGOUT.icachansind = evalin('base', varname, 'fprintf(''pop_editset() warning: variable ''''%s'''' not found, ignoring\n'', varname)' ); else EEGOUT.icachansind = varname; end; case 'icasphere', varname = getfield(g, {1}, curfield{1}); if isstr(varname) & exist( varname ) == 2 fprintf('pop_editset(): ICA sphere matrix file ''%s'' found\n', varname); if ~isempty(EEGOUT.icachansind), nbcol = length(EEGOUT.icachansind); else nbcol = EEG.nbchan; end; try, EEGOUT.icasphere = load(varname, '-ascii'); EEGOUT.icawinv = []; catch, try EEGOUT.icasphere = floatread(varname, [1 Inf]); EEGOUT.icasphere = reshape( EEGOUT.icasphere, [length(EEGOUT.icasphere)/nbcol nbcol]); catch fprintf('pop_editset() warning: erro while reading filename ''%s'' for ICA weight matrix\n', varname); end; end; else if isempty(varname) EEGOUT.icasphere = []; elseif isstr(varname) EEGOUT.icasphere = evalin('base', varname, 'fprintf(''pop_editset() warning: variable ''''%s'''' not found, ignoring\n'', varname)' ); EEGOUT.icawinv = []; else EEGOUT.icaweights = varname; EEGOUT.icawinv = []; end; end; if ~isempty(EEGOUT.icaweights) & isempty(EEGOUT.icasphere) EEGOUT.icasphere = eye(size(EEGOUT.icaweights,2)); end; case 'data' , varname = getfield(g, {1}, curfield{1}); if isnumeric(varname) EEGOUT.data = varname; elseif exist( varname ) == 2 & ~strcmp(lower(g.dataformat), 'array'); fprintf('pop_editset(): raw data file ''%s'' found\n', varname); switch lower(g.dataformat) case 'ascii' , try, EEGOUT.data = load(varname, '-ascii'); catch, disp(lasterr); error(['pop_editset() error: cannot read ascii file ''' varname ''' ']); end; if ndims(EEGOUT.data)<3 & size(EEGOUT.data,1) > size(EEGOUT.data,2), EEGOUT.data = transpose(EEGOUT.data); end; case 'matlab', try, x = whos('-file', varname); if length(x) > 1, error('pop_editset() error: .mat file must contain a single variable'); end; tmpdata = load(varname, '-mat'); EEGOUT.data = getfield(tmpdata,{1},x(1).name); clear tmpdata; catch, error(['pop_editset() error: cannot read .mat file ''' varname ''' ']); end; if ndims(EEGOUT.data)<3 & size(EEGOUT.data,1) > size(EEGOUT.data,2), EEGOUT.data = transpose(EEGOUT.data); end; case {'float32le' 'float32be'}, if EEGOUT.nbchan == 0, error(['pop_editset() error: to read float32 data you must first specify the number of channels']); end; try, EEGOUT.data = floatread(varname, [EEGOUT.nbchan Inf], ... fastif(strcmpi(g.dataformat, 'float32le'), 'ieee-le', 'ieee-be')); catch, error(['pop_editset() error: cannot read float32 data file ''' varname ''' ']); end; otherwise, error('pop_editset() error: unrecognized file format'); end; elseif isstr(varname) % restoration command %-------------------- try res = evalin('base', ['exist(''' varname ''') == 1']); catch disp('pop_editset() warning: cannot find specified variable in global workspace!'); end; if ~res, error('pop_editset(): cannot find specified variable.'); end; warning off; try, testval = evalin('base', ['isglobal(' varname ')']); catch, testval = 0; end; if ~testval commandrestore = [ ' tmpp = ' varname '; clear global ' varname ';' varname '=tmpp;clear tmpp;' ]; else commandrestore = []; end; % make global, must make these variable global, if you try to evaluate them direclty in the base % workspace, with a large array the computation becomes incredibly slow. %-------------------------------------------------------------------- comglobal = sprintf('global %s;', varname); evalin('base', comglobal); eval(comglobal); eval( ['EEGOUT.data = ' varname ';' ]); try, evalin('base', commandrestore); catch, end; warning on; else EEGOUT.data = varname; if ndims(EEGOUT.data)<3 & size(EEGOUT.data,1) > size(EEGOUT.data,2), EEGOUT.data = transpose(EEGOUT.data); end; end; otherwise, error(['pop_editset() error: unrecognized field ''' curfield{1} '''']); end; end; EEGOUT = eeg_checkset(EEGOUT); % generate the output command % --------------------------- if nargout > 1 com = sprintf( '%s = pop_editset(%s', inputname(1), inputname(1) ); for i=1:2:length(args) if ~isempty( args{i+1} ) if isstr( args{i+1} ) com = sprintf('%s, ''%s'', %s', com, args{i}, vararg2str(args{i+1}) ); else com = sprintf('%s, ''%s'', [%s]', com, args{i}, num2str(args{i+1}) ); end; else com = sprintf('%s, ''%s'', []', com, args{i} ); end; end; com = [com ');']; end; return; function num = popask( text ) ButtonName=questdlg2( text, ... 'Confirmation', 'Cancel', 'Yes','Yes'); switch lower(ButtonName), case 'cancel', num = 0; case 'yes', num = 1; end;
github
lcnhappe/happe-master
pop_snapread.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_snapread.m
3,759
utf_8
28b076d60861433397b0c0dd49338875
% pop_snapread() - load an EEG SnapMaster file (pop out window if no arguments). % % Usage: % >> [dat] = pop_snapread( filename, gain); % % Graphic interface: % "Relative gain" - [edit box] to compute the relative gain, fisrt look at % the text header of the snapmater file with a text editor. % Find the recording unit, usually in volts (UNITS field). % Then, find the voltage range in the "CHANNEL.RANGE" [cmin cmax] % field. Finally, determine the gain of the amplifiers (directly % on the machine, not in the header file). % Knowing that the recording precision is 12 bits. The folowing % formula % 1/2^12*[cmax-cmin]*1e6/gain % returns the relative gain. You have to compute it and enter % it in the edit box. Enter 1, for preserving the data file units. % (note that if the voltage range is not the same for all channels % or if the CONVERSION.POLY field in the file header % is not "0 + 1x" for all channels, you will have to load the data % using snapread() and scale manually all channels, then import % the Matlab array into EEGLAB). % % Inputs: % filename - SnapMaster file name % gain - relative gain. See graphic interface help. % % Outputs: % dat - EEGLAB data structure % % Author: Arnaud Delorme, CNL/Salk Institute, 13 March 2002 % % See also: eeglab(), snapread() % Copyright (C) 13 March 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, command] = pop_snapread(filename, gain); command = ''; EEG = []; if nargin < 1 % ask user [filename, filepath] = uigetfile('*.SMA', 'Choose a SnapMaster file -- pop_snapread()'); if filename == 0 return; end; filename = [filepath filename]; promptstr = { 'Relative gain (see help)' }; inistr = { '400' }; result = inputdlg2( promptstr, 'Import SnapMaster file -- pop_snapread()', 1, inistr, 'pop_snapread'); if length(result) == 0 return; end; gain = eval( result{1} ); end; if exist('gain') ~= 1 gain = 1; end; % load datas % ---------- EEG = eeg_emptyset; [EEG.data,params,events, head] = snapread(filename); EEG.data = EEG.data*gain; EEG.comments = [ 'Original file: ' filename ]; EEG.filepath = ''; EEG.setname = 'SnapMaster file'; EEG.nbchan = params(1); EEG.pnts = params(2); EEG.trials = 1; EEG.srate = params(3); EEG.xmin = 0; A = find(events ~= 0); if ~isempty(A) EEG.event = struct( 'type', mattocell(events(A), [1], ones(1,length(events(A)))), ... 'latency', mattocell(A(:)', [1], ones(1,length(A))) ); end; EEG = eeg_checkset(EEG, 'eventconsistency'); EEG = eeg_checkset(EEG, 'makeur'); command = sprintf('EEG = pop_snapread(''%s'', %f);', filename, gain); return;
github
lcnhappe/happe-master
eeg_decodechan.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_decodechan.m
3,799
utf_8
600c82eb2fe26e4e9b5b1d1af79b383d
% eeg_decodechan() - given an input EEG dataset structure, output a new EEG data structure % retaining and/or excluding specified time/latency, data point, channel, % and/or epoch range(s). % Usage: % >> [chaninds chanlist] = eeg_decodechan(chanlocs, chanlist); % % Inputs: % chanlocs - channel location structure % chanlist - list of channels, numerical indices [1 2 3 ...] or string % 'cz pz fz' or cell array { 'cz' 'pz' 'fz' } % % Outputs: % chaninds - integer array with the list of channel indices % chanlist - cell array with a list of channel labels % % Author: Arnaud Delorme, SCCN/INC/UCSD, 2009- % % see also: eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [ chaninds chanlist ] = eeg_decodechan(chanlocs, chanstr); if nargin < 2 help eeg_decodechan; return; end; if isempty(chanlocs) && isstr(chanstr) chaninds = str2num(chanstr); chanlist = chaninds; return; end; if isstr(chanstr) % convert chanstr % --------------- chanstr(find(chanstr == ']')) = []; chanstr(find(chanstr == '[')) = []; chanlistnum = []; chanstr = [ ' ' chanstr ' ' ]; chanlist = {}; sp = find(chanstr == ' '); for i = 1:length(sp)-1 c = chanstr(sp(i)+1:sp(i+1)-1); if ~isempty(c) chanlist{end+1} = c; if isnan(str2double(chanlocs(1).labels)) % channel labels are not numerical if ~isnan(str2double(c)) chanlistnum(end+1) = str2double(c); end; end; end; end; if length(chanlistnum) == length(chanlist) chanlist = chanlistnum; end; else chanlist = chanstr; end; % convert to values % ----------------- chanval = 0; if isnumeric(chanlist) chanval = chanlist; end; % chanval = []; % if iscell(chanlist) % for ind = 1:length(chanlist) % % valtmp = str2double(chanlist{ind}); % if ~isnan(valtmp) % chanval(end+1) = valtmp; % else chanval(end+1) = 0; % end; % end; % else % chanval = chanlist; % end; % convert to numerical % -------------------- if all(chanval) > 0 chaninds = chanval; chanlist = chanval; else chaninds = []; alllabs = lower({ chanlocs.labels }); chanlist = lower(chanlist); for ind = 1:length(chanlist) indmatch = find(strcmp(alllabs,chanlist{ind})); %#ok<STCI> if ~isempty(indmatch) for tmpi = 1:length(indmatch) chaninds(end+1) = indmatch(tmpi); end; else try, eval([ 'chaninds = ' chanlist{ind} ';' ]); if isempty(chaninds) error([ 'Channel ''' chanlist{ind} ''' not found' ]); else end; catch error([ 'Channel ''' chanlist{ind} ''' not found' ]); end; end; end; end; chaninds = sort(chaninds); if ~isempty(chanlocs) chanlist = { chanlocs(chaninds).labels }; else chanlist = {}; end;
github
lcnhappe/happe-master
eeg_getica.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_getica.m
1,704
utf_8
00350d1cd6a4ab711db93297dd29454d
% eeg_getica() - get ICA component activation. Recompute if necessary. % % >> mergelocs = eeg_getica(EEG, comp); % % Inputs: % EEG - EEGLAB dataset structure % comp - component index % % Output: % icaact - ICA component activity % % Author: Arnaud Delorme, 2006 % Copyright (C) Arnaud Delorme, CERCO, 2006, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function icaact = eeg_getica(EEG, comp) if nargin < 1 help eeg_getica; return; end; if nargin < 2 comp = 1:size(EEG.icaweights,1); end; if ~isempty(EEG.icaact) icaact = EEG.icaact(comp,:,:); else disp('Recomputing ICA activations'); if isempty(EEG.icachansind) EEG.icachansind = 1:EEG.nbchan; disp('Channels indices are assumed to be in regular order and arranged accordingly'); end icaact = (EEG.icaweights(comp,:)*EEG.icasphere)*reshape(EEG.data(EEG.icachansind,:,:), length(EEG.icachansind), EEG.trials*EEG.pnts); icaact = reshape( icaact, size(icaact,1), EEG.pnts, EEG.trials); end;
github
lcnhappe/happe-master
pop_mergeset.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_mergeset.m
13,668
utf_8
307f42bbcf51af31a20f499cdc766249
% pop_mergeset() - Merge two or more datasets. If only one argument is given, % a window pops up to ask for more arguments. % Usage: % >> OUTEEG = pop_mergeset( ALLEEG ); % use a pop-up window % >> OUTEEG = pop_mergeset( ALLEEG, indices, keepall); % >> OUTEEG = pop_mergeset( INEEG1, INEEG2, keepall); % % Inputs: % INEEG1 - first input dataset % INEEG2 - second input dataset % % else % ALLEEG - array of EEG dataset structures % indices - indices of EEG datasets to merge % % keepall - [0|1] 0 -> remove, or 1 -> preserve, ICA activations % of the first dataset and recompute the activations % of the merged data {default: 0} % % Outputs: % OUTEEG - merged dataset % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 01-26-02 change format for events and trial conditions -ad function [INEEG1, com] = pop_mergeset( INEEG1, INEEG2, keepall); com = ''; if nargin < 1 help pop_mergeset; return; end; if isempty(INEEG1) error('needs at least two datasets'); end; if nargin < 2 & length(INEEG1) == 1 error('needs at least two datasets'); end; if nargin == 1 uilist = { { 'style' 'text' 'string' 'Dataset indices to merge' } ... { 'style' 'edit' 'string' '1' } ... { 'style' 'text' 'string' 'Preserve ICA weights of the first dataset ?' } ... { 'style' 'checkbox' 'string' '' } }; res = inputgui( 'uilist', uilist, 'geometry', { [3 1] [3 1] }, 'helpcom', 'pophelp(''pop_mergeset'')'); if isempty(res) return; end; INEEG2 = eval( [ '[' res{1} ']' ] ); keepall = res{2}; else if nargin < 3 keepall = 0; % default end; end; fprintf('Merging datasets...\n'); if ~isstruct(INEEG2) % if INEEG2 is a vector of ALLEEG indices indices = INEEG2; NEWEEG = eeg_retrieve(INEEG1, indices(1)); % why abandoned? for index = 2:length(indices) INEEG2 = eeg_retrieve(INEEG1, indices(index)); NEWEEG = pop_mergeset(NEWEEG, INEEG2, keepall); % recursive call end; INEEG1 = NEWEEG; else % INEEG is an EEG struct % check consistency % ----------------- if INEEG1.nbchan ~= INEEG2.nbchan error('The two datasets must have the same number of channels'); end; if INEEG1.srate ~= INEEG2.srate error('The two datasets must have the same sampling rate'); end; if INEEG1.trials > 1 | INEEG2.trials > 1 if INEEG1.pnts ~= INEEG2.pnts error('The two epoched datasets must have the same number of points'); end; if INEEG1.xmin ~= INEEG2.xmin INEEG2.xmin = INEEG1.xmin; fprintf('Warning: the two epoched datasets do not have the same time onset, adjusted'); end; if INEEG1.xmax ~= INEEG2.xmax INEEG2.xmax = INEEG1.xmax; fprintf('Warning: the two epoched datasets do not have the same time offset, adjusted'); end; end; % repopulate epoch field if necessary % ----------------------------------- if INEEG1.trials > 1 && INEEG2.trials == 1 for iEvent = 1:length(INEEG2.event) INEEG2.event(iEvent).epoch = 1; end; end; if INEEG1.trials == 1 && INEEG2.trials > 1 for iEvent = 1:length(INEEG1.event) INEEG1.event(iEvent).epoch = 1; end; end; % Merge the epoch field % --------------------- if INEEG1.trials > 1 || INEEG2.trials > 1 INEEGX = {INEEG1,INEEG2}; for n = 1:2 % make sure that both have an (appropriately-sized) epoch field % ------------------------------------------------------------- if ~isfield(INEEGX{n},'epoch') INEEGX{n}.epoch = repmat(struct(),[1,INEEGX{n}.trials]); end % make sure that the epoch number is correct in each dataset % ---------------------------------------------------------- if ~isempty(INEEGX{n}.epoch) && length(INEEGX{n}.epoch) ~= INEEGX{n}.trials disp('Warning: The number of trials does not match the length of the EEG.epoch field in one of'); disp(' the datasets. Its epoch info will be reset and derived from the respective events.'); INEEGX{n}.epoch = repmat(struct(),[1,INEEGX{n}.trials]); end end for n=1:2 % purge all event-related epoch fields from each dataset (EEG.epoch.event* fields) % -------------------------------------------------------------------------------- if isstruct(INEEGX{n}.epoch) fn = fieldnames(INEEGX{n}.epoch); INEEGX{n}.epoch = rmfield(INEEGX{n}.epoch,{fn{strmatch('event',fn)}}); % copy remaining field names to the other dataset % ----------------------------------------------- for f = fieldnames(INEEGX{n}.epoch)' if ~isfield(INEEGX{3-n}.epoch,f{1}) INEEGX{3-n}.epoch(1).(f{1}) = []; end end % after this, both sets have an epoch field with the appropriate number of items % and possibly some user-defined fields, but no event* fields. end end % concatenate epochs % ------------------ if isstruct(INEEGX{1}.epoch) && isstruct(INEEGX{2}.epoch) if length(fieldnames(INEEGX{2}.epoch)) > 0 INEEGX{1}.epoch(end+1:end+INEEGX{2}.trials) = orderfields(INEEGX{2}.epoch,INEEGX{1}.epoch); else INEEGX{1}.epoch(end+1:end+INEEGX{2}.trials) = INEEGX{2}.epoch; end; end % and write back INEEG1 = INEEGX{1}; INEEG2 = INEEGX{2}; INEEGX = {}; end % Concatenate data % ---------------- if INEEG1.trials > 1 | INEEG2.trials > 1 INEEG1.data(:,:,end+1:end+size(INEEG2.data,3)) = INEEG2.data(:,:,:); else INEEG1.data(:,end+1:end+size(INEEG2.data,2)) = INEEG2.data(:,:); end; INEEG1.setname = 'Merged datasets'; INEEG1trials = INEEG1.trials; INEEG2trials = INEEG2.trials; INEEG1pnts = INEEG1.pnts; INEEG2pnts = INEEG2.pnts; if INEEG1.trials > 1 | INEEG2.trials > 1 % epoched data INEEG1.trials = INEEG1.trials + INEEG2.trials; else % continuous data INEEG1.pnts = INEEG1.pnts + INEEG2.pnts; end; if isfield(INEEG1, 'reject') INEEG1 = rmfield(INEEG1, 'reject' ); end; INEEG1.specicaact = []; INEEG1.specdata = []; if keepall == 0 INEEG1.icaact = []; INEEG1.icawinv = []; INEEG1.icasphere = []; INEEG1.icaweights = []; if isfield(INEEG1, 'stats') INEEG1 = rmfield(INEEG1, 'stats' ); end; else INEEG1.icaact = []; end; % concatenate events % ------------------ if isempty(INEEG2.event) && INEEG2.trials == 1 && INEEG1.trials == 1 % boundary event % ------------- disp('Inserting boundary event...'); INEEG1.event(end+1).type = 'boundary'; % add boundary event between datasets INEEG1.event(end ).latency = INEEG1pnts+0.5; % make boundary halfway between last,first pts % check urevents % -------------- if ~isfield(INEEG1, 'urevent'), INEEG1.urevent = []; fprintf('Warning: first dataset has no urevent structure.\n'); end; % add boundary urevent % -------------------- disp('Inserting boundary urevent...'); INEEG1.urevent(end+1).type = 'boundary'; if length(INEEG1.urevent) > 1 % if previous INEEG1 urevents INEEG1.urevent(end ).latency = max(INEEG1pnts, INEEG1.urevent(end-1).latency)+0.5; else INEEG1.urevent(end ).latency = INEEG1pnts+0.5; end; else % is ~isempty(INEEG2.event) % concatenate urevents % -------------------- if isfield(INEEG2, 'urevent') if ~isempty(INEEG2.urevent) && isfield(INEEG1.urevent, 'latency') % insert boundary event % --------------------- disp('Inserting boundary event...'); INEEG1.urevent(end+1).type = 'boundary'; try INEEG1.urevent(end ).latency = max(INEEG1pnts, INEEG1.urevent(end-1).latency)+0.5; catch % cko: sometimes INEEG1 has no events / urevents INEEG1.urevent(end ).latency = INEEG1pnts+0.5; end % update urevent indices for second dataset % ----------------------------------------- disp('Concatenating urevents...'); orilen = length(INEEG1.urevent); newlen = length(INEEG2.urevent); INEEG2event = INEEG2.event; % update urevent index in INEEG2.event tmpevents = INEEG2.event; nonemptymask = ~cellfun('isempty',{tmpevents.urevent}); [tmpevents(nonemptymask).urevent] = celldeal(num2cell([INEEG2event.urevent]+orilen)); INEEG2.event = tmpevents; % reserve space and append INEEG2.urevent INEEG1.urevent(orilen+newlen).latency = []; INEEG2urevent = INEEG2.urevent; tmpevents = INEEG1.urevent; for f = fieldnames(INEEG2urevent)' [tmpevents((orilen+1):(orilen+newlen)).(f{1})] = INEEG2urevent.(f{1}); end INEEG1.urevent = tmpevents; else INEEG1.urevent = []; INEEG2.urevent = []; fprintf('Warning: second dataset has empty urevent structure.\n'); end end; % concatenate events % ------------------ disp('Concatenating events...'); orilen = length(INEEG1.event); newlen = length(INEEG2.event); %allfields = fieldnames(INEEG2.event); % add discontinuity event if continuous % ------------------------------------- if INEEG1trials == 1 & INEEG2trials == 1 disp('Adding boundary event...'); INEEG1.event(end+1).type = 'boundary'; INEEG1.event(end ).latency = INEEG1pnts+0.5; INEEG1.event(end ).duration = NaN; orilen = orilen+1; % eeg_insertbound(INEEG1.event, INEEG1.pnts, INEEG1pnts+1, 0); % +1 since 0.5 is subtracted end; % ensure similar event structures % ------------------------------- if ~isempty(INEEG2.event) if isstruct(INEEG1.event) for f = fieldnames(INEEG1.event)' if ~isfield(INEEG2.event,f{1}) INEEG2.event(1).(f{1}) = []; end end end if isstruct(INEEG2.event) for f = fieldnames(INEEG2.event)' if ~isfield(INEEG1.event,f{1}) INEEG1.event(1).(f{1}) = []; end end end INEEG2.event = orderfields(INEEG2.event, INEEG1.event); end; % append % ------ INEEG1.event(orilen + (1:newlen)) = INEEG2.event; INEEG2event = INEEG2.event; if isfield(INEEG1.event,'latency') && isfield(INEEG2.event,'latency') % update latency tmpevents = INEEG1.event; [tmpevents(orilen + (1:newlen)).latency] = celldeal(num2cell([INEEG2event.latency] + INEEG1pnts*INEEG1trials)); INEEG1.event = tmpevents; end if isfield(INEEG1.event,'epoch') && isfield(INEEG2.event,'epoch') % update epoch index tmpevents = INEEG1.event; [tmpevents(orilen + (1:newlen)).epoch] = celldeal(num2cell([INEEG2event.epoch]+INEEG1trials)); INEEG1.event = tmpevents; end end; INEEG1.pnts = size(INEEG1.data,2); if ~isfield(INEEG1.event,'epoch') && ~isempty(INEEG1.event) && (size(INEEG1.data,3)>1 || ~isempty(INEEG1.epoch)) INEEG1.event(1).epoch = []; end % rebuild event-related epoch fields % ---------------------------------- disp('Reconstituting epoch information...'); INEEG1.epoch = []; INEEG1 = eeg_checkset(INEEG1, 'eventconsistency'); end % build the command % ----------------- if exist('indices') == 1 com = sprintf('EEG = pop_mergeset( %s, [%s], %d);', inputname(1), int2str(indices), keepall); else com = sprintf('EEG = pop_mergeset( %s, %s, %d);', inputname(1), inputname(2), keepall); end return function varargout = celldeal(X) varargout = X;
github
lcnhappe/happe-master
pop_importevent.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_importevent.m
12,593
utf_8
6b64e9391f0dca41020312951341bd55
% pop_importevent() - Import events into an EEG dataset. If the EEG dataset % is the only input, a window pops up to ask for the relevant % parameter values. % % Usage: >> EEG = pop_importevent( EEG ); % pop-up window mode % >> EEG = pop_importevent( EEG, 'key1', 'value1', ...); % % Graphic interface: % "Event indices" - [edit box] Enter indices of events to modify. % Leave this field blank to import new events. % Command line equivalent: 'indices'. % "Append events?" - [checkbox] Check this checkbox to clear prior % event information. In addition, see the "Align event latencies ..." % edit box. Command line equivalent: 'append'. % "Event file or array" - [edit box] Enter event file name. Use "Browse" % button to browse for a file. If a file with the given name % cannot be found, the function search for a variable with % this name in the global workspace. % Command line equivalent: 'filename'. % "Input field (column) name" - [edit box] Enter a name for each of the % columns in the event text file. If column names are defined % in the text file, they cannnot be used and you must copy % the names into this edit box (and skip the name row). Must % provide a name for each column. The keywords "type", % "latency", and "duration" are recognized EEGLAB keywords and % should be used to define the event log file columns containing % event types, latencies, and durations. Column names can be % separated by commas, quoted or not. % Command line equivalent: fields. % "Latency time unit (sec)" - [edit box] Specify the time unit for the % latency column defined above relative to seconds. % Command line equivalent: 'timeunit'. % "Number of header lines to ignore" - [edit box] For some text files, the % first rows do not contain epoch information and need to be % skipped. Command line equivalent: 'skiplines'. % "Align event latencies to data events" - [edit box] For most EEG datasets, % basic event information is defined along with the EEG, and % a more detailed file is recorded separately. This option % helps fuse the two sources of information by realigning the % imported data text file information into the existing event. % A value of 0 indicates that the first events of the pre-defined % events and imported events will be aligned. A positive value (num) % aligns the first event to the num-th pre-existing event. % A negative value can also be used; then event number (-num) % is aligned to the first pre-existing event. Default is 0. % (NaN-> no alignment). Command line equivalent is 'align'. % "Auto adjust event sampling rate" - [checkbox] When checked, the function % automatically adjusts the sampling rate of the new events so % they best align with the closest old events. This may account % for small differences in sampling rate that could lead to % big differences at the end of the experiement (e.g., A 0.01% % clock difference over an hour would lead to a 360-ms difference % if not corrected). Command line line equivalent is 'optimalim'. % Input: % EEG - input dataset % % Optional file or array input: % 'event' - [ 'filename'|array ] Filename of a text file, or name of s % Matlab array in the global workspace containing an % array of events in the folowing format: The first column % is the type of the event, the second the latency. % The others are user-defined. The function can read % either numeric or text entries in ascii files. % 'fields' - [Cell array] List of the name of each user-defined column, % optionally followed by a description. Ex: { 'type', 'latency' } % 'skipline' - [Interger] Number of header rows to skip in the text file % 'timeunit' - [ latency unit rel. to seconds ]. Default unit is 1 = seconds. % 'delim' - [string] String of delimiting characters in the input file. % Default is tab|space. % % Optional oldevent input: % 'append' - ['yes'|'no'] 'yes' = Append events to the current events in % the EEG dataset {default}: 'no' = Erase the previous events. % 'indices' - {integer vector] Vector indicating the indices of the events to % modify. % 'align' - [num] Align the first event latency to the latency of existing % event number (num), and check latency consistency. % 'optimalign' - ['on'|'off'] Optimize the sampling rate of the new events so % they best align with old events. Default is 'on'. % % Outputs: % EEG - EEG dataset with updated event fields % % Example: >> [EEG, eventnumbers] = pop_importevent(EEG, 'event', ... % 'event_values.txt', 'fields', {'type', 'latency','condition' }, ... % 'append', 'no', 'align', 0, 'timeunit', 1E-3 ); % % This loads the ascii file 'event_values.txt' containing 3 columns % (event_type, latency, and condition). Latencies in the file are % in ms (1E-3). The first event latency is re-aligned with the % beginning of the dataset ('align', 0). Any previous events % are erased ('append', 'no'). % % Author: Arnaud Delorme & Scott Makeig, CNL / Salk Institute, 9 Feb 2002 % % See also: importevent(), pop_editeventfield(), pop_selectevent() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 9 Feb 2002, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, com] = pop_importevent(EEG, varargin); com =''; if nargin < 1 help pop_importevent; return; end; if isempty(EEG.data) disp('pop_importevent(): error: cannot process empty dataset'); return; end; I = []; % warning if data epochs % ---------------------- if nargin<2 & EEG.trials > 1 questdlg2(strvcat('Though epoch information is defined in terms of the event structure,', ... 'this function is usually used to import events into continuous data.', ... 'For epoched data, use menu item ''File > Import epoch info'''), ... 'pop_importevent warning', 'OK', 'OK'); end; % remove the event field % ---------------------- if ~isempty(EEG.event), allfields = fieldnames(EEG.event); else allfields = {}; end; if nargin<2 commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ... 'if filename ~=0,' ... ' set(findobj(''parent'', gcbf, ''tag'', tagtest), ''string'', [ filepath filename ]);' ... 'end;' ... 'clear filename filepath tagtest;' ]; helpfields = ['latency field (lowercase) must be present; field ''type'' and' 10 ... '''duration'' are also recognized keywords and it is recommended to define them']; uilist = { ... { 'Style', 'text', 'string', 'Event indices', 'fontweight', 'bold' }, ... { 'Style', 'text', 'string', 'Append events?', 'fontweight', 'bold' } }; geometry = { [ 1 1.1 1.1 1] [ 1 1 2] [1 1 2] [ 1.2 1 1] }; uilist = { uilist{:}, ... { 'Style', 'text', 'string', 'Event file or array', 'horizontalalignment', 'right', 'fontweight', 'bold' }, ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''globfile'';' commandload ] }, ... { 'Style', 'edit' } ... { 'Style', 'checkbox', 'string', 'Yes/No', 'value', 0 }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'globfile' }, ... { }, { 'Style', 'text', 'string', 'NB: No = overwrite', 'value', 0 }, { }, ... { 'Style', 'text', 'string', 'Input field (column) names ', 'fontweight', 'bold', 'tooltipstring', helpfields } ... { 'Style', 'edit', 'string', '' } { 'Style', 'text', 'string', 'Ex: type latency duration', 'tooltipstring', helpfields } }; geometry = { geometry{:} [1.2 1 1] [1.2 1 1] [1.2 1 1] [1.2 0.2 1.8] }; uilist = { uilist{:}, ... { 'Style', 'text', 'string', 'Number of file header lines', 'horizontalalignment', 'left' }, { 'Style', 'edit', 'string', '0' }, ... { 'Style', 'text', 'string', '(latency field required above)', 'tooltipstring', helpfields },... { 'Style', 'text', 'string', 'Time unit (sec)', 'horizontalalignment', 'left' }, { 'Style', 'edit', 'string', '1' } ... { 'Style', 'text', 'string', 'Ex: If ms, 1E-3; if points, NaN' },... { 'Style', 'text', 'string', 'Align event latencies to data events', 'horizontalalignment', 'left' }, ... { 'Style', 'edit', 'string', fastif(isempty(EEG.event),'NaN','0') } { 'Style', 'text', 'string', 'See Help' },... { 'Style', 'text', 'string', 'Auto adjust new events sampling rate', 'horizontalalignment', 'left' }, ... { 'Style', 'checkbox', 'value' 1 } { },... }; results = inputgui( geometry, uilist, 'pophelp(''pop_importevent'');', 'Import event info -- pop_importevent()' ); if length(results) == 0, return; end; % decode top inputs % ----------------- args = {}; if ~isempty( results{1} ), args = { args{:}, 'indices', eval( [ '[' results{1} ']' ]) }; end; if results{2} == 0 & ~isempty(EEG.event), args = { args{:}, 'append', 'no' }; end; if ~isempty( results{3} ), if isstr( results{3} ) && ~exist(results{3}) args = { args{:}, 'event', evalin('base', results{3}) }; else args = { args{:}, 'event', results{3} }; end; end; if ~isempty( results{4} ), args = { args{:}, 'fields', parsetxt(results{4}) }; end; % handle skipline % --------------- if ~isempty(eval(results{end-3})), if eval(results{end-3}) ~= 0, args = { args{:}, 'skipline', eval(results{end-3}) }; end; end; % handle timeunit % ------------- if ~isempty(eval(results{end-2})), if eval(results{end-2}) ~= 0, args = { args{:}, 'timeunit', eval(results{end-2}) }; end; end; % handle alignment % ---------------- if ~isempty(eval(results{end-1})), if ~isnan(eval(results{end-1})), args = { args{:}, 'align', eval(results{end-1}) }; end; end; if ~results{end} ~= 0, args = { args{:}, 'optimalign', 'off' }; end; else % no interactive inputs args = varargin; % scan args to modify array/file format % array are transformed into string % files are transformed into string of string % (this is usefull to build the string command for the function) % -------------------------------------------------------------- for index=1:2:length(args) if iscell(args{index+1}), if iscell(args{index+1}{1}) args{index+1} = args{index+1}{1}; end; end; % double nested if isstr(args{index+1}) & length(args{index+1}) > 2 & args{index+1}(1) == '''' & args{index+1}(end) == '''' args{index+1} = args{index+1}(2:end-1); end; %else if ~isempty( inputname(index+2) ), args{index+1} = inputname(index+2); end; %end; end; end; EEG.event = importevent( [], EEG.event, EEG.srate, args{:}); % generate ur variables % --------------------- EEG = eeg_checkset(EEG, 'eventconsistency'); EEG = eeg_checkset(EEG, 'makeur'); % generate the output command % --------------------------- com = sprintf('%s = pop_importevent( %s, %s);', inputname(1), inputname(1), vararg2str(args));
github
lcnhappe/happe-master
eeg_eventtypes.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_eventtypes.m
5,504
utf_8
d106acb9a7c18278b36620b4a206edb5
% eeg_eventtypes() - return a list of event or urevent types in a dataset and % the respective number of events of each type. Ouput event % types are sorted in reverse order of their number. If no % outputs, print this list on the commandline instead. % % Usage: % >> [types,numbers] = eeg_eventtypes(EEG); % Inputs: % EEG - EEGLAB dataset structure % Outputs: % types - cell array of event type strings % numbers - vector giving the numbers of each event type in the data % % Example: % >> eeg_eventtypes(EEG); % print numner of each event types % % Author: Scott Makeig, SCCN/INC/UCSD, April 28, 2004- % >> [types,numbers] = eeg_eventtypes(EEG,types); % >> [types,numbers] = eeg_eventtypes(EEG,'urevents',types); % Inputs: % EEG - EEGLAB dataset structure % 'urevents' - return event information for the EEG.urevent structure % types - {cell array} of event types to return or print. % Outputs: % types - cell array of event type strings % numbers - vector giving the numbers of each event type in the data % % Note: Numeric (ur)event types are converted to strings, so, for example, % types {13} and {'13'} are not distinguished. % % Example: % >> eeg_eventtypes(EEG); % print numner of each event types % % Curently disabled: % >> eeg_eventtypes(EEG,'urevent'); % print hist. of urevent types % >> eeg_eventtypes(EEG,{'rt'});% print number of 'rt' events % >> eeg_eventtypes(EEG,'urevent',{'rt','break'}); % % print numbers of 'rt' and 'break' % % type urevents % Copyright (C) 2004 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % % % event types can be numbers, Stefan Debener, 05/12/2006, % added 2nd and 3rd args, sorted outputs by number, Scott Makeig, 09/12/06 function [types,numbers] = eeg_eventtypes(EEG,arg2,arg3) if nargin< 1 help eeg_eventtypes return end if ~isstruct(EEG) error('EEG argument must be a dataset structure') end if ~isfield(EEG,'event') error('EEG.event field not found'); end if nargin > 1 error('Multiple input arguments are currently disabled'); end; UREVENTS = 0; % flag returning infor for urevents instead of events typelist = []; if nargin>1 if ischar(arg2) if strcmp(arg2,'urevent') | strcmp(arg2,'urevents') UREVENTS = 1; % change flag else error('second argument string not understood') end if nargin>2 if iscell(arg3) typelist = arg3; end end elseif iscell(arg2) typelist = arg2; end end if ~isempty(typelist) % cast to cell array of strings for k=1:length(typelist) if isnumeric(typelist{k}) typelist{k} = num2str(typelist{k}); end end end if ~UREVENTS nevents = length(EEG.event); alltypes = cell(nevents,1); for k=1:nevents if isnumeric(EEG.event(k).type) alltypes{k} = num2str(EEG.event(k).type); else alltypes{k} = EEG.event(k).type; end end else nevents = length(EEG.urevent); alltypes = cell(nevents,1); for k=1:nevents if isnumeric(EEG.urevent(k).type) alltypes{k} = num2str(EEG.urevent(k).type); else alltypes{k} = EEG.urevent(k).type; end end end [types i j] = unique_bc(alltypes); istypes = 1:length(types); notistypes = []; if ~isempty(typelist) notistypes = ismember_bc(typelist,types); istypes = ismember_bc(types,typelist(find(notistypes==1))); % types in typelist? notistypes = typelist(find(notistypes==0)); end types(~istypes) = []; % restrict types to typelist ntypes = length(types); numbers = zeros(ntypes + length(notistypes),1); for k=1:ntypes numbers(k) = length(find(j==k)); end types = [types(:); notistypes(:)]; % concatenate the types not found ntypes = length(types); for j = 1:length(notistypes) numbers(k+j) = 0; end % sort types in reverse order of event numbers [numbers nsort] = sort(numbers); numbers = numbers(end:-1:1); types = types(nsort(end:-1:1)); % % print output on commandline %%%%%%%%%%%%%%%%%%%%%%%%%%%% % if nargout < 1 fprintf('\n'); if UREVENTS fprintf('EEG urevent types:\n\n') else fprintf('EEG event types:\n\n') end maxx = 0; for k=1:ntypes x = length(types{k}); if x > maxx maxx = x; % find max type name length end end for k=1:ntypes fprintf(' %s',types{k}); for j=length(types{k})+1:maxx+4 fprintf(' '); end fprintf('%d\n',numbers(k)); end fprintf('\n'); clear types % no return variables end
github
lcnhappe/happe-master
pop_signalstat.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_signalstat.m
5,079
utf_8
5066bdd6d63e075bfeaf649483b7b2bb
% pop_signalstat() - Computes and plots statistical characteristics of a signal, % including the data histogram, a fitted normal distribution, % a normal ditribution fitted on trimmed data, a boxplot, and % the QQ-plot. The estimates value are printed in a panel and % can be read as output. See SIGNALSTAT. % Usage: % >> OUTEEG = pop_signalstat( EEG, type ); % pops up % >> [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh] = pop_signalstat( EEG, type, cnum ); % >> [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh] = pop_signalstat( EEG, type, cnum, percent ); % % Inputs: % EEG - input EEG dataset % type - type of processing % 1: process the raw data; 0: the ICA components % cnum - selected channel or component % % Outputs: % OUTEEG - output dataset % % Author: Luca Finelli, CNL / Salk Institute - SCCN, 2 August 2002 % % See also: % SIGNALSTAT, EEGLAB % Copyright (C) 2002 Luca Finelli, Salk/SCCN, La Jolla, CA % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function varargout = pop_signalstat( EEG, typeproc, cnum, percent ); % the command output is a hidden output that does not have to % be described in the header com = ''; % this initialization ensure that the function will return something % if the user press the cancel button varargout{1} = ''; % display help if not enough arguments % ------------------------------------ if nargin < 2 help pop_signalstat; return; end; popup=0; if nargin < 3 popup = 1; end; if nargin < 4 percent=5; end; % pop up window % ------------- if (nargin < 3 & typeproc==1) promptstr = { 'Channel number:'; 'Trim percentage (each end):' }; inistr = { '1';'5' }; result = inputdlg2( promptstr, 'Plot signal statistics -- pop_signalstat()', 1, inistr, 'signalstat'); if length( result ) == 0 return; end; cnum = eval( [ '[' result{1} ']' ] ); % the brackets allow processing Matlab arrays percent = eval( [ '[' result{2} ']' ] ); elseif (nargin < 3 & typeproc==0) promptstr = { 'Component number:'; 'Trim percentage (each end):' }; inistr = { '1'; '5' }; result = inputdlg2( promptstr, 'Plot signal statistics -- pop_signalstat()', 1, inistr, 'signalstat'); if length( result ) == 0 return; end; cnum = eval( [ '[' result{1} ']' ] ); % the brackets allow processing Matlab arrays percent = eval( [ '[' result{2} ']' ] ); end; if length(cnum) ~= 1 | (cnum-floor(cnum)) ~= 0 error('pop_signalstat(): Channel/component number must be a single integer'); end if cnum < 1 | cnum > EEG.nbchan error('pop_signalstat(): Channel/component number out of range'); end; % call function signalstat() either on raw data or ICA data % --------------------------------------------------------- if typeproc == 1 tmpsig=EEG.data(cnum,:); % [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh]=signalstat( EEG.data(cnum,:),1,[], percent); dlabel=[]; dlabel2=['Channel ' num2str(cnum)]; map = cnum; else if ~isempty( EEG.icasphere ) tmpsig = eeg_getdatact(EEG, 'component', cnum); tmpsig = tmpsig(:,:); % [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh]=signalstat( tmpsig,1,'Component Activity',percent); dlabel='Component Activity'; dlabel2=['Component ' num2str(cnum)]; map = EEG.icawinv(:,cnum); else error('You must run ICA first'); end; end; % outputs % ------- outstr = ''; if ~popup for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end; if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end; end; % return the string command % ------------------------- %fprintf('Pop_signalstat: computing statistics...\n'); varargout{1} = sprintf('pop_signalstat( %s, %d, %d );', inputname(1), typeproc, cnum); plotloc = 0; if ~isempty(EEG.chanlocs) if isfield(EEG.chanlocs, 'theta') if ~isempty(EEG.chanlocs(cnum).theta) plotloc = 1; end; end; end; if plotloc if typeproc == 1 com = sprintf('%s signalstat( tmpsig, 1, dlabel, percent, dlabel2, map, EEG.chanlocs );', outstr); else com = sprintf('%s signalstat( tmpsig, 1, dlabel, percent, dlabel2, map, EEG.chanlocs(EEG.icachansind) );', outstr); end; else com = sprintf('%s signalstat( tmpsig, 1, dlabel, percent, dlabel2);', outstr); end; eval(com) try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; return;
github
lcnhappe/happe-master
pop_rejchanspec.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_rejchanspec.m
10,691
utf_8
8549b5c2d8a05e2ca0aa177b4a248efc
% pop_rejchanspec() - reject artifacts channels in an EEG dataset using % channel spectrum. The average spectrum for all selected % is computed and a threshold is applied. % % Usage: % >> pop_rejchanspec( INEEG ) % pop-up interative window mode % >> [OUTEEG, indelec] = pop_rejchanspec( INEEG, 'key', 'val'); % % Inputs: % INEEG - input EEGLAB dataset % % Optional inputs: % 'freqlims' - [min max] frequency limits. May also be an array where % each row defines a different set of limits. Default is % 35 to the Niquist frequency of the data. % 'stdthresh' - [max] positive threshold in terms of standard deviation. % Default is 5. % 'absthresh' - [max] positive threshold in terms of spectrum units % (overides the option above). % 'averef' - ['on'|'off'] 'on' computes average reference before % applying threshold. Default is 'off'. % 'plothist' - ['on'|'off'] 'on' plot the histogram of values along % with the threshold. % 'plotchans' - ['on'|'off'] 'on' plot the channels scrollplot with % selected channels for rejection in red. Allow selected % channels rejection with the 'REJECT' button. % 'elec' - [integer array] only include specific channels. Default % is to use all channels. % 'specdata' - [fload array] use this array containing the precomputed % spectrum instead of computing the spectrum. Default is % empty. % 'specfreqs' - [fload array] frequency array for precomputed spectrum % above. % 'verbose' - ['on'|'off'] display information. Default is 'off'. % % Outputs: % OUTEEG - output dataset with updated joint probability array % indelec - indices of rejected electrodes % specdata - data spectrum for the selected channels % specfreqs - frequency array for spectrum above % % Author: Arnaud Delorme, CERCO, UPS/CNRS, 2008- % Copyright (C) 2008 Arnaud Delorme, CERCO, UPS/CNRS % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG allrmchan specdata specfreqs com] = pop_rejchanspec(EEG, varargin) if nargin < 1 help pop_rejchanspec; return; end; allrmchan = []; specdata = []; specfreqs = []; com = ''; if nargin < 2 uilist = { { 'style' 'text' 'string' 'Electrode (number(s); Ex: 2 4 5)' } ... { 'style' 'edit' 'string' ['1:' int2str(EEG.nbchan)] } ... { 'style' 'text' 'string' 'Frequency limits [min max]' } ... { 'style' 'edit' 'string' [ '35 ' int2str(floor(EEG.srate/2)) ] } ... { 'style' 'text' 'string' 'Standard dev. threshold limits [max]' } ... { 'style' 'edit' 'string' '5' } ... { 'style' 'text' 'string' 'OR absolute threshold limit [min max]' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Compute average reference first (check=on)' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } { } ... { 'style' 'text' 'string' 'Plot histogram of power values (check=on)' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } { } ... { 'style' 'text' 'string' 'Plot channels scrollplot (check=on)' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } { } ... }; geom = { [2 1] [2 1] [2 1] [2 1] [2 0.3 0.7] [2 0.3 0.7] [2 0.3 0.7] }; result = inputgui( 'uilist', uilist, 'geometry', geom, 'title', 'Reject channel using spectrum -- pop_rejchanspec()', ... 'helpcom', 'pophelp(''pop_rejchan'')'); if isempty(result), return; end; options = { 'elec' eval( [ '[' result{1} ']' ] ) 'stdthresh' str2num(result{3}) 'freqlims' str2num(result{2}) }; if ~isempty(result{4}) options = { options{:} 'absthresh' str2num(result{4}) }; end; if result{5}, options = { options{:} 'averef', 'on' }; end; if result{6}, options = { options{:} 'plothist', 'on' }; end; % Begin: Added by Romain on 22 July 2010 if result{7}, options = { options{:} 'plotchans', 'on' }; end; % End: Added by Romain on 22 July 2010 else options = varargin; end; % decode options % -------------- opt = finputcheck( options, { 'averef' 'string' { 'on';'off' } 'off'; 'plothist' 'string' { 'on';'off' } 'off'; 'plotchans' 'string' { 'on';'off' } 'off'; 'verbose' 'string' { 'on';'off' } 'off'; 'elec' 'integer' [] [1:EEG.nbchan]; 'freqlims' 'real' [] [35 EEG.srate/2]; 'specdata' 'real' [] []; 'specfreqs' 'real' [] []; 'absthresh' 'real' [] []; 'stdthresh' 'real' [] 5 }, 'pop_rejchanspec'); if isstr(opt), error(opt); end; % compute average referecne if necessary if strcmpi(opt.averef, 'on') NEWEEG = pop_reref(EEG, [], 'exclude', setdiff([1:EEG.nbchan], opt.elec)); else NEWEEG = EEG; end; if isempty(opt.specdata) [tmpspecdata specfreqs] = pop_spectopo(NEWEEG, 1, [], 'EEG' , 'percent', 100, 'freqrange',[0 EEG.srate/2], 'plot', 'off'); % add back 0 channels devStd = std(EEG.data(:,:), [], 2); if any(devStd == 0) goodchan = find(devStd ~= 0); specdata = zeros(length(opt.elec), size(tmpspecdata,2)); specdata(goodchan,:) = tmpspecdata; else specdata = tmpspecdata; end; else specdata = opt.specdata; specfreqs = opt.specfreqs; end; if size(opt.stdthresh,1) == 1 && size(opt.freqlims,1) > 1 opt.stdthresh = ones(length(opt.stdthresh), size(opt.freqlims,1))*opt.stdthresh; end; allrmchan = []; for index = 1:size(opt.freqlims,1) % select frequencies, compute median and std then reject channels % --------------------------------------------------------------- [tmp fbeg] = min(abs(specfreqs - opt.freqlims(index,1))); [tmp fend] = min(abs(specfreqs - opt.freqlims(index,2))); selectedspec = mean(specdata(opt.elec, fbeg:fend), 2); if ~isempty(opt.absthresh) rmchan = find(selectedspec <= opt.absthresh(1) | selectedspec >= opt.absthresh(2)); else m = median(selectedspec); s = std( selectedspec); nbTresh = size(opt.stdthresh); if length(opt.stdthresh) > 1 rmchan = find(selectedspec <= m+s*opt.stdthresh(index,1) | selectedspec >= m+s*opt.stdthresh(index,2)); else rmchan = find(selectedspec > m+s*opt.stdthresh(index)); end end; % print out results % ----------------- if isempty(rmchan) textout = sprintf('Range %2.1f-%2.1f Hz: no channel removed\n', opt.freqlims(index,1), opt.freqlims(index,2)); else textout = sprintf('Range %2.1f-%2.1f Hz: channels %s removed\n', opt.freqlims(index,1), opt.freqlims(index,2), int2str(opt.elec(rmchan'))); end; fprintf(textout); if strcmpi(opt.verbose, 'on') for inde = 1:length(opt.elec) if ismember(inde, rmchan) fprintf('Elec %s power: %1.2f *\n', EEG.chanlocs(opt.elec(inde)).labels, selectedspec(inde)); else fprintf('Elec %s power: %1.2f\n', EEG.chanlocs(opt.elec(inde)).labels , selectedspec(inde)); end; end; end; allrmchan = [ allrmchan rmchan' ]; % plot histogram % -------------- if strcmpi(opt.plothist, 'on') figure; hist(selectedspec); hold on; yl = ylim; if ~isempty(opt.absthresh) plot([opt.absthresh(1) opt.absthresh(1)], yl, 'r'); plot([opt.absthresh(2) opt.absthresh(2)], yl, 'r'); else if length(opt.stdthresh) > 1 threshold1 = m+s*opt.stdthresh(index,1); threshold2 = m+s*opt.stdthresh(index,2); plot([m m], yl, 'g'); plot([threshold1 threshold1], yl, 'r'); plot([threshold2 threshold2], yl, 'r'); else threshold = m+s*opt.stdthresh(index,1); plot([threshold threshold], yl, 'r'); end end; title(textout); end; end; allrmchan = unique_bc(allrmchan); com = sprintf('EEG = pop_rejchan(EEG, %s);', vararg2str(options)); if strcmpi(opt.plotchans, 'on') tmpcom = [ 'EEGTMP = pop_select(EEG, ''nochannel'', [' num2str(opt.elec(allrmchan)) ']);' ]; tmpcom = [ tmpcom ... 'LASTCOM = ' vararg2str(com) ';' ... '[ALLEEG EEG CURRENTSET tmpcom] = pop_newset(ALLEEG, EEGTMP, CURRENTSET);' ... ' if ~isempty(tmpcom),' ... ' EEG = eegh(LASTCOM, EEG);' ... ' eegh(tmpcom);' ... ' eeglab(''redraw'');' ... ' end; clear EEGTMP tmpcom;' ]; colors = cell(1,length(opt.elec)); colors(:) = { 'k' }; colors(allrmchan) = { 'r' }; colors = colors(end:-1:1); fprintf('%d electrodes labeled for rejection\n', length(find(allrmchan))); tmpchanlocs = EEG.chanlocs; if ~isempty(EEG.chanlocs), tmplocs = EEG.chanlocs(opt.elec); tmpelec = { tmpchanlocs(opt.elec).labels }'; else tmplocs = []; tmpelec = mattocell([1:EEG.nbchan]'); end; eegplot(EEG.data(opt.elec,:,:), 'srate', EEG.srate, 'title', 'Scroll component activities -- eegplot()', ... 'limits', [EEG.xmin EEG.xmax]*1000, 'color', colors, 'eloc_file', tmplocs, 'command', tmpcom); else EEG = pop_select(EEG, 'nochannel', opt.elec(allrmchan)); end; if nargin < 2 allrmchan = sprintf('EEG = pop_rejchanspec(EEG, %s);', vararg2str(options)); end;
github
lcnhappe/happe-master
pop_rejtrend.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_rejtrend.m
9,362
utf_8
8dba06eafda1461d9b44d39f9dfa3e5f
% pop_rejtrend() - Measure linear trends in EEG data; reject data epochs % containing strong trends. % Usage: % >> pop_rejtrend( INEEG, typerej); % pop up an interactive window % >> OUTEEG = pop_rejtrend( INEEG, typerej, elec_comp, ... % winsize, maxslope, minR, superpose, reject,calldisp); % % Pop-up window interface: % "Electrode|Component indices(s)" - [edit box] electrode or component indices % to take into consideration during rejection. Sets the 'elec_comp' % parameter in the command line call (see below). % "Slope window width" - [edit box] integer number of consecutive data % points to use in detecting linear trends. Sets the 'winsize' % parameter in the command line call. % "Maximum slope to allow" - [edit box] maximal absolute slope of the % linear trend to allow in the data. If electrode data, uV/epoch; % if component data, std. dev./epoch. Sets the 'maxslope' % parameter in the command line call. % "R-square limit" -[edit box] maximal regression R-square (0 to 1) value % to allow. Sets the 'minR' parameter in the command line call. % This represents how "line-like" the rejected data should be; 0 % accepts everything that meets the slope requirement, 0.9 is visibly % flat. % "Display with previous rejection(s)" - [checkbox] This checkbox set the % command line input option 'superpose'. % "Reject marked trial(s)" - [checkbox] This checkbox set the command % line input option 'reject'. % Command line inputs: % INEEG - input EEG dataset % typerej - [1|0] data to reject on: 0 = component activations; % 1 = electrode data. {Default: 1}. % elec_comp - [e1 e2 ...] electrode|component number(s) to take into % consideration during rejection % winsize - (integer) number of consecutive points % to use in detecing linear trends % maxslope - maximal absolute slope of the linear trend to allow in the data % minR - minimal linear regression R-square value to allow in the data % (= coefficient of determination, between 0 and 1) % superpose - [0|1] 0 = Do not superpose marks on previous marks % stored in the dataset; 1 = Show both types of marks using % different colors. {Default: 0} % reject - [1|0] 0 = Do not reject marked trials but store the % labels; 1 = Reject marked trials. {Default: 1} % calldisp - [0|1] 1 = Open scroll window indicating rejected trials % 0 = Do not open scroll window. {Default: 1} % % Outputs: % OUTEEG - output dataset with rejected trials marked for rejection % Note: When eegplot() is called, modifications are applied to the current % dataset at the end of the call to eegplot() (e.g., when the user presses % the 'Reject' button). % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: rejtrend(), eeglab(), eegplot(), pop_rejepoch() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-07-02 added srate argument to eegplot call -ad % 03-07-02 add the eeglab options -ad function [EEG, com] = pop_rejtrend( EEG, icacomp, elecrange, winsize, ... minslope, minstd, superpose, reject, calldisp); com = ''; if nargin < 1 help pop_rejtrend; return; end; if nargin < 2 icacomp = 1; end; if icacomp == 0 if isempty( EEG.icasphere ) ButtonName=questdlg( 'Do you want to run ICA now ?', ... 'Confirmation', 'NO', 'YES', 'YES'); switch ButtonName, case 'NO', disp('Operation cancelled'); return; case 'YES', [ EEG com ] = pop_runica(EEG); end % switch end; end; if exist('reject') ~= 1 reject = 1; end; if nargin < 3 % which set to save % ----------------- promptstr = { [fastif(icacomp, 'Electrode', 'Component') ' (indices; Ex: 2 6:8 10):' ], ... 'Slope window width (in points)', ... [fastif(icacomp,'Maximum slope to allow (std. dev./epoch)','Maximum slope to allow (uV/epoch)')], ... 'R-square limit to allow ([0:1], Ex: 0.8)', ... 'Display previous rejection marks', ... 'Reject marked trial(s)' }; inistr = { ['1:' int2str(EEG.nbchan)], ... int2str(EEG.pnts), ... '0.5', ... '0.3', ... '0', ... '0' }; g1 = [1 0.1 0.75]; g2 = [1 0.22 0.85]; geometry = {g1 g1 g1 g1 1 g2 g2}; uilist = {... { 'Style', 'text', 'string', promptstr{1}} {} { 'Style','edit' ,'string' ,inistr{1} 'tag' 'cpnum'}... { 'Style', 'text', 'string', promptstr{2}} {} { 'Style','edit' ,'string' ,inistr{2} 'tag' 'win' }... { 'Style', 'text', 'string', promptstr{3}} {} { 'Style','edit' ,'string' ,inistr{3} 'tag' 'maxslope'}... { 'Style', 'text', 'string', promptstr{4}} {} { 'Style','edit' ,'string' ,inistr{4} 'tag' 'rlim'}... {}... { 'Style', 'text', 'string', promptstr{5}} {} { 'Style','checkbox' ,'string' ,' ' 'value' str2double(inistr{6}) 'tag','rejmarks' }... { 'Style', 'text', 'string', promptstr{6}} {} { 'Style','checkbox' ,'string' ,' ' 'value' str2double(inistr{6}) 'tag' 'rejtrials'} ... }; figname = fastif(~icacomp, 'Trend rejection in component(s) -- pop_rejtrend()','Data trend rejection -- pop_rejtrend()'); result = inputgui( geometry,uilist,'pophelp(''pop_rejtrend'');', figname); size_result = size( result ); if size_result(1) == 0 return; end; elecrange = result{1}; winsize = result{2}; minslope = result{3}; minstd = result{4}; superpose = result{5}; reject = result{6}; calldisp = 1; end; if ~exist('superpose','var'), superpose = 0; end; if ~exist('reject','var'), reject = 0; end; if ~exist('calldisp','var'), calldisp = 1; end; if nargin < 9 calldisp = 1; end if isstr(elecrange) % convert arguments if they are in text format calldisp = 1; elecrange = eval( [ '[' elecrange ']' ] ); winsize = eval( [ '[' winsize ']' ] ); minslope = eval( [ '[' minslope ']' ] ); minstd = eval( [ '[' minstd ']' ] ); end; fprintf('Selecting trials...\n'); if icacomp == 1 [rej tmprejE] = rejtrend( EEG.data(elecrange, :, :), winsize, minslope, minstd); rejE = zeros(EEG.nbchan, length(rej)); rejE(elecrange,:) = tmprejE; else % test if ICA was computed or if one has to compute on line % --------------------------------------------------------- icaacttmp = eeg_getdatact(EEG, 'component', elecrange); [rej tmprejE] = rejtrend( icaacttmp, winsize, minslope, minstd); rejE = zeros(size(icaacttmp,1), length(rej)); rejE(elecrange,:) = tmprejE; end rejtrials = find(rej > 0); fprintf('%d channel(s) selected\n', size(elecrange(:), 1)); fprintf('%d/%d trial(s) marked for rejection\n', length(rejtrials), EEG.trials); fprintf('The following trials have been marked for rejection\n'); fprintf([num2str(rejtrials) '\n']); if calldisp if icacomp == 1 macrorej = 'EEG.reject.rejconst'; macrorejE = 'EEG.reject.rejconstE'; else macrorej = 'EEG.reject.icarejconst'; macrorejE = 'EEG.reject.icarejconstE'; end; colrej = EEG.reject.rejconstcol; eeg_rejmacro; % script macro for generating command and old rejection arrays if icacomp == 1 eegplot( EEG.data(elecrange,:,:), 'srate', ... EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}); else eegplot( icaacttmp, 'srate', ... EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}); end; end; if ~isempty(rej) if icacomp == 1 EEG.reject.rejconst = rej; EEG.reject.rejconstE = rejE; else EEG.reject.icarejconst = rej; EEG.reject.icarejconstE = rejE; end; if reject EEG = pop_rejepoch(EEG, rej, 0); end; end; %com = sprintf('Indexes = pop_rejtrend( %s, %d, [%s], %s, %s, %s, %d, %d);', ... % inputname(1), icacomp, num2str(elecrange), num2str(winsize), num2str(minslope), num2str(minstd), superpose, reject ); com = [ com sprintf('%s = pop_rejtrend(%s,%s);', inputname(1), ... inputname(1), vararg2str({icacomp,elecrange,winsize,minslope,minstd,superpose,reject})) ]; return;