plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
lcnhappe/happe-master
|
std_rejectoutliers.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_rejectoutliers.m
| 5,458 |
utf_8
|
5295d178e50afb94a6b71303a3d9aaa9
|
% std_rejectoutliers() - Commandline function, to reject outlier component(s) from clusters.
% Reassign the outlier component(s) to an outlier cluster specific to each cluster.
% Usage:
% >> [STUDY] = std_rejectoutliers(STUDY, ALLEEG, clusters, th);
% Inputs:
% STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - global EEGLAB vector of EEG structures for the dataset(s) included in the STUDY.
% ALLEEG for a STUDY set is typically created using load_ALLEEG().
% Optional inputs:
% clusters - [numeric vector| 'all' ] specific cluster numbers (or 'all' clusters), which outliers
% will be rejected from. {default:'all'}.
% th - [number] a threshold factor to select outliers. How far a component can be from the
% cluster centroid (in the cluster std multiples) befor it will be considered as an outlier.
% Components that their distance from the cluster centroid are more than this factor
% times the cluster std (th *std) will be rejected. {default: 3}.
%
% Outputs:
% STUDY - the input STUDY set structure modified with the components reassignment,
% from the cluster to its outlier cluster.
%
% Example:
% >> clusters = [10 15]; th = 2;
% >> [STUDY] = std_rejectoutliers(STUDY, ALLEEG, clusters, th);
% Reject outlier components (that are more than 2 std from the cluster centroid) from cluster 10 and 15.
%
% See also pop_clustedit
%
% Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, July, 2005
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, July 11, 2005, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function STUDY = std_rejectoutliers(STUDY, ALLEEG, varargin)
cls = 2:length(STUDY.cluster); % all clusters in STUDY
th = 3; % The threshold factor - default: 3
if length(varargin) > 1
if isnumeric(varargin{1})
cls = varargin{1};
if isempty(cls)
cls = 2:length(STUDY.cluster);
end
else
if isstr(varargin{1}) & strcmpi(varargin{1}, 'all')
cls = 2:length(STUDY.cluster);
else
error('std_prejectoutliers: clusters input takes either specific clusters (numeric vector) or keyword ''all''.');
end
end
end
tmp =[];
for k = 1: length(cls)
% don't include 'Notclust' clusters
if ~strncmpi('Notclust',STUDY.cluster(cls(k)).name,8) & ~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13)
tmp = [tmp cls(k)];
end
end
cls = tmp;
clear tmp
if length(varargin) == 2
if isnumeric(varargin{2})
th = varargin{2};
else
error('std_prejectoutliers: std input must be a numeric value.');
end
end
% Perform validity checks
for k = 1:length(cls)
% Cannot reject outlier components if cluster is a 'Notclust' or 'Outlier' cluster
if strncmpi('Notclust',STUDY.cluster(cls(k)).name,8) | strncmpi('Outliers',STUDY.cluster(cls(k)).name,8) | ...
strncmpi('ParentCluster', STUDY.cluster(cls(k)).name,13)
warndlg2('Cannot reject outlier components from a Notclust or Outliers cluster');
return;
end
% Cannot reject outlier components if cluster has children clusters
if ~isempty(STUDY.cluster(cls(k)).child)
warndlg2('Cannot reject outlier components if cluster has children clusters.');
return;
end
% If the PCA data matrix of the cluster components is empty (case of merged cluster)
if isempty(STUDY.cluster(cls(k)).preclust.preclustdata) % No preclustering information
warndlg2('Cannot reject outlier components if cluster was not a part of pre-clustering.');
return;
end
end
% For each of the clusters reject outlier components
for k = 1:length(cls)
% The PCA data matrix of the cluster components
clsPCA = STUDY.cluster(cls(k)).preclust.preclustdata;
% The cluster centroid
clsCentr = mean(clsPCA,1);
% The std of the cluster (based on the distances between all cluster components to the cluster centroid).
std_std = std(sum((clsPCA-ones(size(clsPCA,1),1)*clsCentr).^2,2),1);
outliers = [];
for l = 1:length(STUDY.cluster(cls(k)).comps)
compdist = sum((clsPCA(l,:) - clsCentr).^2); % Component distance from cluster centroid
if compdist > std_std * th % check if an outlier
outliers = [ outliers l];
end
end
% Move outlier to the outlier cluster
if ~isempty(outliers) % reject outliers if exist
STUDY = std_moveoutlier(STUDY, ALLEEG,cls(k) , outliers);
end
end
|
github
|
lcnhappe/happe-master
|
std_makedesign.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_makedesign.m
| 21,788 |
utf_8
|
cdedb0dc0d7f5f2628779978f9309b6d
|
% std_makedesign() - create a new or edit an existing STUDY.design by
% selecting specific factors to include in subsequent
% 1x2 or 2x2 STUDY measures and statistical computations
% for this design. A STUDY may have many factors
% (task or stimulus conditions, subject groups, session
% numbers, trial types, etc.), but current EEGLAB
% STUDY statistics functions apply only to at most two
% (paired or unpaired) factors. A STUDY.design may
% also be (further) restricted to include only specific
% subjects, datasets, or trial types.
% Usage:
% >> [STUDY] = std_makedesign(STUDY, ALLEEG); % create a default design
% >> [STUDY] = std_makedesign(STUDY, ALLEEG, designind, 'key', 'val' ...);
%
% Inputs:
% STUDY - EEGLAB STUDY set
% ALLEEG - vector of the EEG datasets included in the STUDY structure
% designind - [integer > 0] index (number) of the new STUDY design {default: 1}
%
% Optional inputs:
% 'name' - ['string'] mnemonic design name (ex: 'Targets only')
% {default: 'Design d', where d = designind}
% 'variable1' - ['string'] - first independent variable or contrast. Must
% be a field name in STUDY.datasetinfo or in
% STUDY.datasetinfo.trialinfo. Typical choices include (task
% or other) 'condition', (subject) 'group', (subject) 'session',
% or other condition/group/session factors in STUDY.datasetinfo
% -- for example (subject factor) 'gender' or (condition factor)
% 'timeofday', etc. If trial type variables are defined in
% STUDY.datasetinfo.trialinfo, they may also be used here
% -- for example, 'stimcolor'. However, in this case datasets
% consist of heterogeneous sets of trials of different types,
% so many dataset Plot and Tools menu items may not give
% interpretable results and will thus be made unavailable for
% selection {default: 'condition'}
% 'pairing1' - ['on'|'off'] the nature of the 'variable1' contrast.
% For example, to compare two conditions recorded from the
% same group of 10 subjects, the 'variable1','condition' design
% elements are paired ('on') since each dataset for one
% condition has a corresponding dataset from the same subject
% in the second condition. If the two conditions were recorded
% from different groups of subjects, the variable1 'condition'
% would be unpaired ('off') {default: 'on'}
% 'values1' - {cell array of 'strings'} - 'variable1' instances to include
% in the design. For example, if 'variable1' is 'condition'and
% three values for 'condition' (e.g., 'a' , 'b', and 'c')
% are listed in STUDY.datasetinfo, then 'indval1', { 'a' 'b' }
% will contrast conditions 'a' and 'b', and datasets for
% condition 'c' will be ignored. To combine conditions, use
% nested '{}'s. For example, to combine conditions 'a' and
% 'b' into one condition and contrast it to condition 'c',
% specify 'indval1', { { 'a' 'b' } 'c' } {default: all values
% of 'variable1' in STUDY.datasetinfo}
% 'variable2' - ['string'] - second independent variable name, if any. Typically,
% this might refer to ('unpaired') subject group or (typically
% 'paired') session number, etc.
% 'pairing2' - ['on'|'off'] type of statistics for variable2
% (default: 'on'}
% 'values2' - {cell array of 'strings'} - variable2 values to include in the
% design {default: all}. Here, 'var[12]' must be field names
% in STUDY.datasetinfo or STUDY.datasetinfo.trialinfo.
% 'datselect' - {cell array} select specific datasets and/or trials: 'datselect',
% {'var1' {'vals'} 'var2' {'vas'}}. Selected datasets must
% meet all the specified conditions. For example, 'datselect',
% { 'condition' { 'a' 'b' } 'group' { 'g1' 'g2' } } will
% select only datasets from conditions 'a' OR 'b' AND only
% subjects in groups 'g1' OR 'g2'. If 'subjselect' is also
% specified, only datasets meeting both criteria are included.
% 'variable1' and 'variable2' will only consider
% the values after they have passed through 'datselect' and
% 'subjselect'. For instance, if conditions { 'a' 'b' 'c' }
% exist and conditions 'a' is removed by 'datselect', the only
% two conditions that will be considered are 'b' and 'c'
% (which is then equivalent to using 'variable1vals' to specify
% values for the 'condition' factor. Calls function
% std_selectdataset() {default: select all datasets}
% 'subjselect' - {cell array} subject codes of specific subjects to include
% in the STUDY design {default: all subjects in the specified
% conditions, groups, etc.} If 'datselect' is also specified,
% only datasets meeting both criteria are included.
% 'rmfiles' - ['on'|'off'] remove from the STUDY all data measure files
% NOT included in this design. Selecting this option will
% remove all the old measure files associated with the previous
% definition of this design. {default: 'off'}
% 'filepath' - [string] file path for saving precomputed files. Default is
% empty meaning it is in the same folder as the data.
% 'delfiles' - ['on'|'off'|'limited'] delete data files
% associated with the design specified as parameter. 'on'
% delete all data files related to the design. 'limited'
% deletes all data files contained in the design. 'limited'
% will not delete data files from other STUDY using the same
% files. Default is 'off'.
%
% Output:
% STUDY - The input STUDY with a new design added and designated
% as the current design.
%
% Examples:
% STUDY = std_makedesign(STUDY, ALLEEG); % make default design
%
% % create design with 1 independent variable equal to 'condition'
% STUDY = std_makedesign(STUDY, ALLEEG, 2, 'variable1', 'condition');
%
% % create design with 1 independent variable equal to 'condition'
% % but only consider the sub-condition 'stim1' and 'stim2' - of course
% % such conditions must be present in the STUDY
% STUDY = std_makedesign(STUDY, ALLEEG, 2, 'variable1', 'condition', ...
% 'values1', { 'stim1' 'stim2' });
%
% % create design and only include subject 's1' and 's2'
% STUDY = std_makedesign(STUDY, ALLEEG, 2, 'variable1', 'condition', ...
% 'subjselect', { 's1' 's2' });
%
% Author: Arnaud Delorme, Institute for Neural Computation UCSD, 2010-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [STUDY com] = std_makedesign(STUDY, ALLEEG, designind, varargin)
if nargin < 2
help std_makedesign;
return;
end;
if nargin < 3
designind = 1;
end;
defdes.name = sprintf('STUDY.design %d', designind);
defdes.cases.label = 'subject';
defdes.cases.value = {};
defdes.variable(1).label = 'condition';
defdes.variable(2).label = 'group';
defdes.variable(1).value = {};
defdes.variable(2).value = {};
defdes.variable(1).pairing = 'on';
defdes.variable(2).pairing = 'on';
defdes.filepath = '';
defdes.include = {};
orivarargin = varargin;
if ~isempty(varargin) && isstruct(varargin{1})
defdes = varargin{1};
varargin(1) = [];
end;
if isempty(defdes.variable(1).pairing), defdes.variable(1).pairing = 'on'; end;
if isempty(defdes.variable(2).pairing), defdes.variable(2).pairing = 'on'; end;
if isempty(defdes.filepath), defdes.filepath = ''; end;
opt = finputcheck(varargin, {'variable1' 'string' [] defdes.variable(1).label;
'variable2' 'string' [] defdes.variable(2).label;
'values1' {'real','cell' } [] defdes.variable(1).value;
'values2' {'real','cell' } [] defdes.variable(2).value;
'pairing1' 'string' [] defdes.variable(1).pairing;
'pairing2' 'string' [] defdes.variable(2).pairing;
'name' 'string' {} defdes.name;
'filepath' 'string' {} defdes.filepath;
'datselect' 'cell' {} defdes.include;
'dataselect' 'cell' {} {};
'subjselect' 'cell' {} defdes.cases.value;
'delfiles' 'string' { 'on','off', 'limited' } 'off';
'verbose' 'string' { 'on','off' } 'on';
'defaultdesign' 'string' { 'on','off','forceoff'} fastif(nargin < 3, 'on', 'off') }, ...
'std_makedesign');
if isstr(opt), error(opt); end;
if ~isempty(opt.dataselect), opt.datselect = opt.dataselect; end;
if strcmpi(opt.variable1, 'none'), opt.variable1 = ''; end;
if strcmpi(opt.variable2, 'none'), opt.variable2 = ''; end;
if ~isempty(opt.subjselect) && iscell(opt.subjselect{1}), opt.subjselect = opt.subjselect{1}; end;
%if iscell(opt.values1), for i = 1:length(opt.values1), if iscell(opt.values1{i}), opt.values1{i} = cell2str(opt.values1{i}); end; end; end;
%if iscell(opt.values2), for i = 1:length(opt.values2), if iscell(opt.values2{i}), opt.values2{i} = cell2str(opt.values2{i}); end; end; end;
% build command list for history
% ------------------------------
listcom = { 'variable1' opt.variable1 'variable2' opt.variable2 'name' opt.name 'pairing1' opt.pairing1 'pairing2' opt.pairing2 'delfiles' opt.delfiles 'defaultdesign' opt.defaultdesign };
if ~isempty(opt.values1), listcom = { listcom{:} 'values1' opt.values1 }; end;
if ~isempty(opt.values2), listcom = { listcom{:} 'values2' opt.values2 }; end;
if ~isempty(opt.subjselect), listcom = { listcom{:} 'subjselect' opt.subjselect }; end;
if ~isempty(opt.datselect), listcom = { listcom{:} 'datselect' opt.datselect }; end;
if ~isempty(opt.filepath), listcom = { listcom{:} 'filepath' opt.filepath }; end;
if ~isempty(opt.datselect), listcom = { listcom{:} 'datselect' opt.datselect }; end;
% select specific subjects
% ------------------------
datsubjects = { STUDY.datasetinfo.subject };
if ~isempty(opt.subjselect)
allsubjects = opt.subjselect;
else
allsubjects = unique_bc( datsubjects );
end;
% delete design files
% ---------------------
if strcmpi(opt.delfiles, 'on')
myfprintf(opt.verbose, 'Deleting all files pertaining to design %d\n', designind);
for index = 1:length(ALLEEG)
files = fullfile(ALLEEG(index).filepath, sprintf(opt.verbose, 'design%d*.*', designind));
files = dir(files);
for indf = 1:length(files)
delete(fullfile(ALLEEG(index).filepath, files(indf).name));
end;
end;
elseif strcmpi(opt.delfiles, 'limited')
myfprintf(opt.verbose, 'Deleting all files for STUDY design %d\n', designind);
for index = 1:length(STUDY.design(designind).cell)
filedir = [ STUDY.design(designind).cell(index).filebase '.dat*' ];
filepath = fileparts(filedir);
files = dir(filedir);
for indf = 1:length(files)
%disp(fullfile(filepath, files(indf).name));
delete(fullfile(filepath, files(indf).name));
end;
end;
for index = 1:length(STUDY.design(designind).cell)
filedir = [ STUDY.design(designind).cell(index).filebase '.ica*' ];
filepath = fileparts(filedir);
files = dir(filedir);
for indf = 1:length(files)
%disp(fullfile(filepath, files(indf).name));
delete(fullfile(filepath, files(indf).name));
end;
end;
end;
% check inputs
% ------------
[indvars indvarvals ] = std_getindvar(STUDY);
if isfield(STUDY.datasetinfo, 'trialinfo')
alltrialinfo = { STUDY.datasetinfo.trialinfo };
dattrialselect = cellfun(@(x)([1:length(x)]), alltrialinfo, 'uniformoutput', false);
else alltrialinfo = cell(length(STUDY.datasetinfo));
for i=1:length(ALLEEG), dattrialselect{i} = [1:ALLEEG(i).trials]; end;
end;
% get values for each independent variable
% ----------------------------------------
m1 = strmatch(opt.variable1, indvars, 'exact'); if isempty(m1), opt.variable1 = ''; end;
m2 = strmatch(opt.variable2, indvars, 'exact'); if isempty(m2), opt.variable2 = ''; end;
if isempty(opt.values1) && ~isempty(opt.variable1), opt.values1 = indvarvals{m1}; end;
if isempty(opt.values2) && ~isempty(opt.variable2), opt.values2 = indvarvals{m2}; end;
if isempty(opt.variable1), opt.values1 = { '' }; end;
if isempty(opt.variable2), opt.values2 = { '' }; end;
% preselect data
% --------------
datselect = [1:length(STUDY.datasetinfo)];
if ~isempty(opt.datselect)
myfprintf(opt.verbose, 'Data preselection for STUDY design\n');
for ind = 1:2:length(opt.datselect)
[ dattmp dattrialstmp ] = std_selectdataset( STUDY, ALLEEG, opt.datselect{ind}, opt.datselect{ind+1});
datselect = intersect_bc(datselect, dattmp);
dattrialselect = intersectcell(dattrialselect, dattrialstmp);
end;
end;
datselect = intersect_bc(datselect, strmatchmult(allsubjects, datsubjects));
% get the dataset and trials for each of the ind. variable
% --------------------------------------------------------
ns = length(allsubjects);
nf1 = max(1,length(opt.values1));
nf2 = max(1,length(opt.values2));
myfprintf(opt.verbose, 'Building STUDY design\n');
for n1 = 1:nf1, [ dats1{n1} dattrials1{n1} ] = std_selectdataset( STUDY, ALLEEG, opt.variable1, opt.values1{n1}, fastif(strcmpi(opt.verbose, 'on'), 'verbose', 'silent')); end;
for n2 = 1:nf2, [ dats2{n2} dattrials2{n2} ] = std_selectdataset( STUDY, ALLEEG, opt.variable2, opt.values2{n2}, fastif(strcmpi(opt.verbose, 'on'), 'verbose', 'silent')); end;
% detect files from old format
% ----------------------------
if ~strcmpi(opt.defaultdesign, 'forceoff') && isempty(opt.filepath)
if designind == 1
if strcmpi(opt.defaultdesign, 'off')
if isfield(STUDY, 'design') && ( ~isfield(STUDY.design, 'cell') || ~isfield(STUDY.design(1).cell, 'filebase') )
opt.defaultdesign = 'on';
end;
end;
if isempty(dir(fullfile(ALLEEG(1).filepath, [ ALLEEG(1).filename(1:end-4) '.dat*' ]))) && ...
isempty(dir(fullfile(ALLEEG(1).filepath, [ ALLEEG(1).filename(1:end-4) '.ica*' ])))
opt.defaultdesign = 'off';
end;
else
opt.defaultdesign = 'off';
end;
else
opt.defaultdesign = 'off';
end;
% scan subjects and conditions
% ----------------------------
count = 1;
for n1 = 1:nf1
for n2 = 1:nf2
% create design for this set of conditions and subject
% ----------------------------------------------------
datasets = intersect_bc(intersect(dats1{n1}, dats2{n2}), datselect);
if ~isempty(datasets)
subjects = unique_bc(datsubjects(datasets));
for s = 1:length(subjects)
datsubj = datasets(strmatch(subjects{s}, datsubjects(datasets), 'exact'));
des.cell(count).dataset = datsubj;
des.cell(count).trials = intersectcell(dattrialselect(datsubj), dattrials1{n1}(datsubj), dattrials2{n2}(datsubj));
des.cell(count).value = { opt.values1{n1} opt.values2{n2} };
des.cell(count).case = subjects{s};
defaultFile = fullfile(ALLEEG(datsubj(1)).filepath, ALLEEG(datsubj(1)).filename(1:end-4));
dirres1 = dir( [ defaultFile '.dat*' ] );
dirres2 = dir( [ defaultFile '.ica*' ] );
if strcmpi(opt.defaultdesign, 'on') && (~isempty(dirres1) || ~isempty(dirres2)) && isempty(opt.filepath)
des.cell(count).filebase = defaultFile;
else
if isempty(rmblk(opt.values1{n1})), txtval = rmblk(opt.values2{n2});
elseif isempty(rmblk(opt.values2{n2})) txtval = rmblk(opt.values1{n1});
else txtval = [ rmblk(opt.values1{n1}) '_' rmblk(opt.values2{n2}) ];
end;
if ~isempty(txtval), txtval = [ '_' txtval ]; end;
if ~isempty(subjects{s}), txtval = [ '_' rmblk(subjects{s}) txtval ]; end;
if isempty(opt.filepath), tmpfilepath = ALLEEG(datsubj(1)).filepath; else tmpfilepath = opt.filepath; end;
des.cell(count).filebase = fullfile(tmpfilepath, [ 'design' int2str(designind) txtval ] );
%des.cell(count).filebase = checkfilelength(des.cell(count).filebase);
end;
count = count+1;
end;
end;
end;
end;
% create other fields for the design
% ----------------------------------
if exist('des') ~= 1
error( [ 'One of your design is empty. This could be because the datasets/subjects/trials' 10 ...
'you have selected do not contain any of the selected independent variables values.' 10 ...
'Check your data and datasets carefully for any missing information.' ]);
else
% check for duplicate entries in filebase
% ---------------------------------------
if length( { des.cell.filebase } ) > length(unique({ des.cell.filebase }))
if ~isempty(findstr('design_', des.cell(1).filebase))
error('There is a problem with your STUDY, contact EEGLAB support');
else
disp('Duplicate entry detected in new design, reinitializing design with new file names');
if length(dbstack) > 10
error('There is probably an issue with the folder names - move the files and try again');
end;
[STUDY com] = std_makedesign(STUDY, ALLEEG, designind, orivarargin{:}, 'defaultdesign', 'forceoff');
return;
end
end;
%allval1 = unique_bc(cellfun(@(x)x{1}, { des.cell.value }, 'uniformoutput', false));
%allval2 = unique_bc(cellfun(@(x)x{2}, { des.cell.value }, 'uniformoutput', false));
des.name = opt.name;
des.filepath = opt.filepath;
des.variable(1).label = opt.variable1;
des.variable(2).label = opt.variable2;
des.variable(1).pairing = opt.pairing1;
des.variable(2).pairing = opt.pairing2;
des.variable(1).value = opt.values1;
des.variable(2).value = opt.values2;
des.include = opt.datselect;
des.cases.label = 'subject';
des.cases.value = unique_bc( { des.cell.case });
end;
fieldorder = { 'name' 'filepath' 'variable' 'cases' 'include' 'cell' };
des = orderfields(des, fieldorder);
try,
STUDY.design = orderfields(STUDY.design, fieldorder);
catch,
STUDY.design = [];
end;
if ~isfield(STUDY, 'design') || isempty(STUDY.design)
STUDY.design = des;
else
STUDY.design(designind) = des; % fill STUDY.design
end;
% select the new design in the STUDY output
% -----------------------------------------
STUDY.currentdesign = designind;
STUDY = std_selectdesign(STUDY, ALLEEG, designind);
% build output command
% --------------------
com = sprintf('STUDY = std_makedesign(STUDY, ALLEEG, %d, %s);', designind, vararg2str( listcom ) );
% ---------------------------------------------------
% return intersection of cell arrays
% ----------------------------------
function res = intersectcell(a, b, c);
if nargin > 2
res = intersectcell(a, intersectcell(b, c));
else
for index = 1:length(a)
res{index} = intersect_bc(a{index}, b{index});
end;
end;
% perform multi strmatch
% ----------------------
function res = strmatchmult(a, b);
res = [];
for index = 1:length(a)
res = [ res strmatch(a{index}, b, 'exact')' ];
end;
% remove blanks
% -------------
function res = rmblk(a);
if iscell(a), a = cell2str(a); end;
if ~isstr(a), a = num2str(a); end;
res = a;
res(find(res == ' ')) = '_';
res(find(res == '\')) = '_';
res(find(res == '/')) = '_';
res(find(res == ':')) = '_';
res(find(res == ';')) = '_';
res(find(res == '"')) = '_';
function strval = cell2str(vals);
strval = vals{1};
for ind = 2:length(vals)
strval = [ strval ' - ' vals{ind} ];
end;
function tmpfile = checkfilelength(tmpfile);
if length(tmpfile) > 120,
tmpfile = tmpfile(1:120);
end;
function myfprintf(verbose, varargin);
if strcmpi(verbose, 'on'), fprintf(varargin{:}); end;
|
github
|
lcnhappe/happe-master
|
std_readspec.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_readspec.m
| 3,551 |
utf_8
|
0315bf04416f115f6af90007ab60704e
|
% std_readspec() - load spectrum measures for data channels or
% for all components of a specified cluster.
% Called by plotting functions
% std_envtopo(), std_erpplot(), std_erspplot(), ...
% Usage:
% >> [STUDY, specdata, allfreqs, setinds, cinds] = ...
% std_readspec(STUDY, ALLEEG, varargin);
% Inputs:
% STUDY - studyset structure containing some or all files in ALLEEG
% ALLEEG - vector of loaded EEG datasets
%
% Optional inputs:
% 'design' - [integer] read files from a specific STUDY design. Default
% is empty (use current design in STUDY.currentdesign).
% 'channels' - [cell] list of channels to import {default: none}
% 'clusters' - [integer] list of clusters to import {[]|default: all but
% the parent cluster (1) and any 'NotClust' clusters}
% 'singletrials' - ['on'|'off'] load single trials spectral data (if
% available). Default is 'off'.
% 'subject' - [string] select a specific subject {default:all}
% 'component' - [integer] select a specific component in a cluster
% {default:all}
%
% Spectrum specific inputs:
% 'freqrange' - [min max] frequency range {default: whole measure range}
% 'rmsubjmean' - ['on'|'off'] remove mean subject spectrum from every
% channel spectrum, making them easier to compare
% { default: 'off' }
% Output:
% STUDY - updated studyset structure
% specdata - [cell array] spectral data (the cell array size is
% condition x groups)
% freqs - [float array] array of frequencies
% setinds - [cell array] datasets indices
% cinds - [cell array] channel or component indices
%
% Example:
% std_precomp(STUDY, ALLEEG, { ALLEEG(1).chanlocs.labels }, 'spec', 'on');
% [spec freqs] = std_readspec(STUDY, ALLEEG, 'channels', { ALLEEG(1).chanlocs(1).labels });
%
% Author: Arnaud Delorme, CERCO, 2006-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [STUDY, specdata, allfreqs] = std_readspec(STUDY, ALLEEG, varargin)
if nargin < 2
help std_readspec;
return;
end
if ~isstruct(ALLEEG) % old calling format
% old calling format
% ------------------
EEG = STUDY(ALLEEG);
filename = fullfile(EEG.filepath, EEG.filename(1:end-4));
comporchan = varargin{1};
options = {'measure', 'spec'};
if length(varargin) > 1, options = { options{:} 'freqlimits', varargin{2} }; end;
if comporchan(1) > 0
[datavals tmp xvals] = std_readfile(filename, 'components',comporchan, options{:});
else
[datavals tmp xvals] = std_readfile(filename, 'channels', comporchan, options{:});
end;
STUDY = datavals';
specdata = xvals;
end;
[STUDY, specdata, allfreqs] = std_readerp(STUDY, ALLEEG, 'datatype', 'spec', varargin{:});
|
github
|
lcnhappe/happe-master
|
pop_erpparams.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/pop_erpparams.m
| 10,477 |
utf_8
|
68e8b342681fb13cd747c25aa1e5582f
|
% pop_erpparams() - Set plotting and statistics parameters for cluster ERP
% plotting
% Usage:
% >> STUDY = pop_erpparams(STUDY, 'key', 'val');
%
% Inputs:
% STUDY - EEGLAB STUDY set
%
% Input:
% 'topotime' - [real] Plot ERP scalp maps at one specific latency (ms).
% A latency range [min max] may also be defined (the
% ERP is then averaged over the interval) {default: []}
% 'filter' - [real] low pass filter the ERP curves at a given
% frequency threshold. Default is no filtering.
% 'timerange' - [min max] ERP plotting latency range in ms.
% {default: the whole epoch}
% 'ylim' - [min max] ERP limits in microvolts {default: from data}
% 'plotgroups' - ['together'|'apart'] 'together' -> plot subject groups
% on the same axis in different colors, else ('apart')
% on different axes. {default: 'apart'}
% 'plotconditions' - ['together'|'apart'] 'together' -> plot conditions
% on the same axis in different colors, else ('apart')
% on different axes. Note: Keywords 'plotgroups' and
% 'plotconditions' may not both be set to 'together'.
% {default: 'together'}
% 'averagechan' - ['on'|'off'] average data channels when several are
% selected.
%
% See also: std_erpplot()
%
% Authors: Arnaud Delorme, CERCO, CNRS, 2006-
% Copyright (C) Arnaud Delorme, 2006
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ STUDY, com ] = pop_erpparams(STUDY, varargin);
STUDY = default_params(STUDY);
TMPSTUDY = STUDY;
com = '';
if isempty(varargin)
enablecond = fastif(length(STUDY.design(STUDY.currentdesign).variable(1).value)>1, 'on', 'off');
enablegroup = fastif(length(STUDY.design(STUDY.currentdesign).variable(2).value)>1, 'on', 'off');
detachplots = fastif(strcmpi(STUDY.etc.erpparams.detachplots,'on'), 1, 0);
plotconditions = fastif(strcmpi(STUDY.etc.erpparams.plotconditions, 'together'), 1, 0);
plotgroups = fastif(strcmpi(STUDY.etc.erpparams.plotgroups,'together'), 1, 0);
radio_averagechan = fastif(strcmpi(STUDY.etc.erpparams.averagechan,'on'), 1, 0);
radio_scalptopo = fastif(isempty(STUDY.etc.erpparams.topotime), 0, 1);
if radio_scalptopo, radio_averagechan = 0; end;
if radio_scalptopo+radio_averagechan == 0, radio_scalparray = 1; else radio_scalparray = 0; end;
cb_radio = [ 'set(findobj(gcbf, ''userdata'', ''radio''), ''value'', 0);' ...
'set(gcbo, ''value'', 1);' ...
'set(findobj(gcbf, ''tag'', ''topotime''), ''string'', '''');' ];
cb_edit = [ 'set(findobj(gcbf, ''userdata'', ''radio''), ''value'', 0);' ...
'set(findobj(gcbf, ''tag'', ''scalptopotext''), ''value'', 1);' ];
uilist = { ...
{'style' 'text' 'string' 'ERP plotting options' 'fontweight' 'bold' 'fontsize', 12} ...
{} {'style' 'text' 'string' 'Time limits (ms) [low high]' } ...
{'style' 'edit' 'string' num2str(STUDY.etc.erpparams.timerange) 'tag' 'timerange' } ...
{} {'style' 'text' 'string' 'Plot limits [low high]'} ...
{'style' 'edit' 'string' num2str(STUDY.etc.erpparams.ylim) 'tag' 'ylim' } ...
{} {'style' 'text' 'string' 'Lowpass plotted data [Hz]' } ...
{'style' 'edit' 'string' num2str(STUDY.etc.erpparams.filter) 'tag' 'filter' } ...
{} ...
{'style' 'text' 'string' 'ERP plotting format' 'fontweight' 'bold' 'fontsize', 12} ...
{} {'style' 'checkbox' 'string' 'Plot first variable on the same panel' 'value' plotconditions 'enable' enablecond 'tag' 'plotconditions' } ...
{} {'style' 'checkbox' 'string' 'Plot second variable on the same panel' 'value' plotgroups 'enable' enablegroup 'tag' 'plotgroups' } ...
{} {'style' 'checkbox' 'string' 'Detach plots' 'value' detachplots 'enable' 'on' 'tag' 'detachtag' } ...
{} ...
{'style' 'text' 'string' 'Multiple channels selection' 'fontweight' 'bold' 'tag', 'spec' 'fontsize', 12} ...
{} {'style' 'radio' 'string' 'Plot channels in scalp array' 'value' radio_scalparray 'tag' 'scalparray' 'userdata' 'radio' 'callback' cb_radio} { } ...
{} {'style' 'radio' 'string' 'Plot topography at time (ms)' 'value' radio_scalptopo 'tag' 'scalptopotext' 'userdata' 'radio' 'callback' cb_radio} ...
{'style' 'edit' 'string' num2str(STUDY.etc.erpparams.topotime) 'tag' 'topotime' 'callback' cb_edit } ...
{} {'style' 'radio' 'string' 'Average selected channels' 'value' radio_averagechan 'tag' 'averagechan' 'userdata' 'radio' 'callback' cb_radio} { } };
cbline = [0.07 1.1];
otherline = [ 0.07 0.6 .3];
chanline = [ 0.07 0.8 0.3];
geometry = { 1 otherline otherline otherline 1 1 cbline cbline cbline 1 1 chanline chanline chanline };
geomvert = [1.2 1 1 1 0.5 1.2 1 1 1 0.5 1.2 1 1 1 ];
% component plotting
% ------------------
if isnan(STUDY.etc.erpparams.topotime)
geometry(end-4:end) = [];
geomvert(end-4:end) = [];
uilist(end-10:end) = [];
end;
[out_param userdat tmp res] = inputgui( 'geometry' , geometry, 'uilist', uilist, 'geomvert', geomvert, ...
'title', 'ERP plotting options -- pop_erpparams()');
if isempty(res), return; end;
% decode inputs
% -------------
%if res.plotgroups & res.plotconditions, warndlg2('Both conditions and group cannot be plotted on the same panel'); return; end;
if res.plotgroups, res.plotgroups = 'together'; else res.plotgroups = 'apart'; end;
if res.plotconditions , res.plotconditions = 'together'; else res.plotconditions = 'apart'; end;
if res.detachtag, res.detachtag = 'on'; else res.detachtag = 'off'; end;
if ~isfield(res, 'topotime'), res.topotime = STUDY.etc.erpparams.topotime;
else res.topotime = str2num( res.topotime );
end;
res.timerange = str2num( res.timerange );
res.ylim = str2num( res.ylim );
res.filter = str2num( res.filter );
if ~isfield(res, 'averagechan'), res.averagechan = STUDY.etc.erpparams.averagechan;
elseif res.averagechan, res.averagechan = 'on'; else res.averagechan = 'off';
end;
% build command call
% ------------------
options = {};
if ~strcmpi( char(res.filter), char(STUDY.etc.erpparams.filter)), options = { options{:} 'filter' res.filter }; end;
if ~strcmpi( res.plotgroups, STUDY.etc.erpparams.plotgroups), options = { options{:} 'plotgroups' res.plotgroups }; end;
if ~strcmpi( res.plotconditions , STUDY.etc.erpparams.plotconditions ), options = { options{:} 'plotconditions' res.plotconditions }; end;
if ~strcmpi( res.detachtag, STUDY.etc.erpparams.detachplots), options = { options{:} 'detachplots' res.detachtag}; end;
if ~isequal(res.ylim , STUDY.etc.erpparams.ylim), options = { options{:} 'ylim' res.ylim }; end;
if ~isequal(res.timerange , STUDY.etc.erpparams.timerange) , options = { options{:} 'timerange' res.timerange }; end;
if ~isequal(res.averagechan, STUDY.etc.erpparams.averagechan), options = { options{:} 'averagechan' res.averagechan }; end;
if (all(isnan(res.topotime)) & all(~isnan(STUDY.etc.erpparams.topotime))) | ...
(all(~isnan(res.topotime)) & all(isnan(STUDY.etc.erpparams.topotime))) | ...
(all(~isnan(res.topotime)) & ~isequal(res.topotime, STUDY.etc.erpparams.topotime))
options = { options{:} 'topotime' res.topotime };
end;
if ~isempty(options)
STUDY = pop_erpparams(STUDY, options{:});
com = sprintf('STUDY = pop_erpparams(STUDY, %s);', vararg2str( options ));
end;
else
if strcmpi(varargin{1}, 'default')
STUDY = default_params(STUDY);
else
for index = 1:2:length(varargin)
if ~isempty(strmatch(varargin{index}, fieldnames(STUDY.etc.erpparams), 'exact'))
STUDY.etc.erpparams = setfield(STUDY.etc.erpparams, varargin{index}, varargin{index+1});
end;
end;
end;
end;
% scan clusters and channels to remove erpdata info if timerange has changed
% ----------------------------------------------------------
if ~isequal(STUDY.etc.erpparams.timerange, TMPSTUDY.etc.erpparams.timerange)
rmfields = { 'erpdata' 'erptimes' };
for iField = 1:length(rmfields)
if isfield(STUDY.cluster, rmfields{iField})
STUDY.cluster = rmfield(STUDY.cluster, rmfields{iField});
end;
if isfield(STUDY.changrp, rmfields{iField})
STUDY.changrp = rmfield(STUDY.changrp, rmfields{iField});
end;
end;
end;
function STUDY = default_params(STUDY)
if ~isfield(STUDY.etc, 'erpparams'), STUDY.etc.erpparams = []; end;
if ~isfield(STUDY.etc.erpparams, 'topotime'), STUDY.etc.erpparams.topotime = []; end;
if ~isfield(STUDY.etc.erpparams, 'filter'), STUDY.etc.erpparams.filter = []; end;
if ~isfield(STUDY.etc.erpparams, 'timerange'), STUDY.etc.erpparams.timerange = []; end;
if ~isfield(STUDY.etc.erpparams, 'ylim' ), STUDY.etc.erpparams.ylim = []; end;
if ~isfield(STUDY.etc.erpparams, 'plotgroups') , STUDY.etc.erpparams.plotgroups = 'apart'; end;
if ~isfield(STUDY.etc.erpparams, 'plotconditions') , STUDY.etc.erpparams.plotconditions = 'apart'; end;
if ~isfield(STUDY.etc.erpparams, 'averagechan') , STUDY.etc.erpparams.averagechan = 'off'; end;
if ~isfield(STUDY.etc.erpparams, 'detachplots') , STUDY.etc.erpparams.detachplots = 'on'; end;
|
github
|
lcnhappe/happe-master
|
eeglabciplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/eeglabciplot.m
| 1,171 |
utf_8
|
a54755e9a50c126bf4fd48d251eff99e
|
% eeglabciplot(lower,upper)
% eeglabciplot(lower,upper,x)
% eeglabciplot(lower,upper,x,colour)
%
% Plots a shaded region on a graph between specified lower and upper confidence intervals (L and U).
% l and u must be vectors of the same length.
% Uses the 'fill' function, not 'area'. Therefore multiple shaded plots
% can be overlayed without a problem. Make them transparent for total visibility.
% x data can be specified, otherwise plots against index values.
% colour can be specified (eg 'k'). Defaults to blue.
% Author: Raymond Reynolds 24/11/06
% Modified by Ramon Martinez Cancino
function eeglabciplot(lower,upper,x,colour, alphaval)
if length(lower)~=length(upper)
error('lower and upper vectors must be same length')
end
if nargin<5
alphaval = 1;
end
if nargin<4
colour= 'r';
end
if nargin<3
x=1:length(lower);
end
% convert to row vectors so fliplr can work
if find(size(x)==(max(size(x))))<2
x=x'; end
if find(size(lower)==(max(size(lower))))<2
lower=lower'; end
if find(size(upper)==(max(size(upper))))<2
upper=upper'; end
hdl_tmp = fill([x fliplr(x)],[upper fliplr(lower)],colour,'FaceAlpha', alphaval, 'EdgeColor', 'none');
|
github
|
lcnhappe/happe-master
|
std_selectdesign.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_selectdesign.m
| 1,989 |
utf_8
|
b3048a1a88ea00503584ee7c9c6d418b
|
% std_selectdesign() - select an existing STUDY design.
% Use std_makedesign() to add a new STUDY.design.
%
% Usage:
% >> [STUDY] = std_selectdesign(STUDY, ALLEEG, designind);
%
% Inputs:
% STUDY - EEGLAB STUDY structure
% STUDY - EEGLAB ALLEEG structure
% designind - desired (existing) design index
%
% Outputs:
% STUDY - EEGLAB STUDY structure with currentdesign set to the input design index.
%
% Author: Arnaud Delorme, Institute for Neural Computation, UCSD, 2010-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function STUDY = std_selectdesign(STUDY, ALLEEG, designind);
if nargin < 3
help std_selectdesign;
return;
end;
if designind < 1 || designind > length(STUDY.design) || isempty(STUDY.design(designind).name)
disp('Cannot select an empty STUDY.design');
return;
end;
STUDY.currentdesign = designind;
STUDY = std_rmalldatafields( STUDY );
% remake setinds and allinds
% --------------------------
STUDY = std_changroup(STUDY, ALLEEG, [], 'on'); % with interpolation HAVE TO FIX THAT
% update the component indices
% ----------------------------
STUDY.cluster(1).setinds = {};
STUDY.cluster(1).allinds = {};
for index = 1:length(STUDY.cluster)
STUDY.cluster(index) = std_setcomps2cell(STUDY, index);
end;
|
github
|
lcnhappe/happe-master
|
std_getdataset.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_getdataset.m
| 7,391 |
utf_8
|
30fe56beb0eae5a9d470402fc8ae35a2
|
% std_getdataset() - Constructs and returns EEG dataset from STUDY design.
%
% Usage:
% >> EEG = std_getdataset(STUDY, ALLEEG, 'key', 'val', ...);
%
% Inputs:
% STUDY - EEGLAB STUDY set
% ALLEEG - vector of the EEG datasets included in the STUDY structure
%
% Optional inputs:
% 'design' - [numeric vector] STUDY design index. Default is to use
% the current design.
% 'rmcomps' - [integer array] remove artifactual components (this entry
% is ignored when plotting components). This entry contains
% the indices of the components to be removed. Default is none.
% 'rmclust' - [integer array] which cluster(s) to remove from the data
% Default is none.
% 'interp' - [struct] channel location structure containing electrode
% to interpolate ((this entry is ignored when plotting
% components). Default is no interpolation.
% 'cell' - [integer] index of the STUDY design cell to convert to
% an EEG dataset. Default is the first cell.
% 'onecomppercluster' - ['on'|'off'] when 'on' enforces one component per
% cluster. Default is 'off'.
% 'interpcomponent' - ['on'|'off'] when 'on' interpolating component
% scalp maps. Default is 'off'.
% 'cluster' - [integer] which cluster(s). When this option is being
% used, only the component contained in the selected
% clusters are being loaded in the dataset.
% 'checkonly' - ['on'|'off'] use in conjunction with the option above.
% When 'on', no dataset is returned. Default is 'off'.
%
% Outputs:
% EEG - EEG dataset structure corresponding to the selected
% STUDY design cell (element)
% complist - list of components selected
%
% Example to build the dataset corresponding to the first cell of the first
% design:
% EEG = std_getdataset(STUDY, ALLEEG, 'design', 1, 'cell', 1);
%
% Example to check that all datasets in the design have exactly one
% component per cluster for cluster 2, 3, 4 and 5.
% std_getdataset(STUDY, ALLEEG, 'design', 1, 'cell',
% [1:length(STUDY.design(1).cell)], 'cluster', [2 3 4 5], 'checkonly', 'on');
%
% Authors: Arnaud Delorme, SCCN, INC, UCSD, January, 2012
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 12, 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
function [EEGOUT listcomp rmlistcomp] = std_getdataset(STUDY, ALLEEG, varargin);
if nargin < 2
help std_getdataset;
return;
end;
opt = finputcheck( varargin, { 'design' 'integer' [] STUDY.currentdesign;
'interp' 'struct' { } struct([]);
'rmcomps' 'integer' [] [];
'cluster' 'integer' [] [];
'rmclust' 'integer' [] [];
'onecomppercluster' 'string' {'on' 'off'} 'off';
'interpcomponent' 'string' {'on' 'off'} 'off';
'checkonly' 'string' {'on' 'off'} 'off';
'cell' 'integer' [] 1 }, 'std_getdataset');
% 'mode' 'string' { 'channels' 'components' } 'channels';
if isstr(opt), error(opt); end;
if length(opt.cell) > 1
% recursive call if more than one dataset
% ---------------------------------------
indcell = strmatch('cell', varargin(1:2:end));
for index = 1:length(opt.cell)
varargin{2*indcell} = index;
EEGOUT(index) = std_getdataset(STUDY, ALLEEG, varargin{:});
end;
else
mycell = STUDY.design(opt.design).cell(opt.cell);
% find components in non-artifactual cluster
if ~isempty(opt.cluster)
listcomp = [];
for index = 1:length(opt.cluster)
clsset = STUDY.cluster(opt.cluster(index)).sets;
clscomp = STUDY.cluster(opt.cluster(index)).comps;
[indrow indcomp] = find(clsset == mycell.dataset(1));
if length(indcomp) ~= 1 && strcmpi(opt.onecomppercluster, 'on')
error(sprintf('Dataset %d must have exactly 1 components in cluster %d', mycell.dataset(1), opt.cluster(index)));
end;
listcomp = [listcomp clscomp(indcomp')];
end;
end;
% find components in artifactual clusters
if ~isempty(opt.rmclust)
rmlistcomp = [];
for index = 1:length(opt.rmclust)
clsset = STUDY.cluster(opt.rmclust(index)).sets;
clscomp = STUDY.cluster(opt.rmclust(index)).comps;
[indrow indcomp] = find(clsset == mycell.dataset(1));
rmlistcomp = [rmlistcomp clscomp(indcomp')];
end;
if ~isempty(opt.rmcomps)
disp('Both ''rmclust'' and ''rmcomps'' are being set. Artifact components will be merged');
end;
opt.rmcomps = [ opt.rmcomps rmlistcomp ];
end;
rmlistcomp = opt.rmcomps;
if strcmpi(opt.checkonly, 'on'), EEGOUT = 0; return; end;
% get data
EEG = ALLEEG(mycell.dataset);
EEGOUT = EEG(1);
EEGOUT.data = eeg_getdatact(EEG, 'channel', [], 'trialindices', mycell.trials, 'rmcomps', opt.rmcomps, 'interp', opt.interp);
EEGOUT.trials = size(EEGOUT.data,3);
EEGOUT.nbchan = size(EEGOUT.data,1);
if ~isempty(opt.interp)
EEGOUT.chanlocs = opt.interp;
end;
EEGOUT.event = [];
EEGOUT.epoch = [];
EEGOUT.filename = mycell.filebase;
EEGOUT.condition = mycell.value{1};
EEGOUT.group = mycell.value{2};
EEGOUT.subject = mycell.case;
if ~isempty(opt.cluster)
if ~isempty(opt.interp) && strcmpi(opt.interpcomponent, 'on')
TMPEEG = EEGOUT;
TMPEEG.chanlocs = EEG(1).chanlocs;
TMPEEG.data = EEG(1).icawinv;
TMPEEG.nbchan = size(TMPEEG.data,1);
TMPEEG.pnts = size(TMPEEG.data,2);
TMPEEG.trials = 1;
TMPEEG = eeg_interp(TMPEEG, opt.interp, 'spherical');
EEGOUT.icawinv = TMPEEG.data(:, listcomp);
else
EEGOUT.icawinv = EEGOUT.icawinv(:, listcomp);
end;
EEGOUT.icaact = eeg_getdatact(EEG, 'component', listcomp, 'trialindices', mycell.trials );
EEGOUT.icaweights = EEGOUT.icaweights(listcomp,:);
EEGOUT.etc.clustid = { STUDY.cluster(opt.cluster).name }; % name of each cluster
EEGOUT.etc.clustcmpid = listcomp; % index of each component in original ICA matrix
else
EEGOUT = eeg_checkset(EEGOUT);
end;
end;
|
github
|
lcnhappe/happe-master
|
std_readpac.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_readpac.m
| 9,664 |
utf_8
|
969615c6dc80b8442761d8a892ebdef1
|
% std_readpac() - read phase-amplitude correlation
%
% Usage:
% >> [STUDY, clustinfo] = std_readpac(STUDY, ALLEEG);
% >> [STUDY, clustinfo] = std_readpac(STUDY, ALLEEG, ...
% 'key', 'val');
% Inputs:
% STUDY - studyset structure containing some or all files in ALLEEG
% ALLEEG - vector of loaded EEG datasets
%
% Optional inputs:
% 'channels' - [cell] list of channels to import {default: all}
% 'clusters' - [integer] list of clusters to import {[]|default: all but
% the parent cluster (1) and any 'NotClust' clusters}
% 'freqrange' - [min max] frequency range {default: whole measure range}
% 'timerange' - [min max] time range {default: whole measure epoch}
%
% Output:
% STUDY - (possibly) updated STUDY structure
% clustinfo - structure of specified cluster information.
%
% Author: Arnaud Delorme, CERCO, 2009-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [STUDY, clustinfo] = std_readpac(STUDY, ALLEEG, varargin);
if nargin < 2
help std_readpac;
return;
end
[opt moreopts] = finputcheck( varargin, { ...
'condition' 'cell' [] {};
'channels1' 'cell' [] {};
'clusters1' 'integer' [] [];
'channels2' 'cell' [] {};
'clusters2' 'integer' [] [];
'onepersubj' 'string' { 'on','off' } 'off';
'forceread' 'string' { 'on','off' } 'off';
'recompute' 'string' { 'on','off' } 'off';
'freqrange' 'real' [] [];
'timerange' 'real' [] [] }, ...
'std_readpac', 'ignore');
if isstr(opt), error(opt); end;
%STUDY = pop_pacparams(STUDY, 'default');
%if isempty(opt.timerange), opt.timerange = STUDY.etc.pacparams.timerange; end;
%if isempty(opt.freqrange), opt.freqrange = STUDY.etc.pacparams.freqrange; end;
nc = max(length(STUDY.condition),1);
ng = max(length(STUDY.group),1);
% find channel indices
% --------------------
if ~isempty(opt.channels1)
len1 = length(opt.channels1);
len2 = length(opt.channels2);
opt.indices1 = std_chaninds(STUDY, opt.channels1);
opt.indices2 = std_chaninds(STUDY, opt.channels2);
else
len1 = length(opt.clusters1);
len2 = length(opt.clusters2);
opt.indices1 = opt.clusters1;
opt.indices2 = opt.clusters2;
end;
STUDY = std_convertoldsetformat(STUDY); %XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX REMOVE WHEN READY TO GET RID OF OLD FORMAT
for ind1 = 1:len1 % usually only one channel/component
for ind2 = 1:len2 % usually one channel/component
% find indices
% ------------
if ~isempty(opt.channels1)
tmpstruct1 = STUDY.changrp(opt.indices1(ind1));
tmpstruct2 = STUDY.changrp(opt.indices2(ind2));
else
tmpstruct1 = STUDY.cluster(opt.indices1(ind1));
tmpstruct2 = STUDY.cluster(opt.indices2(ind2));
end;
allinds1 = tmpstruct1.allinds;
setinds1 = tmpstruct1.setinds;
allinds2 = tmpstruct2.allinds;
setinds2 = tmpstruct2.setinds;
% check if data is already here
% -----------------------------
dataread = 0;
if isfield(tmpstruct1, 'pacdata') & strcmpi(opt.forceread, 'off') & strcmpi(opt.recompute, 'off')
if ~isempty(tmpstruct1.pacdata) & iscell(tmpstruct1.pacdata) & length(tmpstruct1.pacdata) >= opt.indices2(ind2)
if ~isempty(tmpstruct1.pacdata{opt.indices2(ind2)})
%if isequal( STUDY.etc.pacparams.timerange, opt.timerange) & ...
% isequal( STUDY.etc.pacparams.freqrange, opt.freqrange) & ~isempty(tmpstruct.pacdata)
dataread = 1;
end;
end;
end;
if ~dataread
% reserve arrays
% --------------
% pacarray = cell( max(length(STUDY.condition),1), max(length(STUDY.group),1) );
% tmpind1 = 1; while(isempty(setinds{tmpind1})), tmpind1 = tmpind1+1; end;
% tmpind2 = 1; while(isempty(setinds{tmpind2})), tmpind2 = tmpind2+1; end;
% if ~isempty(opt.channels1)
% [ tmp allfreqs alltimes ] = std_readpac( ALLEEG, 'channels1' , setinds1{tmpind}(1), 'channels2' , setinds2{tmpind}(1), 'timerange', opt.timerange, 'freqrange', opt.freqrange);
% else [ tmp allfreqs alltimes ] = std_readpac( ALLEEG, 'components1', setinds1{tmpind}(1), 'components2', setinds2{tmpind}(1), 'timerange', opt.timerange, 'freqrange', opt.freqrange);
% end;
% for c = 1:nc
% for g = 1:ng
% pacarray{c, g} = repmat(zero, [length(alltimes), length(allfreqs), length(allinds1{c,g}) ]);
% end;
% end;
% read the data and select channels
% ---------------------------------
fprintf('Reading all PAC data...\n');
for c = 1:nc
for g = 1:ng
% scan all subjects
count = 1;
for subj = 1:length(STUDY.subject)
% get dataset indices for this subject
[inds1 inds2] = getsubjcomps(STUDY, subj, setinds1{c,g}, setinds2{c,g});
if setinds1{c,g}(inds1) ~= setinds2{c,g}(inds2), error('Wrong subject index'); end;
if ~strcmpi(ALLEEG(setinds1{c,g}(inds1)).subject, STUDY.subject(subj)), error('Wrong subject index'); end;
if ~isempty(inds1) & ~isempty(inds2)
if ~isempty(opt.channels1)
[pacarraytmp allfreqs alltimes] = std_pac( ALLEEG(setinds1{c,g}(subj)), 'channels1' , allinds1{c,g}(inds1), 'channels2', allinds2{c,g}(inds2), 'timerange', opt.timerange, 'freqrange', opt.freqrange, 'recompute', opt.recompute, moreopts{:});
else [pacarraytmp allfreqs alltimes] = std_pac( ALLEEG(setinds1{c,g}(subj)), 'components1', allinds1{c,g}(inds1), 'components2', allinds2{c,g}(inds2), 'timerange', opt.timerange, 'freqrange', opt.freqrange, 'recompute', opt.recompute, moreopts{:});
end;
% collapse first 2 dimentions (comps x comps)
if ndims(pacarraytmp) == 4
pacarraytmp = reshape(pacarraytmp, size(pacarraytmp,1)*size(pacarraytmp,2), size(pacarraytmp,3), size(pacarraytmp,4));
else pacarraytmp = reshape(pacarraytmp, 1, size(pacarraytmp,1),size(pacarraytmp,2));
end;
if strcmpi(opt.onepersubj, 'on')
pacarray{c, g}(:,:,count) = squeeze(mean(pacarraytmp,1));
count = count+1;
else
for tmpi = 1:size(pacarraytmp,1)
pacarray{c, g}(:,:,count) = pacarraytmp(tmpi,:,:);
count = count+1;
end;
end;
end;
end;
end;
end;
% copy data to structure
% ----------------------
if ~isempty(opt.channels1)
STUDY.changrp(opt.indices1(ind1)).pacfreqs = allfreqs;
STUDY.changrp(opt.indices1(ind1)).pactimes = alltimes;
STUDY.changrp(opt.indices1(ind1)).pacdata{opt.indices2(ind2)} = pacarray;
else STUDY.cluster(opt.indices1(ind1)).pacfreqs = allfreqs;
STUDY.cluster(opt.indices1(ind1)).pactimes = alltimes;
STUDY.cluster(opt.indices1(ind1)).pacdata{opt.indices2(ind2)} = pacarray;
end;
end;
end;
end;
% return structure
% ----------------
if ~isempty(opt.channels1)
clustinfo = STUDY.changrp(opt.indices1);
else clustinfo = STUDY.cluster(opt.indices1);
end;
% get components common to a given subject
% ----------------------------------------
function [inds1 inds2] = getsubjcomps(STUDY, subj, setlist1, setlist2, complist1, complist2)
inds1 = [];
inds2 = [];
datasets = strmatch(STUDY.subject{subj}, { STUDY.datasetinfo.subject } ); % all datasets of subject
[tmp1] = intersect_bc(setlist1, datasets);
[tmp2] = intersect_bc(setlist2, datasets);
if length(tmp1) > 1, error('This function does not support sessions for subjects'); end;
if length(tmp2) > 1, error('This function does not support sessions for subjects'); end;
if tmp1 ~= tmp2, error('Different datasets while it should be the same'); end;
if ~isempty(tmp1), inds1 = find(setlist1 == tmp1); end;
if ~isempty(tmp2), inds2 = find(setlist2 == tmp2); end;
|
github
|
lcnhappe/happe-master
|
std_pvaf.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_pvaf.m
| 3,535 |
utf_8
|
3244c50b0ea6577e8f51f7107250c283
|
% std_pvaf() - Compute 'percent variance accounted for' (pvaf) by specified
% ICA component clusters. This function computes eeg_pvaf on each
% of the component of the cluster and then average them. See
% eeg_pvaf for more information. This function uses the
% Usage:
% >> [pvaf pvafs] = std_pvaf(STUDY, ALLEEG, cluster, 'key', 'val');
% Inputs:
% EEG - EEGLAB dataset. Must have icaweights, icasphere, icawinv, icaact.
% comps - vector of component indices to sum {default|[] -> progressive mode}
% In progressive mode, comps is first [1], then [1 2], etc. up to
% [1:size(EEG.icaweights,2)] (all components); here, the plot shows pvaf.
%
% Optional inputs:
% 'design' - [integer] selected design. Default is the current design.
% 'rmcomps' - [integer array] remove artifactual components (this entry
% is ignored when plotting components). This entry contains
% the indices of the components to be removed. Default is none.
% 'interp' - [struct] channel location structure containing electrode
% to interpolate ((this entry is ignored when plotting
% components). Default is no interpolation.
% Other optional inputs are the same as eeg_pvaf()
%
% Outputs:
% pvaf - (real) percent total variance accounted for by the summed
% back-projection of the requested clusters.
% pvafs - [vector] pvaf for each of the cell of the selected design.
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2012-
% Copyright (C) 2012 Arnaud Delorme, SCCN, INC, UCSD
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [pvafAve pvafs] = std_pvaf(STUDY, ALLEEG, cluster, varargin);
if nargin < 3
help std_pvaf;
return;
end;
[opt addOptions] = finputcheck(varargin, { 'design' 'integer' [] STUDY.currentdesign;
'rmclust' 'integer' [] [];
'interp' 'struct' { } struct([]);
'rmcomps' 'cell' [] cell(1,length(ALLEEG)) }, 'std_pvaf', 'ignore');
if isstr(opt), error(opt); end;
DES = STUDY.design(opt.design);
for iCell = 1:length(DES.cell)
[EEG complist rmlistcomp] = std_getdataset(STUDY, ALLEEG, 'cell', iCell, 'cluster', cluster, 'interp', opt.interp, ...
'rmcomps', opt.rmcomps{iCell}, 'rmclust', opt.rmclust, 'interpcomponent', 'on' );
%EEG = std_getdataset(STUDY, ALLEEG, 'cell', iCell);
if ~isempty(EEG.icaweights)
pvafs(iCell) = eeg_pvaf(EEG, [1:size(EEG.icaweights,1)], addOptions{:});
%pvafs(iCell) = eeg_pvaf(EEG, complist, 'artcomps', rmlistcomp, addOptions{:});
else pvafs(iCell) = NaN;
end;
end;
pvafAve = nan_mean(pvafs);
|
github
|
lcnhappe/happe-master
|
std_mergeclust.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_mergeclust.m
| 3,678 |
utf_8
|
8a328c6df1c40cfc3d89f72eb8af8a11
|
% std_mergeclust() - Commandline function, to merge several clusters.
% Usage:
% >> [STUDY] = std_mergeclust(STUDY, ALLEEG, mrg_cls, name);
% Inputs:
% STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - global EEGLAB vector of EEG structures for the dataset(s) included in the STUDY.
% ALLEEG for a STUDY set is typically created using load_ALLEEG().
% mrg_cls - clusters indexes to merge.
% Optional inputs:
% name - [string] a mnemonic cluster name for the merged cluster.
% {default: 'Cls #', where '#' is the next available cluster number}.
%
% Outputs:
% STUDY - the input STUDY set structure modified with the merged cluster.
%
% Example:
% >> mrg_cls = [3 7 9]; name = 'eyes';
% >> [STUDY] = std_mergecluster(STUDY,ALLEEG, mrg_cls, name);
% Merge clusters 3, 7 and 9 to a new cluster named 'eyes'.
%
% See also pop_clustedit
%
% Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, July, 2005
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, July 11, 2005, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function STUDY = std_mergeclust(STUDY, ALLEEG, mrg_cls, varargin)
if isempty(varargin) | strcmpi(varargin,'')
name = 'Cls';
else
name = varargin{1};
end
% Cannot merge clusters if any of the clusters is a 'Notclust' or 'Outlier'
% cluster, or if has children
comps = [];
sets = [];
for k = 1:length(mrg_cls)
if strncmpi('Notclust',STUDY.cluster(mrg_cls(k)).name,8) | strncmpi('Outliers',STUDY.cluster(mrg_cls(k)).name,8) | ...
~isempty(STUDY.cluster(mrg_cls(k)).child)
warndlg2([ 'std_mergeclust: cannot merge clusters if one of the clusters '...
'is a ''Notclust'' or ''Outliers'' cluster, or if it has children clusters.']);
end
parent{k} = STUDY.cluster(mrg_cls(k)).name;
comps = [comps STUDY.cluster(mrg_cls(k)).comps];
sets = [sets STUDY.cluster(mrg_cls(k)).sets];
end
%sort by sets
[tmp,sind] = sort(sets(1,:));
sets = sets(:,sind);
comps = comps(sind);
% sort component indexes within a set
diffsets = unique_bc(sets(1,:));
for k = 1:length(diffsets)
ci = find(sets(1,:) == diffsets(k)); % find the compnents belonging to each set
[tmp,cind] = sort(comps(ci));
comps(ci) = comps(ci(cind));
end
% Create a new empty cluster
[STUDY] = std_createclust(STUDY, ALLEEG, name);
% Update merge cluster with parent clusters
STUDY.cluster(end).parent = parent;
STUDY.cluster(end).sets = sets; % Update merge cluster with merged component sets
STUDY.cluster(end).comps = comps; % Update merge cluster with the merged components
for k = 1:length(mrg_cls) % update the merge cluster as a child for the parent clusters
STUDY.cluster(mrg_cls(k)).child{end + 1} = STUDY.cluster(end).name;
end
STUDY = std_selectdesign(STUDY, ALLEEG, STUDY.currentdesign);
|
github
|
lcnhappe/happe-master
|
std_findoutlierclust.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_findoutlierclust.m
| 599 |
utf_8
|
5cf670b56c3d2178f15c05b6c8482328
|
% std_findoutlierclust() - determine whether an outlier cluster already exists
% for a specified cluster. If so, return the outlier cluster index.
% If not, return zero. This helper function is called by
% pop_clustedit(), std_moveoutlier(), std_renameclust().
function outlier_clust = std_findoutlierclust(STUDY,clust)
outlier_clust = 0;
outlier_name = [ 'Outliers ' STUDY.cluster(clust).name ' ' ];
for k = 1:length(STUDY.cluster)
if strncmpi(outlier_name,STUDY.cluster(k).name,length(outlier_name))
outlier_clust = k;
end
end
|
github
|
lcnhappe/happe-master
|
std_indvarmatch.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_indvarmatch.m
| 2,411 |
utf_8
|
5902a4b72dc6351b4f1b4c26c2975ab8
|
% std_indvarmatch - match independent variable value in a list of values
%
% Usage:
% indices = std_indvarmatch(value, valuelist);
%
% Input:
% value - [string|real|cell] value to be matched
% valuelist - [cell array] cell array of string, numerical values or
% cell array
%
% Output:
% indices - [integer] numerical indices
%
% Example:
% std_indvarmatch( 3, { 3 4 [2 3] });
% std_indvarmatch( [2 3], { 3 4 [2 3] });
% std_indvarmatch( [2 3], { 3 4 2 4 3 });
% std_indvarmatch( 'test1', { 'test1' 'test2' { 'test1' 'test2' } });
% std_indvarmatch( { 'test1' 'test2' }, { 'test1' 'test2' { 'test1' 'test2' } });
% std_indvarmatch( { 'test1' 'test2' }, { 'test1' 'test2' 'test3' 'test1' });
%
% Author: Arnaud Delorme, CERCO/CNRS, UCSD, 2009-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function indices = std_indvarmatch(val, allvals);
indices = [];
if nargin < 1
help std_indvarmatch;
return;
end;
% match values
% ------------
if all(cellfun(@isstr, allvals)) % string
if ~iscell(val)
indices = strmatch( val, allvals, 'exact')';
else
for indcell = 1:length(val)
indices = [ indices std_indvarmatch(val{indcell}, allvals) ];
end;
end;
elseif all(cellfun(@length, allvals) == 1) % numerical
if length(val) == 1
indices = find( val == [allvals{:}]);
else
for ind = 1:length(val)
indices = [ indices std_indvarmatch(val(ind), allvals) ];
end;
end;
else
% mixed with cell array
indices = [];
for index = 1:length(allvals)
if isequal(val, allvals{index})
indices = [indices index];
end;
end;
end;
return;
|
github
|
lcnhappe/happe-master
|
std_renamestudyfiles.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_renamestudyfiles.m
| 3,659 |
utf_8
|
4f9bcafcb1c0e952fab0e36174fc66b2
|
% std_renamestudyfiles() - rename files for design 1 if necessary. In design
% 1, for backward compatibility, files could have
% legacy names. For consistency these files now
% need to be renamed. Note that the STUDY is
% automatically resave on disk to avoid any potential
% inconsistency.
%
% Usage:
% >> STUDY = std_renamestudyfiles(STUDY, ALLEEG)
%
% Inputs:
% STUDY - EEGLAB STUDY set
% ALLEEG - vector of the EEG datasets included in the STUDY structure
%
% Output:
% STUDY - The input STUDY with new design files.
%
% Author: Arnaud Delorme, Institute for Neural Computation UCSD, 2013-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function STUDY = std_renamestudyfiles(STUDY, ALLEEG)
if nargin < 2
help std_renamestudyfiles;
return;
end;
STUDY2 = std_makedesign(STUDY, ALLEEG, 1, STUDY.design(1), 'defaultdesign', 'forceoff', 'verbose', 'off');
allCell1 = { STUDY.design(1).cell.filebase };
allCell2 = { STUDY2.design(1).cell.filebase };
fileExtensions = { 'daterp' 'datspec' 'datersp' 'daterpim' 'dattimef' 'datitc' 'daterpim' ...
'icaerp' 'icaspec' 'icaersp' 'icaerpim' 'icatimef' 'icaitc' 'icaerpim' };
if ~isequal(allCell1, allCell2)
thereIsAFileNotDesign = false;
for index = 1:length(allCell1), if length(allCell1{index}) < 6 || all(allCell1{index}(1:6) == 'design'), thereIsAFileNotDesign = true; end; end;
for index = 1:length(allCell1), if length(allCell1{index}) < 6 || all(allCell1{index}(1:6) == 'design'), thereIsAFileNotDesign = true; end; end;
if thereIsAFileNotDesign
res = questdlg2(['Old STUDY design data files have been detected.' 10 ...
'EEGLAB wants to rename these files to improve consistency' 10 ...
'and stability. No dataset will be renamed, only preprocessed' 10 ...
'STUDY data files.' ], 'Rename STUDY data files', 'Cancel', ...
'Rename', 'Rename');
if strcmpi(res, 'rename')
STUDY = pop_savestudy(STUDY, ALLEEG, 'savemode', 'resave');
for iCell = 1:length(allCell1)
% scan file extensions
for iExt = 1:length(fileExtensions)
files = dir( [ allCell1{iCell} '.' fileExtensions{iExt} ]);
if ~isempty(files) && ~strcmpi(allCell1{iCell}, allCell2{iCell})
movefile( [ allCell1{iCell} '.' fileExtensions{iExt} ], ...
[ allCell2{iCell} '.' fileExtensions{iExt} ]);
disp([ 'Moving ' [ allCell1{iCell} '.' fileExtensions{iExt} ] ' to ' [ allCell2{iCell} '.' fileExtensions{iExt} ] ]);
end;
end;
end;
STUDY = STUDY2;
STUDY = pop_savestudy(STUDY, ALLEEG, 'savemode', 'resave');
end;
end;
end;
|
github
|
lcnhappe/happe-master
|
pop_specparams.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/pop_specparams.m
| 10,715 |
utf_8
|
027537cb2c61d5a0c4c36d1e4010028c
|
% pop_specparams() - Set plotting and statistics parameters for computing
% STUDY component spectra.
% Usage:
% >> STUDY = pop_specparams(STUDY, 'key', 'val');
%
% Inputs:
% STUDY - EEGLAB STUDY set
%
% Plot options:
% 'topofreq' - [real] Plot Spectrum scalp maps at one specific freq. (Hz).
% A frequency range [min max] may also be defined (the
% spectrum is then averaged over the interval) {default: []}
% 'freqrange' - [min max] spectral frequency range (in Hz) to plot.
% {default: whole frequency range} .
% 'ylim' - [mindB maxdB] spectral plotting limits in dB
% {default: from data}
% 'plotgroups' - ['together'|'apart'] 'together' -> plot subject groups
% on the same figure in different colors, else ('apart') on
% different figures {default: 'apart'}
% 'plotconditions' - ['together'|'apart'] 'together' -> plot conditions
% on the same figure in different colors, else ('apart')
% on different figures. Note: keywords 'plotgroups' and
% 'plotconditions' cannot both be set to 'together'.
% {default: 'apart'}
% 'subtractsubjectmean' - ['on'|'off'] subtract individual subject mean
% from each spectrum before plotting and computing
% statistics. Default is 'off'.
% 'averagechan' - ['on'|'off'] average data channels when several are
% selected.
%
% See also: std_specplot()
%
% Authors: Arnaud Delorme, CERCO, CNRS, 2006-
% Copyright (C) Arnaud Delorme, CERCO
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public 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 [ STUDY, com ] = pop_specparams(STUDY, varargin);
STUDY = default_params(STUDY);
TMPSTUDY = STUDY;
com = '';
if isempty(varargin)
enablecond = fastif(length(STUDY.design(STUDY.currentdesign).variable(1).value)>1, 'on', 'off');
enablegroup = fastif(length(STUDY.design(STUDY.currentdesign).variable(2).value)>1, 'on', 'off');
detachplots = fastif(strcmpi(STUDY.etc.specparams.detachplots,'on'), 1, 0);
plotconditions = fastif(strcmpi(STUDY.etc.specparams.plotconditions, 'together'), 1, 0);
plotgroups = fastif(strcmpi(STUDY.etc.specparams.plotgroups,'together'), 1, 0);
submean = fastif(strcmpi(STUDY.etc.specparams.subtractsubjectmean,'on'), 1, 0);
radio_averagechan = fastif(strcmpi(STUDY.etc.specparams.averagechan,'on'), 1, 0);
radio_scalptopo = fastif(isempty(STUDY.etc.specparams.topofreq), 0, 1);
if radio_scalptopo, radio_averagechan = 0; end;
if radio_scalptopo+radio_averagechan == 0, radio_scalparray = 1; else radio_scalparray = 0; end;
cb_radio = [ 'set(findobj(gcbf, ''userdata'', ''radio''), ''value'', 0);' ...
'set(gcbo, ''value'', 1);' ...
'set(findobj(gcbf, ''tag'', ''topofreq''), ''string'', '''');' ];
cb_edit = [ 'set(findobj(gcbf, ''userdata'', ''radio''), ''value'', 0);' ...
'set(findobj(gcbf, ''tag'', ''scalptopotext''), ''value'', 1);' ];
uilist = { ...
{'style' 'text' 'string' 'Spectrum plotting options' 'fontweight' 'bold' 'fontsize', 12} ...
{} {'style' 'text' 'string' 'Frequency [low_Hz high_Hz]' } ...
{'style' 'edit' 'string' num2str(STUDY.etc.specparams.freqrange) 'tag' 'freqrange' } ...
{} {'style' 'text' 'string' 'Plot limits [low high]'} ...
{'style' 'edit' 'string' num2str(STUDY.etc.specparams.ylim) 'tag' 'ylim' } ...
{} {'style' 'checkbox' 'string' 'Subtract individual subject mean spectrum' 'value' submean 'tag' 'submean' } ...
{} ...
{'style' 'text' 'string' 'Spectrum plotting format' 'fontweight' 'bold' 'fontsize', 12} ...
{} {'style' 'checkbox' 'string' 'Plot first variable on the same panel' 'value' plotconditions 'enable' enablecond 'tag' 'plotconditions' } ...
{} {'style' 'checkbox' 'string' 'Plot second variable on the same panel' 'value' plotgroups 'enable' enablegroup 'tag' 'plotgroups' } ...
{} {'style' 'checkbox' 'string' 'Detach plots' 'value' detachplots 'enable' 'on' 'tag' 'detachtag' } ...
{} ...
{'style' 'text' 'string' 'Multiple channels selection' 'fontweight' 'bold' 'fontsize', 12} ...
{} {'style' 'radio' 'string' 'Plot channels in scalp array' 'value' radio_scalparray 'tag' 'scalparray' 'userdata' 'radio' 'callback' cb_radio} { } ...
{} {'style' 'radio' 'string' 'Plot topography at freq. (Hz)' 'value' radio_scalptopo 'tag' 'scalptopotext' 'userdata' 'radio' 'callback' cb_radio} ...
{'style' 'edit' 'string' num2str(STUDY.etc.specparams.topofreq) 'tag' 'topofreq' 'callback' cb_edit } ...
{} {'style' 'radio' 'string' 'Average selected channels' 'value' radio_averagechan 'tag' 'averagechan' 'userdata' 'radio' 'callback' cb_radio} { } };
cbline = [0.07 1.1];
otherline = [ 0.07 0.6 .3];
chanline = [ 0.07 0.8 0.3];
geometry = { 1 otherline otherline cbline 1 1 cbline cbline cbline 1 1 chanline chanline chanline };
geomvert = [1.2 1 1 1 0.5 1.2 1 1 1 0.5 1.2 1 1 1 ];
% component plotting
% ------------------
if isnan(STUDY.etc.specparams.topofreq)
geometry(end-4:end) = [];
geomvert(end-4:end) = [];
uilist(end-10:end) = [];
end;
[out_param userdat tmp res] = inputgui( 'geometry' , geometry, 'uilist', uilist, 'geomvert', geomvert, ...
'title', 'Spectrum plotting options -- pop_specparams()');
if isempty(res), return; end;
% decode inputs
% -------------
%if res.plotgroups & res.plotconditions, warndlg2('Both conditions and group cannot be plotted on the same panel'); return; end;
if res.submean , res.submean = 'on'; else res.submean = 'off'; end;
if res.plotgroups, res.plotgroups = 'together'; else res.plotgroups = 'apart'; end;
if res.plotconditions , res.plotconditions = 'together'; else res.plotconditions = 'apart'; end;
if res.detachtag, res.detachtag = 'on'; else res.detachtag = 'off'; end;
if ~isfield(res, 'topofreq'), res.topofreq = STUDY.etc.specparams.topofreq;
else res.topofreq = str2num( res.topofreq );
end;
if ~isfield(res, 'averagechan'), res.averagechan = STUDY.etc.specparams.averagechan;
elseif res.averagechan, res.averagechan = 'on'; else res.averagechan = 'off';
end;
res.freqrange = str2num( res.freqrange );
res.ylim = str2num( res.ylim );
% build command call
% ------------------
options = {};
if ~strcmpi( res.plotgroups, STUDY.etc.specparams.plotgroups), options = { options{:} 'plotgroups' res.plotgroups }; end;
if ~strcmpi( res.plotconditions , STUDY.etc.specparams.plotconditions ), options = { options{:} 'plotconditions' res.plotconditions }; end;
if ~strcmpi( res.detachtag, STUDY.etc.specparams.detachplots), options = { options{:} 'detachplots' res.detachtag}; end;
if ~strcmpi( res.submean , STUDY.etc.specparams.subtractsubjectmean ), options = { options{:} 'subtractsubjectmean' res.submean }; end;
if ~isequal(res.topofreq, STUDY.etc.specparams.topofreq), options = { options{:} 'topofreq' res.topofreq }; end;
if ~isequal(res.ylim, STUDY.etc.specparams.ylim), options = { options{:} 'ylim' res.ylim }; end;
if ~isequal(res.freqrange, STUDY.etc.specparams.freqrange), options = { options{:} 'freqrange' res.freqrange }; end;
if ~isequal(res.averagechan, STUDY.etc.specparams.averagechan), options = { options{:} 'averagechan' res.averagechan }; end;
if ~isempty(options)
STUDY = pop_specparams(STUDY, options{:});
com = sprintf('STUDY = pop_specparams(STUDY, %s);', vararg2str( options ));
end;
else
if strcmpi(varargin{1}, 'default')
STUDY = default_params(STUDY);
else
for index = 1:2:length(varargin)
if ~isempty(strmatch(varargin{index}, fieldnames(STUDY.etc.specparams), 'exact'))
STUDY.etc.specparams = setfield(STUDY.etc.specparams, varargin{index}, varargin{index+1});
end;
end;
end;
end;
% scan clusters and channels to remove specdata info if freqrange has changed
% ----------------------------------------------------------
if ~isequal(STUDY.etc.specparams.freqrange, TMPSTUDY.etc.specparams.freqrange) | ...
~isequal(STUDY.etc.specparams.subtractsubjectmean, TMPSTUDY.etc.specparams.subtractsubjectmean)
rmfields = { 'specdata' 'specfreqs' };
for iField = 1:length(rmfields)
if isfield(STUDY.cluster, rmfields{iField})
STUDY.cluster = rmfield(STUDY.cluster, rmfields{iField});
end;
if isfield(STUDY.changrp, rmfields{iField})
STUDY.changrp = rmfield(STUDY.changrp, rmfields{iField});
end;
end;
end;
function STUDY = default_params(STUDY)
if ~isfield(STUDY.etc, 'specparams'), STUDY.etc.specparams = []; end;
if ~isfield(STUDY.etc.specparams, 'topofreq'), STUDY.etc.specparams.topofreq = []; end;
if ~isfield(STUDY.etc.specparams, 'freqrange'), STUDY.etc.specparams.freqrange = []; end;
if ~isfield(STUDY.etc.specparams, 'ylim' ), STUDY.etc.specparams.ylim = []; end;
if ~isfield(STUDY.etc.specparams, 'subtractsubjectmean' ), STUDY.etc.specparams.subtractsubjectmean = 'off'; end;
if ~isfield(STUDY.etc.specparams, 'plotgroups'), STUDY.etc.specparams.plotgroups = 'apart'; end;
if ~isfield(STUDY.etc.specparams, 'plotconditions'), STUDY.etc.specparams.plotconditions = 'apart'; end;
if ~isfield(STUDY.etc.specparams, 'averagechan') , STUDY.etc.specparams.averagechan = 'off'; end;
if ~isfield(STUDY.etc.specparams, 'detachplots') , STUDY.etc.specparams.detachplots = 'on'; end;
|
github
|
lcnhappe/happe-master
|
std_erp.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_erp.m
| 10,470 |
utf_8
|
f3a709fb521ddae8ca35a36c72b67d97
|
% std_erp() - Constructs and returns channel or ICA activation ERPs for a dataset.
% Saves the ERPs into a Matlab file, [dataset_name].icaerp, for
% data channels or [dataset_name].icaerp for ICA components,
% in the same directory as the dataset file. If such a file
% already exists, loads its information.
% Usage:
% >> [erp, times] = std_erp(EEG, 'key', 'val', ...);
% Inputs:
% EEG - a loaded epoched EEG dataset structure. May be an array
% of such structure containing several datasets.
%
% Optional inputs:
% 'components' - [numeric vector] components of the EEG structure for which
% activation ERPs will be computed. Note that because
% computation of ERP is so fast, all components ERP are
% computed and saved. Only selected component
% are returned by the function to Matlab
% {default|[] -> all}
% 'channels' - [cell array] channels of the EEG structure for which
% activation ERPs will be computed. Note that because
% computation of ERP is so fast, all channels ERP are
% computed and saved. Only selected channels
% are returned by the function to Matlab
% {default|[] -> none}
% 'recompute' - ['on'|'off'] force recomputing ERP file even if it is
% already on disk.
% 'trialindices' - [cell array] indices of trials for each dataset.
% Default is all trials.
% 'recompute' - ['on'|'off'] force recomputing data file even if it is
% already on disk.
% 'rmcomps' - [integer array] remove artifactual components (this entry
% is ignored when plotting components). This entry contains
% the indices of the components to be removed. Default is none.
% 'interp' - [struct] channel location structure containing electrode
% to interpolate (this entry is ignored when plotting
% components). Default is no interpolation.
% 'fileout' - [string] name of the file to save on disk. The default
% is the same name (with a different extension) as the
% dataset given as input.
% 'savetrials' - ['on'|'off'] save single-trials ERSP. Requires a lot of disk
% space (dataset space on disk times 10) but allow for refined
% single-trial statistics.
%
% ERP specific options:
% 'rmbase' - [min max] remove baseline. This option does not affect
% the original datasets.
%
% Outputs:
% erp - ERP for the requested ICA components in the selected
% latency window. ERPs are scaled by the RMS over of the
% component scalp map projection over all data channels.
% times - vector of times (epoch latencies in ms) for the ERP
%
% File output:
% [dataset_file].icaerp % component erp file
% OR
% [dataset_file].daterp % channel erp file
%
% See also: std_spec(), std_ersp(), std_topo(), std_preclust()
%
% Authors: Arnaud Delorme, SCCN, INC, UCSD, January, 2005
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 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
function [X, t] = std_erp(EEG, varargin); %comps, timerange)
if nargin < 1
help std_erp;
return;
end;
% decode inputs
% -------------
if ~isempty(varargin)
if ~isstr(varargin{1})
varargin = { varargin{:} [] [] };
if all(varargin{1} > 0)
options = { 'components' varargin{1} 'timerange' varargin{2} };
else
options = { 'channels' -varargin{1} 'timerange' varargin{2} };
end;
else
options = varargin;
end;
else
options = varargin;
end;
g = finputcheck(options, { 'components' 'integer' [] [];
'channels' 'cell' {} {};
'rmbase' 'real' [] [];
'trialindices' { 'integer','cell' } [] [];
'rmcomps' 'cell' [] cell(1,length(EEG));
'fileout' 'string' [] '';
'savetrials' 'string' { 'on','off' } 'off';
'interp' 'struct' { } struct([]);
'timerange' 'real' [] []; % the timerange option is deprecated and has no effect
'recompute' 'string' { 'on','off' } 'off' }, 'std_erp');
if isstr(g), error(g); end;
if isempty(g.trialindices), g.trialindices = cell(length(EEG)); end;
if ~iscell(g.trialindices), g.trialindices = { g.trialindices }; end;
if isfield(EEG,'icaweights')
numc = size(EEG(1).icaweights,1);
else
error('EEG.icaweights not found');
end
if isempty(g.components)
g.components = 1:numc;
end
% % THIS SECTION WOULD NEED TO TEST THAT THE PARAMETERS ON DISK ARE CONSISTENT
%
% % filename
% % --------
if isempty(g.fileout), g.fileout = fullfile(EEG(1).filepath, EEG(1).filename(1:end-4)); end;
if ~isempty(g.channels)
filenameshort = [ g.fileout '.daterp'];
prefix = 'chan';
else
filenameshort = [ g.fileout '.icaerp'];
prefix = 'comp';
end;
%filename = fullfile( EEG(1).filepath, filenameshort);
filename = filenameshort;
% ERP information found in datasets
% ---------------------------------
if exist(filename) & strcmpi(g.recompute, 'off')
fprintf('File "%s" found on disk, no need to recompute\n', filenameshort);
setinfo.filebase = g.fileout;
if strcmpi(prefix, 'comp')
[X tmp t] = std_readfile(setinfo, 'components', g.components, 'timelimits', g.timerange, 'measure', 'erp');
else
[X tmp t] = std_readfile(setinfo, 'channels', g.channels, 'timelimits', g.timerange, 'measure', 'erp');
end;
if ~isempty(X), return; end;
end
% No ERP information found
% ------------------------
% if isstr(EEG.data)
% TMP = eeg_checkset( EEG, 'loaddata' ); % load EEG.data and EEG.icaact
% else
% TMP = EEG;
% end
% & isempty(TMP.icaact)
% TMP.icaact = (TMP.icaweights*TMP.icasphere)* ...
% reshape(TMP.data(TMP.icachansind,:,:), [ length(TMP.icachansind) size(TMP.data,2)*size(TMP.data,3) ]);
% TMP.icaact = reshape(TMP.icaact, [ size(TMP.icaact,1) size(TMP.data,2) size(TMP.data,3) ]);
%end;
%if strcmpi(prefix, 'comp'), X = TMP.icaact;
%else X = TMP.data;
%end;
options = {};
if ~isempty(g.rmcomps), options = { options{:} 'rmcomps' g.rmcomps }; end;
if ~isempty(g.interp), options = { options{:} 'interp' g.interp }; end;
if isempty(g.channels)
X = eeg_getdatact(EEG, 'component', [1:size(EEG(1).icaweights,1)], 'trialindices', g.trialindices );
else X = eeg_getdatact(EEG, 'trialindices', g.trialindices, 'rmcomps', g.rmcomps, 'interp', g.interp);
end;
% Remove baseline mean
% --------------------
pnts = EEG(1).pnts;
trials = size(X,3);
timevals = EEG(1).times;
if ~isempty(g.timerange)
disp('Warning: the ''timerange'' option is deprecated and has no effect');
end;
if ~isempty(X)
if ~isempty(g.rmbase)
disp('Removing baseline...');
options = { options{:} 'rmbase' g.rmbase };
[tmp timebeg] = min(abs(timevals - g.rmbase(1)));
[tmp timeend] = min(abs(timevals - g.rmbase(2)));
if ~isempty(timebeg)
X = rmbase(X,pnts, [timebeg:timeend]);
else
X = rmbase(X,pnts);
end
end
X = reshape(X, [ size(X,1) pnts trials ]);
if strcmpi(prefix, 'comp')
if strcmpi(g.savetrials, 'on')
X = repmat(sqrt(mean(EEG(1).icawinv.^2))', [1 EEG(1).pnts size(X,3)]) .* X;
else
X = repmat(sqrt(mean(EEG(1).icawinv.^2))', [1 EEG(1).pnts]) .* mean(X,3); % calculate ERP
end;
elseif strcmpi(g.savetrials, 'off')
X = mean(X, 3);
end;
end;
% Save ERPs in file (all components or channels)
% ----------------------------------------------
if isempty(timevals), timevals = linspace(EEG(1).xmin, EEG(1).xmax, EEG(1).pnts)*1000; end; % continuous data
fileNames = computeFullFileName( { EEG.filepath }, { EEG.filename });
if strcmpi(prefix, 'comp')
savetofile( filename, timevals, X, 'comp', 1:size(X,1), options, {}, fileNames, g.trialindices);
%[X,t] = std_readerp( EEG, 1, g.components, g.timerange);
else
if ~isempty(g.interp)
savetofile( filename, timevals, X, 'chan', 1:size(X,1), options, { g.interp.labels }, fileNames, g.trialindices);
else
tmpchanlocs = EEG(1).chanlocs;
savetofile( filename, timevals, X, 'chan', 1:size(X,1), options, { tmpchanlocs.labels }, fileNames, g.trialindices);
end;
%[X,t] = std_readerp( EEG, 1, g.channels, g.timerange);
end;
% compute full file names
% -----------------------
function res = computeFullFileName(filePaths, fileNames);
for index = 1:length(fileNames)
res{index} = fullfile(filePaths{index}, fileNames{index});
end;
% -------------------------------------
% saving ERP information to Matlab file
% -------------------------------------
function savetofile(filename, t, X, prefix, comps, params, labels, dataFiles, dataTrials);
disp([ 'Saving ERP file ''' filename '''' ]);
allerp = [];
for k = 1:length(comps)
allerp = setfield( allerp, [ prefix int2str(comps(k)) ], squeeze(X(k,:,:)));
end;
if nargin > 6 && ~isempty(labels)
allerp.labels = labels;
end;
allerp.times = t;
allerp.datatype = 'ERP';
allerp.parameters = params;
allerp.datafiles = dataFiles;
allerp.datatrials = dataTrials;
std_savedat(filename, allerp);
|
github
|
lcnhappe/happe-master
|
pop_erpimparams.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/pop_erpimparams.m
| 8,436 |
utf_8
|
239b2e9f4a563e64fe4a3d7d631a5b62
|
% pop_erpimparams() - Set plotting and statistics parameters for
% computing and plotting STUDY mean ERPimages and measure
% statistics. Settings are stored within the STUDY
% structure (STUDY.etc.erpimparams) which is used
% whenever plotting is performed by the function
% std_erpimage().
% Usage:
% >> STUDY = pop_erpimparams(STUDY, 'key', 'val', ...);
%
% Inputs:
% STUDY - EEGLAB STUDY set
%
% Erpimage plotting options:
% 'timerange' - [min max] erpim/ITC plotting latency range in ms.
% {default: the whole output latency range}.
% 'trialrange' - [min max] erpim/ITC plotting frequency range in ms.
% {default: the whole output frequency range}
% 'topotime' - [float] plot scalp map at specific time. A time range may
% also be provide and the erpim will be averaged over the
% given time range. Requires 'topofreq' below to be set.
% 'topotrial' - [float] plot scalp map at specific trial in ERPimage. As
% above a trial range may also be provided.
%
% Authors: Arnaud Delorme, CERCO, CNRS, 2006-
% Copyright (C) Arnaud Delorme, 2006
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ STUDY, com ] = pop_erpimparams(STUDY, varargin);
STUDY = default_params(STUDY);
TMPSTUDY = STUDY;
com = '';
if isempty(varargin)
vis = fastif(isnan(STUDY.etc.erpimparams.topotime), 'off', 'on');
uilist = { ...
{'style' 'text' 'string' 'ERPimage plotting options' 'fontweight' 'bold' 'tag', 'erpim' } ...
{'style' 'text' 'string' 'Time range in ms [Low High]'} ...
{'style' 'edit' 'string' num2str(STUDY.etc.erpimparams.timerange) 'tag' 'timerange' } ...
{'style' 'text' 'string' 'Plot scalp map at time [ms]' 'visible' vis} ...
{'style' 'edit' 'string' num2str(STUDY.etc.erpimparams.topotime) 'tag' 'topotime' 'visible' vis } ...
{'style' 'text' 'string' 'Trial range [Low High]'} ...
{'style' 'edit' 'string' num2str(STUDY.etc.erpimparams.trialrange) 'tag' 'trialrange' } ...
{'style' 'text' 'string' 'Plot scalp map at trial(s)' 'visible' vis} ...
{'style' 'edit' 'string' num2str(STUDY.etc.erpimparams.topotrial) 'tag' 'topotrial' 'visible' vis } ...
{'style' 'text' 'string' 'Color limits [Low High]'} ...
{'style' 'edit' 'string' num2str(STUDY.etc.erpimparams.colorlimits) 'tag' 'colorlimits' } ...
{'style' 'text' 'string' '' } ...
{'style' 'text' 'string' '' } };
evalstr = 'set(findobj(gcf, ''tag'', ''erpim''), ''fontsize'', 12);';
cbline = [0.07 1.1];
otherline = [ 0.6 .4 0.6 .4];
geometry = { 1 otherline otherline otherline };
enablecond = fastif(length(STUDY.design(STUDY.currentdesign).variable(1).value)>1, 'on', 'off');
enablegroup = fastif(length(STUDY.design(STUDY.currentdesign).variable(2).value)>1, 'on', 'off');
[out_param userdat tmp res] = inputgui( 'geometry' , geometry, 'uilist', uilist, ...
'title', 'Set Erpimage plotting parameters -- pop_erpimparams()', 'eval', evalstr);
if isempty(res), return; end;
% decode input
% ------------
res.topotime = str2num( res.topotime );
res.topotrial = str2num( res.topotrial );
res.timerange = str2num( res.timerange );
res.trialrange = str2num( res.trialrange );
res.colorlimits = str2num( res.colorlimits );
% build command call
% ------------------
options = {};
if ~isequal(res.topotime , STUDY.etc.erpimparams.topotime), options = { options{:} 'topotime' res.topotime }; end;
if ~isequal(res.topotrial, STUDY.etc.erpimparams.topotrial), options = { options{:} 'topotrial' res.topotrial }; end;
if ~isequal(res.timerange , STUDY.etc.erpimparams.timerange), options = { options{:} 'timerange' res.timerange }; end;
if ~isequal(res.trialrange, STUDY.etc.erpimparams.trialrange), options = { options{:} 'trialrange' res.trialrange }; end;
if ~isequal(res.colorlimits, STUDY.etc.erpimparams.colorlimits), options = { options{:} 'colorlimits' res.colorlimits }; end;
if ~isempty(options)
STUDY = pop_erpimparams(STUDY, options{:});
com = sprintf('STUDY = pop_erpimparams(STUDY, %s);', vararg2str( options ));
end;
else
if strcmpi(varargin{1}, 'default')
STUDY = default_params(STUDY);
else
allfields = fieldnames(STUDY.etc.erpimparams);
for index = 1:2:length(varargin)
if ~isempty(strmatch(varargin{index}, allfields, 'exact'))
STUDY.etc.erpimparams = setfield(STUDY.etc.erpimparams, varargin{index}, varargin{index+1});
else
if ~isequal(varargin{index}, 'datatype') && ~isequal(varargin{index}, 'channels')
inderpimopt = strmatch(varargin{index}, STUDY.etc.erpimparams.erpimageopt(1:2:end), 'exact');
if ~isempty(inderpimopt)
STUDY.etc.erpimparams.erpimageopt{2*inderpimopt} = varargin{index+1};
else
STUDY.etc.erpimparams.erpimageopt = { STUDY.etc.erpimparams.erpimageopt{:} varargin{index}, varargin{index+1} };
end;
end;
end;
end;
end;
end;
% scan clusters and channels to remove erpimdata info if timerange etc. have changed
% ---------------------------------------------------------------------------------
if ~isequal(STUDY.etc.erpimparams.timerange, TMPSTUDY.etc.erpimparams.timerange) | ...
~isequal(STUDY.etc.erpimparams.trialrange, TMPSTUDY.etc.erpimparams.trialrange)
rmfields = { 'erpimdata' 'erpimtimes' 'erpimtrials' 'erpimevents' };
for iField = 1:length(rmfields)
if isfield(STUDY.cluster, rmfields{iField})
STUDY.cluster = rmfield(STUDY.cluster, rmfields{iField});
end;
if isfield(STUDY.changrp, rmfields{iField})
STUDY.changrp = rmfield(STUDY.changrp, rmfields{iField});
end;
end;
end;
function STUDY = default_params(STUDY)
if ~isfield(STUDY.etc, 'erpimparams'), STUDY.etc.erpimparams = []; end;
if ~isfield(STUDY.etc.erpimparams, 'erpimageopt'), STUDY.etc.erpimparams.erpimageopt = {}; end;
if ~isfield(STUDY.etc.erpimparams, 'sorttype' ), STUDY.etc.erpimparams.sorttype = ''; end;
if ~isfield(STUDY.etc.erpimparams, 'sortwin' ), STUDY.etc.erpimparams.sortwin = []; end;
if ~isfield(STUDY.etc.erpimparams, 'sortfield' ), STUDY.etc.erpimparams.sortfield = 'latency'; end;
if ~isfield(STUDY.etc.erpimparams, 'rmcomps' ), STUDY.etc.erpimparams.rmcomps = []; end;
if ~isfield(STUDY.etc.erpimparams, 'interp' ), STUDY.etc.erpimparams.interp = []; end;
if ~isfield(STUDY.etc.erpimparams, 'timerange' ), STUDY.etc.erpimparams.timerange = []; end;
if ~isfield(STUDY.etc.erpimparams, 'trialrange' ), STUDY.etc.erpimparams.trialrange = []; end;
if ~isfield(STUDY.etc.erpimparams, 'topotime' ), STUDY.etc.erpimparams.topotime = []; end;
if ~isfield(STUDY.etc.erpimparams, 'topotrial' ), STUDY.etc.erpimparams.topotrial = []; end;
if ~isfield(STUDY.etc.erpimparams, 'colorlimits'), STUDY.etc.erpimparams.colorlimits = []; end;
if ~isfield(STUDY.etc.erpimparams, 'concatenate'), STUDY.etc.erpimparams.concatenate = 'off'; end;
if ~isfield(STUDY.etc.erpimparams, 'nlines'), STUDY.etc.erpimparams.nlines = 20; end;
if ~isfield(STUDY.etc.erpimparams, 'smoothing'), STUDY.etc.erpimparams.smoothing = 10; end;
|
github
|
lcnhappe/happe-master
|
std_dipoleclusters.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_dipoleclusters.m
| 13,236 |
utf_8
|
6bbd84189c57ef6ab08de937ebf62583
|
% std_dipoleclusters - Plots clusters of ICs as colored dipoles in MRI
% images (side, rear, top and oblique angles possible)
%
% std_dipoleclusters(STUDY,ALLEEG,'key1',value1, 'key2',value2, ... );
%
% Inputs:
% STUDY - EEGLAB STUDY set
% ALLEEG - vector of the EEG datasets included in the STUDY structure
%
% Optional inputs:
% 'clusters' - [vector of numbers] list of clusters to plot in same head space
% 'title' - [string] figure title
% 'viewnum' - [vector] list of views to plot: 1=top, 2=side, 3=rear, 4 is an oblique view;
% length(viewnum) gives the number of subplots that will be produced and the
% values within the vector tell the orientation and order of views
% 'rowcolplace' - [rows cols subplot] If plotting into an existing figure, specify the number of rows,
% columns and the subplot number to start plotting dipole panels.
% 'colors' - [vector or matrix] if 1 x 3 vector of RGB values, this will plot all dipoles as the
% same color. ex. [1 0 0] is red, [0 0 1] is blue, [0 1 0] is green.
% If a matrix, should be n x 3, with the number of rows equal to the number
% of clusters to be plotted and the columns should be RGB values for each.
% If [], will plot clusters as 'jet' colorscale from the first to the last cluster
% requested (therefore an alternate way to control dipole color is to input a specific
% order of clusters).
% [] will assign colors from hsv color scale.
% 'centroid' - ['only', 'add', 'off'] 'only' will plot only cluster centroids, 'add' will superimpose
% centroids over cluster dipoles, 'off' will skip centroid plotting and only plot
% cluster-member dipoles.
%
% Authors: Julie Onton, SCCN/INC UCSD, June 2009
% Copyright (C) Julie Onton, SCCN/INC/UCSD, October 11, 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 std_dipoleclusters(STUDY,ALLEEG, varargin);
if nargin < 2
help std_dipoleclusters;
return;
end;
% Set default values------------------------------------------------------------------------
if strcmp(STUDY.cluster(2),'outlier 2') % don't plot outlier cluster #2
clustvec = [3:length(STUDY.cluster)]; % plot all clusters in STUDY
else
clustvec = [2:length(STUDY.cluster)]; % plot all clusters in STUDY
end;
onecolor = [];
colvec = [];
centroid = 'off';
viewnum = [1:4]; % plot all views and oblique
rowcolplace = [2 2 1]; % 2 X 2 figure starting in subplot 1
figureon = 1; % plot on a new figure
ttl = ''; % no title
%---------------------------------------------------------------------------------
for k = 3:2:nargin
switch varargin{k-2}
case 'clusters'
clusters = varargin{k-1}; % redefine from all to specified clusters
case 'title'
ttl = varargin{k-1};
case 'viewnum',
viewnum = varargin{k-1};
case 'rowcolplace' %, mode = varargin{k-1}; % what is mode? JO
rowcolplace = varargin{k-1};
if length(rowcolplace) < 3
fprintf('\nThe variable ''rowcolplace'' must contain 3 values.\n');
return;
end;
row = rowcolplace(1);
col = rowcolplace(2);
place = rowcolplace(3);
figureon = 0; % don't pop a new figure if plotting into existing fig
case 'colors'
colvec = varargin{k-1};
case 'centroid'
centroid = varargin{k-1};
end
end
% adjust color matrix for dipoles:---------------
if isempty(colvec)
cols = jet(length(clusters));% default colors
else
cols = colvec; % input RGB colors
end;
% extract IC cluster and data path info from STUDY structure
clear clustcps fullpaths gdcomps
x = cell(1,length(unique({STUDY.datasetinfo.subject})));
subjs = unique_bc({STUDY.datasetinfo.subject});
origlist = cell(1,length(unique({STUDY.datasetinfo.subject})));
sets = cell(1,length(unique({STUDY.datasetinfo.subject})));
for clust = 1:length(STUDY.cluster)
clustcps{clust} = x;
for st = 1:size(STUDY.cluster(clust).sets,2)
currset = STUDY.cluster(clust).sets(1,st);
currcomp = STUDY.cluster(clust).comps(1,st);
subjidx = strmatch(STUDY.datasetinfo(currset).subject,subjs);
clustcps{clust}{subjidx}(end+1) = currcomp;
origlist{subjidx} = [origlist{subjidx} currcomp];
[origlist{subjidx} idx] = unique_bc(origlist{subjidx});
sets{subjidx} = currset;
end;
end;
%-----------------------------------------------------------
% extract dipole info for ALL ICs to be plotted subj by subj
for nx = 1:length(origlist)
dipsources = [];
if ~isempty(origlist{nx})
EEG = ALLEEG(sets{nx}); % call in a dataset from subj
if isfield(EEG.dipfit.model,'diffmap')
EEG.dipfit.model = rmfield(EEG.dipfit.model,'diffmap');
end;
if isfield(EEG.dipfit.model,'active')
EEG.dipfit.model = rmfield(EEG.dipfit.model,'active');
end;
if isfield(EEG.dipfit.model,'select')
EEG.dipfit.model = rmfield(EEG.dipfit.model,'select');
end;
dipsources.posxyz = EEG.dipfit.model(origlist{nx}(1)).posxyz;
dipsources.momxyz = EEG.dipfit.model(origlist{nx}(1)).momxyz;
dipsources.rv = EEG.dipfit.model(origlist{nx}(1)).rv;p=1;
for w = 1:length(origlist{nx})
dipsources(1,p).posxyz = EEG.dipfit.model(origlist{nx}(w)).posxyz;
dipsources(1,p).momxyz = EEG.dipfit.model(origlist{nx}(w)).momxyz;
dipsources(1,p).rv = EEG.dipfit.model(origlist{nx}(w)).rv;
p=p+1;
end;
allbesa1{nx} = dipsources; new = 0;
end;
end;
%-----------------------------------------------------------
% collect cluster dipole info from extracted dipole infos (above)
%%%%%%%%%%%%%%%%%%%%%%%%%
new = 1; pp=1; bic = 1;
centrstr = struct('posxyz',[0 0 0],'momxyz',[0 0 0],'rv',0);
for clst =1:length(clusters)
clust = clusters(clst);
centr = [];
centr2 = [];
for nx = 1:length(clustcps{clust})
if ~isempty(clustcps{clust}{nx})
for k = 1:length(clustcps{clust}{nx})
if new == 1
allbesa = allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k)));
centr = [centr; allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(1,:)];
if size(allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz,1) > 1& allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(2,1) ~= 0 % actual values, not zero
if allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(2,2) > 0 % on the wrong side, switch with centr1
centr2 = [centr2;allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(2,:)];
centr2(end,2) = centr2(end,2)*-1; centr1(end,2) = centr1(end,2)*-1;
else
centr2 = [centr2;allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(2,:)];
end;
end;
new = 0;
else
allbesa(1,end+1) = allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k)));
centr = [centr; allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(1,:)];
if size(allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz,1) > 1 & allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(2,1) ~= 0 % actual values, not zero
if allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(2,2) > 0 % on the wrong side, switch with centr1
centr2 = [centr2; allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(2,:)];
centr2(end,2) = centr2(end,2)*-1; centr1(end,2) = centr1(end,2)*-1;
else
centr2 = [centr2;allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(2,:)];
end;
end;
end;
colset{pp} = cols(clst,:); pp = pp+1;
end;
end;
end;
if length(allbesa) > 1
centr = mean(centr,1);
centr2 = mean(centr2,1);
centrstr(clst).posxyz = centr;
centrstr(clst).momxyz = allbesa(end).momxyz(1,:);
centrstr(clst).rv = 2;
centcols{clst} = cols(clst,:);
centcols2{clst} = cols(clst,:)/5;
if ~isempty(find(centr2))
centrstr2(bic).posxyz = centr2;
centrstr2(bic).momxyz = allbesa(end).momxyz(1,:);
centrstr2(bic).rv = 2;
bic = bic + 1; % separate count for bilaterals
end;
end;
end;
if figureon == 1
figure; row = 2; col = 2; place= 1;
end;
%-------------------------------------------
% PLOT the clusster dipoles:
if length(allbesa) > 1
for sbpt = 1:length(viewnum)
if sbpt < 4
prjimg = 'off';
else
prjimg = 'on';
end;
sbplot(row,col,place)
if strcmp(centroid,'only')
dipplot(centrstr,'image','mri','gui','off','dipolelength',0,'dipolesize',40,'normlen','on','spheres','on','color',centcols,'projlines','off','projimg',prjimg,'coordformat',EEG.dipfit.coordformat);hold on; view(90,0);
if ~isempty(find(centrstr2(1).posxyz)) % only if there were bilaterals
dipplot(centrstr2,'image','mri','gui','off','dipolelength',0,'dipolesize',40,'normlen','on','spheres','on','color',centcols,'projlines','off','projimg',prjimg,'coordformat',EEG.dipfit.coordformat);hold on; view(90,0); camzoom(.8)
else
camzoom(1)
end;
elseif strcmp(centroid,'add')
dipplot(allbesa,'image','mri','gui','off','dipolelength',0,'dipolesize',25,'normlen','on','spheres','on','color',colset,'projlines','off','projimg',prjimg,'coordformat',EEG.dipfit.coordformat);hold on; view(90,0);
dipplot(centrstr,'image','mri','gui','off','dipolelength',0,'dipolesize',40,'normlen','on','spheres','on','color',centcols2,'projlines','off','projimg',prjimg,'coordformat',EEG.dipfit.coordformat);hold on; view(90,0); camzoom(.8)
if ~isempty(find(centrstr2(1).posxyz)) % only if there were bilaterals
dipplot(centrstr2,'image','mri','gui','off','dipolelength',0,'dipolesize',40,'normlen','on','spheres','on','color',centcols2,'projlines','off','projimg',prjimg,'coordformat',EEG.dipfit.coordformat);hold on; view(90,0);camzoom(.8)
else
camzoom(1)
end;
else
dipplot(allbesa,'image','mri','gui','off','dipolelength',0,'dipolesize',25,'normlen','on','spheres','on','color',colset,'projlines','off','projimg',prjimg,'coordformat',EEG.dipfit.coordformat);hold on; view(90,0); camzoom(1.1)
end;
if viewnum(sbpt) == 3
view(0,0)
elseif viewnum(sbpt) == 1
view(0,90)
elseif viewnum(sbpt) == 4
view(63,22);
end;
place = place+1;
end;
if ~isempty(ttl)
if sbpt == 4 % if oblique
ph = text(-75,-75,125,ttl); set(ph,'color','r');
elseif sbpt == 1 % 2d image:
ph = text(-50,110,125,ttl); set(ph,'color','r');
elseif sbpt == 2 % 2d image:
ph = text(-75,-75,125,ttl); set(ph,'color','r');
elseif sbpt == 3 % 2d image:
ph = text(-100,-50,130,ttl); set(ph,'color','r');
end;
end;
end;
|
github
|
lcnhappe/happe-master
|
std_readtopo.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_readtopo.m
| 5,758 |
utf_8
|
200d8ea0bad1829dc48821eb15ac629b
|
% std_readtopo() - returns the scalp map of a specified ICA component, assumed
% to have been saved in a Matlab file, [dataset_name].icatopo,
% in the same directory as the dataset file. If this file does
% not exist, use std_topo() to create it, else a pre-clustering
% function that calls it: pop_preclust() or eeg_preclust().
% Usage:
% >> [grid, y, x ] = std_readtopo(ALLEEG, setindx, component);
% >> [grid, y, x ] = std_readtopo(ALLEEG, setindx, component, transform, mode);
%
% Inputs:
% ALLEEG - vector of EEG datasets (can also be one EEG set).
% must contain the dataset of interest (see 'setindx' below).
% setindx - [integer] an index of an EEG dataset in the ALLEEG
% structure, for which to get the component ERP.
% component - [integer] index of the component for which the scalp map
% grid should be returned.
% transform - ['none'!'laplacian'|'gradient'] transform scalp map to
% laplacian or gradient map. Default is 'none'.
% mode - ['2dmap'|'preclust'] return either a 2-D array for direct
% plotting ('2dmap') or an array formated for preclustering
% with all the NaN values removed (ncomps x points). Default
% is '2dmap' for 1 component and 'preclust' for several.
%
% Outputs:
% grid - square scalp-map color-value grid for the requested ICA component
% in the specified dataset, an interpolated Cartesian grid as output
% by topoplot().
% y - y-axis values for the interpolated grid
% x - x-axis values of the interpolated grid
%
% See also std_topo(), std_preclust()
%
% Authors: Arnaud Delorme, Hilit Serby, SCCN, INC, UCSD, February, 2005
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, October 11, 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
function [X, yi, xi ] = std_readtopo(ALLEEG, abset, comps, option, mode)
X = [];
yi = [];
xi = [];
if nargin < 4
option = 'none';
end;
if nargin < 5
mode = '2Dmap';
end;
filename = correctfile(fullfile( ALLEEG(abset).filepath,[ ALLEEG(abset).filename(1:end-3) 'icatopo']));
tmpfile = which(filename);
if ~isempty(tmpfile), filename = tmpfile; end;
% 061411, 2:51pm
% Modified by Joaquin
% while getfield(dir(filename), 'bytes') < 1000
i = 1;
while getfield(dir(filename), 'bytes') < 5000
topo = load( '-mat', filename);
filename = correctfile(topo.file, ALLEEG(abset).filepath);
tmpfile = which(filename);
if ~isempty(tmpfile), filename = tmpfile; end;
if(i>100)
error('too many attempts to find valid icatopo');
end
i = i+1;
end;
for k = 1:length(comps)
if length(comps) < 3
try
topo = load( '-mat', filename, ...
[ 'comp' int2str(comps(k)) '_grid'], ...
[ 'comp' int2str(comps(k)) '_x'], ...
[ 'comp' int2str(comps(k)) '_y'] );
catch
error( [ 'Cannot read file ''' filename '''' ]);
end;
elseif k == 1
try
topo = load( '-mat', filename);
catch
error([ 'Missing scalp topography file - also necessary for ERP polarity' 10 'Try recomputing scalp topographies for components' ]);
end;
end;
try,
tmp = getfield(topo, [ 'comp' int2str(comps(k)) '_grid' ]);
catch,
error([ 'Empty scalp topography file - also necessary for ERP polarity' 10 'Try recomputing scalp topographies for components' ]);
end;
if strcmpi(option, 'gradient')
[tmpx, tmpy] = gradient(tmp); % Gradient
tmp = tmpx;
tmp(:,:,2) = tmpy;
elseif strcmpi(option, 'laplacian')
tmp = del2(tmp); % Laplacian
end;
if length(comps) > 1 | strcmpi(mode, 'preclust')
tmp = tmp(find(~isnan(tmp))); % remove NaN for more than 1 component
end;
if k == 1
X = zeros([ length(comps) size(tmp) ]) ;
end
X(k,:,:,:) = tmp;
if k == 1
yi = getfield(topo, [ 'comp' int2str(comps(k)) '_y']);
xi = getfield(topo, [ 'comp' int2str(comps(k)) '_x']);
end;
end
X = squeeze(X);
return;
function filename = correctfile(filename, datasetpath)
comp = computer;
if filename(2) == ':' & ~strcmpi(comp(1:2), 'PC')
filename = [filesep filename(4:end) ];
filename(find(filename == '\')) = filesep;
end;
if ~exist(filename)
[tmpp tmpf ext] = fileparts(filename);
if exist([tmpf ext])
filename = [tmpf ext];
else
[tmpp2 tmpp1] = fileparts(tmpp);
if exist(fullfile(tmpp1, [ tmpf ext ]))
filename = fullfile(tmpp1, [ tmpf ext ]);
else
filename = fullfile(datasetpath, [ tmpf ext ]);
if ~exist(filename)
error([ 'Cannot load file ''' [ tmpf ext ] '''' ]);
end;
end;
end;
end;
|
github
|
lcnhappe/happe-master
|
std_erspplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_erspplot.m
| 19,648 |
utf_8
|
cb3030aac38bf825bfc6510c39e5d9cc
|
% std_erspplot() - plot STUDY cluster ERSPs. Displays either mean cluster ERSPs,
% or else all cluster component ERSPs plus the mean cluster
% ERSP in one figure per condition. The ERSPs can be plotted
% only if component ERSPs were computed and saved in the
% EEG datasets in the STUDY. These may either be computed
% during pre-clustering using the gui-based function
% pop_preclust(), or via the equivalent commandline functions
% eeg_createdata() and eeg_preclust(). Called by pop_clustedit().
% Usage:
% >> [STUDY] = std_erspplot(STUDY, ALLEEG, key1, val1, key2, val2);
% >> [STUDY erspdata ersptimes erspfreqs pgroup pcond pinter] = ...
% std_erspplot(STUDY, ALLEEG ...);
%
% Inputs:
% STUDY - STUDY set comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - global vector of EEG structures for the datasets included
% in the STUDY. ALLEEG for a STUDY set is typically created
% using load_ALLEEG().
% either 'channels' or 'cluster' inputs are also mandatory.
%
% Optional inputs for channel plotting:
% 'channels' - [numeric vector] specific channel group to plot. By
% default, the grand mean channel ERSP is plotted (using the
% same format as for the cluster component means described above)
% 'subject' - [numeric vector] In 'changrp' mode (above), index of
% the subject(s) to plot. Else by default, plot all components
% in the cluster.
% 'plotsubjects' - ['on'|'off'] When 'on', plot ERSP of all subjects.
% 'noplot' - ['on'|'off'] When 'on', only return output values. Default
% is 'off'.
%
% Optional inputs:
% 'clusters' - [numeric vector|'all'] indices of clusters to plot.
% If no component indices ('comps' below) are given, the average
% ERSPs of the requested clusters are plotted in the same figure,
% with ERSPs for different conditions (and groups if any) plotted
% in different colors. In 'comps' (below) mode, ERSP for each
% specified cluster are plotted in separate figures (one per
% condition), each overplotting cluster component ERSP plus the
% average cluster ERSP in bold. Note this parameter has no effect
% if the 'comps' option (below) is used. {default: 'all'}
% 'comps' - [numeric vector|'all'] indices of the cluster components to plot.
% Note that 'comps', 'all' is equivalent to 'plotsubjects', 'on'.
%
% Other optional inputs:
% 'plotmode' - ['normal'|'condensed'|'none'] 'normal' -> plot in a new figure;
% 'condensed' -> plot all curves in the current figure in a
% condensed fashion. 'none' toggles off plotting {default: 'normal'}
% 'key','val' - All optional inputs to pop_specparams() are also accepted here
% to plot subset of time, statistics etc. The values used by default
% are the ones set using pop_specparams() and stored in the
% STUDY structure.
% Output:
% STUDY - the input STUDY set structure with the plotted cluster
% mean ERSPs added to allow quick replotting
% erspdata - [cell] ERSP data for each condition, group and subjects.
% size of cell array is [nconds x ngroups]. Size of each element
% is [freqs x times x subjects] for data channels or
% [freqs x times x components] for component clusters. This
% array may be gicen as input directly to the statcond() f
% unction or std_stats() function to compute statistics.
% ersptimes - [array] ERSP time point latencies.
% erspfreqs - [array] ERSP point frequency values.
% pgroup - [array or cell] p-values group statistics. Output of the
% statcond() function.
% pcond - [array or cell] condition statistics. Output of the statcond()
% function.
% pinter - [array or cell] groups x conditions statistics. Output of
% statcond() function.
%
% Example:
% >> [STUDY] = std_erspplot(STUDY,ALLEEG, 'clusters', 'all', ...
% 'mode', 'together');
% % Plot the mean ERSPs of all clusters in STUDY together
% % on the same figure.
%
% Known limitations: when plotting multiple clusters, the output
% contains the last plotted cluster.
%
% See also: pop_clustedit(), pop_preclust(), eeg_createdata(), eeg_preclust(), pop_clustedit()
%
% Authors: Arnaud Delorme, CERCO, August, 2006
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [STUDY, allersp, alltimes, allfreqs, pgroup, pcond, pinter events] = std_erspplot(STUDY, ALLEEG, varargin)
if nargin < 2
help std_erspstatplot;
return;
end;
% find datatype and default options
% ---------------------------------
dtype = 'ersp';
for ind = 1:2:length(varargin)
if strcmpi(varargin{ind}, 'datatype')
dtype = varargin{ind+1};
end;
end;
if strcmpi(dtype, 'erpim')
STUDY = pop_erpimparams(STUDY, varargin{:});
params = STUDY.etc.erpimparams;
else STUDY = pop_erspparams( STUDY, varargin{:});
params = STUDY.etc.erspparams;
end;
% get parameters
% --------------
statstruct.etc = STUDY.etc;
statstruct.design = STUDY.design; %added by behnam
statstruct.currentdesign = STUDY.currentdesign; %added by behnam
statstruct = pop_statparams(statstruct, varargin{:});
stats = statstruct.etc.statistics;
stats.fieldtrip.channelneighbor = struct([]); % asumes one channel or 1 component
% potentially missing fields
% --------------------------
fields = { 'freqrange' [];
'topofreq' [];
'topotrial' [];
'singletrials' 'off'
'trialrange' []
'concatenate' 'off';
'colorlimits' [];
'ersplim' [];
'itclim' [];
'maskdata' 'off';
'subbaseline' 'off' };
for ind=1:size(fields,1)
if ~isfield(params, fields{ind,1}),
params = setfield(params, fields{ind,1}, fields{ind,2});
end;
end;
% decode input parameters
% -----------------------
options = mystruct(varargin);
options = myrmfield( options, myfieldnames(params));
options = myrmfield( options, myfieldnames(stats));
options = myrmfield( options, { 'threshold' 'statistics' } ); % for backward compatibility
[ opt moreparams ] = finputcheck( options, { ...
'design' 'integer' [] STUDY.currentdesign;
'caxis' 'real' [] [];
'statmode' 'string' [] ''; % deprecated
'channels' 'cell' [] {};
'clusters' 'integer' [] [];
'datatype' 'string' { 'itc','ersp','pac' 'erpim' } 'ersp';
'plottf' 'real' [] [];
'mode' 'string' [] ''; % for backward compatibility (now used for statistics)
'comps' {'integer','string'} [] []; % for backward compatibility
'plotsubjects' 'string' { 'on','off' } 'off';
'noplot' 'string' { 'on','off' } 'off';
'plotmode' 'string' { 'normal','condensed','none' } 'normal';
'subject' 'string' [] '' }, ...
'std_erspstatplot', 'ignore');
if isstr(opt), error(opt); end;
if strcmpi(opt.noplot, 'on'), opt.plotmode = 'none'; end;
if isempty(opt.caxis),
if strcmpi(opt.datatype, 'ersp')
opt.caxis = params.ersplim;
elseif strcmpi(opt.datatype, 'itc') && ~isempty(params.itclim)
opt.caxis = [-params.itclim(end) params.itclim(end)];
end;
end;
allconditions = STUDY.design(opt.design).variable(1).value;
allgroups = STUDY.design(opt.design).variable(2).value;
paired = { STUDY.design(opt.design).variable(1).pairing ...
STUDY.design(opt.design).variable(2).pairing };
stats.paired = paired;
% for backward compatibility
% --------------------------
if strcmpi(opt.datatype, 'erpim'),
params.topofreq = params.topotrial;
opt.caxis = params.colorlimits;
valunit = 'trials';
else
valunit = 'Hz';
end;
if isempty(opt.plottf) && ~isempty(params.topofreq) && ~isempty(params.topotime) && ~isnan(params.topofreq(1)) && ~isnan(params.topotime(1))
params.plottf = [ params.topofreq(1) params.topofreq(end) params.topotime(1) params.topotime(end) ];
else params.plottf = opt.plottf;
end;
%if strcmpi(opt.mode, 'comps'), opt.plotsubjects = 'on'; end; %deprecated
if strcmpi(stats.singletrials, 'off') && ((~isempty(opt.subject) || ~isempty(opt.comps)))
if strcmpi(stats.condstats, 'on') || strcmpi(stats.groupstats, 'on')
stats.groupstats = 'off';
stats.condstats = 'off';
disp('No statistics for single subject/component');
end;
end;
if length(opt.comps) == 1
stats.condstats = 'off'; stats.groupstats = 'off';
disp('Statistics cannot be computed for single component');
end;
alpha = fastif(strcmpi(stats.mode, 'eeglab'), stats.eeglab.alpha, stats.fieldtrip.alpha);
mcorrect = fastif(strcmpi(stats.mode, 'eeglab'), stats.eeglab.mcorrect, stats.fieldtrip.mcorrect);
method = fastif(strcmpi(stats.mode, 'eeglab'), stats.eeglab.method, ['Fieldtrip ' stats.fieldtrip.method ]);
plottfopt = { ...
'ersplim', opt.caxis, ...
'threshold', alpha, ...
'maskdata', params.maskdata };
if ~isempty(params.plottf) && length(opt.channels) < 5
warndlg2(strvcat('ERSP/ITC parameters indicate that you wish to plot scalp maps', 'Select at least 5 channels to plot topography'));
return;
end;
% plot single scalp map
% ---------------------
if ~isempty(opt.channels)
[STUDY allersp alltimes allfreqs tmp events unitPower] = std_readersp(STUDY, ALLEEG, 'channels', opt.channels, 'infotype', opt.datatype, 'subject', opt.subject, ...
'singletrials', stats.singletrials, 'subbaseline', params.subbaseline, 'timerange', params.timerange, 'freqrange', params.freqrange, 'design', opt.design, 'concatenate', params.concatenate);
% select specific time and freq
% -----------------------------
if ~isempty(params.plottf)
if length(params.plottf) < 3,
params.plottf(3:4) = params.plottf(2);
params.plottf(2) = params.plottf(1);
end;
[tmp fi1] = min(abs(allfreqs-params.plottf(1)));
[tmp fi2] = min(abs(allfreqs-params.plottf(2)));
[tmp ti1] = min(abs(alltimes-params.plottf(3)));
[tmp ti2] = min(abs(alltimes-params.plottf(4)));
for index = 1:length(allersp(:))
allersp{index} = mean(mean(allersp{index}(fi1:fi2,ti1:ti2,:,:),1),2);
allersp{index} = reshape(allersp{index}, [1 size(allersp{index},3) size(allersp{index},4) ]);
end;
% prepare channel neighbor matrix for Fieldtrip
statstruct = std_prepare_neighbors(statstruct, ALLEEG, 'channels', opt.channels);
stats.fieldtrip.channelneighbor = statstruct.etc.statistics.fieldtrip.channelneighbor;
params.plottf = { params.plottf(1:2) params.plottf(3:4) };
[pcond pgroup pinter] = std_stat(allersp, stats);
if (~isempty(pcond) && length(pcond{1}) == 1) || (~isempty(pgroup) && length(pgroup{1}) == 1), pcond = {}; pgroup = {}; pinter = {}; end; % single subject STUDY
else
[pcond pgroup pinter] = std_stat(allersp, stats);
if (~isempty(pcond ) && (size( pcond{1},1) == 1 || size( pcond{1},2) == 1)) || ...
(~isempty(pgroup) && (size(pgroup{1},1) == 1 || size(pgroup{1},2) == 1)),
pcond = {}; pgroup = {}; pinter = {};
disp('No statistics possible for single subject STUDY');
end; % single subject STUDY
end
% plot specific channel(s)
% ------------------------
if ~strcmpi(opt.plotmode, 'none')
locs = eeg_mergelocs(ALLEEG.chanlocs);
locs = locs(std_chaninds(STUDY, opt.channels));
if ~isempty(params.plottf)
alltitles = std_figtitle('threshold', alpha, 'mcorrect', mcorrect, 'condstat', stats.condstats, 'cond2stat', stats.groupstats, ...
'statistics', method, 'condnames', allconditions, 'cond2names', allgroups, 'chanlabels', { locs.labels }, ...
'subject', opt.subject, 'valsunit', { valunit 'ms' }, 'vals', params.plottf, 'datatype', upper(opt.datatype));
std_chantopo(allersp, 'groupstats', pgroup, 'condstats', pcond, 'interstats', pinter, 'caxis', opt.caxis, ...
'chanlocs', locs, 'threshold', alpha, 'titles', alltitles);
else
if length(opt.channels) > 1 & ~strcmpi(opt.plotmode, 'none'), figure; opt.plotmode = 'condensed'; end;
nc = ceil(sqrt(length(opt.channels)));
nr = ceil(length(opt.channels)/nc);
for index = 1:max(cellfun(@(x)(size(x,3)), allersp(:)))
if length(opt.channels) > 1, try, subplot(nr,nc,index, 'align'); catch, subplot(nr,nc,index); end; end;
tmpersp = cell(size(allersp));
for ind = 1:length(allersp(:))
if ~isempty(allersp{ind})
tmpersp{ind} = squeeze(allersp{ind}(:,:,index,:));
end;
end;
alltitles = std_figtitle('threshold', alpha, 'mcorrect', mcorrect, 'condstat', stats.condstats, 'cond2stat', stats.groupstats, ...
'statistics', method, 'condnames', allconditions, 'cond2names', allgroups, 'chanlabels', { locs(index).labels }, ...
'subject', opt.subject, 'datatype', upper(opt.datatype), 'plotmode', opt.plotmode);
std_plottf(alltimes, allfreqs, tmpersp, 'datatype', opt.datatype, 'titles', alltitles, ...
'groupstats', pgroup, 'condstats', pcond, 'interstats', pinter, 'plotmode', ...
opt.plotmode, 'unitcolor', unitPower, 'chanlocs', ALLEEG(1).chanlocs, 'events', events, plottfopt{:});
end;
end;
end;
else
if length(opt.clusters) > 1 & ~strcmpi(opt.plotmode, 'none'), figure; opt.plotmode = 'condensed'; end;
nc = ceil(sqrt(length(opt.clusters)));
nr = ceil(length(opt.clusters)/nc);
comp_names = {};
if length(opt.clusters) > 1 && ( strcmpi(stats.condstats, 'on') || strcmpi(stats.groupstats, 'on'))
stats.condstats = 'off'; stats.groupstats = 'off';
end;
for index = 1:length(opt.clusters)
[STUDY allersp alltimes allfreqs tmp events unitPower] = std_readersp(STUDY, ALLEEG, 'clusters', opt.clusters(index), 'infotype', opt.datatype, ...
'component', opt.comps, 'singletrials', stats.singletrials, 'subbaseline', params.subbaseline, 'timerange', params.timerange, 'freqrange', params.freqrange, 'design', opt.design, 'concatenate', params.concatenate);
if length(opt.clusters) > 1, try, subplot(nr,nc,index, 'align'); catch, subplot(nr,nc,index); end; end;
% plot specific component
% -----------------------
if ~isempty(opt.comps)
comp_names = { STUDY.cluster(opt.clusters(index)).comps(opt.comps) };
opt.subject = STUDY.datasetinfo(STUDY.cluster(opt.clusters(index)).sets(1,opt.comps)).subject;
end;
% select specific time and freq
% -----------------------------
if ~isempty(params.plottf)
if length(params.plottf) < 3,
params.plottf(3:4) = params.plottf(2);
params.plottf(2) = params.plottf(1);
end;
[tmp fi1] = min(abs(allfreqs-params.plottf(1)));
[tmp fi2] = min(abs(allfreqs-params.plottf(2)));
[tmp ti1] = min(abs(alltimes-params.plottf(3)));
[tmp ti2] = min(abs(alltimes-params.plottf(4)));
for index = 1:length(allersp(:))
allersp{index} = mean(mean(allersp{index}(fi1:fi2,ti1:ti2,:,:),1),2);
allersp{index} = reshape(allersp{index}, [1 size(allersp{index},3) size(allersp{index},4) ]);
end;
end
[pcond pgroup pinter] = std_stat(allersp, stats);
% plot specific component
% -----------------------
if index == length(opt.clusters), opt.legend = 'on'; end;
if ~strcmpi(opt.plotmode, 'none')
alltitles = std_figtitle('threshold', alpha, 'mcorrect', mcorrect, 'condstat', stats.condstats, 'cond2stat', stats.groupstats, ...
'statistics', method, 'condnames', allconditions, 'cond2names', allgroups, 'clustname', STUDY.cluster(opt.clusters(index)).name, 'compnames', comp_names, ...
'subject', opt.subject, 'datatype', upper(opt.datatype), 'plotmode', opt.plotmode);
std_plottf(alltimes, allfreqs, allersp, 'datatype', opt.datatype, ...
'groupstats', pgroup, 'condstats', pcond, 'interstats', pinter, 'plotmode', ...
opt.plotmode, 'titles', alltitles, ...
'events', events, 'unitcolor', unitPower, 'chanlocs', ALLEEG(1).chanlocs, plottfopt{:});
end;
end;
end;
% remove fields and ignore fields who are absent
% ----------------------------------------------
function s = myrmfield(s, f);
for index = 1:length(f)
if isfield(s, f{index})
s = rmfield(s, f{index});
end;
end;
% convert to structure (but take into account cells)
% --------------------------------------------------
function s = mystruct(v);
for index=1:length(v)
if iscell(v{index})
v{index} = { v{index} };
end;
end;
try
s = struct(v{:});
catch, error('Parameter error'); end;
% convert to structure (but take into account cells)
% --------------------------------------------------
function s = myfieldnames(v);
s = fieldnames(v);
if isfield(v, 'eeglab')
s2 = fieldnames(v.eeglab);
s = { s{:} s2{:} };
end;
if isfield(v, 'fieldtrip')
s3 = fieldnames(v.fieldtrip);
for index=1:length(s3)
s3{index} = [ 'fieldtrip' s3{index} ];
end;
s = { s{:} s3{:} };
end;
|
github
|
lcnhappe/happe-master
|
std_readtopoclust.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_readtopoclust.m
| 4,978 |
utf_8
|
d3ea827af1511d8ae06298bd66565857
|
% std_readtopoclust() - Compute and return cluster component scalp maps.
% Automatically inverts the polarity of component scalp maps
% to best match the polarity of the cluster mean scalp map.
% Usage:
% >> [STUDY clsstruct] = std_readtopoclust(STUDY, ALLEEG, clusters);
% Inputs:
% STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - global EEGLAB vector of EEG structures for the dataset(s) included in
% the STUDY.
% clusters - cluster numbers to read.
%
% Outputs:
% STUDY - the input STUDY set structure with the computed mean cluster scalp
% map added (unless cluster scalp map means already exist in the STUDY)
% to allow quick replotting.
% clsstruct - STUDY.cluster structure array for the modified clusters.
%
% See also std_topoplot(), pop_clustedit()
%
% Authors: Arnaud Delorme, SCCN, INC, UCSD, 2007
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, June 07, 2007, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public 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 [STUDY, centroid] = std_readtopoclust(STUDY,ALLEEG, clsind);
if nargin < 3
help readtopoclust;
return;
end;
if isempty(clsind)
for k = 2: length(STUDY.cluster) % don't include the ParentCluster
if ~strncmpi('Notclust',STUDY.cluster(k).name,8)
% don't include 'Notclust' clusters
clsind = [clsind k];
end
end
end
Ncond = length(STUDY.condition);
if Ncond == 0
Ncond = 1;
end
centroid = cell(length(clsind),1);
fprintf('Computing the requested mean cluster scalp maps (only done once)\n');
if ~isfield( STUDY.cluster, 'topo' ), STUDY.cluster(1).topo = []; end;
cond = 1;
for clust = 1:length(clsind) %go over all requested clusters
if isempty( STUDY.cluster(clsind(clust)).topo )
numitems = length(STUDY.cluster(clsind(clust)).comps);
for k = 1:numitems % go through all components
comp = STUDY.cluster(clsind(clust)).comps(k);
abset = STUDY.cluster(clsind(clust)).sets(cond,k);
if ~isnan(comp) & ~isnan(abset)
[grid yi xi] = std_readtopo(ALLEEG, abset, comp);
if ~isfield(centroid{clust}, 'topotmp') || isempty(centroid{clust}.topotmp)
centroid{clust}.topotmp = zeros([ size(grid(1:4:end),2) numitems ]);
end;
centroid{clust}.topotmp(:,k) = grid(1:4:end); % for inversion
centroid{clust}.topo{k} = grid;
centroid{clust}.topox = xi;
centroid{clust}.topoy = yi;
end
end
fprintf('\n');
%update STUDY
tmpinds = find(isnan(centroid{clust}.topotmp(:,1)));
%centroid{clust}.topotmp(tmpinds,:) = [];
%for clust = 1:length(clsind) %go over all requested clusters
for cond = 1
if clsind(1) > 0
ncomp = length(STUDY.cluster(clsind(clust)).comps);
end;
[ tmp pol ] = std_comppol(centroid{clust}.topotmp);
fprintf('%d/%d polarities inverted while reading component scalp maps\n', ...
length(find(pol == -1)), length(pol));
nitems = length(centroid{clust}.topo);
for k = 1:nitems
centroid{clust}.topo{k} = pol(k)*centroid{clust}.topo{k};
if k == 1, allscalp = centroid{clust}.topo{k}/nitems;
else allscalp = centroid{clust}.topo{k}/nitems + allscalp;
end;
end;
STUDY.cluster(clsind(clust)).topox = centroid{clust}.topox;
STUDY.cluster(clsind(clust)).topoy = centroid{clust}.topoy;
STUDY.cluster(clsind(clust)).topoall = centroid{clust}.topo;
STUDY.cluster(clsind(clust)).topo = allscalp;
STUDY.cluster(clsind(clust)).topopol = pol;
end
%end
else
centroid{clust}.topox = STUDY.cluster(clsind(clust)).topox;
centroid{clust}.topoy = STUDY.cluster(clsind(clust)).topoy;
centroid{clust}.topo = STUDY.cluster(clsind(clust)).topoall;
end;
end
fprintf('\n');
|
github
|
lcnhappe/happe-master
|
std_readcustom.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_readcustom.m
| 5,376 |
utf_8
|
ab9dee0bfcae0ccce1ff1c97d5d14089
|
% std_readcustom() - Read custom data structure for file save on disk.
%
% Usage:
% >> data = std_readcustom(STUDY, ALLEEG, fileext, 'key', 'val', ...);
%
% Required inputs:
% STUDY - an EEGLAB STUDY set of loaded EEG structures
% ALLEEG - ALLEEG vector of one or more loaded EEG dataset structures
% fileext - [string] file extension (without '.')
%
% Optional inputs:
% 'design' - [integer] use specific study index design to compute measure.
% Default is to use the default design.
% 'datafield' - [string or cell] extract only specific variables from the data
% files. By default, all fields are loaded. Use '*' to match
% patterns. If more than 1 variable is selected, data is
% placed in a structure named data.
% 'eegfield' - [string] copy data to a field of an EEG structure and return
% EEG structure. Default is to return the data itself.
% 'eegrmdata' - ['on'|'off'] when option above is used, remove data from
% EEG structures before returning them. Default is 'on'.
%
% Outputs:
% data - cell array containing data organized according to the selected
% design.
%
% Example:
% % assuming ERP have been computed for the currently selected design
% data = std_readcustom(STUDY, ALLEEG, 'daterp', 'datafield', 'chan1');
% data = cellfun(@(x)x', siftdata, 'uniformoutput', false); % transpose data
% std_plotcurve([1:size(data{1})], data); % plot data
%
% Authors: Arnaud Delorme, SCCN, INC, UCSD, 2013-
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, 2013, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public 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 [ returndata ] = std_readcustom(STUDY, ALLEEG, fileext, varargin)
if nargin < 2
help std_sift;
return;
end;
[g arguments] = finputcheck(varargin, { 'design' 'integer' [] STUDY.currentdesign;
'datafield' { 'string' 'cell' } [] {};
'eegfield' 'string' [] '';
'eegrmdata' 'string' { 'on' 'off' } 'on' }, 'std_sift', 'mode', 'ignore');
if isstr(g), error(g); end;
if ~iscell(g.datafield), g.datafield = { g.datafield }; end;
% Scan design and save data
% -------------------------
nc = max(length(STUDY.design(g.design).variable(1).value),1);
ng = max(length(STUDY.design(g.design).variable(2).value),1);
for cInd = 1:nc
for gInd = 1:ng
% find the right cell in the design
cellInds = [];
for index = 1:length(STUDY.design(g.design).cell)
condind = std_indvarmatch( STUDY.design(g.design).cell(index).value{1}, STUDY.design(g.design).variable(1).value);
grpind = std_indvarmatch( STUDY.design(g.design).cell(index).value{2}, STUDY.design(g.design).variable(2).value);
if isempty(STUDY.design(g.design).variable(1).value), condind = 1; end;
if isempty(STUDY.design(g.design).variable(2).value), grpind = 1; end;
if cInd == condind && gInd == grpind
cellInds = [ cellInds index ];
end;
end;
desset = STUDY.design(g.design).cell(cellInds);
clear EEGTMP data;
for iDes = 1:length(desset)
% load data on disk
tmpData = load('-mat', [ STUDY.design(g.design).cell(cellInds(iDes)).filebase '.' fileext ], g.datafield{:});
% put data in EEG structure if necessary
if ~isempty(g.eegfield)
EEGTMPTMP = std_getdataset(STUDY, ALLEEG, 'design', g.design, 'cell', cellInds(iDes));
if strcmpi(g.eegrmdata, 'on'), EEGTMPTMP.data = []; EEGTMPTMP.icaact = []; end;
EEGTMPTMP.(g.eegfield) = tmpData;
EEGTMP(iDes) = EEGTMPTMP;
elseif length(g.datafield) == 1
if ~isstr(tmpData.(g.datafield{1})), error('Field content cannot be a string'); end;
data(iDes,:,:,:) = tmpData.(g.datafield{1});
elseif isfield(tmpData, 'data') && isempty(g.datafield)
data(iDes,:,:,:) = tmpData.data;
else
data(iDes) = tmpData;
end;
end;
data = shiftdim(data,1);
if ~isempty(g.eegfield)
returndata{cInd,gInd} = EEGTMP;
else
returndata{cInd,gInd} = data;
end;
end;
end;
|
github
|
lcnhappe/happe-master
|
std_ersp.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_ersp.m
| 20,553 |
utf_8
|
41dd4eed5c09acca4f4c7b9a30289ea8
|
% std_ersp() - Compute ERSP and/or ITC transforms for ICA components
% or data channels of a dataset. Save results into Matlab
% float files.
%
% Function description:
% The function computes the mean ERSP or ITC for the selected
% dataset ICA components or data channels in the requested
% frequency range and time window (the two are dependent).
% Frequencies are equally log spaced. Options specify component
% numbers, desired frequency range, time window length,
% frequency resolution, significance level, and wavelet
% cycles. See >> help newtimef and >> timef details
%
% Two Matlab files are saved (for ERSP and ITC). These contain
% the ERSP|ITC image, plus the transform parameters
% used to compute them. Saves the computed dataset mean images
% in dataset-name files with extensions '.icaersp' and '.icaitc'
% for ICA components or '.datersp', '.datitc' for data channels.
% Usage:
% >> [X times logfreqs ] = std_ersp(EEG, 'key', 'val', ...);
% Inputs:
% EEG - a loaded epoched EEG dataset structure. May be an array
% of such structure containing several datasets.
%
% Other inputs:
% 'trialindices' - [cell array] indices of trials for each dataset.
% Default is EMPTY (no trials). NEEDS TO BE SET.
% 'components' - [numeric vector] components of the EEG structure for which
% activation spectrum will be computed. Note that because
% computation of ERP is so fast, all components spectrum are
% computed and saved. Only selected component
% are returned by the function to Matlab
% {default|[] -> all}
% 'channels' - [cell array] channels of the EEG structure for which
% activation spectrum will be computed. Note that because
% computation of ERP is so fast, all channels spectrum are
% computed and saved. Only selected channels
% are returned by the function to Matlab
% {default|[] -> none}
% 'recompute' - ['on'|'off'] force recomputing ERP file even if it is
% already on disk.
% 'recompute' - ['on'|'off'] force recomputing data file even if it is
% already on disk.
% 'rmcomps' - [integer array] remove artifactual components (this entry
% is ignored when plotting components). This entry contains
% the indices of the components to be removed. Default is none.
% 'interp' - [struct] channel location structure containing electrode
% to interpolate ((this entry is ignored when plotting
% components). Default is no interpolation.
% 'fileout' - [string] name of the file to save on disk. The default
% is the same name (with a different extension) as the
% dataset given as input.
% 'savetrials' - ['on'|'off'] save single-trials ERSP. Requires a lot of disk
% space (dataset space on disk times 10) but allow for refined
% single-trial statistics.
% 'savefile' - ['on'|'off'] save file or simply return measures.
% Default is to save files ('on').
% 'getparams' - ['on'|'off'] return optional parameters for the newtimef
% function (and do not compute anything). This argument is
% obsolete (default is 'off').
%
% ERSP optional inputs:
% 'type' - ['ersp'|'itc'|'ersp&itc'] save ERSP, ITC, or both data
% types to disk {default: 'ersp'}
% 'freqs' - [minHz maxHz] the ERSP/ITC frequency range to compute
% and return. {default: 3 to EEG sampling rate divided by 3}
% 'timelimits' - [minms maxms] time window (in ms) to compute.
% {default: whole input epoch}.
% 'cycles' - [wavecycles (factor)]. If 0 -> DFT (constant window length
% across frequencies).
% If >0 -> the number of cycles in each analysis wavelet.
% If [wavecycles factor], wavelet cycles increase with
% frequency, beginning at wavecyles. (0 < factor < 1)
% factor = 0 -> fixed epoch length (DFT, as in FFT).
% factor = 1 -> no increase (standard wavelets)
% {default: [0]}
% 'padratio' - (power of 2). Multiply the number of output frequencies
% by dividing their frequency spacing through 0-padding.
% Output frequency spacing is (low_freq/padratio).
% 'alpha' - If in (0, 1), compute two-tailed permutation-based
% probability thresholds and use these to mask the output
% ERSP/ITC images {default: NaN}
% 'powbase' - [ncomps,nfreqs] optional input matrix giving baseline power
% spectra (not dB power, see >> help timef).
% For use in repeated calls to timef() using the same baseine
% {default|[] -> none; data windows centered before 0 latency}
%
% Other optional inputs:
% This function will take any of the newtimef() optional inputs (for instance
% to compute log-space frequencies)...
%
% Outputs:
% X - the masked log ERSP/ITC of the requested ICA components/channels
% in the selected frequency and time range. Note that for
% optimization reasons, this parameter is now empty or 0. X
% thus must be read from the datafile saved on disk.
% times - vector of time points for which the ERSPs/ITCs were computed.
% logfreqs - vector of (equally log spaced) frequencies (in Hz) at which the
% log ERSP/ITC was evaluated.
% parameters - parameters given as input to the newtimef function.
%
% Files written or modified:
% [dataset_filename].icaersp <-- saved component ERSPs
% [dataset_filename].icaitc <-- saved component ITCs
% [dataset_filename].icatimef <-- saved component single
% trial decompositions.
% OR for channels
% [dataset_filename].datersp <-- saved channel ERSPs
% [dataset_filename].datitc <-- saved channel ITCs
% [dataset_filename].dattimef <-- saved channel single
% trial decompositions.
% Example:
% % Create mean ERSP and ITC images on disk for all comps from
% % dataset EEG use three-cycle wavelets (at 3 Hz) to more than
% % three-cycle wavelets at 50 Hz. See >> help newtimef
% % Return the (equally log-freq spaced, probability-masked) ERSP.
% >> [Xersp, times, logfreqs] = std_ersp(EEG, ...
% 'type', 'ersp', 'freqs', [3 50], 'cycles', [3 0.5]);
%
% See also: timef(), std_itc(), std_erp(), std_spec(), std_topo(), std_preclust()
%
% Authors: Arnaud Delorme, Hilit Serby, SCCN, INC, UCSD, January, 2005-
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 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
function [X, times, logfreqs, parameters] = std_ersp(EEG, varargin)
if nargin < 1
help std_ersp;
return;
end;
X = [];
options = {};
if length(varargin) > 1
if ~isstr(varargin{1})
if length(varargin) > 0, options = { options{:} 'components' varargin{1} }; end;
if length(varargin) > 1, options = { options{:} 'freqs' varargin{2} }; end;
if length(varargin) > 2, options = { options{:} 'timewindow' varargin{3} }; end;
if length(varargin) > 3, options = { options{:} 'cycles' varargin{4} }; end;
if length(varargin) > 4, options = { options{:} 'padratio' varargin{5} }; end;
if length(varargin) > 5, options = { options{:} 'alpha' varargin{6} }; end;
if length(varargin) > 6, options = { options{:} 'type' varargin{7} }; end;
if length(varargin) > 7, options = { options{:} 'powbase' varargin{8} }; end;
else
options = varargin;
end;
end;
[g timefargs] = finputcheck(options, { ...
'components' 'integer' [] [];
'channels' { 'cell','integer' } { [] [] } {};
'powbase' 'real' [] [];
'trialindices' { 'integer','cell' } [] [];
'savetrials' 'string' { 'on','off' } 'off';
'plot' 'string' { 'on','off' } 'off'; % not documented for debugging purpose
'recompute' 'string' { 'on','off' } 'off';
'getparams' 'string' { 'on','off' } 'off';
'savefile' 'string' { 'on','off' } 'on';
'timewindow' 'real' [] []; % ignored, deprecated
'fileout' 'string' [] '';
'timelimits' 'real' [] [EEG(1).xmin EEG(1).xmax]*1000;
'cycles' 'real' [] [3 .5];
'padratio' 'real' [] 1;
'freqs' 'real' [] [0 EEG(1).srate/2];
'rmcomps' 'cell' [] cell(1,length(EEG));
'interp' 'struct' { } struct([]);
'freqscale' 'string' [] 'log';
'alpha' 'real' [] NaN;
'type' 'string' { 'ersp','itc','both','ersp&itc' } 'both'}, 'std_ersp', 'ignore');
if isstr(g), error(g); end;
if isempty(g.trialindices), g.trialindices = cell(length(EEG)); end;
if ~iscell(g.trialindices), g.trialindices = { g.trialindices }; end;
% checking input parameters
% -------------------------
if isempty(g.components) & isempty(g.channels)
if isempty(EEG(1).icaweights)
error('EEG.icaweights not found');
end
g.components = 1:size(EEG(1).icaweights,1);
disp('Computing ERSP with default values for all components of the dataset');
end
% select ICA components or data channels
% --------------------------------------
if isempty(g.fileout), g.fileout = fullfile(EEG(1).filepath, EEG(1).filename(1:end-4)); end;
if ~isempty(g.components)
g.indices = g.components;
prefix = 'comp';
filenameersp = [ g.fileout '.icaersp' ];
filenameitc = [ g.fileout '.icaitc' ];
filenametrials = [ g.fileout '.icatimef' ];
if ~isempty(g.channels)
error('Cannot compute ERSP/ITC for components and channels at the same time');
end;
elseif ~isempty(g.channels)
if iscell(g.channels)
if ~isempty(g.interp)
g.indices = eeg_chaninds(g.interp, g.channels, 0);
else
g.indices = eeg_chaninds(EEG(1), g.channels, 0);
for ind = 2:length(EEG)
if ~isequal(eeg_chaninds(EEG(ind), g.channels, 0), g.indices)
error([ 'Channel information must be consistant when ' 10 'several datasets are merged for a specific design' ]);
end;
end;
end;
else
g.indices = g.channels;
end;
prefix = 'chan';
filenameersp = [ g.fileout '.datersp' ];
filenameitc = [ g.fileout '.datitc' ];
filenametrials = [ g.fileout '.dattimef' ];
end;
powbaseexist = 1; % used also later
if isempty(g.powbase) | isnan(g.powbase)
powbaseexist = 0;
g.powbase = NaN*ones(length(g.indices),1); % default for timef()
end;
if size(g.powbase,1) ~= length(g.indices)
error('powbase should be of size (ncomps,nfreqs)');
end
% Check if ERSP/ITC information found in datasets and if fits requested parameters
% ----------------------------------------------------------------------------
if exist( filenameersp ) & strcmpi(g.recompute, 'off')
fprintf('Use existing file for ERSP: %s\n', filenameersp);
return;
end;
% tmpersp = load( '-mat', filenameersp, 'parameters'); % AND IT SHOULD BE USED HERE TOO - ARNO
% params = struct(tmpersp.parameters{:});
% if ~isequal(params.cycles, g.cycles) ...
% | (g.padratio ~= params.padratio) ...
% | ( (g.alpha~= params.alpha) & ~( isnan(g.alpha) & isnan(params.alpha)) )
% % if not computed with the requested parameters, recompute ERSP/ITC
% % i.e., continue
% else
% disp('File ERSP/ITC data already present, computed with the same parameters: no need to recompute...');
% return; % no need to compute ERSP/ITC
% end
%end;
% Compute ERSP parameters
% -----------------------
parameters = { 'cycles', g.cycles, 'padratio', g.padratio, ...
'alpha', g.alpha, 'freqscale', g.freqscale, timefargs{:} };
defaultlowfreq = 3;
[time_range] = compute_ersp_times(g.cycles, EEG(1).srate, ...
[EEG(1).xmin EEG(1).xmax]*1000 , defaultlowfreq, g.padratio);
if time_range(1) < time_range(2) && g.freqs(1) == 0
g.freqs(1) = defaultlowfreq; % for backward compatibility
end
parameters = { parameters{:} 'freqs' g.freqs };
if strcmpi(g.plot, 'off')
parameters = { parameters{:} 'plotersp', 'off', 'plotitc', 'off', 'plotphase', 'off' };
end;
if powbaseexist & time_range(1) >= 0
parameters{end+1} = 'baseboot';
parameters{end+1} = 0;
fprintf('No pre-0 baseline spectral estimates: Using whole epoch for timef() "baseboot"\n');
end
% return parameters
% -----------------
if strcmpi(g.getparams, 'on')
X = []; times = []; logfreqs = [];
if strcmpi(g.savetrials, 'on')
parameters = { parameters{:} 'savetrials', g.savetrials };
end;
return;
end;
% No usable ERSP/ITC information available
% ---------------------------------
% tmpdata = [];
% for index = 1:length(EEG)
% if isstr(EEG(index).data)
% TMP = eeg_checkset( EEG(index), 'loaddata' ); % load EEG.data and EEG.icaact
% else
% TMP = EEG;
% end
% if ~isempty(g.components)
% if isempty(TMP.icaact) % make icaact if necessary
% TMP.icaact = (TMP.icaweights*TMP.icasphere)* ...
% reshape(TMP.data(TMP.icachansind,:,:), [ length(TMP.icachansind) size(TMP.data,2)*size(TMP.data,3) ]);
% end;
% tmpdata = reshape(TMP.icaact, [ size(TMP.icaact,1) size(TMP.data,2) size(TMP.data,3) ]);
% tmpdata = tmpdata(g.indices, :,:);
% else
% if isempty(tmpdata)
% tmpdata = TMP.data(g.indices,:,:);
% else
% tmpdata(:,:,end+1:end+size(TMP.data,3)) = TMP.data(g.indices,:,:);
% end;
% end;
% end;
options = {};
if ~isempty(g.rmcomps), options = { options{:} 'rmcomps' g.rmcomps }; end;
if ~isempty(g.interp), options = { options{:} 'interp' g.interp }; end;
if isempty(g.channels)
X = eeg_getdatact(EEG, 'component', g.indices, 'trialindices', g.trialindices );
else X = eeg_getdatact(EEG, 'channel' , g.indices, 'trialindices', g.trialindices, 'rmcomps', g.rmcomps, 'interp', g.interp);
end;
% frame range
% -----------
pointrange1 = round(max((g.timelimits(1)/1000-EEG(1).xmin)*EEG(1).srate, 1));
pointrange2 = round(min(((g.timelimits(2)+1000/EEG(1).srate)/1000-EEG(1).xmin)*EEG(1).srate, EEG(1).pnts));
pointrange = [pointrange1:pointrange2];
% Compute ERSP & ITC
% ------------------
all_ersp = [];
all_trials = [];
all_itc = [];
for k = 1:length(g.indices) % for each (specified) component
if k>size(X,1), break; end; % happens for components
if powbaseexist
tmpparams = parameters;
tmpparams{end+1} = 'powbase';
tmpparams{end+1} = g.powbase(k,:);
else
tmpparams = parameters;
end;
% Run timef() to get ERSP
% ------------------------
timefdata = reshape(X(k,pointrange,:), 1, length(pointrange)*size(X,3));
if strcmpi(g.plot, 'on'), figure; end;
flagEmpty = 0;
if isempty(timefdata)
flagEmpty = 1;
timefdata = rand(1,length(pointrange));
end;
[logersp,logitc,logbase,times,logfreqs,logeboot,logiboot,alltfX] ...
= newtimef( timefdata, length(pointrange), g.timelimits, EEG(1).srate, tmpparams{2:end});
%figure; newtimef( TMP.data(32,:), EEG.pnts, [EEG.xmin EEG.xmax]*1000, EEG.srate, cycles, 'freqs', freqs);
%figure; newtimef( timefdata, length(pointrange), g.timelimits, EEG.srate, cycles, 'freqs', freqs);
if flagEmpty
logersp = [];
logitc = [];
logbase = [];
logeboot = [];
logiboot = [];
alltfX = [];
end;
if strcmpi(g.plot, 'on'), return; end;
all_ersp = setfield( all_ersp, [ prefix int2str(g.indices(k)) '_ersp' ], single(logersp ));
all_ersp = setfield( all_ersp, [ prefix int2str(g.indices(k)) '_erspbase' ], single(logbase ));
all_ersp = setfield( all_ersp, [ prefix int2str(g.indices(k)) '_erspboot' ], single(logeboot));
all_itc = setfield( all_itc , [ prefix int2str(g.indices(k)) '_itc' ], single(logitc ));
all_itc = setfield( all_itc , [ prefix int2str(g.indices(k)) '_itcboot' ], single(logiboot));
if strcmpi(g.savetrials, 'on')
all_trials = setfield( all_trials, [ prefix int2str(g.indices(k)) '_timef' ], single( alltfX ));
end;
end
X = logersp;
% Save ERSP into file
% -------------------
all_ersp.freqs = logfreqs;
all_ersp.times = times;
all_ersp.datatype = 'ERSP';
all_ersp.datafiles = computeFullFileName( { EEG.filepath }, { EEG.filename });
all_ersp.datatrials = g.trialindices;
all_itc.freqs = logfreqs;
all_itc.times = times;
all_itc.parameters = parameters;
all_itc.datatype = 'ITC';
all_itc.datafiles = computeFullFileName( { EEG.filepath }, { EEG.filename });
all_itc.datatrials = g.trialindices;
all_trials.freqs = logfreqs;
all_trials.times = times;
all_trials.parameters = { options{:} parameters{:} };
all_trials.datatype = 'TIMEF';
all_trials.datafiles = computeFullFileName( { EEG.filepath }, { EEG.filename });
all_trials.datatrials = g.trialindices;
if powbaseexist
all_ersp.parameters = { parameters{:}, 'baseline', g.powbase };
else
all_ersp.parameters = parameters;
end;
if ~isempty(g.channels)
if ~isempty(g.interp)
all_ersp.chanlabels = { g.interp(g.indices).labels };
all_itc.chanlabels = { g.interp(g.indices).labels };
all_trials.chanlabels = { g.interp(g.indices).labels };
elseif ~isempty(EEG(1).chanlocs)
tmpchanlocs = EEG(1).chanlocs;
all_ersp.chanlabels = { tmpchanlocs(g.indices).labels };
all_itc.chanlabels = { tmpchanlocs(g.indices).labels };
all_trials.chanlabels = { tmpchanlocs(g.indices).labels };
end;
end;
if strcmpi(g.savefile, 'on')
if strcmpi(g.type, 'both') | strcmpi(g.type, 'ersp') | strcmpi(g.type, 'ersp&itc')
std_savedat( filenameersp, all_ersp);
end;
if strcmpi(g.type, 'both') | strcmpi(g.type, 'itc') | strcmpi(g.type, 'ersp&itc')
std_savedat( filenameitc , all_itc );
end;
if strcmpi(g.savetrials, 'on')
std_savedat( filenametrials , all_trials );
end;
end;
% compute full file names
% -----------------------
function res = computeFullFileName(filePaths, fileNames);
for index = 1:length(fileNames)
res{index} = fullfile(filePaths{index}, fileNames{index});
end;
|
github
|
lcnhappe/happe-master
|
std_setcomps2cell.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_setcomps2cell.m
| 3,998 |
utf_8
|
6f637e1842fe051b8c6772049b76f035
|
% std_setcomps2cell - convert .sets and .comps to cell array. The .sets and
% .comps format is useful for GUI but the cell array
% format is used for plotting and statistics.
%
% Usage:
% [ struct setinds allinds ] = std_setcomps2cell(STUDY, clustind);
% [ struct setinds allinds ] = std_setcomps2cell(STUDY, sets, comps);
% [ struct setinds allinds measurecell] = std_setcomps2cell(STUDY, sets, comps, measure);
%
% Author: Arnaud Delorme, CERCO/CNRS, UCSD, 2009-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ tmpstruct setinds allinds measurecell] = std_setcomps2cell(STUDY, sets, comps, measure, generateerror)
if nargin < 5
generateerror = 0;
end;
if nargin == 4 && length(measure) == 1
generateerror = measure;
measure = [];
end;
if nargin < 3
tmpstruct = STUDY.cluster(sets);
sets = tmpstruct.sets;
comps = tmpstruct.comps; % old format
else
tmpstruct = [];
end;
if nargin < 4 || isempty(measure)
measure = comps;
end;
measure = repmat(measure, [size(sets,1) 1]);
comps = repmat(comps , [size(sets,1) 1]);
oldsets = sets;
sets = reshape(sets , 1, size(sets ,1)*size(sets ,2));
measure = reshape(measure, 1, size(measure,1)*size(measure,2));
comps = reshape(comps , 1, size(comps ,1)*size(comps ,2));
% get indices for all groups and conditions
% -----------------------------------------
setinfo = STUDY.design(STUDY.currentdesign).cell;
allconditions = STUDY.design(STUDY.currentdesign).variable(1).value;
allgroups = STUDY.design(STUDY.currentdesign).variable(2).value;
nc = max(length(allconditions),1);
ng = max(length(allgroups), 1);
allinds = cell( nc, ng );
setinds = cell( nc, ng );
measurecell = cell( nc, ng );
for index = 1:length(setinfo)
% get index of independent variables
% ----------------------------------
condind = std_indvarmatch( setinfo(index).value{1}, allconditions);
grpind = std_indvarmatch( setinfo(index).value{2}, allgroups );
if isempty(allconditions), condind = 1; end;
if isempty(allgroups), grpind = 1; end;
% get the position in sets where the dataset is
% if several datasets check that they all have the same
% ICA and component index
% -----------------------
datind = setinfo(index).dataset;
ind = find(datind(1) == sets);
if ~isempty(ind) && length(datind) > 1
[ind1 ind2] = find(datind(1) == oldsets);
columnica = oldsets(:,ind2(1));
if ~all(ismember(datind, columnica));
disp('Warning: STUDY design combines datasets with different ICA - use ICA only for artifact rejection');
end;
end;
measurecell{ condind, grpind } = [ measurecell{ condind, grpind } measure(ind) ];
allinds{ condind, grpind } = [ allinds{ condind, grpind } comps( ind) ];
setinds{ condind, grpind } = [ setinds{ condind, grpind } repmat(index, [1 length(ind)]) ];
end;
tmpstruct.allinds = allinds;
tmpstruct.setinds = setinds;
if generateerror && isempty(setinds{1})
error( [ 'Some datasets not included in preclustering' 10 ...
'because of partial STUDY design. You need to' 10 ...
'use a STUDY design that includes all datasets.' ]);
end;
|
github
|
lcnhappe/happe-master
|
pop_study.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/pop_study.m
| 32,837 |
utf_8
|
7f2812b93e1ee6f7b6b9cca9dacc7844
|
% pop_study() - create a new STUDY set structure defining a group of related EEG datasets.
% The STUDY set also contains information about each of the datasets: the
% subject code, subject group, experimental condition, and session. This can
% be provided interactively in a pop-up window or be automatically filled
% in by the function. Defaults: Assume a different subject for each
% dataset and only one condition; leave subject group and session fields
% empty. Additional STUDY information about the STUDY name, task and
% miscellaneous notes can also be saved in the STUDY structure.
% Usage:
% >> [ STUDY ALLEEG ] = pop_study([],[], 'gui', 'on'); % create new study interactively
% >> [ STUDY ALLEEG ] = pop_study(STUDY, ALLEEG, 'gui', 'on'); % edit study interactively
% >> [ STUDY ALLEEG ] = pop_study(STUDY, ALLEEG, 'key', 'val', ...); % edit study
%
% Optional Inputs:
% STUDY - existing study structure.
% ALLEEG - vector of EEG dataset structures to be included in the STUDY.
%
% Optional Inputs:
% All "'key', 'val'" inputs of std_editset() may be used.
%
% Outputs:
% STUDY - new STUDY set comprising some or all of the datasets in
% ALLEEG, plus other information about the experiments.
% ALLEEG - an updated ALLEEG structure including the STUDY datasets.
%
% Graphic interface buttons:
% "STUDY set name" - [edit box] name for the STUDY structure {default: ''}
% "STUDY set task name" - [edit box] name for the task performed by the subject {default: ''}
% "STUDY set notes" - [edit box] notes about the experiment, the datasets, the STUDY,
% or anything else to store with the rest of the STUDY information
% {default: ''}
% "subject" - [edit box] subject code associated with the dataset. If no
% subject code is provided, each dataset will assumed to be from
% a different subject {default: 'S1', 'S2', ..., 'Sn'}
% "session" - [edit box] dataset session. If no session information is
% provided, all datasets that belong to one subject are assumed to
% have been recorded within one session {default: []}
% "condition" - [edit box] dataset condition. If no condition code is provided,
% all datasets are assumed to be from the same condition {default:[]}
% "group" - [edit box] the subject group the dataset belongs to. If no group
% is provided, all subjects and datasets are assumed to belong to
% the same group. {default: []}
% "Save this STUDY set to disk file" - [check box] If checked, save the new STUDY set
% structure to disk. If no filename is provided, a window will
% pop up to ask for it.
%
% See also: std_editset, pop_loadstudy(), pop_preclust(), pop_clust()
%
% Authors: Arnaud Delorme, Hilit Serby, Scott Makeig, SCCN, INC, UCSD, July 22, 2005
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, July 22, 2005, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% Coding notes: Useful information on functions and global variables used.
function [STUDY, ALLEEG, com] = pop_study(STUDY, ALLEEG, varargin)
com = '';
if nargin < 1
help pop_study;
return;
end
% type of call (gui, script or internal)
% --------------------------------------
mode = 'internal_command';
if ~isstr(STUDY) %initial settings
mode = 'script';
if nargin > 2
for index = 1:length(varargin)
if isstr(varargin{index})
if strcmpi(varargin{index}, 'gui')
mode = 'gui';
end;
end;
end;
end;
end;
if isempty(STUDY)
newstudy = 1;
STUDY.name = '';
STUDY.task = '';
STUDY.notes = '';
STUDY.filename = '';
STUDY.cluster = [];
STUDY.history = 'STUDY = [];';
else
newstudy = 0;
end;
if strcmpi(mode, 'script') % script mode
[STUDY ALLEEG] = std_editset(STUDY, ALLEEG, varargin{:});
return;
elseif strcmpi(mode, 'gui') % GUI mode
% show warning if necessary
% -------------------------
if isreal(ALLEEG)
if ALLEEG == 0
res = questdlg2( strvcat('Datasets currently loaded will be removed from EEGLAB memory.', ...
'Are you sure you want to continue?'), ...
'Discard loaded EEGLAB datasets?', 'Cancel', 'Yes', 'Yes');
if strcmpi(res, 'cancel'), return; end;
end;
ALLEEG = [];
end;
% set initial datasetinfo
% -----------------------
if isfield(STUDY, 'datasetinfo')
datasetinfo = STUDY.datasetinfo;
different = 0;
for k = 1:length(ALLEEG)
if ~strcmpi(datasetinfo(k).filename, ALLEEG(k).filename), different = 1; break; end;
if ~strcmpi(datasetinfo(k).subject, ALLEEG(k).subject), different = 1; break; end;
if ~strcmpi(datasetinfo(k).condition, ALLEEG(k).condition), different = 1; break; end;
if ~strcmpi(char(datasetinfo(k).group), char(ALLEEG(k).group)), different = 1; break; end;
if datasetinfo(k).session ~= ALLEEG(k).session, different = 1; break; end;
end
if different
info = 'from_STUDY_different_from_ALLEEG';
else
info = 'from_STUDY';
end;
if ~isfield(datasetinfo, 'comps');
datasetinfo(1).comps = [];
end;
else
info = 'from_ALLEEG';
if length(ALLEEG) > 0
datasetinfo(length(ALLEEG)).filename = [];
datasetinfo(length(ALLEEG)).filepath = [];
datasetinfo(length(ALLEEG)).subject = [];
datasetinfo(length(ALLEEG)).session = [];
datasetinfo(length(ALLEEG)).condition = [];
datasetinfo(length(ALLEEG)).group = [];
for k = 1:length(ALLEEG)
datasetinfo(k).filename = ALLEEG(k).filename;
datasetinfo(k).filepath = ALLEEG(k).filepath;
datasetinfo(k).subject = ALLEEG(k).subject;
datasetinfo(k).session = ALLEEG(k).session;
datasetinfo(k).condition = ALLEEG(k).condition;
datasetinfo(k).group = ALLEEG(k).group;
end
if ~isfield(datasetinfo, 'comps');
datasetinfo(1).comps = [];
end;
else
datasetinfo = [];
end;
end;
nextpage = 'pop_study(''nextpage'', gcbf);';
prevpage = 'pop_study(''prevpage'', gcbf);';
delset = 'pop_study(''clear'', gcbf, get(gcbo, ''userdata''));';
loadset = 'pop_study(''load'', gcbf, get(guiind, ''userdata''), get(guiind, ''string'')); clear guiind;';
loadsetedit = [ 'guiind = gcbo;' loadset ];
subcom = 'pop_study(''subject'' , gcbf, get(gcbo, ''userdata''), get(gcbo, ''string''));';
sescom = 'pop_study(''session'' , gcbf, get(gcbo, ''userdata''), get(gcbo, ''string''));';
condcom = 'pop_study(''condition'', gcbf, get(gcbo, ''userdata''), get(gcbo, ''string''));';
grpcom = 'pop_study(''group'' , gcbf, get(gcbo, ''userdata''), get(gcbo, ''string''));';
compcom = 'pop_study(''component'', gcbf, get(gcbo, ''userdata''), get(gcbo, ''string''));';
cb_del = 'pop_study(''delclust'' , gcbf, ''showwarning'');';
cb_dipole = 'pop_study(''dipselect'', gcbf, ''showwarning'');';
browsestudy = [ '[filename, filepath] = uiputfile2(''*.study'', ''Use exsiting STUDY set to import dataset information -- pop_study()''); ' ...
'set(findobj(''parent'', gcbf, ''tag'', ''usestudy_file''), ''string'', [filepath filename]);' ];
saveSTUDY = [ 'set(findobj(''parent'', gcbf, ''userdata'', ''save''), ''enable'', fastif(get(gcbo, ''value'')==1, ''on'', ''off''));' ];
browsesave = [ '[filename, filepath] = uiputfile2(''*.study'', ''Save STUDY with .study extension -- pop_clust()''); ' ...
'if filename ~= 0,' ...
' set(findobj(''parent'', gcbf, ''tag'', ''studyfile''), ''string'', [filepath filename]);' ...
'end;' ...
'clear filename filepath;' ];
texthead = fastif(newstudy, 'Create a new STUDY set', 'Edit STUDY set information - remember to save changes');
guispec = { ...
{'style' 'text' 'string' texthead 'FontWeight' 'Bold' 'HorizontalAlignment' 'center'} ...
{} {'style' 'text' 'string' 'STUDY set name:' } { 'style' 'edit' 'string' STUDY.name 'tag' 'study_name' } ...
{} {'style' 'text' 'string' 'STUDY set task name:' } { 'style' 'edit' 'string' STUDY.task 'tag' 'study_task' } ...
{} {'style' 'text' 'string' 'STUDY set notes:' } { 'style' 'edit' 'string' STUDY.notes 'tag' 'study_notes' } {}...
{} ...
{'style' 'text' 'string' 'dataset filename' 'userdata' 'addt'} {'style' 'text' 'string' 'browse' 'userdata' 'addt'} ...
{'style' 'text' 'string' 'subject' 'userdata' 'addt'} ...
{'style' 'text' 'string' 'session' 'userdata' 'addt'} ...
{'style' 'text' 'string' 'condition' 'userdata' 'addt'} ...
{'style' 'text' 'string' 'group' 'userdata' 'addt'} ...
{'style' 'pushbutton' 'string' 'Select by r.v.' 'userdata' 'addt' 'callback' cb_dipole } ...
{} };
guigeom = { [1] [0.2 1 3.5] [0.2 1 3.5] [0.2 1 3.5] [1] [0.2 1.05 0.35 0.4 0.35 0.6 0.4 0.6 0.3]};
% create edit boxes
% -----------------
for index = 1:10
guigeom = { guigeom{:} [0.2 1 0.2 0.5 0.2 0.5 0.5 0.5 0.3] };
select_com = ['[inputname, inputpath] = uigetfile2(''*.set;*.SET'', ''Choose dataset to add to STUDY -- pop_study()'');'...
'if inputname ~= 0,' ...
' guiind = findobj(''parent'', gcbf, ''tag'', ''set' int2str(index) ''');' ...
' set( guiind,''string'', [inputpath inputname]);' ...
loadset ...
'end; clear inputname inputpath;'];
numstr = int2str(index);
guispec = { guispec{:}, ...
{'style' 'text' 'string' numstr 'tag' [ 'num' int2str(index) ] 'userdata' index }, ...
{'style' 'edit' 'string' '' 'tag' [ 'set' int2str(index) ] 'userdata' index 'callback' loadsetedit}, ...
{'style' 'pushbutton' 'string' '...' 'tag' [ 'brw' int2str(index) ] 'userdata' index 'Callback' select_com}, ...
{'style' 'edit' 'string' '' 'tag' [ 'sub' int2str(index) ] 'userdata' index 'Callback' subcom}, ...
{'style' 'edit' 'string' '' 'tag' [ 'sess' int2str(index) ] 'userdata' index 'Callback' sescom}, ...
{'style' 'edit' 'string' '' 'tag' [ 'cond' int2str(index) ] 'userdata' index 'Callback' condcom}, ...
{'style' 'edit' 'string' '' 'tag' [ 'group' int2str(index) ] 'userdata' index 'Callback' grpcom}, ...
{'style' 'pushbutton' 'string' 'All comp.' 'tag' [ 'comps' int2str(index) ] 'userdata' index 'Callback' compcom}, ...
{'style' 'pushbutton' 'string' 'CLear' 'tag' [ 'clear' int2str(index) ] 'userdata' index 'callback' delset} };
end;
if strcmpi(info, 'from_STUDY_different_from_ALLEEG')
text1 = 'Dataset info (condition, group, ...) differs from study info. [set] = Overwrite dataset info for each dataset on disk.';
value_cb = 0;
else
text1 = 'Update dataset info - datasets stored on disk will be overwritten (unset = Keep study info separate).';
value_cb = 1;
end;
guispec = { guispec{:}, ...
{'style' 'text' 'string' 'Important note: Removed datasets will not be saved before being deleted from EEGLAB memory' }, ...
{}, ...
{'style' 'pushbutton' 'string' '<' 'Callback' prevpage 'userdata' 'addt'}, ...
{'style' 'text' 'string' 'Page 1' 'tag' 'page' 'horizontalalignment' 'center' }, ...
{'style' 'pushbutton' 'string' '>' 'Callback' nextpage 'userdata' 'addt'}, {}, ...
{}, ...
{'style' 'checkbox' 'value' value_cb 'tag' 'copy_to_dataset' }, ...
{'style' 'text' 'string' text1 }, ...
{'style' 'checkbox' 'value' 0 'tag' 'delclust' 'callback' cb_del }, ...
{'style' 'text' 'string' 'Delete cluster information (to allow loading new datasets, set new components for clustering, etc.)' } };
guigeom = { guigeom{:} [1] [1 0.2 0.3 0.2 1] [1] [0.14 3] [0.14 3] };
% if ~isempty(STUDY.filename)
% guispec{end-3} = {'style' 'checkbox' 'string' '' 'value' 0 'tag' 'studyfile' };
% guispec{end-2} = {'style' 'text' 'string' 'Re-save STUDY. Uncheck and use menu File > Save study as to save under a new filename'};
% guispec(end-1) = [];
% guigeom{end-1} = [0.14 3];
% end;
fig_arg{1} = ALLEEG; % datasets
fig_arg{2} = datasetinfo; % datasetinfo
fig_arg{3} = 1; % page
fig_arg{4} = {}; % all commands
fig_arg{5} = (length(STUDY.cluster) > 1); % are cluster present
fig_arg{6} = STUDY; % are cluster present
% generate GUI
% ------------
optiongui = { 'geometry', guigeom, ...
'uilist' , guispec, ...
'helpcom' , 'pophelp(''pop_study'')', ...
'title' , 'Create a new STUDY set -- pop_study()', ...
'userdata', fig_arg, ...
'eval' , 'pop_study(''delclust'', gcf); pop_study(''redraw'', gcf);' };
[result, userdat2, strhalt, outstruct, instruct] = inputgui( 'mode', 'noclose', optiongui{:});
if isempty(result), return; end;
if ~isempty(get(0, 'currentfigure')) currentfig = gcf; end;
while test_wrong_parameters(currentfig)
[result, userdat2, strhalt, outstruct] = inputgui( 'mode', currentfig, optiongui{:});
if isempty(result), return; end;
end;
close(currentfig);
% convert GUI selection to options
% --------------------------------
allcom = simplifycom(userdat2{4});
options = {};
if ~strcmpi(result{1}, STUDY.name ), options = { options{:} 'name' result{1} }; end;
if ~strcmpi(result{2}, STUDY.task ), options = { options{:} 'task' result{2} }; end;
if ~strcmpi(result{3}, STUDY.notes), options = { options{:} 'notes' result{3} }; end;
if ~isempty(allcom), options = { options{:} 'commands' allcom }; end;
% if isnumeric(outstruct(1).studyfile)
% if outstruct(1).studyfile == 1, options = { options{:} 'resave' 'on' }; end;
% else
% if ~isempty(outstruct(1).studyfile), options = { options{:} 'filename' outstruct(1).studyfile }; end;
% end;
if outstruct(1).copy_to_dataset == 1
options = { options{:} 'updatedat' 'on' };
eeglab_options;
if option_storedisk
options = { options{:} 'savedat' 'on' };
end;
else options = { options{:} 'updatedat' 'off' };
end;
if outstruct(1).delclust == 1
options = { options{:} 'rmclust' 'on' };
else
options = { options{:} 'rmclust' 'off' };
end;
% ---
if ~isequal(outstruct, instruct) && (outstruct(1).delclust ~= 1) % notice that isequal is sensitive to fields order. isequaln isn't backward compatible
strfields = fieldnames(outstruct);
for i = 1:length(strfields)
strdiff(i) = strcmp(outstruct.(strfields{i}),instruct.(strfields{i}));
end
% If the information of the STUDY differ, then remove information from clusters
% Ignoring ('STUDY set name','STUDY set task','STUDY set notes')
if any(~strdiff(3:end-2))
options{find(strcmp(options,'rmclust'))+1} = 'on';
end
end
% ---
% check channel labels
% --------------------
ALLEEG = userdat2{1};
if isfield(ALLEEG, 'chanlocs')
allchans = { ALLEEG.chanlocs };
if any(cellfun('isempty', allchans))
txt = strvcat('Some datasets do not have channel labels. Do you wish to generate', ...
'channel labels automatically for all datasets ("1" for channel 1,', ...
'"2" for channel 2, ...). Datasets will be overwritten on disk.', ...
'If you abort, the STUDY will not be created.');
res = questdlg2(txt, 'Dataset format problem', 'Yes', 'No, abort', 'Yes');
if strcmpi(res, 'yes'), options = { options{:} 'addchannellabels' 'on' 'savedat' 'on'};
else return;
end;
end;
end;
% run command and create history
% ------------------------------
com = sprintf( '[STUDY ALLEEG] = std_editset( STUDY, ALLEEG, %s );\n[STUDY ALLEEG] = std_checkset(STUDY, ALLEEG);', vararg2str(options) );
[STUDY ALLEEG] = std_editset(STUDY, ALLEEG, options{:});
else % internal command
com = STUDY;
hdl = ALLEEG; %figure handle
% userdata info
% -------------
userdat = get(hdl, 'userdata');
ALLEEG = userdat{1};
datasetinfo = userdat{2};
page = userdat{3};
allcom = userdat{4};
clusterpresent = userdat{5};
STUDY = userdat{6};
switch com
case 'subject'
guiindex = varargin{1};
realindex = guiindex+(page-1)*10;
datasetinfo(realindex).subject = varargin{2};
if get(findobj(hdl, 'tag', 'copy_to_dataset'), 'value')
ALLEEG(realindex).subject = varargin{2};
end;
allcom = { allcom{:}, { 'index' realindex 'subject' varargin{2} } };
userdat{1} = ALLEEG;
userdat{2} = datasetinfo;
userdat{4} = allcom;
set(hdl, 'userdata', userdat);
case 'session'
guiindex = varargin{1};
realindex = guiindex+(page-1)*10;
datasetinfo(realindex).session = str2num(varargin{2});
if get(findobj(hdl, 'tag', 'copy_to_dataset'), 'value')
ALLEEG(realindex).session = str2num(varargin{2});
end;
allcom = { allcom{:}, { 'index' realindex 'session' str2num(varargin{2}) } };
userdat{1} = ALLEEG;
userdat{2} = datasetinfo;
userdat{4} = allcom;
set(hdl, 'userdata', userdat);
case 'group'
guiindex = varargin{1};
realindex = guiindex+(page-1)*10;
datasetinfo(realindex).group = varargin{2};
if get(findobj(hdl, 'tag', 'copy_to_dataset'), 'value')
ALLEEG(realindex).group = varargin{2};
end;
allcom = { allcom{:}, { 'index' realindex 'group' varargin{2} } };
userdat{1} = ALLEEG;
userdat{2} = datasetinfo;
userdat{4} = allcom;
set(hdl, 'userdata', userdat);
case 'condition'
guiindex = varargin{1};
realindex = guiindex+(page-1)*10;
datasetinfo(realindex).condition = varargin{2};
if get(findobj(hdl, 'tag', 'copy_to_dataset'), 'value')
ALLEEG(realindex).conditon = varargin{2};
end;
allcom = { allcom{:}, { 'index' realindex 'condition' varargin{2} } };
userdat{1} = ALLEEG;
userdat{2} = datasetinfo;
userdat{4} = allcom;
set(hdl, 'userdata', userdat);
case 'dipselect'
STUDY.datasetinfo = datasetinfo;
res = inputdlg2_with_checkbox( { strvcat('Enter maximum residual (topo map - dipole proj.) var. (in %)', ...
'NOTE: This will delete any existing component clusters!') }, ...
'pop_study(): Pre-select components', 1, { '15' },'pop_study' );
if isempty(res), return; end;
if res{2} == 1
STUDY = std_editset(STUDY, ALLEEG, 'commands', { 'inbrain', 'on', 'dipselect' str2num(res{1})/100 'return' });
allcom = { allcom{:}, { 'inbrain', 'on', 'dipselect' str2num(res{1})/100 } };
else
STUDY = std_editset(STUDY, ALLEEG, 'commands', { 'inbrain', 'off','dipselect' str2num(res{1})/100 'return' });
allcom = { allcom{:}, { 'inbrain', 'off', 'dipselect' str2num(res{1})/100 } };
end;
datasetinfo = STUDY.datasetinfo;
userdat{2} = datasetinfo;
userdat{4} = allcom;
set(hdl, 'userdata', userdat);
set(findobj(hdl, 'tag', 'delclust'), 'value', 1);
pop_study('delclust', hdl);
pop_study('redraw', hdl);
case 'component'
guiindex = varargin{1};
realindex = guiindex+(page-1)*10;
for index = 1:size(ALLEEG(realindex).icaweights,1)
complist{index} = [ 'IC ' int2str(index) ];
end;
[tmps,tmpv] = listdlg2('PromptString', 'Select components', 'SelectionMode', ...
'multiple', 'ListString', strvcat(complist), 'initialvalue', datasetinfo(realindex).comps);
if tmpv ~= 0 % no cancel
% find other subjects with the same session
% -----------------------------------------
for index = 1:length(datasetinfo)
if realindex == index | (strcmpi(datasetinfo(index).subject, datasetinfo(realindex).subject) & ...
~isempty(datasetinfo(index).subject) & ...
isequal( datasetinfo(index).session, datasetinfo(realindex).session ) )
datasetinfo(index).comps = tmps;
allcom = { allcom{:}, { 'index' index 'comps' tmps } };
set(findobj('tag', [ 'comps' int2str(index) ]), ...
'string', formatbut(tmps), 'horizontalalignment', 'left');
end;
end;
end;
userdat{2} = datasetinfo;
userdat{4} = allcom;
set(hdl, 'userdata', userdat);
pop_study('redraw', hdl);
case 'clear'
guiindex = varargin{1};
realindex = guiindex+(page-1)*10;
datasetinfo(realindex).filename = '';
datasetinfo(realindex).filepath = '';
datasetinfo(realindex).subject = '';
datasetinfo(realindex).session = [];
datasetinfo(realindex).condition = '';
datasetinfo(realindex).group = '';
datasetinfo(realindex).comps = [];
allcom = { allcom{:}, { 'remove' realindex } };
userdat{1} = ALLEEG;
userdat{2} = datasetinfo;
userdat{4} = allcom;
set(hdl, 'userdata', userdat);
pop_study('redraw', hdl);
case 'nextpage'
userdat{3} = page+1;
set(hdl, 'userdata', userdat);
pop_study('redraw', hdl);
case 'prevpage'
userdat{3} = max(1,page-1);
set(hdl, 'userdata', userdat);
pop_study('redraw', hdl);
case 'load'
guiindex = varargin{1};
filename = varargin{2};
realindex = guiindex+(page-1)*10;
% load dataset
% ------------
TMPEEG = pop_loadset('filename', filename, 'loadmode', 'info');
ALLEEG = eeg_store(ALLEEG, eeg_checkset(TMPEEG), realindex);
% update datasetinfo structure
% ----------------------------
datasetinfo(realindex).filename = ALLEEG(realindex).filename;
datasetinfo(realindex).filepath = ALLEEG(realindex).filepath;
datasetinfo(realindex).subject = ALLEEG(realindex).subject;
datasetinfo(realindex).session = ALLEEG(realindex).session;
datasetinfo(realindex).condition = ALLEEG(realindex).condition;
datasetinfo(realindex).group = ALLEEG(realindex).group;
datasetinfo(realindex).comps = [];
allcom = { allcom{:}, { 'index' realindex 'load' filename } };
userdat{1} = ALLEEG;
userdat{2} = datasetinfo;
userdat{4} = allcom;
set(hdl, 'userdata', userdat);
pop_study('redraw', hdl);
case 'delclust'
if clusterpresent
if ~get(findobj(hdl, 'tag', 'delclust'), 'value')
for k = 1:10
set(findobj('parent', hdl, 'tag',['set' num2str(k)]), 'style', 'text');
set(findobj('parent', hdl, 'tag',['comps' num2str(k)]), 'enable', 'off');
set(findobj('parent', hdl, 'tag',['sess' num2str(k)]), 'enable', 'off');
set(findobj('parent', hdl, 'tag',['brw' num2str(k)]), 'enable', 'off');
end;
else
for k = 1:10
set(findobj('parent', hdl, 'tag',['set' num2str(k)]), 'style', 'edit');
set(findobj('parent', hdl, 'tag',['comps' num2str(k)]), 'enable', 'on');
set(findobj('parent', hdl, 'tag',['sess' num2str(k)]), 'enable', 'on');
set(findobj('parent', hdl, 'tag',['brw' num2str(k)]), 'enable', 'on');
end;
end;
else
set(findobj(hdl, 'tag', 'delclust'), 'value', 0)
if nargin > 2
warndlg2('No cluster present');
end;
end;
case 'redraw'
for k = 1:10
kk = k+(page-1)*10; % real index
if kk > length(datasetinfo)
set(findobj('parent', hdl, 'tag',['num' num2str(k)]), 'string', int2str(kk));
set(findobj('parent', hdl, 'tag',['set' num2str(k)]), 'string', '');
set(findobj('parent', hdl, 'tag',['sub' num2str(k)]), 'string','');
set(findobj('parent', hdl, 'tag',['sess' num2str(k)]), 'string','');
set(findobj('parent', hdl, 'tag',['cond' num2str(k)]), 'string','');
set(findobj('parent', hdl, 'tag',['comps' num2str(k)]), 'string','');
set(findobj('parent', hdl, 'tag',['group' num2str(k)]), 'string','');
else
set(findobj('parent', hdl, 'tag',['num' num2str(k)]), 'string', int2str(kk));
set(findobj('parent', hdl, 'tag',['set' num2str(k)]), 'string', fullfile(char(datasetinfo(kk).filepath), char(datasetinfo(kk).filename)));
set(findobj('parent', hdl, 'tag',['sub' num2str(k)]), 'string', datasetinfo(kk).subject);
set(findobj('parent', hdl, 'tag',['sess' num2str(k)]), 'string', int2str(datasetinfo(kk).session));
set(findobj('parent', hdl, 'tag',['cond' num2str(k)]), 'string', datasetinfo(kk).condition);
set(findobj('parent', hdl, 'tag',['comps' num2str(k)]), 'string', formatbut(datasetinfo(kk).comps));
set(findobj('parent', hdl, 'tag',['group' num2str(k)]), 'string', datasetinfo(kk).group);
end;
end
if page<10
pagestr = [ ' Page ' int2str(page) ];
else pagestr = [ 'Page ' int2str(page) ];
end;
set(findobj('parent', hdl, 'tag','page'), 'string', pagestr );
end
end;
% remove empty elements in allcom
% -------------------------------
function allcom = simplifycom(allcom);
for index = length(allcom)-1:-1:1
if strcmpi(allcom{index}{1}, 'index') & strcmpi(allcom{index+1}{1}, 'index')
if allcom{index}{2} == allcom{index+1}{2} % same dataset index
allcom{index}(end+1:end+length(allcom{index+1})-2) = allcom{index+1}(3:end);
allcom(index+1) = [];
end;
end;
end;
% test for wrong parameters
% -------------------------
function bool = test_wrong_parameters(hdl)
userdat = get(hdl, 'userdata');
datasetinfo = userdat{2};
datastrinfo = userdat{1};
bool = 0;
for index = 1:length(datasetinfo)
if ~isempty(datasetinfo(index).filename)
if isempty(datasetinfo(index).subject) & bool == 0
bool = 1; warndlg2('All datasets must have a subject name or code', 'Error');
end;
end;
end;
nonempty = cellfun('isempty', { datasetinfo.filename });
anysession = any(~cellfun('isempty', { datasetinfo(nonempty).session }));
allsession = all(~cellfun('isempty', { datasetinfo(nonempty).session }));
anycondition = any(~cellfun('isempty', { datasetinfo(nonempty).condition }));
allcondition = all(~cellfun('isempty', { datasetinfo(nonempty).condition }));
anygroup = any(~cellfun('isempty', { datasetinfo(nonempty).group }));
allgroup = all(~cellfun('isempty', { datasetinfo(nonempty).group }));
anydipfit = any(~cellfun('isempty', { datastrinfo(nonempty).dipfit}));
alldipfit = all(~cellfun('isempty', { datastrinfo(nonempty).dipfit}));
if anygroup & ~allgroup
bool = 1; warndlg2('If one dataset has a group label, they must all have one', 'Error');
end;
if anycondition & ~allcondition
bool = 1; warndlg2('If one dataset has a condition label, they must all have one', 'Error');
end;
if anysession & ~allsession
bool = 1; warndlg2('If one dataset has a session index, they must all have one', 'Error');
end;
if anydipfit & ~alldipfit
bool = 1; warndlg2('Dipole''s data across datasets is not uniform');
end;
function strbut = formatbut(complist)
if isempty(complist)
strbut = 'All comp.';
else
if length(complist) > 3, strbut = [ 'Comp.: ' int2str(complist(1:2)) ' ...' ];
else strbut = [ 'Comp.: ' int2str(complist) ];
end;
end;
%---------------------- helper functions -------------------------------------
function [result] = inputdlg2_with_checkbox(Prompt,Title,LineNo,DefAns,funcname);
if nargin < 4
help inputdlg2;
return;
end;
if nargin < 5
funcname = '';
end;
if length(Prompt) ~= length(DefAns)
error('inputdlg2: prompt and default answer cell array must have the smae size');
end;
geometry = {};
listgui = {};
% determine if vertical or horizontal
% -----------------------------------
geomvert = [];
for index = 1:length(Prompt)
geomvert = [geomvert size(Prompt{index},1) 1]; % default is vertical geometry
end;
if all(geomvert == 1) & length(Prompt) > 1
geomvert = []; % horizontal
end;
for index = 1:length(Prompt)
if ~isempty(geomvert) % vertical
geometry = { geometry{:} [ 1] [1 ]};
else
geometry = { geometry{:} [ 1 0.6 ]};
end;
listgui = { listgui{:} { 'Style', 'text', 'string', Prompt{index}} ...
{ 'Style', 'edit', 'string', DefAns{index} } { 'Style', 'checkbox', 'string','Keep only in-brain dipoles (requires Fieldtrip extension).','value',1 } };
end;
geometry = [1 1 1];geomvert = [2 1 1];
result = inputgui(geometry, listgui, ['pophelp(''' funcname ''');'], Title, [], 'normal', geomvert);
|
github
|
lcnhappe/happe-master
|
std_convertdesign.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_convertdesign.m
| 1,356 |
utf_8
|
186f56b44af9306eb22e85b0ccd8896b
|
% std_convertdesign - temporary function converting STUDY design legacy
% format to new format.
function STUDY = std_convertdesign(STUDY,ALLEEG);
for index = 1:length(STUDY.design)
design(index).name = STUDY.design(index).name;
design(index).variable(1).label = STUDY.design(index).indvar1;
design(index).variable(2).label = STUDY.design(index).indvar2;
design(index).variable(1).value = STUDY.design(index).condition;
design(index).variable(2).value = STUDY.design(index).group;
design(index).variable(1).pairing = STUDY.design(index).statvar1;
design(index).variable(2).pairing = STUDY.design(index).statvar2;
design(index).cases.label = 'subject';
design(index).cases.value = STUDY.design(index).subject;
design(index).include = STUDY.design(index).includevarlist;
setinfo = STUDY.design(index).setinfo;
for c = 1:length(setinfo)
design(index).cell(c).dataset = setinfo(c).setindex;
design(index).cell(c).trials = setinfo(c).trialindices;
design(index).cell(c).value = { setinfo(c).condition setinfo(c).group };
design(index).cell(c).case = setinfo(c).subject;
design(index).cell(c).filebase = setinfo(c).filebase;
end;
end;
STUDY.design = design;
STUDY = std_selectdesign(STUDY, ALLEEG, STUDY.currentdesign);
|
github
|
lcnhappe/happe-master
|
std_renameclust.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_renameclust.m
| 4,375 |
utf_8
|
0daee3bdeeb5edb5b7c913f30868434b
|
% std_renameclust() - Commandline function, to rename clusters using specified (mnemonic) names.
% Usage:
% >> [STUDY] = std_renameclust(STUDY, ALLEEG, cluster, new_name);
% Inputs:
% STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - global EEGLAB vector of EEG structures for the dataset(s) included in the STUDY.
% ALLEEG for a STUDY set is typically created using load_ALLEEG().
% cluster - single cluster number.
% new_name - [string] mnemonic cluster name.
%
% Outputs:
% STUDY - the input STUDY set structure modified according to specified new cluster name.
%
% Example:
% >> cluster = 7; new_name = 'artifacts';
% >> [STUDY] = std_renameclust(STUDY,ALLEEG, cluster, new_name);
% Cluster 7 name (i.e.: STUDY.cluster(7).name) will change to 'artifacts 7'.
%
% See also pop_clustedit
%
% Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, June, 2005
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, June 07, 2005, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function STUDY = std_renameclust(STUDY, ALLEEG, cls, new_name)
if ~exist('cls')
error('std_renameclust: you must provide a cluster number to rename.');
end
if isempty(cls)
error('std_renameclust: you must provide a cluster number to rename.');
end
if ~exist('new_name')
error('std_renameclust: you must provide a new cluster name.');
end
if strncmpi('Notclust',STUDY.cluster(cls).name,8) % Don't rename Notclust 'clusters'
warndlg2('std_renameclust: Notclust cannot be renamed');
return;
end
ti = strfind(STUDY.cluster(cls).name, ' ');
clus_id = STUDY.cluster(cls).name(ti(end) + 1:end);
new_name = sprintf('%s %s', new_name, clus_id);
% If the cluster have children cluster update their parent cluster name to the
% new cluster.
if ~isempty(STUDY.cluster(cls).child)
for k = 1:length(STUDY.cluster(cls).child)
child_cls = STUDY.cluster(cls).child{k};
child_id = find(strcmp({STUDY.cluster.name},child_cls));
parent_id = find(strcmp(STUDY.cluster(child_id).parent,STUDY.cluster(cls).name));
STUDY.cluster(child_id).parent{parent_id} = new_name;
end
end
% If the cluster has parent clusters, update the parent clusters with the
% new cluster name of child cluster.
if ~isempty(STUDY.cluster(cls).parent)
for k = 1:length(STUDY.cluster(cls).parent)
parent_cls = STUDY.cluster(cls).parent{k};
parent_id = find(strcmp({STUDY.cluster.name},parent_cls));
STUDY.cluster(parent_id).child{find(strcmp(STUDY.cluster(parent_id).child,STUDY.cluster(cls).name))} = new_name;
end
end
% If the cluster have an Outlier cluster, update the Outlier cluster name.
outlier_clust = std_findoutlierclust(STUDY,cls); %find the outlier cluster for this cluster
if outlier_clust ~= 0
ti = strfind(STUDY.cluster(outlier_clust).name, ' ');
clus_id = STUDY.cluster(outlier_clust).name(ti(end) + 1:end);
% If the outlier has parent clusters, update the parent clusters with the
% new cluster name of child cluster.
for k = 1:length(STUDY.cluster(outlier_clust).parent)
parent_cls = STUDY.cluster(outlier_clust).parent{k};
parent_id = find(strcmp({STUDY.cluster.name},parent_cls));
STUDY.cluster(parent_id).child{find(strcmp(STUDY.cluster(parent_id).child,STUDY.cluster(outlier_clust).name))} = sprintf('Outliers %s %s', new_name, clus_id);
end
STUDY.cluster(outlier_clust).name = sprintf('Outliers %s %s', new_name, clus_id);
end
% Rename cluster
STUDY.cluster(cls).name = new_name;
|
github
|
lcnhappe/happe-master
|
toporeplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/toporeplot.m
| 32,771 |
utf_8
|
a2d2fb39ae360df3cbefbd0d42f15e4a
|
% toporeplot() - re-plot a saved topoplot() output image (a square matrix)
% in a 2-D circular scalp map view (as looking down at the top
% of the head). May also be used to re-plot a mean topoplot()
% map for a number of subjects and/or components without all
% the constitutent maps having the same channel montage.
% Nose is at top of plot. Left = left. See topoplot().
% Usage:
% >> toporeplot(topoimage,'plotrad',val1, 'intrad',val2);
% % Use an existing (or mean) topoplot output image. Give the
% % original 'intrad' and 'plotrad' values used to in topoimage.
% >> toporeplot(topoimage,'plotrad',val1,'xsurface', Xi, 'ysurface',Yi );
% % Use an existing (or mean) topoplot output image. Give the same
% % 'plotrad' value used to create it. Since 'intrad' was not input
% % to topoplot(), give the grid axes Xi and Yi as inputs.
% >> [hfig val ]= toporeplot(topoimage,'plotrad',val1, 'Param1','Value1', ...);
% % Give one of the two options above plus other optional parameters.
% Required inputs:
% topoimage - output image matrix (as) from topoplot(). For maximum flexibility,
% create topoimage using topoplot() options: 'plotrad',1, 'intrad',1
% 'plotrad' - [0.15<=float<=1.0] plotting radius = max channel arc_length to plot.
% If plotrad > 0.5, chans with arc_length > 0.5 (i.e. below ears,eyes)
% are plotted in a circular 'skirt' outside the cartoon head.
% The topoimage depends on 'plotrad', so 'plotrad' is required to
% reproduce the 'topoplot' image.
% Optional inputs:
% 'chanlocs' - name of an EEG electrode position file (see >> topoplot example).
% Else, an EEG.chanlocs structure (see >> help pop_editset).
% 'maplimits' - 'absmax' -> scale map colors to +/- the absolute-max (makes green 0);
% 'maxmin' -> scale colors to the data range (makes green mid-range);
% [lo,hi] -> use user-definined lo/hi limits {default: 'absmax'}
% 'style' - 'map' -> plot colored map only
% 'contour' -> plot contour lines only
% 'both' -> plot both colored map and contour lines {default: 'both'}
% 'fill' -> plot constant color between contour lines
% 'blank' -> plot electrode locations only, requires electrode info.
% 'electrodes' - 'on','off','labels','numbers','ptslabels','ptsnumbers' See Plot detail
% options below. {default: 'on' -> mark electrode locations with points
% unless more than 64 channels, then 'off'}. Requires electrode info.
% 'intrad' - [0.15<=float<=1.0] radius of the interpolation area used in topoplot()
% to get the grid.
% 'headrad' - [0.15<=float<=1.0] drawing radius (arc_length) for the cartoon head.
% NB: Only headrad = 0.5 is anatomically correct! 0 -> don't draw head;
% 'rim' -> show cartoon head at outer edge of the plot {default: 0.5}.
% Requires electrode information.
% 'noplot' - [rad theta] are coordinates of a (possibly missing) channel.
% Do not plot but return interpolated value for channel location.
% Do not plot but return interpolated value for this location.
% 'xsurface' - [Xi- matrix] the Xi grid points for the surface of the plotting
% an output of topoplot().
% 'ysurface' - [Yi- matrix] the Yi grid points for the surface of the plotting,
% an output of topoplot().
% Dipole plotting:
% 'dipole' - [xi yi xe ye ze] plot dipole on the top of the scalp map
% from coordinate (xi,yi) to coordinates (xe,ye,ze) (dipole head
% model has radius 1). If several rows, plot one dipole per row.
% Coordinates returned by dipplot() may be used. Can accept
% an EEG.dipfit.model structure (See >> help dipplot).
% Ex: ,'dipole',EEG.dipfit.model(17) % Plot dipole(s) for comp. 17.
% 'dipnorm' - ['on'|'off'] normalize dipole length {default: 'on'}.
% 'diporient' - [-1|1] invert dipole orientation {default: 1}.
% 'diplen' - [real] scale dipole length {default: 1}.
% 'dipscale' - [real] scale dipole size {default: 1}.
% 'dipsphere' - [real] size of the dipole sphere. {default: 85 mm}.
% 'dipcolor' - [color] dipole color as Matlab code code or [r g b] vector
% {default: 'k' = black}.
% Plot detail options:
% 'electcolor' {'k'}|'emarker' {'.'}|'emarkersize' {14} ...
% |'emarkersize1chan' {40}|'efontsize' {var} - electrode marking details and {defaults}.
% 'shading' - 'flat','interp' {default: 'flat'}
% 'colormap' - (n,3) any size colormap {default: existing colormap}
% 'numcontour' - number of contour lines {default: 6}
% 'ccolor' - color of the contours {default: dark grey}
% 'hcolor'|'ecolor' - colors of the cartoon head and electrodes {default: black}
% 'circgrid' - [int > 100] number of elements (angles) in head and border circles {201}
% 'verbose' - ['on'|'off'] comment on operations on command line {default: 'on'}.
%
% Outputs:
% hfig - plot axes handle
% val - single interpolated value at the specified 'noplot' arg channel
% location ([rad theta]).
%
% Notes: - To change the plot map masking ring to a new figure background color,
% >> set(findobj(gca,'type','patch'),'facecolor',get(gcf,'color'))
% - Topoplots may be rotated from the commandline >> view([deg 90]) {default:[0 90])
%
% Authors: Hilit Serby, Andy Spydell, Colin Humphries, Arnaud Delorme & Scott Makeig
% CNL / Salk Institute, 8/1996-/10/2001; SCCN/INC/UCSD, Nov. 2001- Nov. 2004
%
% See also: topoplot(), timtopo(), envtopo()
% Deprecated but still usable;
% 'interplimits' - ['electrodes'|'head'] 'electrodes'-> interpolate the electrode grid;
% 'head'-> interpolate the whole disk {default: 'head'}.
% toporeplot() - From topoplot.m, Revision 1.216 2004/12/05 12:00:00 hilit
%[hfig grid] = topoplot( EEG.icawinv(:, 5), EEG.chanlocs, 'verbose', 'off','electrodes', 'off' ,'style','both');
%figure; toporeplot(grid, 'style', 'both', 'plotrad',0.5,'intrad',0.5, 'verbose', 'off');
function [handle,chanval] = toporeplot(grid,p1,v1,p2,v2,p3,v3,p4,v4,p5,v5,p6,v6,p7,v7,p8,v8,p9,v9,p10,v10)
%
%%%%%%%%%%%%%%%%%%%%%%%% Set defaults %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
icadefs % read defaults MAXTOPOPLOTCHANS and DEFAULT_ELOC and BACKCOLOR
if ~exist('BACKCOLOR') % if icadefs.m does not define BACKCOLOR
BACKCOLOR = [.93 .96 1]; % EEGLAB standard
end
GRID_SCALE = length(grid);
noplot = 'off';
handle = [];
chanval = NaN;
rmax = 0.5; % head radius - don't change this!
INTERPLIMITS = 'head'; % head, electrodes
MAPLIMITS = 'absmax'; % absmax, maxmin, [values]
CIRCGRID = 201; % number of angles to use in drawing circles
AXHEADFAC = 1.3; % head to axes scaling factor
CONTOURNUM = 6; % number of contour levels to plot
STYLE = 'both'; % default 'style': both,straight,fill,contour,blank
HEADCOLOR = [0 0 0]; % default head color (black)
CCOLOR = [0.2 0.2 0.2]; % default contour color
ECOLOR = [0 0 0]; % default electrode color
ELECTRODES = []; % default 'electrodes': on|off|label - set below
MAXDEFAULTSHOWLOCS = 64;% if more channels than this, don't show electrode locations by default
EMARKER = '.'; % mark electrode locations with small disks
EMARKERSIZE = []; % default depends on number of electrodes, set in code
EMARKERSIZE1CHAN = 40; % default selected channel location marker size
EMARKERCOLOR1CHAN = 'red'; % selected channel location marker color
EFSIZE = get(0,'DefaultAxesFontSize'); % use current default fontsize for electrode labels
HLINEWIDTH = 3; % default linewidth for head, nose, ears
BLANKINGRINGWIDTH = .035;% width of the blanking ring
HEADRINGWIDTH = .007;% width of the cartoon head ring
SHADING = 'flat'; % default 'shading': flat|interp
plotrad = []; % plotting radius ([] = auto, based on outermost channel location)
intrad = []; % default interpolation square is to outermost electrode (<=1.0)
headrad = []; % default plotting radius for cartoon head is 0.5
MINPLOTRAD = 0.15; % can't make a topoplot with smaller plotrad (contours fail)
VERBOSE = 'off';
MASKSURF = 'off';
%%%%%% Dipole defaults %%%%%%%%%%%%
DIPOLE = [];
DIPNORM = 'on';
DIPSPHERE = 85;
DIPLEN = 1;
DIPSCALE = 1;
DIPORIENT = 1;
DIPCOLOR = [0 0 0];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%%%%%%%%%%%%%%%%%%%%%%% Handle arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if nargin< 1
help topoplot;
return
end
nargs = nargin;
if ~mod(nargs,2)
error('Optional inputs must come in Key - Val pairs')
end
if ~isnumeric(grid) | size(grid,1) ~= size(grid,2)
error('topoimage must be a square matrix');
end
for i = 2:2:nargs
Param = eval(['p',int2str((i-2)/2 +1)]);
Value = eval(['v',int2str((i-2)/2 +1)]);
if ~isstr(Param)
error('Flag arguments must be strings')
end
Param = lower(Param);
switch lower(Param)
case 'chanlocs'
loc_file = Value;
case 'colormap'
if size(Value,2)~=3
error('Colormap must be a n x 3 matrix')
end
colormap(Value)
case {'interplimits','headlimits'}
if ~isstr(Value)
error('''interplimits'' value must be a string')
end
Value = lower(Value);
if ~strcmp(Value,'electrodes') & ~strcmp(Value,'head')
error('Incorrect value for interplimits')
end
INTERPLIMITS = Value;
case 'verbose'
VERBOSE = Value;
case 'maplimits'
MAPLIMITS = Value;
case 'masksurf'
MASKSURF = Value;
case 'circgrid'
CIRCGRID = Value;
if isstr(CIRCGRID) | CIRCGRID<100
error('''circgrid'' value must be an int > 100');
end
case 'style'
STYLE = lower(Value);
case 'numcontour'
CONTOURNUM = Value;
case 'electrodes'
ELECTRODES = lower(Value);
if strcmpi(ELECTRODES,'pointlabels') | strcmpi(ELECTRODES,'ptslabels') ...
| strcmpi(ELECTRODES,'labelspts') | strcmpi(ELECTRODES,'ptlabels') ...
| strcmpi(ELECTRODES,'labelpts')
ELECTRODES = 'labelpoint'; % backwards compatability
end
if strcmpi(ELECTRODES,'pointnumbers') | strcmpi(ELECTRODES,'ptsnumbers') ...
| strcmpi(ELECTRODES,'numberspts') | strcmpi(ELECTRODES,'ptnumbers') ...
| strcmpi(ELECTRODES,'numberpts') | strcmpi(ELECTRODES,'ptsnums') ...
| strcmpi(ELECTRODES,'numspts')
ELECTRODES = 'numpoint'; % backwards compatability
end
if strcmpi(ELECTRODES,'nums')
ELECTRODES = 'numbers'; % backwards compatability
end
if strcmpi(ELECTRODES,'pts')
ELECTRODES = 'on'; % backwards compatability
end
if ~strcmpi(ELECTRODES,'labelpoint') ...
& ~strcmpi(ELECTRODES,'numpoint') ...
& ~strcmp(ELECTRODES,'on') ...
& ~strcmp(ELECTRODES,'off') ...
& ~strcmp(ELECTRODES,'labels') ...
& ~strcmpi(ELECTRODES,'numbers')
error('Unknown value for keyword ''electrodes''');
end
case 'dipole'
DIPOLE = Value;
case 'dipsphere'
DIPSPHERE = Value;
case 'dipnorm'
DIPNORM = Value;
case 'diplen'
DIPLEN = Value;
case 'dipscale'
DIPSCALE = Value;
case 'diporient'
DIPORIENT = Value;
case 'dipcolor'
DIPCOLOR = Value;
case 'emarker'
EMARKER = Value;
case 'plotrad'
plotrad = Value;
if isstr(plotrad) | (plotrad < MINPLOTRAD | plotrad > 1)
error('plotrad argument should be a number between 0.15 and 1.0');
end
case 'intrad'
intrad = Value;
if isstr(intrad) | (intrad < MINPLOTRAD | intrad > 1)
error('intrad argument should be a number between 0.15 and 1.0');
end
case 'headrad'
headrad = Value;
if isstr(headrad) & ( strcmpi(headrad,'off') | strcmpi(headrad,'none') )
headrad = 0; % undocumented 'no head' alternatives
end
if isempty(headrad) % [] -> none also
headrad = 0;
end
if ~isstr(headrad)
if ~(headrad==0) & (headrad < MINPLOTRAD | headrad>1)
error('bad value for headrad');
end
elseif ~strcmpi(headrad,'rim')
error('bad value for headrad');
end
case 'xsurface'
Xi = Value;
if ~isnumeric(Xi) | size(Xi,1) ~= size(Xi,2) | size(Xi,1) ~= size(grid,1)
error('xsurface must be a square matrix the size of grid');
end
case 'ysurface'
Yi = Value;
if ~isnumeric(Yi) | size(Yi,1) ~= size(Yi,2) | size(Yi,1) ~= size(grid,1)
error('ysurface must be a square matrix the size of grid');
end
case {'headcolor','hcolor'}
HEADCOLOR = Value;
case {'contourcolor','ccolor'}
CCOLOR = Value;
case {'electcolor','ecolor'}
ECOLOR = Value;
case {'emarkersize','emsize'}
EMARKERSIZE = Value;
case 'emarkersize1chan'
EMARKERSIZE1CHAN= Value;
case {'efontsize','efsize'}
EFSIZE = Value;
case 'shading'
SHADING = lower(Value);
if ~any(strcmp(SHADING,{'flat','interp'}))
error('Invalid shading parameter')
end
case 'noplot'
noplot = Value;
if ~isstr(noplot)
if length(noplot) ~= 2
error('''noplot'' location should be [radius, angle]')
else
chanrad = noplot(1);
chantheta = noplot(2);
noplot = 'on';
end
end
otherwise
error(['Unknown input parameter ''' Param ''' ???'])
end
end
if isempty(plotrad)
error(' ''plotrad'' must be given')
end
if isempty(intrad)
if ~exist('Yi') | ~exist('Xi')
error('either ''intrad'' or the grid axes (Xi and Yi) must be given');
end
end
%
%%%%%%%%%%%%%%%%%%%% Read the channel location information %%%%%%%%%%%%%%%%%%%%%%%%
%
if exist('loc_file')
if isstr(loc_file)
[tmpeloc labels Th Rd indices] = readlocs(loc_file,'filetype','loc');
else % a locs struct
[tmpeloc labels Th Rd indices] = readlocs(loc_file);
% Note: Th and Rd correspond to indices channels-with-coordinates only
end
labels = strvcat(labels);
Th = pi/180*Th; % convert degrees to radians
%
%%%%%%%%%%%%%%%%%% Read plotting radius from chanlocs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isempty(plotrad) & isfield(tmpeloc, 'plotrad'),
plotrad = tmpeloc(1).plotrad;
if isstr(plotrad) % plotrad shouldn't be a string
plotrad = str2num(plotrad) % just checking
end
if plotrad < MINPLOTRAD | plotrad > 1.0
fprintf('Bad value (%g) for plotrad.\n',plotrad);
error(' ');
end
if strcmpi(VERBOSE,'on') & ~isempty(plotrad)
fprintf('Plotting radius plotrad (%g) set from EEG.chanlocs.\n',plotrad);
end
end;
if isempty(plotrad)
plotrad = min(1.0,max(Rd)*1.02); % default: just outside the outermost electrode location
plotrad = max(plotrad,0.5); % default: plot out to the 0.5 head boundary
end % don't plot channels with Rd > 1 (below head)
if isstr(plotrad) | plotrad < MINPLOTRAD | plotrad > 1.0
error('plotrad must be between 0.15 and 1.0');
end
end
if isempty(plotrad) & ~ exist('loc_file')
plotrad = 1; % default: plot out to the 0.5 head bounda
end
% plotrad now set
%
%%%%%%%%%%%%%%%%%%%%%%% Set radius of head cartoon %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isempty(headrad) % never set -> defaults
if plotrad >= rmax
headrad = rmax; % (anatomically correct)
else % if plotrad < rmax
headrad = 0; % don't plot head
if strcmpi(VERBOSE, 'on')
fprintf('topoplot(): not plotting cartoon head since plotrad (%5.4g) < 0.5\n',...
plotrad);
end
end
elseif strcmpi(headrad,'rim') % force plotting at rim of map
headrad = plotrad;
end
% headrad now set
%
%%%%%%%%%%%%%%%%% Issue warning if headrad ~= rmax %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if headrad ~= 0.5 & strcmpi(VERBOSE, 'on')
fprintf(' NB: Plotting map using ''plotrad'' %-4.3g,',plotrad);
fprintf( ' ''headrad'' %-4.3g\n',headrad);
fprintf('Warning: The plotting radius of the cartoon head is NOT anatomically correct (0.5).\n')
end
squeezefac = rmax/plotrad;
%
%%%%%%%%%%%%%%%%%%%%% Find plotting channels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if exist('tmpeloc')
pltchans = find(Rd <= plotrad); % plot channels inside plotting circle
[x,y] = pol2cart(Th,Rd); % transform electrode locations from polar to cartesian coordinates
%
%%%%%%%%%%%%%%%%%%%%% Eliminate channels not plotted %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
allx = x;
ally = y;
Th = Th(pltchans); % eliminate channels outside the plotting area
Rd = Rd(pltchans);
x = x(pltchans);
y = y(pltchans);
labels= labels(pltchans,:);
%
%%%%%%%%%%%%%%% Squeeze channel locations to <= rmax %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
Rd = Rd*squeezefac; % squeeze electrode arc_lengths towards the vertex
% to plot all inside the head cartoon
x = x*squeezefac;
y = y*squeezefac;
allx = allx*squeezefac;
ally = ally*squeezefac;
end
% Note: Now outermost channel will be plotted just inside rmax
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Make the plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~strcmpi(STYLE,'blank') % if draw interpolated scalp map
%
%%%%%%%%%%%%%%%%%%%%%%% Interpolate scalp map data %%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(intrad) % intrad specified
xi = linspace(-intrad*squeezefac,intrad*squeezefac,GRID_SCALE); % use the specified intrad value
yi = linspace(-intrad*squeezefac,intrad*squeezefac,GRID_SCALE);
[Xi,Yi] = meshgrid(yi',xi);
elseif ~exist('Xi') | ~exist('Yi')
error('toporeplot require either intrad input or both xsurface and ysurface')
end
Zi = grid;
mask = (sqrt(Xi.^2 + Yi.^2) <= rmax); % mask outside the plotting circle
ii = find(mask == 0);
Zi(ii) = NaN;
%
%%%%%%%%%% Return interpolated value at designated scalp location %%%%%%%%%%
%
if exist('chanrad') % optional first argument to 'noplot'
chantheta = (chantheta/360)*2*pi;
chancoords = round(ceil(GRID_SCALE/2)+GRID_SCALE/2*2*chanrad*[cos(-chantheta),...
-sin(-chantheta)]);
if chancoords(1)<1 ...
| chancoords(1) > GRID_SCALE ...
| chancoords(2)<1 ...
| chancoords(2)>GRID_SCALE
error('designated ''noplot'' channel out of bounds')
else
chanval = Zi(chancoords(1),chancoords(2));
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%% Return interpolated image only %%%%%%%%%%%%%%%%%
%
if strcmpi(noplot, 'on')
if strcmpi(VERBOSE,'on')
fprintf('topoplot(): no plot requested.\n')
end
return;
end
%
%%%%%%%%%%%%%%%%%%%%%%% Calculate colormap limits %%%%%%%%%%%%%%%%%%%%%%%%%%
%
m = size(colormap,1);
if isstr(MAPLIMITS)
if strcmp(MAPLIMITS,'absmax')
amin = -max(max(abs(Zi)));
amax = max(max(abs(Zi)));
elseif strcmp(MAPLIMITS,'maxmin') | strcmp(MAPLIMITS,'minmax')
amin = min(min(Zi));
amax = max(max(Zi));
else
error('unknown ''maplimits'' value.');
end
else
amin = MAPLIMITS(1);
amax = MAPLIMITS(2);
end
delta = Xi(1,2)-Xi(1,1); % length of grid entry
%
%%%%%%%%%%%%%%%%%%%%%%%%%% Scale the axes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
cla % clear current axis
hold on
h = gca; % uses current axes
% instead of default larger AXHEADFAC
if squeezefac<0.92 & plotrad-headrad > 0.05 % (size of head in axes)
AXHEADFAC = 1.05; % do not leave room for external ears if head cartoon
% shrunk enough by the 'skirt' option
end
set(gca,'Xlim',[-rmax rmax]*AXHEADFAC,'Ylim',[-rmax rmax]*AXHEADFAC);
% specify size of head axes in gca
unsh = (GRID_SCALE+1)/GRID_SCALE; % un-shrink the effects of 'interp' SHADING
switch STYLE
%
%%%%%%%%%%%%%%%%%%%%%%%% Plot map contours only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
case 'contour' % plot surface contours only
[cls chs] = contour(Xi,Yi,Zi,CONTOURNUM,'k');
%
%%%%%%%%%%%%%%%%%%%%%%%% Else plot map and contours %%%%%%%%%%%%%%%%%%%%%%%%%
%
case 'both' % plot interpolated surface and surface contours
if strcmp(SHADING,'interp')
tmph = surface(Xi*unsh,Yi*unsh,zeros(size(Zi)),Zi,...
'EdgeColor','none','FaceColor',SHADING);
else % SHADING == 'flat'
tmph = surface(Xi-delta/2,Yi-delta/2,zeros(size(Zi)),Zi,...
'EdgeColor','none','FaceColor',SHADING);
end
if strcmpi(MASKSURF, 'on')
set(tmph, 'visible', 'off');
handle = tmph;
end;
[cls chs] = contour(Xi,Yi,Zi,CONTOURNUM,'k');
for h=chs, set(h,'color',CCOLOR); end
%
%%%%%%%%%%%%%%%%%%%%%%%% Else plot map only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
case {'straight', 'map'} % 'straight' was former arg
if strcmp(SHADING,'interp') % 'interp' mode is shifted somehow... but how?
tmph = surface(Xi*unsh,Yi*unsh,zeros(size(Zi)),Zi,'EdgeColor','none',...
'FaceColor',SHADING);
else
tmph = surface(Xi-delta/2,Yi-delta/2,zeros(size(Zi)),Zi,'EdgeColor','none',...
'FaceColor',SHADING);
end
if strcmpi(MASKSURF, 'on')
set(tmph, 'visible', 'off');
handle = tmph;
end;
%
%%%%%%%%%%%%%%%%%% Else fill contours with uniform colors %%%%%%%%%%%%%%%%%%
%
case 'fill'
[cls chs] = contourf(Xi,Yi,Zi,CONTOURNUM,'k');
otherwise
error('Invalid style')
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Set color axis %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
caxis([amin amax]) % set coloraxis
%
%%%%%%%%%%%%%%%%%%%%%%% Draw blank head %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
else % if STYLE 'blank'
if strcmpi(noplot, 'on')
if strcmpi(VERBOSE,'on')
fprintf('topoplot(): no plot requested.\n')
end
return;
end
cla
hold on
set(gca,'Xlim',[-rmax rmax]*AXHEADFAC,'Ylim',[-rmax rmax]*AXHEADFAC)
if ~exist('tmpeloc')
error('No electrode location information found');
end
if strcmp(ELECTRODES,'labelpoint') | strcmp(ELECTRODES,'numpoint')
text(-0.6,-0.6, [ int2str(length(Rd)) ' of ' int2str(length(tmpeloc)) ' electrode locations shown']);
text(-0.6,-0.7, [ 'Click on electrodes to toggle name/number']);
tl = title('Channel locations');
set(tl, 'fontweight', 'bold');
end
end
if exist('handle') ~= 1
handle = gca;
end;
%
%%%%%%%%%%%%%%%%%%% Plot filled ring to mask jagged grid boundary %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
hwidth = HEADRINGWIDTH; % width of head ring
hin = squeezefac*headrad*(1- hwidth/2); % inner head ring radius
if strcmp(SHADING,'interp')
rwidth = BLANKINGRINGWIDTH*1.3; % width of blanking outer ring
else
rwidth = BLANKINGRINGWIDTH; % width of blanking outer ring
end
rin = rmax*(1-rwidth/2); % inner ring radius
if hin>rin
rin = hin; % dont blank inside the head ring
end
circ = linspace(0,2*pi,CIRCGRID);
rx = sin(circ);
ry = cos(circ);
ringx = [[rx(:)' rx(1) ]*(rin+rwidth) [rx(:)' rx(1)]*rin];
ringy = [[ry(:)' ry(1) ]*(rin+rwidth) [ry(:)' ry(1)]*rin];
if ~strcmpi(STYLE,'blank')
ringh= patch(ringx,ringy,0.01*ones(size(ringx)),BACKCOLOR,'edgecolor','none'); hold on
end
%
%%%%%%%%%%%%%%%%%%%%%%%%% Plot cartoon head, ears, nose %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if headrad > 0 % if cartoon head to be plotted
%
%%%%%%%%%%%%%%%%%%% Plot head outline %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
headx = [[rx(:)' rx(1) ]*(hin+hwidth) [rx(:)' rx(1)]*hin];
heady = [[ry(:)' ry(1) ]*(hin+hwidth) [ry(:)' ry(1)]*hin];
ringh= patch(headx,heady,ones(size(headx)),HEADCOLOR,'edgecolor',HEADCOLOR); hold on
%
%%%%%%%%%%%%%%%%%%% Plot ears and nose %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
base = rmax-.0046;
basex = 0.18*rmax; % nose width
tip = 1.15*rmax;
tiphw = .04*rmax; % nose tip half width
tipr = .01*rmax; % nose tip rounding
q = .04; % ear lengthening
EarX = [.497-.005 .510 .518 .5299 .5419 .54 .547 .532 .510 .489-.005]; % rmax = 0.5
EarY = [q+.0555 q+.0775 q+.0783 q+.0746 q+.0555 -.0055 -.0932 -.1313 -.1384 -.1199];
sf = headrad/plotrad; % squeeze the model ears and nose
% by this factor
plot3([basex;tiphw;0;-tiphw;-basex]*sf,[base;tip-tipr;tip;tip-tipr;base]*sf,...
2*ones(size([basex;tiphw;0;-tiphw;-basex])),...
'Color',HEADCOLOR,'LineWidth',HLINEWIDTH); % plot nose
plot3(EarX*sf,EarY*sf,2*ones(size(EarX)),'color',HEADCOLOR,'LineWidth',HLINEWIDTH) % plot left ear
plot3(-EarX*sf,EarY*sf,2*ones(size(EarY)),'color',HEADCOLOR,'LineWidth',HLINEWIDTH) % plot right ear
end
%
% %%%%%%%%%%%%%%%%%%% Show electrode information %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
plotax = gca;
axis square % make plotax square
axis off
pos = get(gca,'position');
xlm = get(gca,'xlim');
ylm = get(gca,'ylim');
axis square % make textax square
pos = get(gca,'position');
set(plotax,'position',pos);
xlm = get(gca,'xlim');
set(plotax,'xlim',xlm);
ylm = get(gca,'ylim');
set(plotax,'ylim',ylm); % copy position and axis limits again
%%%%%%%%%%%%%%%%%%%%%%%%%only if electrode info is available %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if exist('tmpeloc')
if isempty(EMARKERSIZE)
EMARKERSIZE = 10;
if length(y)>=32
EMARKERSIZE = 8;
elseif length(y)>=48
EMARKERSIZE = 6;
elseif length(y)>=64
EMARKERSIZE = 5;
elseif length(y)>=80
EMARKERSIZE = 4;
elseif length(y)>=100
EMARKERSIZE = 3;
elseif length(y)>=128
EMARKERSIZE = 2;
elseif length(y)>=160
EMARKERSIZE = 1;
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Mark electrode locations only %%%%%%%%%%%%%%%%%%%%%%%%%%
%
ELECTRODE_HEIGHT = 2.1; % z value for plotting electrode information (above the surf)
if strcmp(ELECTRODES,'on') % plot electrodes as spots
hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE);
%
%%%%%%%%%%%%%%%%%%%%%%%% Print electrode labels only %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'labels') % print electrode names (labels)
for i = 1:size(labels,1)
text(double(y(i)),double(x(i)),...
ELECTRODE_HEIGHT,labels(i,:),'HorizontalAlignment','center',...
'VerticalAlignment','middle','Color',ECOLOR,...
'FontSize',EFSIZE)
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Mark electrode locations plus labels %%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'labelpoint')
hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE);
for i = 1:size(labels,1)
hh(i) = text(double(y(i)+0.01),double(x(i)),...
ELECTRODE_HEIGHT,labels(i,:),'HorizontalAlignment','left',...
'VerticalAlignment','middle','Color', ECOLOR,'userdata', num2str(pltchans(i)), ...
'FontSize',EFSIZE, 'buttondownfcn', ...
['tmpstr = get(gco, ''userdata'');'...
'set(gco, ''userdata'', get(gco, ''string''));' ...
'set(gco, ''string'', tmpstr); clear tmpstr;'] );
end
%
%%%%%%%%%%%%%%%%%%%%%%% Mark electrode locations plus numbers %%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'numpoint')
hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE);
for i = 1:size(labels,1)
hh(i) = text(double(y(i)+0.01),double(x(i)),...
ELECTRODE_HEIGHT,num2str(pltchans(i)),'HorizontalAlignment','left',...
'VerticalAlignment','middle','Color', ECOLOR,'userdata', labels(i,:) , ...
'FontSize',EFSIZE, 'buttondownfcn', ...
['tmpstr = get(gco, ''userdata'');'...
'set(gco, ''userdata'', get(gco, ''string''));' ...
'set(gco, ''string'', tmpstr); clear tmpstr;'] );
end
%
%%%%%%%%%%%%%%%%%%%%%% Print electrode numbers only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'numbers')
for i = 1:size(labels,1)
text(double(y(i)),double(x(i)),...
ELECTRODE_HEIGHT,int2str(pltchans(i)),'HorizontalAlignment','center',...
'VerticalAlignment','middle','Color',ECOLOR,...
'FontSize',EFSIZE)
end
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%% Plot dipole(s) on the scalp map %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(DIPOLE)
hold on;
tmp = DIPOLE;
if isstruct(DIPOLE)
if ~isfield(tmp,'posxyz')
error('dipole structure is not an EEG.dipfit.model')
end
DIPOLE = []; % Note: invert x and y from dipplot usage
DIPOLE(:,1) = -tmp.posxyz(:,2)/DIPSPHERE; % -y -> x
DIPOLE(:,2) = tmp.posxyz(:,1)/DIPSPHERE; % x -> y
DIPOLE(:,3) = -tmp.momxyz(:,2);
DIPOLE(:,4) = tmp.momxyz(:,1);
else
DIPOLE(:,1) = -tmp(:,2); % same for vector input
DIPOLE(:,2) = tmp(:,1);
DIPOLE(:,3) = -tmp(:,4);
DIPOLE(:,4) = tmp(:,3);
end;
for index = 1:size(DIPOLE,1)
if ~any(DIPOLE(index,:))
DIPOLE(index,:) = [];
end
end;
DIPOLE(:,1:4) = DIPOLE(:,1:4)*rmax*(rmax/plotrad); % scale radius from 1 -> rmax (0.5)
DIPOLE(:,3:end) = (DIPOLE(:,3:end))*rmax/100000*(rmax/plotrad);
if strcmpi(DIPNORM, 'on')
for index = 1:size(DIPOLE,1)
DIPOLE(index,3:4) = DIPOLE(index,3:4)/norm(DIPOLE(index,3:end))*0.2;
end;
end;
DIPOLE(:, 3:4) = DIPORIENT*DIPOLE(:, 3:4)*DIPLEN;
PLOT_DIPOLE=1;
if sum(DIPOLE(1,3:4).^2) <= 0.00001
if strcmpi(VERBOSE,'on')
fprintf('Note: dipole is length 0 - not plotted\n')
end
PLOT_DIPOLE = 0;
end
if 0 % sum(DIPOLE(1,1:2).^2) > plotrad
if strcmpi(VERBOSE,'on')
fprintf('Note: dipole is outside plotting area - not plotted\n')
end
PLOT_DIPOLE = 0;
end
if PLOT_DIPOLE
for index = 1:size(DIPOLE,1)
hh = plot( DIPOLE(index, 1), DIPOLE(index, 2), '.');
set(hh, 'color', DIPCOLOR, 'markersize', DIPSCALE*30);
hh = line( [DIPOLE(index, 1) DIPOLE(index, 1)+DIPOLE(index, 3)]', ...
[DIPOLE(index, 2) DIPOLE(index, 2)+DIPOLE(index, 4)]');
set(hh, 'color', DIPCOLOR, 'linewidth', DIPSCALE*30/7);
end;
end;
end;
%
%%%%%%%%%%%%% Set EEGLAB background color to match head border %%%%%%%%%%%%%%%%%%%%%%%%
%
try,
icadefs;
set(gcf, 'color', BACKCOLOR);
catch,
end;
hold off
axis off
return
|
github
|
lcnhappe/happe-master
|
std_selectdataset.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_selectdataset.m
| 3,936 |
utf_8
|
6c9ce8182feee7b5ddbbe5eb2f9d979b
|
% std_selectdataset() - select datasets and trials for a given independent
% variable with a given set of values.
%
% Usage:
% >> [STUDY] = std_selectdataset(STUDY, ALLEEG, indvar, indvarvals);
%
% Inputs:
% STUDY - EELAB STUDY structure
% ALLEEG - EELAB dataset structure
% indvar - [string] independent variable name
% indvarvals - [cell] cell array of string for selected values for the
% verboseflag - ['verbose'|'silent'] print info flag
%
% choosen independent variable
% Output:
% datind - [integer array] indices of selected dataset
% dattrialsind - [cell] trial indices for each dataset (not only the
% datasets selected above).
%
% Author: Arnaud Delorme, CERCO, 2010-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [datind, dattrialselect] = std_selectdataset(STUDY, ALLEEG, indvar, indvarvals, verboseFlag);
if nargin < 3
help std_selectdataset;
return;
end;
if nargin < 5
verboseFlag = 'verbose';
end;
% check for multiple condition selection
if ~iscell(indvarvals),
pos = strfind(' - ', indvarvals);
if ~isempty(pos)
tmpindvar = indvarvals;
indvarvals = { indvarvals(1:pos(1)-1) };
pos(end+1) = length(tmpindvar)+1;
for ind = 1:length(pos)-1
indvarvals{end+1} = tmpindvar(pos(ind)+3:pos(ind+1)-1);
end;
else
indvarvals = { indvarvals };
end;
end;
% default dattrialselect = all trials
% -----------------------------------
if isfield(STUDY.datasetinfo, 'trialinfo')
dattrialselect = cellfun(@(x)([1:length(x)]), { STUDY.datasetinfo.trialinfo }, 'uniformoutput', false);
else for i=1:length(ALLEEG), dattrialselect{i} = [1:ALLEEG(i).trials]; end;
end;
if isempty(indvar)
datind = [1:length(STUDY.datasetinfo)];
elseif isfield(STUDY.datasetinfo, indvar) && ~isempty(getfield(STUDY.datasetinfo(1), indvar))
% regular selection of dataset in datasetinfo
% -------------------------------------------
if strcmpi(verboseFlag, 'verbose'), fprintf(' Selecting datasets with field ''%s'' equal to %s\n', indvar, vararg2str(indvarvals)); end;
eval( [ 'myfieldvals = { STUDY.datasetinfo.' indvar '};' ] );
datind = [];
for dat = 1:length(indvarvals)
datind = union_bc(datind, std_indvarmatch(indvarvals{dat}, myfieldvals));
end;
else
% selection of trials within datasets
% -----------------------------------
if strcmpi(verboseFlag, 'verbose'), fprintf(' Selecting trials with field ''%s'' equal to %s\n', indvar, vararg2str(indvarvals)); end;
dattrials = cellfun(@(x)(eval(['{ x.' indvar '}'])), { STUDY.datasetinfo.trialinfo }, 'uniformoutput', false);
dattrials = cellfun(@(x)(eval(['{ x.' indvar '}'])), { STUDY.datasetinfo.trialinfo }, 'uniformoutput', false); % do not remove duplicate line (or Matlab crashes)
dattrialselect = cell(1,length(STUDY.datasetinfo));
for dat = 1:length(indvarvals)
for tmpi = 1:length(dattrials)
dattrialselect{tmpi} = union_bc(dattrialselect{tmpi}, std_indvarmatch(indvarvals{dat}, dattrials{tmpi}));
end;
end;
datind = find(~cellfun(@isempty, dattrialselect));
end;
|
github
|
lcnhappe/happe-master
|
pop_clust.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/pop_clust.m
| 17,403 |
utf_8
|
0c86a64fc1bc38103e1e67f0c4b204a9
|
% pop_clust() - select and run a clustering algorithm on components from an EEGLAB STUDY
% structure of EEG datasets. Clustering data should be prepared beforehand using
% pop_preclust() and/or std_preclust(). The number of clusters must be
% specified in advance. If called in gui mode, the pop_clustedit() window
% appears when the clustering is complete to display clustering results
% and allow the user to review and edit them.
% Usage:
% >> STUDY = pop_clust( STUDY, ALLEEG); % pop up a graphic interface
% >> STUDY = pop_clust( STUDY, ALLEEG, 'key1', 'val1', ...); % no pop-up
% Inputs:
% STUDY - an EEGLAB STUDY set containing some or all of the EEG sets in ALLEEG.
% ALLEEG - a vector of loaded EEG dataset structures of all sets in the STUDY set.
%
% Optional Inputs:
% 'algorithm' - ['kmeans'|'kmeanscluster'|'Neural Network'] algorithm to be used for
% clustering. The 'kmeans' options requires the statistical toolbox. The
% 'kmeanscluster' option is included in EEGLAB. The 'Neural Network'
% option requires the Matlab Neural Net toolbox {default: 'kmeans'}
% 'clus_num' - [integer] the number of desired clusters (must be > 1) {default: 20}
% 'outliers' - [integer] identify outliers further than the given number of standard
% deviations from any cluster centroid. Inf --> identify no such outliers.
% {default: Inf from the command line; 3 for 'kmeans' from the pop window}
% 'save' - ['on' | 'off'] save the updated STUDY to disk {default: 'off'}
% 'filename' - [string] if save option is 'on', save the STUDY under this file name
% {default: current STUDY filename}
% 'filepath' - [string] if save option is 'on', will save the STUDY in this directory
% {default: current STUDY filepath}
% Outputs:
% STUDY - as input, but modified adding the clustering results.
%
% Graphic interface buttons:
% "Clustering algorithm" - [list box] display/choose among the available clustering
% algorithms.
% "Number of clusters to compute" - [edit box] the number of desired clusters (>2)
% "Identify outliers" - [check box] check to detect outliers.
% "Save STUDY" - [check box] check to save the updated STUDY after clustering
% is performed. If no file entered, overwrites the current STUDY.
%
% See also pop_clustedit(), pop_preclust(), std_preclust(), pop_clust()
%
% Authors: Hilit Serby & Arnaud Delorme, SCCN, INC, UCSD, October 11, 2004
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, October 11, 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
% Coding notes: Useful information on functions and global variables used.
function [STUDY, ALLEEG, command] = pop_clust(STUDY, ALLEEG, varargin)
command = '';
if nargin < 2
help pop_clust;
return;
end;
if isempty(STUDY.etc)
error('No pre-clustering information, pre-cluster first!');
end;
if ~isfield(STUDY.etc, 'preclust')
error('No pre-clustering information, pre-cluster first!');
end;
if isempty(STUDY.etc.preclust)
error('No pre-clustering information, pre-cluster first!');
end;
% check that the path to the stat toolbox comes first (conflict
% with Fieldtrip)
kmeansPath = fileparts(which('kmeans'));
if ~isempty(kmeansPath)
rmpath(kmeansPath);
addpath(kmeansPath);
end;
if isempty(varargin) %GUI call
% remove clusters below clustering level (done also after GUI)
% --------------------------------------
rmindex = [];
clustlevel = STUDY.etc.preclust.clustlevel;
nameclustbase = STUDY.cluster(clustlevel).name;
if clustlevel == 1
rmindex = [2:length(STUDY.cluster)];
else
for index = 2:length(STUDY.cluster)
if strcmpi(STUDY.cluster(index).parent{1}, nameclustbase) & ~strncmpi('Notclust',STUDY.cluster(index).name,8)
rmindex = [ rmindex index ];
end;
end;
end;
if length(STUDY.cluster) > 2 & ~isempty(rmindex)
resp = questdlg2('Clustering again will delete the last clustering results', 'Warning', 'Cancel', 'Ok', 'Ok');
if strcmpi(resp, 'cancel'), return; end;
end;
alg_options = {'Kmeans (stat. toolbox)' 'Neural Network (stat. toolbox)' 'Kmeanscluster (no toolbox)' }; %'Hierarchical tree'
set_outliers = ['set(findobj(''parent'', gcbf, ''tag'', ''outliers_std''), ''enable'', fastif(get(gcbo, ''value''), ''on'', ''off''));'...
'set(findobj(''parent'', gcbf, ''tag'', ''std_txt''), ''enable'', fastif(get(gcbo, ''value''), ''on'', ''off''));'];
algoptions = [ 'set(findobj(''parent'', gcbf, ''userdata'', ''kmeans''), ''enable'', fastif(get(gcbo, ''value'')==1, ''on'', ''off''));' ];
saveSTUDY = [ 'set(findobj(''parent'', gcbf, ''userdata'', ''save''), ''enable'', fastif(get(gcbo, ''value'')==1, ''on'', ''off''));' ];
browsesave = [ '[filename, filepath] = uiputfile2(''*.study'', ''Save STUDY with .study extension -- pop_clust()''); ' ...
'set(findobj(''parent'', gcbf, ''tag'', ''studyfile''), ''string'', [filepath filename]);' ];
if ~exist('kmeans'), valalg = 3; else valalg = 1; end;
strclust = '';
if STUDY.etc.preclust.clustlevel > length(STUDY.cluster)
STUDY.etc.preclust.clustlevel = 1;
end;
if STUDY.etc.preclust.clustlevel == 1
strclust = [ 'Performing clustering on cluster ''' STUDY.cluster(STUDY.etc.preclust.clustlevel).name '''' ];
else
strclust = [ 'Performing sub-clustering on cluster ''' STUDY.cluster(STUDY.etc.preclust.clustlevel).name '''' ];
end;
numClust = ceil(mean(cellfun(@length, { STUDY.datasetinfo.comps })));
if numClust > 2, numClustStr = num2str(numClust);
else numClustStr = '10';
end;
clust_param = inputgui( { [1] [1] [1 1] [1 0.5 0.5 ] [ 1 0.5 0.5 ] }, ...
{ {'style' 'text' 'string' strclust 'fontweight' 'bold' } {} ...
{'style' 'text' 'string' 'Clustering algorithm:' } ...
{'style' 'popupmenu' 'string' alg_options 'value' valalg 'tag' 'clust_algorithm' 'Callback' algoptions } ...
{'style' 'text' 'string' 'Number of clusters to compute:' } ...
{'style' 'edit' 'string' numClustStr 'tag' 'clust_num' } {} ...
{'style' 'checkbox' 'string' 'Separate outliers (enter std.)' 'tag' 'outliers_on' 'value' 0 'Callback' set_outliers 'userdata' 'kmeans' 'enable' 'on' } ...
{'style' 'edit' 'string' '3' 'tag' 'outliers_std' 'enable' 'off' } {} },...
'pophelp(''pop_clust'')', 'Set clustering algorithm -- pop_clust()' , [] , 'normal', [ 1 .5 1 1 1]);
if ~isempty(clust_param)
% removing previous cluster information
% -------------------------------------
if ~isempty(rmindex)
fprintf('Removing child clusters of ''%s''...\n', nameclustbase);
STUDY.cluster(rmindex) = [];
STUDY.cluster(clustlevel).child = [];
if clustlevel == 1 & length(STUDY.cluster) > 1
STUDY.cluster(1).child = { STUDY.cluster(2).name }; % "Notclust" cluster
end;
end;
clus_alg = alg_options{clust_param{1}};
clus_num = str2num(clust_param{2});
outliers_on = clust_param{3};
stdval = clust_param{4};
outliers = [];
try
clustdata = STUDY.etc.preclust.preclustdata;
catch
error('Error accesing preclustering data. Perform pre-clustering.');
end;
command = '[STUDY] = pop_clust(STUDY, ALLEEG,';
if ~isempty(findstr(clus_alg, 'Kmeanscluster')), clus_alg = 'kmeanscluster'; end;
if ~isempty(findstr(clus_alg, 'Kmeans ')), clus_alg = 'kmeans'; end;
if ~isempty(findstr(clus_alg, 'Neural ')), clus_alg = 'neural network'; end;
disp('Clustering ...');
switch clus_alg
case { 'kmeans' 'kmeanscluster' }
command = sprintf('%s %s%s%s %d %s', command, '''algorithm'',''', clus_alg, ''',''clus_num'', ', clus_num, ',');
if outliers_on
command = sprintf('%s %s %s %s', command, '''outliers'', ', stdval, ',');
[IDX,C,sumd,D,outliers] = robust_kmeans(clustdata,clus_num,str2num(stdval),5,lower(clus_alg));
[STUDY] = std_createclust(STUDY, ALLEEG, 'clusterind', IDX, 'algorithm', {'robust_kmeans', clus_num});
else
if strcmpi(clus_alg, 'kmeans')
[IDX,C,sumd,D] = kmeans(clustdata,clus_num,'replicates',10,'emptyaction','drop');
else
%[IDX,C,sumd,D] = kmeanscluster(clustdata,clus_num);
[C,IDX,sumd] =kmeans_st(real(clustdata),clus_num,150);
end;
[STUDY] = std_createclust(STUDY, ALLEEG, 'clusterind', IDX, 'algorithm', {'Kmeans', clus_num});
end
case 'Hierarchical tree'
%[IDX,C] = hierarchical_tree(clustdata,clus_num);
%[STUDY] = std_createclust(STUDY,IDX,C, {'Neural Network', clus_num});
case 'neural network'
[IDX,C] = neural_net(clustdata,clus_num);
[STUDY] = std_createclust(STUDY, ALLEEG, 'clusterind', IDX, 'algorithm', {'Neural Network', clus_num});
command = sprintf('%s %s %d %s', command, '''algorithm'', ''Neural Network'',''clus_num'', ', clus_num, ',');
end
disp('Done.');
% If save updated STUDY to disk
save_on = 0; % old option to save STUDY
if save_on
command = sprintf('%s %s', command, '''save'', ''on'',');
if ~isempty(clust_param{6})
[filepath filename ext] = fileparts(clust_param{6});
command = sprintf('%s%s%s%s%s%s', command, '''filename'', ''', [filename ext], ', ''filepath'', ''', filepath, ''');' );
STUDY = pop_savestudy(STUDY, ALLEEG, 'filename', [filename ext], 'filepath', filepath);
else
command(end:end+1) = ');';
if (~isempty(STUDY.filename)) & (~isempty(STUDY.filepath))
STUDY = pop_savestudy(STUDY, ALLEEG, 'filename', STUDY.filename, 'filepath', STUDY.filepath);
else
STUDY = pop_savestudy(STUDY, ALLEEG);
end
end
else
command(end:end+1) = ');';
end
% Call menu to plot clusters (use EEGLAB menu which include
% std_envtopo) - this crashed the hisotry
%eval( [ get(findobj(findobj('tag', 'EEGLAB'), 'Label', 'Edit/plot clusters'), 'callback') ] );
[STUDY LASTCOM] = pop_clustedit(STUDY, ALLEEG);
command = [ command LASTCOM ];
end
else %command line call
% remove clusters below clustering level (done also after GUI)
% --------------------------------------
rmindex = [];
clustlevel = STUDY.etc.preclust.clustlevel;
nameclustbase = STUDY.cluster(clustlevel).name;
if clustlevel == 1
rmindex = [2:length(STUDY.cluster)];
else
for index = 2:length(STUDY.cluster)
if strcmpi(STUDY.cluster(index).parent{1}, nameclustbase) & ~strncmpi('Notclust',STUDY.cluster(index).name,8)
rmindex = [ rmindex index ];
end;
end;
end;
if ~isempty(rmindex)
fprintf('Removing child clusters of ''%s''...\n', nameclustbase);
STUDY.cluster(rmindex) = [];
STUDY.cluster(clustlevel).child = [];
if clustlevel == 1 & length(STUDY.cluster) > 1
STUDY.cluster(1).child = { STUDY.cluster(2).name }; % "Notclust" cluster
end;
end;
%default values
algorithm = 'kmeans';
clus_num = 20;
save = 'off';
filename = STUDY.filename;
filepath = STUDY.filepath;
outliers = Inf; % default std is Inf - no outliers
if mod(length(varargin),2) ~= 0
error('pop_clust(): input variables must be specified in pairs: keywords, values');
end
for k = 1:2:length(varargin)
switch(varargin{k})
case 'algorithm'
algorithm = varargin{k+1};
case 'clus_num'
clus_num = varargin{k+1};
case 'outliers'
outliers = varargin{k+1};
case 'save'
save = varargin{k+1};
case 'filename'
filename = varargin{k+1};
case 'filepath'
filepath = varargin{k+1};
end
end
if clus_num < 2
clus_num = 2;
end
clustdata = STUDY.etc.preclust.preclustdata;
switch lower(algorithm)
case { 'kmeans' 'kmeanscluster' }
if outliers == Inf
if strcmpi(algorithm, 'kmeans')
[IDX,C,sumd,D] = kmeans(clustdata,clus_num,'replicates',10,'emptyaction','drop');
else
[IDX,C,sumd,D] = kmeanscluster(clustdata,clus_num);
end;
[STUDY] = std_createclust(STUDY, ALLEEG, 'clusterind', IDX, 'algorithm', {'Kmeans', clus_num});
else
[IDX,C,sumd,D,outliers] = robust_kmeans(clustdata,clus_num,outliers,5, algorithm);
[STUDY] = std_createclust(STUDY, ALLEEG, 'clusterind', IDX, 'algorithm', {'robust_kmeans', clus_num});
end
case 'neural network'
[IDX,C] = neural_net(clustdata,clus_num);
[STUDY] = std_createclust(STUDY, ALLEEG, 'clusterind', IDX, 'algorithm', {'Neural Network', clus_num});
otherwise
disp('pop_clust: unknown algorithm return');
return
end
% If save updated STUDY to disk
if strcmpi(save,'on')
if (~isempty(STUDY.filename)) & (~isempty(STUDY.filepath))
STUDY = pop_savestudy(STUDY, 'filename', STUDY.filename, 'filepath', STUDY.filepath);
else
STUDY = pop_savestudy(STUDY);
end
end
end
STUDY.saved = 'no';
% IDX - index of cluster for each component. Ex: 63 components and 2
% clusters: IDX will be a 61x1 vector of 1 and 2 (and 0=outlisers)
% C - centroid for clusters. If 2 clusters, size will be 2 x
% width of the preclustering matrix
function [STUDY] = std_createclust2_old(STUDY,IDX,C, algorithm)
% Find the next available cluster index
% -------------------------------------
clusters = [];
cls = size(C,1); % number of cluster = number of row of centroid matrix
nc = 0; % index of last cluster
for k = 1:length(STUDY.cluster)
ti = strfind(STUDY.cluster(k).name, ' ');
tmp = STUDY.cluster(k).name(ti(end) + 1:end);
nc = max(nc,str2num(tmp));
% check if there is a cluster of Notclust components
if strcmp(STUDY.cluster(k).parent,STUDY.cluster(STUDY.etc.preclust.clustlevel).name)
STUDY.cluster(k).preclust.preclustparams = STUDY.etc.preclust.preclustparams;
clusters = [clusters k];
end
end
len = length(STUDY.cluster);
if ~isempty(find(IDX==0)) %outliers exist
firstind = 0;
nc = nc + 1;
len = len + 1;
else
firstind = 1;
end
% create all clusters
% -------------------
for k = firstind:cls
% cluster name
% ------------
if k == 0
STUDY.cluster(len).name = [ 'outlier ' num2str(k+nc)];
else STUDY.cluster(k+len).name = [ 'Cls ' num2str(k+nc)];
end
% find indices
% ------------
tmp = find(IDX==k); % IDX contains the cluster index for each component
STUDY.cluster(k+len).sets = STUDY.cluster(STUDY.etc.preclust.clustlevel).sets(:,tmp);
STUDY.cluster(k+len).comps = STUDY.cluster(STUDY.etc.preclust.clustlevel).comps(tmp);
STUDY.cluster(k+len).algorithm = algorithm;
STUDY.cluster(k+len).parent{end+1} = STUDY.cluster(STUDY.etc.preclust.clustlevel).name;
STUDY.cluster(k+len).child = [];
STUDY.cluster(k+len).preclust.preclustdata = STUDY.etc.preclust.preclustdata(tmp,:);
STUDY.cluster(k+len).preclust.preclustparams = STUDY.etc.preclust.preclustparams;
STUDY.cluster(k+len).preclust.preclustcomps = STUDY.etc.preclust.preclustcomps;
%update parents clusters with cluster child indices
% -------------------------------------------------
STUDY.cluster(STUDY.etc.preclust.clustlevel).child{end+1} = STUDY.cluster(k+nc).name;
end
clusters = [ clusters firstind+len:cls+len];%the new created clusters indices.
|
github
|
lcnhappe/happe-master
|
pop_erspparams.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/pop_erspparams.m
| 8,995 |
utf_8
|
670aed78afeb3667c344e153cf8879fc
|
% pop_erspparams() - Set plotting and statistics parameters for
% computing and plotting STUDY mean (and optionally
% single-trial) ERSP and ITC measures and measure
% statistics. Settings are stored within the STUDY
% structure (STUDY.etc.erspparams) which is used
% whenever plotting is performed by the function
% std_erspplot().
% Usage:
% >> STUDY = pop_erspparams(STUDY, 'key', 'val', ...);
%
% Inputs:
% STUDY - EEGLAB STUDY set
%
% ERSP/ITC image plotting options:
% 'timerange' - [min max] ERSP/ITC plotting latency range in ms.
% {default: the whole output latency range}.
% 'freqrange' - [min max] ERSP/ITC plotting frequency range in ms.
% {default: the whole output frequency range}
% 'ersplim' - [mindB maxdB] ERSP plotting limits in dB
% {default: from [ERSPmin,ERSPmax]}
% 'itclim' - [minitc maxitc] ITC plotting limits (range: [0,1])
% {default: from [0,ITC data max]}
% 'topotime' - [float] plot scalp map at specific time. A time range may
% also be provide and the ERSP will be averaged over the
% given time range. Requires 'topofreq' below to be set.
% 'topofreq' - [float] plot scalp map at specific frequencies. As above
% a frequency range may also be provided.
% 'subbaseline' - ['on'|'off'] subtract the same baseline across conditions
% for ERSP (not ITC). When datasets with different conditions
% are recorded simultaneously, a common baseline spectrum
% should be used. Note that this also affects the
% results of statistics {default: 'on'}
% 'maskdata' - ['on'|'off'] when threshold is not NaN, and 'groupstats'
% or 'condstats' (above) are 'off', masks the data
% for significance.
%
% See also: std_erspplot(), std_itcplot()
%
% Authors: Arnaud Delorme, CERCO, CNRS, 2006-
% Copyright (C) Arnaud Delorme, 2006
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ STUDY, com ] = pop_erspparams(STUDY, varargin);
STUDY = default_params(STUDY);
TMPSTUDY = STUDY;
com = '';
if isempty(varargin)
subbaseline = fastif(strcmpi(STUDY.etc.erspparams.subbaseline,'on'), 1, 0);
vis = fastif(isnan(STUDY.etc.erspparams.topotime), 'off', 'on');
uilist = { ...
{'style' 'text' 'string' 'ERSP/ITC plotting options' 'fontweight' 'bold' 'tag', 'ersp' } ...
{'style' 'text' 'string' 'Time range in ms [Low High]'} ...
{'style' 'edit' 'string' num2str(STUDY.etc.erspparams.timerange) 'tag' 'timerange' } ...
{'style' 'text' 'string' 'Plot scalp map at time [ms]' 'visible' vis} ...
{'style' 'edit' 'string' num2str(STUDY.etc.erspparams.topotime) 'tag' 'topotime' 'visible' vis } ...
{'style' 'text' 'string' 'Freq. range in Hz [Low High]'} ...
{'style' 'edit' 'string' num2str(STUDY.etc.erspparams.freqrange) 'tag' 'freqrange' } ...
{'style' 'text' 'string' 'Plot scalp map at freq. [Hz]' 'visible' vis} ...
{'style' 'edit' 'string' num2str(STUDY.etc.erspparams.topofreq) 'tag' 'topofreq' 'visible' vis } ...
{'style' 'text' 'string' 'Power limits in dB [Low High]'} ...
{'style' 'edit' 'string' num2str(STUDY.etc.erspparams.ersplim) 'tag' 'ersplim' } ...
{'style' 'text' 'string' 'ITC limit (0-1) [High]'} ...
{'style' 'edit' 'string' num2str(STUDY.etc.erspparams.itclim) 'tag' 'itclim' } ...
{} {'style' 'checkbox' 'string' 'Compute common ERSP baseline (assumes additive baseline)' 'value' subbaseline 'tag' 'subbaseline' } };
evalstr = 'set(findobj(gcf, ''tag'', ''ersp''), ''fontsize'', 12);';
cbline = [0.07 1.1];
otherline = [ 0.6 .4 0.6 .4];
geometry = { 1 otherline otherline otherline cbline };
enablecond = fastif(length(STUDY.design(STUDY.currentdesign).variable(1).value)>1, 'on', 'off');
enablegroup = fastif(length(STUDY.design(STUDY.currentdesign).variable(2).value)>1, 'on', 'off');
[out_param userdat tmp res] = inputgui( 'geometry' , geometry, 'uilist', uilist, 'skipline', 'off', ...
'title', 'Set ERSP/ITC plotting parameters -- pop_erspparams()', 'eval', evalstr);
if isempty(res), return; end;
% decode input
% ------------
if res.subbaseline, res.subbaseline = 'on'; else res.subbaseline = 'off'; end;
res.topotime = str2num( res.topotime );
res.topofreq = str2num( res.topofreq );
res.timerange = str2num( res.timerange );
res.freqrange = str2num( res.freqrange );
res.ersplim = str2num( res.ersplim );
res.itclim = str2num( res.itclim );
% build command call
% ------------------
options = {};
if ~strcmpi( res.subbaseline , STUDY.etc.erspparams.subbaseline ), options = { options{:} 'subbaseline' res.subbaseline }; end;
if ~isequal(res.topotime , STUDY.etc.erspparams.topotime), options = { options{:} 'topotime' res.topotime }; end;
if ~isequal(res.topofreq , STUDY.etc.erspparams.topofreq), options = { options{:} 'topofreq' res.topofreq }; end;
if ~isequal(res.ersplim , STUDY.etc.erspparams.ersplim), options = { options{:} 'ersplim' res.ersplim }; end;
if ~isequal(res.itclim , STUDY.etc.erspparams.itclim), options = { options{:} 'itclim' res.itclim }; end;
if ~isequal(res.timerange, STUDY.etc.erspparams.timerange), options = { options{:} 'timerange' res.timerange }; end;
if ~isequal(res.freqrange, STUDY.etc.erspparams.freqrange), options = { options{:} 'freqrange' res.freqrange }; end;
if ~isempty(options)
STUDY = pop_erspparams(STUDY, options{:});
com = sprintf('STUDY = pop_erspparams(STUDY, %s);', vararg2str( options ));
end;
else
if strcmpi(varargin{1}, 'default')
STUDY = default_params(STUDY);
else
for index = 1:2:length(varargin)
if ~isempty(strmatch(varargin{index}, fieldnames(STUDY.etc.erspparams), 'exact'))
STUDY.etc.erspparams = setfield(STUDY.etc.erspparams, varargin{index}, varargin{index+1});
end;
end;
end;
end;
% scan clusters and channels to remove erspdata info if timerange etc. have changed
% ---------------------------------------------------------------------------------
if ~isequal(STUDY.etc.erspparams.timerange, TMPSTUDY.etc.erspparams.timerange) | ...
~isequal(STUDY.etc.erspparams.freqrange, TMPSTUDY.etc.erspparams.freqrange) | ...
~isequal(STUDY.etc.erspparams.subbaseline, TMPSTUDY.etc.erspparams.subbaseline)
rmfields = { 'erspdata' 'ersptimes' 'erspfreqs' 'erspbase' 'erspdatatrials' 'ersptimes' 'erspfreqs' 'erspsubjinds' 'ersptrialinfo' ...
'itcdata' 'itctimes' 'itcfreqs' 'itcdatatrials' 'itctimes' 'itcfreqs' 'itcsubjinds' 'itctrialinfo' };
for iField = 1:length(rmfields)
if isfield(STUDY.cluster, rmfields{iField})
STUDY.cluster = rmfield(STUDY.cluster, rmfields{iField});
end;
if isfield(STUDY.changrp, rmfields{iField})
STUDY.changrp = rmfield(STUDY.changrp, rmfields{iField});
end;
end;
end;
function STUDY = default_params(STUDY)
if ~isfield(STUDY.etc, 'erspparams'), STUDY.etc.erspparams = []; end;
if ~isfield(STUDY.etc.erspparams, 'topotime'), STUDY.etc.erspparams.topotime = []; end;
if ~isfield(STUDY.etc.erspparams, 'topofreq'), STUDY.etc.erspparams.topofreq = []; end;
if ~isfield(STUDY.etc.erspparams, 'timerange'), STUDY.etc.erspparams.timerange = []; end;
if ~isfield(STUDY.etc.erspparams, 'freqrange'), STUDY.etc.erspparams.freqrange = []; end;
if ~isfield(STUDY.etc.erspparams, 'ersplim' ), STUDY.etc.erspparams.ersplim = []; end;
if ~isfield(STUDY.etc.erspparams, 'itclim' ), STUDY.etc.erspparams.itclim = []; end;
if ~isfield(STUDY.etc.erspparams, 'maskdata' ), STUDY.etc.erspparams.maskdata = 'off'; end; %deprecated
if ~isfield(STUDY.etc.erspparams, 'subbaseline' ), STUDY.etc.erspparams.subbaseline = 'off'; end;
|
github
|
lcnhappe/happe-master
|
std_detachplots.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_detachplots.m
| 9,167 |
utf_8
|
27fdb5491e2d54fe4e5fb76418c35ef2
|
% std_detachplots() - Given a figure with subplots and several lines per axis, will add a callback to
% each axis specified in the 'figtitles' input. The callback consist in a figure with all the detached
% individuals lines.
%
% Usage:
% >> std_detachplots('','','data',data 'figtitles', alltitlestmp,'sbtitles',sbtitles,'handles', handles);
%
% Inputs:
% data - Cell array containing the data matrices for each plot in the same order showed in the figure
% figtitles - Cell array of the titles of each individual axes in
% the figure. The titles must correspond. The function
% use this value to find the right hanlde of the axis
% sbtitles - Cell array of cell arrays with the titles for each
% detached line per axis. i.e. {{'Axis1 line1' 'Axis1 line2'} {'Axis2 line1' 'Axis2 line2'}}
% handles - Handles of the main figure who contain all the
% subplots
% flagstd - Flag to plot the Standar Deviation {default: 1} means 'on'
%
% See also:
%
% Author: Ramon Martinez-Cancino, SCCN, 2014
%
% Copyright (C) 2014 Ramon Martinez-Cancino,INC, SCCN
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function std_detachplots(hObject,eventdata,varargin)
% display help if not enough arguments
if nargin < 2
help std_detachplots;
return;
end
icadefs;
try
options = varargin;
if ~isempty( varargin ),
for i = 1:2:numel(options)
g.(options{i}) = options{i+1};
end
else g= []; end;
catch
disp('std_detachplots() error: calling convention {''key'', value, ... } error'); return;
end;
try g.data; catch, g.data = []; end; % Name of plots
try g.figtitles; catch, g.figtitles = []; end; % Name of plots
try g.sbtitles; catch, g.sbtitles = []; end; % Name of plots
try g.handles; catch, g.handles = []; end; % Handles of figure
try g.flagstd; catch, g.flagstd = 1; end; % Plot std band around mean
try g.xlabel; catch, g.xlabel = ''; end; % xlabel
try g.ylabel; catch, g.ylabel = ''; end; % ylabel
try g.timevec; catch, g.timevec = ''; end; % Time or freq vector
try g.filter; catch, g.filter = ''; end; % Low pass filter freq
% Checking data
if isempty(g.handles) && any([isempty(g.data) isempty(g.figtitles)])
error('std_detachplots : Check entries. Options ''handles'', ''data'' and ''figtitles'' must be provided');
end
if iscell(g.data)
nplots = numel(g.data(:));
else
nplots = 1 ;
g.data = {g.data};
end
% Checking sbtitles
if isempty(g.sbtitles)
for i = 1:numel(g.data)
c = 1;
if ~isempty(g.data{i})
for j = 1:size(g.data{i},2)
g.sbtitles{i}{j} = {['Line ' num2str(c)]};
c = c+1;
end
end
end
end
% Plot goes here
%--------------------------------------------------------------------------
if isempty(g.handles)
for i_nplots = 1 : nplots
idata = g.data{i_nplots};
% Filtering data to be plotted
if ~isempty(g.filter), idata = myfilt(idata, 1000/(g.timevec(2)-g.timevec(1)), 0, g.filter); end;
len = size(idata,2);
if len > 0 % A non-empty cluster
% Getting the mean
meandata = mean(idata,2);
stddata = std(idata,0,2);
if license('checkout', 'statistics_toolbox')
SEM = std(idata,0,2)/sqrt(size(idata,2)); % Standard Error
ts = tinv([0.025 0.975],size(idata,2)-1); % T-Score
lower = meandata + ts(1)*SEM; % CI
upper = meandata + ts(2)*SEM; % CI
else
lower = meandata-2*stddata;
upper = meandata+2*stddata;
end
hplot = figure('name', g.figtitles, 'NumberTitle','off');
rowcols(2) = ceil(sqrt(len + 4));
rowcols(1) = ceil((len+4)/rowcols(2));
for k = 1:len
%--- first sbplot row ----
if k <= rowcols(2) - 2
figure(hplot);
sbplot(rowcols(1),rowcols(2),k+2);
hold on;
plotlines(k,idata,meandata,lower, upper,g.sbtitles{k},g);
else
figure(hplot)
sbplot(rowcols(1),rowcols(2),k+4);
hold on;
plotlines(k,idata,meandata,lower, upper,g.sbtitles{k},g);
end
end
% Plot all figure
figure(hplot)
sbplot(rowcols(1),rowcols(2),[1 rowcols(2)+2 ]);
hold on;
plotlines(1:len,idata,meandata,lower,upper,g.figtitles,g);
set(gcf,'Color', BACKCOLOR);
orient tall;
end
end
else
xlabelval = '';
ylabelval = '';
% Match Children handles based on titles provided
c = 0;
for i = 1: nplots
htemp = findall(g.handles,'String', g.figtitles{i});
if all([~isempty(htemp) ~isempty(g.data(i))])
handlestemp{i} = htemp(1);
% Getting x label from handles
if isempty(xlabelval)
xlabelval = get(get(get(handlestemp{i},'Parent'),'Xlabel'),'String'); % xlabelval = handlestemp{i}.Parent.XLabel.String;
end
% Getting y label from handles
if isempty(ylabelval)
ylabelval = get(get(get(handlestemp{i},'Parent'),'Ylabel'),'String'); % ylabelval = handlestemp{i}.Parent.YLabel.String;
end
% Getting timevec from handles
if isempty(g.timevec)
tmp = get(get(get(handlestemp{i},'Parent'),'Children'));
g.timevec = tmp(i).XData; % g.timevec = handlestemp{i}.Parent.Children(i).XData;
end
else
handlestemp{i} = [];
end
% Callback setting
if ~isempty(handlestemp{i})
c = c + 1;
% For Axis
set( get( handlestemp{i}, 'Parent'), 'ButtonDownFcn',{@std_detachplots,...
'data' ,g.data{i},...
'timevec' ,g.timevec,...
'handles' ,'',...
'figtitles',g.figtitles{i},...
'sbtitles' ,g.sbtitles{c},...
'xlabel' ,xlabelval,...
'ylabel' ,ylabelval,...
'filter' , g.filter,...
});
% For lines
set( get(get( handlestemp{i}, 'Parent'), 'Children'), 'ButtonDownFcn',{@std_detachplots,...
'data' ,g.data{i},...
'timevec' ,g.timevec,...
'handles' ,'',...
'figtitles',g.figtitles{i},...
'sbtitles' ,g.sbtitles{c},...
'xlabel' ,xlabelval,...
'ylabel' ,ylabelval,...
'filter' , g.filter,...
});
end
end
end
function plotlines(kindx,idata,meandata,lower,upper,sbtitle,g)
for i = 1:length(kindx)
plot(g.timevec,idata(:,kindx(i)),'b','LineWidth', 0.1); % plot g.data
end
plot(g.timevec,meandata,'r','LineWidth', 0.1); % plot mean
if g.flagstd % plot std band
eeglabciplot(lower,upper,g.timevec, 'r', 0.2);
axis tight;
end
if length(kindx)>1
xlabel(g.xlabel);
ylabel(g.ylabel);
end
box on;
grid on;
axis tight;
title(sbtitle, 'interpreter', 'none');
% rapid filtering for ERP (from std_plotcurve)
% -----------------------
function tmpdata2 = myfilt(tmpdata, srate, lowpass, highpass);
bscorrect = 1;
if bscorrect
% Getting initial baseline
bs_val1 = mean(tmpdata,1);
bs1 = repmat(bs_val1, size(tmpdata,1), 1);
end
% Filtering
tmpdata2 = reshape(tmpdata, size(tmpdata,1), size(tmpdata,2)*size(tmpdata,3)*size(tmpdata,4));
tmpdata2 = eegfiltfft(tmpdata2',srate, lowpass, highpass)';
tmpdata2 = reshape(tmpdata2, size(tmpdata,1), size(tmpdata,2), size(tmpdata,3), size(tmpdata,4));
if bscorrect
% Getting after-filter baseline
bs_val2 = mean(tmpdata2,1);
bs2 = repmat(bs_val2, size(tmpdata2,1), 1);
% Correcting the baseline
realbs = bs1-bs2;
tmpdata2 = tmpdata2 + realbs;
end
|
github
|
lcnhappe/happe-master
|
std_specplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_specplot.m
| 5,582 |
utf_8
|
a9230bd77bad7d1ec5ac55b5c61beed8
|
% std_specplot() - plot STUDY component cluster spectra, either mean spectra
% for all requested clusters in the same figure, with spectra
% for different conditions (if any) plotted in different colors,
% or spectra for each specified cluster in a separate figure
% for each condition, showing the cluster component spectra plus
% the mean cluster spectrum (in bold). The spectra can be
% plotted only if component spectra have been computed and
% saved with the EEG datasets in Matlab files "[datasetname].icaspec"
% using pop_preclust() or std_preclust(). Called by pop_clustedit().
% Calls std_readspec() and internal function std_plotcompspec()
% Usage:
% >> [STUDY] = std_specplot(STUDY, ALLEEG, key1, val1, key2, val2, ...);
% >> [STUDY specdata specfreqs pgroup pcond pinter] = std_specplot(STUDY, ALLEEG, ...);
%
% Inputs:
% STUDY - STUDY structure comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - vector of EEG dataset structures for the dataset(s) in the STUDY,
% typically created using load_ALLEEG().
% Optional inputs for component plotting:
% 'clusters' - [numeric vector|'all'] indices of clusters to plot.
% If no component indices ('comps' below) are given, the average
% spectrums of the requested clusters are plotted in the same figure,
% with spectrums for different conditions (and groups if any) plotted
% in different colors. In 'comps' (below) mode, spectrum for each
% specified cluster are plotted in separate figures (one per
% condition), each overplotting cluster component spectrum plus the
% average cluster spectrum in bold. Note this parameter has no effect
% if the 'comps' option (below) is used. {default: 'all'}
% 'comps' - [numeric vector|'all'] indices of the cluster components to plot.
% Note that 'comps', 'all' is equivalent to 'plotsubjects', 'on'.
%
% Optional inputs for channel plotting:
% 'channels' - [numeric vector] specific channel group to plot. By
% default, the grand mean channel spectrum is plotted (using the
% same format as for the cluster component means described above)
% 'subject' - [numeric vector] In 'changrp' mode (above), index of
% the subject(s) to plot. Else by default, plot all components
% in the cluster.
% 'plotsubjects' - ['on'|'off'] When 'on', plot spectrum of all subjects.
%
% Other optional inputs:
% 'plotmode' - ['normal'|'condensed'] 'normal' -> plot in a new figure;
% 'condensed' -> plot all curves in the current figure in a
% condensed fashion {default: 'normal'}
% 'key','val' - All optional inputs to pop_specparams() are also accepted here
% to plot subset of time, statistics etc. The values used by default
% are the ones set using pop_specparams() and stored in the
% STUDY structure.
% Outputs:
% STUDY - the input STUDY set structure with the plotted cluster mean spectra
% added?? to allow quick replotting.
% specdata - [cell] spectral data for each condition, group and subjects.
% size of cell array is [nconds x ngroups]. Size of each element
% is [freqs x subjects] for data channels or [freqs x components]
% for component clusters. This array may be gicen as input
% directly to the statcond() function or std_stats() function
% to compute statistics.
% specfreqs - [array] Sprectum point frequency values.
% pgroup - [array or cell] p-values group statistics. Output of the
% statcond() function.
% pcond - [array or cell] condition statistics. Output of the statcond()
% function.
% pinter - [array or cell] groups x conditions statistics. Output of
% statcond() function.
% Example:
% >> [STUDY] = std_specplot(STUDY,ALLEEG, 'clusters', 2, 'mode', 'apart');
% % Plot component spectra for STUDY cluster 2, plus the mean cluster
% % spectrum (in bold).
%
% See also pop_clustedit(), pop_preclust() std_preclust(), pop_clustedit(), std_readspec()
%
% Authors: Arnaud Delorme, CERCO, August, 2006
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [STUDY, specdata, allfreqs, pgroup, pcond, pinter] = std_specplot(STUDY, ALLEEG, varargin)
if nargin < 2
help std_specplot;
return;
end;
[STUDY, specdata, allfreqs, pgroup, pcond, pinter] = std_erpplot(STUDY, ALLEEG, 'datatype', 'spec', 'unitx', 'Hz', varargin{:});
|
github
|
lcnhappe/happe-master
|
std_movecomp.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_movecomp.m
| 6,804 |
utf_8
|
a592dff7e0ffc5b384d4dcc8b41d55b6
|
% std_movecomp() - Move ICA component(s) from one cluster to another.
%
% Usage:
% >> [STUDY] = std_movecomp(STUDY, ALLEEG, from_cluster, to_cluster, comps);
% Inputs:
% STUDY - STUDY structure comprising all or some of the EEG datasets in ALLEEG.
% ALLEEG - vector of EEG structures in the STUDY, typically created using
% load_ALLEEG().
% from_cluster - index of the cluster components are to be moved from.
% to_cluster - index of the cluster components are to be moved to.
% comps - [int vector] indices of from_cluster components to move.
%
% Outputs:
% STUDY - input STUDY structure with modified component reassignments.
%
% Example:
% >> [STUDY] = std_movecomp(STUDY, ALLEEG, 10, 7, [2 7]);
% % Move components 2 and 7 of Cluster 10 to Cluster 7.
%
% See also: pop_clustedit
%
% Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, June, 2005
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, June 07, 2005, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function STUDY = std_movecomp(STUDY, ALLEEG, old_clus, new_clus, comps)
icadefs;
% Cannot move components if clusters have children clusters
if ~isempty(STUDY.cluster(old_clus).child) | ~isempty(STUDY.cluster(new_clus).child)
warndlg2('Cannot move components if clusters have children clusters!' , 'Aborting move components');
return;
end
if isempty(STUDY.cluster(old_clus).parent) | isempty(STUDY.cluster(new_clus).parent) % The Parent cluster
warndlg2('Cannot move components to or from the Parent cluster - off all components in STUDY!' , 'Aborting move components');
return;
end
% Cannot move components if clusters have different parent
% clusters (didn'y come from the same level of clustering),
% unless the cluster, components are moved to, is an empty new cluster.
if (length(STUDY.cluster(old_clus).parent) ~= length(STUDY.cluster(new_clus).parent)) & ~strcmp(STUDY.cluster(new_clus).parent, 'manual')
warndlg2(strvcat('Cannot move components if clusters have different parent clusters!', ...
'This limitation will be fixed in the future'), 'Aborting move components');
return;
end
% Check if all parents are the same
if (~strcmp(STUDY.cluster(new_clus).parent, 'manual'))
if ~(sum(strcmp(STUDY.cluster(old_clus).parent, STUDY.cluster(new_clus).parent)) == length(STUDY.cluster(new_clus).parent))% different parent
warndlg2(strvcat('Cannot move components if clusters have different parent clusters!', ...
'This limitation will be fixed in the future') , 'Aborting move components');
return;
end
end
for ci = 1:length(comps)
comp = STUDY.cluster(old_clus).comps(comps(ci));
sets = STUDY.cluster(old_clus).sets(:,comps(ci));
fprintf('Moving component %d from cluster %d to cluster %d, centroids will be recomputed\n',comp, old_clus, new_clus);
%update new cluster
indcomp = length(STUDY.cluster(new_clus).comps)+1;
STUDY.cluster(new_clus).comps(indcomp) = comp;%with comp index
STUDY.cluster(new_clus).sets(:,indcomp) = sets; %with set indices
if strcmpi(STUDY.cluster(new_clus).parent, 'manual')
STUDY.cluster(new_clus).preclust.preclustparams = STUDY.cluster(old_clus).preclust.preclustparams;
STUDY.cluster(new_clus).parent = STUDY.cluster(old_clus).parent;
STUDY.cluster(find(strcmp({STUDY.cluster.name},STUDY.cluster(new_clus).parent))).child{end+1} = STUDY.cluster(new_clus).name;
end
% update preclustering array
% --------------------------
if strncmpi('Notclust',STUDY.cluster(old_clus).name,8)
STUDY.cluster(new_clus).preclust.preclustparams = [];
STUDY.cluster(new_clus).preclust.preclustdata = [];
STUDY.cluster(new_clus).preclust.preclustcomp = [];
disp('Important warning: pre-clustering information removed for target cluster');
disp('(this is because the component moved had no pre-clustering data associated to it)');
elseif ~strncmpi('Notclust',STUDY.cluster(new_clus).name,8)
STUDY.cluster(new_clus).preclust.preclustdata(indcomp,:) = STUDY.cluster(old_clus).preclust.preclustdata(comps(ci),:); %with preclustdata
end;
% sort by sets
% ------------
[tmp,sind] = sort(STUDY.cluster(new_clus).sets(1,:));
STUDY.cluster(new_clus).sets = STUDY.cluster(new_clus).sets(:,sind);
STUDY.cluster(new_clus).comps = STUDY.cluster(new_clus).comps(sind);
if ~isempty(STUDY.cluster(new_clus).preclust.preclustdata)
STUDY.cluster(new_clus).preclust.preclustdata(sind,:) = STUDY.cluster(new_clus).preclust.preclustdata(:,:);
end
end
%STUDY.cluster(new_clus).centroid = []; % remove centroid
STUDY = rm_centroid(STUDY, new_clus);
STUDY = rm_centroid(STUDY, old_clus);
% Remove data from old cluster
% left_comps - are all the components of the cluster after the
% components that were moved to the new cluster were removed.
left_comps = find(~ismember([1:length(STUDY.cluster(old_clus).comps)],comps));
STUDY.cluster(old_clus).comps = STUDY.cluster(old_clus).comps(left_comps);
STUDY.cluster(old_clus).sets = STUDY.cluster(old_clus).sets(:,left_comps);
if ~isempty(STUDY.cluster(old_clus).preclust.preclustdata)
try,
STUDY.cluster(old_clus).preclust.preclustdata = STUDY.cluster(old_clus).preclust.preclustdata(left_comps,:);
catch, % this generates an unknown error but I was not able to reproduce it - AD Sept. 26, 2009
end;
end;
% update the component indices
% ----------------------------
STUDY = std_selectdesign(STUDY, ALLEEG, STUDY.currentdesign);
disp('Done.');
% remove cluster information
% --------------------------
function STUDY = rm_centroid(STUDY, clsindex)
keepfields = { 'name' 'parent' 'child' 'comps' 'sets' 'algorithm' 'preclust' };
allfields = fieldnames(STUDY.cluster);
for index = 1:length(allfields)
if isempty(strmatch(allfields{index}, keepfields))
STUDY.cluster = setfield( STUDY.cluster, { clsindex }, allfields{index}, []);
end;
end;
|
github
|
lcnhappe/happe-master
|
std_plottf.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_plottf.m
| 14,853 |
utf_8
|
309b1ebe75a277c0130cf64bc514b243
|
% std_plottf() - plot ERSP/ITC images a component
% or channel cluster in a STUDY. Also allows plotting scalp
% maps.
% Usage:
% >> std_plottf( times, freqs, data, 'key', 'val', ...)
% Inputs:
% times - [vector] latencies in ms of the data points.
% freqs - [vector] frequencies in Hz of the data points.
% data - [cell array] mean data for each subject group and/or data
% condition. For example, to plot mean ERPs from a STUDY
% for epochs of 800 frames in two conditions from three groups
% of 12 subjects:
%
% >> data = { [800x12] [800x12] [800x12];... % 3 groups, cond 1
% [800x12] [800x12] [800x12] }; % 3 groups, cond 2
% >> std_plottf(erp_ms,data);
%
% By default, parametric statistics are computed across subjects
% in the three groups. (group,condition) ERP averages are plotted.
% See below and >> help statcond
% for more information about the statistical computations.
%
% Optional display parameters:
% 'datatype' - ['ersp'|'itc'] data type {default: 'ersp'}
% 'titles' - [cell array of string] titles for each of the subplots.
% { default: none}
%
% Statistics options:
% 'groupstats' - ['on'|'off'] Compute (or not) statistics across groups.
% {default: 'off'}
% 'condstats' - ['on'|'off'] Compute (or not) statistics across groups.
% {default: 'off'}
% 'threshold' - [NaN|real<<1] Significance threshold. NaN -> plot the
% p-values themselves on a different figure. When possible,
% significance regions are indicated below the data.
% {default: NaN}
% 'maskdata' - ['on'|'off'] when threshold is non-NaN and not both
% condition and group statistics are computed, the user
% has the option to mask the data for significance.
% {defualt: 'off'}
%
% Other plotting options:
% 'plotmode' - ['normal'|'condensed'] statistics plotting mode:
% 'condensed' -> plot statistics under the curves
% (when possible); 'normal' -> plot them in separate
% axes {default: 'normal'}
% 'freqscale' - ['log'|'linear'|'auto'] frequency plotting scale. This
% will only change the ordinate not interpolate the data.
% If you change this option blindly, your frequency scale
% might be innacurate {default: 'auto'}
% 'ylim' - [min max] ordinate limits for ERP and spectrum plots
% {default: all available data}
%
% ITC/ERSP image plotting options:
% 'tftopoopt' - [cell array] tftopo() plotting options (ERSP and ITC)
% 'caxis' - [min max] color axis (ERSP, ITC, scalp maps)
%
% Scalp map plotting options:
% 'chanlocs' - [struct] channel location structure
%
% Author: Arnaud Delorme, CERCO, CNRS, 2006-
%
% See also: pop_erspparams(), pop_erpparams(), pop_specparams(), statcond()
% Copyright (C) 2006 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 [pgroup, pcond, pinter] = std_plottf(timevals, freqs, data, varargin)
pgroup = [];
pcond = [];
pinter = [];
if nargin < 2
help std_plottf;
return;
end;
opt = finputcheck( varargin, { 'titles' 'cell' [] cellfun(@num2str, cell(20,20), 'uniformoutput', false);
'caxis' 'real' [] [];
'ersplim' 'real' [] []; % same as above
'itclim' 'real' [] []; % same as above
'ylim' 'real' [] [];
'tftopoopt' 'cell' [] {};
'threshold' 'real' [] NaN;
'unitx' 'string' [] 'ms'; % just for titles
'unitcolor' 'string' {} 'dB';
'chanlocs' 'struct' [] struct('labels', {});
'freqscale' 'string' { 'log','linear','auto' } 'auto';
'events' 'cell' [] {};
'groupstats' 'cell' [] {};
'condstats' 'cell' [] {};
'interstats' 'cell' [] {};
'maskdata' 'string' { 'on','off' } 'off';
'datatype' 'string' { 'ersp','itc' 'erpim' } 'ersp';
'plotmode' 'string' { 'normal','condensed' } 'normal' }, 'std_plottf');
if isstr(opt), error(opt); end;
if all(all(cellfun('size', data, 3)==1)) opt.singlesubject = 'on'; end;
% remove empty entries
datapresent = ~cellfun(@isempty, data);
for c = size(data,1):-1:1, if sum(datapresent(c,:)) == 0, data(c,:) = []; opt.titles(c,:) = []; if ~isempty(opt.groupstats), opt.groupstats(c) = []; end; end; end;
for g = size(data,2):-1:1, if sum(datapresent(:,g)) == 0, data(:,g) = []; opt.titles(:,g) = []; if ~isempty(opt.condstats ), opt.condstats( g) = []; end; end; end;
if ~isempty(opt.groupstats) & ~isempty(opt.condstats) & strcmpi(opt.maskdata, 'on')
disp('Cannot use ''maskdata'' option with both condition stat. and group stat. on');
disp('Disabling statistics');
opt.groupstats = {}; opt.condstats = {}; opt.maskdata = 'off';
end;
if ~isempty(opt.ersplim), opt.caxis = opt.ersplim; end;
if ~isempty(opt.itclim), opt.caxis = opt.itclim; end;
onecol = { 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' };
manycol = { 'b' 'r' 'g' 'k' 'c' 'y' };
nc = size(data,1);
ng = size(data,2);
if nc >= ng, opt.transpose = 'on';
else opt.transpose = 'off';
end;
% test log frequencies
% --------------------
if length(freqs) > 2 & strcmpi(opt.freqscale, 'auto')
midfreq = (freqs(3)+freqs(1))/2;
if midfreq*.9999 < freqs(2) & midfreq*1.0001 > freqs(2), opt.freqscale = 'linear';
else opt.freqscale = 'log';
end;
end;
% condensed plot
% --------------
if strcmpi(opt.plotmode, 'condensed')
meanplot = zeros(size(data{1},1), size(data{1},2));
count = 0;
for c = 1:nc
for g = 1:ng
if ~isempty(data{c,g})
meanplot = meanplot + mean(data{c,g},3);
count = count+1;
end;
end;
end;
meanplot = meanplot/count;
options = { 'chanlocs', opt.chanlocs, 'electrodes', 'off', 'cbar', 'on', ...
'cmode', 'separate', opt.tftopoopt{:} };
if strcmpi(opt.datatype, 'erpim'), options = { options{:} 'ylabel' 'Trials' }; end;
if strcmpi(opt.freqscale, 'log'), options = { options{:} 'logfreq', 'native' }; end;
tftopo( meanplot', timevals, freqs, 'title', opt.titles{1}, options{:});
currentHangle = gca;
if ~isempty( opt.caxis )
caxis( currentHangle, opt.caxis )
end
colorbarHandle = cbar;
title(colorbarHandle,opt.unitcolor);
axes(currentHangle);
return;
end;
% plotting paramters
% ------------------
if ng > 1 && ~isempty(opt.groupstats), addc = 1; else addc = 0; end;
if nc > 1 && ~isempty(opt.condstats ), addr = 1; else addr = 0; end;
% compute significance mask
% --------------------------
if ~isempty(opt.interstats), pinter = opt.interstats{3}; end;
if ~isnan(opt.threshold) && ( ~isempty(opt.groupstats) || ~isempty(opt.condstats) )
pcondplot = opt.condstats;
pgroupplot = opt.groupstats;
pinterplot = pinter;
maxplot = 1;
else
for ind = 1:length(opt.condstats), pcondplot{ind} = -log10(opt.condstats{ind}); end;
for ind = 1:length(opt.groupstats), pgroupplot{ind} = -log10(opt.groupstats{ind}); end;
if ~isempty(pinter), pinterplot = -log10(pinter); end;
maxplot = 3;
end;
% -------------------------------
% masking for significance of not
% -------------------------------
statmask = 0;
if strcmpi(opt.maskdata, 'on') && ~isnan(opt.threshold) && ...
(~isempty(opt.condstats) || ~isempty(opt.condstats))
addc = 0; addr = 0; statmask = 1;
end;
% -------------------------
% plot time/frequency image
% -------------------------
options = { 'chanlocs', opt.chanlocs, 'electrodes', 'off', 'cbar', 'off', ...
'cmode', 'separate', opt.tftopoopt{:} };
if strcmpi(opt.freqscale, 'log'), options = { options{:} 'logfreq', 'native' }; end;
if strcmpi(opt.datatype, 'erpim'), options = { options{:} 'ylabel' 'Trials' }; end;
% adjust figure size
% ------------------
fig = figure('color', 'w');
pos = get(fig, 'position');
set(fig, 'position', [ pos(1)+15 pos(2)+15 pos(3)/2.5*(nc+addr), pos(4)/2*(ng+addc) ]);
pos = get(fig, 'position');
if strcmpi(opt.transpose, 'off'), set(gcf, 'position', [ pos(1) pos(2) pos(4) pos(3)]);
else set(gcf, 'position', pos);
end;
tmpc = [inf -inf];
for c = 1:nc
for g = 1:ng
hdl(c,g) = mysubplot(nc+addr, ng+addc, g + (c-1)*(ng+addc), opt.transpose);
if ~isempty(data{c,g})
tmpplot = mean(data{c,g},3);
if ~isreal(tmpplot(1)), tmpplot = abs(tmpplot); end;
if statmask,
if ~isempty(opt.condstats), tmpplot(find(pcondplot{g}(:) == 0)) = 0;
else tmpplot(find(pgroupplot{c}(:) == 0)) = 0;
end;
end;
if ~isempty(opt.events)
tmpevents = mean(opt.events{c,g},2);
else tmpevents = [];
end;
tftopo( tmpplot, timevals, freqs, 'events', tmpevents, 'title', opt.titles{c,g}, options{:});
if isempty(opt.caxis) && ~isempty(tmpc)
warning off;
tmpc = [ min(min(tmpplot(:)), tmpc(1)) max(max(tmpplot(:)), tmpc(2)) ];
warning on;
else
if ~isempty(opt.caxis)
caxis(opt.caxis);
end;
end;
if c > 1
ylabel('');
end;
end;
% statistics accross groups
% -------------------------
if g == ng && ng > 1 && ~isempty(opt.groupstats) && ~isinf(pgroupplot{c}(1)) && ~statmask
hdl(c,g+1) = mysubplot(nc+addr, ng+addc, g + 1 + (c-1)*(ng+addc), opt.transpose);
tftopo( pgroupplot{c}, timevals, freqs, 'title', opt.titles{c,g+1}, options{:});
caxis([-maxplot maxplot]);
end;
end;
end;
for g = 1:ng
% statistics accross conditions
% -----------------------------
if ~isempty(opt.condstats) && ~isinf(pcondplot{g}(1)) && ~statmask && nc > 1
hdl(nc+1,g) = mysubplot(nc+addr, ng+addc, g + c*(ng+addc), opt.transpose);
tftopo( pcondplot{g}, timevals, freqs, 'title', opt.titles{nc+1,g}, options{:});
caxis([-maxplot maxplot]);
end;
end;
% color scale
% -----------
if isempty(opt.caxis)
tmpc = [-max(abs(tmpc)) max(abs(tmpc))];
for c = 1:nc
for g = 1:ng
axes(hdl(c,g));
if ~isempty(tmpc)
caxis(tmpc);
end;
end;
end;
end;
% statistics accross group and conditions
% ---------------------------------------
if ~isempty(opt.groupstats) && ~isempty(opt.condstats) && ng > 1 && nc > 1
hdl(nc+1,ng+1) = mysubplot(nc+addr, ng+addc, g + 1 + c*(ng+addr), opt.transpose);
tftopo( pinterplot, timevals, freqs, 'title', opt.titles{nc+1,ng+1}, options{:});
caxis([-maxplot maxplot]);
ylabel('');
end;
% color bars
% ----------
axes(hdl(nc,ng));
cbar_standard(opt.datatype, ng, opt.unitcolor);
if isnan(opt.threshold) && (nc ~= size(hdl,1) || ng ~= size(hdl,2))
ind = find(ishandle(hdl(end:-1:1)));
axes(hdl(end-ind(1)+1));
cbar_signif(ng, maxplot);
end;
% mysubplot (allow to transpose if necessary)
% -------------------------------------------
function hdl = mysubplot(nr,nc,ind,transp);
r = ceil(ind/nc);
c = ind -(r-1)*nc;
if strcmpi(transp, 'on'), hdl = subplot(nc,nr,(c-1)*nr+r);
else hdl = subplot(nr,nc,(r-1)*nc+c);
end;
% colorbar for ERSP and scalp plot
% --------------------------------
function cbar_standard(datatype, ng, unitcolor);
pos = get(gca, 'position');
tmpc = caxis;
fact = fastif(ng == 1, 40, 20);
tmp = axes('position', [ pos(1)+pos(3)+max(pos(3)/fact,0.006) pos(2) max(pos(3)/fact,0.01) pos(4) ]);
set(gca, 'unit', 'normalized');
if strcmpi(datatype, 'itc')
cbar(tmp, 0, tmpc, 10); ylim([0.5 1]);
title('ITC','fontsize',10,'fontweight','normal');
elseif strcmpi(datatype, 'erpim')
cbar(tmp, 0, tmpc, 5);
else
cbar(tmp, 0, tmpc, 5);
title(unitcolor);
end;
% colorbar for significance
% -------------------------
function cbar_signif(ng, maxplot);
% Retrieving Defaults
icadefs;
pos = get(gca, 'position');
tmpc = caxis;
fact = fastif(ng == 1, 40, 20);
tmp = axes('position', [ pos(1)+pos(3)+max(pos(3)/fact,0.006) pos(2) max(pos(3)/fact,0.01) pos(4) ]);
map = colormap(DEFAULT_COLORMAP);
n = size(map,1);
cols = [ceil(n/2):n]';
image([0 1],linspace(0,maxplot,length(cols)),[cols cols]);
%cbar(tmp, 0, tmpc, 5);
tick = linspace(0, maxplot, maxplot+1);
set(gca, 'ytickmode', 'manual', 'YAxisLocation', 'right', 'xtick', [], ...
'ytick', tick, 'yticklabel', round(10.^-tick*1000)/1000);
xlabel('');
colormap(DEFAULT_COLORMAP);
% rapid filtering for ERP
% -----------------------
function tmpdata2 = myfilt(tmpdata, lowpass, highpass, factor, filtertype)
tmpdata2 = reshape(tmpdata, size(tmpdata,1), size(tmpdata,2)*size(tmpdata,3)*size(tmpdata,4));
tmpdata2 = eegfiltfft(tmpdata2',lowpass, highpass, factor, filtertype)';
tmpdata2 = reshape(tmpdata2, size(tmpdata,1), size(tmpdata,2), size(tmpdata,3), size(tmpdata,4));
|
github
|
lcnhappe/happe-master
|
std_getindvar.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_getindvar.m
| 7,332 |
utf_8
|
6ae9d669af217a88f9cf15ea2478d5c6
|
% std_getindvar - get independent variables of a STUDY
%
% Usage:
% [indvar indvarvals] = std_getindvar(STUDY);
% [indvar indvarvals] = std_getindvar(STUDY, mode, scandesign);
%
% Input:
% STUDY - EEGLAB STUDY structure
% mode - ['datinfo'|'trialinfo'|'both'] get independent variables
% linked to STUDY.datasetinfo, STUDY.datasetinfo.trialinfo or
% both. Default is 'both'.
% scandesign - [0|1] scan STUDY design for additional combinations of
% independent variable values. Default is 0.
%
% Output:
% indvar - [cell array] cell array of independent variable names
% indvarvals - [cell array] cell array of independent variable values
%
% Authors: A. Delorme, CERCO/CNRS and SCCN/UCSD, 2010-
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, 2010, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public 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 [ factor factorvals subjects ] = std_getindvar(STUDY, mode, scandesign)
if nargin < 1
help std_getindvar;
return;
end;
factor = {};
factorvals = {};
subjects = {};
if nargin < 2, mode = 'both'; end;
if nargin < 3, scandesign = 0; end;
countfact = 1;
setinfo = STUDY.datasetinfo;
if strcmpi(mode, 'datinfo') || strcmpi(mode, 'both')
% get trial info
ff = fieldnames(setinfo);
ff = setdiff_bc(ff, { 'filepath' 'filename' 'subject' 'index' 'ncomps' 'comps' 'trialinfo' });
for index = 1:length(ff)
if isstr(getfield(setinfo(1), ff{index}))
eval( [ 'tmpvals = unique_bc({ setinfo.' ff{index} '});' ] );
if length(tmpvals) > 1
factor{ countfact} = ff{index};
factorvals{countfact} = tmpvals;
% get subject for each factor value
for c = 1:length(tmpvals)
eval( [ 'datind = strmatch(tmpvals{c}, { setinfo.' ff{index} '}, ''exact'');' ] );
subjects{ countfact}{c} = unique_bc( { setinfo(datind).subject } );
end;
countfact = countfact + 1;
end;
else
eval( [ 'tmpvals = unique_bc([ setinfo.' ff{index} ']);' ] );
if length(tmpvals) > 1
factor{ countfact} = ff{index};
factorvals{countfact} = mattocell(tmpvals);
% get subject for each factor value
for c = 1:length(tmpvals)
eval( [ 'datind = find(tmpvals(c) == [ setinfo.' ff{index} ']);' ] );
subjects{ countfact}{c} = unique_bc( { setinfo(datind).subject } );
end;
countfact = countfact + 1;
end;
end;
end;
end;
% add ind. variables for trials
% -----------------------------
if strcmpi(mode, 'trialinfo') || strcmpi(mode, 'both')
% add trial info
if isfield(setinfo, 'trialinfo')
ff = fieldnames(setinfo(1).trialinfo);
for index = 1:length(ff)
% check if any of the datasets are using string for event type
allFieldsPresent = cellfun(@(x)(isfield(x, ff{index})), { setinfo.trialinfo });
allFirstVal = cellfun(@(x)(getfield(x, ff{index})), { setinfo(allFieldsPresent).trialinfo }, 'uniformoutput', false);
if any(cellfun(@isstr, allFirstVal))
alltmpvals = {};
for ind = 1:length(setinfo)
if isfield(setinfo(ind).trialinfo, ff{index})
eval( [ 'tmpTrialVals = { setinfo(ind).trialinfo.' ff{index} ' };' ] );
if isnumeric(tmpTrialVals{1})
% convert to string if necessary
tmpTrialVals = cellfun(@num2str, tmpTrialVals, 'uniformoutput', false);
end;
tmpvals = unique_bc(tmpTrialVals);
else tmpvals = {};
end;
if isempty(alltmpvals)
alltmpvals = tmpvals;
else
alltmpvals = { alltmpvals{:} tmpvals{:} };
end;
end;
alltmpvals = unique_bc(alltmpvals);
if length(alltmpvals) > 1
factor{ countfact} = ff{index};
factorvals{countfact} = alltmpvals;
subjects{ countfact} = {};
countfact = countfact + 1;
end;
else
alltmpvals = [];
for ind = 1:length(setinfo)
if isfield(setinfo(ind).trialinfo, ff{index})
eval( [ 'tmpvals = unique_bc([ setinfo(ind).trialinfo.' ff{index} ' ]);' ] );
else tmpvals = [];
end;
alltmpvals = [ alltmpvals tmpvals ];
end;
alltmpvals = unique_bc(alltmpvals);
if length(alltmpvals) > 1
factor{ countfact} = ff{index};
factorvals{countfact} = mattocell(alltmpvals);
subjects{ countfact} = {};
countfact = countfact + 1;
end;
end;
end;
end;
end;
% scan existing design for additional combinations
% ------------------------------------------------
if scandesign
for desind = 1:length(STUDY.design)
pos1 = strmatch(STUDY.design(desind).variable(1).label, factor, 'exact');
pos2 = strmatch(STUDY.design(desind).variable(2).label, factor, 'exact');
if ~isempty(pos1), add1 = mysetdiff(STUDY.design(desind).variable(1).value, factorvals{pos1}); else add1 = []; end;
if ~isempty(pos2), add2 = mysetdiff(STUDY.design(desind).variable(2).value, factorvals{pos2}); else add2 = []; end;
if ~isempty(add1), factorvals{pos1} = { factorvals{pos1}{:} add1{:} }; end;
if ~isempty(add2), factorvals{pos2} = { factorvals{pos2}{:} add2{:} }; end;
end;
end;
function cellout = mysetdiff(cell1, cell2);
if isstr(cell2{1})
indcell = cellfun(@iscell, cell1);
else indcell = cellfun(@(x)(length(x)>1), cell1);
end;
cellout = cell1(indcell);
% if isstr(cell1{1}) && isstr(cell2{1})
% cellout = setdiff_bc(cell1, cell2);
% elseif ~isstr(cell1{1}) && ~isstr(cell2{1})
% cellout = mattocell(setdiff( [ cell1{:} ], [ cell2{:} ]));
% elseif isstr(cell1{1}) && ~isstr(cell2{1})
% cellout = setdiff_bc(cell1, cellfun(@(x)(num2str(x)),cell2, 'uniformoutput', false));
% elseif ~isstr(cell1{1}) && isstr(cell2{1})
% cellout = setdiff_bc(cellfun(@(x)(num2str(x)),cell1, 'uniformoutput', false), cell2);
% end;
|
github
|
lcnhappe/happe-master
|
std_uniformsetinds.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_uniformsetinds.m
| 1,311 |
utf_8
|
8c693e38166509a1a4f3be6994c4eb1e
|
% std_uniformsetinds() - Check uniform channel distribution accross datasets
%
% Usage:
% >> boolval = std_uniformsetinds(STUDY);
% Inputs:
% STUDY - EEGLAB STUDY
%
% Outputs:
% boolval - [0|1] 1 if uniform
%
% Authors: Arnaud Delorme, SCCN/UCSD, CERCO/CNRS, 2010-
% Copyright (C) Arnaud Delorme
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function uniformchannels = std_uniformsetinds( STUDY );
uniformchannels = 1;
for c = 1:length(STUDY.changrp(1).setinds(:))
tmpind = cellfun(@(x)(length(x{c})), { STUDY.changrp(:).setinds });
if length(unique(tmpind)) ~= 1
uniformchannels = 0;
end;
end;
|
github
|
lcnhappe/happe-master
|
std_topoplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_topoplot.m
| 14,420 |
utf_8
|
a3141fe7504cf37ab41fb362f25aedd8
|
% std_topoplot() - Command line function to plot cluster component and mean scalp maps.
% Displays either mean cluster/s scalp map/s, or all cluster/s components
% scalp maps with the mean cluster/s scsalp map in one figure.
% The scalp maps can be visualized only if component scalp maps
% were calculated and saved in the EEG datasets in the STUDY.
% These can be computed during pre-clustering using the GUI-based function
% pop_preclust() or the equivalent commandline functions eeg_createdata()
% and eeg_preclust(). A pop-function that calls this function is
% pop_clustedit().
% Usage:
% >> [STUDY] = std_topoplot(STUDY, ALLEEG, key1, val1, key2, val2);
% Inputs:
% STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - global EEGLAB vector of EEG structures for the dataset(s) included in
% the STUDY. ALLEEG for a STUDY set is typically created using load_ALLEEG().
% Optional inputs:
% 'clusters' - [numeric vector| 'all'] -> specific cluster numbers to plot.
% 'all' -> plot all clusters in STUDY.
% {default: 'all'}.
% 'comps' - [numeric vector | 'all'] -> indices of the cluster components to plot.
% 'all' -> plot all the components in the cluster
% {default: 'all'}.
% 'mode' - ['together'|'apart'] a plotting mode. In 'together' mode, the average
% scalp maps of the requested clusters are plotted in the same figure,
% one per condition. In 'apart' mode, component scalp maps for each
% cluster are plotted in a separate figure for each condition, plus the
% cluster mean map. Note that this option is irrelevant if component
% indices ('comps' above) are provided.{default: 'apart'}.
% 'figure' - ['on'|'off'] for the 'together' mode option, plots on
% a new figure ('on'), or on the current figure ('off').
% {default: 'on'}.
% Outputs:
% STUDY - the input STUDY set structure modified with plotted cluster scalp
% map means, to allow quick replotting (unless clusters meands
% already exists in th STUDY).
%
% Example:
% % Plot the mean scalp maps for clusters 1 through 20 on the same figure.
% >> [STUDY] = std_topoplot(STUDY,ALLEEG, 'clusters', [1:20], 'mode', 'together');
%
% See also pop_clustedit(), pop_preclust()
%
% Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, June, 2005
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, June 07, 2005, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function STUDY = std_topoplot(STUDY, ALLEEG, varargin)
icadefs;
% Set default values
cls = [];
mode = 'together'; % plot all cluster mean scalp maps on one figure
figureon = 1; % plot on a new figure
for k = 3:2:nargin
switch varargin{k-2}
case 'clusters'
if isnumeric(varargin{k-1})
cls = varargin{k-1};
if isempty(cls)
cls = 2:length(STUDY.cluster);
end
else
if isstr(varargin{k-1}) & strcmpi(varargin{k-1}, 'all')
cls = 2:length(STUDY.cluster);
else
error('std_topoplot: ''clusters'' input takes either specific clusters (numeric vector) or keyword ''all''.');
end
end
case 'plotsubjects' % legacy
mode = 'apart';
case 'comps'
if isstr( varargin{k-1} ), mode = 'apart';
else STUDY = std_plotcompmap(STUDY, ALLEEG, cls, varargin{k-1}); return;
end;
case 'mode' % Plotting mode 'together' / 'apart'
mode = varargin{k-1};
case 'figure'
if strcmpi(varargin{k-1},'off')
figureon = 0;
end
case 'plotrad'
inputPlotrad = varargin{k-1};
end
end
% select clusters to plot
% -----------------------
if isempty(cls)
tmp =[];
cls = 2:length(STUDY.cluster); % plot all clusters in STUDY
for k = 1: length(cls)
% don't include 'Notclust' clusters
if ~strncmpi('Notclust',STUDY.cluster(cls(k)).name,8) & ~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13)
tmp = [tmp cls(k)];
end
end
cls = tmp;
end;
% Plot all the components in the cluster
disp('Drawing components of cluster (all at once)...');
if ~isfield(STUDY.cluster,'topo'), STUDY.cluster(1).topo = []; end;
for clus = 1: length(cls) % For each cluster requested
if isempty(STUDY.cluster(cls(clus)).topo)
STUDY = std_readtopoclust(STUDY,ALLEEG, cls(clus));
end;
end
if strcmpi(mode, 'apart')
for clus = 1: length(cls) % For each cluster requested
len = length(STUDY.cluster(cls(clus)).comps);
if len > 0 % A non-empty cluster
h_topo = figure;
rowcols(2) = ceil(sqrt(len + 4)); rowcols(1) = ceil((len+4)/rowcols(2));
clusscalp = STUDY.cluster(cls(clus));
ave_grid = clusscalp.topo;
tmp_ave = ave_grid;
tmp_ave(find(isnan(tmp_ave))) = 0; % remove NaN values from grid for later correlation calculation.
for k = 1:len
abset = STUDY.datasetinfo(STUDY.cluster(cls(clus)).sets(1,k)).index;
subject = STUDY.datasetinfo(STUDY.cluster(cls(clus)).sets(1,k)).subject;
comp = STUDY.cluster(cls(clus)).comps(k);
[Xi,Yi] = meshgrid(clusscalp.topoy,clusscalp.topox);
scalpmap = squeeze(clusscalp.topoall{k}); % already correct polarity
if k <= rowcols(2) - 2 %first sbplot row
figure(h_topo);
sbplot(rowcols(1),rowcols(2),k+2) ,
toporeplot(scalpmap, 'style', 'both', 'plotrad',0.5,'intrad',0.5, 'verbose', 'off','xsurface', Xi, 'ysurface', Yi );
title([subject '/' 'ic' num2str(comp) ], 'interpreter', 'none');
colormap(DEFAULT_COLORMAP);
%waitbar(k/(len+1),h_wait)
else %other sbplot rows
figure(h_topo)
sbplot(rowcols(1),rowcols(2),k+4) ,
toporeplot(scalpmap, 'style', 'both', 'plotrad',0.5,'intrad',0.5, 'verbose', 'off','xsurface', Xi, 'ysurface', Yi );
title([subject '/' 'ic' num2str(comp)], 'interpreter', 'none');
colormap(DEFAULT_COLORMAP);
%waitbar(k/(len+1),h_wait)
end
end
figure(h_topo)
sbplot(rowcols(1),rowcols(2),[1 rowcols(2)+2 ]) ,
toporeplot(ave_grid, 'style', 'both', 'plotrad',0.5,'intrad',0.5, 'verbose', 'off');
title([ STUDY.cluster(cls(clus)).name ' (' num2str(length(unique(STUDY.cluster(cls(clus)).sets(1,:)))) ' Ss, ' num2str(length(STUDY.cluster(cls(clus)).comps)),' ICs)']);
%title([ STUDY.cluster(cls(clus)).name ' average scalp map, ' num2str(length(unique(STUDY.cluster(cls(clus)).sets(1,:)))) 'Ss']);
set(gcf,'Color', BACKCOLOR);
colormap(DEFAULT_COLORMAP);
%waitbar(1,h_wait)
%delete(h_wait)
orient tall % fill the figure page for printing
axcopy
end % Finished one cluster plot
end % Finished plotting all clusters
end % Finished 'apart' plotting mode
% Plot clusters centroid maps
if strcmpi(mode, 'together')
len = length(cls);
rowcols(2) = ceil(sqrt(len)); rowcols(1) = ceil((len)/rowcols(2));
if figureon
try
% optional 'CreateCancelBtn', 'delete(gcbf); error(''USER ABORT'');',
h_wait = waitbar(0,'Computing topoplot ...', 'Color', BACKEEGLABCOLOR,'position', [300, 200, 300, 48]);
catch % for Matlab 5.3
h_wait = waitbar(0,'Computing topoplot ...','position', [300, 200, 300, 48]);
end
figure
end
for k = 1:len
if len ~= 1
sbplot(rowcols(1),rowcols(2),k)
end
tmpcmap = colormap(DEFAULT_COLORMAP);
toporeplot(STUDY.cluster(cls(k)).topo, 'style', 'both', 'plotrad',0.5,'intrad',0.5, 'verbose', 'off','colormap', tmpcmap);
title([ STUDY.cluster(cls(k)).name ' (' num2str(length(unique(STUDY.cluster(cls(k)).sets(1,:)))) ' Ss, ' num2str(length(STUDY.cluster(cls(k)).comps)),' ICs)']);
colormap(DEFAULT_COLORMAP);
%title([ STUDY.cluster(cls(k)).name ', ' num2str(length(unique(STUDY.cluster(cls(k)).sets(1,:)))) 'Ss' ]);
if figureon
waitbar(k/len,h_wait)
end
end
if figureon
delete(h_wait)
end
if len ~= 1
maintitle = 'Average scalp map for all clusters';
a = textsc(maintitle, 'title');
set(a, 'fontweight', 'bold');
set(gcf,'name', maintitle);
else
title([ STUDY.cluster(cls(k)).name ' (' num2str(length(unique(STUDY.cluster(cls(k)).sets(1,:)))) ' Ss, ' num2str(length(STUDY.cluster(cls(k)).comps)),' ICs)']);
set(gcf,'name',['Scalp map of ' STUDY.cluster(cls(k)).name ' (' num2str(length(unique(STUDY.cluster(cls(k)).sets(1,:)))) ' Ss, ' num2str(length(STUDY.cluster(cls(k)).comps)),' ICs)']);
%title([ STUDY.cluster(cls(k)).name ' scalp map, ' num2str(length(unique(STUDY.cluster(cls(k)).sets(1,:)))) 'Ss' ]);
end
set(gcf,'Color', BACKCOLOR);
orient tall
axcopy
end
% std_plotcompmap() - Commandline function, to visualizing cluster components scalp maps.
% Displays the scalp maps of specified cluster components on separate figures.
% The scalp maps can be visualized only if component scalp maps
% were calculated and saved in the EEG datasets in the STUDY.
% These can be computed during pre-clustering using the GUI-based function
% pop_preclust() or the equivalent commandline functions eeg_createdata()
% and eeg_preclust(). A pop-function that calls this function is pop_clustedit().
% Usage:
% >> [STUDY] = std_plotcompmap(STUDY, ALLEEG, cluster, comps);
% Inputs:
% STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - global EEGLAB vector of EEG structures for the dataset(s) included in the STUDY.
% ALLEEG for a STUDY set is typically created using load_ALLEEG().
% cluster - single cluster number.
%
% Optional inputs:
% comps - [numeric vector] -> indices of the cluster components to plot.
% 'all' -> plot all the components in the cluster
% (as in std_topoplot). {default: 'all'}.
%
% Outputs:
% STUDY - the input STUDY set structure modified with plotted cluster scalp
% map mean, to allow quick replotting (unless cluster mean
% already existed in the STUDY).
%
% Example:
% >> cluster = 4; comps= [1 7 10];
% >> [STUDY] = std_plotcompmap(STUDY,ALLEEG, cluster, comps);
% Plots components 1, 7 & 10 scalp maps of cluster 4 on separate figures.
%
% See also pop_clustedit, pop_preclust, eeg_createdata, std_topoplot
%
% Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, June, 2005
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, June 07, 2005, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function STUDY = std_plotcompmap(STUDY, ALLEEG, cls, varargin)
icadefs;
if ~exist('cls')
error('std_plotcompmap: you must provide a cluster numberas an input.');
end
if isempty(cls)
error('std_plotcompmap: you must provide a cluster numberas an input.');
end
if nargin == 3 % no component indices were given
% Default: plot all components of the cluster
[STUDY] = std_topoplot(STUDY, ALLEEG, 'clusters', cls, 'mode', 'apart');
return
else
comp_ind = varargin{1};
end
STUDY = std_readtopoclust(STUDY,ALLEEG, cls);
for ci = 1:length(comp_ind)
abset = STUDY.datasetinfo(STUDY.cluster(cls).sets(1,comp_ind(ci))).index;
subject = STUDY.datasetinfo(STUDY.cluster(cls).sets(1,comp_ind(ci))).subject;
comp = STUDY.cluster(cls).comps(comp_ind(ci));
grid = STUDY.cluster(cls).topoall{comp_ind(ci)};
xi = STUDY.cluster(cls).topox;
yi = STUDY.cluster(cls).topoy;
[Xi,Yi] = meshgrid(yi,xi);
figure;
toporeplot(grid, 'style', 'both', 'plotrad',0.5,'intrad',0.5,'xsurface', Xi, 'ysurface', Yi, 'verbose', 'off');
title([subject ' / ' 'IC' num2str(comp) ', ' STUDY.cluster(cls).name ]);
set(gcf,'Color', BACKCOLOR);
colormap(DEFAULT_COLORMAP);
axcopy;
end
|
github
|
lcnhappe/happe-master
|
std_centroid.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_centroid.m
| 14,174 |
utf_8
|
f1be77fa82ecbcda91a416c38ccf6fb1
|
% std_centroid() - compute cluster centroid in EEGLAB dataset STUDY.
% Compute and store the centroid(s) (i.e., mean(s))
% for some combination of six measures on specified
% clusters in a STUDY. Possible measures include: scalp
% maps, ERPs, spectra, ERSPs, ITCs, dipole_locations
% Usage:
% >> [STUDY, centroid] = std_centroid(STUDY, ALLEEG, ...
% clusters, measure1, measure2, ...);
%
% Inputs:
% STUDY - STUDY set
% ALLEEG - ALLEEG dataset vector (else an EEG dataset) containing the STUDY
% datasets, typically created using load_ALLEEG().
% clusters - [vector] of cluster indices. Computes measure means for the
% specified clusters. {deffault|[]: compute means for all
% STUDY clusters}
% measure(s) - ['erp'|'spec'|'scalp'|'dipole'|'itc'|'ersp'].
% The measures(s) for which to calculate the cluster centroid(s):
% 'erp' -> mean ERP of each cluster.
% 'dipole' -> mean dipole of each cluster.
% 'spec' -> mean spectrum of each cluster (baseline removed).
% 'scalp' -> mean topoplot scalp map of each cluster.
% 'ersp' -> mean ERSP of each cluster.
% 'itc' -> mean ITC of each cluster.
% If [], re-compute the centroid for whichever centroids
% have previously been computed.
% Outputs:
% STUDY - input STUDY structure with computed centroids added.
% If the requested centroids already exist, overwites them.
% centroid - cell array of centroid structures, each cell corrasponding
% to a different cluster requested in 'clusters' (above).
% fields of 'centroid' may include centroid.erp, centroid.dipole,
% etc. (as above). The structure is similar as the output
% of the std_readdata() function (with some fields
% about the cluster name and index missing).
% Examples:
%
% >> [STUDY, centroid] = std_centroid(STUDY, ALLEEG,[], 'scalp');
% % For each of the clusters in STUDY, compute a mean scalp map.
% % The centroids are saved in the STUDY structure as entries in array
% % STUDY.cluster(k).centroid.scalp. The centroids are also returned in
% % a cell array the size of the clusters (i.e., in: centroid(k).scalp).
%
% >> [STUDY, centroid] = std_centroid(STUDY, ALLEEG,5,'spec','scalp');
% % Same as above, but now compute only two centroids for Cluster 5.
% % The returned 'centroid' has two fields: centroid.scalp and centroid.spec
%
% Authors: Hilit Serby & Arnaud Delorme, SCCN, INC, UCSD, Feb 03, 2005
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, Feb 03, 2005, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% Coding notes: Useful information on functions and global variables used.
function [STUDY, centroid] = std_centroid(STUDY,ALLEEG, clsind, varargin);
if nargin < 3
help std_centroid;
return
end
if isempty(clsind)
for k = 2: length(STUDY.cluster) %don't include the ParentCluster
if ~strncmpi('Notclust',STUDY.cluster(k).name,8)
% don't include 'Notclust' clusters
clsind = [clsind k];
end
end
end
%defult values
erpC =0;
specC =0 ;
scalpC = 0;
dipoleC = 0;
itcC = 0;
erspC = 0;
commands = {};
if isempty(varargin)
if isfield(STUDY.cluster(clsind(1)).centroid,'scalp')
commands{end+1} = 'scalp';
end
if isfield(STUDY.cluster(clsind(1)).centroid,'spec')
commands{end+1} = 'spec';
end
if isfield(STUDY.cluster(clsind(1)).centroid,'erp')
commands{end+1} = 'erp';
end
if isfield(STUDY.cluster(clsind(1)).centroid,'ersp')
commands{end+1} = 'ersp';
end
if isfield(STUDY.cluster(clsind(1)).centroid,'itc')
commands{end+1} = 'itc';
end
if isfield(STUDY.cluster(clsind(1)).centroid,'dipole')
commands{end+1} = 'dipole';
end
else
commands = varargin;
end
Ncond = length(STUDY.condition);
if Ncond == 0
Ncond = 1;
end
centroid = cell(length(clsind),1);
fprintf('Computing ');
for k = 1:length(clsind)
for l = 1:Ncond
for ind = 1:length(commands)
ctr = commands{ind};
switch ctr
case 'scalp'
centroid{k}.scalp = 0;
scalpC = 1;
if (l ==1) & (k ==1)
fprintf('scalp ');
end
case 'erp'
centroid{k}.erp{l} = 0;
erpC = 1;
if (l ==1) & (k ==1)
fprintf('erp ');
end
case 'spec'
centroid{k}.spec{l} = 0;
specC = 1;
if (l ==1) & (k ==1)
fprintf('spectrum ');
end
case 'ersp'
centroid{k}.ersp{l} = 0;
centroid{k}.ersp_limits{l} = 0;
erspC =1;
if (l ==1) & (k ==1)
fprintf('ersp ');
end
case 'itc'
centroid{k}.itc{l} = 0;
centroid{k}.itc_limits{l} = 0;
itcC = 1;
if (l ==1) & (k ==1)
fprintf('itc ');
end
case 'dipole'
dipoleC =1;
if (l ==1) & (k ==1)
fprintf('dipole ');
end
end
end
end
end
fprintf('centroid (only done once)\n');
if itcC | erspC | specC | erpC | scalpC
for clust = 1:length(clsind) %go over all requested clusters
for cond = 1:Ncond %compute for all conditions
for k = 1:length(STUDY.cluster(clsind(clust)).comps) % go through all components
comp = STUDY.cluster(clsind(clust)).comps(k);
abset = STUDY.cluster(clsind(clust)).sets(cond,k);
if scalpC & cond == 1 %scalp centroid, does not depend on condition
grid = std_readtopo(ALLEEG, abset, comp);
if isempty(grid)
return;
end
centroid{clust}.scalp = centroid{clust}.scalp + grid;
end
if erpC %erp centroid
[erp, t] = std_readerp(ALLEEG, abset, comp, STUDY.preclust.erpclusttimes);
fprintf('.');
if isempty(erp)
return;
end
if (cond==1) & (k==1)
all_erp = zeros(length(erp),length(STUDY.cluster(clsind(clust)).comps));
end
all_erp(:,k) = erp';
if k == length(STUDY.cluster(clsind(clust)).comps)
[all_erp pol] = std_comppol(all_erp);
centroid{clust}.erp{cond} = mean(all_erp,2);
centroid{clust}.erp_times = t;
end
end
if specC %spec centroid
[spec, f] = std_readspec(ALLEEG, abset, comp, STUDY.preclust.specclustfreqs);
fprintf('.');
if isempty(spec)
return;
end
centroid{clust}.spec{cond} = centroid{clust}.spec{cond} + spec;
centroid{clust}.spec_freqs = f;
end
if erspC %ersp centroid
fprintf('.');
if cond == 1
tmpabset = STUDY.cluster(clsind(clust)).sets(:,k);
[ersp, logfreqs, timevals] = std_readersp(ALLEEG, tmpabset, comp, STUDY.preclust.erspclusttimes, ...
STUDY.preclust.erspclustfreqs );
if isempty(ersp)
return;
end
for m = 1:Ncond
centroid{clust}.ersp{m} = centroid{clust}.ersp{m} + ersp(:,:,m);
centroid{clust}.ersp_limits{m} = max(floor(max(max(abs(ersp(:,:,m))))), centroid{clust}.ersp_limits{m});
end
centroid{clust}.ersp_freqs = logfreqs;
centroid{clust}.ersp_times = timevals;
end
end
if itcC %itc centroid
fprintf('.');
[itc, logfreqs, timevals] = std_readitc(ALLEEG, abset, comp, STUDY.preclust.erspclusttimes, ...
STUDY.preclust.erspclustfreqs );
if isempty(itc)
return;
end
centroid{clust}.itc{cond} = centroid{clust}.itc{cond} + itc;
centroid{clust}.itc_limits{cond} = max(floor(max(max(abs(itc)))), centroid{clust}.itc_limits{cond}); %ersp image limits
centroid{clust}.itc_freqs = logfreqs;
centroid{clust}.itc_times = timevals;
end
end
end
if ~scalpC
fprintf('\n');
end;
end
end
if dipoleC %dipole centroid
for clust = 1:length(clsind)
max_r = 0;
len = length(STUDY.cluster(clsind(clust)).comps);
tmppos = 0;
tmpmom = 0;
tmprv = 0;
ndip = 0;
for k = 1:len
fprintf('.');
comp = STUDY.cluster(clsind(clust)).comps(k);
abset = STUDY.cluster(clsind(clust)).sets(1,k);
if ~isfield(ALLEEG(abset), 'dipfit')
warndlg2(['No dipole information available in dataset ' num2str(abset) ], 'Aborting compute centroid dipole');
return;
end
if ~isempty(ALLEEG(abset).dipfit.model(comp).posxyz)
ndip = ndip +1;
tmppos = tmppos + ALLEEG(abset).dipfit.model(comp).posxyz;
tmpmom = tmpmom + ALLEEG(abset).dipfit.model(comp).momxyz;
tmprv = tmprv + ALLEEG(abset).dipfit.model(comp).rv;
if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')
if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model
load('-mat', ALLEEG(abset).dipfit.hdmfile);
max_r = max(max_r, max(vol.r));
else % old version of dipfit
max_r = max(max_r,max(ALLEEG(abset).dipfit.vol.r));
end
end
end
end
centroid{clust}.dipole.posxyz = tmppos/ndip;
centroid{clust}.dipole.momxyz = tmpmom/ndip;
centroid{clust}.dipole.rv = tmprv/ndip;
if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical') & (~isfield(ALLEEG(abset).dipfit, 'hdmfile')) %old dipfit
centroid{clust}.dipole.maxr = max_r;
end
STUDY.cluster(clsind(clust)).centroid.dipole = centroid{clust}.dipole;
end
end
%updat STUDY
for clust = 1:length(clsind) %go over all requested clusters
for cond = 1:Ncond
ncomp = length(STUDY.cluster(clsind(clust)).comps);
if scalpC & cond == 1%scalp centroid
centroid{clust}.scalp = centroid{clust}.scalp/ncomp;
STUDY.cluster(clsind(clust)).centroid.scalp = centroid{clust}.scalp ;
end
if erpC
STUDY.cluster(clsind(clust)).centroid.erp{cond} = centroid{clust}.erp{cond};
STUDY.cluster(clsind(clust)).centroid.erp_times = centroid{clust}.erp_times;
end
if specC
centroid{clust}.spec{cond} = centroid{clust}.spec{cond}/ncomp;
STUDY.cluster(clsind(clust)).centroid.spec{cond} = centroid{clust}.spec{cond};
STUDY.cluster(clsind(clust)).centroid.spec_freqs = centroid{clust}.spec_freqs;
end
if erspC %ersp centroid
centroid{clust}.ersp{cond} = centroid{clust}.ersp{cond}/ncomp;
STUDY.cluster(clsind(clust)).centroid.ersp{cond} = centroid{clust}.ersp{cond};
STUDY.cluster(clsind(clust)).centroid.ersp_limits{cond} = floor(0.75*centroid{clust}.ersp_limits{cond});
%[round(0.9*min(cell2mat({centroid{clust}.ersp_limits{cond,:}}))) round(0.9*max(cell2mat({centroid{clust}.ersp_limits{cond,:}})))];
STUDY.cluster(clsind(clust)).centroid.ersp_freqs = centroid{clust}.ersp_freqs;
STUDY.cluster(clsind(clust)).centroid.ersp_times = centroid{clust}.ersp_times;
end
if itcC
centroid{clust}.itc{cond} = centroid{clust}.itc{cond}/ncomp;
STUDY.cluster(clsind(clust)).centroid.itc{cond} = centroid{clust}.itc{cond} ;
STUDY.cluster(clsind(clust)).centroid.itc_limits{cond} = floor(0.75*centroid{clust}.itc_limits{cond});%round(0.9*max(cell2mat({centroid{clust}.itc_limits{cond,:}})));
STUDY.cluster(clsind(clust)).centroid.itc_freqs = centroid{clust}.itc_freqs;
STUDY.cluster(clsind(clust)).centroid.itc_times = centroid{clust}.itc_times;
end
end
end
fprintf('\n');
|
github
|
lcnhappe/happe-master
|
std_loadalleeg.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_loadalleeg.m
| 7,104 |
utf_8
|
377b0d5ee639622ea35859ef5af323cf
|
% std_loadalleeg() - constructs an ALLEEG structure, given the paths and file names
% of all the EEG datasets that will be loaded into the ALLEEG
% structure. The EEG datasets may be loaded without their EEG.data
% (see the pop_editoptions() function), so many datasets can be
% loaded simultaneously. The loaded EEG datasets have dataset
% information and a (filename) pointer to the data.
% Usage:
% % Load sseveral EEG datasets into an ALLEEG structure.
% >> ALLEEG = std_loadalleeg(paths,datasets) ;
% >> ALLEEG = std_loadalleeg(STUDY) ;
% Inputs:
% paths - [cell array of strings] cell array with all the datasets paths.
% datasets - [cell array of strings] cell array with all the datasets file names.
%
% Output:
% ALLEEG - an EEGLAB data structure, which holds the loaded EEG sets
% (can also be one EEG set).
% Example:
% >> paths = {'/home/eeglab/data/sub1/','/home/eeglab/data/sub2/', ...
% >> '/home/eeglab/data/sub3/', '/home/eeglab/data/sub6/'};
% >> datasets = { 'visattS1', 'visattS2', 'visattS3', 'visattS4'};
% >> ALLEEG = std_loadalleeg(paths,datasets) ;
%
% See also: pop_loadstudy(), pop_study()
%
% Authors: Hilit Serby, Arnaud Delorme, SCCN, INC, UCSD, October , 2004
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, October 11, 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
function ALLEEG = std_loadalleeg(varargin)
if nargin < 1
help std_loadalleeg;
return;
end;
genpath = '';
oldgenpath = '';
if isstruct(varargin{1})
datasets = {varargin{1}.datasetinfo.filename};
try,
paths = {varargin{1}.datasetinfo.filepath};
catch,
paths = cell(1,length(datasets));
paths(:) = { '' };
end;
genpath = varargin{1}.filepath;
if isfield(varargin{1}.etc, 'oldfilepath')
oldgenpath = varargin{1}.etc.oldfilepath;
end;
else
paths = varargin{1};
if nargin > 1
datasets = varargin{2};
else
datasets = paths;
paths = cell(size(datasets));
end;
end
set = 1;
ALLEEG = [];
eeglab_options;
% read datasets
% -------------
warnfold = 'off';
for dset = 1:length(paths)
if ~isempty(paths{dset})
comp = computer;
if paths{dset}(2) == ':' & ~strcmpi(comp(1:2), 'PC')
paths{dset} = [ filesep paths{dset}(4:end) ];
paths{dset}(find(paths{dset} == '\')) = filesep;
end;
end;
[sub2 sub1] = fileparts(char(paths{dset}));
[sub3 sub2] = fileparts(sub2);
% priority is given to relative path of the STUDY if STUDY has moved
if ~isequal(genpath, oldgenpath) && ~isempty(oldgenpath)
disp('Warning: STUDY moved since last saved, trying to load data files using relative path');
if ~isempty(strfind(char(paths{dset}), oldgenpath))
relativePath = char(paths{dset}(length(oldgenpath)+1:end));
relativePath = fullfile(genpath, relativePath);
else
disp('Important warning: relative path cannot calculated, make sure the correct data files are loaded');
relativePath = char(paths{dset});
end;
else
relativePath = char(paths{dset});
end;
% load data files
if exist(fullfile(relativePath, datasets{dset})) == 2
EEG = pop_loadset('filename', datasets{dset}, 'filepath', relativePath, 'loadmode', 'info', 'check', 'off');
elseif exist(fullfile(char(paths{dset}), datasets{dset})) == 2
EEG = pop_loadset('filename', datasets{dset}, 'filepath', char(paths{dset}), 'loadmode', 'info', 'check', 'off');
elseif exist( fullfile(genpath, datasets{dset})) == 2
[tmpp tmpf ext] = fileparts(fullfile(genpath, datasets{dset}));
EEG = pop_loadset('filename', [tmpf ext], 'filepath',tmpp, 'loadmode', 'info', 'check', 'off');
warnfold = 'on';
elseif exist( fullfile(genpath, sub1, datasets{dset})) == 2
[tmpp tmpf ext] = fileparts(fullfile(genpath, sub1, datasets{dset}));
EEG = pop_loadset('filename', [tmpf ext], 'filepath',tmpp, 'loadmode', 'info', 'check', 'off');
warnfold = 'on';
elseif exist( fullfile(genpath, sub2, datasets{dset})) == 2
[tmpp tmpf ext] = fileparts(fullfile(genpath, sub2, datasets{dset}));
EEG = pop_loadset('filename', [tmpf ext], 'filepath',tmpp, 'loadmode', 'info', 'check', 'off');
warnfold = 'on';
elseif exist( fullfile(genpath, sub2, sub1, datasets{dset})) == 2
[tmpp tmpf ext] = fileparts(fullfile(genpath, sub2, sub1, datasets{dset}));
EEG = pop_loadset('filename', [tmpf ext], 'filepath',tmpp, 'loadmode', 'info', 'check', 'off');
warnfold = 'on';
elseif exist(lower(fullfile(char(paths{dset}), datasets{dset}))) == 2
EEG = pop_loadset('filename', lower(datasets{dset}), 'filepath',lower(char(paths{dset})), 'loadmode', 'info', 'check', 'off');
else
txt = [ sprintf('The dataset %s is missing\n', datasets{dset}) 10 ...
'Is it possible that it might have been deleted?' 10 ...
'If this is the case, re-create the STUDY using the remaining datasets' ];
error(txt);
end;
EEG = eeg_checkset(EEG);
if ~option_storedisk
EEG = eeg_checkset(EEG, 'loaddata');
elseif ~isstr(EEG.data)
EEG.data = 'in set file';
EEG.icaact = [];
end;
[ALLEEG EEG] = eeg_store(ALLEEG, EEG, 0, 'notext');
end
ALLEEG = eeg_checkset(ALLEEG);
if strcmpi(warnfold, 'on') & ~strcmpi(pwd, genpath)
disp('Changing current path to STUDY path...');
cd(genpath);
end;
if strcmpi(warnfold, 'on')
disp('This STUDY has a relative path set for the datasets');
disp('so the current path MUST remain the STUDY path');
end;
|
github
|
lcnhappe/happe-master
|
std_propplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_propplot.m
| 8,354 |
utf_8
|
e7b216945a5dab56aa4be65b1672f850
|
% std_propplot() - Command line function to plot component cluster
% properties for a STUDY set.
% Displays mean cluster scalp map, ERP, ERSP;
% dipole model, spectrum, and ITC in one figure
% per cluster. Only meaasures computed during
% pre-clustering (by pop_preclust() or std_preclust())
% are plotted. Called by pop_clustedit().
% Leaves the plotted grand mean cluster measures
% in STUDY.cluster for quick replotting.
% Usage:
% >> [STUDY] = std_propplot(STUDY, ALLEEG, clusters);
% Inputs:
% STUDY - STUDY set including some or all EEG datasets in ALLEEG.
% ALLEEG - vector of EEG dataset structures including the datasets
% in the STUDY. Yypically created using load_ALLEEG().
%
% Optional inputs:
% clusters - [numeric vector | 'all'] -> cluster numbers to plot.
% Else 'all' -> make plots for all clusters in the STUDY
% {default: 'all'}.
% Outputs:
% STUDY - the input STUDY set structure modified with the plotted
% cluster mean properties to allow quick replotting (unless
% cluster means already existed in the STUDY).
% Example:
% % Plot mean properties of Cluster 5 in one figure.
% >> [STUDY] = std_propplot(STUDY,ALLEEG, 5);
%
% See also: pop_clustedit()
%
% Authors: Arnaud Delorme, Hilit Serby, Scott Makeig, SCCN/INC/UCSD, 2005
% 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 STUDY = std_propplot(STUDY, ALLEEG, varargin)
icadefs; % read EEGLAB defaults
warningon = 0;
if iscell(varargin{1}) % channel plotting
chans = varargin{1};
for k = 1: length(chans);
figure
orient tall
set(gcf,'Color', BACKCOLOR);
subplot(2,2,1),
try,
STUDY = std_erpplot(STUDY,ALLEEG, 'channels', chans(k), 'mode', 'together', 'plotmode', 'condensed' );
erpAxisHangle = gca;
catch
axis off; text(0.5, 0.5, 'No ERP information', 'horizontalalignment', 'center');
warningon = 1;
end
subplot(2,2,2),
try,
[STUDY] = std_erspplot(STUDY,ALLEEG, 'channels', chans(k), 'mode', 'together', 'plotmode', 'condensed' );
catch,
axis off; text(0.5, 0.5, 'No ERSP information', 'horizontalalignment', 'center');
warningon = 1;
end
subplot(2,2,3),
try,
STUDY = std_specplot(STUDY,ALLEEG, 'channels', chans(k), 'mode', 'together', 'plotmode', 'condensed');
catch
axis off; text(0.5, 0.5, 'No spectral information', 'horizontalalignment', 'center');
warningon = 1;
end
subplot(2,2,4),
try,
[STUDY] = std_itcplot(STUDY,ALLEEG, 'channels', chans(k), 'mode', 'together', 'plotmode', 'condensed' );
catch,
axis off; text(0.5, 0.5, 'No ITC information', 'horizontalalignment', 'center');
warningon = 1;
end
%subplot('position', [0.77 0.16 0.15 0.28]),
maintitle = ['Channel ''' chans{k} ''' average properties' ];
a = textsc(maintitle, 'title');
set(a, 'fontweight', 'bold');
if warningon
disp('Some properties could not be plotted. To plot these properties, first');
disp('include them in pre-clustering. There, specify 0 dimensions if you do');
disp('now want a property (scalp map, ERSP, etc...) to be included');
disp('in the clustering procedure. See the clustering tutorial.');
end;
end % Finished all conditions
return;
end;
% Set default values
cls = 1:length(STUDY.cluster); % plot all clusters in STUDY
if length(varargin) > 0
if length(varargin) == 1, varargin{2} = varargin{1}; end; % backward compatibility
if isnumeric(varargin{2})
cls = varargin{2};
elseif isstr(varargin{2}) & strcmpi(varargin{2}, 'all')
cls = 1:length(STUDY.cluster);
else
error('cluster input should be either a vector of cluster indices or the keyword ''all''.');
end
end
len = length(cls);
% Plot clusters mean properties
for k = 1: len
if k == 1
try
% optional 'CreateCancelBtn', 'delete(gcbf); error(''USER ABORT'');',
h_wait = waitbar(0,['Computing cluster properties ...'], 'Color', BACKEEGLABCOLOR,'position', [300, 200, 300, 48]);
catch % for Matlab 5.3
h_wait = waitbar(0,['Computing cluster properties ...'],'position', [300, 200, 300, 48]);
end
end
warningon = 0;
figure
orient tall
set(gcf,'Color', BACKCOLOR);
subplot(2,3,1),
try,
STUDY = std_topoplot(STUDY,ALLEEG, 'clusters', cls(k), 'mode', 'together', 'figure', 'off');
catch
axis off; text(0.5, 0.5, 'No scalp map information', 'horizontalalignment', 'center');
warningon = 1;
end
waitbar(k/(len*6),h_wait)
subplot(2,3,2),
try,
STUDY = std_erpplot(STUDY,ALLEEG, 'clusters', cls(k), 'mode', 'together', 'plotmode', 'condensed' );
erpAxisHangle = gca;
catch
axis off; text(0.5, 0.5, 'No ERP information', 'horizontalalignment', 'center');
warningon = 1;
end
waitbar((k*2)/(len*6),h_wait)
subplot(2,3,3),
try,
[STUDY] = std_erspplot(STUDY,ALLEEG, 'clusters', cls(k), 'mode', 'together', 'plotmode', 'condensed' );
catch,
axis off; text(0.5, 0.5, 'No ERSP information', 'horizontalalignment', 'center');
warningon = 1;
end
waitbar((k*3)/(len*6),h_wait)
axes('unit', 'normalized', 'position', [0.1 0.16 0.2 0.28]); %subplot(2,3,4),
try,
STUDY = std_dipplot(STUDY,ALLEEG, 'clusters', cls(k), 'mode', 'apart', 'figure', 'off'); set(gcf,'Color', BACKCOLOR);
catch
axis off; text(0.5, 0.5, 'No dipole information', 'horizontalalignment', 'center');
warningon = 1;
end
waitbar((k*4)/(len*6),h_wait)
subplot(2,3,5),
try,
STUDY = std_specplot(STUDY,ALLEEG, 'clusters', cls(k), 'mode', 'together', 'plotmode', 'condensed');
catch
axis off; text(0.5, 0.5, 'No spectral information', 'horizontalalignment', 'center');
warningon = 1;
end
waitbar((k*5)/(len*6),h_wait)
subplot(2,3,6),
try,
[STUDY] = std_itcplot(STUDY,ALLEEG, 'clusters', cls(k), 'mode', 'together', 'plotmode', 'condensed' );
catch,
axis off; text(0.5, 0.5, 'No ITC information', 'horizontalalignment', 'center');
warningon = 1;
end
waitbar((k*6)/(len*6),h_wait);
%subplot('position', [0.77 0.16 0.15 0.28]),
maintitle = ['Cluster ''' STUDY.cluster(cls(k)).name ''' mean properties (' num2str(length(STUDY.cluster(cls(k)).comps)) ' comps).' ];
a = textsc(maintitle, 'title');
set(a, 'fontweight', 'bold');
set(gcf,'name',maintitle);
if warningon
disp('Some properties could not be plotted. To plot these properties, first');
disp('include them in pre-clustering. There, specify 0 dimensions if you do');
disp('not want a property (scalp map, ERSP, etc...) to be included');
disp('in the clustering procedure. See the clustering tutorial.');
end;
end % Finished all conditions
if ishandle(erpAxisHangle) % make sure it is a valid graphics handle
legend(erpAxisHangle,'off');
set(erpAxisHangle,'YTickLabelMode','auto');
set(erpAxisHangle,'YTickMode','auto');
end;
delete(h_wait)
|
github
|
lcnhappe/happe-master
|
robust_kmeans.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/robust_kmeans.m
| 2,982 |
utf_8
|
b864201b216bd48106be885d09d04273
|
% robust_kmeans() - an extension of Matlab kmeans() that removes outlier
% components from all clusters.
% This is a helper function called from pop_clust().
function [IDX,C,sumd,D,outliers] = robust_kmeans(data,N,STD,MAXiter,method)
% data - pre-clustering data matrix.
% N - number of wanted clusters.
if nargin < 5
method = 'kmeans';
end;
flag = 1;
not_outliers = 1:size(data,1);
old_outliers = [];
if strcmpi(method, 'kmeans')
[IDX,C,sumd,D] = kmeans(data,N,'replicates',30,'emptyaction','drop'); % Cluster using K-means algorithm
else
[IDX,C,sumd,D] = kmeanscluster(data,N); % Cluster using K-means algorithm
end;
if STD >= 2 % STD for returned outlier
rSTD = STD -1;
else
rSTD = STD;
end
loop = 0;
while flag
loop = loop + 1;
std_all = [];
ref_D = 0;
for k = 1:N
tmp = ['cls' num2str(k) ' = find(IDX==' num2str(k) ')''; ' ]; %find the component indices belonging to each cluster (cls1 = ...).
eval(tmp);
tmp = ['std' num2str(k) ' = std(D(cls' num2str(k) ' ,' num2str(k) ')); ' ]; %compute the std of each cluster
eval(tmp);
std_all = [std_all ['std' num2str(k) ' ']];
tmp = [ 'ref_D = ' num2str(ref_D) ' + mean(D(cls' num2str(k) ' ,' num2str(k) '));' ];
eval(tmp);
end
std_all = [ '[ ' std_all ' ]' ];
std_all = eval(std_all);
% Find the outliers
% Outlier definition - its distance from its cluster center is bigger
% than STD times the std of the cluster, as long as the distance is bigger
% than the mean distance times STD (avoid problems where all points turn to be outliers).
outliers = [];
ref_D = ref_D/N;
for k = 1:N
tmp = ['cls' num2str(k) '(find(D(find(IDX==' num2str(k) ')'' , ' num2str(k) ') > ' num2str(STD) '*std' num2str(k) ')); ' ];
optionalO = eval(tmp);
Oind = find(D(optionalO,k) > ref_D*STD);
outliers = [outliers optionalO(Oind)];
end
if isempty(outliers) | (loop == MAXiter)
flag = 0;
end
l = length(old_outliers);
returned_outliers = [];
for k = 1:l
tmp = sum((C-ones(N,1)*data(old_outliers(k),:)).^2,2)'; % Find the distance of each former outlier to the current cluster
if isempty(find(tmp <= std_all*rSTD)) %Check if the outlier is still an outlier (far from each cluster center more than STD-1 times its std).
returned_outliers = [returned_outliers old_outliers(k)];
end;
end
outliers = not_outliers(outliers);
outliers = [outliers returned_outliers ];
tmp = ones(1,size(data,1));
tmp(outliers) = 0;
not_outliers = (find(tmp==1));
if strcmpi(method, 'kmeans')
[IDX,C,sumd,D] = kmeans(data(not_outliers,:),N,'replicates',30,'emptyaction','drop');
else
[IDX,C,sumd,D] = kmeanscluster(data(not_outliers,:),N);
end;
old_outliers = outliers;
old_IDX = zeros(size(data,1),1);
old_IDX(sort(not_outliers)) = IDX;
end
IDX = old_IDX;
|
github
|
lcnhappe/happe-master
|
std_interp.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_interp.m
| 6,657 |
utf_8
|
7117e3e4255231bb8538847cbb3531b2
|
% std_interp() - interpolate, if needed, a list of named data channels
% for all datasets included in a STUDY. Currently assumes
% that all channels have uniform locations across datasets.
%
% Usage: >> [STUDY ALLEEG] = std_interp(STUDY, ALLEEG, chans, method);
%
% Inputs:
% STUDY - EEGLAB STUDY structure
% ALLEEG - EEGLAB vector containing all EEG dataset structures in the STUDY.
% chans - [Cell array] cell array of channel names (labels) to interpolate
% into the data if they are missing from one of the datasets.
% method - [string] griddata() method to use for interpolation.
% See >> help eeg_interp() {default:'spherical'}
%
% Important limitation:
% This function currently presuposes that all datasets have the same channel
% locations (with various channels from a standard set possibly missing).
% If this is not the case, the interpolation will not be performed.
%
% Output:
% STUDY - study structure.
% ALLEEG - updated datasets.
%
% Author: Arnaud Delorme, CERCO, CNRS, August 2006-
%
% See also: eeg_interp()
% 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
% Deprecated:
% - [chanlocs structure] channel location structure containing
% a full channel structure (missing channels in the current
% dataset are interpolated).
function [STUDY, ALLEEG] = std_interp(STUDY, ALLEEG, chans, method);
if nargin < 2
help std_interp;
return;
end;
if nargin < 3
chans = [];
end;
if nargin < 4
method = 'spherical';
end;
% union of all channel structures
% -------------------------------
alllocs = eeg_mergelocs(ALLEEG.chanlocs);
% check electrode names to interpolate
% ------------------------------------
if iscell(chans)
alllabs = lower({ alllocs.labels });
for index = 1:length(chans)
tmpind = strmatch(lower(chans{index}), alllabs, 'exact');
if isempty(tmpind)
error( sprintf('Channel named ''%s'' not found in any dataset', chans{index}));
end;
end;
end;
% read all STUDY datasets and interpolate electrodes
% ---------------------------------------------------
for index = 1:length(STUDY.datasetinfo)
tmpind = STUDY.datasetinfo(index).index;
tmplocs = ALLEEG(tmpind).chanlocs;
% build electrode location structure for interpolation
% ----------------------------------------------------
[tmp tmp2 id1] = intersect_bc({tmplocs.labels}, {alllocs.labels});
if isempty(chans)
interplocs = alllocs;
elseif iscell(chans)
[tmp tmp2 id2] = intersect_bc( chans, {alllocs.labels});
interplocs = alllocs(union(id1, id2));
else
interplocs = chans;
end;
if length(interplocs) ~= length(tmplocs)
% search for position of electrode in backup structure
% ----------------------------------------------
extrachans = [];
if isfield(ALLEEG(tmpind).chaninfo, 'nodatchans')
if isfield(ALLEEG(tmpind).chaninfo.nodatchans, 'labels')
extrachans = ALLEEG(tmpind).chaninfo.nodatchans;
end;
end;
tmplabels = { tmplocs.labels };
for i=1:length(interplocs)
ind = strmatch( interplocs(i).labels, tmplabels, 'exact');
if ~isempty(ind)
interplocs(i) = tmplocs(ind); % this is necessary for polhemus
elseif ~isempty(extrachans)
ind = strmatch( interplocs(i).labels, { extrachans.labels }, 'exact');
if ~isempty(ind)
fprintf('Found position of %s in chaninfo structure\n', interplocs(i).labels);
interplocs(i) = extrachans(ind);
end;
end;
end;
% perform interpolation
% ---------------------
EEG = eeg_retrieve(ALLEEG, index);
EEG = eeg_checkset(EEG);
EEG = eeg_interp(EEG, interplocs, method);
EEG.saved = 'no';
EEG = pop_saveset(EEG, 'savemode', 'resave');
% update dataset in EEGLAB
% ------------------------
if isstr(ALLEEG(tmpind).data)
tmpdata = ALLEEG(tmpind).data;
[ ALLEEG EEG ] = eeg_store(ALLEEG, EEG, tmpind);
ALLEEG(tmpind).data = tmpdata;
ALLEEG(tmpind).saved = 'yes';
clear EEG;
else
[ ALLEEG EEG ] = eeg_store(ALLEEG, EEG, tmpind);
ALLEEG(tmpind).saved = 'yes';
end;
else
fprintf('No need for interpolation for dataset %d\n', tmpind);
end;
end;
function checkchans(STUDY, ALLEEG)
% Check to see if all the channels have the same coordinates
% (check only the theta field)
% ----------------------------------------------------------
for index = 1:length(STUDY.datasetinfo)
tmpind = STUDY.datasetinfo(index).index;
tmplocs = ALLEEG(tmpind).chanlocs;
[tmp id1 id2] = intersect_bc({tmplocs.labels}, {alllocs.labels});
for ind = 1:length(id1)
if tmplocs(id1(ind)).theta ~= alllocs(id2(ind)).theta
% find datasets with different coordinates
% ----------------------------------------
for ind2 = 1:length(STUDY.datasetinfo)
tmplocs2 = ALLEEG(ind2).chanlocs;
tmpmatch = strmatch(alllocs(id2(ind)).labels, { tmplocs2.labels }, 'exact');
if ~isempty(tmpmatch)
if alllocs(id2(ind)).theta == tmplocs2(tmpmatch).theta
datind = ind2;
break;
end;
end;
end;
error(sprintf( [ 'Dataset %d and %d do not have the same channel location\n' ...
'for electrode ''%s''' ], datind, tmpind, tmplocs(id1(ind)).labels));
end;
end;
end;
|
github
|
lcnhappe/happe-master
|
std_chaninds.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_chaninds.m
| 2,244 |
utf_8
|
f67a5b8ff7e1719881c3267bb7140eba
|
% std_chaninds() - look up channel indices in a STUDY
%
% Usage:
% >> inds = std_chaninds(STUDY, channames);
% >> inds = std_chaninds(EEG, channames);
% >> inds = std_chaninds(chanlocs, channames);
% Inputs:
% STUDY - studyset structure containing a changrp substructure.
% EEG - EEG structure containing channel location structure
% chanlocs - channel location structure
% channames - [cell] channel names
%
% Outputs:
% inds - [integer array] channel indices
%
% Author: Arnaud Delorme, CERCO, 2006-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function finalinds = std_chaninds(instruct, channames);
finalinds = [];
if isfield(instruct, 'chanlocs')
EEG = instruct;
tmpchanlocs = EEG.chanlocs;
tmpallchans = lower({ tmpchanlocs.labels });
elseif isfield(instruct, 'filename')
tmpallchans = lower({ instruct.changrp.name });
else
tmpallchans = instruct;
end;
if ~iscell(channames), channames = { channames }; end;
if isempty(channames), finalinds = [1:length(tmpallchans)]; return; end;
for c = 1:length(channames)
if isnumeric(channames)
chanind = channames(c);
else
chanind = strmatch( lower(channames{c}), tmpallchans, 'exact');
if isempty(chanind), warning(sprintf([ 'Channel "%s" and maybe others was not' 10 'found in pre-computed data file' ], channames{c})); end;
end;
finalinds = [ finalinds chanind ];
end;
|
github
|
lcnhappe/happe-master
|
pop_statparams.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/pop_statparams.m
| 24,437 |
utf_8
|
8a9b2a040c4a54b5cca5cf657871b47b
|
% pop_statparams() - helper function for pop_erspparams, pop_erpparams, and
% pop_specparams.
%
% Usage:
% >> struct = pop_statparams(struct, 'default');
% >> struct = pop_statparams(struct, 'key', 'val', ...);
%
% Inputs:
% struct - parameter structure. When called with the 'default'
% option only, the function creates all the fields in
% the structure and populate these fields with default
% values.
%
% Statistics options:
% 'groupstats' - ['on'|'off'] Compute statistics across subject
% groups {default: 'off'}
% 'condstats' - ['on'|'off'] Compute statistics across data
% conditions {default: 'off'}
% 'statistics' - ['param'|'perm'|'bootstrap'] Type of statistics to compute
% 'param' for parametric (t-test/anova); 'perm' for
% permutation-based and 'bootstrap' for bootstrap
% {default: 'param'}
% 'singletrials' - ['on'|'off'] use single trials to compute statistics.
% This requires the measure to be computed with the
% 'savetrials', 'on' option.
% 'mode' - ['eeglab'|'fieldtrip'] use either EEGLAB or Fieldtrip
% statistics.
%
% EEGLAB statistics:
% 'method' - ['param'|'perm'|'bootstrap'] statistical
% method. See help statcond for more information.
% 'naccu' - [integer] Number of surrogate data averages to use in
% surrogate statistics. For instance, if p<0.01,
% use naccu>200. For p<0.001, naccu>2000. If a 'threshold'
% (not NaN) is set below and 'naccu' is too low, it will
% be automatically increased. (This keyword is currently
% only modifiable from the command line, not from the gui).
% 'alpha' - [NaN|alpha] Significance threshold (0<alpha<<1). Value
% NaN will plot p-values for each time and/or frequency
% on a different axis. If alpha is used, significant time
% and/or frequency regions will be indicated either on
% a separate axis or (whenever possible) along with the
% data {default: NaN}
% 'mcorrect' - ['fdr'|'holms'|'bonferoni'|'none'] correction for multiple
% comparisons. 'fdr' uses false discovery rate. See the fdr
% function for more information. Defaut is
% none'.
%
% Fieldtrip statistics:
% 'fieldtripmethod' - ['analytic'|'montecarlo'] statistical
% method. See help statcond for more information.
% 'fieldtripnaccu' - [integer] Number of surrogate data averages to use in
% surrogate statistics.
% 'fieldtripalpha' - [alpha] Significance threshold (0<alpha<<1). This
% parameter is mandatory. Default is 0.05.
% 'fieldtripmcorrect' - ['cluster'|'max'|'fdr'|'holms'|'bonferoni'|'none']
% correction for multiple comparisons. See help
% ft_statistics_montecarlo for more information.
% 'fieldtripclusterparam - [string] parameters for clustering. See help
% ft_statistics_montecarlo for more information.
% 'fieldtripchannelneighbor - [struct] channel neighbor structure.
% 'fieldtripchannelneighborparam' - [string] parameters for channel
% neighbor. See help ft_statistics_montecarlo for more
% information.
%
% Legacy parameters:
% 'threshold' - now 'alpha'
% 'statistics' - now 'method'
%
% Authors: Arnaud Delorme, CERCO, CNRS, 2010-
% Copyright (C) Arnaud Delorme, 2010
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [STUDY, com] = pop_statparams(STUDY, varargin);
com = '';
if isfield(STUDY, 'etc')
if ~isfield(STUDY.etc, 'statistics') STUDY.etc.statistics = default_stats([]);
else STUDY.etc.statistics = default_stats(STUDY.etc.statistics);
end;
if length(varargin) == 1 && strcmpi(varargin{1}, 'default')
return;
end;
end;
if isempty(varargin) && ~isempty(STUDY)
if ~exist('ft_freqstatistics'), fieldtripInstalled = false; else fieldtripInstalled = true; end;
opt.enablecond = fastif(length(STUDY.design(STUDY.currentdesign).variable(1).value)>1, 'on', 'off');
opt.enablegroup = fastif(length(STUDY.design(STUDY.currentdesign).variable(2).value)>1, 'on', 'off');
opt.enablesingletrials = 'on';
% encode parameters
% -----------------
paramstruct = STUDY.etc.statistics;
eeglabStatvalues = { 'param' 'perm' 'bootstrap' };
fieldtripStatvalues = { 'analytic' 'montecarlo' };
mCorrectList = { 'none' 'bonferoni' 'holms' 'fdr' 'max' 'cluster' };
condstats = fastif(strcmpi(paramstruct.condstats, 'on'), 1, 0);
groupstats = fastif(strcmpi(paramstruct.groupstats,'on'), 1, 0);
statmode = fastif(strcmpi(paramstruct.singletrials,'on'), 1, 0);
eeglabThresh = fastif(isnan(paramstruct.eeglab.alpha),'exact', num2str(paramstruct.eeglab.alpha));
fieldtripThresh = fastif(isnan(paramstruct.fieldtrip.alpha),'exact', num2str(paramstruct.fieldtrip.alpha));
eeglabStat = strmatch(paramstruct.eeglab.method, eeglabStatvalues);
fieldtripStat = strmatch(paramstruct.fieldtrip.method, fieldtripStatvalues);
if isempty(eeglabStat) , error('Unknown statistical method for EEGLAB'); end;
if isempty(fieldtripStat), error('Unknown statistical method for Fieldtrip'); end;
eeglabRand = fastif(isempty(paramstruct.eeglab.naccu), 'auto', num2str(paramstruct.eeglab.naccu));
fieldtripRand = fastif(isempty(paramstruct.fieldtrip.naccu), 'auto', num2str(paramstruct.fieldtrip.naccu));
eeglabMcorrect = strmatch(paramstruct.eeglab.mcorrect, mCorrectList);
fieldtripMcorrect = strmatch(paramstruct.fieldtrip.mcorrect, mCorrectList);
fieldtripClust = paramstruct.fieldtrip.clusterparam;
fieldtripChan = paramstruct.fieldtrip.channelneighborparam;
combootstrap = [ 'warndlg2( strvcat(''Warning: bootstrap is selected. Bootstrap currently'',' ...
'''overestimates significance by a factor of 2 for paired data '',' ...
'''(unpaired data is working properly). You should use'',' ...
'''permutation instead of bootstrap if you have paired data.'') );' ];
cb_bootstrap = [ 'if get(gcbo, ''value'') == 3,' combootstrap ' end;' ];
cb_help_neighbor = 'pophelp(''ft_prepare_neighbours'');';
cb_help_cluster = 'pophelp(''ft_statistics_montecarlo'');';
cb_textSyntax = 'try, eval( [ ''{'' get(gcbo, ''string'') ''};'' ]); catch, warndlg2(''Syntax error''); end;';
if strcmpi(opt.enablecond , 'off') && condstats == 1, condstats = 0; end;
if strcmpi(opt.enablegroup, 'off') && groupstats == 1, groupstats = 0; end;
% callback for randomization selection
% ------------------------------------
cbSelectRandEeglab = [ 'set(findobj(gcbf, ''tag'', ''eeglabnaccu''), ''enable'', ''on'');' ...
'set(findobj(gcbf, ''tag'', ''eeglabnaccutext''),''enable'', ''on'');' ];
cbUnselectRandEeglab = [ 'set(findobj(gcbf, ''tag'', ''eeglabnaccu''), ''enable'', ''off'');' ...
'set(findobj(gcbf, ''tag'', ''eeglabnaccutext''),''enable'', ''off'');' ];
cbSelectRandFieldtrip = [ 'set(findobj(gcbf, ''tag'', ''fieldtripnaccu''), ''enable'', ''on'');' ...
'set(findobj(gcbf, ''tag'', ''fieldtripnaccutext''),''enable'', ''on'');' ];
cbUnselectRandFieldtrip = [ 'set(findobj(gcbf, ''tag'', ''fieldtripnaccu''), ''enable'', ''off'');' ...
'set(findobj(gcbf, ''tag'', ''fieldtripnaccutext''),''enable'', ''off'');' ];
cbSetFullMcorrectFieldtrip = 'set(findobj(gcbf, ''tag'', ''fieldtripmcorrect''), ''string'', ''Do not correct for multiple comparisons|Use Bonferoni correction|Use Holms correction|Use FDR correction|Use max correction|Use cluster correction (CC)'');';
cbUnsetFullMcorrectFieldtrip = 'set(findobj(gcbf, ''tag'', ''fieldtripmcorrect''), ''value'', min(4, get(findobj(gcbf, ''tag'', ''fieldtripmcorrect''), ''value'')), ''string'', ''Do not correct for multiple comparisons|Use Bonferoni correction|Use Holms correction|Use FDR correction'');';
cb_eeglab_statlist = [ 'if get(findobj(gcbf, ''tag'', ''stateeglab'' ),''value'') > 1,' cbSelectRandEeglab ',else,' cbUnselectRandEeglab ',end;' ];
cb_fieldtrip_statlist = [ 'if get(findobj(gcbf, ''tag'', ''statfieldtrip'' ),''value'') > 1,' cbSelectRandFieldtrip cbSetFullMcorrectFieldtrip ',else,' cbUnselectRandFieldtrip cbUnsetFullMcorrectFieldtrip ',end;' ];
% callback for activating clusters inputs
% ---------------------------------------
cb_select_cluster = [ 'set(findobj(gcbf, ''tag'', ''clustertext1''),''enable'', ''on'');' ...
'set(findobj(gcbf, ''tag'', ''clustertext2''),''enable'', ''on'');' ...
'set(findobj(gcbf, ''tag'', ''clusterhelp1''),''enable'', ''on'');' ...
'set(findobj(gcbf, ''tag'', ''clusterhelp2''),''enable'', ''on'');' ...
'set(findobj(gcbf, ''tag'', ''clusterchan'' ),''enable'', ''on'');' ...
'set(findobj(gcbf, ''tag'', ''clusterstat'' ),''enable'', ''on'');' ];
cb_unselect_cluster = [ 'set(findobj(gcbf, ''tag'', ''clustertext1''),''enable'', ''off'');' ...
'set(findobj(gcbf, ''tag'', ''clustertext2''),''enable'', ''off'');' ...
'set(findobj(gcbf, ''tag'', ''clusterhelp1''),''enable'', ''off'');' ...
'set(findobj(gcbf, ''tag'', ''clusterhelp2''),''enable'', ''off'');' ...
'set(findobj(gcbf, ''tag'', ''clusterchan'' ),''enable'', ''off'');' ...
'set(findobj(gcbf, ''tag'', ''clusterstat'' ),''enable'', ''off'');' ];
cb_fieldtrip_mcorrect = [ cb_fieldtrip_statlist 'if get(findobj(gcbf, ''tag'', ''fieldtripmcorrect'' ),''value'') == 6,' cb_select_cluster ',else,' cb_unselect_cluster ',end;' cb_fieldtrip_statlist]; % cb_fieldtrip_statlist repeated on purpose
% callback for activating eeglab/fieldtrip
% ----------------------------------------
enable_eeglab = [ 'set(findobj(gcbf, ''userdata'', ''eeglab'') ,''enable'', ''on'');' ...
'set(findobj(gcbf, ''userdata'', ''fieldtrip''),''enable'', ''off'');' ...
'set(findobj(gcbf, ''tag'', ''but_eeglab'') ,''value'', 1);' ...
'set(findobj(gcbf, ''tag'', ''but_fieldtrip''),''value'', 0);' cb_eeglab_statlist ];
enable_fieldtrip=[ 'if get(findobj(gcbf, ''tag'', ''condstats''), ''value'') && get(findobj(gcbf, ''tag'', ''groupstats''), ''value''),' ...
enable_eeglab ...
'warndlg2(strvcat(''Switching to EEGLAB statistics since'',''Fieldtrip cannot perform 2-way statistics''));' ...
'else,' ...
' set(findobj(gcbf, ''userdata'', ''eeglab'') ,''enable'', ''off'');' ...
' set(findobj(gcbf, ''userdata'', ''fieldtrip''),''enable'', ''on'');' ...
' set(findobj(gcbf, ''tag'', ''but_fieldtrip''),''value'', 1);' ...
' set(findobj(gcbf, ''tag'', ''but_eeglab'') ,''value'', 0);' cb_fieldtrip_mcorrect ...
'end;'];
cb_select_fieldtrip = [ 'if get(findobj(gcbf, ''tag'', ''but_fieldtrip''),''value''),' enable_fieldtrip ',else,' enable_eeglab ',end;' ];
cb_select_eeglab = [ 'if get(findobj(gcbf, ''tag'', ''but_eeglab''),''value''),,' enable_eeglab ',else,' enable_fieldtrip ',end;' ];
if strcmpi(paramstruct.mode, 'eeglab'), evalstr = enable_eeglab;
else evalstr = enable_fieldtrip;
end;
inds = findstr('gcbf', evalstr);
evalstr(inds+2) = [];
% special case if Fieldtrip is not installed
if ~fieldtripInstalled
strFieldtrip = 'Use Fieldtrip statistics (to use install "Fieldtrip-lite" using File > Manage EEGLAB extensions)';
fieldtripEnable = 'off';
cb_select_eeglab = 'set(findobj(gcbf, ''tag'', ''but_eeglab''),''value'', 1)';
else
strFieldtrip = 'Use Fieldtrip statistics';
fieldtripEnable = 'on';
end;
opt.uilist = { ...
{'style' 'text' 'string' 'General statistical parameters' 'fontweight' 'bold' } ...
{} {'style' 'checkbox' 'string' 'Compute 1st independent variable statistics' 'value' condstats 'enable' opt.enablecond 'callback' cb_select_fieldtrip 'tag' 'condstats' } ...
{} {'style' 'checkbox' 'string' 'Compute 2nd independent variable statistics' 'value' groupstats 'enable' opt.enablegroup 'callback' cb_select_fieldtrip 'tag' 'groupstats' } ...
{} {'style' 'checkbox' 'string' 'Use single trials (when available)' 'value' statmode 'tag' 'singletrials' 'enable' opt.enablesingletrials } ...
{} ...
{'style' 'checkbox' 'string' 'Use EEGLAB statistics' 'fontweight' 'bold' 'tag' 'but_eeglab' 'callback' cb_select_eeglab } ...
{} {'style' 'popupmenu' 'string' 'Use parametric statistics|Use permutation statistics|Use bootstrap statistics' 'tag' 'stateeglab' 'value' eeglabStat 'listboxtop' eeglabStat 'callback' [ cb_eeglab_statlist cb_bootstrap ] 'userdata' 'eeglab' } ...
{'style' 'text' 'string' 'Statistical threshold (p-value)' 'userdata' 'eeglab'} ...
{'style' 'edit' 'string' eeglabThresh 'tag' 'eeglabalpha' 'userdata' 'eeglab' } ...
{} {'style' 'popupmenu' 'string' 'Do not correct for multiple comparisons|Use Bonferoni correction|Use Holms correction|Use FDR correction' 'value' eeglabMcorrect 'listboxtop' eeglabMcorrect 'tag' 'eeglabmcorrect' 'userdata' 'eeglab' } ...
{'style' 'text' 'string' ' Randomization (n)' 'userdata' 'eeglab' 'tag' 'eeglabnaccutext' } ...
{'style' 'edit' 'string' eeglabRand 'userdata' 'eeglab' 'tag' 'eeglabnaccu' } ...
{} ...
{'style' 'checkbox' 'string' strFieldtrip 'enable' fieldtripEnable 'fontweight' 'bold' 'tag' 'but_fieldtrip' 'callback' cb_select_fieldtrip } ...
{} {'style' 'popupmenu' 'string' 'Use analytic/parametric statistics|Use montecarlo/permutation statistics' 'tag' 'statfieldtrip' 'value' fieldtripStat 'listboxtop' fieldtripStat 'callback' cb_fieldtrip_mcorrect 'userdata' 'fieldtrip' } ...
{'style' 'text' 'string' 'Statistical threshold (p-value)' 'userdata' 'fieldtrip' } ...
{'style' 'edit' 'string' fieldtripThresh 'tag' 'fieldtripalpha' 'userdata' 'fieldtrip' } ...
{} {'style' 'popupmenu' 'string' 'Do not correct for multiple comparisons|Use Bonferoni correction|Use Holms correction|Use FDR correction|Use max correction|Use cluster correction (CC)' 'tag' 'fieldtripmcorrect' 'value' fieldtripMcorrect 'listboxtop' fieldtripMcorrect 'callback' cb_fieldtrip_mcorrect 'userdata' 'fieldtrip' } ...
{'style' 'text' 'string' ' Randomization (n)' 'userdata' 'fieldtrip' 'tag' 'fieldtripnaccutext' } ...
{'style' 'edit' 'string' fieldtripRand 'userdata' 'fieldtrip' 'tag' 'fieldtripnaccu' } ...
{} {'style' 'text' 'string' 'CC channel neighbor parameters' 'userdata' 'fieldtrip' 'tag' 'clustertext1' } ...
{ 'style' 'edit' 'string' fieldtripChan 'userdata' 'fieldtrip' 'tag' 'clusterchan' 'callback' cb_textSyntax } ...
{ 'style' 'pushbutton' 'string' 'help' 'callback' cb_help_neighbor 'userdata' 'fieldtrip' 'tag' 'clusterhelp1' } ...
{} {'style' 'text' 'string' 'CC clustering parameters' 'userdata' 'fieldtrip' 'tag' 'clustertext2' } ...
{ 'style' 'edit' 'string' fieldtripClust 'userdata' 'fieldtrip' 'tag' 'clusterstat' 'callback' cb_textSyntax } ...
{ 'style' 'pushbutton' 'string' 'help' 'callback' cb_help_cluster 'userdata' 'fieldtrip' 'tag' 'clusterhelp2' } ...
};
if eeglabStat == 3,
eval(combootstrap);
end;
cbline = [0.07 1.1];
otherline = [ 0.7 0.6 .5];
eeglabline = [ 0.7 0.6 .5];
opt.geometry = { [1] cbline cbline cbline [1] [1] [0.07 0.51 0.34 0.13] [0.07 0.6 0.25 0.13] ...
[1] [1] [0.07 0.51 0.34 0.13] [0.07 0.6 0.25 0.13] [0.13 0.4 0.4 0.1] [0.13 0.4 0.4 0.1] };
[out_param userdat tmp res] = inputgui( 'geometry' , opt.geometry, 'uilist', opt.uilist, ...
'title', 'Set statistical parameters -- pop_statparams()','eval', evalstr);
if isempty(res), return; end;
% decode paramters
% ----------------
if res.groupstats, res.groupstats = 'on'; else res.groupstats = 'off'; end;
if res.condstats , res.condstats = 'on'; else res.condstats = 'off'; end;
if res.singletrials, res.singletrials = 'on'; else res.singletrials = 'off'; end;
res.eeglabalpha = str2num(res.eeglabalpha);
res.fieldtripalpha = str2num(res.fieldtripalpha);
if isempty(res.eeglabalpha) ,res.eeglabalpha = NaN; end;
if isempty(res.fieldtripalpha),res.fieldtripalpha = NaN; end;
res.stateeglab = eeglabStatvalues{res.stateeglab};
res.statfieldtrip = fieldtripStatvalues{res.statfieldtrip};
res.eeglabmcorrect = mCorrectList{res.eeglabmcorrect};
res.fieldtripmcorrect = mCorrectList{res.fieldtripmcorrect};
res.mode = fastif(res.but_eeglab, 'eeglab', 'fieldtrip');
res.eeglabnaccu = str2num(res.eeglabnaccu);
if ~isstr(res.fieldtripnaccu) || ~strcmpi(res.fieldtripnaccu, 'all')
res.fieldtripnaccu = str2num(res.fieldtripnaccu);
end;
% build command call
% ------------------
options = {};
if strcmp(res.stateeglab, 'param' ) && exist('fcdf') ~= 2
fprintf(['statcond(): EEGLAB parametric testing requires fcdf() \n' ...
' from the Matlab Statstical Toolbox. Running\n' ...
' nonparametric permutation tests instead.\n']);
res.stateeglab = 'perm';
end
if ~strcmpi( res.groupstats, paramstruct.groupstats), options = { options{:} 'groupstats' res.groupstats }; end;
if ~strcmpi( res.condstats , paramstruct.condstats ), options = { options{:} 'condstats' res.condstats }; end;
if ~strcmpi( res.singletrials, paramstruct.singletrials ), options = { options{:} 'singletrials' res.singletrials }; end;
if ~strcmpi( res.mode , paramstruct.mode), options = { options{:} 'mode' res.mode }; end; % statistics
if ~isequal( res.eeglabnaccu , paramstruct.eeglab.naccu), options = { options{:} 'naccu' res.eeglabnaccu }; end;
if ~strcmpi( res.stateeglab , paramstruct.eeglab.method), options = { options{:} 'method' res.stateeglab }; end; % statistics
if ~strcmpi( res.eeglabmcorrect , paramstruct.eeglab.mcorrect), options = { options{:} 'mcorrect' res.eeglabmcorrect }; end;
if ~isequal( res.fieldtripnaccu , paramstruct.fieldtrip.naccu), options = { options{:} 'fieldtripnaccu' res.fieldtripnaccu }; end;
if ~strcmpi( res.statfieldtrip , paramstruct.fieldtrip.method), options = { options{:} 'fieldtripmethod' res.statfieldtrip }; end;
if ~strcmpi( res.fieldtripmcorrect , paramstruct.fieldtrip.mcorrect), options = { options{:} 'fieldtripmcorrect' res.fieldtripmcorrect }; end;
if ~strcmpi( res.clusterstat , paramstruct.fieldtrip.clusterparam), options = { options{:} 'fieldtripclusterparam' res.clusterstat }; end;
if ~strcmpi( res.clusterchan , paramstruct.fieldtrip.channelneighborparam), options = { options{:} 'fieldtripchannelneighborparam' res.clusterchan }; end;
if ~(isnan(res.eeglabalpha(1)) && isnan(paramstruct.eeglab.alpha(1))) && ~isequal(res.eeglabalpha, paramstruct.eeglab.alpha) % threshold
options = { options{:} 'alpha' res.eeglabalpha };
end;
if ~(isnan(res.fieldtripalpha(1)) && isnan(paramstruct.fieldtrip.alpha(1))) && ~isequal(res.fieldtripalpha, paramstruct.fieldtrip.alpha) % threshold
options = { options{:} 'fieldtripalpha' res.fieldtripalpha };
end;
if ~isempty(options)
STUDY = pop_statparams(STUDY, options{:});
com = sprintf('STUDY = pop_statparams(STUDY, %s);', vararg2str( options ));
end;
else
% interpret parameters
% --------------------
if isfield(STUDY, 'etc')
paramstruct = STUDY.etc.statistics; isstudy = true;
else paramstruct = STUDY;
if isempty(paramstruct), paramstruct = default_stats([]); end;
isstudy = false;
end;
if isempty(varargin) || strcmpi(varargin{1}, 'default')
paramstruct = default_stats(paramstruct);
else
for index = 1:2:length(varargin)
v = varargin{index};
if strcmpi(v, 'statistics'), v = 'method'; end; % backward compatibility
if strcmpi(v, 'threshold' ), v = 'alpha'; end; % backward compatibility
if strcmpi(v, 'alpha') || strcmpi(v, 'method') || strcmpi(v, 'naccu') || strcmpi(v, 'mcorrect')
paramstruct = setfield(paramstruct, 'eeglab', v, varargin{index+1});
elseif ~isempty(findstr('fieldtrip', v))
v2 = v(10:end);
paramstruct = setfield(paramstruct, 'fieldtrip', v2, varargin{index+1});
if strcmpi(v2, 'channelneighborparam')
paramstruct.fieldtrip.channelneighbor = []; % reset neighbor matrix if parameter change
end;
else
if (~isempty(paramstruct) && ~isempty(strmatch(v, fieldnames(paramstruct), 'exact'))) || ~isstudy
paramstruct = setfield(paramstruct, v, varargin{index+1});
end;
end;
end;
end;
if isfield(STUDY, 'etc')
STUDY.etc.statistics = paramstruct;
else STUDY = paramstruct;
end;
end;
% default parameters
% ------------------
function paramstruct = default_stats(paramstruct)
if ~isfield(paramstruct, 'groupstats'), paramstruct.groupstats = 'off'; end;
if ~isfield(paramstruct, 'condstats' ), paramstruct.condstats = 'off'; end;
if ~isfield(paramstruct, 'singletrials' ), paramstruct.singletrials = 'off'; end;
if ~isfield(paramstruct, 'mode' ), paramstruct.mode = 'eeglab'; end;
if ~isfield(paramstruct, 'eeglab'), paramstruct.eeglab = []; end;
if ~isfield(paramstruct, 'fieldtrip'), paramstruct.fieldtrip = []; end;
if ~isfield(paramstruct.eeglab, 'naccu'), paramstruct.eeglab.naccu = []; end;
if ~isfield(paramstruct.eeglab, 'alpha' ), paramstruct.eeglab.alpha = NaN; end;
if ~isfield(paramstruct.eeglab, 'method'), paramstruct.eeglab.method = 'param'; end;
if ~isfield(paramstruct.eeglab, 'mcorrect'), paramstruct.eeglab.mcorrect = 'none'; end;
if ~isfield(paramstruct.fieldtrip, 'naccu'), paramstruct.fieldtrip.naccu = []; end;
if ~isfield(paramstruct.fieldtrip, 'method'), paramstruct.fieldtrip.method = 'analytic'; end;
if ~isfield(paramstruct.fieldtrip, 'alpha'), paramstruct.fieldtrip.alpha = NaN; end;
if ~isfield(paramstruct.fieldtrip, 'mcorrect'), paramstruct.fieldtrip.mcorrect = 'none'; end;
if ~isfield(paramstruct.fieldtrip, 'clusterparam'), paramstruct.fieldtrip.clusterparam = '''clusterstatistic'',''maxsum'''; end;
if ~isfield(paramstruct.fieldtrip, 'channelneighbor'), paramstruct.fieldtrip.channelneighbor = []; end;
if ~isfield(paramstruct.fieldtrip, 'channelneighborparam'), paramstruct.fieldtrip.channelneighborparam = '''method'',''triangulation'''; end;
if strcmpi(paramstruct.eeglab.mcorrect, 'benferoni'), paramstruct.eeglab.mcorrect = 'bonferoni'; end;
if strcmpi(paramstruct.eeglab.mcorrect, 'no'), paramstruct.eeglab.mcorrect = 'none'; end;
if strcmpi(paramstruct.fieldtrip.mcorrect, 'no'), paramstruct.fieldtrip.mcorrect = 'none'; end;
|
github
|
lcnhappe/happe-master
|
std_maketrialinfo.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_maketrialinfo.m
| 5,118 |
utf_8
|
4ca496b66ab94b2ec129cd988851b1d7
|
% std_maketrialinfo() - create trial information structure using the
% .epoch structure of EEGLAB datasets
%
% Usage:
% >> STUDY = std_maketrialinfo(STUDY, ALLEEG);
%
% Inputs:
% STUDY - EEGLAB STUDY set
% ALLEEG - vector of the EEG datasets included in the STUDY structure
%
% Inputs:
% STUDY - EEGLAB STUDY set updated. The fields which is created or
% updated is STUDY.datasetinfo.trialinfo
%
% Authors: Arnaud Delorme, SCCN/INC/UCSD, April 2010
% Copyright (C) Arnaud Delorme [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function STUDY = std_maketrialinfo(STUDY, ALLEEG);
%% test if .epoch field exist in ALLEEG structure
epochfield = cellfun(@isempty, { ALLEEG.epoch });
if any(epochfield)
fprintf('Warning: some datasets are continuous and trial information cannot be created\n');
return;
end;
%% check if conversion of event is necessary
ff = {};
flagConvert = true;
for index = 1:length(ALLEEG), ff = union(ff, fieldnames(ALLEEG(index).event)); end;
for iField = 1:length(ff)
fieldChar = zeros(1,length(ALLEEG))*NaN;
for index = 1:length(ALLEEG)
if isfield(ALLEEG(index).event, ff{iField})
if ischar(ALLEEG(index).event(1).(ff{iField}))
fieldChar(index) = 1;
else fieldChar(index) = 0;
end;
end;
end;
if ~all(fieldChar(~isnan(fieldChar)) == 1) && ~all(fieldChar(~isnan(fieldChar)) == 0)
% need conversion to char
for index = 1:length(ALLEEG)
if fieldChar(index) == 0
if flagConvert, disp('Warning: converting some event fields to strings - this may be slow'); flagConvert = false; end;
for iEvent = 1:length(ALLEEG(index).event)
ALLEEG(index).event(iEvent).(ff{iField}) = num2str(ALLEEG(index).event(iEvent).(ff{iField}));
end;
end;
end;
end
end;
%% Make trial info
for index = 1:length(ALLEEG)
tmpevent = ALLEEG(index).event;
eventlat = abs(eeg_point2lat( [ tmpevent.latency ], [ tmpevent.epoch ], ALLEEG(index).srate, [ALLEEG(index).xmin ALLEEG(index).xmax]));
events = ALLEEG(index).event;
ff = fieldnames(events);
ff = setdiff_bc(ff, { 'latency' 'urevent' 'epoch' });
trialinfo = [];
% process time locking event fields
% ---------------------------------
indtle = find(eventlat == 0);
epochs = [ events(indtle).epoch ];
extractepoch = true;
% Double checking and changing threshold
if length(epochs) < ALLEEG(index).trials
indtle = find(eventlat < 0.02);
epochs = [ events(indtle).epoch ];
end
if length(epochs) ~= ALLEEG(index).trials
% special case where there are not the same number of time-locking
% event as there are data epochs
if length(unique(epochs)) ~= ALLEEG(index).trials
extractepoch = false;
disp('std_maketrialinfo: not the same number of time-locking events as trials, trial info ignored');
else
% pick one event per epoch
[tmp tmpind] = unique_bc(epochs(end:-1:1)); % reversing the array ensures the first event gets picked
tmpind = length(epochs)+1-tmpind;
indtle = indtle(tmpind);
if length(indtle) ~= ALLEEG(index).trials
extractepoch = false;
disp('std_maketrialinfo: not the same number of time-locking events as trials, trial info ignored');
end;
end;
end;
if extractepoch
commands = {};
for f = 1:length(ff)
eval( [ 'eventvals = {events(indtle).' ff{f} '};' ]);
%if isnumeric(eventvals{1})
% eventvals = cellfun(@num2str, eventvals, 'uniformoutput', false);
%end;
commands = { commands{:} ff{f} eventvals };
end;
trialinfo = struct(commands{:});
STUDY.datasetinfo(index).trialinfo = trialinfo;
end;
% % same as above but 10 times slower
% for e = 1:length(ALLEEG(index).event)
% if eventlat(e) < 0.0005 % time locking event only
% epoch = events(e).epoch;
% for f = 1:length(ff)
% fieldval = getfield(events, {e}, ff{f});
% trialinfo = setfield(trialinfo, {epoch}, ff{f}, fieldval);
% end;
% end;
% end;
end;
|
github
|
lcnhappe/happe-master
|
std_topo.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_topo.m
| 5,582 |
utf_8
|
1b9b523a881bf168a2748a5049883851
|
% std_topo() - uses topoplot() to get the interpolated Cartesian grid of the
% specified component topo maps. The topo map grids are saved
% into a (.icatopo) file and a pointer to the file is stored
% in the EEG structure. If such a file already exists,
% loads the information from it.
%
% Returns the topo map grids of all the requested components. Also
% returns the EEG sub-structure etc (i.e EEG.etc), which is modified
% with a pointer to the float file and some information about the file.
% Usage:
% >> X = std_topo(EEG, components, option);
%
% % Returns the ICA topo map grid for a dataset.
% % Updates the EEG structure in the Matlab environment and re-saves
% Inputs:
% EEG - an EEG dataset structure.
% components - [numeric vector] components in the EEG structure to compute topo maps
% {default|[] -> all}
% option - ['gradient'|'laplacian'|'none'] compute gradient or laplacian of
% the scale topography. This does not acffect the saved file which is
% always 'none' {default is 'none' = the interpolated topo map}
% Optional inputs
% 'recompute' - ['on'|'off'] force recomputing topo file even if it is
% already on disk.
% 'fileout' - [string] Path of the folder to save output. The default
% is EEG.filepath
% Outputs:
% X - the topo map grid of the requested ICA components, each grid is
% one ROW of X.
%
% File output: [dataset_name].icatopo
%
% Authors: Hilit Serby, Arnaud Delorme, SCCN, INC, UCSD, January, 2005
%
% See also topoplot(), std_erp(), std_ersp(), std_spec(), std_preclust()
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, October 11, 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
function [X] = std_topo(EEG, comps, option, varargin)
if nargin < 1
help std_topo;
return;
end;
if isfield(EEG,'icaweights')
numc = size(EEG.icaweights,1);
else
error('EEG.icaweights not found');
end
if nargin < 2
comps = 1:numc;
elseif isempty(comps)
comps = 1:numc;
end
if nargin < 3
option = 'none';
end;
g = finputcheck( varargin, { 'recompute' 'string' { 'on','off' } 'off' ;...
'fileout' 'string' [] EEG.filepath},...
'std_topo');
% if isstr(g), error(g); end;
% figure; toporeplot(grid,'style', 'both','plotrad', 0.5, 'intrad', 0.5, 'xsurface' ,Xi, 'ysurface',Yi );
% Topo information found in dataset
% ---------------------------------
if exist(fullfile(g.fileout, [ EEG.filename(1:end-3) 'icatopo' ])) && strcmpi(g.recompute, 'off')
for k = 1:length(comps)
tmp = std_readtopo( EEG, 1, comps(k));
if strcmpi(option, 'gradient')
[tmpx, tmpy] = gradient(tmp); %Gradient
tmp = [tmpx(:); tmpy(:)]';
elseif strcmpi(option, 'laplacian')
tmp = del2(tmp); %Laplacian
tmp = tmp(:)';
else
tmp = tmp(:)';
end;
tmp = tmp(find(~isnan(tmp)));
if k == 1
X = zeros(length(comps),length(tmp)) ;
end
X(k,:) = tmp;
end
return
end
all_topos = [];
for k = 1:numc
% compute topo map grid (topoimage)
% ---------------------------------
chanlocs = EEG.chanlocs(EEG.icachansind);
if isempty( [ chanlocs.theta ] )
error('Channel locations are required for computing scalp topographies');
end;
[hfig grid plotrad Xi Yi] = topoplot( EEG.icawinv(:,k), chanlocs, ...
'verbose', 'off',...
'electrodes', 'on' ,'style','both',...
'plotrad',0.55,'intrad',0.55,...
'noplot', 'on', 'chaninfo', EEG.chaninfo);
all_topos = setfield(all_topos, [ 'comp' int2str(k) '_grid' ], grid);
all_topos = setfield(all_topos, [ 'comp' int2str(k) '_x' ] , Xi(:,1));
all_topos = setfield(all_topos, [ 'comp' int2str(k) '_y' ] , Yi(:,1));
end
% Save topos in file
% ------------------
all_topos.datatype = 'TOPO';
tmpfile = fullfile( g.fileout, [ EEG.filename(1:end-3) 'icatopo' ]);
std_savedat(tmpfile, all_topos);
for k = 1:length(comps)
tmp = getfield(all_topos, [ 'comp' int2str(comps(k)) '_grid' ]);
if strcmpi(option, 'gradient')
[tmpx, tmpy] = gradient(tmp); % Gradient
tmp = [tmpx(:); tmpy(:)]';
elseif strcmpi(option, 'laplacian')
tmp = del2(tmp); % Laplacian
tmp = tmp(:)';
else
tmp = tmp(:)';
end;
tmp = tmp(find(~isnan(tmp)));
if k == 1
X = zeros(length(comps),length(tmp)) ;
end
X(k,:) = tmp;
end
|
github
|
lcnhappe/happe-master
|
std_stat.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_stat.m
| 11,198 |
utf_8
|
5f23c07e5c7ae572b7612768a93018be
|
% std_stat() - compute statistics for ERP/spectral traces or ERSP/ITC images
% of a component or channel cluster in a STUDY.
% Usage:
% >> [pcond, pgroup, pinter, statscond, statsgroup, statsinter] = std_stat( data, 'key', 'val', ...)
% Inputs:
% data - [cell array] mean data for each subject group and/or data
% condition. For example, to compute mean ERPs statistics from a
% STUDY for epochs of 800 frames in two conditions from three
% groups of 12 subjects:
%
% >> data = { [800x12] [800x12] [800x12];... % 3 groups, cond 1
% [800x12] [800x12] [800x12] }; % 3 groups, cond 2
% >> pcond = std_stat(data, 'condstats', 'on');
%
% By default, parametric statistics are computed across subjects
% in the three groups. See below and >> help statcond
% for more information about the statistical computations.
%
% Statistics options (EEGLAB):
% 'groupstats' - ['on'|'off'] Compute (or not) statistics across groups.
% {default: 'off'}
% 'condstats' - ['on'|'off'] Compute (or not) statistics across groups.
% {default: 'off'}
% 'method' - ['parametric'|'permutation'] Type of statistics to use
% default is 'parametric'. 'perm' and 'param' legacy
% abreviations are still functional.
% 'naccu' - [integer] Number of surrogate averages fo accumulate when
% computing permutation-based statistics. For example, to
% test p<0.01 use naccu>=200; for p<0.001, use naccu>=2000.
% If a non-NaN 'threshold' is set (see below) and 'naccu'
% is too low, it will be automatically increased. This
% keyword available only from the command line {default:500}
% 'alpha' - [NaN|p-value] threshold for computing p-value. In this
% function, it is only used to compute naccu above. NaN
% means that no threshold has been set.
% 'mcorrect' - ['none'|'fdr'] apply correcting for multiple comparisons.
% 'mode' - ['eeglab'|'fieldtrip'] statistical framework to use.
% 'eeglab' uses EEGLAB statistical functions and 'fieldtrip'
% uses Fieldtrip statistical funcitons. Default is 'eeglab'.
%
% Fieldtrip statistics options:
% 'fieldtripnaccu' - 'numrandomization' Fieldtrip parameter
% 'fieldtripalpha' - 'alpha' Fieldtrip parameter. Default is 0.05.
% 'fieldtripmethod' - 'method' Fieldtrip parameter. Default is 'analytic'
% 'fieldtripmcorrect' - 'mcorrect' Fieldtrip parameter. Default is 'none'.
% 'fieldtripclusterparam' - string or cell array for optional parameters
% for cluster correction method, see function
% ft_statistics_montecarlo for more information.
% 'fieldtripchannelneighbor' - Fieldtrip channel neighbour structure for
% cluster correction method, see function
% std_prepare_neighbors for more information.
% Legacy parameters:
% 'threshold' - now 'alpha'
% 'statistics' - now 'method'
%
% Outputs:
% pcond - [cell] condition pvalues or mask (0 or 1) if an alpha value
% is selected. One element per group.
% pgroup - [cell] group pvalues or mask (0 or 1). One element per
% condition.
% pinter - [cell] three elements, condition pvalues (group pooled),
% group pvalues (condition pooled) and interaction pvalues.
% statcond - [cell] condition statistic values (F or T).
% statgroup - [cell] group pvalues or mask (0 or 1). One element per
% condition.
% statinter - [cell] three elements, condition statistics (group pooled),
% group statistics (condition pooled) and interaction F statistics.
%
% Author: Arnaud Delorme, CERCO, CNRS, 2006-
%
% See also: statcond()
% 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 [pcond, pgroup, pinter, statscond, statsgroup, statsinter] = std_stat(data, varargin)
pgroup = {};
pcond = {};
pinter = {};
if nargin < 1
help std_stat;
return;
end;
% decode inputs
% -------------
if ~isempty(varargin) && isstruct(varargin{1})
opt = varargin{1};
varargin(1) = [];
else
opt = [];
end;
if ~isempty(varargin) ||isempty(opt);
opt = pop_statparams(opt, varargin{:});
end;
if ~isfield(opt, 'paired'), opt.paired = { 'off' 'off' }; end;
if ~isnan(opt.eeglab.alpha(1)) && isempty(opt.eeglab.naccu), opt.eeglab.naccu = 1/opt.eeglab.alpha(end)*2; end;
if any(any(cellfun('size', data, 2)==1)), opt.groupstats = 'off'; opt.condstats = 'off'; end;
if strcmpi(opt.eeglab.mcorrect, 'fdr'), opt.eeglab.naccu = opt.eeglab.naccu*20; end;
if isempty(opt.eeglab.naccu), opt.eeglab.naccu = 2000; end;
if ~isreal(data{1})
fprintf('*** ITC significance - converting complex values to absolute amplitude ***\n');
for ind = 1:length(data(:))
data{ind} = abs(data{ind});
end;
end;
nc = size(data,1);
ng = size(data,2);
% compute significance mask
% -------------------------
pcond = {};
pgroup = {};
pinter = {};
statscond = {};
statsgroup = {};
statsinter = {};
if strcmpi(opt.mode, 'eeglab')
% EEGLAB statistics
% -----------------
if strcmpi(opt.condstats, 'on') && nc > 1
for g = 1:ng
[F df pval] = statcond(data(:,g), 'method', opt.eeglab.method, 'naccu', opt.eeglab.naccu, 'paired', opt.paired{1});
pcond{g} = squeeze(pval);
statscond{g} = squeeze(F);
end;
end;
if strcmpi(opt.groupstats, 'on') && ng > 1
for c = 1:nc
[F df pval] = statcond(data(c,:), 'method', opt.eeglab.method, 'naccu', opt.eeglab.naccu, 'paired', opt.paired{2});
pgroup{c} = squeeze(pval);
statsgroup{c} = squeeze(F);
end;
else
end;
if ( strcmpi(opt.groupstats, 'on') && strcmpi(opt.condstats, 'on') ) & ng > 1 & nc > 1
opt.paired = sort(opt.paired); % put 'off' first if present
[F df pval] = statcond(data, 'method', opt.eeglab.method, 'naccu', opt.eeglab.naccu, 'paired', opt.paired{1});
for index = 1:length(pval)
pinter{index} = squeeze(pval{index});
statsinter{index} = squeeze(F{index});
end;
end;
if ~isempty(opt.groupstats) || ~isempty(opt.condstats)
if ~strcmpi(opt.eeglab.mcorrect, 'none'),
disp([ 'Applying ' upper(opt.eeglab.mcorrect) ' correction for multiple comparisons' ]);
for ind = 1:length(pcond), pcond{ind} = mcorrect( pcond{ind} , opt.eeglab.mcorrect ); end;
for ind = 1:length(pgroup), pgroup{ind} = mcorrect( pgroup{ind}, opt.eeglab.mcorrect ); end;
if ~isempty(pinter),
pinter{1} = mcorrect(pinter{1}, opt.eeglab.mcorrect);
pinter{2} = mcorrect(pinter{2}, opt.eeglab.mcorrect);
pinter{3} = mcorrect(pinter{3}, opt.eeglab.mcorrect);
end;
end;
if ~isnan(opt.eeglab.alpha)
for ind = 1:length(pcond), pcond{ind} = applythreshold(pcond{ind}, opt.eeglab.alpha); end;
for ind = 1:length(pgroup), pgroup{ind} = applythreshold(pgroup{ind}, opt.eeglab.alpha); end;
for ind = 1:length(pinter), pinter{ind} = applythreshold(pinter{ind}, opt.eeglab.alpha); end;
end;
end;
else
if ~exist('ft_freqstatistics'), error('Install Fieldtrip-lite to use Fieldtrip statistics'); end;
% Fieldtrip statistics
% --------------------
params = {};
if strcmpi(opt.fieldtrip.mcorrect, 'cluster')
params = eval( [ '{' opt.fieldtrip.clusterparam '}' ]);
if isempty(opt.fieldtrip.channelneighbor), opt.fieldtrip.channelneighbor = struct([]); end;
params = { params{:} 'neighbours' opt.fieldtrip.channelneighbor }; % channelneighbor is empty if only one channel selected
end;
params = { params{:} 'method', opt.fieldtrip.method, 'naccu', opt.fieldtrip.naccu 'mcorrect' opt.fieldtrip.mcorrect 'alpha' opt.fieldtrip.alpha 'numrandomization' opt.fieldtrip.naccu };
params = { params{:} 'structoutput' 'on' }; % before if ~isnan(opt.fieldtrip.alpha), end;
if strcmpi(opt.condstats, 'on') && nc > 1
for g = 1:ng
[F df pval] = statcondfieldtrip(data(:,g), 'paired', opt.paired{1}, params{:});
pcond{g} = applymask( F, opt.fieldtrip);
statscond{g} = squeeze(F.stat);
end;
else
pcond = {};
end;
if strcmpi(opt.groupstats, 'on') && ng > 1
for c = 1:nc
[F df pval] = statcondfieldtrip(data(c,:), 'paired', opt.paired{2}, params{:});
pgroup{c} = applymask( F, opt.fieldtrip);
statsgroup{c} = squeeze(F.stat);
end;
else
pgroup = {};
end;
if ( strcmpi(opt.groupstats, 'on') && strcmpi(opt.condstats, 'on') ) & ng > 1 & nc > 1
opt.paired = sort(opt.paired); % put 'off' first if present
[F df pval] = statcondfieldtrip(data, 'paired', opt.paired{1}, params{:});
for index = 1:length(pval)
pinter{index} = applymask(F{inter}, opt.fieldtrip);
statsinter{index} = squeeze(F.stat{index});
end;
else
pinter = {};
end;
end;
% apply mask for fieldtrip data
% -----------------------------
function p = applymask(F, fieldtrip)
if ~isnan(fieldtrip.alpha), p = squeeze(F.mask);
else
p = squeeze(F.pval);
if ~strcmpi(fieldtrip.mcorrect, 'none')
p(~F.mask) = 1;
end;
end;
% apply stat threshold to data for EEGLAB stats
% ---------------------------------------------
function newdata = applythreshold(data, threshold)
threshold = sort(threshold);
newdata = zeros(size(data));
for index = 1:length(threshold)
inds = data < threshold(index);
data(inds) = 1;
newdata(inds) = length(threshold)-index+1;
end;
% compute correction for multiple comparisons
% -------------------------------------------
function pvals = mcorrect(pvals, method);
switch method
case {'no' 'none'}, return;
case 'bonferoni', pvals = pvals*prod(size(pvals));
case 'holms', [tmp ind] = sort(pvals(:)); [tmp ind2] = sort(ind); pvals(:) = pvals(:).*(prod(size(pvals))-ind2+1);
case 'fdr', pvals = fdr(pvals);
otherwise error(['Unknown method ''' method ''' for correction for multiple comparisons' ]);
end;
|
github
|
lcnhappe/happe-master
|
std_selcomp.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_selcomp.m
| 3,156 |
utf_8
|
00aa637c4e0c27267077e0bd01c2d8c6
|
% std_selcomp() - Helper function for std_erpplot(), std_specplot()
% and std_erspplot() to select specific
% components prior to plotting.
% Usage:
% >> std_selcomp( STUDY, data, cluster, setinds, compinds, comps)
%
% Inputs:
% STUDY - EEGLAB STUDY structure.
% data - [cell array] mean data for each subject group and/or data
% condition. For example, to compute mean ERPs statistics from a
% STUDY for epochs of 800 frames in two conditions from three
% groups of 12 subjects,
% >> data = { [800x12] [800x12] [800x12];... % 3 groups, cond 1
% [800x12] [800x12] [800x12] }; % 3 groups, cond 2
% cluster - [integer] cluster index
% setinds - [cell array] set indices for each of the last dimension of the
% data cell array.
% >> setinds = { [12] [12] [12];... % 3 groups, cond 1
% [12] [12] [12] }; % 3 groups, cond 2
% compinds - [cell array] component indices for each of the last dimension
% of the data cell array.
% >> compinds = { [12] [12] [12];... % 3 groups, cond 1
% [12] [12] [12] }; % 3 groups, cond 2
% comps - [integer] find and select specific component index in array
%
% Output:
% data - [cell array] data array with the subject or component selected
% subject - [string] subject name (for component selection)
% comp_names - [cell array] component names (for component selection)
%
% Author: Arnaud Delorme, CERCO, CNRS, 2006-
%
% See also: std_erpplot(), std_specplot() and std_erspplot()
function [data, subject, comp_names] = std_selcomp(STUDY, data, clust, setinds, compinds, compsel)
if nargin < 2
help std_selcomp;
return;
end;
optndims = ndims(data{1});
comp_names = {};
subject = '';
% find and select group
% ---------------------
if isempty(compsel), return; end;
sets = STUDY.cluster(clust).sets(:,compsel);
comps = STUDY.cluster(clust).comps(compsel);
%grp = STUDY.datasetinfo(sets(1)).group;
%grpind = strmatch( grp, STUDY.group );
%if isempty(grpind), grpind = 1; end;
%data = data(:,grpind);
% find component
% --------------
for c = 1:length(data(:))
rminds = 1:size(data{c},optndims);
for ind = length(compinds{c}):-1:1
setindex = STUDY.design(STUDY.currentdesign).cell(setinds{c}(ind)).dataset;
if compinds{c}(ind) == comps && any(setindex == sets)
rminds(ind) = [];
end;
end;
if optndims == 2
data{c}(:,rminds) = []; %2-D
elseif optndims == 3
data{c}(:,:,rminds) = []; %3-D
else
data{c}(:,:,:,rminds) = []; %3-D
end;
comp_names{c,1} = comps;
end;
% for c = 1:size(data,1)
% for ind = 1:length(compinds{1,grpind})
% if compinds{1,grpind}(ind) == comps & any(setinds{1,grpind}(ind) == sets)
% if optndims == 2
% data{c} = data{c}(:,ind);
% else data{c} = data{c}(:,:,ind);
% end;
% comp_names{c,1} = comps;
% end;
% end;
% end;
subject = STUDY.datasetinfo(sets(1)).subject;
|
github
|
lcnhappe/happe-master
|
neural_net.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/neural_net.m
| 507 |
utf_8
|
0511a54c57462633b86130c890cfbb4d
|
% neural_net() - computes clusters using Matlab Neural Net toolbox.
% Alternative clustering algorithm to kmeans().
% This is a helper function called from pop_clust().
function [IDX,C] = neural_net(clustdata,clus_num)
nmin = min(clustdata);
nmax = max(clustdata);
net = newc([nmin ;nmax].',clus_num);
net = train(net,(clustdata).');
Y = sim(net,(clustdata).');
IDX = vec2ind(Y);
C = zeros(clus_num,size(clustdata,2));
for k = 1:clus_num
C(k,:) = sum(clustdata(find(IDX == k),:));
end
|
github
|
lcnhappe/happe-master
|
std_spec.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_spec.m
| 17,403 |
utf_8
|
0785a60da38cc843ec475bdac86f8574
|
% std_spec() - Returns the ICA component spectra for a dataset. Updates the EEG structure
% in the Matlab environment and in the .set file as well. Saves the spectra
% in a file.
% Usage:
% >> [spec freqs] = std_spec(EEG, 'key', 'val', ...);
%
% Computes the mean spectra of the activites of specified components of the
% supplied dataset. The spectra are saved in a Matlab file. If such a file
% already exists, loads the spectral information from this file.
% Options (below) specify which components to use, and the desired frequency
% range. There is also an option to specify other spectopo() input variables
% (see >> help spectopo for details).
%
% Returns the removed mean spectra of the selected ICA components in the
% requested frequency range. If the spectra were computed previously but a
% different frequency range is selected, there is an overwrite option.
% so. The function will load previously computed log spectra, if any, and
% will remove the mean from the requested frequency range. The frequencies
% vector is also returned.
% Inputs:
% EEG - a loaded epoched EEG dataset structure.
%
% Optional inputs:
% 'components' - [numeric vector] components of the EEG structure for which
% activation spectrum will be computed. Note that because
% computation of ERP is so fast, all components spectrum are
% computed and saved. Only selected component
% are returned by the function to Matlab
% {default|[] -> all}
% 'channels' - [cell array] channels of the EEG structure for which
% activation spectrum will be computed. Note that because
% computation of ERP is so fast, all channels spectrum are
% computed and saved. Only selected channels
% are returned by the function to Matlab
% {default|[] -> none}
% 'recompute' - ['on'|'off'] force recomputing ERP file even if it is
% already on disk.
% 'trialindices' - [cell array] indices of trials for each dataset.
% Default is all trials.
% 'recompute' - ['on'|'off'] force recomputing data file even if it is
% already on disk.
% 'rmcomps' - [integer array] remove artifactual components (this entry
% is ignored when plotting components). This entry contains
% the indices of the components to be removed. Default is none.
% 'interp' - [struct] channel location structure containing electrode
% to interpolate ((this entry is ignored when plotting
% components). Default is no interpolation.
% 'fileout' - [string] name of the file to save on disk. The default
% is the same name (with a different extension) as the
% dataset given as input.
% 'savetrials' - ['on'|'off'] save single-trials ERSP. Requires a lot of disk
% space (dataset space on disk times 10) but allow for refined
% single-trial statistics.
%
% spectrum specific optional inputs:
% 'specmode' - ['psd'|'fft'|'pburg'|'pmtm'] method to compute spectral
% decomposition. 'psd' uses the spectopo function (optional
% parameters to this function may be given as input). 'fft'
% uses a simple fft on each trial. For continuous data
% data trials are extracted automatically (see 'epochlim'
% and 'epochrecur' below). Two experimental modes are
% 'pmtm' and 'pbug' which use multitaper and the Burg
% method to compute spectrum respectively. NOTE THAT SOME
% OF THESE OPTIONS REQUIRE THE SIGNAL PROCESSING TOOLBOX.
% 'epochlim' - [min max] for FFT on continuous data, extract data
% epochs with specific epoch limits in seconds (see also
% 'epochrecur' below). Default is [0 1].
% 'epochrecur' - [float] for FFT on continuous data, set the automatic
% epoch extraction recurence interval (default is 0.5 second).
% 'timerange' - [min max] use data within a specific time range before
% computing the data spectrum. For instance, for evoked
% data trials, it is recommended to use the baseline time
% period.
% 'logtrials' - ['on'|'off'] compute single-trial log transform before
% averaging them. Default is 'off' for 'psd' specmode and
% 'on' for 'fft' specmode.
% 'continuous' - ['on'|'off'] force epoch data to be treated as
% continuous so small data epochs can be extracted for the
% 'fft' specmode option. Default is 'off'.
% 'freqrange' - [minhz maxhz] frequency range (in Hz) within which to
% return the spectrum {default|[]: [0 sample rate/2]}.
% Note that this does not affect the spectrum computed on
% disk, only the data returned by this function as output.
% 'nw' - [integer] number of tapers for the 'pmtm' spectral
% method. Default is 4.
% 'burgorder' - [integet] order for the Burg spectral method.
%
% Other optional spectral parameters:
% All optional parameters to the spectopo function may be provided to this
% function as well (requires the 'specmode' option above to be set to
% 'psd').
%
% Outputs:
% spec - the mean spectra (in dB) of the requested ICA components in the selected
% frequency range (with the mean of each spectrum removed).
% freqs - a vector of frequencies at which the spectra have been computed.
%
% Files output or overwritten for ICA:
% [dataset_filename].icaspec, % raw spectrum of ICA components
% Files output or overwritten for data:
% [dataset_filename].datspec,
%
% See also spectopo(), std_erp(), std_ersp(), std_map(), std_preclust()
%
% Authors: Arnaud Delorme, SCCN, INC, UCSD, January, 2005
% Defunct: 0 -> if frequency range is different from saved spectra, ask via a
% pop-up window whether to keep existing spectra or to overwrite them.
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 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
function [X, f, overwrt] = std_spec(EEG, varargin)
overwrt = 1; % deprecated
if nargin < 1
help std_spec;
return;
end;
% decode inputs
% -------------
if ~isempty(varargin)
if ~isstr(varargin{1})
varargin = { varargin{:} [] [] };
if all(varargin{1} > 0)
options = { 'components' varargin{1} 'freqrange' varargin{2} };
else
options = { 'channels' -varargin{1} 'freqrange' varargin{2} };
end;
else
options = varargin;
end;
else
options = varargin;
end;
[g spec_opt] = finputcheck(options, { 'components' 'integer' [] [];
'channels' 'cell' {} {};
'timerange' 'float' [] [];
'specmode' 'string' {'fft','psd','pmtm','pburg'} 'psd';
'recompute' 'string' { 'on','off' } 'off';
'savetrials' 'string' { 'on','off' } 'off';
'continuous' 'string' { 'on','off' } 'off';
'logtrials' 'string' { 'on','off' 'notset' } 'notset';
'savefile' 'string' { 'on','off' } 'on';
'epochlim' 'real' [] [0 1];
'trialindices' { 'integer','cell' } [] [];
'epochrecur' 'real' [] 0.5;
'rmcomps' 'cell' [] cell(1,length(EEG));
'nw' 'float' [] 4;
'fileout' 'string' [] '';
'burgorder' 'integer' [] 20;
'interp' 'struct' { } struct([]);
'nfft' 'integer' [] [];
'freqrange' 'real' [] [] }, 'std_spec', 'ignore');
if isstr(g), error(g); end;
if isfield(EEG,'icaweights')
numc = size(EEG(1).icaweights,1);
else
error('EEG.icaweights not found');
end
if isempty(g.components)
g.components = 1:numc;
end
EEG_etc = [];
% filename
% --------
if isempty(g.fileout), g.fileout = fullfile(EEG(1).filepath, EEG(1).filename(1:end-4)); end;
if ~isempty(g.channels)
filename = [ g.fileout '.datspec'];
prefix = 'chan';
else
filename = [ g.fileout '.icaspec'];
prefix = 'comp';
end;
% SPEC information found in datasets
% ---------------------------------
if exist(filename) & strcmpi(g.recompute, 'off')
fprintf('File "%s" found on disk, no need to recompute\n', filename);
setinfo.filebase = g.fileout;
if strcmpi(prefix, 'comp')
[X tmp f] = std_readfile(setinfo, 'components', g.components, 'freqlimits', g.freqrange, 'measure', 'spec');
else
[X tmp f] = std_readfile(setinfo, 'channels', g.channels, 'freqlimits', g.freqrange, 'measure', 'spec');
end;
if ~isempty(X), return; end;
end
% No SPEC information found
% -------------------------
options = {};
if ~isempty(g.rmcomps), options = { options{:} 'rmcomps' g.rmcomps }; end;
if ~isempty(g.interp), options = { options{:} 'interp' g.interp }; end;
if isempty(g.channels)
[X boundaries] = eeg_getdatact(EEG, 'component', [1:size(EEG(1).icaweights,1)], 'trialindices', g.trialindices );
else [X boundaries] = eeg_getdatact(EEG, 'trialindices', g.trialindices, 'rmcomps', g.rmcomps, 'interp', g.interp);
end;
if ~isempty(boundaries) && boundaries(end) ~= size(X,2), boundaries = [boundaries size(X,2)]; end;
% get specific time range for epoched and continuous data
% -------------------------------------------------------
oritrials = EEG.trials;
if ~isempty(g.timerange)
if oritrials > 1
timebef = find(EEG(1).times >= g.timerange(1) & EEG(1).times < g.timerange(2) );
X = X(:,timebef,:);
EEG(1).pnts = length(timebef);
else
disp('warning: ''timerange'' option cannot be used with continuous data');
end;
end;
% extract epochs if necessary
% ---------------------------
if ~strcmpi(g.specmode, 'psd')
if EEG(1).trials == 1 || strcmpi(g.continuous, 'on')
TMP = EEG(1);
TMP.data = X;
TMP.icaweights = [];
TMP.icasphere = [];
TMP.icawinv = [];
TMP.icaact = [];
TMP.icachansind = [];
TMP.trials = size(TMP.data,3);
TMP.pnts = size(TMP.data,2);
TMP.event = [];
TMP.epoch = [];
for index = 1:length(boundaries)
TMP.event(index).type = 'boundary';
TMP.event(index).latency = boundaries(index);
end;
TMP = eeg_checkset(TMP);
if TMP.trials > 1
TMP = eeg_epoch2continuous(TMP);
end;
TMP = eeg_regepochs(TMP, g.epochrecur, g.epochlim);
disp('Warning: continuous data, extracting 1-second epochs');
X = TMP.data;
end;
end;
% compute spectral decomposition
% ------------------------------
if strcmpi(g.logtrials, 'notset'), if strcmpi(g.specmode, 'fft') g.logtrials = 'on'; else g.logtrials = 'off'; end; end;
if strcmpi(g.logtrials, 'on'), datatype = 'SPECTRUMLOG'; else datatype = 'SPECTRUMABS'; end;
if strcmpi(g.specmode, 'psd')
if strcmpi(g.savetrials, 'on') || strcmpi(g.logtrials, 'on')
for iTrial = 1:size(X,3)
[XX(:,:,iTrial), f] = spectopo(X(:,:,iTrial), size(X,2), EEG(1).srate, 'plot', 'off', 'boundaries', boundaries, 'nfft', g.nfft, spec_opt{:});
if iTrial == 1, XX(:,:,size(X,3)) = 0; end;
end;
if strcmpi(g.logtrials, 'off')
X = 10.^(XX/10);
else X = XX;
end;
if strcmpi(g.savetrials, 'off')
X = mean(X,3);
end;
else
[X, f] = spectopo(X, size(X,2), EEG(1).srate, 'plot', 'off', 'boundaries', boundaries, 'nfft', g.nfft, spec_opt{:});
X = 10.^(X/10);
end;
elseif strcmpi(g.specmode, 'pmtm')
if strcmpi(g.logtrials, 'on')
error('Log trials option cannot be used in conjunction with the PMTM option');
end;
if all([ EEG.trials ] == 1) && ~isempty(boundaries), disp('Warning: multitaper does not take into account boundaries in continuous data'); end;
fprintf('Computing spectrum using multitaper method:');
for cind = 1:size(X,1)
fprintf('.');
for tind = 1:size(X,3)
[tmpdat f] = pmtm(X(cind,:,tind), g.nw, g.nfft, EEG.srate);
if cind == 1 && tind == 1
X2 = zeros(size(X,1), length(tmpdat), size(X,3));
end;
X2(cind,:,tind) = tmpdat;
end;
end;
fprintf('\n');
X = X2;
if strcmpi(g.savetrials, 'off'), X = mean(X,3); end;
elseif strcmpi(g.specmode, 'pburg')
if strcmpi(g.logtrials, 'on')
error('Log trials option cannot be used in conjunction with the PBURB option');
end;
fprintf('Computing spectrum using Burg method:');
if all([ EEG.trials ] == 1) && ~isempty(boundaries), disp('Warning: pburg does not take into account boundaries in continuous data'); end;
for cind = 1:size(X,1)
fprintf('.');
for tind = 1:size(X,3)
[tmpdat f] = pburg(X(cind,:,tind), g.burgorder, g.nfft, EEG.srate);
if cind == 1 && tind == 1
X2 = zeros(size(X,1), length(tmpdat), size(X,3));
end;
X2(cind,:,tind) = tmpdat;
end;
end;
fprintf('\n');
X = X2;
if strcmpi(g.savetrials, 'off'), X = mean(X,3); end;
else % fft mode
if oritrials == 1 || strcmpi(g.continuous, 'on')
X = bsxfun(@times, X, hamming(size(X,2))');
end;
if all([ EEG.trials ] == 1) && ~isempty(boundaries), disp('Warning: fft does not take into account boundaries in continuous data'); end;
tmp = fft(X, g.nfft, 2);
f = linspace(0, EEG(1).srate/2, floor(size(tmp,2)/2));
f = f(2:end); % remove DC (match the output of PSD)
tmp = tmp(:,2:floor(size(tmp,2)/2),:);
X = tmp.*conj(tmp);
if strcmpi(g.logtrials, 'on'), X = 10*log10(X); end;
if strcmpi(g.savetrials, 'off'), X = mean(X,3); end;
if strcmpi(g.logtrials, 'off'), X = 10*log10(X); end;
end;
% Save SPECs in file (all components or channels)
% -----------------------------------------------
fileNames = computeFullFileName( { EEG.filepath }, { EEG.filename });
if strcmpi(g.savefile, 'on')
options = { options{:} spec_opt{:} 'timerange' g.timerange 'nfft' g.nfft 'specmode' g.specmode };
if strcmpi(prefix, 'comp')
savetofile( filename, f, X, 'comp', 1:size(X,1), options, {}, fileNames, g.trialindices, datatype);
else
if ~isempty(g.interp)
savetofile( filename, f, X, 'chan', 1:size(X,1), options, { g.interp.labels }, fileNames, g.trialindices, datatype);
else
tmpchanlocs = EEG(1).chanlocs;
savetofile( filename, f, X, 'chan', 1:size(X,1), options, { tmpchanlocs.labels }, fileNames, g.trialindices, datatype);
end;
end;
end;
return;
% compute full file names
% -----------------------
function res = computeFullFileName(filePaths, fileNames);
for index = 1:length(fileNames)
res{index} = fullfile(filePaths{index}, fileNames{index});
end;
% -------------------------------------
% saving SPEC information to Matlab file
% -------------------------------------
function savetofile(filename, f, X, prefix, comps, params, labels, dataFiles, dataTrials, datatype);
disp([ 'Saving SPECTRAL file ''' filename '''' ]);
allspec = [];
for k = 1:length(comps)
allspec = setfield( allspec, [ prefix int2str(comps(k)) ], squeeze(X(k,:,:)));
end;
if nargin > 6 && ~isempty(labels)
allspec.labels = labels;
end;
allspec.freqs = f;
allspec.parameters = params;
allspec.datatype = datatype;
allspec.datafiles = dataFiles;
allspec.datatrials = dataTrials;
allspec.average_spec = mean(X,1);
std_savedat(filename, allspec);
|
github
|
lcnhappe/happe-master
|
std_precomp_worker.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_precomp_worker.m
| 2,834 |
utf_8
|
35f7db94f3bde2742d8ec681fae164f1
|
% std_precomp_worker() - allow dispatching ERSP to be computed in parallel
% on a given cluster.
% Usage:
% >> feature = std_precomp_worker(filename, varargin);
%
% Inputs:
% filename - STUDY file name
%
% Optional inputs:
% Optional inputs are the same as for the std_precomp function. Note that
% this function can currently only compute ERSP and ITC. The argument
% 'cell' must be defined so a given node will only compute the measure on
% one cell (one cell per node).
% output trials {default: whole measure range}
% Output:
% feature - data structure containing ERSP and/or ITC
%
% Author: Arnaud Delorme, SCCN, UCSD, 2012-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function feature = std_precomp_worker(filename, varargin)
if nargin < 2
help std_precomp_worker;
return;
end;
g = struct(varargin{2:end});
% load dataset
% ------------
[STUDY ALLEEG] = pop_loadstudy('filename', filename);
if ~isfield(g, 'design'), g.design = STUDY.currentdesign; end;
if isfield(g, 'erp') || isfield(g, 'spec') || isfield(g, 'erpim') || isfield(g, 'scalp')
error('This function is currently designed to compute time-frequency decompositions only');
end;
if ~isfield(g, 'ersp') && ~isfield(g, 'itc')
error('You must compute either ERSP or ITC when using the EC2 cluster');
end;
% run std_precomp (THIS IS THE PART WE WANT TO PARALELIZE)
% ---------------
% for index = 1:length(STUDY.design(g.design).cell)
% [STUDY ALLEEG] = std_precomp(STUDY, ALLEEG, varargin{:}, 'cell', index);
% end;
std_precomp(STUDY, ALLEEG, varargin{:});
filebase = STUDY.design(g.design).cell(g.cell).filebase;
if isfield(g, 'channel')
fileERSP = [ filebase '.datersp' ];
fileITC = [ filebase '.datitc' ];
if exist(fileERSP), feature.ersp = load('-mat', fileERSP); end;
if exist(fileITC ), feature.itc = load('-mat', fileITC ); end;
else
fileERSP = [ filebase '.icaersp' ];
fileITC = [ filebase '.icaitc' ];
if exist(fileERSP), feature.ersp = load('-mat', fileERSP); end;
if exist(fileITC ), feature.itc = load('-mat', fileITC ); end;
end;
|
github
|
lcnhappe/happe-master
|
pop_studyerp.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/pop_studyerp.m
| 8,206 |
utf_8
|
b0813e4eb5cf7b6f15ee9f45028b7261
|
% pop_studyerp() - create a simple design for ERP analysis
%
% Usage:
% >> [STUDY ALLEEG] = pop_studyerp; % pop up interface
%
% Outputs:
% STUDY - an EEGLAB STUDY set of loaded EEG structures
% ALLEEG - ALLEEG vector of one or more loaded EEG dataset structures
%
% Author: Arnaud Delorme, SCCN, UCSD, 2011-
%
% See also: eeg_checkset()
% Copyright (C) 15 Feb 2002 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [STUDY ALLEEG com ] = pop_studyerp;
% first GUI, get the number of conditions and subjects
% ----------------------------------------------------
textinfo = [ 'This interface creates a simple STUDY and ' 10 ...
'computes its condition grand average ERPs.' 10 ...
'For each subject, trials for each condition' 10 ...
'must first be stored in a separate dataset.' 10 ...
'Create other STUDY using the standard editor.' ];
guispec = { ...
{'style' 'text' 'string' 'Create simple ERP STUDY' ...
'FontWeight' 'Bold' 'fontsize', 12} ...
{ 'style' 'text' 'string' textinfo } ...
{'style' 'text' 'string' 'Number of conditions:' } ...
{'style' 'edit' 'string' '1' 'tag' 'cond' } { } ...
{'style' 'text' 'string' 'Number of subjects:' } ...
{'style' 'edit' 'string' '15' 'tag' 'subjects' } { } };
guigeom = { [1] [1] [1 0.3 0.4] [1 0.3 0.4] };
optiongui = { 'geometry', guigeom, 'uilist' , guispec, ...
'geomvert', [ 1 4 1 1], ...
'helpcom' , 'pophelp(''pop_studyerp'')', ...
'title' , 'Create a new STUDY set -- pop_studyerp()' };
[result, userdat2, strhalt, outstruct] = inputgui(optiongui{:});
STUDY = [];
ALLEEG = [];
com = '';
if isempty(result), return; end;
nSubjects = str2num(outstruct.subjects);
nConds = str2num(outstruct.cond);
% second GUI, enter the datasets
% ------------------------------
guispec = { ...
{'style' 'text' 'string' 'Create simple ERP STUDY' 'FontWeight' 'Bold' 'fontsize', 12} ...
{} ...
{} {'style' 'text' 'string' 'STUDY set name:' } { 'style' 'edit' 'string' '' 'tag' 'study_name' } ...
{} };
guigeom = { [1] [1] [0.2 1 3.5] [1] };
% define conditions
% -----------------
guigeom{end+1} = [];
for icond = 1:nConds
if icond == 1, guigeom{end} = [ guigeom{end} 1 0.2];
else guigeom{end} = [ guigeom{end} 0.1 1 0.2];
end;
if icond > 1, guispec{end+1} = {}; end;
guispec = { guispec{:}, {'style' 'text' 'string' [ 'Condition ' num2str(icond) ' name'] } {} };
end;
% edit boxes for conditions
% -------------------------
guigeom{end+1} = [];
for icond = 1:nConds
if icond == 1, guigeom{end} = [ guigeom{end} 1 0.2];
else guigeom{end} = [ guigeom{end} 0.1 1 0.2];
end;
if icond > 1, guispec{end+1} = {}; end;
guispec = { guispec{:}, {'style' 'edit' 'string' '' 'tag' [ 'cond' num2str(icond) ] } {} };
end;
guispec{end+1} = {};
guigeom{end+1} = [1];
% define dataset headers
% ----------------------
guigeom{end+1} = [];
for icond = 1:nConds
if icond == 1, guigeom{end} = [ guigeom{end} 1 0.2];
else guigeom{end} = [ guigeom{end} 0.1 1 0.2];
end;
if icond > 1, guispec{end+1} = {}; end;
guispec = { guispec{:}, {'style' 'text' 'string' ['Condition ' num2str(icond) ' datasets' ] } {} };
end;
% create edit boxes
% -----------------
for index = 1:nSubjects
guigeom{end+1} = [];
for icond = 1:nConds
if icond == 1, guigeom{end} = [ guigeom{end} 1 0.2];
else guigeom{end} = [ guigeom{end} 0.1 1 0.2];
end;
select_com = ['[inputname, inputpath] = uigetfile2(''*.set;*.SET'', ''Choose dataset to add to STUDY -- pop_study()'');'...
'if inputname ~= 0,' ...
' guiind = findobj(''parent'', gcbf, ''tag'', ''set' int2str(icond) '_' int2str(index) ''');' ...
' set( guiind,''string'', fullfile(inputpath, inputname));' ...
'end; clear inputname inputpath;'];
if icond > 1, guispec{end+1} = {}; end;
guispec = { guispec{:}, ...
{'style' 'edit' 'string' '' 'tag' [ 'set' int2str(icond) '_' int2str(index) ] }, ...
{'style' 'pushbutton' 'string' '...' 'Callback' select_com } };
end;
end;
% last text
% ---------
textinfo = [ 'When using more than 1 condition, datasets on each line must correspond to the same subject.' ];
guispec = { guispec{:}, {}, {'style' 'text' 'string' textinfo } };
guigeom = { guigeom{:} [1] [1] };
optiongui = { 'geometry', guigeom, ...
'uilist' , guispec, ...
'helpcom' , 'pophelp(''pop_studyerp'')', ...
'title' , 'Create a new STUDY set -- pop_studyerp()' };
[result, userdat2, strhalt, outstruct] = inputgui(optiongui{:});
if isempty(result), return; end;
% decode outstruct and build call to std_editset
% ----------------------------------------------
options = { 'name' outstruct.study_name 'updatedat' 'off' };
commands = {};
for icond = 1:nConds
% check that condition name is defined
tagCond = ['cond' int2str(icond) ];
if isempty(outstruct.(tagCond))
outstruct.(tagCond) = [ 'condition ' int2str(icond) ];
end;
for index = 1:nSubjects
tagSet = [ 'set' int2str(icond) '_' int2str(index) ];
subject = sprintf('S%2.2d', index);
if ~isempty(outstruct.(tagSet))
commands = { commands{:}, {'index' nConds*index+icond-1 'load' outstruct.(tagSet) 'subject' subject 'condition' outstruct.(tagCond) } };
end;
end;
end;
options = { options{:}, 'commands', commands };
% call std_editset to create the STUDY
% ------------------------------------
com1 = sprintf( '[STUDY ALLEEG] = std_editset( STUDY, ALLEEG, %s );', vararg2str(options) );
[STUDY ALLEEG] = std_editset(STUDY, ALLEEG, options{:});
if exist([ STUDY.design(STUDY.currentdesign).cell(1).filebase '.daterp' ])
textmsg = [ 'WARNING: SOME ERP DATAFILES ALREADY EXIST, OVERWRITE THEM?' 10 ...
'(if you have another STUDY using the same datasets, it might overwrite its' 10 ...
'precomputed data files. Instead, use a single STUDY and create multiple designs).' ];
res = questdlg2(textmsg, 'Precomputed datafiles already present on disk', 'No', 'Yes', 'Yes');
if strcmpi(res, 'No')
error('User aborded precomputing ERPs');
end;
end;
% call std_precomp for ERP (channels)
% -----------------------------------
com2 = '[STUDY ALLEEG] = std_precomp(STUDY, ALLEEG, ''channels'', ''interpolate'', ''on'', ''recompute'',''on'',''erp'',''on'');';
[STUDY ALLEEG] = std_precomp(STUDY, ALLEEG, 'channels','interp', 'on', 'recompute','on','erp','on');
% call std_erpplot to plot ERPs (channels)
% ----------------------------------------
com3 = 'tmpchanlocs = ALLEEG(1).chanlocs; STUDY = std_erpplot(STUDY, ALLEEG, ''channels'', { tmpchanlocs.labels }, ''plotconditions'', ''together'');';
tmpchanlocs = ALLEEG(1).chanlocs;
STUDY = std_erpplot(STUDY, ALLEEG, 'channels', { tmpchanlocs.labels }, 'plotconditions', 'together');
pos = get(gcf, 'position');
set(gcf, 'position', [10 pos(2) pos(3)*2 pos(4)*2]);
% call the STUDY plotting interface
% ---------------------------------
disp('Press OK to close plotting interface and save the STUDY');
disp('If you press CANCEL, the whole STUDY will be lost.');
[STUDY com4] = pop_chanplot(STUDY, ALLEEG);
com = sprintf('%s\n%s\n%s\n%s', com1, com2, com3, com4);
|
github
|
lcnhappe/happe-master
|
std_itcplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_itcplot.m
| 2,459 |
utf_8
|
5d31d5576a555fc6e0ea524887479c2c
|
% std_itcplot() - Commandline function to plot cluster ITCs. Either displays mean cluster
% ITCs, or else all cluster component ITCs, plus the mean cluster ITC, in
% one figure per cluster and condition. ITCs can be visualized only if
% component ITCs were calculated and saved in the STUDY EEG datasets.
% These can be computed during pre-clustering using the gui-based function
% pop_preclust(), or via the equivalent commandline functions
% eeg_createdata() and eeg_preclust(). Called by pop_clustedit().
% Usage:
% >> [STUDY] = std_itcplot(STUDY, ALLEEG, key1, val1, key2, val2);
% >> [STUDY itcdata itctimes itcfreqs pgroup pcond pinter] = ...
% std_itcplot(STUDY, ALLEEG ...);
% Inputs:
% STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - global EEGLAB vector of EEG structures for the datasets in the STUDY.
% Note: ALLEEG for a STUDY set is typically created using load_ALLEEG().
%
% Additional help:
% Inputs and output of this function are strictly identical to the std_erspplot().
% See the help message of this function for more information. std_itcplot()
% plots the ITC while std_erspplot() plots the ERSP.
%
% See also: std_erspplot(), pop_clustedit(), pop_preclust()
%
% Authors: Arnaud Delorme, CERCO, August, 2006-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [STUDY, allitc, alltimes, allfreqs, pgroup, pcond, pinter] = std_itcplot(STUDY, ALLEEG, varargin)
if nargin < 2
help std_itcplot;
return;
end;
[STUDY allitc alltimes allfreqs pgroup pcond pinter ] = std_erspplot(STUDY, ALLEEG, 'datatype', 'itc', varargin{:});
|
github
|
lcnhappe/happe-master
|
std_readerpimage.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_readerpimage.m
| 1,501 |
utf_8
|
0c21798407bdacd79f5ef9bfe0c4110d
|
% std_readerpimage() - load ERPimage measures for data channels or
% for all components of a specified cluster.
% Usage:
% >> [STUDY, erpimagedata, times, trials, events] = std_readerpimage(STUDY, ALLEEG, varargin);
%
% Note: this function is a helper function that contains a call to the
% std_readersp function that reads all 2-D data matrices for EEGLAB STUDY.
% See the std_readersp help message for more information.
%
% Author: Arnaud Delorme, CERCO, 2006-
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 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
function [STUDY, erspdata, alltimes, allfreqs, events] = std_readerpimage(STUDY, ALLEEG, varargin);
[STUDY, erspdata, alltimes, allfreqs, erspbase, events] = std_readersp(STUDY, ALLEEG, 'infotype','erpim', varargin{:});
|
github
|
lcnhappe/happe-master
|
std_fileinfo.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_fileinfo.m
| 3,535 |
utf_8
|
e6de7fbc6e0b582bd20aabb2d0afafbf
|
% std_fileinfo() - Check uniform channel distribution accross datasets
%
% Usage:
% >> [struct filepresent] = std_fileinfo(ALLEEG);
% Inputs:
% ALLEEG - EEGLAB ALLEEG structure
%
% Outputs:
% struct - structure of the same length as the ALLEEG variable
% containing all the fields in the datafiles
% filepresent - array of 0 and 1 indicating if the file is present for
% each dataset
%
% Authors: Arnaud Delorme, SCCN/UCSD, CERCO/CNRS, 2010-
% Copyright (C) Arnaud Delorme
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [tmpstructout compinds filepresent] = std_fileinfo( ALLEEG, filetype );
firstpass = 1;
notequal = 0;
compinds = {};
tmpstructout = [];
filepresent = zeros(1,length(ALLEEG));
for dat = 1:length(ALLEEG)
filename = fullfile(ALLEEG(dat).filepath, [ ALLEEG(dat).filename(1:end-3) filetype ]);
thisfilepresent = exist(filename);
if thisfilepresent && firstpass == 1
%fprintf('Files of type "%s" detected, checking...', filetype);
elseif firstpass == 1
notequal = 1;
end;
firstpass = 0;
filepresent(dat) = thisfilepresent;
if filepresent(dat)
try
warning('off', 'MATLAB:load:variableNotFound');
tmptmpstruct = load( '-mat', filename, 'times', 'freqs', 'parameters', 'labels', 'chanlabels' );
warning('on', 'MATLAB:load:variableNotFound');
catch
passall = 0;
fprintf(' Error\n');
break;
end;
% rename chanlabels and store structure
if isfield(tmptmpstruct, 'chanlabels')
tmptmpstruct.labels = tmptmpstruct.chanlabels;
tmptmpstruct = rmfield(tmptmpstruct, 'chanlabels');
end;
if filetype(1) ~= 'd' % ICA components
allvars = whos('-file', filename);
tmpinds = [];
for cind = 1:length(allvars)
str = allvars(cind).name(5:end);
ind_ = find(str == '_');
if ~isempty(ind_), str(ind_:end) = []; end;
tmpinds = [ tmpinds str2num(str) ];
end;
compinds(dat) = { unique(tmpinds) };
elseif ~isfield(tmptmpstruct, 'labels')
allvars = whos('-file', filename);
allvarnames = { allvars.name };
tmptmpstruct.labels = allvarnames(strmatch('chan', allvarnames));
end;
try,
tmpstruct(dat) = tmptmpstruct;
catch,
passall = 0;
break;
end;
end;
end;
if exist('tmpstruct') == 1
tmpstructout = tmpstruct;
end;
|
github
|
lcnhappe/happe-master
|
std_clustread.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_clustread.m
| 12,094 |
utf_8
|
fc68f0aa97d01ad111040de7a802cc1e
|
% std_clustread() - this function has been replaced by std_readdata() for
% consistency. Please use std_readdata() instead.
% load one or more requested measures
% ['erp'|'spec'|'ersp'|'itc'|'dipole'|'map']
% for all components of a specified cluster.
% Calls std_readerp(), std_readersp(), etc.
% Usage:
% >> clustinfo = std_clustread(STUDY,ALLEEG, cluster, infotype, condition);
% Inputs:
% STUDY - studyset structure containing some or all files in ALLEEG
% ALLEEG - vector of loaded EEG datasets
% cluster - cluster number in STUDY
% infotype - ['erp'|'spec'|'ersp'|'itc'|'dipole'|'map'] type of stored
% cluster information to read. May also be a cell array of
% these types, for example: { 'erp' 'map' 'dipole' }
% condition - STUDY condition number to read {default: all}
%
% Output:
% clustinfo - structure of specified cluster information:
% clustinfo.name % cluster name
% clustinfo.clusternum % cluster index
% clustinfo.condition % index of the condition asked for
%
% clustinfo.comp[] % array of component indices
% clustinfo.subject{} % cell array of component subject codes
% clustinfo.group{} % cell array of component group codes
%
% clustinfo.erp[] % (ncomps, ntimes) array of component ERPs
% clustinfo.erp_times[] % vector of ERP epoch latencies
%
% clustinfo.spec[] % (ncomps, nfreqs) array of component spectra
% clustinfo.spec_freqs[]% vector of spectral frequencies
%
% clustinfo.ersp[] % (ncomps,ntimes,nfreqs) array of component ERSPs
% clustinfo.ersp_times[]% vector of ERSP latencies
% clustinfo.ersp_freqs[]% vector of ERSP frequencies
%
% clustinfo.itc[] % (ncomps,ntimes,nfreqs) array of component ITCs
% clustinfo.itc_times[] % vector of ITC latencies
% clustinfo.itc_freqs[] % vector of ITC frequencies
%
% clustinfo.scalp[] % (ncomps,65,65) array of component scalp map grids
% clustinfo.xi[] % abscissa values for columns of the scalp maps
% clustinfo.yi[] % ordinate values for rows of the scalp maps
%
% clustinfo.dipole % array of component dipole information structs
% % with same format as EEG.dipfit.model
% Example:
% % To plot the ERPs for all components in cluster 3 of a loaded STUDY
% >> clustinfo = std_clustread(STUDY, ALLEEG, 3, 'erp');
% figure; plot(clustinfo.erp_times, clustinfo.erp);
%
% See also: std_readerp(), std_readspec(), std_readersp(), std_readitc(), std_readtopo()
%
% Authors: Hilit Serby, Scott Makeig & Arnaud Delorme, SCCN/INC/UCSD, 2005-
%
% RCS-recorded version number, date, editor and comments
function clustinfo = std_clustread(STUDY,ALLEEG, cluster, infotype, condition);
help std_clustread;
return;
if nargin < 4
help std_clustread;
return;
end
if nargin < 5
condition = [1:length(STUDY.condition)]; % default
end
if ~iscell(infotype),
infotype = { infotype };
end;
clustinfo = [];
clustinfo.name = STUDY.cluster(cluster).name;
clustinfo.clusternum = cluster;
clustinfo.comps = STUDY.cluster(cluster).comps;
clustinfo.condition = condition;
ncomps = length(STUDY.cluster(cluster).comps);
for k = 1:ncomps %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for each channel | component %%%%%%%%%%%%%%
for n = 1:length(condition) %%%%%%%%%%%%%%%%%%%%%%%% for each STUDY condition %%%%%%%%%%%%%%
abset = [STUDY.datasetinfo(STUDY.cluster(cluster).sets(condition(n),k)).index];
comp = STUDY.cluster(cluster).comps(k);
clustinfo.subject{k} = STUDY.datasetinfo(STUDY.cluster(cluster).sets(condition(n),k)).subject;
clustinfo.group{k} = STUDY.datasetinfo(STUDY.cluster(cluster).sets(condition(n),k)).group;
for index = 1:length(infotype) %%%%%%%%%%%%%% for each information type %%%%%%%%%%%%%%%%
switch infotype{index}
case 'erp'
[erp, t] = std_readerp(ALLEEG, abset, comp, STUDY.preclust.erpclusttimes);
clustinfo.erp_times = t;
clustinfo.erp{n,k} = erp;
case 'spec'
[spec, f] = std_readspec(ALLEEG, abset, comp, STUDY.preclust.specclustfreqs);
clustinfo.spec_freqs = f;
clustinfo.spec{n,k} = spec;
case 'ersp'
if n == 1
abset = [STUDY.datasetinfo(STUDY.cluster(cluster).sets(condition,k)).index];
[ersp, logfreqs, timevals] = std_readersp(ALLEEG, abset, comp, ...
STUDY.preclust.erspclusttimes, STUDY.preclust.erspclustfreqs);
for cc = 1:length(condition)
clustinfo.ersp{condition(cc), k} = ersp(:,:,cc);
end;
clustinfo.ersp_freqs = logfreqs;
clustinfo.ersp_times = timevals;
end;
case 'itc'
[itc, logfreqs, timevals] = std_readitc(ALLEEG, abset, comp, ...
STUDY.preclust.erspclusttimes, STUDY.preclust.erspclustfreqs );
clustinfo.itc_freqs = logfreqs;
clustinfo.itc_times = timevals;
clustinfo.itc{n,k} = itc;
case 'dipole'
if n == 1, clustinfo.dipole(k) = ALLEEG(abset).dipfit.model(comp); end;
case { 'map' 'scalp' 'topo' }
if n == 1
[grid, yi, xi] = std_readtopo(ALLEEG, abset, comp);
if k == 1
clustinfo.xi = xi;
clustinfo.yi = yi;
end
clustinfo.scalp{k} = grid;
end;
otherwise, error('Unrecognized ''infotype'' entry');
end; % switch
end;
end; % infotype
end % comp
% FUTURE HEADER
% std_clustread() - return detailed information and (any) requested component
% measures for all components of a specified cluster. Restrict
% component info to components from specified subjects, groups,
% sessions, and/or conditions. Use in scripts handling results
% of component clustering. Called by cluster plotting
% functions: std_envtopo(), std_erpplot(), std_erspplot(), ...
% Usage:
% >> clsinfo = std_clustread(STUDY, ALLEEG, cluster); % use defaults
% >> clsinfo = std_clustread(STUDY, ALLEEG, cluster, ...
% 'keyword1', keyval1, ...
% 'keyword2', keyval2, ...);
% Inputs:
% STUDY - studyset structure containing some or all files in ALLEEG
% ALLEEG - vector of loaded EEG datasets including those in STUDY
% cluster - cluster number in STUDY to return information for
%
% Optional keywords - and values: IMPLEMENT !!
% 'measure' - ['erp'|'spec'|'ersp'|'itc'|'dipole'|'topo'] stored
% cluster measure(s) to read. May also be a cell array of
% these, for example: { 'erp' 'map' 'dipole' }.
% Else 'all', meaning all measures available.
% Else 'cls', meaning all measures clustered on.
% Else [], for none {default: 'cls'}
% 'condition' - STUDY condition 'name' or {'names'} to read,
% Else 'all' {default: 'all'}
% 'condnum'' - STUDY condition [number(s)] to read,
% Else 0 -> all {default: 0}
% 'subject' - STUDY subjects 'name' or {'names'} to read,
% Else 'all' {default: 'all'}
% 'subjnum' - STUDY subjects [number(s)] to read,
% Else 0 -> all {default: 0}
% 'group' - STUDY subject group 'name' or {'names'} to read,
% Else 'all' {default: 'all'}
% 'groupnum' - STUDY subject group [number(s)] to read,
% Else 0 -> all {default: 0}
% 'session' - STUDY session [number(s)] to read,
% Else 0 -> all {default: 0}
%
% Output:
% clsinfo - structure containing information about cluster components in fields:
%
% .clustername % cluster name
% .clusternum % cluster index
%
% .dataset % {(conditions,components) cell array} component dataset indices
% in the input ALLEEG array
% .component % [(1,components) int array] component decomposition indices
% .subject % {(1,components) cell array} component subject codes
% .subjectnum % [(1,components) int array] component subject indices
% .group % {(1,components) cell array} component group codes
% .groupnum % [(1,components) int array] component group indices
%
% .condition % {(1,components) cell array} component condition codes
% .conditionnum % [(1,components) int array] component condition indices
% .session % [(1,components) int array] component session indices
%
% .erp % {(conditions, components) cell array}
% (1, latencies) component ERPs CHECK DIM
% .erp_times % [num vector] ERP epoch latencies (s)
%
% .spec % {(conditions, components) cell array}
% (1,frequencies) component spectra CHECK DIM
% .spec_freqs % [num vector] spectral frequencies (Hz)
%
% .ersp % {(conditions, components) cell array}
% (freqs,latencies) component ERSPs CHECK DIM
% .ersp_times % [num vector] ERSP epoch latencies (s)
% .ersp_freqs % [num vector] ERSP frequencies (Hz)
%
% .itc % {(conditions, components) cell array}
% (freqs,latencies) component ITCs CHECK DIM
% .itc_times % [num vector] ITC epoch latencies (s)
% .itc_freqs % [num vector] ITC frequencies (Hz)
%
% .topo % {(1,components) cell array}
% (65,65) component topo map grids CHECK DIM
% .xi % [vector] topo grid abscissa values
% .yi % [vector] topo grid ordinate values
%
% .dipole % [struct array] component dipole information
% % structures with same format as "EEG.dipfit.model"
% % See >> help dipfit CHECK HELP
% Example:
% % To plot the ERPs for all Cluster-3 components in a one-condition STUDY
% %
% clsinfo3 = std_clustread(STUDY, ALLEEG, 3, 'measure', 'erp'); % assume 1 condition
% times = clsinfo3.erp_times; figure; plot(times, clsinfo3.erp');
% %
% % To plot ERPs for only those Cluster-3 components from subjects in group 'female'
% %
% feminfo3 = std_clustread(STUDY, ALLEEG, 3, 'measure', 'erp', 'group', 'female');
% figure; plot(times, feminfo3.erp');
% %
% % Alternatively, to extract 'female' subject components from clsinfo3 above
% %
% femidx = find(strcmp({clsinfo3.group},'female'));
% figure; plot(times, clustinfo.erp(femidx,:)'); CHECK EXAMPLE
%
% Authors: Hilit Serby, Scott Makeig, Toby Fernsler & Arnaud Delorme, SCCN/INC/UCSD, 2005-
|
github
|
lcnhappe/happe-master
|
std_erpimageplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_erpimageplot.m
| 7,319 |
utf_8
|
5073f5d9c0bdd1e64fab8c87596d6553
|
% std_erpimageplot() - Commandline function to plot cluster ERPimage or channel erpimage.
%
% Usage:
% >> [STUDY] = std_erpimageplot(STUDY, ALLEEG, key1, val1, key2, val2);
% >> [STUDY data times freqs pgroup pcond pinter] = ...
% std_erpimageplot(STUDY, ALLEEG ...);
% Inputs:
% STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - global EEGLAB vector of EEG structures for the datasets in the STUDY.
% Note: ALLEEG for a STUDY set is typically created using load_ALLEEG().
%
% Additional help:
% Inputs and output of this function are strictly identical to the std_erspplot().
% See the help message of this function for more information.
%
% See also: std_erspplot()
%
% Authors: Arnaud Delorme, UCSD/CERCO, August, 2011-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [STUDY, allitc, alltimes, allfreqs, pgroup, pcond, pinter, events] = std_erpimageplot(STUDY, ALLEEG, varargin)
if nargin < 2
help std_erpimageplot;
return;
end;
events = [];
STUDY = pop_erpimparams(STUDY, 'default');
if strcmpi(STUDY.etc.erpimparams.concatenate, 'off')
% use std_erspplot for stats when concatenate is off
[STUDY allitc alltimes allfreqs pgroup pcond pinter events] = std_erspplot(STUDY, ALLEEG, 'datatype', 'erpim', varargin{:});
else
params = STUDY.etc.erpimparams;
[ opt moreparams ] = finputcheck( varargin, { ...
'design' 'integer' [] STUDY.currentdesign;
'topotime' 'real' [] params.topotime;
'topotrial' 'real' [] params.topotrial;
'timerange' 'real' [] params.timerange;
'trialrange' 'real' [] params.trialrange;
'colorlimits' 'real' [] params.colorlimits; % ERPimage
'statistics' 'string' [] params.statistics;
'groupstats' 'string' [] params.groupstats;
'condstats' 'string' [] params.condstats;
'threshold' 'real' [] params.threshold;
'naccu' 'integer' [] params.naccu;
'mcorrect' 'string' [] params.mcorrect;
'erpimageopt' 'cell' [] params.erpimageopt;
'concatenate' 'string' { 'on','off' } params.concatenate;
'channels' 'cell' [] {};
'clusters' 'integer' [] [];
'comps' {'integer','string'} [] []; % for backward compatibility
'plotsubjects' 'string' { 'on','off' } 'off';
'plotmode' 'string' { 'normal','condensed','none' } 'normal';
'subject' 'string' [] '' }, 'std_erpimageplot', 'ignore');
if ~isempty(opt.topotime) && ~isempty(opt.topotrial)
error('Cannot plot topography when ERP-image is in trial concatenation mode');
end;
if ~isempty(opt.trialrange)
error('Cannot select trial range when ERP-image is in trial concatenation mode');
end;
if strcmpi(opt.groupstats, 'on') || strcmpi(opt.condstats, 'on')
disp('Warning: cannot perform statistics when ERP-image is in trial concatenation mode');
end;
% options
if ~isempty(opt.colorlimits), options = { 'caxis' opt.colorlimits opt.erpimageopt{:} };
else options = { 'cbar' 'on' opt.erpimageopt{:} };
end;
if ~isempty(opt.channels)
[STUDY allerpimage alltimes alltrials tmp events] = std_readersp(STUDY, ALLEEG, 'channels', opt.channels, 'infotype', 'erpim', 'subject', opt.subject, ...
'concatenate', 'on', 'timerange', opt.timerange, 'design', opt.design);
% get figure title
% ----------------
locs = eeg_mergelocs(ALLEEG.chanlocs);
locs = locs(std_chaninds(STUDY, opt.channels));
allconditions = STUDY.design(opt.design).variable(1).value;
allgroups = STUDY.design(opt.design).variable(2).value;
alltitles = std_figtitle('condnames', allconditions, 'cond2names', allgroups, 'chanlabels', { locs.labels }, ...
'subject', opt.subject, 'valsunit', 'ms', 'datatype', 'ERPIM');
figure;
for iCond = 1:length(allconditions)
for iGroup = 1:length(allgroups)
tmpevents = events{iCond, iGroup};
if isempty(tmpevents), tmpevents = zeros(1, size(allerpimage{iCond, iGroup},2)); end;
subplot(length(allconditions), length(allgroups), (iCond-1)*length(allgroups) + iGroup);
% use color scale for last plot
if ~isempty(opt.colorlimits) && iCond == length(allconditions) && iGroup == length(allgroups)
options = { options{:} 'cbar' 'on' };
end;
erpimage(allerpimage{iCond, iGroup}, tmpevents, alltimes, alltitles{iCond, iGroup}, params.smoothing, params.nlines, options{:});
end;
end;
else
for cInd = 1:length(opt.clusters)
[STUDY allerpimage alltimes alltrials tmp events] = std_readersp(STUDY, ALLEEG, 'clusters', opt.clusters(cInd), 'infotype', 'erpim', 'subject', opt.subject, ...
'concatenate', 'on', 'timerange', opt.timerange, 'design', opt.design);
% get figure title
% ----------------
locs = eeg_mergelocs(ALLEEG.chanlocs);
locs = locs(std_chaninds(STUDY, opt.channels));
allconditions = STUDY.design(opt.design).variable(1).value;
allgroups = STUDY.design(opt.design).variable(2).value;
alltitles = std_figtitle('condnames', allconditions, 'cond2names', allgroups, 'clustname', STUDY.cluster(opt.clusters(cInd)).name, ...
'subject', opt.subject, 'valsunit', 'ms', 'datatype', 'ERPIM');
figure;
for iCond = 1:length(allconditions)
for iGroup = 1:length(allgroups)
tmpevents = events{iCond, iGroup};
if isempty(tmpevents), tmpevents = zeros(1, size(allerpimage{iCond, iGroup},2)); end;
subplot(length(allconditions), length(allgroups), (iCond-1)*length(allgroups) + iGroup);
% use color scale for last plot
if ~isempty(opt.colorlimits) && iCond == length(allconditions) && iGroup == length(allgroups)
options = { options{:} 'cbar' 'on' };
end;
erpimage(allerpimage{iCond, iGroup}, tmpevents, alltimes, alltitles{iCond, iGroup}, params.smoothing, params.nlines, options{:});
end;
end;
end;
end;
end;
|
github
|
lcnhappe/happe-master
|
std_checkset.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_checkset.m
| 15,270 |
utf_8
|
198e4cb3540ff8db426b902da6f4f092
|
% std_checkset() - check STUDY set consistency
%
% Usage: >> [STUDY, ALLEEG] = std_checkset(STUDY, ALLEEG);
%
% Input:
% STUDY - EEGLAB STUDY set
% ALLEEG - vector of EEG datasets included in the STUDY structure
%
% Output:
% STUDY - a new STUDY set containing some or all of the datasets in ALLEEG,
% plus additional information from the optional inputs above.
% ALLEEG - an EEGLAB vector of EEG sets included in the STUDY structure
%
% Authors: Arnaud Delorme & Hilit Serby, SCCN, INC, UCSD, November 2005
% 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 [STUDY, ALLEEG, command] = std_checkset(STUDY, ALLEEG, option);
if nargin < 2
help std_checkset;
return;
end;
command = '';
if isempty(STUDY), return; end;
studywasempty = 0;
modif = 0;
if ~isfield(STUDY, 'name'), STUDY.name = ''; modif = 1; end;
if ~isfield(STUDY, 'task'), STUDY.task = ''; modif = 1; end;
if ~isfield(STUDY, 'notes'), STUDY.notes = ''; modif = 1; end;
if ~isfield(STUDY, 'filename'), STUDY.filename = ''; modif = 1; end;
if ~isfield(STUDY, 'filepath'), STUDY.filepath = ''; modif = 1; end;
if ~isfield(STUDY, 'history'), STUDY.history = ''; modif = 1; end;
if ~isfield(STUDY, 'subject'), STUDY.subject = {}; modif = 1; end;
if ~isfield(STUDY, 'group'), STUDY.group = {}; modif = 1; end;
if ~isfield(STUDY, 'session'), STUDY.session = {}; modif = 1; end;
if ~isfield(STUDY, 'condition'), STUDY.condition = {}; modif = 1; end;
if ~isfield(STUDY, 'setind'), STUDY.setind = {}; modif = 1; end;
if ~isfield(STUDY, 'etc'), STUDY.etc = []; modif = 1; end;
if ~isfield(STUDY, 'etc.warnmemory'), STUDY.etc.warnmemory = 1; modif = 1; end;
if ~isfield(STUDY, 'preclust'), STUDY.preclust = []; modif = 1; end;
if ~isfield(STUDY, 'datasetinfo'), STUDY.datasetinfo = []; modif = 1; end;
if ~isfield(STUDY.etc, 'version'), STUDY.etc.version = []; modif = 1; end;
if ~isfield(STUDY.preclust, 'erpclusttimes' ), STUDY.preclust.erpclusttimes = []; modif = 1; end;
if ~isfield(STUDY.preclust, 'specclustfreqs' ), STUDY.preclust.specclustfreqs = []; modif = 1; end;
if ~isfield(STUDY.preclust, 'erspclustfreqs' ), STUDY.preclust.erspclustfreqs = []; modif = 1; end;
if ~isfield(STUDY.preclust, 'erspclusttimes' ), STUDY.preclust.erspclusttimes = []; modif = 1; end;
if ~isfield(STUDY.datasetinfo, 'comps') & ~isempty(STUDY.datasetinfo), STUDY.datasetinfo(1).comps = []; modif = 1; end;
if ~isfield(STUDY.datasetinfo, 'index') & ~isempty(STUDY.datasetinfo), STUDY.datasetinfo(1).index = []; modif = 1; end;
% all summary fields
% ------------------
try, subject = unique_bc({ STUDY.datasetinfo.subject });
catch,
subject = '';
disp('Important warning: some datasets do not have subject codes; some functions may crash!');
end;
try, group = unique_bc({ STUDY.datasetinfo.group });
catch,
group = {};
% disp('Important warning: some datasets do not have group codes; some functions may crash!');
end;
try, condition = unique_bc({ STUDY.datasetinfo.condition });
catch,
condition = {};
disp('Important warning: some datasets do not have condition codes; some functions may crash!');
end;
try, session = unique_bc([STUDY.datasetinfo.session]);
catch,
session = '';
% disp('Important warning: some datasets do not have session numbers; some functions may crash!');
end;
if ~isequal(STUDY.subject, subject ), STUDY.subject = subject; modif = 1; end;
if ~isequal(STUDY.group, group ), STUDY.group = group; modif = 1; end;
if ~isequal(STUDY.condition, condition), STUDY.condition = condition; modif = 1; end;
if ~isequal(STUDY.session, session ), STUDY.session = session; modif = 1; end;
% check dataset info consistency
% ------------------------------
for k = 1:length(STUDY.datasetinfo)
if ~strcmpi(STUDY.datasetinfo(k).filename, ALLEEG(k).filename)
STUDY.datasetinfo(k).filename = ALLEEG(k).filename; modif = 1;
fprintf('Warning: file name has changed for dataset %d and the study has been updated\n', k);
fprintf(' to discard this change in the study, reload it from disk\n');
end;
end;
% recompute setind array (setind is deprecated but we keep it anyway)
% -------------------------------------------------------------------
setind = [];
sameica = std_findsameica(ALLEEG);
for index = 1:length(sameica)
setind(length(sameica{index}):-1:1,index) = sameica{index}';
end;
setind(find(setind == 0)) = NaN;
if any(isnan(setind))
warndlg('Warning: non-uniform set of dataset, some function might not work');
end
if ~isequal(setind, STUDY.setind), STUDY.setind = setind; modif = 1; end;
% check that dipfit is present in all datasets
% --------------------------------------------
for cc = 1:length(sameica)
idat = [];
for tmpi = 1:length(sameica{cc})
if isfield(ALLEEG(sameica{cc}(tmpi)).dipfit, 'model')
idat = sameica{cc}(tmpi);
end;
end;
if ~isempty(idat)
for tmpi = 1:length(sameica{cc})
if ~isfield(ALLEEG(sameica{cc}(tmpi)).dipfit, 'model')
ALLEEG(sameica{cc}(tmpi)).dipfit = ALLEEG(idat).dipfit;
ALLEEG(sameica{cc}(tmpi)).saved = 'no';
fprintf('Warning: no ICA dipoles for dataset %d, using dipoles from dataset %d (same ICA)\n', sameica{cc}(tmpi), idat);
end;
end;
end;
end;
% put in fake channels if channel labels are missing
% --------------------------------------------------
chanlabels = { ALLEEG.chanlocs };
if any(cellfun(@isempty, chanlabels))
if any(~cellfun(@isempty, chanlabels))
disp('********************************************************************');
disp(' IMPORTANT WARNING: SOME DATASETS DO NOT HAVE CHANNEL LABELS AND ');
disp(' SOME OTHERs HAVE CHANNEL LABELS. GENERATING CHANNEL LABELS FOR ');
disp(' THE FORMER DATASETS (THIS SHOULD PROBABLY BE FIXED BY THE USER).');
disp('********************************************************************');
end;
disp('Generating channel labels for all datasets...');
for currentind = 1:length(ALLEEG)
for ind = 1:ALLEEG(currentind).nbchan
ALLEEG(currentind).chanlocs(ind).labels = int2str(ind);
end;
end;
ALLEEG(currentind).saved = 'no';
end;
if length( unique( [ ALLEEG.srate ] )) > 1
disp('********************************************************************');
disp(' IMPORTANT WARNING: SOME DATASETS DO NOT HAVE THE SAME SAMPLING ');
disp(' RATE AND THIS WILL MAKE MOST OF THE STUDY FUNCTIONS CRASH. THIS');
disp(' SHOULD PROBABLY BE FIXED BY THE USER.');
disp('********************************************************************');
end;
% check cluster array
% -------------------
rebuild_design = 0;
if ~isfield(STUDY, 'cluster'), STUDY.cluster = []; modif = 1; end;
if ~isfield(STUDY, 'changrp'), STUDY.changrp = []; modif = 1; end;
if isempty(STUDY.changrp) && isempty(STUDY.cluster)
rebuild_design = 1;
end;
if isfield(STUDY.cluster, 'sets'),
if max(STUDY.cluster(1).sets(:)) > length(STUDY.datasetinfo)
disp('Warning: Some datasets had been removed from the STUDY, clusters have been reinitialized');
STUDY.cluster = [];
end;
end;
if ~studywasempty
if isempty(STUDY.cluster)
modif = 1;
[STUDY] = std_createclust(STUDY, ALLEEG, 'parentcluster', 'on');
end;
if length(STUDY.cluster(1).child) == length(STUDY.cluster)-1 && length(STUDY.cluster) > 1
newchild = { STUDY.cluster(2:end).name };
if ~isequal(STUDY.cluster(1).child, newchild)
STUDY.cluster(1).child = newchild;
end;
end;
end;
% create STUDY design if it is not present
% ----------------------------------------
if ~studywasempty
if isfield(STUDY.datasetinfo, 'trialinfo')
alltrialinfo = { STUDY.datasetinfo.trialinfo };
if any(cellfun(@isempty, alltrialinfo)) && any(~cellfun(@isempty, alltrialinfo))
disp('Rebuilding trial information structure for STUDY');
STUDY = std_maketrialinfo(STUDY, ALLEEG); % some dataset do not have trialinfo and
% some other have it, remake it for everybody
end;
end;
if ~isfield(STUDY, 'design') || isempty(STUDY.design) || ~isfield(STUDY.design, 'name')
STUDY = std_maketrialinfo(STUDY, ALLEEG);
STUDY = std_makedesign(STUDY, ALLEEG);
STUDY = std_selectdesign(STUDY, ALLEEG,1);
rebuild_design = 0;
else
if isfield(STUDY.design, 'indvar1')
STUDY = std_convertdesign(STUDY, ALLEEG);
end;
% convert combined independent variable values
% between dash to cell array of strings
% -------------------------------------
for inddes = 1:length(STUDY.design)
if length(STUDY.design(inddes).variable) == 0
STUDY.design(inddes).variable(1).label = '';
STUDY.design(inddes).variable(1).value = [];
end;
if length(STUDY.design(inddes).variable) == 1
STUDY.design(inddes).variable(2).label = '';
STUDY.design(inddes).variable(2).value = [];
end;
if ~isfield(STUDY.design(inddes).variable, 'pairing')
STUDY.design(inddes).variable(1).pairing = 'on';
STUDY.design(inddes).variable(2).pairing = 'on';
end;
for indvar = 1:length(STUDY.design(inddes).variable)
for indval = 1:length(STUDY.design(inddes).variable(indvar).value)
STUDY.design(inddes).variable(indvar).value{indval} = convertindvarval(STUDY.design(inddes).variable(indvar).value{indval});
end;
end;
end;
if ~isfield(STUDY.design(1), 'cell') || isempty(STUDY.design(1).cell)
fprintf('Warning: Importing STUDY from a newer version of EEGLAB - some information will be lost\n');
STUDY = std_makedesign(STUDY, ALLEEG, 1, STUDY.design(1), 'defaultdesign', 'forceoff');
end;
for inddes = 1:length(STUDY.design)
for indcell = 1:length(STUDY.design(inddes).cell)
for indval = 1:length(STUDY.design(inddes).cell(indcell).value)
STUDY.design(inddes).cell(indcell).value{indval} = convertindvarval(STUDY.design(inddes).cell(indcell).value{indval});
end;
end;
for indinclude = 1:length(STUDY.design(inddes).include)
if iscell(STUDY.design(inddes).include{indinclude})
for indval = 1:length(STUDY.design(inddes).include{indinclude})
STUDY.design(inddes).include{indinclude}{indval} = convertindvarval(STUDY.design(inddes).include{indinclude}{indval});
end;
end;
end;
% check for duplicate entries in filebase
% ---------------------------------------
if length( { STUDY.design(inddes).cell.filebase } ) > length(unique({ STUDY.design(inddes).cell.filebase }))
if ~isempty(findstr('design_', STUDY.design(inddes).cell(1).filebase))
error('There is a problem with your STUDY, contact EEGLAB support');
else
fprintf('Duplicate entry detected in Design %d, reinitializing design\n', inddes);
[STUDY com] = std_makedesign(STUDY, ALLEEG, inddes, STUDY.design(inddes), 'defaultdesign', 'forceoff');
end
end;
end;
end;
if rebuild_design % in case datasets have been added or removed
STUDY = std_rebuilddesign(STUDY, ALLEEG);
end;
% scan design to fix old paring format
% ------------------------------------
for design = 1:length(STUDY.design)
for var = 1:length(STUDY.design(design).variable)
if isstr(STUDY.design(design).variable(1).pairing)
if strcmpi(STUDY.design(design).variable(1).pairing, 'paired')
STUDY.design(design).variable(1).pairing = 'on';
elseif strcmpi(STUDY.design(design).variable(1).pairing, 'unpaired')
STUDY.design(design).variable(1).pairing = 'off';
end;
end;
if isstr(STUDY.design(design).variable(2).pairing)
if strcmpi(STUDY.design(design).variable(2).pairing, 'paired')
STUDY.design(design).variable(2).pairing = 'on';
elseif strcmpi(STUDY.design(design).variable(2).pairing, 'unpaired')
STUDY.design(design).variable(2).pairing = 'off';
end;
end;
end;
end;
% add filepath field if absent
for ind = 1:length(STUDY.design)
if ~isfield(STUDY.design, 'filepath') || (isnumeric(STUDY.design(ind).filepath) && isempty(STUDY.design(ind).filepath))
STUDY.design(ind).filepath = '';
STUDY.saved = 'no';
modif = 1;
end;
end;
% check that ICA is present and if it is update STUDY.datasetinfo
allcompsSTUDY = { STUDY.datasetinfo.comps };
allcompsALLEEG = { ALLEEG.icaweights };
if all(cellfun(@isempty, allcompsSTUDY)) && ~all(cellfun(@isempty, allcompsALLEEG))
for index = 1:length(STUDY.datasetinfo)
STUDY.datasetinfo(index).comps = [1:size(ALLEEG(index).icaweights,1)];
end;
end;
% make channel groups
% -------------------
if ~isfield(STUDY, 'changrp') || isempty(STUDY.changrp)
STUDY = std_changroup(STUDY, ALLEEG);
modif = 1;
end;
end;
% determine if there has been any change
% --------------------------------------
if modif;
STUDY.saved = 'no';
command = '[STUDY ALLEEG] = std_checkset(STUDY, ALLEEG);';
addToHistory = true;
% check duplicate
if length(STUDY.history) >= length(command) && strcmpi(STUDY.history(end-length(command)+1:end), command)
addToHistory = false;
end;
if addToHistory
STUDY.history = sprintf('%s\n%s', STUDY.history, command);
end;
end;
% convert combined independent variables
% --------------------------------------
function val = convertindvarval(val);
if isstr(val)
inddash = findstr(' - ', val);
if isempty(inddash), return; end;
inddash = [ -2 inddash length(val)+1];
for ind = 1:length(inddash)-1
newval{ind} = val(inddash(ind)+3:inddash(ind+1)-1);
end;
val = newval;
end;
|
github
|
lcnhappe/happe-master
|
std_checkfiles.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_checkfiles.m
| 7,593 |
utf_8
|
6ac22d4c5d62c3eaf4f9a4888c9fa0a9
|
% std_checkfiles() - Check all STUDY files consistency
%
% Usage:
% >> boolval = std_checkfiles(STUDY, ALLEEG);
% Inputs:
% STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - All EEGLAB datasets
%
% Outputs:
% boolval - [0|1] 1 if uniform
%
% Authors: Arnaud Delorme, CERCO, 2010-
% Copyright (C) Arnaud Delorme, CERCO
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public 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 [boolval npersubj] = std_checkfiles(STUDY, ALLEEG);
if nargin < 2
help std_checkfiles;
return;
end;
return;
filetypes = { 'daterp' 'datspec' 'datersp' 'datitc' 'dattimef' ...
'icaerp' 'icaspec' 'icaersp' 'icaitc' 'icatopo' };
% set channel interpolation mode
% ------------------------------
uniformchannels = std_uniformsetinds( STUDY );
disp('---------------------------------------------');
disp('Checking data files integrity and consistency');
passall = 1;
for index = 1:length(filetypes)
% scan datasets
% -------------
[ tmpstruct compinds filepresent ] = std_fileinfo(ALLEEG, filetypes{index});
if ~isempty(tmpstruct)
fprintf('Files of type "%s" detected, checking...', filetypes{index});
end;
% check if the structures are equal
% ---------------------------------
notequal = any(~filepresent);
if ~isempty(tmpstruct)
if any(filepresent == 0)
fprintf(' Error, some files inconsistent or missing\n');
notequal = 1;
passall = 0;
else
firstpass = 1;
fields = fieldnames(tmpstruct);
for f_ind = 1:length(fields)
firstval = getfield(tmpstruct, {1}, fields{f_ind});
for dat = 2:length(tmpstruct)
tmpval = getfield(tmpstruct, {dat}, fields{f_ind});
if ~isequal(firstval, tmpval)
% check for NaNs
if iscell(firstval) && iscell(tmpval)
for cind = 1:length(firstval)
if isreal(firstval{cind}) && ~isempty(firstval{cind}) && isnan(firstval{cind}(1))
firstval{cind} = 'NaN';
end;
end;
for cind = 1:length(tmpval)
if isreal(tmpval{cind}) && ~isempty(tmpval{cind}) && isnan(tmpval{cind}(1))
tmpval{cind} = 'NaN';
end;
end;
end;
if ~isequal(firstval, tmpval)
if ~strcmpi(fields{f_ind}, 'labels') || strcmpi(uniformchannels, 'on')
if firstpass == 1, fprintf('\n'); firstpass = 0; end;
fprintf(' Error, difference accross data files for field "%s"\n', fields{f_ind});
notequal = 1;
passall = 0;
break;
end;
end;
end;
end;
end;
end;
end;
% check the consistency of changrp and cluster with saved information
% -------------------------------------------------------------------
if isempty(tmpstruct), notequal = 1; end;
if filetypes{index}(1) == 'd' && notequal == 0
% scan all channel labels
% -----------------------
if isfield(tmpstruct(1), 'labels')
for cind = 1:length(STUDY.changrp)
if notequal == 0
for inddat = 1:length(ALLEEG)
tmpind = cellfun(@(x)(find(x == inddat)), STUDY.changrp(cind).setinds(:), 'uniformoutput', false);
indnonempty = find(~cellfun(@isempty, tmpind(:)));
if ~isempty(indnonempty)
tmpchan = STUDY.changrp(cind).allinds{indnonempty}(tmpind{indnonempty}); % channel index for dataset inddat
tmpchan2 = strmatch(STUDY.changrp(cind).name, tmpstruct(inddat).labels, 'exact'); % channel index in file
if ~isempty(tmpchan2) || ~strcmpi(filetypes{index}, 'datspec') % the last statement is because channel labels did not use to be saved in spec files
if ~isequal(tmpchan2, tmpchan)
fprintf('\nError: channel index in STUDY.changrp(%d) for dataset %d is "%d" but "%d" in data files\n', cind, inddat, tmpchan, tmpchan2);
notequal = 1;
break;
end;
end;
end;
end;
end;
end;
end;
elseif notequal == 0 && ~isempty(STUDY.cluster) % components
% check that the cell structures are present
% ------------------------------------------
if ~isfield(STUDY.cluster, 'setinds')
STUDY.cluster(1).setinds = [];
STUDY.cluster(1).allinds = [];
end;
for cind = 1:length(STUDY.cluster)
if isempty(STUDY.cluster(cind).setinds)
STUDY.cluster(cind) = std_setcomps2cell(STUDY, cind);
end;
end;
for cind = 1:length(STUDY.cluster)
if notequal == 0
for inddat = 1:length(ALLEEG)
tmpind = cellfun(@(x)(find(x == inddat)), STUDY.cluster(cind).setinds(:), 'uniformoutput', false);
indnonempty = find(~cellfun(@isempty, tmpind(:)));
tmpcomp = [];
for jind = 1:length(indnonempty)
tmpcomp = [ tmpcomp STUDY.cluster(cind).allinds{indnonempty(jind)}(tmpind{indnonempty(jind)}) ];
end;
if ~isempty(setdiff(tmpcomp, compinds{inddat}))
if ~(isempty(compinds{inddat}) && strcmpi(filetypes{index}, 'icatopo'))
fprintf('\nError: some components in clusters %d are absent from .%s files\n', cind, filetypes{index});
notequal = 1;
passall = 0;
break;
end;
end;
end;
end;
end;
end;
if notequal == 0, fprintf(' Pass\n'); end;
end;
if ~passall
disp('**** Recompute any measure above not receiving a "Pass" by')
disp('**** calling menu items "STUDY > Precompute Channel/Component measures" ');
disp('**** and by selecting the "Recompute even if present on disk" checkbox');
end;
disp('Checking completed.');
|
github
|
lcnhappe/happe-master
|
std_specgram.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_specgram.m
| 14,400 |
utf_8
|
c47a0f3d1446e9f4aa6ccb9446dc533a
|
% std_specgram() - Returns the ICA component or channel spectrogram for a dataset.
% Saves the spectra in a file.
% Usage:
% >> [spec freqs] = std_specgram(EEG, 'key', 'val', ...);
%
% Inputs:
% EEG - a loaded epoched EEG dataset structure.
%
% Optional inputs:
% 'components' - [numeric vector] components of the EEG structure for which
% activation spectogram will be computed. Note that because
% computation of component spectra is relatively fast, all
% components spectra are computed and saved. Only selected
% component are returned by the function to Matlab
% {default|[] -> all}
% 'channels' - [cell array] channels of the EEG structure for which
% activation spectogram will be computed. Note that because
% computation of spectrum is relatively fast, all channels
% spectrum are computed and saved. Only selected channels
% are returned by the function to Matlab
% {default|[] -> none}
% 'recompute' - ['on'|'off'] force recomputing ERP file even if it is
% already on disk.
%
% Other optional spectral parameters:
% All optional parameters to the newtimef function may be provided to this function
% as well.
%
% Outputs:
% spec - the mean spectra (in dB) of the requested ICA components in the selected
% frequency range (with the mean of each spectrum removed).
% freqs - a vector of frequencies at which the spectra have been computed.
%
% Files output or overwritten for ICA:
% [dataset_filename].icaspecgram,
% Files output or overwritten for data:
% [dataset_filename].datspecgram,
%
% See also spectopo(), std_erp(), std_ersp(), std_map(), std_preclust()
%
% Authors: Arnaud Delorme, SCCN, INC, UCSD, January, 2005
% Defunct: 0 -> if frequency range is different from saved spectra, ask via a
% pop-up window whether to keep existing spectra or to overwrite them.
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 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
% eeg_specgram() - Compute spectrogramme taking into account boundaries in
% the data.
% Usage:
% >> EEGOUT = eeg_specgram( EEG, typeplot, num, 'key', 'val');
%
% Inputs:
% EEG - EEG dataset structure
% typeplot - type of processinopt. 1 process the raw
% data and 0 the ICA components
% num - component or channel number
%
% Optional inputs:
% 'winsize' - [integer] window size in points
% 'overlap' - [integer] window overlap in points (default: 0)
% 'movav' - [real] moving average
%
% Author: Arnaud Delorme, CERCO, CNRS, 2008-
% 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 [erspinterp t f ] = eeg_specgram(EEG, varargin);
if nargin < 1
help std_specgram;
return;
end;
[opt moreopts] = finputcheck(varargin, { 'components' 'integer' [] [];
'channels' { 'cell','integer' } { [] [] } {}
'recompute' 'string' { 'on','off' } 'off';
'winsize' 'integer' [] 3; % 3 seconds
'rmcomps' 'integer' [] [];
'interp' 'struct' { } struct([]);
'overlap' 'integer' [] 0;
'plot' 'string' { 'off','on' } 'off';
'freqrange' 'real' [] [];
'timerange' 'real' [] [];
'filter' 'real' [] []}, ... % 11 points
'eeg_specgram', 'ignore');
if isstr(opt), error(opt); end;
if isfield(EEG,'icaweights')
numc = size(EEG.icaweights,1);
else
error('EEG.icaweights not found');
end
if isempty(opt.components)
opt.components = 1:numc;
end
%opt.winsize = 2^ceil(log2(opt.winsize*EEG.srate));
opt.winsize = opt.winsize*EEG.srate;
% filename
% --------
if ~isempty(opt.channels)
filename = fullfile( EEG.filepath,[ EEG.filename(1:end-3) 'datspecgram']);
prefix = 'chan';
opt.indices = opt.channels;
if iscell(opt.channels)
tmpchanlocs = EEG(1).chanlocs;
for index = 1:length(opt.channels)
chanind = strmatch( lower(opt.channels{index}), lower({ tmpchanlocs.labels }), 'exact');
if isempty(chanind), error('Channel group not found'); end;
chaninds(index) = chanind;
end;
opt.indices = chaninds;
opt.channels = chaninds;
end;
else
filename = fullfile( EEG.filepath,[ EEG.filename(1:end-3) 'icaspecgram']);
prefix = 'comp';
opt.indices = opt.components;
end;
% SPEC information found in datasets
% ----------------------------------
if exist(filename) & strcmpi(opt.recompute, 'off')
if strcmpi(prefix, 'comp')
[erspinterp, t, f] = std_readspecgram(EEG, 1, opt.components, opt.freqrange);
else
[erspinterp, t, f] = std_readspecgram(EEG, 1, -opt.channels, opt.freqrange);
end;
return;
end
% No SPEC information found
% ------------------------
options = {};
if strcmpi(prefix, 'comp')
X = eeg_getdatact(EEG, 'component', [1:size(EEG.icaweights,1)]);
else
EEG.data = eeg_getdatact(EEG, 'channel', [1:EEG.nbchan], 'rmcomps', opt.rmcomps);
if ~isempty(opt.rmcomps), options = { options{:} 'rmcomps' opt.rmcomps }; end;
if ~isempty(opt.interp),
EEG = eeg_interp(EEG, opt.interp, 'spherical');
end;
X = EEG.data;
end;
% get the array of original point latency
% ---------------------------------------
urpnts = eeg_urpnts(EEG);
urarray = eeg_makeurarray(EEG, urpnts); % contain the indices of the urpoint in the EEG data
% urarray(1000) = 1000, urarray(2300) = 1600 if part removed in the data
urwincenter = opt.winsize/2+1:opt.winsize-opt.overlap:urpnts-opt.winsize/2;
wintag = ones(1, length(urwincenter));
if EEG.trials == 1
for i = 1:length(urwincenter)
win = urwincenter(i)+[-opt.winsize/2+1:opt.winsize/2];
if ~all(urarray(win))
wintag(i) = 0;
%fprintf('Missing data window: %3.1f-%3.1f s\n', (win(1)-1)/EEG.srate, (win(end)-1)/EEG.srate);
end;
end;
else
error('eeg_specgram can only be run on continuous data');
end;
% compute spectrum 2 solutions
% 1- use newtimef, have to set the exact times and window
% 2- redo the FFT myself
% ----------------------
wincenter = urwincenter(find(wintag)); % remove bad windows
wincenter = urarray(wincenter); % latency in current dataset
wincenter = 1000*(wincenter-1)/EEG.srate; % convert to ms
freqs = linspace(0.1, 50, 100);
options = { 0 'winsize', opt.winsize, 'baseline', [0 Inf], 'timesout', wincenter, ...
'plotersp', 'off', 'plotitc', 'off', 'freqs', freqs };
%freqs = exp(linspace(log(EEG.srate/opt.winsize*4), log(50), 100));
%cycles = linspace(3,8,100);
%options = { [3 0.8] 'winsize', opt.winsize, 'baseline', [0 Inf], 'timesout', wincenter, ...
% 'freqs' freqs 'cycles' cycles 'plotersp', 'off', 'plotitc', 'off' };
for ic = 1:length(opt.indices)
[ersp(:,:,ic) itc powebase t f] = newtimef(X(opt.indices(ic), :), EEG.pnts, [EEG.xmin EEG.xmax]*1000, EEG.srate, options{:}, moreopts{:});
end;
% interpolate and smooth in time
% ------------------------------
disp('Now interpolating...');
wininterp = find(wintag == 0);
erspinterp = zeros(size(ersp,1), length(urwincenter), size(ersp,3));
erspinterp(:,find(wintag),:) = ersp;
for s = 1:size(ersp,3)
for i=1:length(wininterp)
first1right = find(wintag(wininterp(i):end));
first1left = find(wintag(wininterp(i):-1:1));
if isempty(first1right)
erspinterp(:,wininterp(i),s) = erspinterp(:,wininterp(i)+1-first1left(1),s);
elseif isempty(first1left)
erspinterp(:,wininterp(i),s) = erspinterp(:,wininterp(i)-1+first1right(1),s);
else
erspinterp(:,wininterp(i),s) =(erspinterp(:,wininterp(i)-1+first1right(1),s) + erspinterp(:,wininterp(i)+1-first1left(1),s))/2;
end;
end;
end;
%erspinterp = vectdata(ersp, urwincenter(find(wintag))/EEG.srate, 'timesout', urwincenter/EEG.srate);
% smooth in time with a simple convolution
% ----------------------------------------
if ~isempty(opt.filter)
filterlen = opt.filter(1);
filterstd = opt.filter(2);
incr = 2*filterstd/(filterlen-1); %gaussian filter
filter = exp(-(-filterstd:incr:filterstd).^2);
erspinterp = convn(erspinterp, filter/sum(filter), 'same');
%erspinterp = conv2(erspinterp, filter/sum(filter));
%erspinterp(:, [1:(filterlen-1)/2 end-(filterlen-1)/2+1:end]) = [];
end;
% plot result
% -----------
t = (urwincenter-1)/EEG.srate;
if strcmpi(opt.plot, 'on')
figure; imagesc(t, log(f), erspinterp);
ft = str2num(get(gca,'yticklabel'));
ft = exp(1).^ft;
ft = unique_bc(round(ft));
ftick = get(gca,'ytick');
ftick = exp(1).^ftick;
ftick = unique_bc(round(ftick));
ftick = log(ftick);
set(gca,'ytick',ftick);
set(gca,'yticklabel', num2str(ft));
xlabel('Time (h)');
ylabel('Frequency (Hz)');
set(gca, 'ydir', 'normal');
end;
% Save SPECs in file (all components or channels)
% ----------------------------------
options = { 'winsize' opt.winsize 'overlap' opt.overlap moreopts{:} };
if strcmpi(prefix, 'comp')
savetofile( filename, t, f, erspinterp, 'comp', opt.indices, options, [], opt.interp);
[erspinterp, t, f] = std_readspecgram(EEG, 1, opt.components, opt.timerange, opt.freqrange);
else
tmpchanlocs = EEG(1).chanlocs;
savetofile( filename, t, f, erspinterp, 'chan', opt.indices, options, { tmpchanlocs.labels }, opt.interp);
[erspinterp, t, f] = std_readspecgram(EEG, 1, -opt.channels, opt.timerange, opt.freqrange);
end;
return;
% recompute the original data length in points
% --------------------------------------------
function urlat = eeg_makeurarray(EEG, urpnts);
if isempty(EEG.event) | ~isfield(EEG.event, 'duration')
urlat = 1:EEG.pnts;
return;
end;
% get boundary events latency and duration
% ----------------------------------------
tmpevent = EEG.event;
bounds = strmatch('boundary', { tmpevent.type });
alldurs = [ tmpevent(bounds).duration ];
alllats = [ tmpevent(bounds).latency ];
if length(alldurs) >= 1
if alldurs(1) <= 1
alllats(1) = [];
alldurs(1) = [];
end;
end;
if isempty(alllats)
urlat = 1:EEG.pnts;
return;
end;
% build the ur boolean array
% --------------------------
urlat = ones(1, urpnts);
for i=1:length(alllats)
urlat(round(alllats(i)+0.5):round(alllats(i)+0.5+alldurs(i)-1)) = 0;
alllats(i+1:end) = alllats(i+1:end)+alldurs(i);
end;
urlat(find(urlat)) = 1:EEG.pnts;
% -------------------------------------
% saving SPEC information to Matlab file
% -------------------------------------
function savetofile(filename, t, f, X, prefix, comps, params, labels, interp);
disp([ 'Saving SPECTRAL file ''' filename '''' ]);
allspec = [];
for k = 1:length(comps)
allspec = setfield( allspec, [ prefix int2str(comps(k)) ], X(:,:,k));
end;
if ~isempty(labels)
allspec.labels = labels;
end;
allspec.freqs = f;
allspec.times = t;
allspec.parameters = params;
allspec.datatype = 'SPECTROGRAM';
allerp.interpolation = fastif(isempty(interp), 'no', interp);
allspec.average_spec = mean(X,1);
std_savedat(filename, allspec);
% recompute the original data length in points
% --------------------------------------------
function pntslat = eeg_urpnts(EEG);
if isempty(EEG.event) | ~isfield(EEG.event, 'duration')
pntslat = EEG.pnts;
return;
end;
tmpevent = EEG.event;
bounds = strmatch('boundary', { tmpevent.type });
alldurs = [ tmpevent(bounds).duration ];
if length(alldurs) > 0
if alldurs(1) <= 1, alldurs(1) = [];
end;
end;
pntslat = EEG.pnts + sum(alldurs);
% recompute the original latency
% ------------------------------
function pntslat = eeg_urlatency(EEG, pntslat);
if isempty(EEG.event), return; end;
if ~isstr(EEG.event(1).type), return; end;
tmpevent = EEG.event;
bounds = strmatch('boundary', { tmpevent.type })
for i=1:length(bounds)
if EEG.event(bounds(i)).duration > 1
pntslat = pntslat + EEG.event(bounds(i)).duration;
end;
end;
|
github
|
lcnhappe/happe-master
|
pop_preclust.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/pop_preclust.m
| 35,559 |
utf_8
|
18c27f006ac8293d4a4fdf78bb6cc55b
|
% pop_preclust() - prepare STUDY components' location and activity measures for later clustering.
% Collect information in an interactive pop-up query window. To pre-cluster
% from the commandline, use std_preclust(). After data entry into the pop window,
% selected measures (one or more from options: ERP, dipole locations, spectra,
% scalp maps, ERSP, and ITC) are computed for each dataset in the STUDY
% set, unless they already present. After all requested measures are computed
% and saved in the STUDY datasets, a PCA matrix (by runica() with 'pca' option)
% is constructed (this is the feature reduction step). This matrix will be used
% as input to the clustering algorithm in pop_clust(). pop_preclust() allows
% selection of a subset of components to cluster. This subset may either be
% user-specified, all components with dipole model residual variance lower than
% a defined threshold (see dipfit()), or components from an already existing cluster
% (for hierarchical clustering). The EEG datasets in the ALLEEG structure are
% updated; then the updated EEG sets are saved to disk. Calls std_preclust().
% Usage:
% >> [STUDY, ALLEEG] = pop_preclust(STUDY, ALLEEG); % pop up interactive window
% >> [STUDY, ALLEEG] = pop_preclust(STUDY, ALLEEG, clustind); % sub-cluster
%
% Inputs:
% STUDY - STUDY set structure containing (loaded) EEG dataset structures
% ALLEEG - ALLEEG vector of EEG structures, else a single EEG dataset.
% clustind - (single) cluster index to sub-cluster, Hhierarchical clustering may be
% useful, for example, to separate a bilteral cluster into left and right
% hemisphere sub-clusters. Should be empty for whole STUDY (top level) clustering
% {default: []}
% Outputs:
% STUDY - the input STUDY set with added pre-clustering data for use by pop_clust()
% ALLEEG - the input ALLEEG vector of EEG dataset structures modified by adding
% pre-clustering data (pointers to .mat files that hold cluster measure information).
%
% Authors: Arnaud Delorme, Hilit Serby & Scott Makeig, SCCN, INC, UCSD, May 13, 2004-
%
% See also: std_preclust()
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, May 13,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
function [STUDY, ALLEEG, com] = pop_preclust(varargin)
com = '';
if ~isstr(varargin{1}) %intial settings
if length(varargin) < 2
error('pop_preclust(): needs both ALLEEG and STUDY structures');
end
STUDY = varargin{1};
ALLEEG = varargin{2};
if length(varargin) >= 3
if length(varargin{3}) > 1
error('pop_preclust(): To cluster components from several clusters, merge them first!');
end
cluster_ind = varargin{3};
else
cluster_ind = [];
end
scalp_options = {'Use channel values' 'Use Laplacian values' 'Use Gradient values'} ;
if isempty(ALLEEG)
error('STUDY contains no datasets');
end
if any(isnan(STUDY.cluster(1).sets(:)))
warndlg2( [ 'FOR CLUSTERING, YOU MAY ONLY USE DIPOLE OR SCALP MAP CLUSTERING.' 10 ...
'This is because some datasets do not have ICA pairs. Look for NaN values in ' 10 ...
'STUDY.cluster(1).sets which indicate missing datasets. Each column in this ' 10 ...
'array indicate datasets with common ICA decompositions' ]);
end;
if length(STUDY.design(STUDY.currentdesign).cases.value) ~= length(STUDY.subject)
warndlg2( [ 'GO BACK TO THE DESIGN INTERFACE AND SELECT A DESIGN THAT ' 10 ...
'INCLUDES ALL DATASETS. Some subjects or datasets have been excluded' 10 ...
'in the current design. ICA clusters are common to all designs, so all' 10 ...
'all datasets must be included for clustering. After clustering, you' 10 ...
'will then be able to select a different design (and keep the clustered' 10 ...
'components) if you wish to exclude a subject or group of dataset.' ]);
return;
end
% cluster text
% ------------
% load leaf clusters
num_cls = 0;
cls = 1:length(STUDY.cluster);
N = length(cls); %number of clusters
show_options{1} = [STUDY.cluster(1).name ' (' num2str(length(STUDY.cluster(1).comps)) ' ICs)'];
cls(1) = 1;
count = 2;
for index1 = 1:length(STUDY.cluster(1).child)
indclust1 = strmatch( STUDY.cluster(1).child(index1), { STUDY.cluster.name }, 'exact');
show_options{count} = [' ' STUDY.cluster(indclust1).name ' (' num2str(length(STUDY.cluster(indclust1).comps)) ' ICs)'];
cls(count) = indclust1;
count = count+1;
for index2 = 1:length( STUDY.cluster(indclust1).child )
indclust2 = strmatch( STUDY.cluster(indclust1).child(index2), { STUDY.cluster.name }, 'exact');
show_options{count} = [' ' STUDY.cluster(indclust2).name ' (' num2str(length(STUDY.cluster(indclust2).comps)) ' ICs)'];
cls(count) = indclust2;
count = count+1;
for index3 = 1:length( STUDY.cluster(indclust2).child )
indclust3 = strmatch( STUDY.cluster(indclust2).child(index3), { STUDY.cluster.name }, 'exact');
show_options{count} = [' ' STUDY.cluster(indclust3).name ' (' num2str(length(STUDY.cluster(indclust3).comps)) ' ICs)'];
cls(count) = indclust3;
count = count+1;
end;
end;
end;
% callbacks
% ---------
erspparams_str = [ '''cycles'', [3 0.5], ''padratio'', 1' ];
specparams_str = '';
show_clust = [ 'pop_preclust(''showclust'',gcf);'];
show_comps = [ 'pop_preclust(''showcomplist'',gcf);'];
help_spectopo = ['pophelp(''spectopo'')'];
set_spectra = ['pop_preclust(''setspec'',gcf);'];
set_erp = ['pop_preclust(''seterp'',gcf);'];
set_scalp = ['pop_preclust(''setscalp'',gcf);'];
set_dipole = ['pop_preclust(''setdipole'',gcf);'];
set_ersp = ['pop_preclust(''setersp'',gcf);'];
set_itc = ['pop_preclust(''setitc'',gcf);'];
set_secpca = ['pop_preclust(''setsec'',gcf);'];
set_mpcluster = ['tmp_preclust(''mpcluster'',gcf);']; % nima
help_clusteron = ['pophelp(''std_helpselecton'');'];
help_ersp = ['pophelp(''pop_timef'')'];
preclust_PCA = ['pop_preclust(''preclustOK'',gcf);'];
ersp_params = ['pop_preclust(''erspparams'',gcf);'];
ersp_edit = ['pop_preclust(''erspedit'',gcf);'];
test_ersp = ['pop_precomp(''testersp'',gcf);'];
itc_edit = 'set(findobj(gcbf, ''tag'', ''ersp_params''), ''string'', get(gcbo, ''string''));';
ersp_edit = 'set(findobj(gcbf, ''tag'', ''itc_params'' ), ''string'', get(gcbo, ''string''));';
saveSTUDY = [ 'set(findobj(''parent'', gcbf, ''userdata'', ''save''), ''enable'', fastif(get(gcbo, ''value'')==1, ''on'', ''off''));' ];
browsesave = [ '[filename, filepath] = uiputfile2(''*.study'', ''Save STUDY with .study extension -- pop_preclust()''); ' ...
'set(findobj(''parent'', gcbf, ''tag'', ''studyfile''), ''string'', [filepath filename]);' ];
str_name = ['Build pre-clustering matrix for STUDY set: ' STUDY.name '' ];
str_time = '';
help_secpca = [ 'warndlg2(strvcat(''This is the final number of dimensions (otherwise use the sum'',' ...
'''of dimensions for all the selected options). See tutorial for more info''), ''Final number of dimensions'');' ];
gui_spec = { ...
{'style' 'text' 'string' str_name 'FontWeight' 'Bold' 'horizontalalignment' 'left'} ...
{'style' 'text' 'string' 'Select the cluster to refine by sub-clustering (any existing sub-hierarchy will be overwritten)' } {} ...
{'style' 'listbox' 'string' show_options 'value' 1 'tag' 'clus_list' 'Callback' show_clust 'max' 1 } {} {} ...
{'style' 'text' 'string' 'Note: Only measures that have been precomputed may be used for clustering.'} ...
{'style' 'text' 'string' 'Measures Dims. Norm. Rel. Wt.' 'FontWeight' 'Bold'} ...
{'style' 'checkbox' 'string' '' 'tag' 'spectra_on' 'value' 0 'Callback' set_spectra 'userdata' '1'} ...
{'style' 'text' 'string' 'spectra' 'horizontalalignment' 'center' } ...
{'style' 'edit' 'string' '10' 'tag' 'spectra_PCA' 'enable' 'off' 'userdata' 'specP'} ...
{'style' 'checkbox' 'string' '' 'tag' 'spectra_norm' 'value' 1 'enable' 'off' 'userdata' 'specP' } ...
{'style' 'edit' 'string' '1' 'tag' 'spectra_weight' 'enable' 'off' 'userdata' 'specP'} ...
{'style' 'text' 'string' 'Freq.range [Hz]' 'tag' 'spectra_freq_txt' 'userdata' 'spec' 'enable' 'off' } ...
{'style' 'edit' 'string' '3 25' 'tag' 'spectra_freq_edit' 'userdata' 'spec' 'enable' 'off' } { } { } ...
{'style' 'checkbox' 'string' '' 'tag' 'erp_on' 'value' 0 'Callback' set_erp 'userdata' '1'} ...
{'style' 'text' 'string' 'ERPs' 'horizontalalignment' 'center' } ...
{'style' 'edit' 'string' '10' 'tag' 'erp_PCA' 'enable' 'off' 'userdata' 'erpP'} ...
{'style' 'checkbox' 'string' '' 'tag' 'erp_norm' 'value' 1 'enable' 'off' 'userdata' 'erpP' } ...
{'style' 'edit' 'string' '1' 'tag' 'erp_weight' 'enable' 'off' 'userdata' 'erpP'} ...
{'style' 'text' 'string' 'Time range [ms]' 'tag' 'erp_time_txt' 'userdata' 'erp' 'enable' 'off' } ...
{'style' 'edit' 'string' str_time 'tag' 'erp_time_edit' 'userdata' 'erp' 'enable' 'off' } { } { }...
{'style' 'checkbox' 'string' '' 'tag' 'dipole_on' 'value' 0 'Callback' set_dipole 'userdata' '1'} ...
{'style' 'text' 'string' 'dipoles' 'HorizontalAlignment' 'center' } ...
{'style' 'text' 'string' '3' 'enable' 'off' 'userdata' 'dipoleP' } ...
{'style' 'checkbox' 'string' '' 'tag' 'locations_norm' 'value' 1 'enable' 'off' 'userdata' 'dipoleP'} ...
{'style' 'edit' 'string' '10' 'tag' 'locations_weight' 'enable' 'off' 'userdata' 'dipoleP'} {} {} {} {} ...
{'style' 'checkbox' 'string' '' 'tag' 'scalp_on' 'value' 0 'Callback' set_scalp 'userdata' '1'} ...
{'style' 'text' 'string' 'scalp maps' 'HorizontalAlignment' 'center' } ...
{'style' 'edit' 'string' '10' 'tag' 'scalp_PCA' 'enable' 'off' 'userdata' 'scalpP'} ...
{'style' 'checkbox' 'string' '' 'tag' 'scalp_norm' 'value' 1 'enable' 'off' 'userdata' 'scalpP'} ...
{'style' 'edit' 'string' '1' 'tag' 'scalp_weight' 'enable' 'off' 'userdata' 'scalpP'} ...
{'style' 'popupmenu' 'string' scalp_options 'value' 1 'tag' 'scalp_choice' 'enable' 'off' 'userdata' 'scalp' } {} ...
{'style' 'checkbox' 'string' 'Absolute values' 'value' 1 'tag' 'scalp_absolute' 'enable' 'off' 'userdata' 'scalp' } {} ...
{'style' 'checkbox' 'string' '' 'tag' 'ersp_on' 'value' 0 'Callback' set_ersp 'userdata' '1'} ...
{'style' 'text' 'string' 'ERSPs' 'horizontalalignment' 'center' } ...
{'style' 'edit' 'string' '10' 'tag' 'ersp_PCA' 'enable' 'off' 'userdata' 'erspP'} ...
{'style' 'checkbox' 'string' '' 'tag' 'ersp_norm' 'value' 1 'enable' 'off' 'userdata' 'erspP'} ...
{'style' 'edit' 'string' '1' 'tag' 'ersp_weight' 'enable' 'off' 'userdata' 'erspP'} ...
{'style' 'text' 'string' 'Time range [ms]' 'tag' 'ersp_time_txt' 'userdata' 'ersp' 'enable' 'off' } ...
{'style' 'edit' 'string' str_time 'tag' 'ersp_time_edit' 'userdata' 'ersp' 'enable' 'off' } ...
{'style' 'text' 'string' 'Freq. range [Hz]' 'tag' 'ersp_time_txt' 'userdata' 'ersp' 'enable' 'off' } ...
{'style' 'edit' 'string' str_time 'tag' 'ersp_freq_edit' 'userdata' 'ersp' 'enable' 'off' } ...
{'style' 'checkbox' 'string' '' 'tag' 'itc_on' 'value' 0 'Callback' set_itc 'userdata' '1'} ...
{'style' 'text' 'string' 'ITCs' 'horizontalalignment' 'center' } ...
{'style' 'edit' 'string' '10' 'tag' 'itc_PCA' 'enable' 'off' 'userdata' 'itcP'} ...
{'style' 'checkbox' 'string' '' 'tag' 'itc_norm' 'value' 1 'enable' 'off' 'userdata' 'itcP'} ...
{'style' 'edit' 'string' '1' 'tag' 'itc_weight' 'enable' 'off' 'userdata' 'itcP'} ...
{'style' 'text' 'string' 'Time range [ms]' 'tag' 'itc_time_txt' 'userdata' 'itcP' 'enable' 'off' } ...
{'style' 'edit' 'string' str_time 'tag' 'itc_time_edit' 'userdata' 'itcP' 'enable' 'off' } ...
{'style' 'text' 'string' 'Freq. range [Hz]' 'tag' 'itc_time_txt' 'userdata' 'itcP' 'enable' 'off' } ...
{'style' 'edit' 'string' str_time 'tag' 'itc_freq_edit' 'userdata' 'itcP' 'enable' 'off' } ...
{} ...
{'style' 'checkbox' 'string' '' 'tag' 'sec_on' 'Callback' set_secpca 'value' 0} ...
{'style' 'text' 'string' 'Final dimensions' } ...
{'style' 'edit' 'string' '10' 'enable' 'off' 'tag' 'sec_PCA' 'userdata' 'sec' } ...
{} {'style' 'pushbutton' 'string' 'Help' 'tag' 'finalDimHelp' 'callback' help_secpca } {} {} {} {} };
% {'link2lines' 'style' 'text' 'string' '' } {} {} {} ...
% {'style' 'text' 'string' 'Time/freq. parameters' 'tag' 'ersp_push' 'value' 1 'enable' 'off' 'userdata' 'ersp' 'Callback' ersp_params} ...
% {'style' 'edit' 'string' erspparams_str 'tag' 'ersp_params' 'enable' 'off' 'userdata' 'ersp' 'Callback' ersp_edit}...
% {'style' 'text' 'string' 'Time/freq. parameters' 'tag' 'itc_push' 'value' 1 'enable' 'off' 'userdata' 'itc' 'Callback' ersp_params} ...
% {'style' 'edit' 'string' erspparams_str 'tag' 'itc_params' 'enable' 'off' 'userdata' 'itc' 'Callback' itc_edit}% {'style' 'checkbox' 'string' '' 'tag' 'preclust_PCA' 'Callback' preclust_PCA 'value' 0} ...
% {'style' 'text' 'string' 'Do not prepare dataset for clustering at this time.' 'FontWeight' 'Bold' } {} ...
fig_arg{1} = { ALLEEG STUDY cls };
geomline = [0.5 2 1 0.5 1 2 1 2 1 ];
geometry = { [1] [1] [1 1 1] [1] [1] ...
[3] geomline geomline geomline [0.5 2 1 0.5 1 2.9 .1 2.9 .1 ] geomline geomline [1] geomline };
geomvert = [ 1 1 3 1 1 1 1 1 1 1 1 1 0.5 1 ];
%if length(show_options) < 3
% gui_spec(2:6) = { {} ...
% { 'style' 'text' 'string' [ 'Among the pre-selected components (Edit study),' ...
% 'remove those which dipole res. var, exceed' ] 'tag' 'dipole_select_on' } ...
% {'style' 'edit' 'string' '0.15' 'horizontalalignment' 'center' 'tag' 'dipole_rv'} ...
% {'style' 'text' 'string' '(empty=all)'} {} };
% geometry{3} = [2.5 0.25 0.4];
% geomvert(3) = 1;
%end;
[preclust_param, userdat2, strhalt, os] = inputgui( 'geometry', geometry, 'uilist', gui_spec, 'geomvert', geomvert, ...
'helpcom', ' pophelp(''std_preclust'')', ...
'title', 'Select and compute component measures for later clustering -- pop_preclust()', ...
'userdata', fig_arg);
if isempty(preclust_param), return; end;
options = { STUDY, ALLEEG };
% precluster on what?
% -------------------
options{3} = cls(os.clus_list); % hierarchical clustering
%if ~(os.preclust_PCA) %create PCA data for clustering
%preclust_command = '[STUDY ALLEEG] = eeg_createdata(STUDY, ALLEEG, ';
%end
% Spectrum option is on
% --------------------
if os.spectra_on== 1
options{end+1} = { 'spec' 'npca' str2num(os.spectra_PCA) 'norm' os.spectra_norm ...
'weight' str2num(os.spectra_weight) 'freqrange' str2num(os.spectra_freq_edit) };
end
% ERP option is on
% ----------------
if os.erp_on == 1
options{end+1} = { 'erp' 'npca' str2num(os.erp_PCA) 'norm' os.erp_norm ...
'weight' str2num(os.erp_weight) 'timewindow' str2num(os.erp_time_edit) };
end
% Scalp maps option is on
% ----------------------
if os.scalp_on == 1
if os.scalp_absolute %absolute maps
abso = 1;
else abso = 0;
end
if (os.scalp_choice == 2) %Laplacian scalp maps
options{end+1} = { 'scalpLaplac' 'npca' str2num(os.scalp_PCA) 'norm' os.scalp_norm ...
'weight' str2num(os.scalp_weight) 'abso' abso };
elseif (os.scalp_choice == 3) %Gradient scalp maps
options{end+1} = { 'scalpGrad' 'npca' str2num(os.scalp_PCA) 'norm' os.scalp_norm, ...
'weight' str2num(os.scalp_weight) 'abso' abso };
elseif (os.scalp_choice == 1) %scalp map case
options{end+1} = { 'scalp' 'npca' str2num(os.scalp_PCA) 'norm' os.scalp_norm, ...
'weight' str2num(os.scalp_weight) 'abso' abso };
end
end
% Dipole option is on
% -------------------
if os.dipole_on == 1
options{end+1} = { 'dipoles' 'norm' os.locations_norm 'weight' str2num(os.locations_weight) };
end
% ERSP option is on
% -----------------
if os.ersp_on == 1
options{end+1} = { 'ersp' 'npca' str2num(os.ersp_PCA) 'freqrange' str2num(os.ersp_freq_edit) ...
'timewindow' str2num(os.ersp_time_edit) 'norm' os.ersp_norm 'weight' str2num(os.ersp_weight) };
end
% ITC option is on
% ----------------
if os.itc_on == 1
options{end+1} = { 'itc' 'npca' str2num(os.itc_PCA) 'freqrange' str2num(os.itc_freq_edit) 'timewindow' ...
str2num(os.itc_time_edit) 'norm' os.itc_norm 'weight' str2num(os.itc_weight) };
end
% ERSP option is on
% -----------------
if os.sec_on == 1
options{end+1} = { 'finaldim' 'npca' str2num(os.sec_PCA) };
end
% evaluate command
% ----------------
if length(options) == 3
warndlg2('No measure selected: aborting.');
return;
end;
[STUDY ALLEEG] = std_preclust(options{:});
com = sprintf('[STUDY ALLEEG] = std_preclust(STUDY, ALLEEG, %s);', vararg2str(options(3:end)));
% save updated STUDY to the disk
% ------------------------------
% if os.saveSTUDY == 1
% if ~isempty(os.studyfile)
% [filepath filename ext] = fileparts(os.studyfile);
% STUDY.filename = [ filename ext ];
% STUDY.filepath = filepath;
% end;
% STUDY = pop_savestudy(STUDY, ALLEEG, 'filename', STUDY.filename, 'filepath', STUDY.filepath);
% com = sprintf('%s\nSTUDY = pop_savestudy(STUDY, ALLEEG, %s);', com, ...
% vararg2str( { 'filename', STUDY.filename, 'filepath', STUDY.filepath }));
% end
else
hdl = varargin{2}; %figure handle
userdat = get(varargin{2}, 'userdat');
ALLEEG = userdat{1}{1};
STUDY = userdat{1}{2};
cls = userdat{1}{3};
N = length(cls);
switch varargin{1}
case 'setspec'
set_spec = get(findobj('parent', hdl, 'tag', 'spectra_on'), 'value');
set(findobj('parent', hdl, 'userdata', 'spec'), 'enable', fastif(set_spec,'on','off'));
PCA_on = get(findobj('parent', hdl, 'tag', 'preclust_PCA'), 'value');
if PCA_on
set(findobj('parent', hdl, 'userdata', 'specP'), 'enable', 'off');
else
set(findobj('parent', hdl, 'userdata', 'specP'), 'enable', fastif(set_spec,'on','off'));
end
case 'mpcluster' % nima
mpclust = get(findobj('parent', hdl, 'tag', 'mpclust'), 'value');
if mpclust
set(findobj('parent', hdl, 'tag', 'spectra_PCA'), 'visible','off');
set(findobj('parent', hdl, 'tag', 'spectra_norm'), 'visible','off');
set(findobj('parent', hdl, 'tag', 'spectra_weight'), 'visible','off');
set(findobj('parent', hdl, 'tag', 'erp_PCA' ), 'visible','off');
set(findobj('parent', hdl, 'tag','erp_norm' ), 'visible','off');
set(findobj('parent', hdl, 'tag','erp_weight' ), 'visible','off');
set(findobj('parent', hdl, 'tag', 'locations_norm' ), 'visible','off');
set(findobj('parent', hdl, 'tag','locations_weight'), 'visible','off');
set(findobj('parent', hdl, 'tag', 'scalp_PCA'), 'visible','off');
set(findobj('parent', hdl, 'tag','scalp_norm' ), 'visible','off');
set(findobj('parent', hdl, 'tag','scalp_weight'), 'visible','off');
set(findobj('parent', hdl, 'tag','ersp_PCA'), 'visible','off');
set(findobj('parent', hdl, 'tag', 'ersp_norm'), 'visible','off');
set(findobj('parent', hdl, 'tag','ersp_weight' ), 'visible','off');
set(findobj('parent', hdl, 'tag', 'itc_PCA'), 'visible','off');
set(findobj('parent', hdl, 'tag','itc_norm'), 'visible','off');
set(findobj('parent', hdl, 'tag','itc_weight'), 'visible','off');
set(findobj('parent', hdl, 'tag','sec_PCA'), 'visible','off');
set(findobj('parent', hdl, 'tag','sec_on'), 'visible','off');
set(findobj('parent', hdl, 'userdata' ,'dipoleP'), 'visible','off');
set(findobj('parent', hdl, 'string','Final dimensions'), 'visible','off');
set(findobj('parent', hdl, 'tag','finalDimHelp' ), 'visible','off');
set(findobj('parent', hdl, 'tag','spectra_freq_txt'), 'visible','off');
set(findobj('parent', hdl, 'tag','spectra_freq_edit'), 'visible','off');
%% these are made invisible for now, but in future we might use them in the new method
set(findobj('parent', hdl, 'tag','erp_time_txt'), 'visible','off');
set(findobj('parent', hdl, 'tag','erp_time_edit'), 'visible','off');
set(findobj('parent', hdl, 'tag','scalp_choice'), 'visible','off');
set(findobj('parent', hdl, 'tag', 'scalp_absolute'), 'visible','off');
set(findobj('parent', hdl, 'tag','ersp_time_txt'), 'visible','off');
set(findobj('parent', hdl, 'tag','ersp_time_edit'), 'visible','off');
set(findobj('parent', hdl, 'tag','ersp_freq_edit'), 'visible','off');
set(findobj('parent', hdl, 'tag','itc_time_txt'), 'visible','off');
set(findobj('parent', hdl, 'tag','itc_time_edit'), 'visible','off');
set(findobj('parent', hdl, 'tag','itc_freq_edit'), 'visible','off');
set(findobj('parent', hdl, 'string','Measures Dims. Norm. Rel. Wt.'), 'string','Measures');
else
set(findobj('parent', hdl, 'tag', 'spectra_PCA'), 'visible','on');
set(findobj('parent', hdl, 'tag', 'spectra_norm'), 'visible','on');
set(findobj('parent', hdl, 'tag', 'spectra_weight'), 'visible','on');
set(findobj('parent', hdl, 'tag', 'erp_PCA' ), 'visible','on');
set(findobj('parent', hdl, 'tag','erp_norm' ), 'visible','on');
set(findobj('parent', hdl, 'tag','erp_weight' ), 'visible','on');
set(findobj('parent', hdl, 'tag', 'locations_norm' ), 'visible','on');
set(findobj('parent', hdl, 'tag','locations_weight'), 'visible','on');
set(findobj('parent', hdl, 'tag', 'scalp_PCA'), 'visible','on');
set(findobj('parent', hdl, 'tag','scalp_norm' ), 'visible','on');
set(findobj('parent', hdl, 'tag','scalp_weight'), 'visible','on');
set(findobj('parent', hdl, 'tag','ersp_PCA'), 'visible','on');
set(findobj('parent', hdl, 'tag', 'ersp_norm'), 'visible','on');
set(findobj('parent', hdl, 'tag','ersp_weight' ), 'visible','on');
set(findobj('parent', hdl, 'tag', 'itc_PCA'), 'visible','on');
set(findobj('parent', hdl, 'tag','itc_norm'), 'visible','on');
set(findobj('parent', hdl, 'tag','itc_weight'), 'visible','on');
set(findobj('parent', hdl, 'tag','sec_PCA'), 'visible','on');
set(findobj('parent', hdl, 'tag','sec_on'), 'visible','on');
set(findobj('parent', hdl, 'userdata' ,'dipoleP'), 'visible','on');
set(findobj('parent', hdl, 'string','Final dimensions'), 'visible','on');
set(findobj('parent', hdl, 'tag','finalDimHelp' ), 'visible','on');
set(findobj('parent', hdl, 'tag','spectra_freq_txt'), 'visible','on');
set(findobj('parent', hdl, 'tag','spectra_freq_edit'), 'visible','on');
%% these are made invisible for now, but in future we might use them in the new method
set(findobj('parent', hdl, 'tag','erp_time_txt'), 'visible','on');
set(findobj('parent', hdl, 'tag','erp_time_edit'), 'visible','on');
set(findobj('parent', hdl, 'tag','scalp_choice'), 'visible','on');
set(findobj('parent', hdl, 'tag', 'scalp_absolute'), 'visible','on');
set(findobj('parent', hdl, 'tag','ersp_time_txt'), 'visible','on');
set(findobj('parent', hdl, 'tag','ersp_time_edit'), 'visible','on');
set(findobj('parent', hdl, 'tag','ersp_freq_edit'), 'visible','on');
set(findobj('parent', hdl, 'tag','itc_time_txt'), 'visible','on');
set(findobj('parent', hdl, 'tag','itc_time_edit'), 'visible','on');
set(findobj('parent', hdl, 'tag','itc_freq_edit'), 'visible','on');
set(findobj('parent', hdl, 'string','Measures to Cluster on:'), 'string','Load Dims. Norm. Rel. Wt.');
set(findobj('parent', hdl, 'string','Measures'), 'string', 'Measures Dims. Norm. Rel. Wt.');
end;
% set_mpcluster = get(findobj('parent', hdl, 'tag', 'spectra_on'), 'value');
% set(findobj('parent', hdl, 'userdata', 'spec'), 'enable', fastif(set_spec,'on','off'));
% PCA_on = get(findobj('parent', hdl, 'tag', 'preclust_PCA'), 'value');
% if PCA_on
% set(findobj('parent', hdl, 'userdata', 'specP'), 'enable', 'off');
% else
% set(findobj('parent', hdl, 'userdata', 'specP'), 'enable', fastif(set_spec,'on','off'));
% end
case 'seterp'
set_erp = get(findobj('parent', hdl, 'tag', 'erp_on'), 'value');
set(findobj('parent', hdl, 'userdata', 'erp'), 'enable', fastif(set_erp,'on','off'));
PCA_on = get(findobj('parent', hdl, 'tag', 'preclust_PCA'), 'value');
if PCA_on
set(findobj('parent', hdl, 'userdata', 'erpP'), 'enable', 'off');
else
set(findobj('parent', hdl, 'userdata', 'erpP'), 'enable', fastif(set_erp,'on','off'));
end
case 'setscalp'
set_scalp = get(findobj('parent', hdl, 'tag', 'scalp_on'), 'value');
set(findobj('parent', hdl, 'userdata', 'scalp'), 'enable', fastif(set_scalp,'on','off'));
PCA_on = get(findobj('parent', hdl, 'tag', 'preclust_PCA'), 'value');
if PCA_on
set(findobj('parent', hdl, 'userdata', 'scalpP'), 'enable', 'off');
else
set(findobj('parent', hdl, 'userdata', 'scalpP'), 'enable', fastif(set_scalp,'on','off'));
end
case 'setdipole'
set_dipole = get(findobj('parent', hdl, 'tag', 'dipole_on'), 'value');
set(findobj('parent', hdl, 'userdata', 'dipole'), 'enable', fastif(set_dipole,'on','off'));
PCA_on = get(findobj('parent', hdl, 'tag', 'preclust_PCA'), 'value');
if PCA_on
set(findobj('parent', hdl, 'userdata', 'dipoleP'), 'enable','off');
else
set(findobj('parent', hdl, 'userdata', 'dipoleP'), 'enable', fastif(set_dipole,'on','off'));
end
case 'setersp'
set_ersp = get(findobj('parent', hdl, 'tag', 'ersp_on'), 'value');
set(findobj('parent', hdl,'userdata', 'ersp'), 'enable', fastif(set_ersp,'on','off'));
PCA_on = get(findobj('parent', hdl, 'tag', 'preclust_PCA'), 'value');
if PCA_on
set(findobj('parent', hdl,'userdata', 'erspP'), 'enable', 'off');
else
set(findobj('parent', hdl,'userdata', 'erspP'), 'enable', fastif(set_ersp,'on','off'));
end
set_itc = get(findobj('parent', hdl, 'tag', 'itc_on'), 'value');
set(findobj('parent', hdl,'tag', 'ersp_push'), 'enable', fastif(set_itc,'off','on'));
set(findobj('parent', hdl,'tag', 'ersp_params'), 'enable', fastif(set_itc,'off','on'));
if (set_itc & (~set_ersp) )
set(findobj('parent', hdl,'tag', 'itc_push'), 'enable', 'on');
set(findobj('parent', hdl,'tag', 'itc_params'), 'enable', 'on');
end
case 'setitc'
set_itc = get(findobj('parent', hdl, 'tag', 'itc_on'), 'value');
set(findobj('parent', hdl,'userdata', 'itc'), 'enable', fastif(set_itc,'on','off'));
PCA_on = get(findobj('parent', hdl, 'tag', 'preclust_PCA'), 'value');
if PCA_on
set(findobj('parent', hdl,'userdata', 'itcP'), 'enable','off');
else
set(findobj('parent', hdl,'userdata', 'itcP'), 'enable', fastif(set_itc,'on','off'));
end
set_ersp = get(findobj('parent', hdl, 'tag', 'ersp_on'), 'value');
set(findobj('parent', hdl,'tag', 'itc_push'), 'enable', fastif(set_ersp,'off','on'));
set(findobj('parent', hdl,'tag', 'itc_params'), 'enable', fastif(set_ersp,'off','on'));
if (set_ersp & (~set_itc) )
set(findobj('parent', hdl,'tag', 'ersp_push'), 'enable', 'on');
set(findobj('parent', hdl,'tag', 'ersp_params'), 'enable', 'on');
end
case 'setsec'
set_sec = get(findobj('parent', hdl, 'tag', 'sec_on'), 'value');
set(findobj('parent', hdl,'userdata', 'sec'), 'enable', fastif(set_sec,'on','off'));
case 'erspparams'
ersp = userdat{2};
[ersp_paramsout, erspuserdat, strhalt, erspstruct] = inputgui( { [1] [3 1] [3 1] [3 1] [3 1] [3 1] [1]}, ...
{ {'style' 'text' 'string' 'ERSP and ITC time/freq. parameters' 'FontWeight' 'Bold'} ...
{'style' 'text' 'string' 'Frequency range [Hz]' 'tag' 'ersp_freq' } ...
{'style' 'edit' 'string' ersp.f 'tag' 'ersp_f' 'Callback' ERSP_timewindow } ...
{'style' 'text' 'string' 'Wavelet cycles (see >> help timef())' 'tag' 'ersp_cycle' } ...
{'style' 'edit' 'string' ersp.c 'tag' 'ersp_c' 'Callback' ERSP_timewindow} ...
{'style' 'text' 'string' 'Significance level (< 0.1)' 'tag' 'ersp_alpha' } ...
{'style' 'edit' 'string' ersp.a 'tag' 'ersp_a'} ...
{'style' 'text' 'string' 'timef() padratio' 'tag' 'ersp_pad' } ...
{'style' 'edit' 'string' ersp.p 'tag' 'ersp_p' 'Callback' ERSP_timewindow} ...
{'style' 'text' 'string' 'Desired time window within the indicated latency range [ms]' 'tag' 'ersp_trtxt' } ...
{'style' 'edit' 'string' ersp.t 'tag' 'ersp_timewindow' 'Callback' ERSP_timewindow} {} }, ...
'pophelp(''pop_timef'')', 'Select clustering ERSP and ITC time/freq. parameters -- pop_preclust()');
if ~isempty(ersp_paramsout)
ersp.f = erspstruct(1).ersp_f;
ersp.c = erspstruct(1).ersp_c;
ersp.p = erspstruct(1).ersp_p;
ersp.a = erspstruct(1).ersp_a;
ersp.t = erspstruct(1).ersp_timewindow;
userdat{2} = ersp;
set(findobj('parent', hdl, 'tag', 'ersp_params'), 'string', ...
[' ''frange'', [' ersp.f '], ''cycles'', [' ...
ersp.c '], ''alpha'', ' ersp.a ', ''padratio'', ' ersp.p ', ''tlimits'', [' ersp.t ']']);
set(findobj('parent', hdl, 'tag', 'itc_params'), 'string', ...
[' ''frange'', [' ersp.f '], ''cycles'', [' ...
ersp.c '], ''alpha'', ' ersp.a ', ''padratio'', ' ersp.p ', ''tlimits'', [' ersp.t ']']);
set(hdl, 'userdat',userdat);
end
case 'preclustOK'
set_PCA = get(findobj('parent', hdl, 'tag', 'preclust_PCA'), 'value');
set_ersp = get(findobj('parent', hdl, 'tag', 'ersp_on'), 'value');
set(findobj('parent', hdl,'userdata', 'erspP'), 'enable', fastif(~set_PCA & set_ersp,'on','off'));
set_itc = get(findobj('parent', hdl, 'tag', 'itc_on'), 'value');
set(findobj('parent', hdl,'userdata', 'itcP'), 'enable', fastif(~set_PCA & set_itc,'on','off'));
set_erp = get(findobj('parent', hdl, 'tag', 'erp_on'), 'value');
set(findobj('parent', hdl,'userdata', 'erpP'), 'enable', fastif(~set_PCA & set_erp,'on','off'));
set_spec = get(findobj('parent', hdl, 'tag', 'spectra_on'), 'value');
set(findobj('parent', hdl,'userdata', 'specP'), 'enable', fastif(~set_PCA & set_spec,'on','off'));
set_scalp = get(findobj('parent', hdl, 'tag', 'scalp_on'), 'value');
set(findobj('parent', hdl,'userdata', 'scalpP'), 'enable', fastif(~set_PCA & set_scalp,'on','off'));
set_dipole = get(findobj('parent', hdl, 'tag', 'dipole_on'), 'value');
set(findobj('parent', hdl,'userdata', 'dipoleP'), 'enable', fastif(~set_PCA & set_dipole,'on','off'));
set(findobj('parent', hdl,'tag', 'chosen_component'), 'enable', fastif(~set_PCA,'on','off'));
set(findobj('parent', hdl,'tag', 'dipole_rv'), 'enable', fastif(~set_PCA,'on','off'));
set(findobj('parent', hdl,'tag', 'compstd_str'), 'enable', fastif(~set_PCA,'on','off'));
end
end
STUDY.saved = 'no';
|
github
|
lcnhappe/happe-master
|
std_selsubject.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_selsubject.m
| 2,842 |
utf_8
|
6466ff23a5fb9b15112c7274c77f6ea5
|
% std_selsubject() - Helper function for std_erpplot(), std_specplot()
% and std_erspplot() to select specific subject when
% plotting channel data.
% Usage:
% >> data = std_selsubject( data, subject, setinds, allsubjects);
%
% Inputs:
% data - [cell array] mean data for each subject group and/or data
% condition. For example, to compute mean ERPs statistics from a
% STUDY for epochs of 800 frames in two conditions from three
% groups of 12 subjects,
% >> data = { [800x12] [800x12] [800x12];... % 3 groups, cond 1
% [800x12] [800x12] [800x12] }; % 3 groups, cond 2
% subject - [string] subject name
% setinds - [cell array] set indices for each of the last dimension of the
% data cell array.
% >> setinds = { [12] [12] [12];... % 3 groups, cond 1
% [12] [12] [12] }; % 3 groups, cond 2
% allsubject - [cell array] all subjects (same order as in
% STUDY.datasetinfo)
%
% Output:
% data - [cell array] data array with the subject or component selected
%
% Author: Arnaud Delorme, CERCO, CNRS, 2006-
%
% See also: std_erpplot(), std_specplot() and std_erspplot()
function [data] = std_selsubject(data, subject, setinds, allsubjects, optndims);
if nargin < 2
help std_selsubject;
return;
end;
optndims = max(optndims, ndims(data{1}));
if isempty(strmatch(lower(subject), lower(allsubjects)))
error(sprintf('Cannot select subject %s in list %s', subject, vararg2str({ allsubjects })));
end;
% plot specific subject
% ---------------------
if size(setinds{1},1) > 1 && size(setinds{1},2) > 1 % single trials
% possible subject indices
selectInds = strmatch(lower(subject), lower(allsubjects));
for c = 1:size(data,1)
for g = 1:size(data,2)
selectCol = [];
for ind = 1:length(selectInds)
selectCol = [ selectCol find(setinds{c,g} == selectInds') ];
end;
if optndims == 2
data{c,g} = data{c,g}(:,selectCol); %2-D
elseif optndims == 3
data{c,g} = data{c,g}(:,:,selectCol); %3-D
else
data{c,g} = data{c,g}(:,:,:,selectCol); %4-D
end;
end;
end;
else
for c = 1:size(data,1)
for g = 1:size(data,2)
subjectind = strmatch(lower(subject), lower(allsubjects));
l = zeros(size(setinds{c,g}));
for iSubj = 1:length(subjectind), l = l | setinds{c,g} == subjectind(iSubj); end;
if optndims == 2
data{c,g}(:,~l) = []; %2-D
elseif optndims == 3
data{c,g}(:,:,~l) = []; %3-D
else
data{c,g}(:,:,:,~l) = []; %4-D
end;
end;
end;
end;
|
github
|
lcnhappe/happe-master
|
std_pac.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_pac.m
| 12,743 |
utf_8
|
9fc01e1de80025c52deebe220a9c0b20
|
% std_pac() - Compute or read PAC data (Phase Amplitude Coupling).
%
% Usage:
% >> [X times logfreqs ] = std_pac(EEG, 'key', 'val', ...);
% Inputs:
% EEG - an EEG dataset structure.
%
% Optional inputs:
% 'components1'- [numeric vector] components in the EEG structure used
% for spectral amplitude in PAC {default|[]: all }
% 'components2'- [numeric vector] components in the EEG structure used
% for phase in PAC {default|[]: all }
% 'channels1' - [numeric vector or cell array of channel labels] channels
% in the EEG structure for spectral amplitude in PAC
% {default|[]: no channels}
% 'channels2' - [numeric vector or cell array of channel labels] channels
% in the EEG structure for phase in PAC
% {default|[]: no channels}
% 'freqs' - [minHz maxHz] the PAC frequency range to compute power.
% {default: 12 to EEG sampling rate divided by 2}
% 'cycles' - [wavecycles (factor)]. If 0 -> DFT (constant window length
% across frequencies).
% If >0 -> the number of cycles in each analysis wavelet.
% If [wavecycles factor], wavelet cycles increase with
% frequency, beginning at wavecyles. (0 < factor < 1)
% factor = 0 -> fixed epoch length (DFT, as in FFT).
% factor = 1 -> no increase (standard wavelets)
% {default: [0]}
% 'freqphase' - [valHz] single number for computing the phase at a given
% frequency.
% 'cyclephase' - [valcycle] single cycle number.
% 'timewindow' - [minms maxms] time window (in ms) to plot.
% {default: all output latencies}
% 'padratio' - (power of 2). Multiply the number of output frequencies
% by dividing their frequency spacing through 0-padding.
% Output frequency spacing is (low_freq/padratio).
% 'recompute' - ['on'|'off'] 'on' forces recomputation of PAC.
% {default: 'off'}
%
% Other optional inputs:
% This function will take any of the newtimef() optional inputs (for instance
% to compute log-space frequencies)...
%
% Outputs:
% X - the PAC of the requested ICA components/channels
% in the selected frequency and time range.
% times - vector of time points for which the PAC were computed.
% freqs - vector of frequencies (in Hz) at which the
% PAC was evaluated.
%
% Files written or modified:
% [dataset_filename].icapac <-- saved component PAC
% OR for channels
% [dataset_filename].datpac <-- saved channel PAC
%
% See also: timef(), std_itc(), std_erp(), std_spec(), std_topo(), std_preclust()
%
% Authors: Arnaud Delorme, SCCN, INC, UCSD, July, 2009-
% 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 [X, times, freqs, parameters] = std_pac(EEG, varargin)
if nargin < 1
help std_pac;
return;
end;
options = {};
[g timefargs] = finputcheck(varargin, { ...
'components1' 'integer' [] [];
'channels1' { 'cell','integer' } { [],[] } {};
'components2' 'integer' [] [];
'channels2' { 'cell','integer' } { [],[] } {};
'outputfile' 'string' [] '';
'powbase' 'real' [] [];
'plot' 'string' { 'on','off' } 'off';
'recompute' 'string' { 'on','off' } 'off';
'getparams' 'string' { 'on','off' } 'off';
'timerange' 'real' [] [];
'freqrange' 'real' [] [];
'padratio' 'real' [] 1;
'freqs' 'real' [] [12 EEG.srate/2];
'cycles' 'real' [] [8];
'freqphase' 'real' [] [5];
'cyclephase' 'real' [] [3];
'interp' 'struct' { } struct([]);
'rmcomps' 'integer' [] [];
'freqscale' 'string' [] 'log' }, 'std_pac', 'ignore');
if isstr(g), error(g); end;
% checking input parameters
% -------------------------
if isempty(g.components1) & isempty(g.channels1)
if isempty(EEG(1).icaweights)
error('EEG.icaweights not found');
end
g.components1 = 1:size(EEG(1).icaweights,1);
g.components2 = 1:size(EEG(1).icaweights,1);
disp('Computing PAC with default values for all components of the dataset');
end
% select ICA components or data channels
% --------------------------------------
if ~isempty(g.outputfile)
filenamepac = fullfile('', [ g.outputfile '.datpac' ]);
g.indices1 = std_chaninds(EEG, g.channels1);
g.indices2 = std_chaninds(EEG, g.channels2);
prefix = 'chan';
elseif ~isempty(g.components1)
g.indices1 = g.components1;
g.indices2 = g.components2;
prefix = 'comp';
filenamepac = fullfile(EEG.filepath, [ EEG.filename(1:end-3) 'icapac' ]);
if ~isempty(g.channels1)
error('Cannot compute PAC for components and channels at the same time');
end;
elseif ~isempty(g.channels1)
g.indices1 = std_chaninds(EEG, g.channels1);
g.indices2 = std_chaninds(EEG, g.channels2);
prefix = 'chan';
filenamepac = fullfile(EEG.filepath, [ EEG.filename(1:end-3) 'datpac' ]);
end;
% Compute PAC parameters
% -----------------------
parameters = { 'wavelet', g.cycles, 'padratio', g.padratio, ...
'freqs2', g.freqphase, 'wavelet2', g.cyclephase, 'freqscale', g.freqscale, timefargs{:} };
if length(g.freqs)>0, parameters = { parameters{:} 'freqs' g.freqs }; end;
% Check if PAC information found in datasets and if fits requested parameters
% ----------------------------------------------------------------------------
if exist( filenamepac ) & strcmpi(g.recompute, 'off')
fprintf('Use existing file for PAC: %s\n', filenamepac);
if ~isempty(g.components1)
[X, times, freqs, parameters] = std_readpac(EEG, 1, g.indices1, g.indices2, g.timerange, g.freqrange);
else [X, times, freqs, parameters] = std_readpac(EEG, 1, -g.indices1, -g.indices2, g.timerange, g.freqrange);
end;
return;
end;
% return parameters
% -----------------
if strcmpi(g.getparams, 'on')
X = []; times = []; freqs = [];
return;
end;
options = {};
if ~isempty(g.components1)
tmpdata = eeg_getdatact(EEG, 'component', [1:size(EEG(1).icaweights,1)]);
else
EEG.data = eeg_getdatact(EEG, 'channel', [1:EEG.nbchan], 'rmcomps', g.rmcomps);
if ~isempty(g.rmcomps), options = { options{:} 'rmcomps' g.rmcomps }; end;
if ~isempty(g.interp),
EEG = eeg_interp(EEG, g.interp, 'spherical');
options = { options{:} 'interp' g.interp };
end;
tmpdata = EEG.data;
end;
% Compute PAC
% -----------
all_pac = [];
for k = 1:length(g.indices1) % for each (specified) component
for l = 1:length(g.indices2) % for each (specified) component
tmpparams = parameters;
% Run pac() to get PAC
% --------------------
timefdata1 = tmpdata(g.indices1(k),:,:);
timefdata2 = tmpdata(g.indices2(l),:,:);
if strcmpi(g.plot, 'on'), figure; end;
%[logersp,logitc,logbase,times,logfreqs,logeboot,logiboot,alltfX] ...
[pacvals, times, freqs1, freqs2] = pac( timefdata1, timefdata2, EEG(1).srate, 'tlimits', [EEG.xmin EEG.xmax]*1000, tmpparams{1:end});
all_pac = setfield( all_pac, [ prefix int2str(g.indices1(k)) '_' int2str(g.indices2(l)) '_pac' ], squeeze(single(pacvals )));
end;
end
% Save PAC into file
% ------------------
all_pac.freqs = freqs1;
all_pac.times = times;
all_pac.datatype = 'PAC';
all_pac.parameters = tmpparams;
if ~isempty(g.channels1)
if ~isempty(EEG(1).chanlocs)
tmpchanlocs = EEG(1).chanlocs;
all_pac.chanlabels1 = { tmpchanlocs(g.indices1).labels };
all_pac.chanlabels2 = { tmpchanlocs(g.indices2).labels };
end;
end;
std_savedat( filenamepac , all_pac );
if ~isempty(g.components1)
[X, times, freqs, parameters] = std_readpac(EEG, 1, g.indices1, g.indices2, g.timerange, g.freqrange);
else [X, times, freqs, parameters] = std_readpac(EEG, 1, -g.indices1, -g.indices2, g.timerange, g.freqrange);
end;
% --------------------------------------------------------
% -------------------- READ PAC DATA ---------------------
% --------------------------------------------------------
function [pacvals, freqs, timevals, params] = std_readpac(ALLEEG, abset, comp1, comp2, timewindow, freqrange);
if nargin < 5
timewindow = [];
end;
if nargin < 6
freqrange = [];
end;
% multiple entry
% --------------
if length(comp1) > 1 | length(comp2) > 1
for index1 = 1:length(comp1)
for index2 = 1:length(comp2)
[tmppac, freqs, timevals, params] = std_readpac(ALLEEG, abset, comp1(index1), comp2(index2), timewindow, freqrange);
pacvals(index1,index2,:,:,:) = tmppac;
end;
end;
return;
end;
for k = 1: length(abset)
if comp1 < 0
filename = fullfile( ALLEEG(abset(k)).filepath,[ ALLEEG(abset(k)).filename(1:end-3) 'datpac']);
comp1 = -comp1;
comp2 = -comp2;
prefix = 'chan';
else
filename = fullfile( ALLEEG(abset(k)).filepath,[ ALLEEG(abset(k)).filename(1:end-3) 'icapac']);
prefix = 'comp';
end;
try
tmppac = load( '-mat', filename, 'parameters', 'times', 'freqs');
catch
error( [ 'Cannot read file ''' filename '''' ]);
end;
tmppac.parameters = removedup(tmppac.parameters);
params = struct(tmppac.parameters{:});
params.times = tmppac.times;
params.freqs = tmppac.freqs;
if isempty(comp1)
pacvals = [];
freqs = [];
timevals = [];
return;
end;
tmppac = load( '-mat', filename, 'parameters', 'times', 'freqs', ...
[ prefix int2str(comp1) '_' int2str(comp2) '_pac']);
pacall{k} = double(getfield(tmppac, [ prefix int2str(comp1) '_' int2str(comp2) '_pac']));
tlen = length(tmppac.times);
flen = length(tmppac.freqs);
end
% select plotting or clustering time/freq range
% ---------------------------------------------
if ~isempty(timewindow)
if timewindow(1) > tmppac.times(1) | timewindow(end) < tmppac.times(end)
maxind = max(find(tmppac.times <= timewindow(end)));
minind = min(find(tmppac.times >= timewindow(1)));
else
minind = 1;
maxind = tlen;
end
else
minind = 1;
maxind = tlen;
end
if ~isempty(freqrange)
if freqrange(1) > exp(1)^tmppac.freqs(1) | freqrange(end) < exp(1)^tmppac.freqs(end)
fmaxind = max(find(tmppac.freqs <= freqrange(end)));
fminind = min(find(tmppac.freqs >= freqrange(1)));
else
fminind = 1;
fmaxind = flen;
end
else
fminind = 1;
fmaxind = flen;
end
% return parameters
% ----------------
for cond = 1:length(abset)
try
pac = pacall{cond}(fminind:fmaxind,minind:maxind);
catch
pac = pacall{cond}; % for 'method', 'latphase'
end;
pacvals(:,:,cond) = pac;
end;
freqs = tmppac.freqs(fminind:fmaxind);
timevals = tmppac.times(minind:maxind);
% remove duplicates in the list of parameters
% -------------------------------------------
function cella = removedup(cella)
[tmp indices] = unique_bc(cella(1:2:end));
if length(tmp) ~= length(cella)/2
%fprintf('Warning: duplicate ''key'', ''val'' parameter(s), keeping the last one(s)\n');
end;
cella = cella(sort(union(indices*2-1, indices*2)));
|
github
|
lcnhappe/happe-master
|
compute_ersp_times.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/compute_ersp_times.m
| 2,069 |
utf_8
|
444923a87f00e754398384b467789b6d
|
% compute_ERSP_times() - computes the widest possible ERSP/ITC time window,
% which depends on requested ERSP/ITC parameters such as epoch limits,
% frequency range, wavelet parameters, sampling rate and frequency
% resolution that are used by timef().
% This helper function is called by pop_preclust() & std_ersp().
% Example:
% [time_range, winsize] = compute_ersp_times(cycles, ALLEEG(seti).srate, ...
% [ALLEEG(seti).xmin ALLEEG(seti).xmax]*1000, freq(1),padratio);
%
% Authors: Hilit Serby & Arnaud Delorme, SCCN, INC, UCSD, Feb 03, 2005
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, Feb 03, 2005, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [time_range, winsize] = compute_ERSP_times(cycles, srate, epoch_lim, lowfreq, padratio)
if cycles == 0 %FFT option
if ~exist('padratio')
error('You must enter padratio value for FFT ERSP');
end
lowfreq = lowfreq*padratio;
t = 1/lowfreq;%time window in sec
winsize = t*srate;%time window in points
%time window in points (must be power of 2) for FFT
winsize =pow2(nextpow2(winsize));
%winsize =2^round(log2(winsize));
else %wavelet
t = cycles(1)/lowfreq; %time window in sec
winsize = round(t*srate); %time window in points
end
time_range(1) = epoch_lim(1) + .5*t*1000;
time_range(2) = epoch_lim(2) - .5*t*1000;
|
github
|
lcnhappe/happe-master
|
std_dipplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_dipplot.m
| 27,155 |
utf_8
|
7aa203b7ca134c606fdce5feeeca46e8
|
% std_dipplot() - Commandline function to plot cluster component dipoles. Dipoles for each
% named cluster is displayed in a separate figure. To view all the clustered
% components in the STUDY on the same figure (in a separate subplot), all
% STUDY clusters must be requested.
% To visualize dipoles, they first must be stored in the EEG dataset structures
% using dipfit(). Only components that have dipole locations will be displayed,
% along with the cluster mean dipole (in red).
% Usage:
% >> [STUDY] = std_dipplot(STUDY, ALLEEG, clusters);
% Inputs:
% STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - global EEGLAB vector of EEG structures for the dataset(s) included in
% the STUDY. ALLEEG for a STUDY set is typically created using load_ALLEEG().
%
% Optional inputs:
% 'clusters' - [numeric vector | 'all'] -> specific cluster numbers to plot.
% 'all' -> plot all clusters in STUDY.
% {default: 'all'}.
% 'comps' - [numeric vector] -> indices of the cluster components to plot.
% 'all' -> plot all the components in the cluster
% {default: 'all'}.
% 'mode' - ['together'|'apart'] Display all requested cluster on one
% figure ('together') or separate figures ('apart').
% 'together'-> plot all 'clusters' in one figure (without the gui).
% 'apart' -> plot each cluster in a separate figure. Note that
% this parameter has no effect if the 'comps' option (above) is used.
% {default: 'together'}
% 'figure' - ['on'|'off'] plots on a new figure ('on') or plots on current
% figure ('off'). If 'figure','off' does not display gui controls,
% Useful for incomporating a cluster dipplot into a complex figure.
% {default: 'on'}.
% 'groups' - ['on'|'off'] use different colors for different groups.
% {default: 'off'}.
% Outputs:
% STUDY - the input STUDY set structure modified with plotted cluster
% mean dipole, to allow quick replotting (unless cluster means
% already exists in the STUDY).
% Example:
% >> [STUDY] = std_dipplot(STUDY,ALLEEG, 'clusters', 5, 'mode', 'apart', 'figure', 'off');
% % Plot cluster-5 component dipoles (in blue), plus ther mean dipole (in red),
% % on an exisiting (gui-less) figure.
%
% See also pop_clustedit(), dipplot()
%
% Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, June, 2005
% 'groups' added by Makoto Miyakoshi on June 2012.
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, June 08, 2005, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function STUDY = std_dipplot(STUDY, ALLEEG, varargin)
% Set default values
cls = []; % plot all clusters in STUDY
figureon = 1; % plot on a new figure
mode = 'apart';
STUDY = pop_dipparams(STUDY, 'default');
opt_dipplot = {'projlines',STUDY.etc.dipparams.projlines, 'axistight', STUDY.etc.dipparams.axistight, 'projimg', STUDY.etc.dipparams.projimg, 'normlen', 'on', 'pointout', 'on', 'verbose', 'off', 'dipolelength', 0,'spheres','on'};
%, 'spheres', 'on'
groupval = 'off';
for k = 3:2:nargin
switch varargin{k-2}
case 'clusters'
if isnumeric(varargin{k-1})
cls = varargin{k-1};
if isempty(cls)
cls = 2:length(STUDY.cluster);
end
else
if isstr(varargin{k-1}) & strcmpi(varargin{k-1}, 'all')
cls = 2:length(STUDY.cluster);
else
error('std_dipplot: ''clusters'' input takes either specific clusters (numeric vector) or keyword ''all''.');
end
end
if length(cls) == 1, mode = 'apart'; else mode = 'together'; end;
case 'comps'
STUDY = std_plotcompdip(STUDY, ALLEEG, cls, varargin{k-1}, opt_dipplot{:});
return;
case 'plotsubjects', % do nothing
case 'mode', mode = varargin{k-1};
case 'groups', groupval = varargin{k-1};
case 'figure'
if strcmpi(varargin{k-1},'off')
opt_dipplot{end + 1} = 'gui';
opt_dipplot{end + 1} = 'off';
figureon = 0;
end
end
end
% select clusters to plot
% -----------------------
if isempty(cls)
tmp =[];
cls = 2:length(STUDY.cluster); % plot all clusters in STUDY
for k = 1: length(cls)
% don't include 'Notclust' clusters
if ~strncmpi('Notclust',STUDY.cluster(cls(k)).name,8) & ~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13)
tmp = [tmp cls(k)];
end
end
cls = tmp;
end;
if strcmpi(mode, 'apart') % case each cluster on a separate figure
for clus = 1: length(cls) % For each cluster requested
if length(STUDY.cluster(cls(clus)).comps) > 0 % check there are comps in cluster
max_r = 0;
clear cluster_dip_models;
len = length(STUDY.cluster(cls(clus)).comps);
ndip = 0;
dip_ind = [];
if ~isfield(STUDY.cluster(cls(clus)),'dipole')
STUDY = std_centroid(STUDY,ALLEEG, cls(clus) , 'dipole');
elseif isempty(STUDY.cluster(cls(clus)).dipole)
STUDY = std_centroid(STUDY,ALLEEG, cls(clus) , 'dipole');
end
for k = 1:len
abset = STUDY.datasetinfo(STUDY.cluster(cls(clus)).sets(1,k)).index;
subject = STUDY.datasetinfo(STUDY.cluster(cls(clus)).sets(1,k)).subject;
if ~isfield(ALLEEG(abset), 'dipfit')
warndlg2(['No dipole information available in dataset ' ALLEEG(abset).filename ' , abort plotting'], 'Aborting plot dipoles');
return;
end
comp = STUDY.cluster(cls(clus)).comps(k);
cluster_dip_models(k).posxyz = ALLEEG(abset).dipfit.model(comp).posxyz;
cluster_dip_models(k).momxyz = ALLEEG(abset).dipfit.model(comp).momxyz;
cluster_dip_models(k).rv = ALLEEG(abset).dipfit.model(comp).rv;
if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')
if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model
load('-mat', ALLEEG(abset).dipfit.hdmfile);
max_r = max(max_r, max(vol.r));
else % old version of dipfit
max_r = max(max_r,max(ALLEEG(abset).dipfit.vol.r));
end
end
comp_to_disp{k} = [subject ', ' 'IC' num2str(comp) ];
if ~isempty(cluster_dip_models(k).posxyz)
ndip = ndip +1;
dip_ind = [dip_ind k];
end
end % finished going over cluster comps
STUDY.cluster(cls(clus)).dipole = computecentroid(cluster_dip_models);
cluster_dip_models(end + 1) = STUDY.cluster(cls(clus)).dipole;
% additional options
% ------------------
dip_color = cell(1,ndip+1);
dip_color(1:ndip) = {'b'};
dip_color(end) = {'r'};
options = opt_dipplot;
options{end+1} = 'mri';
options{end+1} = ALLEEG(abset).dipfit.mrifile;
options{end+1} = 'coordformat';
options{end+1} = ALLEEG(abset).dipfit.coordformat;
options{end+1} = 'dipnames';
options{end+1} = {comp_to_disp{dip_ind } [STUDY.cluster(cls(clus)).name ' mean']};
options{end+1} = 'color';
options{end+1} = dip_color;
% if 'groups'==1, overwrite cluster_dip_models, dip_color and dipnames in option -makoto
if strcmpi(groupval, 'on')
[cluster_dip_models, options] = dipgroups(ALLEEG, STUDY, cls, comp_to_disp, cluster_dip_models, options);
break
end
if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')
options{end+1} = 'sphere';
options{end+1} = max_r;
else
options{end+1} = 'meshdata';
options{end+1} = ALLEEG(abset).dipfit.hdmfile;
end
if ndip < 6 && strcmpi(options{1}, 'projlines') && length(cls) == 1 % less than 6 dipoles, project lines
options{2} = 'on';
end
if figureon
dipplot(cluster_dip_models, options{:});
fig_h = gcf;
set(fig_h,'Name', [STUDY.cluster(cls(clus)).name ' - ' num2str(length(unique(STUDY.cluster(cls(clus)).sets(1,:)))) ...
' sets - ' num2str(length(STUDY.cluster(cls(clus)).comps)) ' components (' num2str(ndip) ' dipoles)' ],'NumberTitle','off');
else
dipplot(cluster_dip_models, options{:},'view', [0.5 -0.5 0.5]);
for gind = 1:length(options) % remove the 'gui' 'off' option
if isstr(options{gind})
if strfind(options{gind}, 'gui')
break;
end
end
end
options(gind:gind+1) = [];
dipinfo.dipmod = cluster_dip_models;
dipinfo.op = options;
diptitle = [STUDY.cluster(cls(clus)).name ', ' num2str(length(unique(STUDY.cluster(cls(clus)).sets(1,:)))) ' sets -' ...
num2str(length(STUDY.cluster(cls(clus)).comps)) ' components (' num2str(ndip) ' dipoles)' ];
dipinfo.title = diptitle;
set(gcf, 'UserData', dipinfo);
set(gca,'UserData', dipinfo);
rotate3d off;
axcopy(gca, ['dipinfo = get(gca, ''''UserData''''); dipplot(dipinfo.dipmod, dipinfo.op{:}); set(gcf, ''''Name'''', dipinfo.title,''''NumberTitle'''',''''off''''); ']);
end
end % finished the if condition that cluster isn't empty
end % finished going over requested clusters
end
if strcmpi(mode, 'together') % case all clusters are plotted in the same figure (must be a new figure)
N = length(cls);
rowcols(2) = ceil(sqrt(N)); % Number of rows in the subplot figure.
rowcols(1) = ceil(N/rowcols(2));
fig_h = figure;
orient tall
set(fig_h,'Color', 'black');
set(fig_h,'Name', 'All clusters dipoles','NumberTitle','off');
set(fig_h, 'resize','off');
for l = 1:N
len = length(STUDY.cluster(cls(l)).comps);
max_r = 0;
clear cluster_dip_models;
if ~isfield(STUDY.cluster(cls(l)),'dipole')
STUDY = std_centroid(STUDY,ALLEEG, cls(l), 'dipole');
elseif isempty(STUDY.cluster(cls(l)).dipole)
STUDY = std_centroid(STUDY,ALLEEG, cls(l), 'dipole');
end
for k = 1: len
abset = STUDY.datasetinfo(STUDY.cluster(cls(l)).sets(1,k)).index;
if ~isfield(ALLEEG(abset), 'dipfit')
warndlg2(['No dipole information available in dataset ' num2str(abset) ' , abort plotting'], 'Aborting plot dipoles');
return;
end
comp = STUDY.cluster(cls(l)).comps(k);
cluster_dip_models(k).posxyz = ALLEEG(abset).dipfit.model(comp).posxyz;
cluster_dip_models(k).momxyz = ALLEEG(abset).dipfit.model(comp).momxyz;
cluster_dip_models(k).rv = ALLEEG(abset).dipfit.model(comp).rv;
if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')
if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model
load('-mat', ALLEEG(abset).dipfit.hdmfile);
max_r = max(max_r, max(vol.r));
else % old version of dipfit
max_r = max(max_r,max(ALLEEG(abset).dipfit.vol.r));
end
end
end % finished going over cluster comps
STUDY.cluster(cls(l)).dipole = computecentroid(cluster_dip_models);
cluster_dip_models(end + 1) = STUDY.cluster(cls(l)).dipole;
dip_color = cell(1,length(cluster_dip_models));
dip_color(1:end-1) = {'b'};
dip_color(end) = {'r'};
options = opt_dipplot;
options{end + 1} = 'gui';
options{end + 1} = 'off';
options{end+1} = 'mri';
options{end+1} = ALLEEG(abset).dipfit.mrifile;
options{end+1} = 'coordformat';
options{end+1} = ALLEEG(abset).dipfit.coordformat;
options{end+1} = 'color';
options{end+1} = dip_color;
if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')
options{end+1} = 'sphere';
options{end+1} = max_r;
else
options{end+1} = 'meshdata';
options{end+1} = ALLEEG(abset).dipfit.hdmfile;
end
subplot(rowcols(1),rowcols(2),l) ,
dipplot(cluster_dip_models, options{:});
title([ STUDY.cluster(cls(l)).name ' (' num2str(length(unique(STUDY.cluster(cls(l)).sets(1,:)))) ' Ss, ' num2str(length(STUDY.cluster(cls(l)).comps)),' ICs)'],'color','white');
%diptitle = [STUDY.cluster(cls(l)).name ', ' num2str(length(unique(STUDY.cluster(cls(l)).sets(1,:)))) 'Ss'];
%title(diptitle, 'Color', 'white');
% Complex axcopy
%if l == 1
% for gind = 1:length(options) % remove the 'gui' 'off' option
% if isstr(options{gind})
% if strfind(options{gind}, 'gui')
% break;
% end
% end
% end
% options(gind:gind+1) = [];
%end
%dipinfo.dipmod = cluster_dip_models;
%dipinfo.op = options;
%dipinfo.title = diptitle;
%set(gcf, 'UserData', dipinfo);
%set(gca,'UserData', dipinfo);
%axcopy(gcf, ['dipinfo = get(gca, ''''UserData''''); dipplot(dipinfo.dipmod, dipinfo.op{:}); set(gcf, ''''Name'''', dipinfo.title,''''NumberTitle'''',''''off'''');']);
end %finished going over all clusters
set(fig_h, 'resize','on');
end % finished case of 'all' clusters
% std_plotcompdip() - Commandline function, to visualizing cluster components dipoles.
% Displays the dipoles of specified cluster components with the cluster mean
% dipole on separate figures.
% To visualize dipoles they first must be stored in the EEG dataset structures
% using dipfit(). Only components that have a dipole locations will be displayed,
% along with the cluster mean dipole in red.
% Usage:
% >> [STUDY] = std_plotcompdip(STUDY, ALLEEG, cluster, comps);
% Inputs:
% STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - global EEGLAB vector of EEG structures for the dataset(s) included in the STUDY.
% ALLEEG for a STUDY set is typically created using load_ALLEEG().
% cluster - single cluster number.
%
% Optional inputs:
% comps - [numeric vector] -> indices of the cluster components to plot.
% 'all' -> plot all the components in the cluster {default: 'all'}.
%
% Outputs:
% STUDY - the input STUDY set structure modified with plotted cluster
% dipole mean, to allow quick replotting (unless cluster mean
% already existed in the STUDY).
%
% Example:
% >> cluster = 4; comps= 1;
% >> [STUDY] = std_plotcompdip(STUDY,ALLEEG, cluster, comps);
% Plots component 1 dipole in blue with the cluster 4 mean dipole in red.
%
% See also pop_clustedit, dipfit, std_dipplot
%
% Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, June, 2005
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, June 08, 2005, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function STUDY = std_plotcompdip(STUDY, ALLEEG, cls, comp_ind, varargin)
if ~exist('cls')
error('std_plotcompdip: you must provide a cluster number as an input.');
end
if isempty(cls)
error('std_plotcompdip: you must provide a cluster number as an input.');
end
if nargin == 3 % no components indices were given
% Default plot all components of the cluster
[STUDY] = std_dipplot(STUDY, ALLEEG, 'clusters', cls);
return
end
for ci = 1:length(comp_ind)
abset = STUDY.datasetinfo(STUDY.cluster(cls).sets(1,comp_ind(ci))).index;
comp = STUDY.cluster(cls).comps(comp_ind(ci));
subject = STUDY.datasetinfo(STUDY.cluster(cls).sets(1,comp_ind(ci))).subject;
if ~isfield(ALLEEG(abset), 'dipfit')
warndlg2(['No dipole information available in dataset ' num2str(abset) ' , abort plotting'], 'Aborting plot dipoles');
return;
end
if length(comp_ind) == 1 & isempty(ALLEEG(abset).dipfit.model(comp).posxyz)
warndlg2(strvcat('There is no dipole information available in', ...
[ 'dataset ' num2str(abset) ' for this component, abort plotting']), 'Aborting plot dipoles');
return;
end;
if ~isfield(STUDY.cluster(cls),'dipole')
STUDY = std_centroid(STUDY,ALLEEG, cls , 'dipole');
elseif isempty(STUDY.cluster(cls).dipole)
STUDY = std_centroid(STUDY,ALLEEG, cls , 'dipole');
end
comp_to_disp = [subject ' / ' 'IC' num2str(comp) ];
cluster_dip_models.posxyz = ALLEEG(abset).dipfit.model(comp).posxyz;
cluster_dip_models.momxyz = ALLEEG(abset).dipfit.model(comp).momxyz;
cluster_dip_models.rv = ALLEEG(abset).dipfit.model(comp).rv;
cluster_dip_models(2) = STUDY.cluster(cls).dipole;
if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')
if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model
load('-mat', ALLEEG(abset).dipfit.hdmfile);
max_r = max(vol.r);
else
max_r = max(ALLEEG(abset).dipfit.vol.r);
end
dipplot(cluster_dip_models, 'sphere', max_r, 'mri', ALLEEG(abset).dipfit.mrifile,'coordformat', ALLEEG(abset).dipfit.coordformat , ...
'normlen' ,'on', 'pointout' ,'on','color', {'b', 'r'}, 'dipnames', {comp_to_disp [ STUDY.cluster(cls).name ' mean' ] },...
'spheres', 'on', 'verbose', 'off', varargin{:});
else
dipplot(cluster_dip_models, 'meshdata', ALLEEG(abset).dipfit.hdmfile, 'mri', ALLEEG(abset).dipfit.mrifile,'coordformat', ALLEEG(abset).dipfit.coordformat , ...
'normlen' ,'on', 'pointout' ,'on','color', {'b', 'r'}, 'dipnames', {comp_to_disp [STUDY.cluster(cls).name ' mean']}, ...
'spheres', 'on', 'verbose', 'off', varargin{:});
end
fig_h = gcf;
set(fig_h,'Name', [subject ' / ' 'IC' num2str(comp) ', ' STUDY.cluster(cls).name],'NumberTitle','off');
end
% -----------------------
% load all dipoles and
% compute dipole centroid
% DEVELOPMENT: this function
% should be the only one to
% access dipole information
% -----------------------
function STUDY = std_centroid(STUDY,ALLEEG, clsind, tmp);
for clust = 1:length(clsind)
max_r = 0;
len = length(STUDY.cluster(clsind(clust)).comps);
tmppos = [ 0 0 0 ];
tmpmom = [ 0 0 0 ];
tmprv = 0;
ndip = 0;
for k = 1:len
fprintf('.');
comp = STUDY.cluster(clsind(clust)).comps(k);
abset = STUDY.cluster(clsind(clust)).sets(1,k);
if ~isfield(ALLEEG(abset), 'dipfit')
warndlg2(['No dipole information available in dataset ' num2str(abset) ], 'Aborting compute centroid dipole');
return;
end
if ~isempty(ALLEEG(abset).dipfit.model(comp).posxyz)
ndip = ndip +1;
posxyz = ALLEEG(abset).dipfit.model(comp).posxyz;
momxyz = ALLEEG(abset).dipfit.model(comp).momxyz;
if size(posxyz,1) == 2
if all(posxyz(2,:) == [ 0 0 0 ])
posxyz(2,:) = [];
momxyz(2,:) = [];
end;
end;
tmppos = tmppos + mean(posxyz,1);
tmpmom = tmpmom + mean(momxyz,1);
tmprv = tmprv + ALLEEG(abset).dipfit.model(comp).rv;
if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical')
if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model
load('-mat', ALLEEG(abset).dipfit.hdmfile);
max_r = max(max_r, max(vol.r));
else % old version of dipfit
max_r = max(max_r,max(ALLEEG(abset).dipfit.vol.r));
end
end
end
end
centroid{clust}.dipole.posxyz = tmppos/ndip;
centroid{clust}.dipole.momxyz = tmpmom/ndip;
centroid{clust}.dipole.rv = tmprv/ndip;
if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical') & (~isfield(ALLEEG(abset).dipfit, 'hdmfile')) %old dipfit
centroid{clust}.dipole.maxr = max_r;
end
STUDY.cluster(clsind(clust)).dipole = centroid{clust}.dipole;
end
fprintf('\n');
% --------------------------------
% new function to compute centroid
% was programmed to debug the function
% above but is now used in the code
% --------------------------------
function dipole = computecentroid(alldipoles)
max_r = 0;
len = length(alldipoles);
dipole.posxyz = [ 0 0 0 ];
dipole.momxyz = [ 0 0 0 ];
dipole.rv = 0;
ndip = 0;
count = 0;
warningon = 1;
for k = 1:len
if size(alldipoles(k).posxyz,1) == 2
if all(alldipoles(k).posxyz(2,:) == [ 0 0 0 ])
alldipoles(k).posxyz(2,:) = [];
alldipoles(k).momxyz(2,:) = [];
end;
end;
if ~isempty(alldipoles(k).posxyz)
dipole.posxyz = dipole.posxyz + mean(alldipoles(k).posxyz,1);
dipole.momxyz = dipole.momxyz + mean(alldipoles(k).momxyz,1);
dipole.rv = dipole.rv + alldipoles(k).rv;
count = count+1;
elseif warningon
disp('Some components do not have dipole information');
warningon = 0;
end;
end
dipole.posxyz = dipole.posxyz/count;
dipole.momxyz = dipole.momxyz/count;
dipole.rv = dipole.rv/count;
if isfield(alldipoles, 'maxr')
dipole.maxr = alldipoles(1).max_r;
end;
function [cluster_dip_models, options] = dipgroups(ALLEEG, STUDY, cls, comp_to_disp, cluster_dip_models, options);
% first, extract the subject number
for n = 1:length(comp_to_disp)
subjectnum(n,1) = str2num(comp_to_disp{n}(1:3));
end
% second, extract group info
for n = 1:length(subjectnum)
subj_group{n,1} = ALLEEG(1,subjectnum(n)).group;
end
% third, replace the group names with numbers
for n = 1:length(subj_group)
for m = 1:length(STUDY.group)
if strcmp(subj_group{n,1}, STUDY.group{1,m})
subj_groupnum(n,1) = m;
break
end
end
end
% fourth, compute centroid for each group
for n = 1:length(STUDY.group)
samegroupIC = find(subj_groupnum==n);
cluster_dip_models(1,length(subj_groupnum)+n) = computecentroid(cluster_dip_models(1, samegroupIC));
end
% fifth, use subj_groupnum as a type of dipole color
%%%%%%%%%%%%%%%%%%%%% color list %%%%%%%%%%%%%%%%%%%%%
% This color list was developped for std_envtopo
% 16 colors names officially supported by W3C specification for HTML
colors{1,1} = [1 1 1]; % White
colors{2,1} = [1 1 0]; % Yellow
colors{3,1} = [1 0 1]; % Fuchsia
colors{4,1} = [1 0 0]; % Red
colors{5,1} = [0.75 0.75 0.75]; % Silver
colors{6,1} = [0.5 0.5 0.5]; % Gray
colors{7,1} = [0.5 0.5 0]; % Olive
colors{8,1} = [0.5 0 0.5]; % Purple
colors{9,1} = [0.5 0 0]; % Maroon
colors{10,1} = [0 1 1]; % Aqua
colors{11,1} = [0 1 0]; % Lime
colors{12,1} = [0 0.5 0.5]; % Teal
colors{13,1} = [0 0.5 0]; % Green
colors{14,1} = [0 0 1]; % Blue
colors{15,1} = [0 0 0.5]; % Navy
colors{16,1} = [0 0 0]; % Black
% Silver is twice brighter because silver is used for a background color
colors{5,1} = [0.875 0.875 0.875];
% Choosing and sorting 12 colors for line plot, namely Red, Blue, Green, Fuchsia, Lime, Aqua, Maroon, Olive, Purple, Teal, Navy, and Gray
selectedcolors = colors([4 13 14 3 11 10 9 7 8 12 15 6]);
% determine the new dip colors
for n = 1:length(subj_groupnum)
dip_color{1,n}=selectedcolors{subj_groupnum(n,1)+1};
end
for n = 1:length(STUDY.group)
dip_color{1,end+1}= selectedcolors{n+1};
end
for n = 1:length(options)
if strcmp(options{1,n}, 'color')
options{1,n+1} = dip_color;
elseif strcmp(options{1,n}, 'dipnames')
dipnames = options{1,n+1};
for m = 1:length(STUDY.group)
dipnames{1,length(subj_groupnum)+m}= [STUDY.group{1,m} ' mean'];
end
options{1,n+1} = dipnames;
end
end
|
github
|
lcnhappe/happe-master
|
std_erpplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_erpplot.m
| 20,955 |
utf_8
|
e91aa1b81b5b2cecf07ce04d70e28dac
|
% std_erpplot() - Command line function to plot STUDY cluster component ERPs. Either
% displays grand mean ERPs for all requested clusters in the same figure,
% with ERPs for different conditions (if any) plotted in different colors.
% Else, displays ERP for each specified cluster in separate figures
% (per condition), each containing the cluster component ERPs plus
% the grand mean cluster ERP (in bold). ERPs can be plotted only if
% component ERPs were computed and saved in the STUDY EEG
% datasets.
% These can be computed during pre-clustering using the gui-based
% function pop_preclust() or the equivalent command line functions
% eeg_createdata() and eeg_preclust(). Called by pop_clustedit().
% and std_propplot().
% Usage:
% >> [STUDY] = std_erpplot(STUDY, ALLEEG, key1, val1, key2, val2);
% >> [STUDY erpdata erptimes pgroup pcond pinter] = std_erpplot(STUDY, ALLEEG, ...);
%
% Inputs:
% STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - global EEGLAB vector of EEG structures for the datasets included
% in the STUDY. A STUDY set ALLEEG is typically created by load_ALLEEG().
% Optional inputs for channel plotting:
% 'channels' - [numeric vector] specific channel group to plot. By
% default, the grand mean channel ERP is plotted (using the
% same format as for the cluster component means described
% above). Default is to plot all channels.
% 'subject' - [numeric vector] In 'changrp' mode (above), index of
% the subject(s) to plot. Else by default, plot all components
% in the cluster.
% 'plotsubjects' - ['on'|'off'] When 'on', plot ERP of all subjects.
% 'noplot' - ['on'|'off'] When 'on', only return output values. Default
% is 'off'.
% 'topoplotopt' - [cell array] options for topoplot plotting.
%
% Optional inputs for component plotting:
% 'clusters' - [numeric vector|'all'] indices of clusters to plot.
% If no component indices ('comps' below) are given, the average
% ERPs of the requested clusters are plotted in the same figure,
% with ERPs for different conditions (and groups if any) plotted
% in different colors. In 'comps' (below) mode, ERPS for each
% specified cluster are plotted in separate figures (one per
% condition), each overplotting cluster component ERPs plus the
% average cluster ERP in bold. Note this parameter has no effect
% if the 'comps' option (below) is used. {default: 'all'}
% 'comps' - [numeric vector|'all'] indices of the cluster components to plot.
% Note that 'comps', 'all' is equivalent to 'plotsubjects', 'on'.
%
% Other optional inputs:
% 'key','val' - All optional inputs to pop_erpparams() are also accepted here
% to plot subset of time, statistics etc. The values used by default
% are the ones set using pop_erpparams() and stored in the
% STUDY structure.
%
% Outputs:
% STUDY - the input STUDY set structure with plotted cluster mean
% ERPs data to allow quick replotting
% erpdata - [cell] ERP data for each condition, group and subjects.
% size of cell array is [nconds x ngroups]. Size of each element
% is [times x subjects] for data channels or [times x components]
% for component clusters. This array may be gicen as input
% directly to the statcond() function or std_stats function
% to compute statistics.
% erptimes - [array] ERP time point latencies.
% pgroup - [array or cell] p-values group statistics. Output of the
% statcond() function.
% pcond - [array or cell] condition statistics. Output of the statcond()
% function.
% pinter - [array or cell] groups x conditions statistics. Output of
% statcond() function.
%
% Example:
% >> [STUDY] = std_erpplot(STUDY,ALLEEG, 'clusters', 2, 'comps', 'all');
% % Plot cluster-2 component ERPs plus the mean ERP in bold.
%
% See also pop_clustedit(), pop_preclust(), eeg_createdata(), eeg_preclust(). std_propplot()
%
% Authors: Arnaud Delorme, CERCO, August, 2006-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [STUDY, erpdata, alltimes, pgroup, pcond, pinter] = std_erpplot(STUDY, ALLEEG, varargin)
if nargin < 2
help std_erpplot;
return;
end;
erpdata = []; alltimes = [];
pgroup = []; pcond = []; pinter = [];
% find datatype and default options
% ---------------------------------
dtype = 'erp';
for ind = 1:2:length(varargin)
if strcmpi(varargin{ind}, 'datatype')
dtype = varargin{ind+1};
end;
end;
% get parameters
% --------------
eval( [ 'tmp = pop_' dtype 'params(STUDY, varargin{:});' ...
'params = tmp.etc.' dtype 'params; clear tmp;' ] );
statstruct.etc = STUDY.etc;
statstruct.design = STUDY.design; %added by behnam
statstruct.currentdesign = STUDY.currentdesign; %added by behnam
statstruct = pop_statparams(statstruct, varargin{:});
stats = statstruct.etc.statistics;
stats.fieldtrip.channelneighbor = struct([]); % asumes one channel or 1 component
% potentially missing fields
% --------------------------
fields = { 'filter' 'subtractsubjectmean' 'timerange' 'freqrange' 'topotime' 'topofreq' 'averagechan'};
defaultval = { [] 'off' [] [] [] [] };
for ind=1:length(fields)
if ~isfield(params, fields{ind}),
params = setfield(params, fields{ind}, defaultval{ind});
end;
end;
% decode parameters
% -----------------
if isempty(varargin)
tmplocs = eeg_mergelocs(ALLEEG.chanlocs);
options.channels = { tmplocs.labels };
else
options = mystruct(varargin);
end;
options = myrmfield( options, myfieldnames(params));
options = myrmfield( options, myfieldnames(stats));
options = myrmfield( options, { 'threshold' 'statistics' } ); % for backward compatibility
opt = finputcheck( options, ...
{ 'design' 'integer' [] STUDY.currentdesign;
'plotstderr' 'string' [] 'off';
'channels' 'cell' [] {};
'clusters' 'integer' [] [];
'datatype' 'string' { 'erp','spec' } 'erp';
'mode' 'string' [] ''; % for backward compatibility (now used for statistics)
'comps' { 'string','integer' } [] []; % for backward compatibility
'statmode' 'string' { 'subjects','common','trials' } 'subjects'; % ignored
'plotmode' 'string' { 'normal','condensed' } 'normal';
'unitx' 'string' { 'ms','Hz' } 'ms';
'plotsubjects' 'string' { 'on','off' } 'off';
'detachplots' 'string' { 'on','off' } params.detachplots;
'noplot' 'string' { 'on','off' } 'off';
'topoplotopt' 'cell' {} { 'style' 'both' };
'subject' 'string' [] '' }, 'std_erpplot');
if isstr(opt), error(opt); end;
if isstr(opt.comps), opt.comps = []; opt.plotsubjects = 'on'; end;
if ~isempty(params.topofreq) && strcmpi(opt.datatype, 'spec'), params.topotime = params.topofreq; end;
if ~isempty(params.freqrange), params.timerange = params.freqrange; end;
datatypestr = upper(opt.datatype);
if strcmpi(datatypestr, 'spec'), datatypestr = 'Spectrum'; end;
% =======================================================================
% below this line, all the code should be non-specific to ERP or spectrum
% =======================================================================
allconditions = STUDY.design(opt.design).variable(1).value;
allgroups = STUDY.design(opt.design).variable(2).value;
paired = { STUDY.design(opt.design).variable(1).pairing ...
STUDY.design(opt.design).variable(2).pairing };
stats.paired = paired;
% for backward compatibility
% --------------------------
if strcmpi(opt.mode, 'comps'), opt.plotsubjects = 'on'; end;
if strcmpi(stats.singletrials, 'off') && ((~isempty(opt.subject) || ~isempty(opt.comps)))
if strcmpi(stats.condstats, 'on') || strcmpi(stats.groupstats, 'on')
stats.groupstats = 'off';
stats.condstats = 'off';
disp('No statistics for single subject/component, to get statistics compute single-trial measures');
end;
end;
if ~isnan(params.topotime) & length(opt.channels) < 5
warndlg2(strvcat('ERP parameters indicate that you wish to plot scalp maps', 'Select at least 5 channels to plot topography'));
return;
end;
plotcurveopt = {};
if length(opt.clusters) > 1
plotcurveopt = { 'figure' 'off' };
params.plotconditions = 'together';
params.plotgroups = 'together';
stats.condstats = 'off';
stats.groupstats = 'off';
end;
% if length(opt.channels) > 1 && strcmpi(opt.plotconditions, 'together') && strcmpi(opt.plotgroups, 'together')
% plotcurveopt = { 'figure' 'off' };
% opt.plotconditions = 'together';
% opt.plotgroups = 'together';
% opt.condstats = 'off';
% opt.groupstats = 'off';
% end;
alpha = fastif(strcmpi(stats.mode, 'eeglab'), stats.eeglab.alpha, stats.fieldtrip.alpha);
mcorrect = fastif(strcmpi(stats.mode, 'eeglab'), stats.eeglab.mcorrect, stats.fieldtrip.mcorrect);
method = fastif(strcmpi(stats.mode, 'eeglab'), stats.eeglab.method, ['Fieldtrip ' stats.fieldtrip.method ]);
plotcurveopt = { plotcurveopt{:} ...
'ylim', params.ylim, ...
'threshold', alpha ...
'unitx' opt.unitx, ...
'filter', params.filter, ...
'plotgroups', params.plotgroups, ...
'plotconditions', params.plotconditions };
% channel plotting
% ----------------
axcopyflag = 1;
if ~isempty(opt.channels)
chaninds = 1:length(opt.channels);
if strcmpi(opt.datatype, 'erp')
[STUDY erpdata alltimes] = std_readerp(STUDY, ALLEEG, 'channels', opt.channels(chaninds), 'timerange', params.timerange, ...
'subject', opt.subject, 'singletrials', stats.singletrials, 'design', opt.design);
else
[STUDY erpdata alltimes] = std_readspec(STUDY, ALLEEG, 'channels', opt.channels(chaninds), 'freqrange', params.freqrange, ...
'rmsubjmean', params.subtractsubjectmean, 'subject', opt.subject, 'singletrials', stats.singletrials, 'design', opt.design);
end;
if strcmpi(params.averagechan, 'on') && length(chaninds) > 1
for index = 1:length(erpdata(:))
erpdata{index} = squeeze(mean(erpdata{index},2));
end;
end;
if isempty(erpdata), return; end;
% select specific time
% --------------------
if ~isempty(params.topotime) & ~isnan(params.topotime)
[tmp ti1] = min(abs(alltimes-params.topotime(1)));
[tmp ti2] = min(abs(alltimes-params.topotime(end)));
for condind = 1:length(erpdata(:))
if ~isempty(erpdata{condind})
erpdata{condind} = mean(erpdata{condind}(ti1:ti2,:,:),1);
end;
end;
end;
% compute statistics
% ------------------
if (isempty(params.topotime) || any(isnan(params.topotime))) && length(alpha) > 1
alpha = alpha(1);
end;
if ~isempty(params.topotime) && all(~isnan(params.topotime))
statstruct = std_prepare_neighbors(statstruct, ALLEEG, 'channels', opt.channels);
stats.fieldtrip.channelneighbor = statstruct.etc.statistics.fieldtrip.channelneighbor;
end;
[pcond pgroup pinter] = std_stat(erpdata, stats);
if (~isempty(pcond) && length(pcond{1}) == 1) || (~isempty(pgroup) && length(pgroup{1}) == 1), pcond = {}; pgroup = {}; pinter = {}; end; % single subject STUDY
if length(opt.channels) > 5 && ndims(erpdata{1}) < 3, pcond = {}; pgroup = {}; pinter = {}; end; % topo plotting for single subject
if strcmpi(opt.noplot, 'on') return; end;
% get titles (not included in std_erspplot because it is not possible
% to merge channels for that function
% -----------------------------------
locs = eeg_mergelocs(ALLEEG.chanlocs);
locs = locs(std_chaninds(STUDY, opt.channels(chaninds)));
if strcmpi(params.averagechan, 'on') && length(chaninds) > 1
chanlabels = { locs.labels };
chanlabels(2,:) = {','};
chanlabels(2,end) = {''};
locs(1).labels = [ chanlabels{:} ];
locs(2:end) = [];
end;
[alltitles alllegends ] = std_figtitle('threshold', alpha, 'mcorrect', mcorrect, 'condstat', stats.condstats, 'cond2stat', stats.groupstats, ...
'statistics', method, 'condnames', allconditions, 'plotsubjects', opt.plotsubjects, 'cond2names', allgroups, 'chanlabels', { locs.labels }, ...
'subject', opt.subject, 'valsunit', opt.unitx, 'vals', params.topotime, 'datatype', datatypestr, 'cond2group', params.plotgroups, 'condgroup', params.plotconditions);
% plot
% ----
if ~isempty(params.topotime) && all(~isnan(params.topotime))
std_chantopo(erpdata, 'groupstats', pgroup, 'condstats', pcond, 'interstats', pinter, 'caxis', params.ylim, ...
'chanlocs', locs, 'threshold', alpha, 'titles', alltitles, 'topoplotopt', opt.topoplotopt);
else
std_plotcurve(alltimes, erpdata, 'groupstats', pgroup, 'legend', alllegends, 'condstats', pcond, 'interstats', pinter, ...
'chanlocs', locs, 'titles', alltitles, 'plotsubjects', opt.plotsubjects, 'plotstderr', opt.plotstderr, ...
'condnames', allconditions, 'groupnames', allgroups, plotcurveopt{:});
end;
set(gcf,'name',['Channel ' datatypestr ]);
axcopy(gca);
else
% plot component
% --------------
if length(opt.clusters) > 1, figure('color', 'w'); end;
nc = ceil(sqrt(length(opt.clusters)));
nr = ceil(length(opt.clusters)/nc);
comp_names = {};
for index = 1:length(opt.clusters)
if length(opt.clusters) > 1, subplot(nr,nc,index); end;
if strcmpi(opt.datatype, 'erp')
[STUDY erpdata alltimes] = std_readerp(STUDY, ALLEEG, 'clusters', opt.clusters(index), 'timerange', params.timerange, ...
'component', opt.comps, 'singletrials', stats.singletrials, 'design', opt.design);
else
[STUDY erpdata alltimes] = std_readspec(STUDY, ALLEEG, 'clusters', opt.clusters(index), 'freqrange', params.freqrange, ...
'rmsubjmean', params.subtractsubjectmean, 'component', opt.comps, 'singletrials', stats.singletrials, 'design', opt.design);
end;
if isempty(erpdata), return; end;
% plot specific component
% -----------------------
if ~isempty(opt.comps)
comp_names = { STUDY.cluster(opt.clusters(index)).comps(opt.comps) };
opt.subject = STUDY.datasetinfo(STUDY.cluster(opt.clusters(index)).sets(1,opt.comps)).subject;
end;
stats.paired = paired;
[pcond pgroup pinter] = std_stat(erpdata, stats);
if strcmpi(opt.noplot, 'on'), return; end;
[alltitles alllegends ] = std_figtitle('threshold', alpha, 'plotsubjects', opt.plotsubjects, 'mcorrect', mcorrect, 'condstat', stats.condstats, 'cond2stat', stats.groupstats, ...
'statistics', method, 'condnames', allconditions, 'cond2names', allgroups, 'clustname', STUDY.cluster(opt.clusters(index)).name, 'compnames', comp_names, ...
'subject', opt.subject, 'valsunit', opt.unitx, 'vals', params.topotime, 'datatype', datatypestr, 'cond2group', params.plotgroups, 'condgroup', params.plotconditions);
if length(opt.clusters) > 1 && index < length(opt.clusters), alllegends = {}; end;
std_plotcurve(alltimes, erpdata, 'condnames', allconditions, 'legend', alllegends, 'groupnames', allgroups, 'plotstderr', opt.plotstderr, ...
'titles', alltitles, 'groupstats', pgroup, 'condstats', pcond, 'interstats', pinter, ...
'plotsubjects', opt.plotsubjects, plotcurveopt{:});
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
if all([strcmp(opt.plotsubjects,'on') strcmp(opt.detachplots,'on')])
% Getting IC and subj
%--------------------------------------------------------------
% WARNING: design.cell used here (this should be replaced)
%--------------------------------------------------------------
c = 0;
for i = 1 : numel(STUDY.cluster(opt.clusters(index)).allinds)
if numel(STUDY.cluster(opt.clusters(index)).allinds{i}) ~= 0
c = c+1;
for j = 1 : numel(STUDY.cluster(opt.clusters(index)).allinds{i})
comp = STUDY.cluster(opt.clusters(index)).allinds{i}(j);
dsgcell_indx = STUDY.cluster(opt.clusters(index)).setinds{i}(j);
subject = STUDY.design(opt.design).cell(dsgcell_indx).case;
sbtitles{c}{j} = ([subject '/' 'IC' num2str(comp)]);
end
end
end
%--------------------------------------------------------------
[alltitlestmp tmp] = std_figtitle('threshold', alpha, 'plotsubjects', opt.plotsubjects, 'mcorrect', mcorrect, 'condstat', 'off', 'cond2stat', 'off', ...
'statistics', method, 'condnames', allconditions, 'cond2names', allgroups, 'clustname', STUDY.cluster(opt.clusters(index)).name, 'compnames', comp_names, ...
'subject', opt.subject, 'valsunit', opt.unitx, 'vals', params.topotime, 'datatype', datatypestr, 'cond2group', params.plotgroups, 'condgroup', params.plotconditions);
handles = findall(0,'Type','Figure', 'Tag','tmp_curvetag');
std_detachplots('','','data',erpdata,'figtitles', {alltitlestmp{:}}','sbtitles',sbtitles,'handles', handles, 'filter',params.filter);
axcopyflag = 0;
end
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
end;
tmpgcf = gcf;
set(tmpgcf,'name', ['Component ' datatypestr ] );
if axcopyflag
haxis = findall(tmpgcf,'type','axes');
for i= 1: length(haxis)
axcopy(haxis(i));
end
end
end;
% remove fields and ignore fields who are absent
% ----------------------------------------------
function s = myrmfield(s, f);
for index = 1:length(f)
if isfield(s, f{index})
s = rmfield(s, f{index});
end;
end;
% convert to structure (but take into account cells)
% --------------------------------------------------
function s = mystruct(v);
for index=1:length(v)
if iscell(v{index})
v{index} = { v{index} };
end;
end;
try
s = struct(v{:});
catch, error('Parameter error'); end;
% convert to structure (but take into account cells)
% --------------------------------------------------
function s = myfieldnames(v);
s = fieldnames(v);
if isfield(v, 'eeglab')
s2 = fieldnames(v.eeglab);
s = { s{:} s2{:} };
end;
if isfield(v, 'fieldtrip')
s3 = fieldnames(v.fieldtrip);
for index=1:length(s3)
s3{index} = [ 'fieldtrip' s3{index} ];
end;
s = { s{:} s3{:} };
end;
|
github
|
lcnhappe/happe-master
|
std_preclust.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_preclust.m
| 27,008 |
utf_8
|
90006ebed95a949b1fd306df6e5d0454
|
% std_preclust() - select measures to be included in computation of a preclustering array.
% This array is used by pop_clust() to find component clusters from a
% specified parent cluster.
% Selected measures (dipole location, ERPs, spectra, scalp maps, ERSPs,
% and/or ITCs) should already be precomputed using pop-precomp(). Each
% feature dimension is reduced by PCA decomposition. These PCA matrices
% (one per measure) are concatenated and used as input to the clustering
% algorithm in pop_clust(). Follow with pop_clust().
% See Example below:
%
% >> [STUDY,ALLEEG] = std_preclust(STUDY,ALLEEG); % prepare to cluster all comps
% % in all sets on all measures
%
% >> [STUDY,ALLEEG] = std_preclust(STUDY,ALLEEG, clustind, preproc1, preproc2...);
% % prepare to cluster specifed
% % cluster on specified measures
% Required inputs:
% STUDY - an EEGLAB STUDY set of loaded EEG structures
% ALLEEG - ALLEEG vector of one or more loaded EEG dataset structures
%
% Optional inputs:
% clustind - a cluster index for further (hierarchical) clustering -
% for example to cluster a spectrum-based mu-rhythm cluster into
% dipole location-based left mu and right mu sub-clusters.
% Should be empty for first stage (whole-STUDY) clustering {default: []}
%
% preproc - {'command' 'key1' val1 'key2' val2 ...} component clustering measures to prepare
%
% * 'command' = component measure to compute:
% 'erp' = cluster on the component ERPs,
% 'dipoles' = cluster on the component [X Y Z] dipole locations
% 'spec' = cluster on the component log activity spectra (in dB)
% (with the baseline mean dB spectrum subtracted).
% 'scalp' = cluster on component (topoplot()) scalp maps
% (or on their absolute values),
% 'scalpLaplac' = cluster on component (topoplot()) laplacian scalp maps
% (or on their absolute values),
% 'scalpGrad' = cluster on the (topoplot()) scalp map gradients
% (or on their absolute values),
% 'ersp' = cluster on components ERSP. (requires: 'cycles',
% 'freqrange', 'padratio', 'timewindow', 'alpha').
% 'itc' = cluster on components ITC.(requires: 'cycles',
% 'freqrange', 'padratio', 'timewindow', 'alpha').
% 'finaldim' = final number of dimensions. Enables second-level PCA.
% By default this command is not used (see Example below).
%
% * 'key' optional keywords and [valuess] used to compute the above 'commands':
% 'npca' = [integer] number of principal components (PCA dimension) of
% the selected measures to retain for clustering. {default: 5}
% 'norm' = [0|1] 1 -> normalize the PCA components so the variance of
% first principal component is 1 (useful when using several
% clustering measures - 'ersp','scalp',...). {default: 1}
% 'weight' = [integer] weight with respect to other clustering measures.
% 'freqrange' = [min max] frequency range (in Hz) to include in activity
% spectrum, 'ersp', and 'itc' measures.
% 'timewindow' = [min max] time window (in sec) to include in 'erp',
% 'ersp', and 'itc' measures.
% 'abso' = [0|1] 1 = use absolute values of topoplot(), gradient, or
% Laplacian maps {default: 1}
% 'funarg' = [cell array] optional function arguments for mean spectrum
% calculation (>> help spectopo) {default: none}
% Outputs:
% STUDY - the input STUDY set with pre-clustering data added, for use by pop_clust()
% ALLEEG - the input ALLEEG vector of EEG dataset structures, modified by adding preprocessing
% data as pointers to Matlab files that hold the pre-clustering component measures.
%
% Example:
% >> [STUDY ALLEEG] = std_preclust(STUDY, ALLEEG, [],...
% { 'spec' 'npca' 10 'norm' 1 'weight' 1 'freqrange' [ 3 25 ] } , ...
% { 'erp' 'npca' 10 'norm' 1 'weight' 2 'timewindow' [ 350 500 ] } ,...
% { 'scalp' 'npca' 10 'norm' 1 'weight' 2 'abso' 1 } , ...
% { 'dipoles' 'norm' 1 'weight' 15 } , ...
% { 'ersp' 'npca' 10 'freqrange' [ 3 25 ] 'cycles' [ 3 0.5 ] 'alpha' 0.01 ....
% 'padratio' 4 'timewindow' [ -1600 1495 ] 'norm' 1 'weight' 1 } ,...
% { 'itc' 'npca' 10 'freqrange' [ 3 25 ] 'cycles' [ 3 0.5 ] 'alpha' 0.01 ...
% 'padratio' 4 'timewindow' [ -1600 1495 ] 'norm' 1 'weight' 1 }, ...
% { 'finaldim' 'npca' 10 });
%
% % This prepares, for initial clustering, all components in the STUDY datasets
% % except components with dipole model residual variance (see function
% % std_editset() for how to select such components).
% % Clustering will be based on the components' mean spectra in the [3 25] Hz
% % frequency range, on the components' ERPs in the [350 500] ms time window,
% % on the (absolute-value) component scalp maps, on the equivalent dipole
% % locations, and on the component mean ERSP and ITC images.
% % The final keyword specifies final PCA dimension reduction to 10
% % principal dimensions. See the clustering tutorial for more details.
%
% Authors: Arnaud Delorme, Hilit Serby & Scott Makeig, SCCN, INC, UCSD, May 13, 2004
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, May 13,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
function [ STUDY, ALLEEG ] = std_preclust(STUDY, ALLEEG, cluster_ind, varargin)
if nargin < 2
help std_preclust;
return;
end;
if nargin == 2
cluster_ind = 1; % default to clustering the whole STUDY
end
% check dataset length consistency before computing
% -------------------------------------------------
pnts = ALLEEG(STUDY.datasetinfo(1).index).pnts;
srate = ALLEEG(STUDY.datasetinfo(1).index).srate;
xmin = ALLEEG(STUDY.datasetinfo(1).index).xmin;
xmax = ALLEEG(STUDY.datasetinfo(1).index).xmax;
for index = 1:length(STUDY.datasetinfo)
ind = STUDY.datasetinfo(index).index;
if srate ~= ALLEEG(ind).srate, error(sprintf('Dataset %d does not have the same sampling rate as dataset 1', ind)); end;
if ~all([ ALLEEG.trials ] == 1)
if abs(xmin-ALLEEG(ind).xmin) > 1e-7, warning(sprintf('Dataset %d does not have the same time limit as dataset 1', ind)); end;
if abs(xmax-ALLEEG(ind).xmax) > 1e-7, warning(sprintf('Dataset %d does not have the same time limit as dataset 1', ind)); end;
if pnts ~= ALLEEG(ind).pnts, error(sprintf('Dataset %d does not have the same number of point as dataset 1', ind)); end;
end;
end;
% Get component indices that are part of the cluster
% --------------------------------------------------
if isempty(cluster_ind)
cluster_ind = 1;
end;
if length(cluster_ind) ~= 1
error('Only one cluster can be sub-clustered. To sub-cluster multiple clusters, first merge them.');
end
% % the goal of this code below is to find the components in the cluster
% % of interest for each set of condition
% for k = 1:size(STUDY.setind,2)
% % Find the first entry in STUDY.setind(:,k) that is non-NaN. We only need one since
% % components are the same across conditions.
% for ri = 1:size(STUDY.setind,1)
% if ~isnan(STUDY.setind(ri,k)), break; end
% end
% sind = find(STUDY.cluster(cluster_ind).sets(ri,:) == STUDY.setind(ri,k));
% succompind{k} = STUDY.cluster(cluster_ind).comps(sind);
% end;
% for ind = 1:size(STUDY.setind,2)
% succompind{ind} = succompind{ind}(find(succompind{ind})); % remove zeros
% % (though there should not be any? -Arno)
% succompind{ind} = sort(succompind{ind}); % sort the components
% end;
% scan all commands to see if file exist
% --------------------------------------
% for index = 1:length(varargin) % scan commands
% strcom = varargin{index}{1};
% if strcmpi(strcom, 'scalp') || strcmpi(strcom, 'scalplaplac') || strcmpi(strcom, 'scalpgrad')
% strcom = 'topo';
% end;
% if ~strcmpi(strcom, 'dipoles') && ~strcmpi(strcom, 'finaldim')
% tmpfile = fullfile( ALLEEG(1).filepath, [ ALLEEG(1).filename(1:end-3) 'ica' strcom ]);
% if exist(tmpfile) ~= 2
% %error([ 'Could not find "' upper(strcom) '" file, they must be precomputed' ]);
% end;
% end;
% end;
% Decode input arguments
% ----------------------
update_flag = 0;
rv = 1;
secondlevpca = Inf;
indrm = [];
for index = 1:length(varargin) % scan commands
strcom = varargin{index}{1};
if strcmpi(strcom,'dipselect')
update_flag = 1;
rv = varargin{index}{3};
indrm = [indrm index]; %remove this command
elseif strcmpi(strcom,'finaldim') % second level pca
secondlevpca = varargin{index}{3};
indrm = [indrm index]; %remove this command
end
end
varargin(indrm) = []; %remove commands
% Scan which component to remove (no dipole info)
% -----------------------------------------------
if update_flag % dipole information is used to select components
error('Update flag is obsolete');
end;
% scan all commands
% -----------------
clustdata = [];
erspquery = 0;
for index = 1:length(varargin)
% decode inputs
% -------------
strcom = varargin{index}{1};
if any(strcom == 'X'), disp('character ''X'' found in command'); end;
%defult values
npca = NaN;
norm = 1;
weight = 1;
freqrange = [];
timewindow = [];
abso = 1;
fun_arg = [];
savetrials = 'off';
recompute = 'on';
for subind = 2:2:length(varargin{index})
switch varargin{index}{subind}
case 'npca'
npca = varargin{index}{subind+1};
case 'norm'
norm = varargin{index}{subind+1};
case 'weight'
weight = varargin{index}{subind+1};
case 'freqrange'
freqrange = varargin{index}{subind+1};
case 'timewindow'
timewindow = varargin{index}{subind+1};
case 'abso'
abso = varargin{index}{subind+1};
case 'savetrials'
error('You may now use the function std_precomp to precompute measures');
case 'cycles'
error('You may now use the function std_precomp to precompute measures');
case 'alpha'
error('You may now use the function std_precomp to precompute measures');
case 'padratio'
error('You may now use the function std_precomp to precompute measures');
otherwise
fun_arg{length(fun_arg)+1} = varargin{index}{subind+1};
end
end
% scan datasets
% -------------
if strcmpi(strcom, 'scalp'), scalpmodif = 'none';
elseif strcmpi(strcom, 'scalpLaplac'), scalpmodif = 'laplacian';
else scalpmodif = 'gradient';
end;
% check that all datasets are in preclustering for current design
% ---------------------------------------------------------------
tmpstruct = std_setcomps2cell(STUDY, STUDY.cluster(cluster_ind).sets, STUDY.cluster(cluster_ind).comps);
alldatasets = unique_bc(STUDY.cluster(cluster_ind).sets(:));
if length(alldatasets) < length(STUDY.datasetinfo) && cluster_ind == 1
error( [ 'Some datasets not included in preclustering' 10 ...
'because of partial STUDY design. You need to' 10 ...
'use a STUDY design that includes all datasets.' ]);
end;
for si = 1:size(STUDY.cluster(cluster_ind).sets,2)
% test consistency of the .set structure
% --------------------------------------
if strcmpi(strcom, 'erp') || strcmpi(strcom, 'spec') || strcmpi(strcom, 'ersp') || strcmpi(strcom, 'itc')
if any(isnan(STUDY.cluster(cluster_ind).sets(:)))
error( [ 'std_preclust error: some datasets do not have ICA pairs.' 10 ...
'Look for NaN values in STUDY.cluster(1).sets which' 10 ...
'indicate missing datasets. FOR CLUSTERING, YOU MAY ONLY' 10 ...
'USE DIPOLE OR SCALP MAP CLUSTERING.' ]);
end;
end;
switch strcom
% select ica component ERPs
% -------------------------
case 'erp',
% read and concatenate all cells for this specific set
% of identical ICA decompositions
STUDY.cluster = checkcentroidfield(STUDY.cluster, 'erp', 'erp_times');
tmpstruct = std_setcomps2cell(STUDY, STUDY.cluster(cluster_ind).sets(:,si), STUDY.cluster(cluster_ind).comps(si));
cellinds = [ tmpstruct.setinds{:} ];
compinds = [ tmpstruct.allinds{:} ];
cells = STUDY.design(STUDY.currentdesign).cell(cellinds);
fprintf('Pre-clustering array row %d, adding ERP for design %d cell(s) [%s] component %d ...\n', si, STUDY.currentdesign, int2str(cellinds), compinds(1));
X = std_readfile( cells, 'components', compinds, 'timelimits', timewindow, 'measure', 'erp');
X = abs(X(:)'); % take the absolute value of the ERP to avoid polarities issues
% select ica scalp maps
% --------------------------
case { 'scalp' 'scalpLaplac' 'scalpGrad' }
idat = STUDY.datasetinfo(STUDY.cluster(cluster_ind).sets(:,si)).index;
icomp = STUDY.cluster(cluster_ind).comps(si);
fprintf('Pre-clustering array row %d, adding interpolated scalp maps for dataset %d component %d...\n', si, idat, icomp);
X = std_readtopo(ALLEEG, idat, icomp, scalpmodif, 'preclust');
% select ica comp spectra
% -----------------------
case 'spec',
% read and concatenate all cells for this specific set
% of identical ICA decompositions
STUDY.cluster = checkcentroidfield(STUDY.cluster, 'spec', 'spec_freqs');
tmpstruct = std_setcomps2cell(STUDY, STUDY.cluster(cluster_ind).sets(:,si), STUDY.cluster(cluster_ind).comps(si));
cellinds = [ tmpstruct.setinds{:} ];
compinds = [ tmpstruct.allinds{:} ];
cells = STUDY.design(STUDY.currentdesign).cell(cellinds);
fprintf('Pre-clustering array row %d, adding spectrum for design %d cell(s) [%s] component %d ...\n', si, STUDY.currentdesign, int2str(cellinds), compinds(1));
X = std_readfile( cells, 'components', compinds, 'freqlimits', freqrange, 'measure', 'spec');
if size(X,2) > 1, X = X - repmat(mean(X,2), [1 size(X,2)]); end;
X = X - repmat(mean(X,1), [size(X,1) 1]);
X = X(:)';
% select dipole information
% -------------------------
case 'dipoles'
idat = STUDY.datasetinfo(STUDY.cluster(cluster_ind).sets(1,si)).index;
icomp = STUDY.cluster(cluster_ind).comps(si);
fprintf('Pre-clustering array row %d, adding dipole for dataset %d component %d...\n', si, idat, icomp);
try
% select among 3 sub-options
% --------------------------
ldip = 1;
if size(ALLEEG(idat).dipfit.model(icomp).posxyz,1) == 2 % two dipoles model
if any(ALLEEG(idat).dipfit.model(icomp).posxyz(1,:)) ...
&& any(ALLEEG(idat).dipfit.model(icomp).posxyz(2,:)) %both dipoles exist
% find the leftmost dipole
[garb ldip] = max(ALLEEG(idat).dipfit.model(icomp).posxyz(:,2));
elseif any(ALLEEG(idat).dipfit.model(icomp).posxyz(2,:))
ldip = 2; % the leftmost dipole is the only one that exists
end
end
X = ALLEEG(idat).dipfit.model(icomp).posxyz(ldip,:);
catch
error([ sprintf('Some dipole information is missing (e.g. component %d of dataset %d)', icomp, idat) 10 ...
'Components are not assigned a dipole if residual variance is too high so' 10 ...
'in the STUDY info editor, remember to select component by residual' 10 ...
'variance (column "select by r.v.") prior to preclustering them.' ]);
end
% cluster on ica ersp / itc values
% --------------------------------
case {'ersp', 'itc' }
% read and concatenate all cells for this specific set
% of identical ICA decompositions
STUDY.cluster = checkcentroidfield(STUDY.cluster, 'ersp', 'ersp_times', 'ersp_freqs', 'itc', 'itc_times', 'itc_freqs');
tmpstruct = std_setcomps2cell(STUDY, STUDY.cluster(cluster_ind).sets(:,si), STUDY.cluster(cluster_ind).comps(si));
cellinds = [ tmpstruct.setinds{:} ];
compinds = [ tmpstruct.allinds{:} ];
cells = STUDY.design(STUDY.currentdesign).cell(cellinds);
fprintf('Pre-clustering array row %d, adding %s for design %d cell(s) [%s] component %d ...\n', si, upper(strcom), STUDY.currentdesign, int2str(cellinds), compinds(1));
X = std_readfile( cells, 'components', compinds, 'timelimits', timewindow, 'measure', strcom);
end;
% copy data in the array
% ----------------------
if ~isreal(X) X = abs(X); end; % for ITC data
X = reshape(X, 1, numel(X));
if si == 1, data = zeros(size(STUDY.cluster(cluster_ind).sets,2),length(X)); end;
data(si,:) = X;
try
data(si,:) = X;
catch,
error([ 'This type of pre-clustering requires that all subjects' 10 ...
'be represented for all combination of selected independent' 10 ...
'variables in the current STUDY design. In addition, for each' 10 ...
'different ICA decomposition included in the STUDY (some' 10 ...
'datasets may have the same decomposition), at least one' 10 ...
'dataset must be represented.' ]);
end;
end; % end scan datasets
% adjust number of PCA values
% ---------------------------
if isnan(npca), npca = 5; end; % default number of components
if npca >= size(data,2)
% no need to run PCA, just copy the data.
% But still run it to "normalize" coordinates
% --------------------------------------
npca = size(data,2);
end;
if npca >= size(data,1) % cannot be more than the number of components
npca = size(data,1);
end;
if ~strcmp(strcom, 'dipoles')
fprintf('PCA dimension reduction to %d for command ''%s'' (normalize:%s; weight:%d)\n', ...
npca, strcom, fastif(norm, 'on', 'off'), weight);
else
fprintf('Retaining the three-dimensional dipole locations (normalize:%s; weight:%d)\n', ...
fastif(norm, 'on', 'off'), weight);
end
% run PCA to reduce data dimension
% --------------------------------
switch strcom
case {'ersp','itc'}
dsflag = 1;
while dsflag
try,
clustdatatmp = runpca( double(data.'), npca, 1);
dsflag = 0;
catch,
% downsample frequency by 2 and times by 2
% ----------------------------------------
data = data(:,1:2:end);
%idat = STUDY.datasetinfo(STUDY.setind(1)).index;
%[ tmp freqs times ] = std_readersp( ALLEEG, idat, succompind{1}(1));
%[data freqs times ] = erspdownsample(data,4, freqs,times,Ncond);
if strcmp(varargin{index}(end-1) , 'downsample')
varargin{index}(end) = {celltomat(varargin{index}(end)) + 4};
else
varargin{index}(end+1) = {'downsample'};
varargin{index}(end+1) = {4};
end
end
end
clustdatatmp = clustdatatmp.';
case 'dipoles'
% normalize each cordinate by the std dev of the radii
normval = std(sqrt(data(:,1).^2 + data(:,2).^2 + data(:,3).^2));
clustdatatmp = data./normval;
norm = 0;
case 'erp'
clustdatatmp = runpca( double(data.'), npca, 1);
clustdatatmp = abs(clustdatatmp.');
otherwise
clustdatatmp = runpca( double(data.'), npca, 1);
clustdatatmp = clustdatatmp.';
end
if norm %normalize the first pc std to 1
normval = std(clustdatatmp(:,1));
for icol = 1:size(clustdatatmp,2)
clustdatatmp(:,icol) = clustdatatmp(:,icol) /normval;
end;
end;
if weight ~= 1
clustdata(:,end+1:end+size(clustdatatmp,2)) = clustdatatmp * weight;
else
clustdata(:,end+1:end+size(clustdatatmp,2)) = clustdatatmp;
end
if strcmpi(strcom, 'itc') | strcmpi(strcom, 'ersp')
erspmode = 'already_computed';
end;
end
% Compute a second PCA of the already PCA'd data if there are too many PCA dimensions.
% ------------------------------------------------------------------------------------
if size(clustdata,2) > secondlevpca
fprintf('Performing second-level PCA: reducing dimension from %d to %d \n', ...
size(clustdata,2), secondlevpca);
clustdata = runpca( double(clustdata.'), secondlevpca, 1);
clustdata = clustdata.';
end
STUDY.etc.preclust.preclustdata = clustdata;
STUDY.etc.preclust.preclustparams = varargin;
if isfield(STUDY.etc.preclust, 'preclustcomps')
STUDY.etc.preclust = rmfield(STUDY.etc.preclust, 'preclustcomps');
end;
% The preclustering level is equal to the parent cluster that the components belong to.
if ~isempty(cluster_ind)
STUDY.etc.preclust.clustlevel = cluster_ind;
else
STUDY.etc.preclust.clustlevel = 1; % No parent cluster (cluster on all components in STUDY).
end
return
% erspdownsample() - down samples component ERSP/ITC images if the
% PCA operation in the clustering feature reduction step fails.
% This is a helper function called by eeg_preclust().
function [dsdata, freqs, times] = erspdownsample(data, n, freqs,times,cond)
len = length(freqs)*length(times); %size of ERSP
nlen = ceil(length(freqs)/2)*ceil(length(times)/2); %new size of ERSP
dsdata = zeros(size(data,1),cond*nlen);
for k = 1:cond
tmpdata = data(:,1+(k-1)*len:k*len);
for l = 1:size(data,1) % go over components
tmpersp = reshape(tmpdata(l,:)',length(freqs),length(times));
tmpersp = downsample(tmpersp.', n/2).'; %downsample times
tmpersp = downsample(tmpersp, n/2); %downsample freqs
dsdata(l,1+(k-1)*nlen:k*nlen) = tmpersp(:)';
end
end
% the function below checks the precense of the centroid field
function cluster = checkcentroidfield(cluster, varargin);
for kk = 1:length(cluster)
if ~isfield('centroid', cluster(kk)), cluster(kk).centroid = []; end;
for vi = 1:length(varargin)
if isfield(cluster(kk).centroid, varargin{vi})
cluster(kk).centroid = rmfield(cluster(kk).centroid, varargin{vi});
end;
end;
end;
|
github
|
lcnhappe/happe-master
|
std_filecheck.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_filecheck.m
| 8,785 |
utf_8
|
ed6e134b227c42300f92308c99c82ecc
|
% std_filecheck() - Check if ERSP or SPEC file contain specific parameters.
% This file must contain a Matlab structure with a field
% named 'parameter'. The content of this field will be
% compared to the 'params' input. If they are identical
% the output flag will indicate that recomputing this
% file is not necessary. If they are different, the user
% is queried ('guion' option) to see if he wishes to use
% the new parameters and recompute the file (not done in
% this function) or if he wishes to use the parameters
% of the file on disk.
%
% Usage:
% >> [ recompflag params ] = std_filecheck(filename, params, mode, ignorefields);
%
% Inputs:
% filename - [string] file containing a given measure (ERSP data for
% instance).
% params - [cell array or structure] cell array of parameters or
% structure. This is compared to the 'parameters' field
% in the data file.
% mode - ['guion'|'usedisk'|'recompute'] 'guion' query the user
% if the disk and input parameters are different. The
% outcome may be either 'usedisk' or 'recompute'. See
% recompflag output for more information.
% ignorefields - [cell array] list fields to ignore
%
% Outputs:
% recompflag - ['same'|'different'|'recompute'|'usedisk'|'cancel'] 'same'
% (resp. 'different') indicates that the parameters in the
% data file are identical (resp. different). 'recompute'
% indicate that the measure should be recomputed and the
% file has been erased. 'usedisk' indicate that the user
% wishes (from the GUI) to use the version on disk.
% params - [structure] final parameter. This is usually identical
% to the 'params' input unless the user choose to use
% parameters from the file on disk. These are then
% copied to this output structure.
%
% Authors: Arnaud Delorme, 2006-
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, 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 [ res, params2 ] = std_filecheck(filename, params2, guiflag, ignorefields);
if nargin < 2
help std_filecheck;
return;
end;
if nargin < 3
guiflag = 'guion';
end;
if nargin < 4
ignorefields = {};
end;
if ~exist( filename ), res = guiflag; return; end;
params1 = load('-mat', filename, 'parameters');
params1 = finputcheck( params1.parameters, { 'tmp' 'real' [] NaN}, '', 'ignore'); % allow to tackle duplicate fields
params1 = rmfield(params1, 'tmp');
if iscell(params2), params2 = struct(params2{:}); end;
% test if the fields are different
% --------------------------------
params1 = orderfields(params1);
params2 = orderfields(params2);
fields1 = fieldnames( params1 ); fields1 = setdiff_bc( fields1, ignorefields);
fields2 = fieldnames( params2 ); fields2 = setdiff_bc( fields2, ignorefields);
allfields = union_bc(fields1, fields2);
% make fields the same
% --------------------
res = 'same';
if ~isequal( fields1, fields2 ),
for ind = 1:length(allfields)
if strcmpi(allfields{ind}, 'plotitc'), adsfads; end;
if ~isfield( params1, allfields{ind})
if isstr(getfield(params2, allfields{ind}))
params1 = setfield(params1, allfields{ind}, '');
else params1 = setfield(params1, allfields{ind}, []);
end;
res = 'different';
end;
if ~isfield( params2, allfields{ind})
if isstr(getfield(params1, allfields{ind}))
params2 = setfield(params2, allfields{ind}, '');
else params2 = setfield(params2, allfields{ind}, []);
end;
res = 'different';
end;
end;
end;
% data type
% ---------
if ~isempty(strmatch('cycles', allfields)), strcom = 'ERSP';
else strcom = 'SPECTRAL';
end;
% compare fields
% --------------
txt = {};
for ind = 1:length(allfields)
if ~strcmp(allfields{ind},'baseline')
val1 = getfield(params1, allfields{ind});
val2 = getfield(params2, allfields{ind});
val1str = fastif(isempty(val1), 'not set', vararg2str({val1(1:min(3, length(val1)))}));
val2str = fastif(isempty(val2), 'not set', vararg2str({val2(1:min(3, length(val2)))}));
tmptxt = sprintf(' ''%s'' is %s in the file (vs. %s)', allfields{ind}, val1str, val2str);
if length(val1) ~= length(val2)
res = 'different';
txt{end+1} = tmptxt;
elseif ~isequal(val1, val2)
if ~isnan(val1) & ~isnan(val2)
res = 'different';
txt{end+1} = tmptxt;
end
end
end
end
% build gui or return
% -------------------
if strcmpi(guiflag, 'usedisk'),
if isempty(txt)
params2 = params1;
res = 'usedisk';
disp(['Using file on disk: ' filename ]);
return;
else
strvcat(txt{:})
error([ 'Two ' strcom ' files had different parameters and the ' strcom ' function' 10 ...
'cannot handle that. We suggest that you delete all files. See command line details' ]);
end;
elseif strcmpi(guiflag, 'recompute'),
res = 'recompute';
disp(['Deleting and recomputing file: ' filename ]);
return;
elseif strcmpi(res, 'same') & ( strcmpi(guiflag, 'guion') | strcmpi(guiflag, 'same') )
disp(['Using file on disk: ' filename ]);
return;
end;
set_yes = [ 'set(findobj(''parent'', gcbf, ''tag'', ''ersp_no''), ''value'', 0);'];
set_no = [ 'set(findobj(''parent'', gcbf, ''tag'', ''ersp_yes''), ''value'', 0);' ];
textgui1 = strvcat( [ upper(strcom) ' info exists in file: ' filename ], ...
'However, as detailed below, it does not fit with the requested values:');
textgui2 = strvcat(txt{:});
%textgui2 = ['wavelet cycles - [' num2str(params1.cycles(1)) ' ' num2str(params2.cycles(2)) ...
% '] instead of [' num2str(params1.cycles(1)) ' ' num2str(params2.cycles(2)) ...
% '], padratio - ' num2str(params1.padratio) ' instead of ' num2str(param2.padratio) ...
% ', and bootstrap significance - ' num2str(params1.alpha) ' instead of ' num2str(params2.alpha) ];
uilist = { {'style' 'text' 'string' textgui1 } ...
{'style' 'text' 'string' textgui2 } {} ...
{'style' 'text' 'string' ['Would you like to recompute ' upper(strcom) ' and overwrite those values?' ]} ...
{'style' 'checkbox' 'tag' 'ersp_yes' 'string' 'Yes, recompute' 'value' 1 'Callback' set_yes } ...
{'style' 'checkbox' 'tag' 'ersp_no' 'string' 'No, use data file parameters (and existing ERSP info)' 'value' 0 'Callback' set_no } };
ersp_ans = inputgui('geometry', {[1] [1] [1] [1] [0.5 1] }, 'geomvert', [2 max(length(txt),1)*0.7 1 1 1 1], 'uilist', uilist, ...
'helpcom', '', 'title', ['Recalculate ' upper(strcom) ' parameters -- part of std_ersp()']);
if isempty(ersp_ans), res = 'cancel'; return; end;
if find(celltomat(ersp_ans)) == 2 % use existing ERSP info from this dataset
disp(['Using file on disk: ' filename ]);
params2 = params1;
res = 'usedisk';
else % Over write data in dataset
disp(['Deleting and recomputing file: ' filename ]);
res = 'recompute';
%delete(filename);
end
|
github
|
lcnhappe/happe-master
|
std_changroup.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_changroup.m
| 5,933 |
utf_8
|
3ec8fa1b075f3697d4a1c1970be1031b
|
% std_changroup() - Create channel groups for plotting.
%
% Usage:
% >> STUDY = std_changroup(STUDY, ALLEEG);
% >> STUDY = std_changroup(STUDY, ALLEEG, chanlocs, 'interp');
% Inputs:
% ALLEEG - Top-level EEGLAB vector of loaded EEG structures for the dataset(s)
% in the STUDY. ALLEEG for a STUDY set is typically loaded using
% pop_loadstudy(), or in creating a new STUDY, using pop_createstudy().
% STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
% chanlocs - EEGLAB channel structure. Only construct the STUDY.changrp
% structure for a subset of channels.
% 'interp' - optional input in case channel locations are interpolated
%
% Outputs:
% STUDY - The input STUDY set structure modified according to specified user
% edits, if any. The STUDY.changrp structure is created. It contains as
% many elements as there are channels. For example, STUDY.changrp(1)
% is the first channel. Fields of the changrp structure created at this
% point are
% STUDY.changrp.name : name of the channel group
% STUDY.changrp.channels : cell array containing channel labels
% for the group.
% STUDY.changrp.setinds : indices of datasets containing the
% selected channels.
% STUDY.changrp.allinds : indices of channels within the datasets
% above.
%
% Authors: Arnaud Delorme, CERCO, 2006
% Copyright (C) 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 STUDY = std_changroup(STUDY, ALLEEG, alllocs, interp);
if nargin < 4
interp = 'off';
end;
% union of all channel structures
% -------------------------------
inputloc = 0;
if nargin >= 3
if ~isempty(alllocs)
inputloc = 1;
end;
end;
if ~inputloc
alllocs = eeg_mergelocs(ALLEEG.chanlocs);
end;
% create group for each electrode
% -------------------------------
if isstruct(alllocs)
alllocs = { alllocs.labels };
end;
STUDY.changrp = [];
for indc = 1:length(alllocs)
STUDY.changrp(indc).name = alllocs{indc};
STUDY.changrp(indc).channels = { alllocs{indc} };
tmp = std_chanlookupnew( STUDY, ALLEEG, STUDY.changrp(indc), interp);
STUDY.changrp(indc).setinds = tmp.setinds;
STUDY.changrp(indc).allinds = tmp.allinds;
STUDY.changrp(indc).centroid = [];
end;
% if strcmpi(interp, 'off')
% if length(unique( cellfun(@length, { ALLEEG.chanlocs }))) ~= 1
% STUDY.changrpstatus = 'some channels missing in some datasets';
% else STUDY.changrpstatus = 'all channels present in all datasets';
% end;
% else STUDY.changrpstatus = 'all channels present in all datasets - interpolated';
% end;
%STUDY.changrp(indc).name = [ 'full montage' ];
%STUDY.changrp(indc).channels = { alllocs.labels };
%tmp = std_chanlookup( STUDY, ALLEEG, STUDY.changrp(indc));
%STUDY.changrp(indc).chaninds = tmp.chaninds;
return;
% find datasets and channel indices
% ---------------------------------
function changrp = std_chanlookupnew( STUDY, ALLEEG, changrp, interp);
setinfo = STUDY.design(STUDY.currentdesign).cell;
allconditions = STUDY.design(STUDY.currentdesign).variable(1).value;
allgroups = STUDY.design(STUDY.currentdesign).variable(2).value;
nc = max(length(allconditions),1);
ng = max(length(allgroups), 1);
changrp.allinds = cell( nc, ng );
changrp.setinds = cell( nc, ng );
for index = 1:length(setinfo)
% get index of independent variables
% ----------------------------------
condind = std_indvarmatch( setinfo(index).value{1}, allconditions);
grpind = std_indvarmatch( setinfo(index).value{2}, allgroups );
if isempty(allconditions), condind = 1; end;
if isempty(allgroups), grpind = 1; end;
% scan all channel labels
% -----------------------
if strcmpi(interp, 'off')
datind = setinfo(index).dataset;
tmpchanlocs = ALLEEG(datind(1)).chanlocs;
tmplocs = { tmpchanlocs.labels };
for indc = 1:length(changrp.channels) % usually just one channel
ind = strmatch( changrp.channels{indc}, tmplocs, 'exact');
if length(ind) > 1, error([ 'Duplicate channel label ''' tmplocs{ind(1)} ''' for dataset ' int2str(datind) ]); end;
if ~isempty(ind)
changrp.allinds{ condind, grpind } = [ changrp.allinds{ condind, grpind } ind ];
changrp.setinds{ condind, grpind } = [ changrp.setinds{ condind, grpind } index ];
end;
end;
else % interpolation is "on", all channels for all datasets
alllocs = { STUDY.changrp.name };
ind = strmatch( changrp.name, alllocs, 'exact');
changrp.allinds{ condind, grpind } = [ changrp.allinds{ condind, grpind } ind ];
changrp.setinds{ condind, grpind } = [ changrp.setinds{ condind, grpind } index ];
end;
end;
|
github
|
lcnhappe/happe-master
|
std_reset.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_reset.m
| 1,619 |
utf_8
|
72ffdfcbfcf2b3d338ff1b59bcf6d6d5
|
% std_reset() - Remove all preloaded measures from STUDY
%
% Usage:
% >> STUDY = std_reset(STUDY);
%
% Inputs:
% STUDY - EEGLAB STUDY structure
%
% Outputs:
% STUDY - EEGLAB STUDY structure
%
% Author: Arnaud Delorme, CERCO/CNRS & SCCN, INC, UCSD, 2009-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function STUDY = std_reset(STUDY)
if nargin < 1
help std_reset;
return;
end;
fields = { 'erpdata' 'erptimes' 'specdata' 'specfreqs' 'erspdata' ...
'ersptimes' 'erspfreqs' 'itcdata' 'itctimes' 'itcfreqs' ...
'topo' 'topox' 'topoy' 'topoall' 'topopol' 'dipole' };
for ind = 1:length(fields)
if isfield(STUDY.cluster, fields{ind})
STUDY.cluster = rmfield(STUDY.cluster, fields{ind});
end;
if isfield(STUDY, 'changrp')
if isfield(STUDY.changrp, fields{ind})
STUDY.changrp = rmfield(STUDY.changrp, fields{ind});
end;
end;
end;
|
github
|
lcnhappe/happe-master
|
std_substudy.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_substudy.m
| 5,138 |
utf_8
|
d57013b3c25ff4a8d8588e247f07bd61
|
% std_substudy() - create a sub-STUDY set by removing datasets, conditions, groups, or
% subjects.
% Usage:
% >> [ STUDY ALLEEG ] = std_substudy(STUDY, ALLEEG, 'key', 'val', ...);
%
% Optional Inputs:
% STUDY - existing study structure.
% ALLEEG - vector of EEG dataset structures to be included in the STUDY.
%
% Optional Inputs:
% 'dataset' - [integer array] indices of dataset to include in sub-STUDY
% Default is all datasets.
% 'subject' - [cell array] name of subjects to include in sub-STUDY.
% Default is all subjects.%
% 'condition' - [cell array] name of conditions to include in sub-STUDY
% Default is all conditions.
% 'group' - [cell array] name of gourps to include in sub-STUDY
% Default is all groups.
% 'rmdat' - ['on'|'off'] actually remove datasets 'on', or simply
% remove all references to these datasets for channels and
% clusters ('off').
%
% Example:
% % create a sub-STUDY using only the first 3 subjects
% % WARNING: make sure your STUDY is saved before creating a sub-STUDY
% [STUDY ALLEEG] = std_substudy(STUDY, ALLEEG, 'subject', STUDY.subjects(1:3));
%
% Authors: Arnaud Delorme, CERCO/CNSR & SCCN, INC, UCSD, 2009-
% 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 [ STUDY ALLEEG ] = std_substudy(STUDY, ALLEEG, varargin);
if nargin < 3
help std_substudy;
return;
end
opt = finputcheck(varargin, { 'condition' 'cell' {} {};
'dataset' 'integer' {} [];
'group' 'cell' {} {};
'rmdat' 'string' { 'on','off' } 'on';
'subject' 'cell' {} {} }, 'std_substudy');
if isstr(opt), return; end;
% find datasets to remove
% -----------------------
tagdel = [];
if ~isempty(opt.subject)
for index = 1:length(STUDY.datasetinfo)
if ~strmatch(STUDY.datasetinfo.subject, opt.subject, 'exact')
tagdel = [ tagdel index ];
end;
end;
end;
if ~isempty(opt.condition)
for index = 1:length(STUDY.datasetinfo)
if ~strmatch(STUDY.datasetinfo.condition, opt.condition, 'exact')
tagdel = [ tagdel index ];
end;
end;
end;
if ~isempty(opt.group)
for index = 1:length(STUDY.datasetinfo)
if ~strmatch(STUDY.datasetinfo.group, opt.group, 'exact')
tagdel = [ tagdel index ];
end;
end;
end;
if ~isempty(opt.dataset)
tagdel = [ tagdel setdiff([1:length(ALLEEG)], opt.dataset) ];
end;
tagdel = unique_bc(tagdel);
% find new dataset indices
% ------------------------
alldats = [1:length(ALLEEG)];
if strcmpi(opt.rmdat, 'on')
alldats(tagdel) = [];
for index = 1:length(ALLEEG)
tmp = find(alldats == index);
if isempty(tmp), tmp = NaN; end;
datcoresp(index) = tmp;
end;
ALLEEG(tagdel) = [];
STUDY.datasetinfo(tagdel) = [];
for index = 1:length(STUDY.datasetinfo)
STUDY.datasetinfo(index).index = index;
end;
else
alldats(tagdel) = [];
for index = 1:length(ALLEEG)
tmp = find(alldats == index);
if isempty(tmp), tmp = NaN; else tmp = index; end;
datcoresp(index) = tmp;
end;
end;
% check channel consistency
% -------------------------
for i = 1:length(STUDY.changrp)
for c = 1:size(STUDY.changrp(i).setinds,1)
for g = 1:size(STUDY.changrp(i).setinds,2)
newinds = datcoresp(STUDY.changrp(i).setinds{c,g});
nonnans = find(~isnan(newinds));
STUDY.changrp(i).setinds{c,g} = newinds(nonnans);
STUDY.changrp(i).allinds{c,g} = STUDY.changrp(i).allinds{c,g}(nonnans);
end;
end;
end;
% check cluster consistency
% -------------------------
for index = 1:length(STUDY.cluster)
STUDY.cluster(index).sets(:) = datcoresp(STUDY.cluster(index).sets(:));
for i = size(STUDY.cluster(index).sets,2):-1:1
if all(isnan(STUDY.cluster(index).sets(:,i)))
STUDY.cluster(index).sets(:,i) = [];
STUDY.cluster(index).comps(:,i) = [];
end;
end;
[tmp STUDY.cluster(index).setinds STUDY.cluster(index).allinds] = std_setcomps2cell(STUDY, STUDY.cluster(index).sets, STUDY.cluster(index).comps);
end;
STUDY = std_reset(STUDY);
STUDY = std_checkset(STUDY, ALLEEG);
|
github
|
lcnhappe/happe-master
|
std_plot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_plot.m
| 1,013 |
utf_8
|
c20379b5799cb761b42ccc8e155eb139
|
% std_plot() - This function is outdated. Use std_plottf() to plot time/
% frequency decompositions and function std_plotcurve() to
% plot erp and spectrum.
% Copyright (C) 2006 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 [pgroup, pcond, pinter] = std_plot(allx, data, varargin)
help std_plot;
return;
|
github
|
lcnhappe/happe-master
|
pop_precomp.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/pop_precomp.m
| 21,303 |
utf_8
|
3635c5fd488f6a3f81aadbc21962c9c5
|
% pop_precomp() - precompute measures (spectrum, ERP, ERSP) for a collection of data
% channels. Calls std_precomp().
% Usage:
% >> [STUDY, ALLEEG] = pop_precomp(STUDY, ALLEEG); % pop up interactive window
% Inputs:
% STUDY - STUDY set structure containing (loaded) EEG dataset structures
% ALLEEG - ALLEEG vector of EEG structures, else a single EEG dataset.
%
% Outputs:
% STUDY - the input STUDY set with added pre-clustering data for use by pop_clust()
% ALLEEG - the input ALLEEG vector of EEG dataset structures modified by adding
% pre-clustering data (pointers to .mat files that hold cluster measure information).
%
% Authors: Arnaud Delorme, CERCO, CNRS, 2006-
%
% See also: std_precomp()
% Copyright (C) Arnaud Delorme, CERCO, CNRS, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public 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 [STUDY, ALLEEG, com] = pop_precomp(varargin)
com = '';
if ~isstr(varargin{1}) %intial settings
if length(varargin) < 2
error('pop_precomp(): needs both ALLEEG and STUDY structures');
end
STUDY = varargin{1};
ALLEEG = varargin{2};
comps = false;
if nargin > 2
if strcmpi(varargin{3}, 'components')
comps = true;
end;
end;
if isempty(ALLEEG)
error('STUDY contains no datasets');
end
% callbacks
% ---------
erspparams_str = [ '''cycles'', [3 0.8], ''nfreqs'', 100, ''ntimesout'', 200' ];
specparams_str = '''specmode'', ''fft'', ''logtrials'', ''off''';
erpimageparams_str = '''nlines'', 10,''smoothing'', 10';
set_ersp = ['pop_precomp(''setersp'',gcf);'];
test_ersp = ['pop_precomp(''testersp'',gcf);'];
set_itc = ['pop_precomp(''setitc'',gcf);'];
set_spec = ['pop_precomp(''setspec'',gcf);'];
set_erp = ['pop_precomp(''seterp'',gcf);'];
set_erpimage = ['pop_precomp(''seterpimage'',gcf);'];
test_spec = ['pop_precomp(''testspec'',gcf);'];
test_erpimage = ['pop_precomp(''testerpimage'',gcf);'];
chanlist = ['pop_precomp(''chanlist'',gcf);'];
chanlist = 'warndlg2([ ''You need to compute measures on all data channels.'' 10 ''This functionality is under construction.'']);';
chaneditbox = ['pop_precomp(''chaneditbox'',gcf);'];
warninterp = ''; %['warndlg2(''EEGLAB will crash when plotting a given channel if it is missing in one dataset'');' ];
cb_ica1 = ''; %[ 'if get(gcbo, ''value''), set(findobj(gcbf, ''tag'', ''rmica2_on''), ''value'', 0); end;' ];
cb_ica2 = ''; %[ 'if get(gcbo, ''value''), set(findobj(gcbf, ''tag'', ''rmica1_on''), ''value'', 0); end;' ];
geomline = [0.35 6];
if comps == true
str_name = sprintf('Pre-compute component measures for STUDY ''%s'' - ''%s''', ...
STUDY.name, STUDY.design(STUDY.currentdesign).name);
if length(str_name) > 80, str_name = [ str_name(1:80) '...' ]; end;
guiadd1 = { {'style' 'checkbox' 'string' '' 'tag' 'compallersp' 'value' 1 } ...
{'style' 'text' 'string' 'Compute ERP/spectrum/ERSP only for components selected by RV (set) or for all components (unset)' } };
guiadd2 = { {'style' 'checkbox' 'string' '' 'tag' 'scalp_on' 'value' 0 } ...
{'style' 'text' 'string' 'Scalp maps' } };
geomadd1 = { geomline };
geomvertadd1 = [ 1 ];
geomadd2 = { geomline };
else
str_name = sprintf('Pre-compute channel measures for STUDY ''%s'' - ''%s''', ...
STUDY.name, STUDY.design(STUDY.currentdesign).name);
if length(str_name) > 80, str_name = [ str_name(1:80) '...''' ]; end;
guiadd1 = { {'style' 'text' 'string' 'Channel list (default:all)' 'FontWeight' 'Bold'} ...
{'Style' 'edit' 'string' '' 'tag' 'chans' 'callback' chaneditbox 'enable' 'off' }, ...
{'style' 'pushbutton' 'string' '...', 'enable' fastif(isempty(ALLEEG(1).chanlocs), 'off', 'on') ...
'callback' chanlist }, ...
{'style' 'checkbox' 'string' '' 'tag' 'interpolate_on' 'value' 1 'callback' warninterp } ...
{'style' 'text' 'string' 'Spherical interpolation of missing channels (performed after optional ICA removal below)' } ...
{'style' 'checkbox' 'string' ' ' 'tag' 'rmica1_on' 'value' 0 'callback' cb_ica1 } ...
{'style' 'text' 'string' 'Remove ICA artifactual components pre-tagged in each dataset' } ...
{'style' 'checkbox' 'string' [ ' ' 10 ' ' ] 'tag' 'rmica2_on' 'value' 0 'callback' cb_ica2 } ...
{'style' 'text' 'string' [ 'Remove artifactual ICA cluster or clusters (hold shift key)' 10 ' ' ] } ...
{'style' 'listbox' 'string' { STUDY.cluster.name } 'value' 1 'max' 2 'tag' 'rmica2_val'} };
guiadd2 = {};
geomadd1 = { [2 3 0.5] geomline geomline [0.35 4 2] };
geomvertadd1 = [ 1 1 1 2 ];
geomadd2 = { };
end;
gui_spec = { ...
{'style' 'text' 'string' str_name 'FontWeight' 'Bold' 'horizontalalignment' 'left'}, ...
{'style' 'text' 'string' '(warning: define your STUDY designs first as precomputation is specific to a given STUDY design)' } {}, ...
guiadd1{:}, ...
{} {'style' 'text' 'string' 'List of measures to precompute' 'FontWeight' 'Bold' 'horizontalalignment' 'left'}, ...
{'style' 'checkbox' 'string' '' 'tag' 'erp_on' 'value' 0 'Callback' set_erp } , ...
{'style' 'text' 'string' 'ERPs' }, {}, ...
{'style' 'text' 'string' 'Baseline ([min max] in ms)' 'tag' 'erp_text' 'enable' 'off'}...
{'style' 'edit' 'string' '' 'tag' 'erp_base' 'enable' 'off' }, { }, ...
{'style' 'checkbox' 'string' '' 'tag' 'spectra_on' 'value' 0 'Callback' set_spec }, ...
{'style' 'text' 'string' 'Power spectrum' }, {}, ...
{'style' 'text' 'string' 'Spectopo parameters' 'tag' 'spec_push' 'enable' 'off'}...
{'style' 'edit' 'string' specparams_str 'tag' 'spec_params' 'enable' 'off' }, ...
{'style' 'pushbutton' 'string' 'Test' 'tag' 'spec_test' 'enable' 'off' 'callback' test_spec}...
{'style' 'checkbox' 'string' '' 'tag' 'erpimage_on' 'value' 0 'Callback' set_erpimage }, ...
{'style' 'text' 'string' 'ERP-image' }, {}, ...
{'style' 'text' 'string' 'ERP-image parameters' 'tag' 'erpimage_push' 'enable' 'off'}...
{'style' 'edit' 'string' erpimageparams_str 'tag' 'erpimage_params' 'enable' 'off' }, ...
{'style' 'pushbutton' 'string' 'Test' 'tag' 'erpimage_test' 'enable' 'off' 'callback' test_erpimage}...
{'style' 'checkbox' 'string' '' 'tag' 'ersp_on' 'value' 0 'Callback' set_ersp } , ...
{'style' 'text' 'string' 'ERSPs' 'horizontalalignment' 'center' }, {}, ...
{'vertshift' 'style' 'text' 'string' 'Time/freq. parameters' 'tag' 'ersp_push' 'value' 1 'enable' 'off'}, ...
{'vertshift' 'style' 'edit' 'string' erspparams_str 'tag' 'ersp_params' 'enable' 'off'}...
{'vertshift' 'style' 'pushbutton' 'string' 'Test' 'tag' 'ersp_test' 'enable' 'off' 'callback' test_ersp }...
{'style' 'checkbox' 'string' '' 'tag' 'itc_on' 'value' 0 'Callback' set_itc }, ...
{'style' 'text' 'string' 'ITCs' 'horizontalalignment' 'center' }, {'link2lines' 'style' 'text' 'string' '' } {} {} {}, ...
guiadd2{:}, ...
{}, ...
{'style' 'checkbox' 'string' 'Save single-trial measures for single-trial statistics (beta) - requires disk space' 'tag' 'savetrials_on' 'value' 0 } {}, ...
{'style' 'checkbox' 'string' 'Overwrite files on disk' 'tag' 'recomp_on' 'value' 1 } {}, ...
};
%{'style' 'checkbox' 'string' '' 'tag' 'precomp_PCA' 'Callback' precomp_PCA 'value' 0} ...
%{'style' 'text' 'string' 'Do not prepare dataset for clustering at this time.' 'FontWeight' 'Bold' } {} ...
% find the list of all channels
% -----------------------------
allchans = { };
keepindex = 0;
for index = 1:length(ALLEEG)
tmpchanlocs = ALLEEG(index).chanlocs;
tmpchans = { tmpchanlocs.labels };
allchans = unique_bc({ allchans{:} tmpchanlocs.labels });
if length(allchans) == length(tmpchans), keepindex = index; end;
end;
if keepindex, tmpchanlocs = ALLEEG(keepindex).chanlocs; allchans = { tmpchanlocs.labels }; end;
chanlist = {};
firsttimeersp = 1;
fig_arg = { ALLEEG STUDY allchans chanlist firsttimeersp };
geomline1 = [0.40 1.3 0.1 2 2.4 0.65 ];
geomline2 = [0.40 0.9 0.5 2 2.4 0.65 ];
geometry = { [1] [1] [1] geomadd1{:} [1] [1] geomline1 geomline1 geomline1 geomline2 geomline2 geomadd2{:} 1 [1 0.1] [1 0.1] };
geomvert = [ 1 1 0.5 geomvertadd1 0.5 1 1 1 1 1 1 1 fastif(length(geomadd2) == 1,1,[]) 1 1];
[precomp_param, userdat2, strhalt, os] = inputgui( 'geometry', geometry, 'uilist', gui_spec, 'geomvert', geomvert, ...
'helpcom', ' pophelp(''std_precomp'')', ...
'title', 'Select and compute component measures for later clustering -- pop_precomp()', ...
'userdata', fig_arg);
if isempty(precomp_param), return; end;
if comps == 1
options = { STUDY ALLEEG 'components' };
else
options = { STUDY ALLEEG userdat2{4} };
end
if ~isfield(os, 'interpolate_on'), os.interpolate_on = 0; end;
if ~isfield(os, 'scalp_on'), os.scalp_on = 0; end;
if ~isfield(os, 'compallersp'), os.compallersp = 1; end;
warnflag = 0;
% rm_ica option is on
% -------------------
if isfield(os, 'rmica1_on')
if os.rmica1_on == 1
options = { options{:} 'rmicacomps' 'on' };
end
end;
% remove ICA cluster
% ------------------
if isfield(os, 'rmica2_on')
if os.rmica2_on == 1
options = { options{:} 'rmclust' os.rmica2_val };
end
end;
% interpolate option is on
% ------------------------
if os.savetrials_on == 1
options = { options{:} 'savetrials' 'on' };
end
% interpolate option is on
% ------------------------
if os.interpolate_on == 1
options = { options{:} 'interp' 'on' };
end
% compallersp option is on
% ------------------------
if os.compallersp == 0
options = { options{:} 'allcomps' 'on' };
end
% recompute option is on
% ----------------------
if os.recomp_on == 1
options = { options{:} 'recompute' 'on' };
end
% ERP option is on
% ----------------
if os.erp_on == 1
options = { options{:} 'erp' 'on' };
if ~isempty(os.erp_base)
options = { options{:} 'erpparams' { 'rmbase' str2num(os.erp_base) } };
end
warnflag = checkFilePresent(STUDY, 'erp', comps, warnflag, os.recomp_on);
end
% SCALP option is on
% ----------------
if os.scalp_on == 1
options = { options{:} 'scalp' 'on' };
end
% Spectrum option is on
% --------------------
if os.spectra_on== 1
tmpparams = eval( [ '{' os.spec_params '}' ] );
options = { options{:} 'spec' 'on' 'specparams' tmpparams };
warnflag = checkFilePresent(STUDY, 'spec', comps, warnflag, os.recomp_on);
end
% ERPimage option is on
% --------------------
if os.erpimage_on== 1
tmpparams = eval( [ '{' os.erpimage_params '}' ] );
options = { options{:} 'erpim' 'on' 'erpimparams' tmpparams };
warnflag = checkFilePresent(STUDY, 'erpim', comps, warnflag, os.recomp_on);
end
% ERSP option is on
% -----------------
if os.ersp_on == 1
tmpparams = eval( [ '{' os.ersp_params '}' ] );
options = { options{:} 'ersp' 'on' 'erspparams' tmpparams };
warnflag = checkFilePresent(STUDY, 'ersp', comps, warnflag, os.recomp_on);
end
% ITC option is on
% ----------------
if os.itc_on == 1
tmpparams = eval( [ '{' os.ersp_params '}' ] );
options = { options{:} 'itc' 'on' };
if os.ersp_on == 0, options = { options{:} 'erspparams' tmpparams }; end;
warnflag = checkFilePresent(STUDY, 'itc', comps, warnflag, os.recomp_on);
end
% evaluate command
% ----------------
if length(options) == 4
warndlg2('No measure selected: aborting.');
return;
end;
[STUDY ALLEEG] = std_precomp(options{:});
com = sprintf('[STUDY ALLEEG] = std_precomp(STUDY, ALLEEG, %s);', vararg2str(options(3:end)));
else
hdl = varargin{2}; %figure handle
userdat = get(varargin{2}, 'userdata');
ALLEEG = userdat{1};
STUDY = userdat{2};
allchans = userdat{3};
chansel = userdat{4};
firsttimeersp = userdat{5};
switch varargin{1}
case 'chanlist'
[tmp tmp2 tmp3] = pop_chansel(allchans, 'select', chansel);
if ~isempty(tmp)
set(findobj('parent', hdl, 'tag', 'chans'), 'string', tmp2);
userdat{4} = tmp3;
end;
set(hdl, 'userdata',userdat);
case 'chaneditbox'
userdat{4} = parsetxt(get(findobj('parent', hdl, 'tag', 'chans'), 'string'));
set(hdl, 'userdata',userdat);
case { 'setitc' 'setersp' }
set_itc = get(findobj('parent', hdl, 'tag', 'itc_on'), 'value');
set_ersp = get(findobj('parent', hdl, 'tag', 'ersp_on'), 'value');
if (~set_ersp & ~set_itc )
set(findobj('parent', hdl,'tag', 'ersp_push'), 'enable', 'off');
set(findobj('parent', hdl,'tag', 'ersp_params'), 'enable', 'off');
set(findobj('parent', hdl,'tag', 'ersp_test'), 'enable', 'off');
else
set(findobj('parent', hdl,'tag', 'ersp_push'), 'enable', 'on');
set(findobj('parent', hdl,'tag', 'ersp_params'), 'enable', 'on');
set(findobj('parent', hdl,'tag', 'ersp_test'), 'enable', 'on');
end
userdat{5} = 0;
set(hdl, 'userdata',userdat);
if firsttimeersp
warndlg2(strvcat('Checking both ''ERSP'' and ''ITC'' does not require further', ...
'computing time. However it requires disk space'));
end;
case 'setspec'
set_spec = get(findobj('parent', hdl, 'tag', 'spectra_on'), 'value');
if set_spec
set(findobj('parent', hdl,'tag', 'spec_push'), 'enable', 'on');
set(findobj('parent', hdl,'tag', 'spec_params'), 'enable', 'on');
set(findobj('parent', hdl,'tag', 'spec_test'), 'enable', 'on');
else set(findobj('parent', hdl,'tag', 'spec_push'), 'enable', 'off');
set(findobj('parent', hdl,'tag', 'spec_params'), 'enable', 'off');
set(findobj('parent', hdl,'tag', 'spec_test'), 'enable', 'off');
end
case 'seterpimage'
set_spec = get(findobj('parent', hdl, 'tag', 'erpimage_on'), 'value');
if set_spec
set(findobj('parent', hdl,'tag', 'erpimage_push'), 'enable', 'on');
set(findobj('parent', hdl,'tag', 'erpimage_params'), 'enable', 'on');
set(findobj('parent', hdl,'tag', 'erpimage_test'), 'enable', 'on');
else set(findobj('parent', hdl,'tag', 'erpimage_push'), 'enable', 'off');
set(findobj('parent', hdl,'tag', 'erpimage_params'), 'enable', 'off');
set(findobj('parent', hdl,'tag', 'erpimage_test'), 'enable', 'off');
end
case 'seterp'
set_erp = get(findobj('parent', hdl, 'tag', 'erp_on'), 'value');
if set_erp
set(findobj('parent', hdl,'tag', 'erp_text'), 'enable', 'on');
set(findobj('parent', hdl,'tag', 'erp_base'), 'enable', 'on');
else set(findobj('parent', hdl,'tag', 'erp_text'), 'enable', 'off');
set(findobj('parent', hdl,'tag', 'erp_base'), 'enable', 'off');
end
case 'testspec'
try,
spec_params = eval([ '{' get(findobj('parent', hdl, 'tag', 'spec_params'), 'string') '}' ]);
TMPEEG = eeg_checkset(ALLEEG(1), 'loaddata');
[ X f ] = std_spec(TMPEEG, 'channels', { TMPEEG.chanlocs(1).labels }, 'trialindices', { [1:min(20,TMPEEG.trials)] }, 'recompute', 'on', 'savefile', 'off', spec_params{:});
figure; plot(f, X);
xlabel('Frequencies (Hz)');
ylabel('Power');
xlim([min(f) max(f)]);
tmplim = ylim;
text( TMPEEG.srate/4, mean(tmplim)+(max(tmplim)-min(tmplim))/3, ...
strvcat('This is a test plot performed on', ...
'the first 20 trials of the first', ...
'dataset (1 line per channel).', ...
'Frequency range may be adjusted', ...
'after computation'));
icadefs;
set(gcf, 'color', BACKCOLOR);
catch, warndlg2('Error while calling function, check parameters'); end;
case 'testersp'
try,
ersp_params = eval([ '{' get(findobj('parent', hdl, 'tag', 'ersp_params'), 'string') '}' ]);
tmpstruct = struct(ersp_params{:});
[ tmpX tmpt tmpf ersp_params ] = std_ersp(ALLEEG(1), 'channels', 1, 'trialindices', { [1:min(20,ALLEEG(1).trials)] }, 'type', 'ersp', 'recompute', 'on', 'savefile', 'off', ersp_params{:});
std_plottf(tmpt, tmpf, { tmpX });
catch, warndlg2('Error while calling function, check parameters'); end;
case 'testerpimage'
try,
erpimage_params = eval([ '{' get(findobj('parent', hdl, 'tag', 'erpimage_params'), 'string') '}' ]);
tmpstruct = struct(erpimage_params{:});
erpimstruct = std_erpimage(ALLEEG(1), 'channels', 1, 'recompute', 'on', 'savefile', 'off', erpimage_params{:});
figure; pos = get(gcf, 'position'); pos(3)=pos(3)*2; set(gcf, 'position', pos);
subplot(1,2,1);
tftopo(erpimstruct.chan1, erpimstruct.times, 1:size(erpimstruct.chan1,1), 'ylabel', 'Trials');
subplot(1,2,2);
text( 0.2, 0.8, strvcat( 'This is a test plot performed on', ...
'the first channel of the first', ...
'dataset.', ...
' ', ...
'Time and trial range may be', ...
'adjusted after computation.'), 'fontsize', 18);
axis off;
icadefs;
set(gcf, 'color', BACKCOLOR);
catch, warndlg2('Error while calling function, check parameters'); end;
end;
end
STUDY.saved = 'no';
% check if file is present
% ------------------------
function warnflag = checkFilePresent(STUDY, datatype, comps, warnflag, recompute);
if ~recompute, return; end;
if warnflag, return; end; % warning has already been issued
if comps
dataFilename = [ STUDY.design(STUDY.currentdesign).cell(1).filebase '.ica' datatype ];
else dataFilename = [ STUDY.design(STUDY.currentdesign).cell(1).filebase '.dat' datatype ];
end;
if exist(dataFilename)
textmsg = [ 'WARNING: SOME DATAFILES ALREADY EXIST, OVERWRITE THEM?' 10 ...
'(if you have another STUDY using the same datasets, it might overwrite its' 10 ...
'precomputed data files. Instead, use a single STUDY and create multiple designs).' ];
res = questdlg2(textmsg, 'Precomputed datafiles already present on disk', 'No', 'Yes', 'Yes');
if strcmpi(res, 'No')
error('User aborded precomputing measures');
end;
end;
warnflag = 1;
|
github
|
lcnhappe/happe-master
|
std_prepare_neighbors.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_prepare_neighbors.m
| 4,382 |
utf_8
|
a4a473e9fb500e8887f25e81a5641d93
|
% std_prepare_neighbors() - prepare Fieldtrip channel neighbor structure.
% Only prepare the structure if necessary based
% on statistical options in STUDY.etc.statistics.
% Use the 'force' option to force preparing the
% matrix.
%
% Usage:
% >> [STUDY neighbors] = std_prepare_neighbors( STUDY, ALLEEG, 'key', val)
%
% Inputs:
% STUDY - an EEGLAB STUDY set of loaded EEG structures
% ALLEEG - ALLEEG vector of one or more loaded EEG dataset structures
%
% Optional inputs:
% 'force' - ['on'|'off'] force generating the structure irrespective
% of the statistics options selected. Default is 'off'.
% 'channels' - [cell] list of channels to include in the matrix
% 'method' - [string] method for preparing. See ft_prepare_neighbors
% 'neighbordist' - [float] max distance. See ft_prepare_neighbors
%
% Note: other ft_prepare_neighbors fields such as template, layout may
% also be used as optional keywords.
%
% Outputs:
% STUDY - an EEGLAB STUDY set of loaded EEG structures
% neighbors - Fieldtrip channel neighbour structure
%
% Author: Arnaud Delorme, SCCN, UCSD, 2012-
%
% See also: statcondfieldtrip()
% 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 [STUDY neighbors] = std_prepare_neighbors(STUDY, ALLEEG, varargin);
neighbors = [];
if nargin < 2
return;
end;
[opt addopts] = finputcheck( varargin, { 'force' 'string' { 'on','off' } 'off';
'channels' 'cell' {} {} }, 'std_stat', 'ignore');
if strcmpi(opt.force, 'on') || (strcmpi(STUDY.etc.statistics.fieldtrip.mcorrect, 'cluster') && ...
strcmpi(STUDY.etc.statistics.mode, 'fieldtrip') && (strcmpi(STUDY.etc.statistics.groupstats, 'on') || strcmpi(STUDY.etc.statistics.condstats, 'on')))
EEG = eeg_emptyset;
EEG.chanlocs = eeg_mergelocs(ALLEEG.chanlocs);
if isempty(EEG.chanlocs)
disp('std_prepare_neighbors: cannot prepare channel neighbour structure because of empty channel structures');
return;
end;
if ~isempty(STUDY.etc.statistics.fieldtrip.channelneighbor) && isempty(addopts) && ...
length(STUDY.etc.statistics.fieldtrip.channelneighbor) == length(EEG.chanlocs)
disp('Using stored channel neighbour structure');
neighbors = STUDY.etc.statistics.fieldtrip.channelneighbor;
else
if ~isempty(opt.channels)
indChans = eeg_chaninds(EEG, opt.channels);
EEG.chanlocs = EEG.chanlocs(indChans);
end;
EEG.nbchan = length(EEG.chanlocs);
EEG.data = zeros(EEG.nbchan,100,1);
EEG.trials = 1;
EEG.pnts = 100;
EEG.xmin = 0;
EEG.srate = 1;
EEG.xmax = 99;
EEG = eeg_checkset(EEG);
tmpcfg = eeglab2fieldtrip(EEG, 'preprocessing', 'none');
% call the function that find channel neighbors
% ---------------------------------------------
addparams = eval( [ '{' STUDY.etc.statistics.fieldtrip.channelneighborparam '}' ]);
for index = 1:2:length(addparams)
tmpcfg = setfield(tmpcfg, addparams{index}, addparams{index+1});
end;
for index = 1:2:length(addopts)
tmpcfg = setfield(tmpcfg, addopts{index}, addopts{index+1});
end;
warning off;
cfg.neighbors = ft_prepare_neighbours(tmpcfg, tmpcfg);
warning on;
neighbors = cfg.neighbors;
end;
STUDY.etc.statistics.fieldtrip.channelneighbor = neighbors;
end;
|
github
|
lcnhappe/happe-master
|
std_savedat.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_savedat.m
| 1,752 |
utf_8
|
32ee6d94f325818156111da795834c6d
|
% std_savedat() - save measure for computed data
%
% Usage: std_savedat( filename, structure);
%
% Authors: Arnaud Delorme, SCCN, INC, UCSD, 2006-
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 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
function std_savedat( tmpfile, structure)
delims = find( tmpfile == '.');
if ~isfield(structure, 'datafile') && ~isfield(structure, 'datafiles')
structure.datafile = [ tmpfile(1:delims(end)-1) '.set' ];
end;
% fix reading problem (bug 764)
tmpfile2 = which(tmpfile);
if isempty(tmpfile2), tmpfile2 = tmpfile; end;
tmpfile = tmpfile2;
eeglab_options;
if option_saveversion6
try
save('-v6' , tmpfile, '-struct', 'structure');
catch
fields = fieldnames(structure);
for i=1:length(fields)
eval([ fields{i} '=structure.' fields{i} ';']);
end;
save('-mat', tmpfile, fields{:});
end;
else
save('-v7.3' , tmpfile, '-struct', 'structure');
end;
|
github
|
lcnhappe/happe-master
|
std_clustmaxelec.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_clustmaxelec.m
| 2,424 |
utf_8
|
1a243dcf2ffd5e5be4cbaf58a69e3ac9
|
% std_clustmaxelec() - function to find the electrode with maximum absolute projection
% for each component of a cluster
% Usage:
% >> [STUDY, ALLEEG] = std_clustmaxelec(STUDY, ALLEEG, clustind);
%
% Inputs:
% STUDY - STUDY set structure containing (loaded) EEG dataset structures
% ALLEEG - ALLEEG vector of EEG structures, else a single EEG dataset.
% clustind - (single) cluster index
%
% Outputs:
% eleclist - [cell] electrode list
% setlist - [integer] set indices for the cluster
% complist - [integer] component indices for the cluster
%
% Authors: Claire Braboszcz & Arnaud Delorme , CERCO, UPS/CRNS, 2011
% Copyright (C) Claire Braboszcz, CERCO, UPS/CRNS, 2011
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public 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 std_clustmaxelec(STUDY, ALLEEG, clusterind);
if nargin < 1
help findicmaxelec;
return;
end;
fprintf('Finding electrodes with max weight for cluster %d\n', clusterind);
fprintf('-------------------------------------------------\n');
for index = 1:length(STUDY.cluster(clusterind).comps)
set = STUDY.cluster(clusterind).sets(1,index);
comp = STUDY.cluster(clusterind).comps( index);
[tmp maxelec] = max( abs(ALLEEG(set).icawinv(:, comp)) );
indelec = ALLEEG(set).icachansind(maxelec);
maxallelec{index} = ALLEEG(set).chanlocs(indelec).labels;
allelec = unique_bc(maxallelec);
fprintf('The electrode with the max weight for component %d of dataset %d is "%s"\n', comp, set, maxallelec{index});
end;
for indelec=1:length(allelec)
nbelec{indelec} = length(find(strcmp(allelec{indelec}, maxallelec) == 1));
fprintf('Number of occurrence of electrode %s: %d\n', allelec{indelec}, nbelec{indelec});
end;
|
github
|
lcnhappe/happe-master
|
pop_studydesign.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/pop_studydesign.m
| 28,501 |
utf_8
|
c75d88532140cf5c2dfed99d9a06843f
|
% pop_studydesign() - create a STUDY design structure.
%
% Usage:
% >> [STUDY, ALLEEG] = pop_studydesign(STUDY, ALLEEG, key1, val1, ...);
%
% Inputs:
% STUDY - EEGLAB STUDY set
% ALLEEG - vector of the EEG datasets included in the STUDY structure
%
% Optional inputs:
%
% Authors: Arnaud Delorme, April 2010
% Copyright (C) Arnaud Delorme & Scott Makeig, SCCN/INC/UCSD, October 11, 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
function [STUDY allcom] = pop_studydesign(STUDY, ALLEEG, designind, varargin);
allcom = '';
if nargin < 2
help pop_studydesign;
return;
end;
if nargin < 3 && ~isstr(STUDY)
%% create GUI
[ usrdat.factors usrdat.factorvals usrdat.factsubj] = std_getindvar(STUDY, 'both', 1);
usrdat.factors = { 'None' usrdat.factors{:} };
usrdat.factorvals = { {} usrdat.factorvals{:} };
usrdat.factsubj = { {} usrdat.factsubj{:} };
usrdat.subjects = STUDY.subject;
usrdat.datasetinfo = STUDY.datasetinfo;
usrdat.design = STUDY.design;
usrdat.filepath = STUDY.filepath;
for ind = 1:length(usrdat.design)
usrdat.design(ind).deletepreviousfiles = 0;
end;
% build menu
popupselectsubj = { 'Select all subjects' };
for ind1 = 1:length(usrdat.factors)
if ~isempty(usrdat.factsubj{ind1})
if any(cellfun(@length, usrdat.factsubj{ind1}) ~= length(usrdat.subjects))
for ind2 = 1:length(usrdat.factorvals{ind1})
if ~iscell(usrdat.factorvals{ind1}{ind2}) % not a combined value
tmpval = encodevals(usrdat.factorvals{ind1}(ind2));
popupselectsubj{end+1} = [ num2str(usrdat.factors{ind1}) ' - ' tmpval{1} ];
end;
end;
end;
end;
end;
cb_rename = 'pop_studydesign(''rename'', gcbf);';
cb_add = 'pop_studydesign(''add'', gcbf);';
cb_del = 'pop_studydesign(''del'', gcbf);';
cb_listboxfact1 = 'pop_studydesign(''selectfact'', gcf, 0);';
cb_listboxfact2 = 'pop_studydesign(''selectfact'', gcf, 1);';
cb_selectsubj = 'pop_studydesign(''selectsubj'', gcbf);';
cb_combinevals1 = 'pop_studydesign(''combinevals'', gcbf, 0);';
cb_combinevals2 = 'pop_studydesign(''combinevals'', gcbf, 1);';
cb_lbval = 'pop_studydesign(''updatedesign'', gcbf);';
cb_selectdesign = 'pop_studydesign(''selectdesign'', gcbf);';
cb_selectdata = 'pop_studydesign(''selectdatatrials'', gcbf);';
cb_selectfolder = 'pop_studydesign(''selectfolder'', gcbf);';
cb_setfolder = 'pop_studydesign(''updatedesign'', gcbf);';
uilist = { { 'style' 'text' 'string' 'Select STUDY design' 'fontweight' 'bold' } ...
{ 'style' 'listbox' 'string' { usrdat.design.name } 'tag' 'listboxdesign' 'callback' cb_selectdesign 'value' STUDY.currentdesign } ...
{ 'style' 'pushbutton' 'string' 'Add design' 'callback' cb_add } ...
{ 'style' 'pushbutton' 'string' 'Rename design' 'callback' cb_rename } ...
{ 'style' 'pushbutton' 'string' 'Delete design' 'callback' cb_del } ...
{ 'style' 'text' 'string' 'Subjects' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Independent variable 1 ' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Independent variable 2 ' 'fontweight' 'bold' } ...
{ 'style' 'listbox' 'string' usrdat.subjects 'tag' 'lbsubj' 'min' 0 'max' 2 'value' 1 'callback' cb_lbval } ...
{ 'style' 'listbox' 'string' usrdat.factors 'tag' 'lbfact0' 'callback' cb_listboxfact1 'value' 2 } ...
{ 'style' 'listbox' 'string' usrdat.factors 'tag' 'lbfact1' 'callback' cb_listboxfact2 'value' 1 } ...
{ 'style' 'text' 'string' 'Ind. var. 1 values ' } ...
{ 'style' 'text' 'string' 'Ind. var. 2 values' } ...
{ 'style' 'listbox' 'string' '' 'tag' 'lbval0' 'min' 0 'max' 2 'callback' cb_lbval } ...
{ 'style' 'listbox' 'string' '' 'tag' 'lbval1' 'min' 0 'max' 2 'callback' cb_lbval } ...
{ 'style' 'popupmenu' 'string' popupselectsubj 'tag' 'popupselect' 'callback' cb_selectsubj } ...
{ 'style' 'pushbutton' 'string' 'Combine selected values' 'tag' 'combine1' 'callback' cb_combinevals1 } ...
{ 'style' 'pushbutton' 'string' 'Combine selected values' 'tag' 'combine2' 'callback' cb_combinevals2 } ...
{ 'style' 'popupmenu' 'string' 'Paired statistics|Unpaired statistics' 'tag' 'lbpair0' 'callback' cb_lbval } ...
{ 'style' 'popupmenu' 'string' 'Paired statistics|Unpaired statistics' 'tag' 'lbpair1' 'callback' cb_lbval } ...
{ 'style' 'pushbutton' 'string' 'Use only specific datasets/trials' 'callback' cb_selectdata } ...
{ 'style' 'edit' 'string' '' 'tag' 'edit_selectdattrials' 'callback' cb_lbval } ...
{ 'style' 'text' 'string' 'Store pre-computed files in folder' } ...
{ 'style' 'edit' 'string' '' 'tag' 'edit_storedir' 'callback' cb_setfolder } ...
{ 'style' 'pushbutton' 'string' '...' 'callback' cb_selectfolder } ...
{ 'style' 'checkbox' 'string' 'Delete all pre-computed datafiles associated with this specific STUDY design' 'tag' 'chk_del' 'callback' cb_lbval } ...
{ 'style' 'checkbox' 'string' 'Save the STUDY' 'tag' 'chk_save' 'value' 1 } };
% { 'style' 'checkbox' 'string' 'Paired statistics' 'tag' 'lbpair0' 'callback' cb_lbval } ...
% { 'style' 'checkbox' 'string' 'Paired statistics' 'tag' 'lbpair1' 'callback' cb_lbval } ...
geometry = { {3 18 [1 1] [2 1] } ...
{3 18 [1 2] [2 3] } ...
{3 18 [3 2] [1 1] } ...
{3 18 [3 3] [1 1] } ...
{3 18 [3 4] [1 1] } ...
{3 18 [1 5] [1 1] } ...
{3 18 [2 5] [1 1] } ...
{3 18 [3 5] [1 1] } ...
{3 18 [1 6] [1 8] } ...
{3 18 [2 6] [0.98 3] } ...
{3 18 [3 6] [0.98 3] } ...
{3 18 [2 9] [1 1] } ...
{3 18 [3 9] [1 1] } ...
{3 18 [2 10] [0.98 3] } ...
{3 18 [3 10] [0.98 3] } ...
{3 18 [1 14] [1 1] } ...
{3 18 [2 13] [1 1] } ...
{3 18 [3 13] [1 1] } ...
{3 18 [2 14] [1 1] } ...
{3 18 [3 14] [1 1] } ...
{3 18 [1 15.5] [1.3 1] } ...
{3 18 [2.25 15.5] [1.7 1] } ...
{3 18 [1 16.5] [1.3 1] } ...
{3 18 [2.25 16.5] [1.2 1] } ...
{3 18 [3.45 16.5] [0.55 1] } ...
{3 18 [1 17.5] [3 1] } ...
{3 18 [1 19] [3 1] } ...
};
for i = 1:length(geometry), geometry{i}{3} = geometry{i}{3}-1; end;
streval = [ 'pop_studydesign(''selectdesign'', gcf);' ];
[tmp usrdat tmp2 result] = inputgui('uilist', uilist, 'title', 'Edit STUDY design -- pop_studydesign()', 'helpbut', 'Web help', 'helpcom', 'web(''http://sccn.ucsd.edu/wiki/Chapter_03:_Working_with_STUDY_designs'', ''-browser'')', 'geom', geometry, 'userdata', usrdat, 'eval', streval);
if isempty(tmp), return; end;
% call std_makedesign
% -------------------
des = usrdat.design;
allcom = '';
if length(des) < length(STUDY.design)
for index = length(des)+1:length(STUDY.design)
fprintf('Deleting STUDY design %d\n', index);
com = 'STUDY.design(index).name = '';'; eval(com);
allcom = [ allcom 10 com ];
end;
end;
for index = 1:length(des)
tmpdes = rmfield(des(index), 'deletepreviousfiles');
rmfiles = fastif(des(index).deletepreviousfiles, 'limited', 'off');
if index > length(STUDY.design) || ~isequal(STUDY.design(index), tmpdes) || strcmpi(rmfiles, 'on')
fprintf('Updating/creating STUDY design %d\n', index);
% test if file exist and issue warning
if length(STUDY.design) >= index && isfield('cell', STUDY.design) && ~isempty(STUDY.design(index).cell) && ...
~isempty(dir([ STUDY.design(index).cell(1).filebase '.*' ])) && strcmpi(rmfiles, 'off')
if ~isequal(tmpdes.variable(1).label, STUDY.design(index).variable(1).label) || ...
~isequal(tmpdes.variable(2).label, STUDY.design(index).variable(2).label) || ...
~isequal(tmpdes.include, STUDY.design(index).include) || ...
~isequal(tmpdes.variable(1).value, STUDY.design(index).variable(1).value) || ...
~isequal(tmpdes.cases.value, STUDY.design(index).cases.value) || ...
~isequal(tmpdes.variable(2).value, STUDY.design(index).variable(2).value)
res = questdlg2(strvcat([ 'Precomputed data files exist for design ' int2str(index) '.' ], ' ', ...
'Modifying this design without deleting the associated files', ...
'might mean that they will stay on disk and will be unusable'), ...
'STUDY design warning', 'Abort', 'Continue', 'Continue');
if strcmpi(res, 'Abort'), return; end;
end;
end;
[STUDY com] = std_makedesign(STUDY, ALLEEG, index, tmpdes, 'delfiles', rmfiles);
allcom = [ allcom 10 com ];
else
fprintf('STUDY design %d not modified\n', index);
end;
end;
if result.listboxdesign ~= STUDY.currentdesign
fprintf('Selecting STUDY design %d\n', result.listboxdesign);
com = sprintf('STUDY = std_selectdesign(STUDY, ALLEEG, %d);', result.listboxdesign); eval(com);
allcom = [ allcom 10 com ];
end;
if result.chk_save == 1
fprintf('Resaving STUDY\n');
[STUDY ALLEEG com] = pop_savestudy(STUDY, ALLEEG, 'savemode', 'resave');
allcom = [ allcom 10 com ];
end;
if ~isempty(allcom), allcom(1) = []; end;
elseif isstr(STUDY)
com = STUDY;
fig = ALLEEG;
usrdat = get(fig, 'userdata');
datinfo = usrdat.datasetinfo;
des = usrdat.design;
filepath = usrdat.filepath;
switch com
% summary of callbacks
% case 'add', Add new study design
% case 'del', Delete study design
% case 'rename', Rename study design
%
% case 'selectdesign', select a specific design
% case 'updatedesign', update the study information (whenever the
% user click on a button
%
% case 'selectfact', select a specific ind. var. (update value listboxes)
% case 'combinevals', combine values in value listboxes
% case 'selectsubj', select specific subjects
%
% case 'selectdatatrials', new GUI to select specific dataset and trials
% case 'selectdatatrialssel', % select in the GUI above
% case 'selectdatatrialsadd', % add new selection in the GUI above
case 'add', % Add new study design
inde = find( cellfun(@isempty,{ des.name }));
if isempty(inde), inde = length(des)+1; end;
des(inde(1)) = des(1);
des(inde(1)).name = sprintf('Design %d', inde(1));
set(findobj(fig, 'tag', 'listboxdesign'), 'string', { des.name }, 'value', inde(1));
usrdat.design = des;
set(fig, 'userdata', usrdat);
pop_studydesign( 'selectstudy', fig);
return;
case 'del', % Delete study design
val = get(findobj(fig, 'tag', 'listboxdesign'), 'value');
if val == 1
warndlg2('The first STUDY design cannot be removed, only modified');
return;
end;
des(val).name = '';
set(findobj(fig, 'tag', 'listboxdesign'), 'value', 1, 'string', { des.name } );
usrdat.design = des;
set(fig, 'userdata', usrdat);
pop_studydesign( 'selectstudy', fig);
return;
case 'rename', % Rename study design
val = get(findobj(fig, 'tag', 'listboxdesign'), 'value');
strs = get(findobj(fig, 'tag', 'listboxdesign'), 'string');
result = inputdlg2( { 'Study design name: ' }, ...
'Rename Study Design', 1, { strs{val} }, 'pop_studydesign');
if isempty(result), return; end;
des(val).name = result{1};
set(findobj(fig, 'tag', 'listboxdesign'), 'string', { des.name } );
case 'selectdesign', % select a specific design
val = get(findobj(fig, 'tag', 'listboxdesign'), 'value');
if isempty(des(val).name)
set(findobj(fig, 'tag', 'lbfact0'), 'string', '', 'value', 1);
set(findobj(fig, 'tag', 'lbfact1'), 'string', '', 'value', 1);
set(findobj(fig, 'tag', 'lbval0') , 'string', '', 'value', 1);
set(findobj(fig, 'tag', 'lbval1') , 'string', '', 'value', 1);
set(findobj(fig, 'tag', 'lbpair0'), 'value', 1);
set(findobj(fig, 'tag', 'lbpair1'), 'value', 1);
set(findobj(fig, 'tag', 'lbsubj') , 'value' , 1, 'string', '');
set(findobj(fig, 'tag', 'chk_del'), 'value', des(val).deletepreviousfiles );
set(findobj(fig, 'tag', 'edit_selectdattrials'), 'string', '' );
% do not change file path
return;
end;
val1 = strmatch(des(val).variable(1).label, usrdat.factors, 'exact'); if isempty(val1), val1 = 1; end;
val2 = strmatch(des(val).variable(2).label, usrdat.factors, 'exact'); if isempty(val2), val2 = 1; end;
set(findobj(fig, 'tag', 'lbfact0'), 'string', usrdat.factors, 'value', val1);
set(findobj(fig, 'tag', 'lbfact1'), 'string', usrdat.factors, 'value', val2);
valfact1 = strmatchmult(des(val).variable(1).value, usrdat.factorvals{val1});
valfact2 = strmatchmult(des(val).variable(2).value, usrdat.factorvals{val2});
if isempty(valfact1), listboxtop1 = 1; else listboxtop1 = valfact1(1); end;
if isempty(valfact2), listboxtop2 = 1; else listboxtop2 = valfact2(1); end;
set(findobj(fig, 'tag', 'lbval0'), 'string', encodevals(usrdat.factorvals{val1}), 'value', valfact1, 'listboxtop', listboxtop1);
set(findobj(fig, 'tag', 'lbval1'), 'string', encodevals(usrdat.factorvals{val2}), 'value', valfact2, 'listboxtop', listboxtop2);
valsubj = strmatchmult(des(val).cases.value, usrdat.subjects);
set(findobj(fig, 'tag', 'lbsubj'), 'string', usrdat.subjects, 'value', valsubj);
if isempty(des(val).include), str = ''; else str = vararg2str(des(val).include); end;
set(findobj(fig, 'tag', 'chk_del'), 'value', des(val).deletepreviousfiles );
set(findobj(fig, 'tag', 'edit_selectdattrials'), 'string', str );
set(findobj(fig, 'tag', 'popupselect'), 'value', 1 );
set(findobj(fig, 'tag', 'lbpair0'), 'value', fastif(isequal(des(val).variable(1).pairing,'on'),1,2));
set(findobj(fig, 'tag', 'lbpair1'), 'value', fastif(isequal(des(val).variable(2).pairing,'on'),1,2));
if ~isfield(des, 'filepath') || isempty(des(val).filepath), des(val).filepath = ''; end;
set(findobj(fig, 'tag', 'edit_storedir'), 'string', des(val).filepath);
case 'updatedesign', % update the study information (whenever the user click on a button)
val = get(findobj(fig, 'tag', 'listboxdesign'), 'value');
val1 = get(findobj(fig, 'tag', 'lbfact0'), 'value');
val2 = get(findobj(fig, 'tag', 'lbfact1'), 'value');
valf1 = get(findobj(fig, 'tag', 'lbval0'), 'value');
valf2 = get(findobj(fig, 'tag', 'lbval1'), 'value');
valp1 = get(findobj(fig, 'tag', 'lbpair0'), 'value');
valp2 = get(findobj(fig, 'tag', 'lbpair1'), 'value');
vals = get(findobj(fig, 'tag', 'lbsubj'), 'value');
valchk = get(findobj(fig, 'tag', 'chk_del'), 'value');
filep = get(findobj(fig, 'tag', 'edit_storedir'), 'string');
strs = get(findobj(fig, 'tag', 'edit_selectdattrials'), 'string');
valpaired = { 'on' 'off' };
if ~strcmpi(des(val).variable(1).label, usrdat.factors{val1})
des(val).variable(1).label = usrdat.factors{val1};
des(val).variable(1).value = usrdat.factorvals{val1}(valf1);
end;
if ~strcmpi(des(val).variable(2).label, usrdat.factors{val2})
des(val).variable(2).label = usrdat.factors{val2};
des(val).variable(2).value = usrdat.factorvals{val2}(valf2);
end;
if ~isequal(mysort(des(val).variable(1).value), mysort(usrdat.factorvals{val1}(valf1)))
des(val).variable(1).value = usrdat.factorvals{val1}(valf1);
end;
if ~isequal(mysort(des(val).variable(2).value), mysort(usrdat.factorvals{val2}(valf2)))
des(val).variable(2).value = usrdat.factorvals{val2}(valf2);
end;
if ~isequal(mysort(des(val).cases.value), mysort(usrdat.subjects(vals)))
des(val).cases.value = usrdat.subjects(vals);
end;
if ~isequal(des(val).variable(1).pairing, valpaired{valp1})
des(val).variable(1).pairing = valpaired{valp1};
end;
if ~isequal(des(val).variable(2).pairing, valpaired{valp2})
des(val).variable(2).pairing = valpaired{valp2};
end;
if ~isequal(des(val).deletepreviousfiles, valchk)
des(val).deletepreviousfiles = 1;
end;
if ~isfield(des, 'filepath') || ~isequal(des(val).filepath, filep)
des(val).filepath = filep;
end;
if ~isequal(des(val).include, strs)
try,
des(val).include = eval( [ '{' strs '}' ]);
catch,
disp('Error while decoding list of parameters');
des(val).include = {};
set(findobj(fig, 'tag', 'edit_selectdattrials'), 'string', '');
end;
end;
case 'selectfact', % select a specific ind. var. (update value listboxes)
factval = designind;
val = get(findobj(fig, 'tag', 'listboxdesign'), 'value');
val1 = get(findobj(fig, 'tag', [ 'lbfact' num2str(factval) ]), 'value');
val2 = get(findobj(fig, 'tag', [ 'lbfact' num2str(~factval) ]), 'value');
% if val1 == val2 && val1 ~= 1
% warndlg2('Cannot select twice the same independent variable');
% val1 = 1;
% set(findobj(fig, 'tag', [ 'lbfact' num2str(factval) ]), 'value', val1);
% end;
valfact = [1:length(usrdat.factorvals{val1})];
set(findobj(fig, 'tag', ['lbval' num2str(factval) ]), 'string', encodevals(usrdat.factorvals{val1}), 'value', valfact, 'listboxtop', 1);
pop_studydesign('updatedesign', fig);
return;
case 'combinevals', % combine values in value listboxes
factval = designind;
val1 = get(findobj(fig, 'tag', [ 'lbfact' num2str(factval) ]), 'value');
vals = get(findobj(fig, 'tag', [ 'lbval' num2str(factval) ]), 'value');
strs = get(findobj(fig, 'tag', [ 'lbval' num2str(factval) ]), 'string');
if length(vals) == 1
warndlg2('You need to select several values to combine them');
return;
end;
if ~iscell(usrdat.factorvals{val1})
warndlg2('Cannot combine values from numerical variables');
return;
end;
% combine values for string and integers
if isstr(usrdat.factorvals{val1}{1}) || iscell(usrdat.factorvals{val1}{1})
tmpcell = {};
for indCell = vals(:)'
if iscell(usrdat.factorvals{val1}{indCell})
tmpcell = { tmpcell{:} usrdat.factorvals{val1}{indCell}{:} };
else
tmpcell = { tmpcell{:} usrdat.factorvals{val1}{indCell} };
end;
end;
usrdat.factorvals{val1}{end+1} = unique_bc(tmpcell);
else
usrdat.factorvals{val1}{end+1} = unique_bc([ usrdat.factorvals{val1}{vals} ]);
end;
set(findobj(fig, 'tag', ['lbval' num2str(factval) ]), 'string', encodevals(usrdat.factorvals{val1}));
case 'selectsubj', % select specific subjects
val = get(findobj(fig, 'tag', 'popupselect'), 'value');
str = get(findobj(fig, 'tag', 'popupselect'), 'string');
str = str{val};
if val == 1,
subjbox = get(findobj(fig, 'tag', 'lbsubj'), 'string');
set(findobj(fig, 'tag', 'lbsubj'), 'value', [1:length(subjbox)]);
return;
end;
indunders = findstr( ' - ', str);
factor = str(1:indunders-1);
factorval = str(indunders+3:end);
% select subjects
eval( [ 'allsetvals = { datinfo.' factor '};' ]);
indset = strmatch(factorval, allsetvals, 'exact');
subjects = unique_bc( { datinfo(indset).subject } );
% change the subject listbox
val = get(findobj(fig, 'tag', 'popupselect'), 'value');
subjbox = get(findobj(fig, 'tag', 'lbsubj'), 'string');
indsubj = [];
for ind = 1:length(subjects);
indsubj(ind) = strmatch(subjects{ind}, subjbox, 'exact');
end;
set(findobj(fig, 'tag', 'lbsubj'), 'value', indsubj);
set(findobj(fig, 'tag', 'popupselect'), 'value', 1);
pop_studydesign('updatedesign', fig);
return;
%set(findobj(get(gcbf, ''userdata''), ''tag'', ''edit_selectdattrials''
case 'selectdatatrials', % select specific dataset and trials
cb_sel = 'pop_studydesign(''selectdatatrialssel'',gcbf);';
cb_add = 'pop_studydesign(''selectdatatrialsadd'',gcbf);';
uilist = { { 'style' 'text' 'string' strvcat('Press ''Add'' to add data', 'selection. Multiple variables', 'are combined using AND.') } ...
{ 'style' 'text' 'string' 'Select data based on variable', 'fontweight' 'bold' } ...
{ 'style' 'listbox' 'string' usrdat.factors 'tag' 'lbfact2' 'callback' cb_sel 'value' 1 } ...
{ 'style' 'text' 'string' 'Select data based on value(s)' 'fontweight' 'bold' } ...
{ 'style' 'listbox' 'string' encodevals(usrdat.factorvals{1}) 'tag' 'lbval2' 'min' 0 'max' 2} };
cb_renamehelp = [ 'set(findobj(gcf, ''tag'', ''help''), ''string'', ''Add'');' ...
'set(findobj(gcf, ''tag'', ''cancel''), ''string'', ''Erase'', ''callback'', ''set(findobj(''''tag'''', ''''edit_selectdattrials''''), ''''string'''', '''''''');'');' ...
'set(findobj(gcf, ''tag'', ''ok''), ''string'', ''Close'');' ];
usrdat.fig = fig;
inputgui('uilist', uilist, 'geometry', { [1] [1] [1] [1] [1] }, 'geomvert', [2 1 2.5 1 2.5], ...
'helpcom', cb_add, 'userdata', usrdat, 'eval', cb_renamehelp);
pop_studydesign('updatedesign', fig);
return;
case 'selectdatatrialssel', % select in the GUI above
val1 = get(findobj(fig, 'tag', 'lbfact2'), 'value');
valfact = [1:length(usrdat.factorvals{val1})];
tmpval = get(findobj(fig, 'tag', 'lbval2'), 'value');
if max(tmpval) > max(valfact)
set(findobj(fig, 'tag', 'lbval2'), 'value', valfact, 'string', encodevals(usrdat.factorvals{val1}));
else
set(findobj(fig, 'tag', 'lbval2'), 'string', encodevals(usrdat.factorvals{val1}), 'value', valfact);
end;
return;
case 'selectfolder',
res = uigetdir;
if ~isempty(findstr(filepath, res)) && findstr(filepath, res) == 1 && ~isequal(filepath, res)
res = res(length(filepath)+2:end);
end;
if res(1) == 0, return; end;
set(findobj(fig, 'tag', 'edit_storedir'), 'string', res);
pop_studydesign('updatedesign', fig);
return;
case 'selectdatatrialsadd', % Add button in the GUI above
val1 = get(findobj(fig, 'tag', 'lbfact2'), 'value');
val2 = get(findobj(fig, 'tag', 'lbval2') , 'value');
objedit = findobj(usrdat.fig, 'tag', 'edit_selectdattrials');
str = get(objedit, 'string');
if ~isempty(str), str = [ str ',' ]; end;
set(objedit, 'string', [ str vararg2str( { usrdat.factors{val1} usrdat.factorvals{val1}(val2) }) ]);
return;
end;
usrdat.design = des;
set(fig, 'userdata', usrdat);
end;
function res = strmatchmult(a, b);
if isempty(b), res = []; return; end;
res = zeros(1,length(a));
for index = 1:length(a)
tmpi = std_indvarmatch(a{index}, b);
res(index) = tmpi(1); % in case there is a duplicate
end;
%[tmp ind] = mysetdiff(b, a);
%res = setdiff_bc([1:length(b)], ind);
function cellarray = mysort(cellarray)
return; % was crashing for combinations of selection
% also there is no reason the order should be different
if ~isempty(cellarray) && isstr(cellarray{1})
cellarray = sort(cellarray);
end;
function [cellout inds ] = mysetdiff(cell1, cell2);
if (~isempty(cell1) && isstr(cell1{1})) || (~isempty(cell2) && isstr(cell2{1}))
[ cellout inds ] = setdiff_bc(cell1, cell2);
else [ cellout inds ] = setdiff_bc([ cell1{:} ], [ cell2{:} ]);
cellout = mattocell(cellout);
end;
% encode string an numerical values for list boxes
function cellout = encodevals(cellin)
if isempty(cellin)
cellout = {};
elseif ~iscell(cellin)
cellout = { num2str(cellin) };
elseif ischar(cellin{1}) || iscell(cellin{1})
for index = 1:length(cellin)
if isstr(cellin{index})
cellout{index} = cellin{index};
else
cellout{index} = cellin{index}{1};
for indcell = 2:length(cellin{index})
cellout{index} = [ cellout{index} ' & ' cellin{index}{indcell} ];
end;
end;
end;
else
for index = 1:length(cellin)
if length(cellin{index}) == 1
cellout{index} = num2str(cellin{index});
else
cellout{index} = num2str(cellin{index}(1));
for indcell = 2:length(cellin{index})
cellout{index} = [ cellout{index} ' & ' num2str(cellin{index}(indcell)) ];
end;
end;
end;
end;
|
github
|
lcnhappe/happe-master
|
std_createclust.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_createclust.m
| 11,296 |
utf_8
|
324e2986c5494686e6ea9fa03913cb90
|
% std_createclust() - dreate a new empty cluster. After creation, components
% may be (re)assigned to it using std_movecomp().
% Usage:
% >> [STUDY] = std_createclust(STUDY, ALLEEG, 'key', val);
% Inputs:
% STUDY - STUDY set comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - vector of EEG datasets included in the STUDY, typically created
% using load_ALLEEG().
%
% Optional inputs:
% 'name' - ['string'] name of the new cluster {default: 'Cls #', where
% '#' is the next available cluster number}
% 'clusterind' - [integer] cluster for each of the component. Ex: 61 components
% and 2 clusters: 'clusterind' will be a 61x1 vector of 1 and
% 2 (and 0=outlisers)
% 'centroid' - centroid for clusters. If 2 clusters, size will be 2 x
% width of the preclustering matrix. This is a deprecated
% functionality.
% 'algorithm' - [cell] algorithm parameters used to obtain the clusters
% 'parentcluster' - ['on'|'off'] use the parent cluster (cluster 1) to
% perform clustering (this cluster contains all the selected
% components by default). Otherwise, the cluster defined in
% STUDY.etc.preclust.clustlevel is used as parent.
%
% Outputs:
% STUDY - the input STUDY set structure modified with the new cluster.
%
% Example:
% >> [STUDY] = std_createclust(STUDY, ALLEEG, 'name', 'eye_movements', ...
% 'clusterind', [0 1 0 1 0 1], 'parentcluster', 'on');
% % Create a new cluster named 'eye_movements' with components 2, 4, and
% % of 6 the default parent cluster defined in
%
% See also pop_clustedit(), std_movecomp()
%
% Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, June, 2005
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, June 07, 2005, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [STUDY] = std_createclust(STUDY, ALLEEG, varargin)
if nargin< 2
help std_createclust;
return;
end;
% decoding options for backward compatibility
% -------------------------------------------
options = {};
if length(varargin) > 0 && ~isstr(varargin{1})
% STUDY, IDX, algorithm, parentClusterNumber
if isnumeric(ALLEEG)
options = { options{:} 'clusterind' ALLEEG };
if nargin > 3, options = { options{:} 'centroid' varargin{1} }; end;
if nargin > 4, options = { options{:} 'algorithm' varargin{2} }; end;
ALLEEG = [];
end;
elseif length(varargin) < 2
options = { options{:} 'name' varargin{1} };
else
options = varargin;
end;
opt = finputcheck(options, { 'name' 'string' [] 'Cls';
'clusterind' 'integer' [] length(STUDY.cluster)+1;
'parentcluster' 'string' { 'on','off' } 'off';
'algorithm' 'cell' [] {};
'ignore0' 'string' { 'on','off' } 'off';
'centroid' 'real' [] [] }, 'std_createclust');
if isstr(opt), error(opt); end;
% opt.clusterind - index of cluster for each component. Ex: 63 components and 2
% clusters: opt.clusterind will be a 61x1 vector of 1 and 2 (and 0=outlisers)
% C - centroid for clusters. If 2 clusters, size will be 2 x
% width of the preclustering matrix
if strcmpi(opt.parentcluster, 'on')
firstind = 1;
cls = 1;
sameica = std_findsameica(ALLEEG);
sets = [];
comps = [];
STUDY.cluster = [];
for index = 1:length(sameica)
newcomps = STUDY.datasetinfo(sameica{index}(1)).comps;
if isempty(newcomps), newcomps = [1:size(ALLEEG(sameica{index}(1)).icaweights,1)]; end;
comps = [ comps newcomps ];
sets(length(sameica{index}):-1:1,end+1:end+length(newcomps)) = repmat( sameica{index}', [1 length(newcomps) ] );
end;
sets(find(sets == 0)) = NaN;
STUDY.cluster(1).name = 'Parentcluster 1';
STUDY.cluster(1).sets = sets;
STUDY.cluster(1).comps = comps;
STUDY.cluster(1).parent = {};
STUDY.cluster(1).child = {};
STUDY.cluster.preclust.preclustparams = [];
STUDY.cluster.preclust.preclustdata = [];
if isfield(STUDY, 'design') && ~isempty(STUDY.design)
STUDY.cluster = std_setcomps2cell(STUDY, 1);
end;
else
% Find the next available cluster index
% -------------------------------------
cls = min(max(opt.clusterind), length(unique(opt.clusterind)));
nc = 0; % index of last cluster
for k = 1:length(STUDY.cluster)
ti = strfind(STUDY.cluster(k).name, ' ');
tmp = STUDY.cluster(k).name(ti(end) + 1:end);
nc = max(nc,str2num(tmp));
% check if there is a cluster of Notclust components
if isfield(STUDY.etc, 'preclust') && isfield(STUDY.etc.preclust, 'preclustparams')
if ~isempty(STUDY.cluster(k).parent)
%strcmp(STUDY.cluster(k).parent,STUDY.cluster(STUDY.etc.preclust.clustlevel).name)
STUDY.cluster(k).preclust.preclustparams = STUDY.etc.preclust.preclustparams;
end;
end
end
len = length(STUDY.cluster);
if ~isempty(find(opt.clusterind==0)) && strcmpi(opt.ignore0, 'off') %outliers exist
firstind = 0;
nc = nc + 1;
len = len + 1;
else
firstind = 1;
end
% create clustlevel if it does not exist
% --------------------------------------
if ~isfield(STUDY.etc, 'preclust')
STUDY.etc.preclust.clustlevel = 1;
STUDY.etc.preclust.preclustdata = [];
elseif ~isfield(STUDY.etc.preclust, 'clustlevel')
STUDY.etc.preclust.clustlevel = 1;
STUDY.etc.preclust.preclustdata = [];
end;
% create all clusters
% -------------------
for k = firstind:cls
% cluster name
% ------------
if k == 0
STUDY.cluster(len).name = [ 'outlier ' num2str(k+nc)];
else STUDY.cluster(k+len).name = [ opt.name ' ' num2str(k+nc)];
end
% find indices
% ------------
tmp = find(opt.clusterind==k); % opt.clust.erind contains the cluster index for each component
STUDY.cluster(k+len).sets = STUDY.cluster(STUDY.etc.preclust.clustlevel).sets(:,tmp);
STUDY.cluster(k+len).comps = STUDY.cluster(STUDY.etc.preclust.clustlevel).comps(tmp);
STUDY.cluster(k+len).algorithm = opt.algorithm;
STUDY.cluster(k+len).parent{end+1} = STUDY.cluster(STUDY.etc.preclust.clustlevel).name;
STUDY.cluster(k+len).child = [];
if ~isempty(STUDY.etc.preclust.preclustdata) && all(tmp <= size(STUDY.etc.preclust.preclustdata,1))
STUDY.cluster(k+len).preclust.preclustdata = STUDY.etc.preclust.preclustdata(tmp,:);
STUDY.cluster(k+len).preclust.preclustparams = STUDY.etc.preclust.preclustparams;
else STUDY.cluster(k+len).preclust.preclustdata = [];
end;
STUDY.cluster(k+len) = std_setcomps2cell(STUDY, k+len);
%update parents clusters with cluster child indices
% -------------------------------------------------
STUDY.cluster(STUDY.etc.preclust.clustlevel).child{end+1} = STUDY.cluster(k+nc).name;
end
end;
% Find out the highst cluster id number (in cluster name), to find
% next available cluster index
% % find max cluster ID
%
% max_id = 0;
% if ~isfield(STUDY, 'cluster'), STUDY.cluster = []; end;
% for k = 1:length(STUDY.cluster)
% ti = strfind(STUDY.cluster(k).name, ' ');
% clus_id = STUDY.cluster(k).name(ti(end) + 1:end);
% max_id = max(max_id, str2num(clus_id));
% end
% max_id = max_id + 1;
% opt.name = sprintf('%s %d', opt.name, max_id);
% clustind = length(STUDY.cluster)+1;
% % Initialize the new cluster fields.
% if length(STUDY.cluster) > 0
% STUDY.cluster(clustind).parent{1} = STUDY.cluster(1).name;
% if ~iscell(STUDY.cluster(1).child)
% STUDY.cluster(1).child = { opt.name };
% else STUDY.cluster(1).child = { STUDY.cluster(1).child{:} opt.name };
% end;
% else
% STUDY.cluster(clustind).parent{1} = 'manual'; % update parent cluster if exists.
% end;
% STUDY.cluster(clustind).name = opt.name;
% STUDY.cluster(clustind).child = [];
% STUDY.cluster(clustind).comps = [];
% STUDY.cluster(clustind).sets = [];
% STUDY.cluster(clustind).algorithm = [];
% STUDY.cluster(clustind).centroid = [];
% STUDY.cluster(clustind).preclust.preclustparams = [];
% STUDY.cluster(clustind).preclust.preclustdata = [];
%
% if (~isempty(opt.datasets) | ~isempty(opt.subjects)) & ~isempty(opt.components)
%
% % convert subjects to dataset indices
% % -----------------------------------
% if ~isempty(opt.subjects)
% if length(opt.subjects) ~= length(opt.components)
% error('If subjects are specified, the length of the cell array must be the same as for the components');
% end;
% alls = { ALLEEG.subject };
% for index = 1:length(opt.subjects)
% tmpinds = strmatch(opt.subjects{index}, alls, 'exact');
% if isempty(tmpinds)
% error('Cannot find subject');
% end;
% opt.datasets(1:length(tmpinds),index) = tmpinds;
% end;
% opt.datasets(opt.datasets(:) == 0) = NaN;
% end;
%
% % deal with cell array inputs
% % ---------------------------
% if iscell(opt.components)
% newcomps = [];
% newdats = [];
% for ind1 = 1:length(opt.components)
% for ind2 = 1:length(opt.components{ind1})
% if iscell(opt.datasets)
% newdats = [ newdats opt.datasets{ind1}' ];
% else newdats = [ newdats opt.datasets(:,ind1) ];
% end;
% newcomps = [ newcomps opt.components{ind1}(ind2) ];
% end;
% end;
% opt.datasets = newdats;
% opt.components = newcomps;
% end;
%
% % create .sets, .comps, .setinds, .allinds fields
% % -----------------------------------------------
% [tmp setinds allinds] = std_setcomps2cell( STUDY, opt.datasets, opt.components);
% STUDY.cluster(clustind).setinds = setinds;
% STUDY.cluster(clustind).allinds = allinds;
% STUDY.cluster(clustind) = std_cell2setcomps( STUDY, ALLEEG, clustind);
% STUDY.cluster(clustind) = std_setcomps2cell( STUDY, clustind);
% %[ STUDY.cluster(finalinds(ind)) setinds allinds ] =
% %std_setcomps2cell(STUDY, finalinds(ind));
% end;
|
github
|
lcnhappe/happe-master
|
std_checkconsist.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_checkconsist.m
| 2,299 |
utf_8
|
e6cbe33ddc8c1fb52b95a02d9bfff1e3
|
% std_checkconsist() - Create channel groups for plotting.
%
% Usage:
% >> boolval = std_checkconsist(STUDY, 'uniform', 'condition');
% >> boolval = std_checkconsist(STUDY, 'uniform', 'group');
% Inputs:
% STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
% 'uniform' - ['condition'|'group'] check if there is one group
% condition per subject
% Outputs:
% boolval - [0|1] 1 if uniform
%
% Authors: Arnaud Delorme, CERCO, 2009
% Copyright (C) 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 [boolval npersubj] = std_checkconsist(STUDY, varargin);
if nargin < 3
help std_checkconsist;
return;
end;
opt = struct(varargin{:});
if strcmpi(opt.uniform, 'condition')
allvals = { STUDY.datasetinfo.condition };
vallist = STUDY.condition;
elseif strcmpi(opt.uniform, 'group')
allvals = { STUDY.datasetinfo.group };
vallist = STUDY.group;
elseif strcmpi(opt.uniform, 'session')
allvals = { STUDY.datasetinfo.session };
allvals = cellfun(@num2str, allvals, 'uniformoutput', false);
vallist = STUDY.session;
if isempty(vallist), boolval = 1; return; end;
vallist = cellfun(@num2str, mattocell(vallist), 'uniformoutput', false);
else
error('unknown option');
end;
if isempty(vallist), boolval = 1; return; end;
for index = 1:length(vallist)
tmplist = strmatch( vallist{index}, allvals, 'exact');
vallen(index) = length(unique( { STUDY.datasetinfo(tmplist).subject } ));
end;
if length(unique(vallen)) == 1
boolval = 1;
else boolval = 0;
end;
|
github
|
lcnhappe/happe-master
|
std_readersp.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_readersp.m
| 27,340 |
utf_8
|
08af4639c7feccd4cfa23d595573b331
|
% std_readersp() - load ERSP measures for data channels or for all
% components of a specified cluster. This function is
% also being used to read ITC and ERPimage data.
% Usage:
% >> [STUDY, erspdata, times, freqs, erspbase] = ...
% std_readersp(STUDY, ALLEEG, varargin);
% Inputs:
% STUDY - studyset structure containing some or all files in ALLEEG
% ALLEEG - vector of loaded EEG datasets
%
% Optional inputs:
% 'design' - [integer] read files from a specific STUDY design. Default
% is empty (use current design in STUDY.currentdesign).
% 'channels' - [cell] list of channels to import {default: none}
% 'clusters' - [integer] list of clusters to import {[]|default: all but
% the parent cluster (1) and any 'NotClust' clusters}
% 'singletrials' - ['on'|'off'] load single trials spectral data (if
% available). Default is 'off'.
% 'forceread' - ['on'|'off'] Force rereading data from disk.
% Default is 'off'.
% 'subject' - [string] select a specific subject {default:all}
% 'component' - [integer] select a specific component in a cluster
% {default:all}
% 'datatype' - {'ersp'|'itc'|'erpim'} This function is used to read all
% 2-D STUDY matrices stored on disk (not only ERSP). It may
% read ERSP ('ersp' option), ITC ('itc' option) or ERPimage
% data ('erpim' option).
%
% ERSP specific options:
% 'timerange' - [min max] time range {default: whole measure range}
% 'freqrange' - [min max] frequency range {default: whole measure range}
% 'subbaseline' - ['on'|'off'] subtract the ERSP baseline for paired
% conditions. The conditions for which baseline is removed
% are indicated on the command line. See help
% std_studydesign for more information about paired and
% unpaired variables.
%
% ERPimage specific option:
% This function is used to read all 2-D STUDY matrices stored on disk
% (this includes ERPimages). It therefore takes as input specific
% ERPimage options. Note that the 'singletrials' optional input is
% irrelevant for ERPimages (which are always stored as single trials).
% 'concatenate' - ['on'|'off'] read concatenated ERPimage data ('on') or
% stacked ERPimage data. See help std_erpimage for more
% information.
% 'timerange' - [min max] time range {default: whole measure range}
% 'trialrange' - [min max] read only a specific range of the ERPimage
% output trials {default: whole measure range}
% Output:
% STUDY - updated studyset structure
% erspdata - [cell array] ERSP data (the cell array size is
% condition x groups). This may also be ITC data or ERPimage
% data (see above).
% times - [float array] array of time points
% freqs - [float array] array of frequencies. For ERPimage this
% contains trial indices.
% erspbase - [cell array] baseline values
% events - [cell array] events (ERPimage only).
%
% Author: Arnaud Delorme, CERCO, 2006-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [STUDY, erspdata, alltimes, allfreqs, erspbase, events, unitPower] = std_readersp(STUDY, ALLEEG, varargin)
if nargin < 2
help std_readersp;
return;
end
events = {};
unitPower = 'dB';
if ~isstruct(ALLEEG) % old calling format
dataset = ALLEEG;
EEG = STUDY(dataset);
comp = varargin{1};
if length(varargin) > 1, timelim = varargin{2}; else timelim = []; end;
if length(varargin) > 2, freqlim = varargin{3}; else freqlim = []; end;
filebase = fullfile(EEG.filepath, EEG.filename(1:end-4));
if comp < 0
error('Old format function call, channel reading not supported');
[ersp params alltimes allfreqs] = std_readfile(filebase, 'channels', -comp, 'timelimits', timelim, 'freqlimits', freqlim);
else
[ersp params alltimes allfreqs] = std_readfile(filebase, 'components', comp, 'timelimits', timelim, 'freqlimits', freqlim, 'measure', 'ersp');
[erspbase params alltimes allfreqs] = std_readfile(filebase, 'components', comp, 'timelimits', timelim, 'freqlimits', freqlim, 'measure', 'erspbase');
end;
STUDY = ersp;
erspdata = allfreqs;
allfreqs = params;
return;
end;
STUDY = pop_erspparams( STUDY, 'default');
STUDY = pop_erpimparams(STUDY, 'default');
[opt moreopts] = finputcheck( varargin, { ...
'design' 'integer' [] STUDY.currentdesign;
'channels' 'cell' [] {};
'clusters' 'integer' [] [];
'trialrange' 'real' [] STUDY.etc.erpimparams.trialrange;
'freqrange' 'real' [] STUDY.etc.erspparams.freqrange;
'timerange' 'real' [] NaN;
'singletrials' 'string' { 'on','off' } 'off';
'forceread' 'string' { 'on','off' } 'off';
'concatenate' 'string' { 'on','off' } STUDY.etc.erpimparams.concatenate;
'subbaseline' 'string' { 'on','off' } STUDY.etc.erspparams.subbaseline;
'component' 'integer' [] [];
'infotype' 'string' { 'ersp','itc','erpim' } 'ersp'; ... % deprecated
'datatype' 'string' { 'ersp','itc','erpim' } 'ersp'; ...
'subject' 'string' [] '' }, ...
'std_readersp', 'ignore');
if isstr(opt), error(opt); end;
if ~strcmpi(opt.infotype, 'ersp'), opt.datatype = opt.infotype; end;
if strcmpi(opt.datatype, 'erpim'), if isnan(opt.timerange), opt.timerange = STUDY.etc.erpimparams.timerange; end;
opt.freqrange = opt.trialrange;
ordinate = 'trials';
else if isnan(opt.timerange) opt.timerange = STUDY.etc.erspparams.timerange; end;
ordinate = 'freqs';
end;
nc = max(length(STUDY.design(opt.design).variable(1).value),1);
ng = max(length(STUDY.design(opt.design).variable(2).value),1);
paired1 = STUDY.design(opt.design).variable(1).pairing;
paired2 = STUDY.design(opt.design).variable(2).pairing;
dtype = opt.datatype;
% find channel indices
% --------------------
if ~isempty(opt.channels)
allChangrp = lower({ STUDY.changrp.name });
finalinds = std_chaninds(STUDY, opt.channels);
else finalinds = opt.clusters;
end;
for ind = 1:length(finalinds)
erspbase = cell( nc, ng );
% find indices
% ------------
if ~isempty(opt.channels)
tmpstruct = STUDY.changrp(finalinds(ind));
allinds = tmpstruct.allinds;
setinds = tmpstruct.setinds;
else
tmpstruct = STUDY.cluster(finalinds(ind));
allinds = tmpstruct.allinds;
setinds = tmpstruct.setinds;
end;
% check if data is already here
% -----------------------------
if strcmpi(dtype, 'erpim') % ERP images
dataread = 0;
eqtf = isequal( STUDY.etc.erpimparams.timerange , opt.timerange) && ...
isequal( STUDY.etc.erpimparams.trialrange, opt.trialrange);
if isfield(tmpstruct, 'erpimdata') && eqtf && ~isempty(tmpstruct.erpimdata)
dataread = 1;
end;
else
dataread = 0;
eqtf = isequal( STUDY.etc.erspparams.timerange, opt.timerange) && ...
isequal( STUDY.etc.erspparams.freqrange, opt.freqrange);
eqtfb = isequal( STUDY.etc.erspparams.subbaseline, opt.subbaseline) && eqtf;
if strcmpi(opt.singletrials,'off')
if isfield(tmpstruct, [ dtype 'data']) && eqtfb && ~isempty(getfield(tmpstruct, [ dtype 'data']))
dataread = 1;
end;
else
if isfield(tmpstruct, [ dtype 'datatrials']) && eqtf && ~isempty(getfield(tmpstruct, [ dtype 'datatrials']))
if ~isempty(opt.channels) && strcmpi(getfield(tmpstruct, [ dtype 'trialinfo' ]), opt.subject)
dataread = 1;
elseif isempty(opt.channels) && isequal(getfield(tmpstruct, [ dtype 'trialinfo' ]), opt.component)
dataread = 1;
end;
end;
end;
end;
if dataread && strcmpi(opt.forceread, 'off')
disp('Using pre-loaded data. To force rereading data from disk use the ''forceread'' flag');
else
if strcmpi(dtype, 'erpim') % ERP images
if strcmpi(opt.singletrials, 'on')
error( [ 'Single trial loading option not supported with STUDY ERP-image' 10 '(there is no such thing as a single-trial ERPimage)' ]);
end;
% read the data and select channels
% ---------------------------------
setinfo = STUDY.design(opt.design).cell;
erpim = cell( nc, ng );
events = cell( nc, ng );
for c = 1:nc
for g = 1:ng
if ~isempty(setinds{c,g})
if ~isempty(opt.channels), opts = { 'channels', allChangrp(allinds{c,g}(:)), 'timelimits', opt.timerange, 'triallimits', opt.trialrange, 'concatenate', opt.concatenate };
else opts = { 'components', allinds{c,g}(:), 'timelimits', opt.timerange, 'triallimits', opt.trialrange, 'concatenate', opt.concatenate };
end;
[erpim{c, g} tmpparams alltimes alltrials events{c,g}] = std_readfile( setinfo(setinds{c,g}(:)), 'measure', 'erpim', opts{:});
fprintf('.');
end;
end;
end;
if strcmpi(opt.concatenate, 'on'), alltrials = []; end;
fprintf('\n');
ersp = erpim;
allfreqs = alltrials;
else % ERSP/ITC
% reserve arrays
% --------------
events = {};
ersp = cell( nc, ng );
erspinds = cell( nc, ng );
% find total nb of trials
% THIS CODE IS NOT NECESSARY ANY MORE (SEE BUG 1170)
% -----------------------
%setinfo = STUDY.design(opt.design).cell;
%tottrials = cell( nc, ng );
%if strcmpi(opt.singletrials, 'on')
% for indSet = 1:length(setinfo)
% condind = std_indvarmatch( setinfo(indSet).value{1}, STUDY.design(opt.design).variable(1).value );
% grpind = std_indvarmatch( setinfo(indSet).value{2}, STUDY.design(opt.design).variable(2).value );
% if isempty(tottrials{condind, grpind}), tottrials{condind, grpind} = sum(cellfun(@length, setinfo(indSet).trials));
% else tottrials{condind, grpind} = tottrials{condind, grpind} + sum(cellfun(@length, setinfo(indSet).trials));
% end;
% end;
%end;
% read the data and select channels
% ---------------------------------
fprintf('Reading all %s data:', upper(dtype));
setinfo = STUDY.design(opt.design).cell;
if strcmpi(opt.singletrials, 'on')
for c = 1:nc
for g = 1:ng
if ~isempty(opt.channels)
allsubjects = { STUDY.design(opt.design).cell.case };
if ~isempty(opt.subject), inds = strmatch( opt.subject, allsubjects(setinds{c,g}));
else inds = 1:length(allinds{c,g}); end;
else
if ~isempty(opt.component) inds = find( allinds{c,g} == STUDY.cluster(finalinds(ind)).comps(opt.component));
else inds = 1:length(allinds{c,g}); end;
end;
if ~isempty(inds)
count{c, g} = 1;
for indtmp = 1:length(inds)
setindtmp = STUDY.design(opt.design).cell(setinds{c,g}(inds(indtmp)));
tmpopts = { 'measure', 'timef' 'timelimits', opt.timerange, 'freqlimits', opt.freqrange };
if ~isempty(opt.channels), [ tmpersp tmpparams alltimes allfreqs] = std_readfile(setindtmp, 'channels', allChangrp(allinds{c,g}(inds(indtmp))), tmpopts{:});
else [ tmpersp tmpparams alltimes allfreqs] = std_readfile(setindtmp, 'components', allinds{c,g}(inds(indtmp)), tmpopts{:});
end;
indices = [count{c, g}:count{c, g}+size(tmpersp,3)-1];
if indtmp == 1
ersp{c, g} = permute(tmpersp, [2 1 3]);
else ersp{c, g}(:,:,indices) = permute(tmpersp, [2 1 3]);
end;
erspinds{c, g}(1:2,indtmp) = [ count{c, g} count{c, g}+size(tmpersp,3)-1 ];
count{c, g} = count{c, g}+size(tmpersp,3);
if size(tmpersp,3) ~= sum(cellfun(@length, setindtmp.trials))
error( sprintf('Wrong number of trials in datafile for design index %d\n', setinds{c,g}(inds(indtmp))));
end;
end;
end;
end;
end;
else
for c = 1:nc
for g = 1:ng
if ~isempty(setinds{c,g})
if ~isempty(opt.channels), opts = { 'channels', allChangrp(allinds{c,g}(:)), 'timelimits', opt.timerange, 'freqlimits', opt.freqrange };
else opts = { 'components', allinds{c,g}(:) , 'timelimits', opt.timerange, 'freqlimits', opt.freqrange };
end;
if strcmpi(dtype, 'ersp')
erspbase{c, g} = std_readfile( setinfo(setinds{c,g}(:)), 'measure', 'erspbase', opts{:});
[ ersp{c, g} tmpparams alltimes allfreqs ] = std_readfile( setinfo(setinds{c,g}(:)), 'measure', 'ersp' , opts{:});
else [ ersp{c, g} tmpparams alltimes allfreqs ] = std_readfile( setinfo(setinds{c,g}(:)), 'measure', 'itc' , opts{:});
ersp{c, g} = ersp{c, g};
end;
fprintf('.');
%ersp{c, g} = permute(ersp{c, g} , [3 2 1]);
%erspbase{c, g} = 10*log(permute(erspbase{c, g}, [3 2 1]));
end;
end;
end;
end;
fprintf('\n');
% compute ERSP or ITC if trial mode
% (since only the timef have been loaded)
% ---------------------------------------
if strcmpi(opt.singletrials, 'on')
tmpparams2 = fieldnames(tmpparams); tmpparams2 = tmpparams2';
tmpparams2(2,:) = struct2cell(tmpparams);
precomp.times = alltimes;
precomp.freqs = allfreqs;
precomp.recompute = dtype;
for c = 1:nc
for g = 1:ng
if ~isempty(ersp{c,g})
precomp.tfdata = permute(ersp{c,g}, [2 1 3]);
if strcmpi(dtype, 'itc')
[tmp ersp{c,g}] = newtimef(zeros(ALLEEG(1).pnts,2), ALLEEG(1).pnts, [ALLEEG(1).xmin ALLEEG(1).xmax]*1000, ...
ALLEEG(1).srate, [], tmpparams2{:}, 'precomputed', precomp, 'verbose', 'off');
elseif strcmpi(dtype, 'ersp')
[ersp{c,g} tmp] = newtimef(zeros(ALLEEG(1).pnts,2), ALLEEG(1).pnts, [ALLEEG(1).xmin ALLEEG(1).xmax]*1000, ...
ALLEEG(1).srate, [], tmpparams2{:}, 'precomputed', precomp, 'verbose', 'off');
end;
ersp{c,g} = permute(ersp{c,g}, [2 1 3]);
end;
end;
end;
end;
% compute average baseline across groups and conditions
% -----------------------------------------------------
if strcmpi(opt.subbaseline, 'on') && strcmpi(dtype, 'ersp')
if strcmpi(opt.singletrials, 'on')
disp('WARNING: no ERSP baseline may not be subtracted when using single trials');
else
disp('Recomputing baseline...');
if strcmpi(paired1, 'on') && strcmpi(paired2, 'on')
disp('Removing ERSP baseline for both indep. variables');
meanpowbase = computeerspbaseline(erspbase(:), opt.singletrials);
ersp = removeerspbaseline(ersp, erspbase, meanpowbase);
elseif strcmpi(paired1, 'on')
disp('Removing ERSP baseline for first indep. variables (second indep. var. is unpaired)');
for g = 1:ng % ng = number of groups
meanpowbase = computeerspbaseline(erspbase(:,g), opt.singletrials);
ersp(:,g) = removeerspbaseline(ersp(:,g), erspbase(:,g), meanpowbase);
end;
elseif strcmpi(paired2, 'on')
disp('Removing ERSP baseline for second indep. variables (first indep. var. is unpaired)');
for c = 1:nc % ng = number of groups
meanpowbase = computeerspbaseline(erspbase(c,:), opt.singletrials);
ersp(c,:) = removeerspbaseline(ersp(c,:), erspbase(c,:), meanpowbase);
end;
else
disp('Not removing ERSP baseline (both indep. variables are unpaired');
end;
end;
end;
end;
% if strcmpi(opt.statmode, 'common')
% % collapse the two last dimensions before computing significance
% % i.e. 18 subject with 4 channels -> same as 4*18 subjects
% % --------------------------------------------------------------
% disp('Using all channels for statistics...');
% for c = 1:nc
% for g = 1:ng
% ersp{c,g} = reshape( ersp{c,g}, size(ersp{c,g},1), size(ersp{c,g},2), size(ersp{c,g},3)*size(ersp{c,g},4));
% end;
% end;
% end;
% copy data to structure
% ----------------------
if ~isempty(events)
tmpstruct = setfield(tmpstruct, [ dtype 'events' ], events);
end;
tmpstruct = setfield(tmpstruct, [ dtype ordinate ], allfreqs);
tmpstruct = setfield(tmpstruct, [ dtype 'times' ], alltimes);
if strcmpi(opt.singletrials, 'on')
tmpstruct = setfield(tmpstruct, [ dtype 'datatrials' ], ersp);
tmpstruct = setfield(tmpstruct, [ dtype 'subjinds' ], erspinds);
tmpstruct = setfield(tmpstruct, [ dtype 'times' ], alltimes);
if ~isempty(opt.channels)
tmpstruct = setfield(tmpstruct, [ dtype 'trialinfo' ], opt.subject);
else tmpstruct = setfield(tmpstruct, [ dtype 'trialinfo' ], opt.component);
end;
else
tmpstruct = setfield(tmpstruct, [ dtype 'data' ], ersp);
if strcmpi(dtype, 'ersp')
tmpstruct = setfield(tmpstruct, [ dtype 'base' ], erspbase);
end;
end;
% copy results to structure
% -------------------------
fields = { [ dtype 'data' ] [ dtype 'events' ] [ dtype ordinate ] [ dtype 'datatrials' ] ...
[ dtype 'subjinds' ] [ dtype 'base' ] [ dtype 'times' ] [ dtype 'trialinfo' ] 'allinds' 'setinds' };
for f = 1:length(fields)
if isfield(tmpstruct, fields{f}),
tmpdata = getfield(tmpstruct, fields{f});
if ~isempty(opt.channels)
STUDY.changrp = setfield(STUDY.changrp, { finalinds(ind) }, fields{f}, tmpdata);
else STUDY.cluster = setfield(STUDY.cluster, { finalinds(ind) }, fields{f}, tmpdata);
end;
end;
end;
end;
end;
% output units
% -----------
if exist('tmpparams') ~= 1
tmpparams = []; ctmp = 1;
while isempty(tmpparams) && ctmp <= length(STUDY.design(opt.design).cell)
try
if ~isempty(opt.channels), [tmpersp tmpparams] = std_readfile(STUDY.design(opt.design).cell(ctmp), 'channels', {STUDY.changrp(1).name}, 'measure', opt.datatype);
else [tmpersp tmpparams] = std_readfile(STUDY.design(opt.design).cell(ctmp), 'components', STUDY.cluster(finalinds(end)).allinds{1,1}(1), 'measure', opt.datatype);
end;
catch
end
ctmp = ctmp + 1;
end
end;
if ~isfield(tmpparams, 'baseline'), tmpparams.baseline = 0; end;
if ~isfield(tmpparams, 'scale' ), tmpparams.scale = 'log'; end;
if ~isfield(tmpparams, 'basenorm'), tmpparams.basenorm = 'off'; end;
if strcmpi(tmpparams.scale, 'log')
if strcmpi(tmpparams.basenorm, 'on')
unitPower = '10*log(std.)'; % impossible
elseif isnan(tmpparams.baseline)
unitPower = '10*log10(\muV^{2}/Hz)';
else
unitPower = 'dB';
end;
else
if strcmpi(tmpparams.basenorm, 'on')
unitPower = 'std.';
elseif isnan(tmpparams.baseline)
unitPower = '\muV^{2}/Hz';
else
unitPower = '% of baseline';
end;
end;
% return structure
% ----------------
if nargout <2
return
end
allinds = finalinds;
if ~isempty(opt.channels)
structdat = STUDY.changrp;
erspdata = cell(nc, ng);
events = {};
for ind = 1:length(erspdata(:))
if strcmpi(opt.singletrials, 'on')
tmpdat = getfield(structdat(allinds(1)), [ dtype 'datatrials' ]);
else tmpdat = getfield(structdat(allinds(1)), [ dtype 'data' ]);
end;
if ndims(tmpdat{ind}) == 2, erspdata{ind} = zeros([ size(tmpdat{ind}) 1 length(allinds)]);
else erspdata{ind} = zeros([ size(tmpdat{ind}) length(allinds)]);
end;
for index = 1:length(allinds)
if strcmpi(opt.singletrials, 'on')
tmpdat = getfield(structdat(allinds(index)), [ dtype 'datatrials' ]);
else tmpdat = getfield(structdat(allinds(index)), [ dtype 'data' ]);
end;
erspdata{ind}(:,:,:,index) = tmpdat{ind};
allfreqs = getfield(structdat(allinds(index)), [ dtype ordinate ]);
alltimes = getfield(structdat(allinds(index)), [ dtype 'times' ]);
if isfield(structdat, [ dtype 'events' ])
events = getfield(structdat(allinds(index)), [ dtype 'events' ]);
end;
compinds = structdat(allinds(index)).allinds;
setinds = structdat(allinds(index)).setinds;
end;
erspdata{ind} = permute(erspdata{ind}, [1 2 4 3]); % time freqs elec subjects
end;
if ~isempty(opt.subject) && strcmpi(opt.singletrials,'off')
erspdata = std_selsubject(erspdata, opt.subject, setinds, { STUDY.design(opt.design).cell.case }, 2);
end;
else
if strcmpi(opt.singletrials, 'on')
erspdata = getfield(STUDY.cluster(allinds(1)), [ dtype 'datatrials' ]);
else erspdata = getfield(STUDY.cluster(allinds(1)), [ dtype 'data' ]);
end;
allfreqs = getfield(STUDY.cluster(allinds(1)), [ dtype ordinate ]);
alltimes = getfield(STUDY.cluster(allinds(1)), [ dtype 'times' ]);
if isfield(STUDY.cluster, [ dtype 'events' ])
events = getfield(STUDY.cluster(allinds(1)), [ dtype 'events' ]);
end;
compinds = STUDY.cluster(allinds(1)).allinds;
setinds = STUDY.cluster(allinds(1)).setinds;
if ~isempty(opt.component) && length(allinds) == 1 && strcmpi(opt.singletrials,'off')
erspdata = std_selcomp(STUDY, erspdata, allinds, setinds, compinds, opt.component);
end;
end;
% compute ERSP baseline
% ---------------------
function meanpowbase = computeerspbaseline(erspbase, singletrials)
try
len = length(erspbase(:));
count = 0;
for index = 1:len
if ~isempty(erspbase{index})
if strcmpi(singletrials, 'on')
if count == 0, meanpowbase = mean(erspbase{index},3);
else meanpowbase = meanpowbase + mean(erspbase{index},3);
end;
else
if count == 0, meanpowbase = erspbase{index};
else meanpowbase = meanpowbase + erspbase{index};
end;
end;
count = count+1;
end;
end;
meanpowbase = reshape(meanpowbase , [size(meanpowbase,1) 1 size(meanpowbase,2)])/count;
catch,
error([ 'Problem while subtracting common ERSP baseline.' 10 ...
'Common baseline subtraction is performed based on' 10 ...
'pairing settings in your design. Most likelly, one' 10 ...
'independent variable should not have its data paired.' ]);
end;
% remove ERSP baseline
% ---------------------
function ersp = removeerspbaseline(ersp, erspbase, meanpowbase)
convert2log = 0;
for g = 1:size(ersp,2) % ng = number of groups
for c = 1:size(ersp,1)
if ~isempty(erspbase{c,g}) && ~isempty(ersp{c,g})
erspbasetmp = reshape(erspbase{c,g}, [size(meanpowbase,1) 1 size(meanpowbase,3)]);
if any(erspbasetmp(:) > 1000)
convert2log = 1;
end;
tmpmeanpowbase = repmat(meanpowbase, [1 size(ersp{c,g},2) 1]);
if convert2log
ersp{c,g} = ersp{c,g} - repmat(10*log10(erspbasetmp), [1 size(ersp{c,g},2) 1 1]) + 10*log10(tmpmeanpowbase);
else ersp{c,g} = ersp{c,g} - repmat(erspbasetmp, [1 size(ersp{c,g},2) 1 1]) + tmpmeanpowbase;
end;
end;
end;
end;
|
github
|
lcnhappe/happe-master
|
std_moveoutlier.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_moveoutlier.m
| 3,042 |
utf_8
|
d3911bba9d7caea1be8f3002aac0e6aa
|
% std_moveoutlier() - Commandline function, to reassign specified outlier component(s)
% from a cluster to its outlier cluster.
% Usage:
% >> STUDY = std_moveoutlier(STUDY, ALLEEG, from_cluster, comps);
% Inputs:
% STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - global EEGLAB vector of EEG structures for the dataset(s) included in the STUDY.
% ALLEEG for a STUDY set is typically created using load_ALLEEG().
% from_cluster - cluster number, the cluster outlier components are moved from.
% comps - [numeric vector] component indices in the from_cluster to move.
%
% Outputs:
% STUDY - the input STUDY set structure modified with the components reassignment.
%
% Example:
% >> from_cluster = 10; comps = [2 7];
% >> STUDY = std_movecomp(STUDY,ALLEEG, from_cluster, to_cluster, comps);
% Components 2 and 7 of cluster 10 are moved to the its outlier cluster ('Outliers Cls 10').
%
% See also pop_clustedit
%
% Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, June, 2005
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, June 07, 2005, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function STUDY = std_moveoutlier(STUDY, ALLEEG, old_clus, comps)
% Cannot move components if the cluster is either a 'Notclust' or
% 'Outliers' cluster
if strncmpi('Notclust',STUDY.cluster(old_clus).name,8) | strncmpi('Outliers',STUDY.cluster(old_clus).name,8)
warndlg2('std_moveoutlier: cannot move components from Notclust or Outliers cluster');
return;
end
% Cannot move components if clusters have children clusters
if ~isempty(STUDY.cluster(old_clus).child)
warndlg2('Cannot move components if cluster has children clusters!' , 'Aborting remove outliers');
return;
end
outlier_clust = std_findoutlierclust(STUDY,old_clus); %find the outlier cluster for this cluster
if outlier_clust == 0 %no such cluster exist
STUDY = std_createclust(STUDY, ALLEEG, ['Outliers ' STUDY.cluster(old_clus).name]); %create an outlier cluster
outlier_clust = length(STUDY.cluster);
end
%move the compnents to the outliers cluster
STUDY = std_movecomp(STUDY, ALLEEG, old_clus, outlier_clust, comps);
|
github
|
lcnhappe/happe-master
|
pop_savestudy.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/pop_savestudy.m
| 4,821 |
utf_8
|
fa0293fa03f7350151ab08e951c9bee4
|
% pop_savestudy() - save a STUDY structure to a disk file
%
% Usage:
% >> STUDY = pop_savestudy( STUDY, EEG ); % pop up and interactive window
% >> STUDY = pop_savestudy( STUDY, EEG, 'key', 'val', ...); % no pop-up
%
% Inputs:
% STUDY - STUDY structure.
% EEG - Array of datasets contained in the study.
%
% Optional inputs:
% 'filename' - [string] name of the STUDY file {default: STUDY.filename}
% 'filepath' - [string] path of the STUDY file {default: STUDY.filepath}
% 'savemode' - ['resave'|'standard'] in resave mode, the file name in
% the study is being used to resave it.
%
% Note: the parameter EEG is currenlty not being used. In the future, this function
% will check if any of the datasets of the study have been modified and
% have to be resaved.
%
% Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, September 2005
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, Spetember 2005, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [STUDY, EEG, com] = pop_savestudy(STUDY, EEG, varargin);
com = '';
if nargin < 1
help pop_savestudy;
return;
end;
if isempty(STUDY) , error('pop_savestudy(): cannot save empty STUDY'); end;
if length(STUDY) >1, error('pop_savestudy(): cannot save multiple STUDY sets'); end;
% backward compatibility
% ----------------------
if nargin > 1
if isstr(EEG)
options = { EEG varargin{:} };
else
options = varargin;
end;
end;
if nargin < 3
% pop up window to ask for file type
% ----------------------------------
[filename, filepath] = uiputfile2('*.study', ...
'Save STUDY with .study extension -- pop_savestudy()');
if isequal(filename,0), return; end;
if ~strncmp(filename(end-5:end), '.study',6)
if isempty(strfind(filename,'.'))
filename = [filename '.study'];
else
filename = [filename(1:strfind(filename,'.')-1) '.study'];
end
end
options = { 'filename' filename 'filepath' filepath };
end
% decoding parameters
% -------------------
g = finputcheck(options, { 'filename' 'string' [] STUDY.filename;
'filepath' 'string' [] STUDY.filepath;
'savemode' 'string' { 'standard','resave' } 'standard' });
if isstr(g), error(g); end;
% fields to remove
% ----------------
fields = { 'erptimes' 'erpdata' ...
'specfreqs' 'specdata' ...
'erspdata' 'ersptimes' 'erspfreqs' 'erspdatatrials' 'erspsubjinds' 'erspbase' 'ersptrialinfo' ...
'itcdata' 'itcfreqs' 'itctimes' ...
'erpimdata' 'erpimevents' 'erpimtrials' 'erpimtimes' };
for fInd = 1:length(fields)
if isfield(STUDY.changrp, fields{fInd})
STUDY.changrp = rmfield(STUDY.changrp, fields{fInd});
end;
if isfield(STUDY.changrp, fields{fInd})
STUDY.cluster = rmfield(STUDY.cluster, fields{fInd});
end;
end;
% resave mode
% -----------
STUDY.saved = 'yes';
if strcmpi(g.savemode, 'resave')
disp('Re-saving study file');
g.filename = STUDY.filename;
g.filepath = STUDY.filepath;
end;
if isempty(g.filename)
disp('pop_savestudy(): no STUDY filename: make sure the STUDY has a filename');
return;
end
if ~strncmp(g.filename(end-5:end), '.study',6)
if isempty(strfind(g.filename,'.'))
g.filename = [g.filename '.study'];
else
g.filename = [g.filename(1:strfind(g.filename,'.')-1) '.study'];
end
end
% [filepath filenamenoext ext] = fileparts(varargin{1});
% filename = [filenamenoext '.study']; % make sure a .study extension
STUDY.filepath = g.filepath;
STUDY.filename = g.filename;
STUDYfile = fullfile(STUDY.filepath,STUDY.filename);
STUDYTMP = STUDY;
STUDY = std_rmalldatafields(STUDY);
eeglab_options;
if option_saveversion6, save('-v6' , STUDYfile, 'STUDY');
else save('-v7.3' , STUDYfile, 'STUDY');
end;
STUDY = STUDYTMP;
% history
% -------
com = sprintf('[STUDY EEG] = pop_savestudy( %s, %s, %s);', inputname(1), inputname(2), vararg2str(options));
|
github
|
lcnhappe/happe-master
|
pop_chanplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/pop_chanplot.m
| 27,582 |
utf_8
|
dcfb38346565d3ab979d9dbbfb4adfc1
|
% pop_chanplot() - graphic user interface (GUI)-based function with plotting
% options for visualizing. Only channel measures (e.g., spectra,
% ERPs, ERSPs, ITCs) that have been computed and saved in the study EEG
% datasets can be visualized. These can be computed using the GUI-based
% pop_precomp().
% Usage:
% >> STUDY = pop_chanplot(STUDY, ALLEEG);
% Inputs:
% ALLEEG - Top-level EEGLAB vector of loaded EEG structures for the dataset(s)
% in the STUDY. ALLEEG for a STUDY set is typically loaded using
% pop_loadstudy(), or in creating a new STUDY, using pop_createstudy().
% STUDY - EEGLAB STUDY set comprising some or all of the EEG
% datasets in ALLEEG.
%
% Outputs:
% STUDY - The input STUDY set structure modified according to specified user edits,
% if any. Plotted channel measure means (maps, ERSPs, etc.) are added to
% the STUDY structure after they are first plotted to allow quick replotting.
%
% Graphic interface buttons:
% "Select channel to plot" - [list box] Displays available channels to plot (format is
% 'channel name (number of channels)'). The presented channels depend s
% on the optional input variable 'channels'. Selecting (clicking on) a
% channel from the list will display the selected channel channels in the
% "Select channel(s) to plot" list box. Use the plotting buttons below
% to plot selected measures of the selected channel.
% "Select channel(s) to plot" - [list box] Displays the ICA channels of the currently
% selected channel (in the "Select channel to plot" list box). Each channel
% has the format: 'subject name, channel index'.
% "Plot channel properties" - [button] Displays in one figure all the mean channel measures
% (e.g., dipole locations, scalp maps, spectra, etc.) that were calculated
% and saved in the EEG datsets. If there is more than one condition, the ERP
% and the spectrum will have different colors for each condition. The ERSP
% and ITC plots will show only the first condition; clicking on the subplot
% will open a new figure with the different conditions displayed together.
% Uses the command line function std_propplot().
% "Plot ERSPs" - [button] Displays the channel channel ERSPs.
% If applied to a channel, channel ERSPs are plotted in one figure
% (per condition) with the channel mean ERSP. If "All # channel centroids"
% option is selected, plots all average ERSPs of the channels in one figure
% per condition. If applied to channels, display the ERSP images of specified
% channel channels in separate figures, using one figure for all conditions.
% Uses the command line functions std_erspplot().
% "Plot ITCs" - [button] Same as "Plot ERSPs" but with ITC.
% Uses the command line functions std_itcplot().
% "Plot spectra" - [button] Displays the channel channel spectra.
% If applied to a channel, displays channel spectra plus the average channel
% spectrum in bold. For a specific channel, displays the channel channel
% spectra plus the average channel spectrum (in bold) in one figure per condition.
% If the "All # channel centroids" option is selected, displays the average
% spectrum of all channels in the same figure, with spectrum for different
% conditions (if any) plotted in different colors.
% If applied to channels, displays the spectrum of specified channel
% channels in separate figures using one figure for all conditions.
% Uses the command line functions std_specplot().
% "Plot ERPs" - [button] Same as "Plot spectra" but for ERPs.
% Uses the command line functions std_erpplot().
% "Plot ERPimage" - [button] Same as "Plot ERP" but for ERPimave.
% Uses the command line functions std_erpimplot().
%
% Authors: Arnaud Delorme, Scott Makeig, SCCN/INC/UCSD, October 11, 2004
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 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
% Coding notes: Useful information on functions and global variables used.
function [STUDY, com] = pop_chanplot(varargin)
icadefs;
com = [];
if ~isstr(varargin{1})
if nargin < 2
error('pop_chanplot(): You must provide ALLEEG and STUDY structures');
end
STUDY = varargin{1};
STUDY.etc.erpparams.topotime = []; % [] for channels and NaN for components
STUDY.etc.specparams.topofreq = []; % NaN -> GUI disabled
STUDY.etc.erspparams.topotime = [];
STUDY.etc.erspparams.topofreq = [];
STUDY.etc.erpimparams.topotime = [];
STUDY.etc.erpimparams.topotrial = [];
% test path
% ---------
pathwarn = 'off';
if ~strcmpi(pwd, STUDY.filepath) && ~strcmpi(pwd, STUDY.filepath(1:end-1))
if length(STUDY.datasetinfo(1).filepath) < 1
pathwarn = 'on';
elseif STUDY.datasetinfo(1).filepath(1) == '.'
pathwarn = 'on';
end;
end;
if strcmpi(pathwarn, 'on')
warndlg2(strvcat('You have changed your working path and data files are', ...
'no longer available; Cancel, and go back to your STUDY folder'), 'warning');
end;
STUDY.tmphist = '';
ALLEEG = varargin{2};
if ~isfield(STUDY, 'changrp')
STUDY = std_changroup(STUDY, ALLEEG);
disp('Warning: history not saved for group creation');
elseif isempty(STUDY.changrp)
STUDY = std_changroup(STUDY, ALLEEG);
disp('Warning: history not saved for group creation');
end;
show_chan = ['pop_chanplot(''showchan'',gcf);'];
show_onechan = ['pop_chanplot(''showchanlist'',gcf);'];
plot_chan_maps = ['pop_chanplot(''topoplot'',gcf); '];
plot_onechan_maps = ['pop_chanplot(''plotchantopo'',gcf); '];
plot_chan_ersps = ['pop_chanplot(''erspplot'',gcf); '];
plot_onechan_ersps = ['pop_chanplot(''plotchanersp'',gcf); '];
plot_chan_itcs = ['pop_chanplot(''itcplot'',gcf); '];
plot_onechan_itcs = ['pop_chanplot(''plotchanitc'',gcf); '];
plot_chan_erpim = ['pop_chanplot(''erpimageplot'',gcf); '];
plot_onechan_erpim = ['pop_chanplot(''plotchanerpimage'',gcf); '];
plot_chan_spectra = ['pop_chanplot(''specplot'',gcf); '];
plot_onechan_spectra = ['pop_chanplot(''plotchanspec'',gcf); '];
plot_chan_erp = ['pop_chanplot(''erpplot'',gcf); '];
plot_onechan_erp = ['pop_chanplot(''plotchanerp'',gcf); '];
plot_chan_dip = ['pop_chanplot(''dipplot'',gcf); '];
plot_onechan_dip = ['pop_chanplot(''plotchandip'',gcf); '];
plot_chan_sum = ['pop_chanplot(''plotsum'',gcf); '];
plot_onechan_sum = ['pop_chanplot(''plotonechanum'',gcf); '];
rename_chan = ['pop_chanplot(''renamechan'',gcf);'];
move_onechan = ['pop_chanplot(''movecomp'',gcf);'];
move_outlier = ['pop_chanplot(''moveoutlier'',gcf);'];
create_chan = ['pop_chanplot(''createchan'',gcf);'];
reject_outliers = ['pop_chanplot(''rejectoutliers'',gcf);'];
merge_channels = ['pop_chanplot(''mergechannels'',gcf);'];
erp_opt = ['pop_chanplot(''erp_opt'',gcf);'];
spec_opt = ['pop_chanplot(''spec_opt'',gcf);'];
erpim_opt = ['pop_chanplot(''erpim_opt'',gcf);'];
ersp_opt = ['pop_chanplot(''ersp_opt'',gcf);'];
stat_opt = ['pop_chanplot(''stat_opt'',gcf);'];
create_group = ['pop_chanplot(''create_group'',gcf);'];
edit_group = ['pop_chanplot(''edit_group'',gcf);'];
delete_group = ['pop_chanplot(''delete_group'',gcf);'];
saveSTUDY = [ 'set(findobj(''parent'', gcbf, ''userdata'', ''save''), ''enable'', fastif(get(gcbo, ''value'')==1, ''on'', ''off''));' ];
browsesave = [ '[filename, filepath] = uiputfile2(''*.study'', ''Save STUDY with .study extension -- pop_chan()''); ' ...
'set(faindobj(''parent'', gcbf, ''tag'', ''studyfile''), ''string'', [filepath filename]);' ];
sel_all_chans = ['pop_chanplot(''sel_all_chans'',gcf);'];
% list of channel groups
% ----------------------
show_options = {};
for index = 1:length(STUDY.changrp)
show_options{end+1} = [ 'All ' STUDY.changrp(index).name ];
end;
% enable buttons
% --------------
filename = STUDY.design(STUDY.currentdesign).cell(1).filebase;
if exist([filename '.datspec']) , spec_enable = 'on'; else spec_enable = 'off'; end;
if exist([filename '.daterp'] ) , erp_enable = 'on'; else erp_enable = 'off'; end;
if exist([filename '.datersp']) , ersp_enable = 'on'; else ersp_enable = 'off'; end;
if exist([filename '.datitc']) , itc_enable = 'on'; else itc_enable = 'off'; end;
if exist([filename '.daterpim']),erpim_enable = 'on'; else erpim_enable = 'off'; end;
if isfield(ALLEEG(1).dipfit, 'model'), dip_enable = 'on'; else dip_enable = 'off'; end;
% userdata below
% --------------
fig_arg{1}{1} = ALLEEG;
fig_arg{1}{2} = STUDY;
fig_arg{1}{3} = STUDY.changrp;
fig_arg{1}{4} = { STUDY.changrp.name };
fig_arg{2} = length(STUDY.changrp);
std_line = [0.9 0.35 0.9];
geometry = { [4] [1] [0.6 0.35 0.1 0.1 0.9] std_line std_line std_line std_line std_line std_line };
str_name = sprintf('STUDY name ''%s'' - ''%s''', STUDY.name, STUDY.design(STUDY.currentdesign).name);
if length(str_name) > 80, str_name = [ str_name(1:80) '...''' ]; end;
uilist = { ...
{'style' 'text' 'string' str_name 'FontWeight' 'Bold' 'HorizontalAlignment' 'center'} {} ...
{'style' 'text' 'string' 'Select channel to plot' 'FontWeight' 'Bold' } ...
{'style' 'pushbutton' 'string' 'Sel. all' 'callback' sel_all_chans } {} {} ...
{'style' 'text' 'string' 'Select subject(s) to plot' 'FontWeight' 'Bold'} ...
{'style' 'listbox' 'string' show_options 'value' 1 'max' 2 'tag' 'chan_list' 'Callback' show_chan } ...
{'style' 'pushbutton' 'enable' 'on' 'string' [ 'STATS' 10 'params' ] 'callback' stat_opt } ...
{'style' 'listbox' 'string' '' 'tag' 'chan_onechan' 'max' 2 'min' 1 'callback' show_onechan } ...
{'style' 'pushbutton' 'enable' erp_enable 'string' 'Plot ERPs' 'Callback' plot_chan_erp} ...
{'style' 'pushbutton' 'enable' erp_enable 'string' 'Params' 'Callback' erp_opt } ...
{'style' 'pushbutton' 'enable' erp_enable 'string' 'Plot ERP(s)' 'Callback' plot_onechan_erp} ...
{'style' 'pushbutton' 'enable' spec_enable 'string' 'Plot spectra' 'Callback' plot_chan_spectra} ...
{'style' 'pushbutton' 'enable' spec_enable 'string' 'Params' 'Callback' spec_opt } ...
{'style' 'pushbutton' 'enable' spec_enable 'string' 'Plot spectra' 'Callback' plot_onechan_spectra} ...
{'style' 'pushbutton' 'enable' erpim_enable 'string' 'Plot ERPimage' 'Callback' plot_chan_erpim } ...
{'style' 'pushbutton' 'enable' erpim_enable 'string' 'Params' 'Callback' erpim_opt } ...
{'style' 'pushbutton' 'enable' erpim_enable 'string' 'Plot ERPimage(s)' 'Callback' plot_onechan_erpim } ...
{'style' 'pushbutton' 'enable' ersp_enable 'string' 'Plot ERSPs' 'Callback' plot_chan_ersps} ...
{'vertexpand' 2.15 'style' 'pushbutton' 'enable' ersp_enable 'string' 'Params' 'Callback' ersp_opt } ...
{'style' 'pushbutton' 'enable' ersp_enable 'string' 'Plot ERSP(s)' 'Callback' plot_onechan_ersps}...
{'style' 'pushbutton' 'enable' itc_enable 'string' 'Plot ITCs' 'Callback' plot_chan_itcs} { } ...
{'style' 'pushbutton' 'enable' itc_enable 'string' 'Plot ITC(s)' 'Callback' plot_onechan_itcs}...
};
% {'style' 'pushbutton' 'string' 'Plot channel properties' 'Callback' plot_chan_sum} {} ...
%{'style' 'pushbutton' 'string' 'Plot channel properties (soon)' 'Callback' plot_onechan_sum 'enable' 'off'}
% additional UI given on the command line
% ---------------------------------------
geomvert = [ 1 0.5 1 5 1 1 1 1 1];
if nargin > 2
addui = varargin{3};
if ~isfield(addui, 'uilist')
error('Additional GUI definition (argument 4) requires the field "uilist"');
end;
if ~isfield(addui, 'geometry')
addui.geometry = mat2cell(ones(1,length(addui.uilist)));
end;
uilist = { uilist{:}, addui.uilist{:} };
geometry = { geometry{:} addui.geometry{:} };
geomvert = [ geomvert ones(1,length(addui.geometry)) ];
end;
[out_param userdat] = inputgui( 'geometry' , geometry, 'uilist', uilist, ...
'helpcom', 'pophelp(''pop_chanplot'')', ...
'title', 'View and edit current channels -- pop_chanplot()' , 'userdata', fig_arg, ...
'geomvert', geomvert, 'eval', show_chan );
if ~isempty(userdat)
ALLEEG = userdat{1}{1};
STUDY = userdat{1}{2};
end
% history
% -------
com = STUDY.tmphist;
STUDY = rmfield(STUDY, 'tmphist');
else
hdl = varargin{2}; %figure handle
userdat = get(varargin{2}, 'userdat');
ALLEEG = userdat{1}{1};
STUDY = userdat{1}{2};
cls = userdat{1}{3};
allchans = userdat{1}{4};
changrp = get(findobj('parent', hdl, 'tag', 'chan_list') , 'value');
onechan = get(findobj('parent', hdl, 'tag', 'chan_onechan'), 'value');
try
switch varargin{1}
case {'topoplot', 'erspplot','itcplot','specplot', 'erpplot', 'erpimageplot' }
changrpstr = allchans(changrp);
plotting_option = varargin{1};
plotting_option = [ plotting_option(1:end-4) 'plot' ];
a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''channels'',' vararg2str({changrpstr}) ');' ];
% update Study history
eval(a); STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat);
case {'plotchanersp','plotchanitc','plotchanspec', 'plotchanerp','plotchanerpimage' }
changrpstr = allchans(changrp);
%if length(changrp) > 1
% subject = STUDY.subject{onechan-1};
%else
% changrpstruct = STUDY.changrp(changrp);
% allsubjects = unique_bc({ STUDY.datasetinfo([ changrpstruct.setinds{:} ]).subject });
% subject = allsubjects{onechan-1};
%end;
plotting_option = varargin{1};
plotting_option = [ plotting_option(9:end) 'plot' ];
if onechan(1) ~= 1 % check that not all onechan in channel are requested
subject = STUDY.design(STUDY.currentdesign).cases.value{onechan-1};
a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''channels'',' vararg2str({changrpstr}) ', ''subject'', ''' subject ''' );' ];
eval(a); STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
else
a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''channels'',' vararg2str({changrpstr}) ', ''plotsubjects'', ''on'' );' ];
eval(a); STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
end;
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat);
case 'stat_opt' % save the list of selected channels
[STUDY com] = pop_statparams(STUDY);
if ~isempty(com)
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com);
end;
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat); %update information (STUDY)
case 'erp_opt' % save the list of selected channels
[STUDY com] = pop_erpparams(STUDY);
if ~isempty(com)
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com);
end;
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat); %update information (STUDY)
case 'spec_opt' % save the list of selected channels
[STUDY com] = pop_specparams(STUDY);
if ~isempty(com)
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com);
end;
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat); %update information (STUDY)
case 'ersp_opt' % save the list of selected channels
[STUDY com] = pop_erspparams(STUDY);
if ~isempty(com)
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com);
end;
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat); %update information (STUDY)
case 'erpim_opt' % save the list of selected channels
[STUDY com] = pop_erpimparams(STUDY);
if ~isempty(com)
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com);
end;
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat); %update information (STUDY)
case 'showchanlist' % save the list of selected channels
if length(changrp) == 1
STUDY.changrp(changrp).selected = onechan;
end;
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat); %update information (STUDY)
case 'showchan'
cind = get(findobj('parent', hdl, 'tag', 'chan_list') , 'value');
changrp = STUDY.changrp(cind);
% Find datasets availaible
% ------------------------
%setind = STUDY.setind .* (changrp.chaninds > 0); % set to 0 the cell not
%% % containing any electrode
%allchansets = unique_bc( setind(find(setind(:))) );
% Generate channel list
% ---------------------
chanid{1} = 'All subjects';
if length(changrp) == 1
allsubjects = unique_bc({ STUDY.design(STUDY.currentdesign).cell([ changrp.setinds{:} ]).case });
for l = 1:length(allsubjects)
chanid{end+1} = [ allsubjects{l} ' ' changrp.name ];
end;
else
for l = 1:length(STUDY.design(STUDY.currentdesign).cases.value)
chanid{end+1} = [ STUDY.design(STUDY.currentdesign).cases.value{l} ];
end;
end;
selected = 1;
if isfield(changrp, 'selected') & length(cind) == 1
if ~isempty(STUDY.changrp(cind).selected)
selected = min(STUDY.changrp(cind).selected, 1+length(chanid));
STUDY.changrp(cind).selected = selected;
end;
end;
set(findobj('parent', hdl, 'tag', 'chan_onechan'), 'value', selected, 'String', chanid);
case 'sel_all_chans'
set(findobj('parent', hdl, 'tag', 'chan_list'), 'value', [1:length(STUDY.changrp)]);
% Generate channel list
% ---------------------
chanid{1} = 'All subjects';
for l = 1:length(STUDY.design(STUDY.currentdesign).cases.value)
chanid{end+1} = [ STUDY.design(STUDY.currentdesign).cases.value{l} ' All' ];
end;
selected = 1;
set(findobj('parent', hdl, 'tag', 'chan_onechan'), 'value', selected, 'String', chanid);
case 'plotsum'
changrpstr = allchans(changrp);
[STUDY] = std_propplot(STUDY, ALLEEG, allchans(changrp));
a = ['STUDY = std_propplot(STUDY, ALLEEG, ' vararg2str({ allchans(changrp) }) ' );' ];
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat);
case 'create_group'
channames = { STUDY.changrp(changrp).name };
for i=1:length(channames), channames{i} = [ ' ' channames{i} ]; end;
channamestr = strcat(channames{:});
res = inputdlg2({ 'Name of channel group', 'Channels to group' }, 'Create channel group', 1, { '' channamestr(2:end) });
if isempty(res), return; end;
STUDY.changrp(end+1).name = res{1};
allchans(end+1) = { res{1} };
chanlabels = parsetxt(res{2});
if length(chanlabels) == 1
warndlg2('Cannot create a channel group with a single channel');
return;
end;
STUDY.changrp(end).channels = chanlabels;
tmp = std_chanlookup( STUDY, ALLEEG, STUDY.changrp(end));
STUDY.changrp(end).chaninds = tmp.chaninds;
userdat{1}{2} = STUDY;
userdat{1}{4} = allchans;
set(hdl, 'userdat',userdat);
% list of channel groups
% ----------------------
tmpobj = findobj('parent', hdl, 'tag', 'chan_list');
tmptext = get(tmpobj, 'string');
tmptext{end+1} = [ 'All ' STUDY.changrp(end).name ];
set(tmpobj, 'string', tmptext, 'value', length(tmptext));
case 'edit_group'
if length(changrp) > 1, return; end;
if length(STUDY.changrp(changrp).channels) < 2, return; end;
channames = STUDY.changrp(changrp).channels;
for i=1:length(channames), channames{i} = [ ' ' channames{i} ]; end;
channamestr = strcat(channames{:});
res = inputdlg2({ 'Name of channel group', 'Channels to group' }, 'Create channel group', ...
1, { STUDY.changrp(changrp).name channamestr(2:end) });
if isempty(res), return; end;
STUDY.changrp(end+1).name = '';
STUDY.changrp(changrp) = STUDY.changrp(end);
STUDY.changrp(end) = [];
STUDY.changrp(changrp).name = res{1};
allchans(changrp) = { res{1} };
chanlabels = parsetxt(res{2});
STUDY.changrp(changrp).channels = chanlabels;
tmp = std_chanlookup( STUDY, ALLEEG, STUDY.changrp(end));
STUDY.changrp(changrp).chaninds = tmp.chaninds;
userdat{1}{2} = STUDY;
userdat{1}{4} = allchans;
set(hdl, 'userdat',userdat);
% list of channel groups
% ----------------------
show_options = {};
for index = 1:length(STUDY.changrp)
show_options{end+1} = [ 'All ' STUDY.changrp(index).name ];
end;
tmpobj = findobj('parent', hdl, 'tag', 'chan_list');
set(tmpobj, 'string', show_options, 'value', changrp);
case 'delete_group'
if length(changrp) > 1, return; end;
if length(STUDY.changrp(changrp).channels) < 2, return; end;
STUDY.changrp(changrp) = [];
% list of channel groups
% ----------------------
show_options = {};
for index = 1:length(STUDY.changrp)
show_options{end+1} = [ 'All ' STUDY.changrp(index).name ];
end;
tmpobj = findobj('parent', hdl, 'tag', 'chan_list');
set(tmpobj, 'string', show_options, 'value', changrp-1);
case 'renamechan'
STUDY.saved = 'no';
chan_name_list = get(findobj('parent', hdl, 'tag', 'chan_list'), 'String');
chan_num = get(findobj('parent', hdl, 'tag', 'chan_list'), 'Value') -1;
if chan_num == 0 % 'all subjects' option
return;
end
% Don't rename 'Notchan' and 'Outliers' channels.
if strncmpi('Notchan',STUDY.channel(cls(chan_num)).name,8) | strncmpi('Outliers',STUDY.channel(cls(chan_num)).name,8) | ...
strncmpi('Parentchannel',STUDY.channel(cls(chan_num)).name,13)
warndlg2('The Parentchannel, Outliers, and Notchan channels cannot be renamed');
return;
end
old_name = STUDY.channel(cls(chan_num)).name;
rename_param = inputgui( { [1] [1] [1]}, ...
{ {'style' 'text' 'string' ['Rename ' old_name] 'FontWeight' 'Bold'} {'style' 'edit' 'string' '' 'tag' 'chan_rename' } {} }, ...
'', 'Rename channel - from pop_chanplot()' );
if ~isempty(rename_param) %if not canceled
new_name = rename_param{1};
STUDY = std_renamechan(STUDY, ALLEEG, cls(chan_num), new_name);
% update Study history
a = ['STUDY = std_renamechan(STUDY, ALLEEG, ' num2str(cls(chan_num)) ', ' STUDY.channel(cls(chan_num)).name ');'];
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
new_name = [ STUDY.channel(cls(chan_num)).name ' (' num2str(length(STUDY.channel(cls(chan_num)).onechan)) ' ICs)'];
chan_name_list{chan_num+1} = renamechan( chan_name_list{chan_num+1}, new_name);
set(findobj('parent', hdl, 'tag', 'chan_list'), 'String', chan_name_list);
set(findobj('parent', hdl, 'tag', 'chan_rename'), 'String', '');
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat); %update STUDY
end
end
catch
eeglab_error;
end;
end
function newname = renamechan(oldname, newname);
tmpname = deblank(oldname(end:-1:1));
strpos = strfind(oldname, tmpname(end:-1:1));
newname = [ oldname(1:strpos-1) newname ];
|
github
|
lcnhappe/happe-master
|
std_erpimage.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_erpimage.m
| 11,020 |
utf_8
|
e610e6ac79890f95ca1b2048f25013fa
|
% std_erpimage() - Compute ERP images and save them on disk.
%
% Usage:
% >> std_erpimage( EEG, 'key', 'val', ...);
%
% Inputs:
% EEG - a loaded epoched EEG dataset structure. May be an array
% of such structure containing several datasets.
%
% Optional inputs:
% 'components' - [numeric vector] components of the EEG structure for which
% the measure will be computed {default|[] -> all}
% 'channels' - [cell array] channels of the EEG structure for which
% activation ERPs will be computed {default|[] -> none}
% 'trialindices' - [cell array] indices of trials for each dataset.
% Default is all trials.
% 'recompute' - ['on'|'off'] force recomputing data file even if it is
% already on disk.
% 'rmcomps' - [integer array] remove artifactual components (this entry
% is ignored when plotting components). This entry contains
% the indices of the components to be removed. Default is none.
% 'interp' - [struct] channel location structure containing electrode
% to interpolate ((this entry is ignored when plotting
% components). Default is no interpolation.
% 'fileout' - [string] name of the file to save on disk. The default
% is the same name (with a different extension) as the
% dataset given as input.
%
% ERPimage options:
% 'concatenate' - ['on'|'off'] concatenate single trial of different
% subjects for plotting ERPimages ('on'). The default
% ('off') computes an ERPimage for each subject and then
% averages these ERPimages. This allows to perform
% statistics (the 'on' options does not allow statistics).
% 'smoothing' - Smoothing parameter (number of trials). {Default: 10}
% erpimage() equivalent: 'avewidth'
% 'nlines' - Number of lines for ERPimage. erpaimge() equivalent is
% 'decimate'. Note that this parameter must be larger than
% the minimum number of trials in each design cell
% {Default: 10}
% 'sorttype' - Sorting event type(s) ([int vector]; []=all). See Notes below.
% Either a string or an integer.
% 'sortwin' - Sorting event window [start, end] in milliseconds ([]=whole epoch)
% 'sortfield' - Sorting field name. {default: latency}.
% 'erpimageopt' - erpimage() options, separated by commas (Ex: 'erp', 'cbar').
% {Default: none}. For further details see >> erpimage help
% Outputs:
% erpimagestruct - structure containing ERPimage information that is
% been saved on disk.
%
% Files are saved on disk.
% [dataset_file].icaerpim % component ERPimage file
% OR
% [dataset_file].daterpim % channel ERPimage file
%
% Author: Arnaud Delorme, SCCN & CERCO, CNRS, 2011-
% Copyright (C) 2011 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 allerpimage = std_erpimage( EEG, varargin);
if nargin < 1
help std_erpimage;
return;
end
allerpimage = [];
[opt moreopts] = finputcheck( varargin, { ...
'components' 'integer' [] [];
'channels' { 'cell','integer' } { [] [] } {};
'trialindices' { 'integer','cell' } [] [];
'recompute' 'string' { 'on','off' } 'off';
'savefile' 'string' { 'on','off' } 'on';
'fileout' 'string' [] '';
'rmcomps' 'cell' [] cell(1,length(EEG));
'interp' 'struct' { } struct([]);
'nlines' '' [] 10;
'smoothing' '' [] 10;
'sorttype' '' {} '';
'sortwin' '' {} [];
'sortfield' '' {} 'latency';
'concatenate' 'string' { 'on','off' } 'off';
'erpimageopt' 'cell' {} {}}, ...
'std_erpimage', 'ignore');
if isstr(opt), error(opt); end;
if length(EEG) == 1 && isempty(opt.trialindices), opt.trialindices = { [1:EEG.trials] }; end;
if isempty(opt.trialindices), opt.trialindices = cell(length(EEG)); end;
if ~iscell(opt.trialindices), opt.trialindices = { opt.trialindices }; end;
if isfield(EEG,'icaweights')
numc = size(EEG(1).icaweights,1);
else
error('EEG.icaweights not found');
end
if isempty(opt.components)
opt.components = 1:numc;
end
% filename
% --------
if isempty(opt.fileout), opt.fileout = fullfile(EEG(1).filepath, EEG(1).filename(1:end-4)); end;
if ~isempty(opt.channels)
filenameshort = [ opt.fileout '.daterpim'];
prefix = 'chan';
if iscell(opt.channels)
if ~isempty(opt.interp)
opt.indices = eeg_chaninds(opt.interp, opt.channels, 0);
else
opt.indices = eeg_chaninds(EEG(1), opt.channels, 0);
for ind = 2:length(EEG)
if ~isequal(eeg_chaninds(EEG(ind), opt.channels, 0), opt.indices)
error([ 'Channel information must be consistant when ' 10 'several datasets are merged for a specific design' ]);
end;
end;
end;
else
opt.indices = opt.channels;
end;
else
opt.indices = opt.components;
filenameshort = [ opt.fileout '.icaerpim'];
prefix = 'comp';
end;
filename = filenameshort;
% ERP information found in datasets
% ---------------------------------
if exist(filename) && strcmpi(opt.recompute, 'off')
fprintf('File "%s" found on disk, no need to recompute\n', filenameshort);
return;
end
allerpimage = [];
if strcmpi(opt.concatenate, 'off')
% compute ERP images
% ------------------
if isempty(opt.channels)
X = eeg_getdatact(EEG, 'component', opt.indices, 'trialindices', opt.trialindices );
else X = eeg_getdatact(EEG, 'channel' , opt.indices, 'trialindices', opt.trialindices, 'rmcomps', opt.rmcomps, 'interp', opt.interp);
end;
if ~isempty(opt.sorttype)
events = eeg_getepochevent(EEG, 'type', opt.sorttype, 'timewin', opt.sortwin, 'fieldname', opt.sortfield, 'trials', opt.trialindices);
else events = [];
end;
% reverse engeeneering the number of lines for ERPimage
finallines = opt.nlines;
if ~isempty(events)
if all(isnan(events))
error('Cannot sort trials for one of the dataset');
end;
lastx = sum(~isnan(events));
else lastx = size(X,3);
end;
if lastx < finallines + floor((opt.smoothing-1)/2) + 3
error('The default number of ERPimage lines is too large for one of the dataset');
end;
firstx = 1;
xwidth = opt.smoothing;
%xadv = lastx/finallines;
nout = finallines; %floor(((lastx-firstx+xadv+1)-xwidth)/xadv);
nlines = (lastx-xwidth)/(nout-0.5)*i; % make it imaginary
%nlines = ceil(lastx/((lastx-firstx+1-xwidth)/(nout-1)));
if 0
% testing conversion back and forth
% ---------------------------------
for lastx = 20:300
for xwidth = 1:19
for nlines = (xwidth+1):100
nout = floor(((lastx+nlines)-xwidth)/nlines);
realnlines = (lastx-xwidth)/(nout-0.5);
noutreal = floor(((lastx+realnlines)-xwidth)/realnlines);
if nout ~= noutreal
error('Wrong conversion 2');
end;
end;
end;
end;
end;
clear tmperpimage eventvals;
parfor index = 1:size(X,1)
[tmpX tmpevents] = erpimage(squeeze(X(index,:,:)), events, EEG(1).times, '', opt.smoothing, nlines, 'noplot', 'on', opt.erpimageopt{:}, moreopts{:});
if isempty(events), tmpevents = []; end;
eventvals{index} = tmpevents;
tmperpimage{index} = tmpX';
end;
allerpimage.events = eventvals{1};
for index = 1:size(X,1)
allerpimage.([ prefix int2str(opt.indices(index)) ]) = tmperpimage{index};
end;
else
% generate dynamic loading commands
% ---------------------------------
for dat = 1:length(EEG)
filenames{dat} = fullfile(EEG(1).filepath, EEG(1).filename);
end;
allerpimage.times = EEG(1).times;
for index = 1:length(opt.indices)
if ~isempty(opt.channels)
com = sprintf('squeeze(eeg_getdatact(%s, ''interp'', chanlocsforinterp));', vararg2str( { filenames 'channel' , opt.indices(index), 'rmcomps', opt.rmcomps, 'trialindices', opt.trialindices } ));
else com = sprintf('squeeze(eeg_getdatact(%s));', vararg2str( { filenames 'component', opt.indices(index), 'trialindices', opt.trialindices } ));
end;
allerpimage = setfield(allerpimage, [ prefix int2str(opt.indices(index)) ], com);
end;
allerpimage = setfield(allerpimage, 'chanlocsforinterp', opt.interp);
if ~isempty(opt.sorttype)
events = eeg_getepochevent(EEG, 'type', opt.sorttype, 'timewin', opt.sortwin, 'fieldname', opt.sortfield, 'trials', opt.trialindices);
%geteventcom = sprintf('eeg_getepochevent(%s);', vararg2str( { filenames 'type', opt.sorttype, 'timewin', opt.sortwin, 'fieldname', opt.sortfield } ));
else events = [];
end;
allerpimage = setfield(allerpimage, 'events', events);
end;
allerpimage.times = EEG(1).times;
allerpimage.parameters = varargin;
allerpimage.datatype = 'ERPIMAGE';
allerpimage.datafiles = computeFullFileName( { EEG.filepath }, { EEG.filename });
allerpimage.datatrials = opt.trialindices;
% Save ERPimages in file (all components or channels)
% ----------------------------------------------
if strcmpi(opt.savefile, 'on')
if strcmpi(prefix, 'comp')
std_savedat(filename, allerpimage);
else
tmpchanlocs = EEG(1).chanlocs;
allerpimage.labels = opt.channels;
std_savedat(filename, allerpimage);
end;
end;
% compute full file names
% -----------------------
function res = computeFullFileName(filePaths, fileNames);
for index = 1:length(fileNames)
res{index} = fullfile(filePaths{index}, fileNames{index});
end;
|
github
|
lcnhappe/happe-master
|
std_cell2setcomps.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_cell2setcomps.m
| 3,058 |
utf_8
|
199bb737c086d50fb622cb63d9511eeb
|
% std_cell2setcomps - convert .sets and .comps to cell array. The .sets and
% .comps format is useful for GUI but the cell array
% format is used for plotting and statistics.
%
% Usage:
% [ struct sets comps ] = std_cell2setcomps(STUDY, clustind);
%
% Author: Arnaud Delorme, CERCO/CNRS, UCSD, 2009-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ tmpstruct setlist complist ] = std_cell2setcomps(STUDY, ALLEEG, setinds, allinds)
if nargin < 4
tmpstruct = STUDY.cluster(setinds);
sets = STUDY.cluster(setinds).setinds;
inds = STUDY.cluster(setinds).allinds;
else
tmpstruct = [];
sets = setinds;
inds = allinds;
end;
% initialize flag array
% ---------------------
flag = cell(size(inds));
for i = 1:size(inds,1)
for j = 1:size(inds,2)
flag{i,j} = zeros(size(inds{i,j}));
end;
end;
% find datasets with common ICA decompositions
clusters = std_findsameica(ALLEEG);
setlist = [];
complist = [];
count = 1;
for i = 1:size(inds,1)
for j = 1:size(inds,2)
for ind = 1:length(inds{i,j})
if ~flag{i,j}(ind)
% found one good component
complist(count) = inds{i,j}(ind);
%if complist(count) == 12, dfds; end;
% search for the same component in other datasets
for c = 1:length(clusters)
if any(clusters{c} == sets{i,j}(ind))
setlist(:,count) = clusters{c}';
% flag all of these datasets
for i2 = 1:size(inds,1)
for j2 = 1:size(inds,2)
for ind2 = 1:length(sets{i2,j2})
if any(sets{i2,j2}(ind2) == clusters{c}) && complist(count) == inds{i2, j2}(ind2)
flag{i2,j2}(ind2) = 1;
end;
end;
end;
end;
end;
end;
count = count+1;
end;
end;
end;
end;
tmpstruct.sets = setlist;
tmpstruct.comps = complist;
|
github
|
lcnhappe/happe-master
|
std_editset.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_editset.m
| 16,290 |
utf_8
|
f7eebc870fafd57a1465c80e576543d1
|
% std_editset() - modify a STUDY set structure.
%
% Usage:
% >> [STUDY, ALLEEG] = std_editset(STUDY, ALLEEG, key1, val1, ...);
% Inputs:
% STUDY - EEGLAB STUDY set
% ALLEEG - vector of the EEG datasets included in the STUDY structure
%
% Optional inputs:
% 'commands' - {cell_array} change STUDY (see command description and
% example below.
% 'name' - [string] specify a (mnemonic) name for the STUDY structure.
% {default: ''}
% 'task' - [string] attach a description of the experimental task(s)
% performed by the STUDY subjects {default: ''}.
% 'filename' - [string] filename for the STUDY set.
% 'filepath' - [string] file path (directory/folder) in which the STUDY file
% will be saved.
% 'addchannellabels' - ['on'|'off'] add channel labels ('1', '2', '3', ...)
% to all datasets of a STUDY to ensure that all STUDY functions
% will work {default: 'off' unless no dataset has channel
% locations and then it is automatically set to on}
% 'notes' - [string] notes about the experiment, the datasets, the STUDY,
% or anything else to store with the STUDY itself {default: ''}.
% 'updatedat' - ['on'|'off'] update 'subject' 'session' 'condition' and/or
% 'group' fields of STUDY dataset(s).
% 'savedat' - ['on'|'off'] re-save datasets
% 'inbrain' - ['on'|'off'] select components for clustering from all STUDY
% datasets with equivalent dipoles located inside the brain volume.
% Dipoles are selected based on their residual variance and their
% location {default: 'off'}
% 'resave' - ['on'|'off'] save or resave STUDY {default: 'off'}
%
% Each of the 'commands' (above) is a cell array composed of any of the following:
% 'index' - [integer] modify/add dataset index. Note that if a
% dataset is added and that this leaves some indices not
% populated, the dataset is automatically set to the last
% empty index. For instance creating a STUDY with a single
% dataset at index 10 will result with a STUDY with a
% single dataset at index 1.
% 'remove' - [integer] remove dataset index.
% 'subject' - [string] subject code.
% 'condition' - [string] dataset condition.
% 'session ' - [integer] dataset session number.
% 'group' - [string] dataset group.
% 'load' - [filename] load dataset from specified filename
% 'dipselect' - [float<1] select components for clustering from all STUDY
% datasets with dipole model residual var. below this value.
% 'inbrain' - ['on'|'off'] same as above. This option may also be
% placed in the command list (preceeding the 'dipselect'
% option).
%
% Outputs:
% STUDY - a new STUDY set containing some or all of the datasets in ALLEEG,
% plus additional information from the optional inputs above.
% ALLEEG - a vector of EEG datasets included in the STUDY structure
%
% See also: pop_createstudy(), std_loadalleeg(), pop_clust(), pop_preclust(),
% eeg_preclust(), eeg_createdata()
%
% Authors: Arnaud Delorme, Hilit Serby, SCCN/INC/UCSD, October , 2004-
% Copyright (C) Arnaud Delorme & Scott Makeig, SCCN/INC/UCSD, October 11, 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
function [STUDY, ALLEEG] = std_editset(STUDY, ALLEEG, varargin)
if (nargin < 3)
help std_editset;
return;
end;
% decode input parameters
% -----------------------
g = finputcheck(varargin, { 'updatedat' 'string' { 'on','off' } 'off';
'name' 'string' { } '';
'task' 'string' { } '';
'notes' 'string' { } '';
'filename' 'string' { } '';
'filepath' 'string' { } '';
'resave' 'string' { 'on','off','info' } 'off';
'savedat' 'string' { 'on','off' } 'off';
'addchannellabels' 'string' { 'on','off' } 'off';
'rmclust' 'string' { 'on','off' } 'on';
'inbrain' 'string' { 'on','off' } 'off';
'commands' 'cell' {} {} }, 'std_editset');
if isstr(g), error(g); end;
if isempty(STUDY), STUDY.history = 'STUDY = [];'; end;
if ~isempty(g.name), STUDY.name = g.name; end
if ~isempty(g.task), STUDY.task = g.task; end
if ~isempty(g.notes), STUDY.notes = g.notes; end
% default addchannellabels
% ------------------------
if ~isempty(ALLEEG)
allchanlocs = { ALLEEG.chanlocs };
if all(cellfun( @isempty, allchanlocs))
g.addchannellabels = 'on';
else
if any(cellfun( @isempty, allchanlocs))
error( [ 'Some datasets have channel locations and some other don''t' 10 ...
'the STUDY is not homogenous and cannot be created.' ]);
end;
end;
end;
% make one cell array with commands
% ---------------------------------
allcoms = {};
if ~isempty(g.commands)
if iscell(g.commands{1})
for k = 1:length(g.commands)
% put index field first
indindex = strmatch('index', lower(g.commands{k}(1:2:end)));
if ~isempty(indindex)
tmpcom = { 'index' g.commands{k}{2*(indindex-1)+1+1} g.commands{k}{:} };
else tmpcom = g.commands{k};
end;
allcoms = { allcoms{:} tmpcom{:} };
end;
else
allcoms = g.commands;
end;
end;
g.commands = allcoms;
% add 'dipselect' command if 'inbrain' option is selected
% ---------------------------------
dipselectExists = false;
for k = 1:2:length(g.commands)
if strcmp(g.commands{k},'dipselect')
dipselectExists = true;
end;
end;
if strcmp(g.inbrain,'on') && ~dipselectExists
g.commands{length(g.commands)+1} = 'dipselect';
g.commands{length(g.commands)+1} = 0.15;
end;
% copy values
% -----------
if ~isfield(STUDY, 'datasetinfo')
for realindex = 1:length(ALLEEG)
if ~isempty(ALLEEG(realindex).data)
[tmppath tmpfile tmpext] = fileparts( fullfile(ALLEEG(realindex).filepath, ALLEEG(realindex).filename) );
STUDY.datasetinfo(realindex).filepath = tmppath;
STUDY.datasetinfo(realindex).filename = [ tmpfile tmpext ];
STUDY.datasetinfo(realindex).subject = ALLEEG(realindex).subject;
STUDY.datasetinfo(realindex).session = ALLEEG(realindex).session;
STUDY.datasetinfo(realindex).condition = ALLEEG(realindex).condition;
STUDY.datasetinfo(realindex).group = ALLEEG(realindex).group;
end;
end;
end;
% execute commands
% ----------------
currentind = 1;
rmlist = [];
for k = 1:2:length(g.commands)
switch g.commands{k}
case 'index'
currentind = g.commands{k+1};
case 'subject'
STUDY.datasetinfo(currentind).subject = g.commands{k+1};
case 'comps'
STUDY.datasetinfo(currentind).comps = g.commands{k+1};
case 'condition'
STUDY.datasetinfo(currentind).condition = g.commands{k+1};
case 'group'
STUDY.datasetinfo(currentind).group = g.commands{k+1};
case 'session'
STUDY.datasetinfo(currentind).session = g.commands{k+1};
case 'session'
STUDY.datasetinfo(currentind).session = g.commands{k+1};
case 'remove'
% create empty structure
allfields = fieldnames(ALLEEG);
tmpfields = allfields;
tmpfields(:,2) = cell(size(tmpfields));
tmpfields = tmpfields';
ALLEEG(g.commands{k+1}) = struct(tmpfields{:});
% create empty structure
allfields = fieldnames(STUDY.datasetinfo);
tmpfields = allfields;
tmpfields(:,2) = cell(size(tmpfields));
tmpfields = tmpfields';
STUDY.datasetinfo(g.commands{k+1}) = struct(tmpfields{:});
if isfield(STUDY.datasetinfo, 'index')
STUDY.datasetinfo = rmfield(STUDY.datasetinfo, 'index');
end;
STUDY.datasetinfo(1).index = [];
STUDY.changrp = [];
case 'return', return;
case 'inbrain'
g.inbrain = g.commands{k+1};
case 'dipselect'
STUDY = std_checkset(STUDY, ALLEEG);
rv = g.commands{k+1};
clusters = std_findsameica(ALLEEG);
for cc = 1:length(clusters)
idat = 0;
for tmpi = 1:length(clusters{cc})
if isfield(ALLEEG(clusters{cc}(tmpi)).dipfit, 'model')
idat = clusters{cc}(tmpi);
end;
end;
indleft = [];
if rv ~= 1
if idat ~= 0
if strcmp(g.inbrain,'on')
fprintf('Selecting dipoles with less than %%%2.1f residual variance and removing dipoles outside brain volume in dataset ''%s''\n', ...
100*rv, ALLEEG(idat).setname);
indleft = eeg_dipselect(ALLEEG(idat), rv*100,'inbrain');
else
fprintf('Selecting dipoles with less than %%%2.1f residual variance in dataset ''%s''\n', ...
100*rv, ALLEEG(idat).setname);
indleft = eeg_dipselect(ALLEEG(idat), rv*100,'rv');
end;
else
fprintf('No dipole information found in ''%s'' dataset, using all components\n', ALLEEG.setname)
end
end;
for tmpi = 1:length(clusters{cc})
STUDY.datasetinfo(clusters{cc}(tmpi)).comps = indleft;
end;
end;
STUDY.cluster = [];
STUDY = std_checkset(STUDY, ALLEEG); % recreate parent dataset
case 'load'
TMPEEG = std_loadalleeg( { g.commands{k+1} } );
ALLEEG = eeg_store(ALLEEG, eeg_checkset(TMPEEG), currentind);
ALLEEG(currentind).saved = 'yes';
% update datasetinfo structure
% ----------------------------
[tmppath tmpfile tmpext] = fileparts( fullfile(ALLEEG(currentind).filepath, ...
ALLEEG(currentind).filename) );
STUDY.datasetinfo(currentind).filepath = tmppath;
STUDY.datasetinfo(currentind).filename = [ tmpfile tmpext ];
STUDY.datasetinfo(currentind).subject = ALLEEG(currentind).subject;
STUDY.datasetinfo(currentind).session = ALLEEG(currentind).session;
STUDY.datasetinfo(currentind).condition = ALLEEG(currentind).condition;
STUDY.datasetinfo(currentind).group = ALLEEG(currentind).group;
STUDY.datasetinfo(currentind).index = currentind;
otherwise, error(sprintf('Unknown command %s', g.commands{k}));
end
end
% add channel labels automatically
% -------------------------------
if strcmpi(g.addchannellabels, 'on')
disp('Generating channel labels for all datasets...');
for currentind = 1:length(ALLEEG)
for ind = 1:ALLEEG(currentind).nbchan
ALLEEG(currentind).chanlocs(ind).labels = int2str(ind);
end;
end;
ALLEEG(currentind).saved = 'no';
g.savedat = 'on';
end;
% update ALLEEG structure?
% ------------------------
if strcmpi(g.updatedat, 'on')
for currentind = 1:length(ALLEEG)
if ~strcmpi(ALLEEG(currentind).subject, STUDY.datasetinfo(currentind).subject)
ALLEEG(currentind).subject = STUDY.datasetinfo(currentind).subject;
ALLEEG(currentind).saved = 'no';
end;
if ~strcmpi(ALLEEG(currentind).condition, STUDY.datasetinfo(currentind).condition)
ALLEEG(currentind).condition = STUDY.datasetinfo(currentind).condition;
ALLEEG(currentind).saved = 'no';
end;
if ~isequal(ALLEEG(currentind).session, STUDY.datasetinfo(currentind).session)
ALLEEG(currentind).session = STUDY.datasetinfo(currentind).session;
ALLEEG(currentind).saved = 'no';
end;
if ~strcmpi(char(ALLEEG(currentind).group), char(STUDY.datasetinfo(currentind).group))
ALLEEG(currentind).group = STUDY.datasetinfo(currentind).group;
ALLEEG(currentind).saved = 'no';
end;
end;
end;
% remove empty datasets (cannot be done above because some empty datasets
% might not have been removed)
% ---------------------
rmindex = [];
for index = 1:length(STUDY.datasetinfo)
if isempty(STUDY.datasetinfo(index).subject) && isempty(ALLEEG(index).nbchan)
rmindex = [ rmindex index ];
end;
end;
STUDY.datasetinfo(rmindex) = [];
ALLEEG(rmindex) = [];
for index = 1:length(STUDY.datasetinfo)
STUDY.datasetinfo(index).index = index;
end;
% remove empty ALLEEG structures
% ------------------------------
while length(ALLEEG) > length(STUDY.datasetinfo)
ALLEEG(end) = [];
end;
%[ ALLEEG STUDY.datasetinfo ] = remove_empty(ALLEEG, STUDY.datasetinfo);
% save datasets if necessary
% --------------------------
if strcmpi(g.savedat, 'on')
for index = 1:length(ALLEEG)
if isempty(ALLEEG(index).filename)
fprintf('Cannot resave ALLEEG(%d) because the dataset has no filename\n', index);
else
TMP = pop_saveset(ALLEEG(index), 'savemode', 'resave');
ALLEEG = eeg_store(ALLEEG, TMP, index);
ALLEEG(index).saved = 'yes';
end;
end;
end;
% remove cluster information if necessary
% ---------------------------------------
if strcmpi(g.rmclust, 'on')
STUDY.cluster = [];
end;
% save study if necessary
% -----------------------
if ~isempty(g.commands)
STUDY.changrp = [];
STUDY.cluster = [];
% if ~isempty(STUDY.design)
% [STUDY] = std_createclust(STUDY, ALLEEG, 'parentcluster', 'on');
% end;
end;
[STUDY ALLEEG] = std_checkset(STUDY, ALLEEG);
if ~isempty(g.filename),
[STUDY.filepath STUDY.filename ext] = fileparts(fullfile( g.filepath, g.filename ));
STUDY.filename = [ STUDY.filename ext ];
g.resave = 'on';
end
if strcmpi(g.resave, 'on')
STUDY = pop_savestudy(STUDY, ALLEEG, 'savemode', 'resave');
end;
% ---------------------
% remove empty elements
% ---------------------
function [ALLEEG, datasetinfo] = remove_empty(ALLEEG, datasetinfo);
rmindex = [];
for index = 1:length(datasetinfo)
if isempty(datasetinfo(index).subject) && isempty(ALLEEG(index).nbchan)
rmindex = [ rmindex index ];
end;
end;
datasetinfo(rmindex) = [];
ALLEEG(rmindex) = [];
for index = 1:length(datasetinfo)
datasetinfo(index).index = index;
end;
% remove empty ALLEEG structures
% ------------------------------
while length(ALLEEG) > length(datasetinfo)
ALLEEG(end) = [];
end;
|
github
|
lcnhappe/happe-master
|
std_readitc.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_readitc.m
| 1,475 |
utf_8
|
0c0874e2789900f1ae4de7b00a08107f
|
% std_readitc() - load ITC measures for data channels or
% for all components of a specified cluster.
% Usage:
% >> [STUDY, itcdata, times, freqs] = ...
% std_readitc(STUDY, ALLEEG, varargin);
%
% Note: this function is a helper function that contains a call to the
% std_readersp function that reads all 2-D data matrices for EEGLAB STUDY.
% See the std_readersp help message for more information.
%
% Author: Arnaud Delorme, CERCO, 2006-
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 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
function [STUDY, erspdata, alltimes, allfreqs, erspbase] = std_readersp(STUDY, ALLEEG, varargin);
[STUDY, erspdata, alltimes, allfreqs] = std_readersp(STUDY, ALLEEG, 'infotype','itc', varargin{:});
|
github
|
lcnhappe/happe-master
|
pop_loadstudy.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/pop_loadstudy.m
| 7,189 |
utf_8
|
8d440b01a822257a1e561422e3db090f
|
% pop_loadstudy() - load an existing EEGLAB STUDY set of EEG datasets plus
% its corresponding ALLEEG structure. Calls std_loadalleeg().
% Usage:
% >> [STUDY ALLEEG] = pop_loadstudy; % pop up a window to collect filename
% >> [STUDY ALLEEG] = pop_loadstudy( 'key', 'val', ...); % no pop-up
%
% Optional inputs:
% 'filename' - [string] filename of the STUDY set file to load.
% 'filepath' - [string] filepath of the STUDY set file to load.
%
% Outputs:
% STUDY - the requested STUDY set structure.
% ALLEEG - the corresponding ALLEEG structure containing
% the (loaded) STUDY EEG datasets.
%
% See also: std_loadalleeg(), pop_savestudy()
%
% Authors: Hilit Serby & Arnaud Delorme, SCCN, INC, UCSD, September 2005
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, Spetember 2005, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% Coding notes: Useful information on functions and global variables used.
function [STUDY, ALLEEG, com] = pop_loadstudy(varargin)
STUDY = [];
ALLEEG = [];
com = '';
if isempty(varargin)
[filename, filepath] = uigetfile2('*.study', 'Load a STUDY -- pop_loadstudy()');
if filename(1) == 0, return; end;
if ~strncmp(filename(end-5:end), '.study',6)
if isempty(strfind(filename,'.'))
filename = [filename '.study'];
else
filename = [filename(1:strfind(filename,'.')-1) '.study'];
end
end
else
filepath = '';
if nargin == 1
varargin = { 'filename' varargin{:} };
end;
for k = 1:2:length(varargin)
switch varargin{k}
case 'filename'
filename = varargin{k+1};
case 'filepath'
filepath = varargin{k+1};
end
end
end
if ~isempty(filename)
STUDYfile = fullfile(filepath,filename);
try
load('-mat', STUDYfile);
catch
error(['pop_loadstudy(): STUDY set file ''STUDYfile'' not loaded -- check filename and path']);
end
[filepath filename ext] = fileparts(STUDYfile);
STUDY.filename = [filename ext];
STUDY.etc.oldfilepath = STUDY.filepath;
STUDY.filepath = filepath;
else
error(['pop_loadstudy(): No STUDY set file provided.']);
end
ALLEEG = std_loadalleeg(STUDY);
% Update the pointers from STUDY to the ALLEEG datasets
for k = 1:length(STUDY.datasetinfo)
STUDY.datasetinfo(k).index = k;
STUDY.datasetinfo(k).filename = ALLEEG(k).filename;
STUDY.datasetinfo(k).filepath = ALLEEG(k).filepath;
end
if ~isfield(STUDY, 'changrp'), STUDY.changrp = []; end;
[STUDY ALLEEG] = std_checkset(STUDY, ALLEEG);
if ~isfield(STUDY, 'changrp') || isempty(STUDY.changrp)
if std_uniformfiles(STUDY, ALLEEG) == 0
STUDY = std_changroup(STUDY, ALLEEG);
else STUDY = std_changroup(STUDY, ALLEEG, [], 'interp');
end;
end;
% Update the design path
for inddes = 1:length(STUDY.design)
for indcell = 1:length(STUDY.design(inddes).cell)
if isempty(STUDY.design(inddes).filepath)
pathname = STUDY.datasetinfo(STUDY.design(inddes).cell(indcell).dataset(1)).filepath;
else
pathname = STUDY.design(inddes).filepath;
end
filebase = STUDY.design(inddes).cell(indcell).filebase;
tmpinds1 = find(filebase == '/');
tmpinds2 = find(filebase == '\');
if ~isempty(tmpinds1)
STUDY.design(inddes).cell(indcell).filebase = fullfile(pathname, filebase(tmpinds1(end)+1:end));
elseif ~isempty(tmpinds2)
STUDY.design(inddes).cell(indcell).filebase = fullfile(pathname, filebase(tmpinds2(end)+1:end));
else STUDY.design(inddes).cell(indcell).filebase = fullfile(pathname, filebase );
end;
end;
end;
% check for corrupted ERSP ICA data files
% A corrupted file is present if
% - components have been selected
% - .icaersp or .icaitc files are present
% - the .trialindices field is missing from these files
try
%% check for corrupted ERSP ICA data files
ncomps1 = cellfun(@length, { STUDY.datasetinfo.comps });
ncomps2 = cellfun(@(x)(size(x,1)), { ALLEEG.icaweights });
if any(~isempty(ncomps1))
if any(ncomps1 ~= ncomps2)
warningshown = 0;
for des = 1:length(STUDY.design)
for iCell = 1:length(STUDY.design(des).cell)
if ~warningshown
if exist( [ STUDY.design(des).cell(iCell).filebase '.icaersp' ] )
warning('off', 'MATLAB:load:variableNotFound');
tmp = load('-mat', [ STUDY.design(des).cell(iCell).filebase '.icaersp' ], 'trialindices');
warning('on', 'MATLAB:load:variableNotFound');
if ~isfield(tmp, 'trialindices')
warningshown = 1;
warndlg( [ 'Warning: ICA ERSP or ITC data files computed with old version of EEGLAB for design ' int2str(des) 10 ...
'(and maybe other designs). These files may be corrupted and must be recomputed.' ], 'Important EEGLAB warning', 'nonmodal');
end;
end;
if warningshown == 0 && exist( [ STUDY.design(des).cell(iCell).filebase '.icaitc' ] )
tmp = load('-mat', [ STUDY.design(des).cell(iCell).filebase '.icaersp' ], 'trialindices');
if ~isfield(tmp, 'trialindices')
warningshown = 1;
warndlg( [ 'Warning: ICA ERSP or ITC data files computed with old version of EEGLAB for design ' int2str(des) 10 ...
'(and maybe other designs). These files may be corrupted and must be recomputed.' ], 'Important EEGLAB warning', 'modal');
end;
end;
end;
end;
end;
end;
end;
catch,
disp('Warning: failed to test STUDY file version');
end;
TMP = STUDY.datasetinfo;
STUDY = std_maketrialinfo(STUDY, ALLEEG);
if ~isequal(STUDY.datasetinfo, TMP)
disp('STUDY Warning: the trial information collected from datasets has changed');
end;
std_checkfiles(STUDY, ALLEEG);
STUDY.saved = 'yes';
STUDY = std_selectdesign(STUDY, ALLEEG, STUDY.currentdesign);
com = sprintf('[STUDY ALLEEG] = pop_loadstudy(''filename'', ''%s'', ''filepath'', ''%s'');', STUDY.filename, STUDY.filepath);
|
github
|
lcnhappe/happe-master
|
std_readspecgram.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_readspecgram.m
| 4,381 |
utf_8
|
96b0d97423e8bcaaf19884201bfb7a63
|
% std_readspecgram() - returns the stored mean power spectrogram for an ICA component
% or a data channel in a specified dataset. The spectrogram is
% assumed to have been saved in a Matlab file,
% "[dataset_name].datspecgram", in the same
% directory as the dataset file. If this file doesn't exist,
% use std_specgram() to create it.
% Usage:
% >> [spec, times, freqs] = std_readspecgram(ALLEEG, setindx, component, timerange, freqrange);
%
% Inputs:
% ALLEEG - a vector of dataset EEG structures (may also be one dataset).
% Must contain the dataset of interest (the 'setindx' below).
% setindx - [integer] an index of an EEG dataset in the ALLEEG
% structure for which to read a component spectrum.
% component - [integer] index of the component in the selected EEG dataset
% for which to return the spectrum
% freqrange - [min max in Hz] frequency range to return
%
%
% Outputs:
% spec - the log-power spectrum of the requested ICA component in the
% specified dataset (in dB)
% freqs - vector of spectral frequencies (in Hz)
%
% See also std_spec(), pop_preclust(), std_preclust()
%
% Authors: Arnaud Delorme, SCCN, INC, UCSD, February, 2008
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, October 11, 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
function [X, t, f] = std_readspecgram(ALLEEG, abset, comp, timerange, freqrange, rmsubjmean);
if nargin < 4
timerange = [];
end;
if nargin < 5
freqrange = [];
end;
X = [];
if iscell(comp)
% find channel indices list
% -------------------------
chanind = [];
tmpchanlocs = ALLEEG(abset).chanlocs;
chanlabs = lower({ tmpchanlocs.labels });
for index = 1:length(comp)
tmp = strmatch(lower(comp{index}), chanlabs, 'exact');
if isempty(tmp)
error([ 'Channel ''' comp{index} ''' not found in dataset ' int2str(abset)]);
else
chanind = [ chanind tmp ];
end;
end;
filename = fullfile( ALLEEG(abset).filepath,[ ALLEEG(abset).filename(1:end-3) 'datspecgram']);
prefix = 'chan';
inds = chanind;
elseif comp(1) < 0
filename = fullfile( ALLEEG(abset).filepath,[ ALLEEG(abset).filename(1:end-3) 'datspecgram']);
prefix = 'chan';
inds = -comp;
else
filename = fullfile( ALLEEG(abset).filepath,[ ALLEEG(abset).filename(1:end-3) 'icaspecgram']);
prefix = 'comp';
inds = comp;
end;
for k=1:length(inds)
try,
warning backtrace off;
erpstruct = load( '-mat', filename, [ prefix int2str(inds(k)) ], 'freqs', 'times');
warning backtrace on;
catch
error( [ 'Cannot read file ''' filename '''' ]);
end;
tmpdat = getfield(erpstruct, [ prefix int2str(inds(k)) ]);
if k == 1
X = zeros([size(tmpdat) length(comp)]);
end;
X(:,:,k) = tmpdat;
f = getfield(erpstruct, 'freqs');
t = getfield(erpstruct, 'times');
end;
% select frequency range of interest
% ----------------------------------
if ~isempty(freqrange)
maxind = max(find(f <= freqrange(end)));
minind = min(find(f >= freqrange(1)));
else
%if not, use whole spectrum
maxind = length(f);
minind = 1;
end
f = f(minind:maxind);
X = X(minind:maxind,:,:);
% select time range of interest
% -----------------------------
if ~isempty(timerange)
maxind = max(find(t <= timerange(end)));
minind = min(find(t >= timerange(1)));
else
%if not, use whole spectrum
maxind = length(t);
minind = 1;
end
t = t(minind:maxind);
X = X(:,minind:maxind,:);
return;
|
github
|
lcnhappe/happe-master
|
std_pacplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_pacplot.m
| 1,889 |
utf_8
|
b3f29ed622b651d14f649518b13acd9f
|
% std_pacplot() - Commandline function to plot cluster PAC
% (phase-amplitude coupling).
%
% Usage:
% >> [STUDY] = std_pacplot(STUDY, ALLEEG, key1, val1, key2, val2);
% >> [STUDY itcdata itctimes itcfreqs pgroup pcond pinter] = ...
% std_pacplot(STUDY, ALLEEG ...);
% Inputs:
% STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - global EEGLAB vector of EEG structures for the datasets in the STUDY.
% Note: ALLEEG for a STUDY set is typically created using load_ALLEEG().
%
% Additional help:
% Inputs and output of this function are strictly identical to the std_erspplot().
% See the help message of this function for more information.
%
% See also: std_erspplot(), pop_clustedit(), pop_preclust()
%
% Authors: Arnaud Delorme, CERCO, July, 2009-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [STUDY, allpac, alltimes, allfreqs, pgroup, pcond, pinter] = std_pacplot(STUDY, ALLEEG, varargin)
if nargin < 2
help std_pacplot;
return;
end;
[STUDY allpac alltimes allfreqs pgroup pcond pinter ] = std_erspplot(STUDY, ALLEEG, 'datatype', 'pac', varargin{:});
|
github
|
lcnhappe/happe-master
|
pop_dipparams.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/pop_dipparams.m
| 3,898 |
utf_8
|
49636409e08a138da902e72246f3131a
|
% pop_dipparams() - Set plotting parameters for dipoles.
%
% Usage:
% >> STUDY = pop_dipparams(STUDY, 'key', 'val');
%
% Inputs:
% STUDY - EEGLAB STUDY set
%
% Optional inputs:
% 'axistight' - ['on'|'off'] Plot closest MRI slide. Default is 'off'.
% 'projimg' - ['on'|'off'] lot dipoles projections on each axix. Default is 'off'.
% 'projlines' - ['on'|'off'] Plot projection lines. Default is 'off'.
%
% See also: std_dipplot()
%
% Authors: Arnaud Delorme
% Copyright (C) Arnaud Delorme, 20013
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public 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 [ STUDY, com ] = pop_dipparams(STUDY, varargin);
STUDY = default_params(STUDY);
TMPSTUDY = STUDY;
com = '';
if isempty(varargin)
val_axistight = fastif(strcmpi(STUDY.etc.dipparams.axistight,'on'), 1, 0);
val_projimg = fastif(strcmpi(STUDY.etc.dipparams.projimg,'on'), 1, 0);
val_projlines = fastif(strcmpi(STUDY.etc.dipparams.projlines,'on'), 1, 0);
uilist = { ...
{'style' 'checkbox' 'tag' 'axistight' 'value' val_axistight } { 'style' 'text' 'string' 'Plot closest MRI slide' } ...
{'style' 'checkbox' 'tag' 'projlines' 'value' val_projlines } { 'style' 'text' 'string' 'Plot projection lines' } ...
{'style' 'checkbox' 'tag' 'projimg' 'value' val_projimg } { 'style' 'text' 'string' 'Plot dipoles projections' } };
[out_param userdat tmp res] = inputgui( 'geometry' , { [0.1 1] [0.1 1] [0.1 1] }, 'uilist', uilist, 'geomvert', [1 1 1], ...
'title', 'ERP plotting options -- pop_dipparams()');
if isempty(res), return; end;
% decode inputs
% -------------
res.axistight = fastif(res.axistight, 'on', 'off');
res.projimg = fastif(res.projimg , 'on', 'off');
res.projlines = fastif(res.projlines, 'on', 'off');
% build command call
% ------------------
options = {};
if ~strcmpi( res.axistight, STUDY.etc.dipparams.axistight), options = { options{:} 'axistight' res.axistight }; end;
if ~strcmpi( res.projimg, STUDY.etc.dipparams.projimg ), options = { options{:} 'projimg' res.projimg }; end;
if ~strcmpi( res.projlines, STUDY.etc.dipparams.projlines), options = { options{:} 'projlines' res.projlines }; end;
if ~isempty(options)
STUDY = pop_dipparams(STUDY, options{:});
com = sprintf('STUDY = pop_dipparams(STUDY, %s);', vararg2str( options ));
end;
else
if strcmpi(varargin{1}, 'default')
STUDY = default_params(STUDY);
else
for index = 1:2:length(varargin)
if ~isempty(strmatch(varargin{index}, fieldnames(STUDY.etc.dipparams), 'exact'))
STUDY.etc.dipparams = setfield(STUDY.etc.dipparams, varargin{index}, varargin{index+1});
end;
end;
end;
end;
function STUDY = default_params(STUDY)
if ~isfield(STUDY.etc, 'dipparams'), STUDY.etc.dipparams = []; end;
if ~isfield(STUDY.etc.dipparams, 'axistight'), STUDY.etc.dipparams.axistight = 'off'; end;
if ~isfield(STUDY.etc.dipparams, 'projimg'), STUDY.etc.dipparams.projimg = 'off'; end;
if ~isfield(STUDY.etc.dipparams, 'projlines'), STUDY.etc.dipparams.projlines = 'off'; end;
|
github
|
lcnhappe/happe-master
|
std_precomp.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_precomp.m
| 29,881 |
utf_8
|
8762251e54d64dd26e02ab863ad5b239
|
% std_precomp() - Precompute measures (ERP, spectrum, ERSP, ITC) for channels in a
% study. If channels are interpolated before computing the measures,
% the updated EEG datasets are also saved to disk. Called by
% pop_precomp(). Follow with pop_plotstudy(). See Example below.
% Usage:
% >> [STUDY ALLEEG customRes] = std_precomp(STUDY, ALLEEG, chanorcomp, 'key', 'val', ...);
%
% Required inputs:
% STUDY - an EEGLAB STUDY set of loaded EEG structures
% ALLEEG - ALLEEG vector of one or more loaded EEG dataset structures
% chanorcomp - ['components'|'channels'| or channel cell array] The string
% 'components' forces the program to precompute all selected
% measures for components. The string 'channels' forces the
% program to compute all measures for all channels.
% A channel cell array containing channel labels will precompute
% the selected measures. Note that the name of the channel is
% not case-sensitive.
% Optional inputs:
% 'design' - [integer] use specific study index design to compute measure.
% 'cell' - [integer] compute measure only for a give data file.
% 'erp' - ['on'|'off'] pre-compute ERPs for each dataset.
% 'spec' - ['on'|'off'] pre-compute spectrum for each dataset.
% Use 'specparams' to set spectrum parameters.
% 'ersp' - ['on'|'off'] pre-compute ERSP for each dataset.
% Use 'erspparams' to set time/frequency parameters.
% 'itc' - ['on'|'off'] pre-compute ITC for each dataset.
% Use 'erspparams' to set time/frequency parameters.
% 'scalp' - ['on'|'off'] pre-compute scalp maps for components.
% 'allcomps' - ['on'|'off'] compute ERSP/ITC for all components ('off'
% only use pre-selected components in the pop_study interface).
% 'erpparams' - [cell array] Parameters for the std_erp function. See
% std_erp for more information.
% 'specparams' - [cell array] Parameters for the std_spec function. See
% std_spec for more information.
% 'erspparams' - [cell array] Optional arguments for the std_ersp function.
% 'erpimparams' - [cell array] Optional argument for std_erpimage. See
% std_erpimage for the list of arguments.
% 'recompute' - ['on'|'off'] force recomputing ERP file even if it is
% already on disk.
% 'rmicacomps' - ['on'|'off'|'processica'] remove ICA components pre-selected in
% each dataset (EEGLAB menu item, "Tools > Reject data using ICA
% > Reject components by map). This option is ignored when
% precomputing measures for ICA clusters. Default is 'off'.
% 'processica' forces to process ICA components instead of
% removing them.
% 'rmclust' - [integer array] remove selected ICA component clusters.
% For example, ICA component clusters containing
% artifacts. This option is ignored when precomputing
% measures for ICA clusters.
% 'savetrials' - ['on'|'off'] save single-trials ERSP. Requires a lot of disk
% space (dataset space on disk times 10) but allow for refined
% single-trial statistics.
% 'customfunc' - [function_handle] execute a specific function on each
% EEGLAB dataset of the selected STUDY design. The fist
% argument to the function is an EEGLAB dataset. Example is
% @(EEG)mean(EEG.data,3)
% This will compute the ERP for the STUDY design. EEG is the
% EEGLAB dataset corresponding to each cell design. It
% corresponds to a dataset computed dynamically based on
% the design selection. If 'rmclust', 'rmicacomps' or 'interp'
% are being used, the channel data is affected
% accordingly. Anonymous and non-anonymous functions may be
% used. The output is returned in CustomRes or saved on
% disk. The output of the custom function may be an numerical
% array or a structure.
% 'customparams' - [cell array] Parameters for the custom function above.
% 'customfileext' - [string] file extension for saving custom data. Use
% function to read custom data. If left empty, the
% result is returned in the customRes output. Note that
% if the custom function does not return a structure,
% the data is automatically saved in a variable named
% 'data'.
% 'customclusters' - [integer array] load only specific clusters. This is
% used with SIFT. chanorcomp 3rd input must be 'components'.
%
% Outputs:
% ALLEEG - the input ALLEEG vector of EEG dataset structures, modified
% by adding preprocessing data as pointers to Matlab files that
% hold the pre-clustering component measures.
% STUDY - the input STUDY set with pre-clustering data added,
% for use by pop_clust()
% customRes - cell array of custom results (one cell for each pair of
% independent variables as defined in the STUDY design).
% If a custom file extension is specified, this variable
% is empty as the function assumes that the result is too
% large to hold in memory.
%
% Example:
% >> [STUDY ALLEEG customRes] = std_precomp(STUDY, ALLEEG, { 'cz' 'oz' }, 'interp', ...
% 'on', 'erp', 'on', 'spec', 'on', 'ersp', 'on', 'erspparams', ...
% { 'cycles' [ 3 0.5 ], 'alpha', 0.01, 'padratio' 1 });
%
% % This prepares, channels 'cz' and 'oz' in the STUDY datasets.
% % If a data channel is missing in one dataset, it will be
% % interpolated (see eeg_interp()). The ERP, spectrum, ERSP, and
% % ITC for each dataset is then computed.
%
% Example of custom call:
% The function below computes the ERP of the EEG data for each channel and plots it.
% >> [STUDY ALLEEG customres] = std_precomp(STUDY, ALLEEG, 'channels', 'customfunc', @(EEG,varargin)(mean(EEG.data,3)'));
% >> std_plotcurve([1:size(customres{1},1)], customres, 'chanlocs', eeg_mergelocs(ALLEEG.chanlocs)); % plot data
%
% The function below uses a data file to store the information then read
% the data and eventyally plot it
% >> [STUDY ALLEEG customres] = std_precomp(STUDY, ALLEEG, 'channels', 'customfunc', @(EEG,varargin)(mean(EEG.data,3)), 'customfileext', 'tmperp');
% >> erpdata = std_readcustom(STUDY, ALLEEG, 'tmperp');
% >> std_plotcurve([1:size(erpdata{1})], erpdata, 'chanlocs', eeg_mergelocs(ALLEEG.chanlocs)); % plot data
%
% Authors: Arnaud Delorme, SCCN, INC, UCSD, 2006-
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, 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 [ STUDY, ALLEEG customRes ] = std_precomp(STUDY, ALLEEG, chanlist, varargin)
if nargin < 2
help std_precomp;
return;
end;
if nargin == 2
chanlist = 'channels'; % default to clustering the whole STUDY
end
customRes = [];
Ncond = length(STUDY.condition);
if Ncond == 0
Ncond = 1;
end
g = finputcheck(varargin, { 'erp' 'string' { 'on','off' } 'off';
'interp' 'string' { 'on','off' } 'off';
'ersp' 'string' { 'on','off' } 'off';
'recompute' 'string' { 'on','off' } 'off';
'spec' 'string' { 'on','off' } 'off';
'erpim' 'string' { 'on','off' } 'off';
'scalp' 'string' { 'on','off' } 'off';
'allcomps' 'string' { 'on','off' } 'off';
'itc' 'string' { 'on','off' } 'off';
'savetrials' 'string' { 'on','off' } 'off';
'rmicacomps' 'string' { 'on','off','processica' } 'off';
'cell' 'integer' [] [];
'design' 'integer' [] STUDY.currentdesign;
'rmclust' 'integer' [] [];
'rmbase' 'integer' [] []; % deprecated, for backward compatibility purposes, not documented
'specparams' 'cell' {} {};
'erpparams' 'cell' {} {};
'customfunc' {'function_handle' 'integer' } { { } {} } [];
'customparams' 'cell' {} {};
'customfileext' 'string' [] '';
'customclusters' 'integer' [] [];
'erpimparams' 'cell' {} {};
'erspparams' 'cell' {} {}}, 'std_precomp');
if isstr(g), error(g); end;
if ~isempty(g.rmbase), g.erpparams = { g.erpparams{:} 'rmbase' g.rmbase }; end;
% union of all channel structures
% -------------------------------
computewhat = 'channels';
if isstr(chanlist)
if strcmpi(chanlist, 'channels')
chanlist = [];
else % components
computewhat = 'components';
if strcmpi(g.allcomps, 'on')
chanlist = {};
for index = 1:length(STUDY.datasetinfo)
chanlist = { chanlist{:} [1:size(ALLEEG(STUDY.datasetinfo(index).index).icaweights,1)] };
end;
else
chanlist = { STUDY.datasetinfo.comps };
end;
end;
end;
if isempty(chanlist)
alllocs = eeg_mergelocs(ALLEEG.chanlocs);
chanlist = { alllocs.labels };
elseif ~isnumeric(chanlist{1})
alllocs = eeg_mergelocs(ALLEEG.chanlocs);
[tmp c1 c2] = intersect_bc( lower({ alllocs.labels }), lower(chanlist));
[tmp c2] = sort(c2);
alllocs = alllocs(c1(c2));
end;
% test if interp and reconstruct channel list
% -------------------------------------------
if strcmpi(computewhat, 'channels')
if strcmpi(g.interp, 'on')
STUDY.changrp = [];
STUDY = std_changroup(STUDY, ALLEEG, chanlist, 'interp');
g.interplocs = alllocs;
else
STUDY.changrp = [];
STUDY = std_changroup(STUDY, ALLEEG, chanlist);
g.interplocs = struct([]);
end;
end;
% components or channels
% ----------------------
if strcmpi(computewhat, 'channels')
curstruct = STUDY.changrp;
else curstruct = STUDY.cluster;
end;
% compute custom measure
% ----------------------
if ~isempty(g.customfunc)
nc = max(length(STUDY.design(g.design).variable(1).value),1);
ng = max(length(STUDY.design(g.design).variable(2).value),1);
allinds = curstruct(1).allinds; % same for all channels and components (see std_selectdesign)
setinds = curstruct(1).setinds; % same for all channels and components (see std_selectdesign)
if ~isempty(g.customclusters)
allinds = curstruct(g.customclusters).allinds; % same for all channels and components (see std_selectdesign)
setinds = curstruct(g.customclusters).setinds; % same for all channels and components (see std_selectdesign)
end;
for cInd = 1:nc
for gInd = 1:ng
if ~isempty(setinds{cInd,gInd})
desset = STUDY.design(g.design).cell(setinds{cInd,gInd}(:));
for iDes = 1:length(desset)
if strcmpi(computewhat, 'channels')
[tmpchanlist opts] = getchansandopts(STUDY, ALLEEG, chanlist, desset(iDes).dataset, g);
TMPEEG = std_getdataset(STUDY, ALLEEG, 'design', g.design, 'cell', setinds{cInd,gInd}(iDes), opts{:}); % trial indices included in cell selection
else TMPEEG = std_getdataset(STUDY, ALLEEG, 'design', g.design, 'cell', setinds{cInd,gInd}(iDes), 'cluster', g.customclusters);
end;
addopts = { 'savetrials', g.savetrials, 'recompute', g.recompute }; % not currently used
tmpData = feval(g.customfunc, TMPEEG, g.customparams{:});
if isempty(g.customfileext)
resTmp(:,:,iDes) = tmpData;
else
fileName = [ desset(iDes).filebase '.' g.customfileext ];
clear data;
data.data = tmpData;
data.datafile = computeFullFileName( { ALLEEG(desset(iDes).dataset).filepath }, { ALLEEG(desset(iDes).dataset).filename });
data.datatrials = desset(iDes).trials;
data.datatype = upper(g.customfileext);
if ~isempty(g.customparams) data.parameters = g.customparams; end;
std_savedat(fileName, data);
end;
end;
if isempty(g.customfileext)
customRes{cInd,gInd} = resTmp;
end;
clear resTmp;
end;
end;
end;
end;
% compute ERPs
% ------------
if strcmpi(g.erp, 'on')
% check dataset consistency
% -------------------------
allPnts = [ALLEEG([STUDY.design(g.design).cell.dataset]).pnts];
if iscell(allPnts), allPnts = [ allPnts{:} ]; end;
if length(unique(allPnts)) > 1
error([ 'Cannot compute ERPs because datasets' 10 'do not have the same number of data points' ])
end;
for index = 1:length(STUDY.design(g.design).cell)
if ~isempty(g.cell)
desset = STUDY.design(g.design).cell(g.cell);
else desset = STUDY.design(g.design).cell(index);
end;
addopts = { 'savetrials', g.savetrials, 'recompute', g.recompute, 'fileout', desset.filebase, 'trialindices', desset.trials };
if strcmpi(computewhat, 'channels')
[tmpchanlist opts] = getchansandopts(STUDY, ALLEEG, chanlist, desset.dataset, g);
std_erp(ALLEEG(desset.dataset), 'channels', tmpchanlist, opts{:}, addopts{:}, g.erpparams{:});
else
if length(desset.dataset)>1 && ~isequal(chanlist{desset.dataset})
error(['ICA decompositions must be identical if' 10 'several datasets are concatenated to build' 10 'the design, abording' ]);
end;
std_erp(ALLEEG(desset.dataset), 'components', chanlist{desset.dataset(1)}, addopts{:}, g.erpparams{:});
end;
if ~isempty(g.cell), break; end;
end;
if isfield(curstruct, 'erpdata')
curstruct = rmfield(curstruct, 'erpdata');
curstruct = rmfield(curstruct, 'erptimes');
end;
end;
% compute spectrum
% ----------------
if strcmpi(g.spec, 'on')
% check dataset consistency
% -------------------------
for index = 1:length(STUDY.design(g.design).cell)
if ~isempty(g.cell)
desset = STUDY.design(g.design).cell(g.cell);
else desset = STUDY.design(g.design).cell(index);
end;
addopts = { 'savetrials', g.savetrials, 'recompute', g.recompute, 'fileout', desset.filebase, 'trialindices', desset.trials };
if strcmpi(computewhat, 'channels')
[tmpchanlist opts] = getchansandopts(STUDY, ALLEEG, chanlist, desset.dataset, g);
std_spec(ALLEEG(desset.dataset), 'channels', tmpchanlist, opts{:}, addopts{:}, g.specparams{:});
else
if length(desset.dataset)>1 && ~isequal(chanlist{desset.dataset})
error(['ICA decompositions must be identical if' 10 'several datasets are concatenated to build' 10 'the design, abording' ]);
end;
std_spec(ALLEEG(desset.dataset), 'components', chanlist{desset.dataset(1)}, addopts{:}, g.specparams{:});
end;
if ~isempty(g.cell), break; end;
end;
if isfield(curstruct, 'specdata')
curstruct = rmfield(curstruct, 'specdata');
curstruct = rmfield(curstruct, 'specfreqs');
end;
end;
% compute spectrum
% ----------------
if strcmpi(g.erpim, 'on')
% check dataset consistency
% -------------------------
allPnts = [ALLEEG([STUDY.design(g.design).cell.dataset]).pnts];
if iscell(allPnts), allPnts = [ allPnts{:} ]; end;
if length(unique(allPnts)) > 1
error([ 'Cannot compute ERSPs/ITCs because datasets' 10 'do not have the same number of data points' ])
end;
% check consistency with parameters on disk
% -----------------------------------------
guimode = 'guion';
tmpparams = {};
tmpparams = g.erpimparams;
if strcmpi(g.recompute, 'off')
for index = 1:length(STUDY.design(g.design).cell)
desset = STUDY.design(g.design).cell(index);
if strcmpi(computewhat, 'channels')
filename = [ desset.filebase '.daterpim'];
else filename = [ desset.filebase '.icaerpim'];
end;
[guimode, g.erpimparams] = std_filecheck(filename, g.erpimparams, guimode, { 'fileout' 'recompute', 'channels', 'components', 'trialindices'});
if strcmpi(guimode, 'cancel'), return; end;
end;
if strcmpi(guimode, 'usedisk') || strcmpi(guimode, 'same'), g.recompute = 'off';
else g.recompute = 'on';
end;
if ~isempty(g.erpimparams) && isstruct(g.erpimparams)
tmpparams = fieldnames(g.erpimparams); tmpparams = tmpparams';
tmpparams(2,:) = struct2cell(g.erpimparams);
end;
end;
% set parameters in ERPimage parameters
% -------------------------------------
STUDY = pop_erpimparams(STUDY, tmpparams{:}); % a little trashy as the function pop_erpimparams does not check the fields
% compute ERPimages
% -----------------
for index = 1:length(STUDY.design(g.design).cell)
if ~isempty(g.cell)
desset = STUDY.design(g.design).cell(g.cell);
else desset = STUDY.design(g.design).cell(index);
end;
addopts = { 'recompute', g.recompute, 'fileout', desset.filebase, 'trialindices', desset.trials };
if strcmpi(computewhat, 'channels')
[tmpchanlist opts] = getchansandopts(STUDY, ALLEEG, chanlist, desset.dataset, g);
std_erpimage(ALLEEG(desset.dataset), 'channels', tmpchanlist, opts{:}, addopts{:}, tmpparams{:});
else
if length(desset.dataset)>1 && ~isequal(chanlist{desset.dataset})
error(['ICA decompositions must be identical if' 10 'several datasets are concatenated to build' 10 'the design, abording' ]);
end;
std_erpimage(ALLEEG(desset.dataset), 'components', chanlist{desset.dataset(1)}, addopts{:}, tmpparams{:});
end;
if ~isempty(g.cell), break; end;
end;
if isfield(curstruct, 'erpimdata')
curstruct = rmfield(curstruct, 'erpimdata');
curstruct = rmfield(curstruct, 'erpimtimes');
curstruct = rmfield(curstruct, 'erpimtrials');
curstruct = rmfield(curstruct, 'erpimevents');
end;
end;
% compute component scalp maps
% ----------------------------
if strcmpi(g.scalp, 'on') && ~strcmpi(computewhat, 'channels')
for index = 1:length(STUDY.datasetinfo)
% find duplicate
% --------------
found = [];
ind1 = STUDY.datasetinfo(index).index;
inds = strmatch(STUDY.datasetinfo(index).subject, { STUDY.datasetinfo(1:index-1).subject });
for index2 = 1:length(inds)
ind2 = STUDY.datasetinfo(inds(index2)).index;
if isequal(ALLEEG(ind1).icawinv, ALLEEG(ind2).icawinv)
found = ind2;
end;
end;
% make link if duplicate
% ----------------------
if ~isempty(g.cell)
desset = STUDY.design(g.design).cell(g.cell);
[path,tmp] = fileparts(desset.filebase);
else path = ALLEEG(index).filepath;
end;
fprintf('Computing/checking topo file for dataset %d\n', ind1);
if ~isempty(found)
clear tmp;
tmpfile1 = fullfile( path, [ ALLEEG(index).filename(1:end-3) 'icatopo' ]);
tmp.file = fullfile( ALLEEG(found).filepath, [ ALLEEG(found).filename(1:end-3) 'icatopo' ]);
std_savedat(tmpfile1, tmp);
else
std_topo(ALLEEG(index), chanlist{index}, 'none', 'recompute', g.recompute,'fileout',path);
end;
end;
if isfield(curstruct, 'topo')
curstruct = rmfield(curstruct, 'topo');
curstruct = rmfield(curstruct, 'topox');
curstruct = rmfield(curstruct, 'topoy');
curstruct = rmfield(curstruct, 'topoall');
curstruct = rmfield(curstruct, 'topopol');
end;
end;
% compute ERSP and ITC
% --------------------
if strcmpi(g.ersp, 'on') || strcmpi(g.itc, 'on')
% check dataset consistency
% -------------------------
allPnts = [ALLEEG([STUDY.design(g.design).cell.dataset]).pnts];
if iscell(allPnts), allPnts = [ allPnts{:} ]; end;
if length(unique(allPnts)) > 1
error([ 'Cannot compute ERSPs/ITCs because datasets' 10 'do not have the same number of data points' ])
end;
if strcmpi(g.ersp, 'on') & strcmpi(g.itc, 'on'), type = 'both';
elseif strcmpi(g.ersp, 'on') , type = 'ersp';
else type = 'itc';
end;
% check for existing files
% ------------------------
guimode = 'guion';
[ tmpX tmpt tmpf g.erspparams ] = std_ersp(ALLEEG(1), 'channels', 1, 'type', type, 'recompute', 'on', 'getparams', 'on', 'savetrials', g.savetrials, g.erspparams{:});
if strcmpi(g.recompute, 'off')
for index = 1:length(STUDY.design(g.design).cell)
desset = STUDY.design(g.design).cell(index);
if strcmpi(computewhat, 'channels')
filename = [ desset.filebase '.datersp'];
else filename = [ desset.filebase '.icaersp'];
end;
[guimode, g.erspparams] = std_filecheck(filename, g.erspparams, guimode, { 'plotitc' 'plotersp' 'plotphase' });
if strcmpi(guimode, 'cancel'), return; end;
end;
if strcmpi(guimode, 'usedisk') || strcmpi(guimode, 'same'), g.recompute = 'off';
else g.recompute = 'on';
end;
end;
% check for existing files
% ------------------------
if isempty(g.erspparams),
tmpparams = {};
elseif iscell(g.erspparams),
tmpparams = g.erspparams;
else
tmpparams = fieldnames(g.erspparams); tmpparams = tmpparams';
tmpparams(2,:) = struct2cell(g.erspparams);
end;
tmpparams = { tmpparams{:} 'recompute' g.recompute };
for index = 1:length(STUDY.design(g.design).cell)
if ~isempty(g.cell)
desset = STUDY.design(g.design).cell(g.cell);
else desset = STUDY.design(g.design).cell(index);
end;
if strcmpi(computewhat, 'channels')
[tmpchanlist opts] = getchansandopts(STUDY, ALLEEG, chanlist, desset.dataset, g);
std_ersp(ALLEEG(desset.dataset), 'channels', tmpchanlist, 'type', type, 'fileout', desset.filebase, 'trialindices', desset.trials, opts{:}, tmpparams{:});
else
if length(desset.dataset)>1 && ~isequal(chanlist{desset.dataset})
error(['ICA decompositions must be identical if' 10 'several datasets are concatenated to build' 10 'the design, abording' ]);
end;
std_ersp(ALLEEG(desset.dataset), 'components', chanlist{desset.dataset(1)}, 'type', type, 'fileout', desset.filebase, 'trialindices', desset.trials, tmpparams{:});
end;
if ~isempty(g.cell), break; end;
end;
if isfield(curstruct, 'erspdata')
curstruct = rmfield(curstruct, 'erspdata');
curstruct = rmfield(curstruct, 'ersptimes');
curstruct = rmfield(curstruct, 'erspfreqs');
end;
if isfield(curstruct, 'itcdata')
curstruct = rmfield(curstruct, 'itcdata');
curstruct = rmfield(curstruct, 'itctimes');
curstruct = rmfield(curstruct, 'itcfreqs');
end;
end;
% components or channels
% ----------------------
if strcmpi(computewhat, 'channels')
STUDY.changrp = curstruct;
else STUDY.cluster = curstruct;
end;
return;
% find components in cluster for specific dataset
% -----------------------------------------------
function rmcomps = getclustcomps(STUDY, rmclust, settmpind);
rmcomps = cell(1,length(settmpind));
for idat = 1:length(settmpind) % scan dataset for which to find component clusters
for rmi = 1:length(rmclust) % scan clusters
comps = STUDY.cluster(rmclust(rmi)).comps;
sets = STUDY.cluster(rmclust(rmi)).sets;
indmatch = find(sets(:) == settmpind(idat));
indmatch = ceil(indmatch/size(sets,1)); % get the column number
rmcomps{idat} = [rmcomps{idat} comps(indmatch(:)') ];
end;
rmcomps{idat} = sort(rmcomps{idat});
end;
% make option array and channel list (which depend on interp) for any type of measure
% ----------------------------------------------------------------------
function [tmpchanlist, opts] = getchansandopts(STUDY, ALLEEG, chanlist, idat, g);
opts = { };
if ~isempty(g.rmclust) || strcmpi(g.rmicacomps, 'on') || strcmpi(g.rmicacomps, 'processica')
rmcomps = cell(1,length(idat));
if ~isempty(g.rmclust)
rmcomps = getclustcomps(STUDY, g.rmclust, idat);
end;
if strcmpi(g.rmicacomps, 'on')
for ind = 1:length(idat)
rmcomps{ind} = union_bc(rmcomps{ind}, find(ALLEEG(idat(ind)).reject.gcompreject));
end;
elseif strcmpi(g.rmicacomps, 'processica')
for ind = 1:length(idat)
rmcomps{ind} = union_bc(rmcomps{ind}, find(~ALLEEG(idat(ind)).reject.gcompreject));
end;
end;
opts = { opts{:} 'rmcomps' rmcomps };
end;
if strcmpi(g.interp, 'on')
tmpchanlist = chanlist;
allocs = eeg_mergelocs(ALLEEG.chanlocs);
[tmp1 tmp2 neworder] = intersect_bc( {allocs.labels}, chanlist);
[tmp1 ordertmp2] = sort(tmp2);
neworder = neworder(ordertmp2);
opts = { opts{:} 'interp' allocs(neworder) };
else
newchanlist = [];
tmpchanlocs = ALLEEG(idat(1)).chanlocs;
chanlocs = { tmpchanlocs.labels };
for i=1:length(chanlist)
newchanlist = [ newchanlist strmatch(chanlist{i}, chanlocs, 'exact') ];
end;
tmpchanlocs = ALLEEG(idat(1)).chanlocs;
tmpchanlist = { tmpchanlocs(newchanlist).labels };
end;
% compute full file names
% -----------------------
function res = computeFullFileName(filePaths, fileNames);
for index = 1:length(fileNames)
res{index} = fullfile(filePaths{index}, fileNames{index});
end;
|
github
|
lcnhappe/happe-master
|
std_rebuilddesign.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_rebuilddesign.m
| 2,984 |
utf_8
|
09dbb018032fb646a0680536ac8e28a2
|
% std_rebuilddesign - reduild design structure when datasets have been
% removed or added.
% Usage:
% STUDY = std_rebuilddesign(STUDY, ALLEEG);
% STUDY = std_rebuilddesign(STUDY, ALLEEG, designind);
%
% Inputs:
% STUDY - EEGLAB STUDY set
% ALLEEG - vector of the EEG datasets included in the STUDY structure
%
% Optional inputs:
% designind - [integer>0] indices (number) of the design to rebuild.
% Default is all.
% Ouput:
% STUDY - updated EEGLAB STUDY set
%
% Author: Arnaud Delorme, Institute for Neural Computation UCSD, 2010-
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function STUDY = std_rebuilddesign(STUDY, ALLEEG, designind);
if nargin < 2
help std_rebuilddesign;
return;
end;
if nargin < 3
designind = 1:length(STUDY.design);
end;
[indvars indvarvals] = std_getindvar(STUDY);
for indDesign = designind
% find out if some independent variables or independent
% variable values have been removed
tmpdesign = STUDY.design(indDesign);
indVar1 = strmatch(tmpdesign.variable(1).label, indvars, 'exact');
indVar2 = strmatch(tmpdesign.variable(2).label, indvars, 'exact');
if isempty(indVar1)
tmpdesign.variable(1).label = '';
tmpdesign.variable(1).value = {};
else
tmpdesign.variable(1).value = myintersect( tmpdesign.variable(1).value, indvarvals{indVar1} );
end;
if isempty(indVar2)
tmpdesign.variable(2).label = '';
tmpdesign.variable(2).value = {};
else
tmpdesign.variable(2).value = myintersect( tmpdesign.variable(2).value, indvarvals{indVar2} );
end;
STUDY = std_makedesign(STUDY, ALLEEG, indDesign, tmpdesign);
end;
STUDY = std_selectdesign(STUDY, ALLEEG, STUDY.currentdesign);
% take the intersection for independent variables
% -----------------------------------------------
function a = myintersect(a,b);
if isempty(b) || isempty(a), a = {}; return; end;
for index = 1:length(a)
if isstr(a{index})
a(index) = intersect_bc(a(index), b);
elseif iscell(a{index})
a{index} = intersect_bc(a{index}, b);
elseif isnumeric(a{index})
a{index} = intersect_bc(a{index}, [ b{:} ]);
end;
end;
|
github
|
lcnhappe/happe-master
|
pop_clustedit.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/pop_clustedit.m
| 59,499 |
utf_8
|
715c47c2679a7429d5bad3902ce3b72e
|
% pop_clustedit() - graphic user interface (GUI)-based function with editing and plotting
% options for visualizing and manipulating an input STUDY structure.
% Only component measures (e.g., dipole locations, scalp maps, spectra,
% ERPs, ERSPs, ITCs) that have been computed and saved in the study EEG
% datasets can be visualized. These can be computed during pre-clustering
% using the GUI-based function pop_preclust() or the equivalent command
% line functions std_preclust(). To use dipole locations for clustering,
% they must first be stored in the EEG dataset structures using dipfit().
% Supported cluster editing functions include new cluster creation, cluster
% merging, outlier rejection, and cluster renaming. Components can also be
% moved from one cluster to another or to the outlier cluster.
% Usage:
% >> STUDY = pop_clustedit(STUDY, ALLEEG, clusters, addui, addgeom);
% Inputs:
% ALLEEG - Top-level EEGLAB vector of loaded EEG structures for the dataset(s)
% in the STUDY. ALLEEG for a STUDY set is typically loaded using
% pop_loadstudy(), or in creating a new STUDY, using pop_createstudy().
% STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG.
%
% Optional inputs:
% clusters - [integer vector] of cluster numbers. These clusters will be visualized
% and manipulated in the pop_clustedit() graphic interface. There are
% restrictions on which clusters can be loaded together. The clusters must
% either originate from the same clustering (same pre_clustering() and
% subsequent pop_clust() execution), or they must all be leaf clusters
% (i.e., clusters with no child clusters) {default: all leaf clusters}.
% addui - [struct] additional uicontrols entries for the graphic
% interface. Must contains the fiels "uilist", "geometry".
%
% Outputs:
% STUDY - The input STUDY set structure modified according to specified user edits,
% if any. Plotted cluster measure means (maps, ERSPs, etc.) are added to
% the STUDY structure after they are first plotted to allow quick replotting.
%
% Graphic interface buttons:
% "Select cluster to plot" - [list box] Displays available clusters to plot (format is
% 'cluster name (number of components)'). The presented clusters depend
% on the optional input variable 'clusters'. Selecting (clicking on) a
% cluster from the list will display the selected cluster components in the
% "Select component(s) to plot" list box. Use the plotting buttons below
% to plot selected measures of the selected cluster. Additional editing
% options (renaming the cluster, rejecting outliers, moving components to
% another cluster) are also available. The option 'All N cluster centroids'
% at the top of the list displays all the clusters in the list except the
% 'Notcluster', 'Outlier' and 'ParentCluster' clusters. Selecting this option
% will plot the cluster centroids (i.e. ERP, ERSP, ...) in a single figure.
% "Select component(s) to plot" - [list box] Displays the ICA components of the currently
% selected cluster (in the "Select cluster to plot" list box). Each component
% has the format: 'subject name, component index'. Multiple components can be
% selected from the list. Use the plotting buttons below to plot different
% measures of the selected components on different figures. Selecting the
% "All components" option is equivalent to using the cluster plotting buttons.
% Additional editing options are reassigning the selected components to
% another cluster or moving them to the outlier cluster.
% "Plot Cluster properties" - [button] Displays in one figure all the mean cluster measures
% (e.g., dipole locations, scalp maps, spectra, etc.) that were calculated
% and saved in the EEG datsets. If there is more than one condition, the ERP
% and the spectrum will have different colors for each condition. The ERSP
% and ITC plots will show only the first condition; clicking on the subplot
% will open a new figure with the different conditions displayed together.
% Uses the command line function std_propplot().
% "Plot scalp maps" - [button] Displays the scalp maps of cluster components.
% If applied to a cluster, scalp maps of the cluster components
% are plotted along with the cluster mean scalp map in one figure.
% If "All # cluster centroids" option is selected, all cluster scalp map
% means are plotted in the same figure. If applied to components, displays
% the scalp maps of the specified cluster components in separate figures.
% Uses the command line functions std_topoplot().
% "Plot ERSPs" - [button] Displays the cluster component ERSPs.
% If applied to a cluster, component ERSPs are plotted in one figure
% (per condition) with the cluster mean ERSP. If "All # cluster centroids"
% option is selected, plots all average ERSPs of the clusters in one figure
% per condition. If applied to components, display the ERSP images of specified
% cluster components in separate figures, using one figure for all conditions.
% Uses the command line functions std_erspplot().
% "Plot ITCs" - [button] Same as "Plot ERSPs" but with ITC.
% Uses the command line functions std_itcplot().
% "Plot dipoles" - [button] Displays the dipoles of the cluster components.
% If applied to a cluster, plots the cluster component dipoles (in blue)
% plus the average cluster dipole (in red). If "All # cluster centroids" option
% is selected, all cluster plots are displayed in one figure each cluster in
% a separate subplot. If applied to components, displays the ERSP images of the
% specified cluster. For specific components displays components dipole (in blue)
% plus the average cluster dipole (in Red) in separate figures.
% Uses the command line functions std_dipplot().
% "Plot spectra" - [button] Displays the cluster component spectra.
% If applied to a cluster, displays component spectra plus the average cluster
% spectrum in bold. For a specific cluster, displays the cluster component
% spectra plus the average cluster spectrum (in bold) in one figure per condition.
% If the "All # cluster centroids" option is selected, displays the average
% spectrum of all clusters in the same figure, with spectrum for different
% conditions (if any) plotted in different colors.
% If applied to components, displays the spectrum of specified cluster
% components in separate figures using one figure for all conditions.
% Uses the command line functions std_specplot().
% "Plot ERPs" - [button] Same as "Plot spectra" but for ERPs.
% Uses the command line functions std_erpplot().
% "Plot ERPimage" - [button] Same as "Plot ERP" but for ERPimave.
% Uses the command line functions std_erpimplot().
% "Create new cluster" - [button] Creates a new empty cluster.
% Opens a popup window in which a name for the new cluster can be entered.
% If no name is given the default name is 'Cls #', where '#' is the next
% available cluster number. For changes to take place, press the popup
% window 'OK' button, else press the 'Cancel' button. After the empty
% cluster is created, components can be moved into it using,
% 'Reassign selected component(s)' (see below). Uses the command line
% function std_createclust().
% "Rename selected cluster" - [button] Renames a cluster using the selected (mnemonic) name.
% Opens a popup window in which a new name for the selected cluster can be
% entered. For changes to take place, press the popup window 'OK' button,
% else press the 'Cancel' button. Uses the command line function std_renameclust().
% "Reject outlier components" - [button] rejects outlier components to an outlier cluster.
% Opens a popup window to specify the outlier threshold. Move outlier
% components that are more than x standard deviations devs from the
% cluster centroid to an outlier cluster. For changes to take place,
% press the popup window 'OK' button, else press the 'Cancel' button.
% Uses the command line function std_rejectoutliers().
% "Merge clusters" - [button] Merges several clusters into one cluster.
% Opens a popup window in which the clusters to merge may be specified
% An optional name can be given to the merged cluster. If no name is given,
% the default name is 'Cls #', where '#' is the next available cluster number.
% For changes to take place, press the popup window 'OK' button, else press
% the 'Cancel' button. Uses the command line function std_mergeclust().
% "Remove selected outlier component(s)" - [button] Moves selected component(s) to the
% outlier cluster. The components that will be moved are the ones selected
% in the "Select component(s) to plot" list box. Opens a popup window in which
% a list of the selected component(s) is presented. For changes to take place,
% press the popup window 'OK' button, else press the 'Cancel' button.
% Uses the command line function std_moveoutlier().
% "Reassign selected component(s)" - [button] Moves selected component(s) from one cluster
% to another. The components that will reassign are the ones selected in the
% "Select component(s) to plot" list box. Opens a popup window in which
% a list of possible clusters to which to move the selected component(s) is
% presented. For changes to take place, press the popup window 'OK' button,
% else press the 'Cancel' button. Uses the command line function std_movecomp().
% "Save STUDY set to disk" - [check box] Saves the STUDY set structure modified according
% to specified user edits to the disk. If no file name is entered will
% overwrite the current STUDY set file.
%
% See also: pop_preclust(), pop_clust().
%
% Authors: Arnaud Delorme, Hilit Serby, Scott Makeig, SCCN/INC/UCSD, October 11, 2004
% Copyright (C) Hilit Serby, SCCN, INC, UCSD, October 11, 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
% Coding notes: Useful information on functions and global variables used.
function [STUDY, com] = pop_clustedit(varargin)
icadefs;
if nargin < 2
help pop_clustedit;
return;
end
if ~isstr(varargin{1})
STUDY = varargin{1};
STUDY.etc.erpparams.topotime = NaN; % [] for channels and NaN for components
STUDY.etc.specparams.topofreq = NaN; % NaN -> GUI disabled
STUDY.etc.erspparams.topotime = NaN;
STUDY.etc.erspparams.topofreq = NaN;
STUDY.etc.erpimparams.topotime = NaN;
STUDY.etc.erpimparams.topotrial = NaN;
STUDY.tmphist = '';
ALLEEG = varargin{2};
clus_comps = 0; % the number of clustered components
if nargin > 2 && ~isempty(varargin{3}) % load specific clusters
cls = varargin{3}; %cluster numbers
N = length(cls); %number of clusters
% Check clusters are either from the same level (same parents) or are
% all leaf clusters.
% Check all input clusters have the same parent
sameparent = 1;
for k = 1: N
% Assess the number of clustered components
if (~strncmpi('Notclust',STUDY.cluster(cls(k)).name,8)) & (~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13))
clus_comps = clus_comps + length(STUDY.cluster(cls(k)).comps);
end
if k == 1
parent = STUDY.cluster(cls(k)).parent;
else
if isempty(parent) % if the first cluster was the parent cluster
parent = STUDY.cluster(cls(k)).parent;
end
% For any other case verify that all clusters have the same parents
if ~(sum(strcmp(STUDY.cluster(cls(k)).parent, parent)) == length(parent)) % different parent
if ~strcmp(STUDY.cluster(cls(k)).parent,'manual') & ~strcmp(parent, 'manual')
% if nither is an empty cluster (which was created manually)
sameparent = 0; % then the clusters have different parents
end
end
end
end
% If not same parent check if all leaf clusters
% ---------------------------------------------
if ~sameparent
for k = 1: N %check if all leaves
if ~isempty(STUDY.cluster(cls(k)).child)
error([ 'pop_clustedit(): All clusters must be from the same level \n' ...
' (i.e., have the same parents or not be child clusters)' ]);
end
end
end
% ploting text etc ...
% --------------------
num_cls = 0;
for k = 1:N
show_options{k+1} = [STUDY.cluster(cls(k)).name ' (' num2str(length(STUDY.cluster(cls(k)).comps)) ' ICs)'];
if (~strncmpi('Notclust',STUDY.cluster(cls(k)).name,8)) & (~strncmpi('Outliers',STUDY.cluster(cls(k)).name,8)) & ...
(~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13))
num_cls = num_cls + 1;
end
end
show_options{1} = ['All ' num2str(num_cls) ' cluster centroids'];
else % load leaf clusters
sameparent = 1;
cls = [];
for k = 2:length(STUDY.cluster)
if isempty(STUDY.cluster(k).child)
if isempty(cls)
parent = STUDY.cluster(k).parent;
elseif ~isempty(STUDY.cluster(k).parent) | ~isempty(parent) % if not both empty
% Check if all parents are the same
if ~(sum(strcmp(STUDY.cluster(k).parent, parent)) == length(parent)) % different parent
if ~strcmp(STUDY.cluster(k).parent,'manual') & ~strcmp(parent, 'manual')
sameparent = 0;
end
end
end
cls = [ cls k];
if ~strncmpi('Notclust',STUDY.cluster(k).name,8)
clus_comps = clus_comps + length(STUDY.cluster(k).comps);
end
end
end
% Plot clusters hierarchically
% ----------------------------
num_cls = 0;
cls = 1:length(STUDY.cluster);
N = length(cls); %number of clusters
show_options{1} = [STUDY.cluster(1).name ' (' num2str(length(STUDY.cluster(1).comps)) ' ICs)'];
cls(1) = 1;
count = 2;
for index1 = 1:length(STUDY.cluster(1).child)
indclust1 = strmatch( STUDY.cluster(1).child(index1), { STUDY.cluster.name }, 'exact');
show_options{count} = [' ' STUDY.cluster(indclust1).name ' (' num2str(length(STUDY.cluster(indclust1).comps)) ' ICs)'];
cls(count) = indclust1;
count = count+1;
for index2 = 1:length( STUDY.cluster(indclust1).child )
indclust2 = strmatch( STUDY.cluster(indclust1).child(index2), { STUDY.cluster.name }, 'exact');
show_options{count} = [' ' STUDY.cluster(indclust2).name ' (' num2str(length(STUDY.cluster(indclust2).comps)) ' ICs)'];
cls(count) = indclust2;
count = count+1;
for index3 = 1:length( STUDY.cluster(indclust2).child )
indclust3 = strmatch( STUDY.cluster(indclust2).child(index3), { STUDY.cluster.name }, 'exact');
show_options{count} = [' ' STUDY.cluster(indclust3).name ' (' num2str(length(STUDY.cluster(indclust3).comps)) ' ICs)'];
cls(count) = indclust3;
count = count+1;
end;
end;
end;
show_options = { ['All cluster centroids'] show_options{:} };
end
all_comps = length(STUDY.cluster(1).comps);
show_clust = [ 'pop_clustedit(''showclust'',gcf);'];
show_comps = [ 'pop_clustedit(''showcomplist'',gcf);'];
plot_clus_maps = [ 'pop_clustedit(''topoplot'',gcf); '];
plot_comp_maps = [ 'pop_clustedit(''plotcomptopo'',gcf); '];
plot_clus_ersps = ['pop_clustedit(''erspplot'',gcf); '];
plot_comp_ersps = ['pop_clustedit(''plotcompersp'',gcf); '];
plot_clus_itcs = ['pop_clustedit(''itcplot'',gcf); '];
plot_comp_itcs = ['pop_clustedit(''plotcompitc'',gcf); '];
plot_clus_erpim = ['pop_clustedit(''erpimageplot'',gcf); '];
plot_comp_erpim = ['pop_clustedit(''plotcomperpimage'',gcf); '];
plot_clus_spectra = ['pop_clustedit(''specplot'',gcf); '];
plot_comp_spectra = ['pop_clustedit(''plotcompspec'',gcf); '];
plot_clus_erp = ['pop_clustedit(''erpplot'',gcf); '];
plot_comp_erp = ['pop_clustedit(''plotcomperp'',gcf); '];
plot_clus_dip = ['pop_clustedit(''dipplot'',gcf); '];
plot_comp_dip = ['pop_clustedit(''plotcompdip'',gcf); '];
plot_clus_sum = ['pop_clustedit(''plotsum'',gcf); '];
plot_comp_sum = ['pop_clustedit(''plotcompsum'',gcf); '];
rename_clust = ['pop_clustedit(''renameclust'',gcf);'];
move_comp = ['pop_clustedit(''movecomp'',gcf);'];
move_outlier = ['pop_clustedit(''moveoutlier'',gcf);'];
create_clus = ['pop_clustedit(''createclust'',gcf);'];
reject_outliers = ['pop_clustedit(''rejectoutliers'',gcf);'];
merge_clusters = ['pop_clustedit(''mergeclusters'',gcf);'];
dip_opt = ['pop_clustedit(''dip_opt'',gcf);'];
erp_opt = ['pop_clustedit(''erp_opt'',gcf);'];
spec_opt = ['pop_clustedit(''spec_opt'',gcf);'];
ersp_opt = ['pop_clustedit(''ersp_opt'',gcf);'];
erpim_opt = ['pop_clustedit(''erpim_opt'',gcf);'];
stat_opt = ['pop_clustedit(''stat_opt'',gcf);'];
saveSTUDY = [ 'set(findobj(''parent'', gcbf, ''userdata'', ''save''), ''enable'', fastif(get(gcbo, ''value'')==1, ''on'', ''off''));' ];
browsesave = [ '[filename, filepath] = uiputfile2(''*.study'', ''Save STUDY with .study extension -- pop_clust()''); ' ...
'set(findobj(''parent'', gcbf, ''tag'', ''studyfile''), ''string'', [filepath filename]);' ];
% Create default ERSP / ITC time/freq. paramters
% ----------------------------------------------
if isempty(ALLEEG)
error('STUDY contains no datasets');
end
% enable buttons
% --------------
filename = STUDY.design(STUDY.currentdesign).cell(1).filebase;
if exist([filename '.icaspec']) , spec_enable = 'on'; else spec_enable = 'off'; end;
if exist([filename '.icaerp'] ) , erp_enable = 'on'; else erp_enable = 'off'; end;
if exist([filename '.icaerpim'] ), erpim_enable = 'on'; else erpim_enable = 'off'; end;
if exist([filename '.icaersp']) , ersp_enable = 'on'; else ersp_enable = 'off'; end;
filename = fullfile( ALLEEG(1).filepath, ALLEEG(1).filename(1:end-4));
if exist([filename '.icatopo']), scalp_enable = 'on'; else scalp_enable = 'off'; end;
if isfield(ALLEEG(1).dipfit, 'model'), dip_enable = 'on'; else dip_enable = 'off'; end;
% userdata below
% --------------
fig_arg{1}{1} = ALLEEG;
fig_arg{1}{2} = STUDY;
fig_arg{1}{3} = cls;
fig_arg{2} = N;
str_name = sprintf('STUDY ''%s'' - ''%s'' component clusters', STUDY.name, STUDY.design(STUDY.currentdesign).name);
if length(str_name) > 80, str_name = [ str_name(1:80) '...''' ]; end;
if length(cls) > 1, vallist = 1; else vallist = 2; end;
geomline = [1 0.35 1];
geometry = { [4 .1 .1 .1 .1] [1] geomline geomline geomline geomline geomline geomline geomline geomline ...
geomline geomline [1] geomline geomline geomline };
geomvert = [ 1 .5 1 3 1 1 1 1 1 1 1 1 1 1 1 1];
uilist = { ...
{'style' 'text' 'string' str_name ...
'FontWeight' 'Bold' 'HorizontalAlignment' 'center'} {} {} {} {} {} ...
{'style' 'text' 'string' 'Select cluster to plot' 'FontWeight' 'Bold' } {} ...
{'style' 'text' 'string' 'Select component to plot ' 'FontWeight' 'Bold'} ...
{'style' 'listbox' 'string' show_options 'value' vallist 'tag' 'clus_list' 'Callback' show_clust } ...
{'style' 'pushbutton' 'enable' 'on' 'string' 'STATS' 'Callback' stat_opt } ...
{'style' 'listbox' 'string' '' 'tag' 'clust_comp' 'max' 2 'min' 1 'callback' show_comps } ...
{'style' 'pushbutton' 'enable' scalp_enable 'string' 'Plot scalp maps' 'Callback' plot_clus_maps} {} ...
{'style' 'pushbutton' 'enable' scalp_enable 'string' 'Plot scalp map(s)' 'Callback' plot_comp_maps}...
{'style' 'pushbutton' 'enable' dip_enable 'string' 'Plot dipoles' 'Callback' plot_clus_dip} ...
{'style' 'pushbutton' 'enable' erp_enable 'string' 'Params' 'Callback' dip_opt } ...
{'style' 'pushbutton' 'enable' dip_enable 'string' 'Plot dipole(s)' 'Callback' plot_comp_dip}...
{'style' 'pushbutton' 'enable' erp_enable 'string' 'Plot ERPs' 'Callback' plot_clus_erp} ...
{'style' 'pushbutton' 'enable' erp_enable 'string' 'Params' 'Callback' erp_opt } ...
{'style' 'pushbutton' 'enable' erp_enable 'string' 'Plot ERP(s)' 'Callback' plot_comp_erp} ...
{'style' 'pushbutton' 'enable' spec_enable 'string' 'Plot spectra' 'Callback' plot_clus_spectra} ...
{'style' 'pushbutton' 'enable' spec_enable 'string' 'Params' 'Callback' spec_opt } ...
{'style' 'pushbutton' 'enable' spec_enable 'string' 'Plot spectra' 'Callback' plot_comp_spectra} ...
{'style' 'pushbutton' 'enable' erpim_enable 'string' 'Plot ERPimage' 'Callback' plot_clus_erpim} ...
{'style' 'pushbutton' 'enable' erpim_enable 'string' 'Params' 'Callback' erpim_opt } ...
{'style' 'pushbutton' 'enable' erpim_enable 'string' 'Plot ERPimage(s)' 'Callback' plot_comp_erpim} ...
{'style' 'pushbutton' 'enable' ersp_enable 'string' 'Plot ERSPs' 'Callback' plot_clus_ersps} ...
{'vertexpand' 2.1 'style' 'pushbutton' 'enable' ersp_enable 'string' 'Params' 'Callback' ersp_opt } ...
{'style' 'pushbutton' 'enable' ersp_enable 'string' 'Plot ERSP(s)' 'Callback' plot_comp_ersps} ...
{'style' 'pushbutton' 'enable' ersp_enable 'string' 'Plot ITCs' 'Callback' plot_clus_itcs} { } ...
{'style' 'pushbutton' 'enable' ersp_enable 'string' 'Plot ITC(s)' 'Callback' plot_comp_itcs} ...
{} {}... %{'style' 'pushbutton' 'string' 'Plot cluster properties' 'Callback' plot_clus_sum 'enable' 'off'} {} ...
{'style' 'pushbutton' 'string' 'Plot component properties' 'Callback' plot_comp_sum 'enable' 'off'} ... % nima, was off
{} ...
{'style' 'pushbutton' 'string' 'Create new cluster' 'Callback' create_clus} {} ...
{'style' 'pushbutton' 'string' 'Reassign selected component(s)' 'Callback' move_comp} ...
{'style' 'pushbutton' 'string' 'Rename selected cluster' 'Callback' rename_clust } {} ...
{'style' 'pushbutton' 'string' 'Remove selected outlier comps.' 'Callback' move_outlier} ...
{'style' 'pushbutton' 'string' 'Merge clusters' 'Callback' merge_clusters 'enable' 'off' } {} ...
{'style' 'pushbutton' 'string' 'Auto-reject outlier components' 'Callback' reject_outliers 'enable' 'off' } };
% additional UI given on the command line
% ---------------------------------------
if nargin > 3
addui = varargin{4};
if ~isfield(addui, 'uilist')
error('Additional GUI definition (argument 4) requires the field "uilist"');
end;
if ~isfield(addui, 'geometry')
addui.geometry = mat2cell(ones(1,length(addui.uilist)));
end;
uilist = { uilist{:}, addui.uilist{:} };
geometry = { geometry{:} addui.geometry{:} };
geomvert = [ geomvert ones(1,length(addui.geometry)) ];
end;
[out_param userdat] = inputgui( 'geometry' , geometry, 'uilist', uilist, ...
'helpcom', 'pophelp(''pop_clustoutput'')', ...
'title', 'View and edit current component clusters -- pop_clustedit()' , 'userdata', fig_arg, ...
'geomvert', geomvert, 'eval', show_clust );
if ~isempty(userdat)
ALLEEG = userdat{1}{1};
STUDY = userdat{1}{2};
end
% history
% -------
com = STUDY.tmphist;
STUDY = rmfield(STUDY, 'tmphist');
else
hdl = varargin{2}; %figure handle
userdat = get(varargin{2}, 'userdat');
ALLEEG = userdat{1}{1};
STUDY = userdat{1}{2};
cls = userdat{1}{3};
clus = get(findobj('parent', hdl, 'tag', 'clus_list'), 'value');
comp_ind = get(findobj('parent', hdl, 'tag', 'clust_comp'), 'Value');
if clus == 1 & length(cls) == 1
warndlg2('No cluster', 'No cluster');
return;
end;
try
switch varargin{1}
case {'plotcomptopo', 'plotcompersp','plotcompitc','plotcompspec', 'plotcomperp', 'plotcompdip', 'plotcomperpimage'}
plotting_option = varargin{1};
plotting_option = [ plotting_option(9:end) 'plot' ];
if (clus ~= 1 ) %specific cluster
if comp_ind(1) ~= 1 % check that not all comps in cluster are requested
subject = STUDY.datasetinfo( STUDY.cluster(cls(clus-1)).sets(1,comp_ind-1)).subject;
a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''clusters'',' num2str(cls(clus-1)) ', ''comps'', ' num2str(comp_ind-1) ' );' ];
eval(a); STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
else
a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''clusters'',' num2str(cls(clus-1)) ', ''plotsubjects'', ''on'' );' ];
eval(a); STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
end
else
comp_list = get(findobj('parent', hdl, 'tag', 'clust_comp'), 'String');
comp_name = comp_list(comp_ind);
for ci = 1:length(comp_name)
num_comps = 0;
tmp = strfind(comp_name{ci},'''');
clust_name = comp_name{ci}(tmp(1)+1:tmp(end)-1);
for k = 1:length(cls)
if ~strncmpi('Notclust',STUDY.cluster(cls(k)).name,8) & ~strncmpi('Outliers',STUDY.cluster(cls(k)).name,8) & ...
(~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13))
if strcmpi(STUDY.cluster(cls(k)).name, clust_name)
cind = comp_ind(ci) - num_comps; % component index in the cluster
subject = STUDY.datasetinfo( STUDY.cluster(cls(k)).sets(1,cind)).subject;
a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''clusters'',' num2str(cls(k)) ', ''comps'',' num2str(cind) ' );' ];
eval(a); STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
break;
else
num_comps = num_comps + length(STUDY.cluster(cls(k)).comps);
end
end
end
end
end
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat);
case {'topoplot', 'erspplot', 'itcplot', 'specplot', 'erpplot', 'dipplot', 'erpimageplot' }
plotting_option = varargin{1};
plotting_option = [ plotting_option(1:end-4) 'plot' ];
if (clus ~= 1 ) % specific cluster option
if ~isempty(STUDY.cluster(cls(clus-1)).comps)
a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''clusters'',' num2str(cls(clus-1)) ');' ];
eval(a); STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
end
else % all clusters
% All clusters does not include 'Notclust' 'ParentCluster' and 'Outliers' clusters.
tmpcls = [];
for k = 1:length(cls)
if ~strncmpi(STUDY.cluster(cls(k)).name,'Notclust',8) & ~strncmpi(STUDY.cluster(cls(k)).name,'Outliers',8) & ...
(~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13)) & ~isempty(STUDY.cluster(cls(k)).comps)
tmpcls = [ tmpcls cls(k)];
end
end
a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''clusters'',[' num2str(tmpcls) ']);' ];
%if strcmpi(plotting_option, 'dipplot'), a = [a(1:end-2) ',''mode'', ''together'');' ]; end;
eval(a); STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
end
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat);
case 'dip_opt' % save the list of selected chaners
[STUDY com] = pop_dipparams(STUDY);
if ~isempty(com)
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com);
end;
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat); %update information (STUDY)
case 'erp_opt' % save the list of selected chaners
[STUDY com] = pop_erpparams(STUDY);
if ~isempty(com)
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com);
end;
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat); %update information (STUDY)
case 'stat_opt' % save the list of selected chaners
[STUDY com] = pop_statparams(STUDY);
if ~isempty(com)
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com);
end;
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat); %update information (STUDY)
case 'spec_opt' % save the list of selected channels
[STUDY com] = pop_specparams(STUDY);
if ~isempty(com)
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com);
end;
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat); %update information (STUDY)
case 'erpim_opt' % save the list of selected channels
[STUDY com] = pop_erpimparams(STUDY);
if ~isempty(com)
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com);
end;
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat); %update information (STUDY)
case 'ersp_opt' % save the list of selected channels
[STUDY com] = pop_erspparams(STUDY);
if ~isempty(com)
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com);
end;
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat); %update information (STUDY)
case 'showcomplist' % save the list of selected clusters
clust = get(findobj('parent', hdl, 'tag', 'clus_list') , 'value');
comp = get(findobj('parent', hdl, 'tag', 'clust_comp'), 'value');
N = userdat{2};
count = 1;
if clust ~= 1 %specific cluster
STUDY.cluster(cls(clust-1)).selected = comp;
end;
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat); %update information (STUDY)
case 'showclust'
cind = get(findobj('parent', hdl, 'tag', 'clus_list'), 'value');
N = userdat{2};
count = 1;
selected = get(findobj('parent', hdl, 'tag', 'clust_comp'), 'value');
if cind ~= 1 %specific cluster
len = length(STUDY.cluster(cls(cind-1)).comps);
compid = cell(len+1,1);
compid{1} = 'All components';
% Convert from components numbering to the indexing form 'setXcomY'
for l = 1:len % go over the components of the cluster
if ~isnan(STUDY.cluster(cls(cind-1)).sets(1,l))
subject = STUDY.datasetinfo(STUDY.cluster(cls(cind-1)).sets(1,l)).subject;
compid{l+1} = [ subject ' IC' num2str(STUDY.cluster(cls(cind-1)).comps(1,l)) ];
end
end
if isfield(STUDY.cluster, 'selected')
if ~isempty(STUDY.cluster(cls(cind-1)).selected)
selected = min(STUDY.cluster(cls(cind-1)).selected, 1+length(STUDY.cluster(cls(cind-1)).comps(1,:)));
STUDY.cluster(cls(cind-1)).selected = selected;
end;
end;
else % All clusters accept 'Notclust' and 'Outliers'
count = 1;
for k = 1: length(cls)
if ~strncmpi('Notclust',STUDY.cluster(cls(k)).name,8) & ~strncmpi('Outliers',STUDY.cluster(cls(k)).name,8) & ...
(~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13))
for l = 1: length(STUDY.cluster(cls(k)).comps)
if ~isnan(STUDY.cluster(cls(k)).sets(1,l))
subject = STUDY.datasetinfo(STUDY.cluster(cls(k)).sets(1,l)).subject; % This line chokes on NaNs. TF 2007.05.31
compid{count} = [ '''' STUDY.cluster(cls(k)).name ''' comp. ' ...
num2str(l) ' (' subject ' IC' num2str(STUDY.cluster(cls(k)).comps(l)) ')'];
count = count +1;
end
end
end
end
end
if selected > length(compid), selected = 1; end;
set(findobj('parent', hdl, 'tag', 'clust_comp'), 'value', selected, 'String', compid);
case 'plotsum'
if clus ~= 1 % specific cluster option
[STUDY] = std_propplot(STUDY, ALLEEG, 'cluster', cls(clus-1));
% update Study history
a = ['STUDY = std_propplot(STUDY, ALLEEG, ''cluster'', ' num2str(cls(clus-1)) ' );' ];
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
else % all clusters
% All clusters does not include 'Notclust' and 'Outliers' clusters.
tmpcls = [];
for k = 1:length(cls)
if ~strncmpi(STUDY.cluster(cls(k)).name,'Notclust',8) & ~strncmpi(STUDY.cluster(cls(k)).name,'Outliers',8) & ...
(~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13))
tmpcls = [tmpcls cls(k)];
end
end
[STUDY] = std_propplot(STUDY, ALLEEG, 'cluster', tmpcls);
% update Study history
a = ['STUDY = std_propplot(STUDY, ALLEEG, ''cluster'', [' num2str(tmpcls) '] );' ];
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
end
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat);
case 'plotcompsum'
for ci = 1 : length(comp_ind)
% place holder for component properties % nima
end
case 'renameclust'
STUDY.saved = 'no';
clus_name_list = get(findobj('parent', hdl, 'tag', 'clus_list'), 'String');
clus_num = get(findobj('parent', hdl, 'tag', 'clus_list'), 'Value') -1;
if clus_num == 0 % 'all clusters' option
return;
end
% Don't rename 'Notclust' and 'Outliers' clusters.
if strncmpi('Notclust',STUDY.cluster(cls(clus_num)).name,8) | strncmpi('Outliers',STUDY.cluster(cls(clus_num)).name,8) | ...
strncmpi('ParentCluster',STUDY.cluster(cls(clus_num)).name,13)
warndlg2('The ParentCluster, Outliers, and Notclust clusters cannot be renamed');
return;
end
old_name = STUDY.cluster(cls(clus_num)).name;
rename_param = inputgui( { [1] [1] [1]}, ...
{ {'style' 'text' 'string' ['Rename ' old_name] 'FontWeight' 'Bold'} {'style' 'edit' 'string' '' 'tag' 'clus_rename' } {} }, ...
'', 'Rename cluster - from pop_clustedit()' );
if ~isempty(rename_param) %if not canceled
new_name = rename_param{1};
STUDY = std_renameclust(STUDY, ALLEEG, cls(clus_num), new_name);
% update Study history
a = ['STUDY = std_renameclust(STUDY, ALLEEG, ' num2str(cls(clus_num)) ', ' STUDY.cluster(cls(clus_num)).name ');'];
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
% Renaming cluster in list
new_name = [ STUDY.cluster(cls(clus_num)).name ' (' num2str(length(STUDY.cluster(cls(clus_num)).comps)) ' ICs)'];
clus_name_list{clus_num+1} = renameclust( clus_name_list{clus_num+1}, new_name);
% Renaming Outlier cluster if exist
outlier_clust = std_findoutlierclust(STUDY,cls(clus_num));
if outlier_clust ~= 0
new_outliername = [ STUDY.cluster(cls(outlier_clust)).name ' (' num2str(length(STUDY.cluster(cls(outlier_clust)).comps)) ' ICs)'];
clus_name_list{outlier_clust+1} = renameclust( clus_name_list{outlier_clust+1}, new_outliername);
end
set(findobj('parent', hdl, 'tag', 'clus_list'), 'String', clus_name_list);
set(findobj('parent', hdl, 'tag', 'clus_rename'), 'String', '');
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat); %update STUDY
end
case 'movecomp'
STUDY.saved = 'no';
old_clus = get(findobj('parent', hdl, 'tag', 'clus_list'), 'value') -1;
comp_ind = get(findobj('parent', hdl, 'tag', 'clust_comp'), 'Value');
if old_clus == 0 % 'all clusters' option
return;
end
% Don't reassign components of 'Notclust' or the 'ParentCluster'.
if strncmpi('ParentCluster',STUDY.cluster(cls(old_clus)).name,13)
warndlg2('Cannot reassign components of ''ParentCluster''.');
return;
end
old_name = STUDY.cluster(cls(old_clus)).name;
ncomp = length(comp_ind); % number of selected components
optionalcls =[];
for k = 1:length(cls)
if (~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13)) & (k~= old_clus)
optionalcls = [optionalcls cls(k)];
end
end
reassign_param = inputgui( { [1] [1] [1]}, ...
{ {'style' 'text' 'string' strvcat(['Reassign ' fastif(ncomp >1, [num2str(length(comp_ind)) ' currently selected components'], ...
'currently selected component') ], ...
[' from ' old_name ' to the cluster selected below']) 'FontWeight' 'Bold'} ...
{'style' 'listbox' 'string' {STUDY.cluster(optionalcls).name} 'tag' 'new_clus'} {} }, ...
'', 'Reassign cluster - from pop_clustedit()' ,[] , 'normal', [2 3 1] );
if ~isempty(reassign_param) %if not canceled
new_clus = reassign_param{1};
comp_to_disp = get(findobj('parent', hdl, 'tag', 'clust_comp'), 'String');
if strcmp(comp_to_disp{comp_ind(1)},'All components')
warndlg2('Cannot move all the components of the cluster - abort move components', 'Aborting move components');
return;
end
STUDY = std_movecomp(STUDY, ALLEEG, cls(old_clus), optionalcls(new_clus), comp_ind - 1);
% update Study history
a = ['STUDY = std_movecomp(STUDY, ALLEEG, ' num2str(cls(old_clus)) ', ' num2str(optionalcls(new_clus)) ', [' num2str(comp_ind - 1) ']);'];
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
newind = find(cls == optionalcls(new_clus));
% update GUI
% ----------
clus_name_list = get(findobj('parent', hdl, 'tag', 'clus_list'), 'String');
newname = [STUDY.cluster(optionalcls(new_clus)).name ' (' num2str(length(STUDY.cluster(optionalcls(new_clus)).comps)) ' ICs)'];
clus_name_list{newind+1} = renameclust( clus_name_list{newind+1}, newname);
newname = [STUDY.cluster(cls(old_clus)).name ' (' num2str(length(STUDY.cluster(cls(old_clus)).comps)) ' ICs)'];
clus_name_list{old_clus+1} = renameclust( clus_name_list{old_clus+1}, newname);
set( findobj('parent', hdl, 'tag', 'clus_list'), 'String', clus_name_list);
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat);
pop_clustedit('showclust',hdl);
end
case 'moveoutlier'
STUDY.saved = 'no';
old_clus = get(findobj('parent', hdl, 'tag', 'clus_list'), 'value') -1;
comp_ind = get(findobj('parent', hdl, 'tag', 'clust_comp'), 'Value');
if ~isempty(find(comp_ind ==1))
warndlg2('Cannot remove all the cluster components');
return;
end
if old_clus == 0 % 'all clusters' option
return;
end
if strncmpi('Notclust',STUDY.cluster(cls(old_clus)).name,8) | strncmpi('ParentCluster',STUDY.cluster(cls(old_clus)).name,13) % There are no outliers to 'Notclust'
warndlg2('Cannot reassign components of ''Notclust'' or ''ParentCluster''.');
return;
end
comp_list = get(findobj('parent', hdl, 'tag', 'clust_comp'), 'String');
ncomp = length(comp_ind);
old_name = STUDY.cluster(cls(old_clus)).name;
if strncmpi('Outliers',STUDY.cluster(cls(old_clus)).name,8) % There are no outliers of 'Outliers'
warndlg2('Cannot use ''Outliers'' clusters for this option.');
return;
end
reassign_param = inputgui( { [1] [1] [1]}, ...
{ {'style' 'text' 'string' ['Remove ' fastif(ncomp >1, [num2str(length(comp_ind)) ' currently selected components below '], 'currently selected component below ') ...
'from ' old_name ' to its outlier cluster?'] 'FontWeight' 'Bold'} ...
{'style' 'listbox' 'string' {comp_list{comp_ind}} 'tag' 'new_clus'} {} }, ...
'', 'Remove outliers - from pop_clustedit()' ,[] , 'normal', [1 3 1] );
if ~isempty(reassign_param) %if not canceled
STUDY = std_moveoutlier(STUDY, ALLEEG, cls(old_clus), comp_ind - 1);
clus_name_list = get(findobj('parent', hdl, 'tag', 'clus_list'), 'String');
outlier_clust = std_findoutlierclust(STUDY,cls(old_clus)); %find the outlier cluster for this cluster
oind = find(cls == outlier_clust); % the outlier clust index (if already exist) in the cluster list GUI
if ~isempty(oind) % the outlier clust is already presented in the cluster list GUI
newname = [STUDY.cluster(outlier_clust).name ' (' num2str(length(STUDY.cluster(outlier_clust).comps)) ' ICs)'];
clus_name_list{oind+1} = renameclust( clus_name_list{oind+1}, newname);
elseif outlier_clust == length(STUDY.cluster) % update the list with the Outlier cluster (if didn't exist before)
clus_name_list{end+1} = [STUDY.cluster(outlier_clust).name ' (' num2str(length(STUDY.cluster(outlier_clust).comps)) ' ICs)'];
userdat{2} = userdat{2} + 1; % update N, number of clusters in edit window
cls(end +1) = length(STUDY.cluster); % update the GUI clusters list with the outlier cluster
userdat{1}{3} = cls; % update cls, the cluster indices in edit window
end
newname = [STUDY.cluster(cls(old_clus)).name ' (' num2str(length(STUDY.cluster(cls(old_clus)).comps)) ' ICs)'];
clus_name_list{old_clus+1} = renameclust(clus_name_list{old_clus+1}, newname);
set(findobj('parent', hdl, 'tag', 'clus_list'), 'String', clus_name_list);
% update Study history
a = ['STUDY = std_moveoutlier(STUDY, ALLEEG, ' num2str(cls(old_clus)) ', [' num2str(comp_ind - 1) ']);'];
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat);
pop_clustedit('showclust',hdl);
end
case 'rejectoutliers'
STUDY.saved = 'no';
clus = get(findobj('parent', hdl, 'tag', 'clus_list'), 'Value') -1;
if clus
std_name = STUDY.cluster(cls(clus)).name;
% Cannot reject outliers from 'Notclust', 'ParentCluster' and 'Outlier' clusters
if strncmpi('Notclust',std_name,8) | strncmpi('ParentCluster', std_name,13) | ...
strncmpi('Outliers',std_name,8)
warndlg2('Cannot reject outliers of ''Notclust'' or ''Outliers'' or ''ParentCluster'' clusters.');
return;
end
clusters = cls(clus);
else
std_name = 'All clusters';
clusters = [];
for k = 1:length(cls)
if ~strncmpi('Notclust',STUDY.cluster(cls(k)).name,8) & ~strncmpi('Outliers',STUDY.cluster(cls(k)).name,8) & ...
~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13)
clusters = [ clusters cls(k)];
end
end
end
reject_param = inputgui( { [1] [1] [4 1 2] [1]}, ...
{ {'style' 'text' 'string' ['Reject "' std_name '" outliers ' ] 'FontWeight' 'Bold'} {} ...
{'style' 'text' 'string' 'Move outlier components that are more than'} {'style' 'edit' 'string' '3' 'tag' 'outliers_std' } ...
{'style' 'text' 'string' 'standard deviations' } ...
{'style' 'text' 'string' [ 'from the "' std_name '" centroid to an outlier cluster.']} }, ...
'', 'Reject outliers - from pop_clustedit()' );
if ~isempty(reject_param) %if not canceled
ostd = reject_param{1}; % the requested outlier std
[STUDY] = std_rejectoutliers(STUDY, ALLEEG, clusters, str2num(ostd));
% update Study history
a = ['STUDY = std_rejectoutliers(STUDY, ALLEEG, [ ' num2str(clusters) ' ], ' ostd ');'];
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
clus_name_list = get(findobj('parent', hdl, 'tag', 'clus_list'), 'String');
for k = 1:length(clusters)
outlier_clust = std_findoutlierclust(STUDY,clusters(k)); %find the outlier cluster for this cluster
oind = find(cls == outlier_clust); % the outlier clust index (if already exist) in the cluster list GUI
if ~isempty(oind) % the outlier clust is already presented in the cluster list GUI
newname = [STUDY.cluster(outlier_clust).name ' (' num2str(length(STUDY.cluster(outlier_clust).comps)) ' ICs)'];
clus_name_list{oind+1} = renameclust( clus_name_list{oind+1}, newname);
else % update the list with the outlier cluster
clus_name_list{end+1} = [STUDY.cluster(outlier_clust).name ' (' num2str(length(STUDY.cluster(outlier_clust).comps)) ' ICs)'];
userdat{2} = userdat{2} + 1; % update N, number of clusters in edit window
cls(end +1) = outlier_clust; % update the GUI clusters list with the outlier cluster
userdat{1}{3} = cls; % update cls, the cluster indices in edit window
end
clsind = find(cls == clusters(k));
newname = [STUDY.cluster(clusters(k)).name ' (' num2str(length(STUDY.cluster(clusters(k)).comps)) ' ICs)'];
clus_name_list{clsind+1} = renameclust( clus_name_list{clsind+1}, newname);
set(findobj('parent', hdl, 'tag', 'clus_list'), 'String', clus_name_list);
end
% If outlier cluster doesn't exist in the GUI window add it
userdat{1}{2} = STUDY;
set(hdl, 'userdat',userdat);
pop_clustedit('showclust',hdl);
end
case 'createclust'
STUDY.saved = 'no';
create_param = inputgui( { [1] [1 1] [1]}, ...
{ {'style' 'text' 'string' 'Create new empty cluster' 'FontWeight' 'Bold'} ...
{'style' 'text' 'string' 'Enter cluster name:'} {'style' 'edit' 'string' '' } {} }, ...
'', 'Create new empty cluster - from pop_clustedit()' );
if ~isempty(create_param) %if not canceled
clus_name = create_param{1}; % the name of the new cluster
[STUDY] = std_createclust(STUDY, ALLEEG, 'name', clus_name);
% Update cluster list
clus_name_list = get(findobj('parent', hdl, 'tag', 'clus_list'), 'String');
clus_name_list{end+1} = [STUDY.cluster(end).name ' (0 ICs)']; %update the cluster list with the new cluster
% update the first option on the GUI list : 'All 10 cluster centroids'
% with the new number of cluster centroids
ti = strfind(clus_name_list{1},'cluster'); %get the number of clusters centroid
cent = num2str(str2num(clus_name_list{1}(5:ti-2))+1); % new number of centroids
clus_name_list{1} = [clus_name_list{1}(1:4) cent clus_name_list{1}(ti-1:end)]; %update list
set(findobj('parent', hdl, 'tag', 'clus_list'), 'String', clus_name_list);
% update Study history
if isempty(clus_name)
a = ['STUDY = std_createclust(STUDY, ALLEEG);'];
else
a = ['STUDY = std_createclust(STUDY, ALLEEG, ''name'', ' clus_name ');'];
end
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
userdat{1}{2} = STUDY;
userdat{2} = userdat{2} + 1; % update N, the number of cluster options in edit window
cls(end +1) = length(STUDY.cluster); % update the GUI clusters list with the new cluster
userdat{1}{3} = cls; % update cls, the cluster indices in edit window
set(hdl, 'userdat',userdat); %update STUDY, cls and N
end
case 'mergeclusters'
STUDY.saved = 'no';
clus_names = get(findobj('parent', hdl, 'tag', 'clus_list'), 'string') ;
optionalcls =[];
for k = 2:length(clus_names)
if (~strncmpi('Notclust',clus_names{k},8)) & (~strncmpi('Outliers',clus_names{k},8)) & ...
(~strncmpi('ParentCluster',clus_names{k},13))
optionalcls = [optionalcls k];
end
end
reassign_param = inputgui( { [1] [1] [1] [2 1] [1]}, ...
{ {'style' 'text' 'string' 'Select clusters to Merge' 'FontWeight' 'Bold'} ...
{'style' 'listbox' 'string' clus_names(optionalcls) 'tag' 'new_clus' 'max' 3 'min' 1} {} ...
{'style' 'text' 'string' 'Optional, enter a name for the merged cluster:' 'FontWeight' 'Bold'} ...
{'style' 'edit' 'string' ''} {} }, ...
'', 'Merge clusters - from pop_clustedit()' ,[] , 'normal', [1 3 1 1 1] );
if ~isempty(reassign_param)
std_mrg = cls(optionalcls(reassign_param{1})-1);
name = reassign_param{2};
allleaves = 1;
N = userdat{2};
for k = 1: N %check if all leaves
if ~isempty(STUDY.cluster(cls(k)).child)
allleaves = 0;
end
end
[STUDY] = std_mergeclust(STUDY, ALLEEG, std_mrg, name);
%
% update Study history
%
if isempty(name)
a = ['STUDY = std_mergeclust(STUDY, ALLEEG, [' num2str(std_mrg) ']);'];
else
a = ['STUDY = std_mergeclust(STUDY, ALLEEG, [' num2str(std_mrg) '], ' name ');'];
end
STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a);
userdat{1}{2} = STUDY;
%
% Replace the merged clusters with the one new merged cluster
% in the GUI if all clusters are leaves
%
if allleaves
%
% Update cluster list
%
clus_names{end+1} = [STUDY.cluster(end).name ' (' num2str(length(STUDY.cluster(end).comps)) ' ICs)'];
%
% update the cluster list with the new cluster
%
clus_names([optionalcls(reassign_param{1})]) = [];
cls = setdiff_bc(cls, std_mrg); % remove from the GUI clusters list the merged clusters
cls(end+1) = length(STUDY.cluster); % update the GUI clusters list with the new cluster
N = length(cls);
%
% update the first option on the GUI list : 'All 10 cluster centroids'
% with the new number of cluster centroids
%
ti = strfind(clus_names{1},'cluster'); %get the number of clusters centroid
cent = num2str(str2num(clus_names{1}(5:ti-2))+1- length(std_mrg)); % new number of centroids
clus_names{1} = [clus_names{1}(1:4) cent clus_names{1}(ti-1:end)]; %update list
set(findobj('parent', hdl, 'tag', 'clus_list'), 'String', clus_names);
%
% update Study history
%
userdat{2} = N; % update N, the number of cluster options in edit window
userdat{1}{3} = cls; % update cls, the cluster indices in edit window
end
set(hdl, 'userdat',userdat); %update information (STUDY)
pop_clustedit('showclust',hdl);
end
end
catch
eeglab_error;
end;
end
function newname = renameclust(oldname, newname);
tmpname = deblank(oldname(end:-1:1));
strpos = strfind(oldname, tmpname(end:-1:1));
newname = [ oldname(1:strpos-1) newname ];
|
github
|
lcnhappe/happe-master
|
std_findsameica.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_findsameica.m
| 2,400 |
utf_8
|
ee2f9d014b8e1c3c6c6844f0fb9e8193
|
% std_findsameica() - find groups of datasets with identical ICA decomposiotions
% (search identical weight*sphere matrices)
%
% Usage:
% >> clusters = std_findsameica(ALLEEG);
% >> clusters = std_findsameica(ALLEEG,icathreshold);
% Inputs:
% ALLEEG - a vector of loaded EEG dataset structures of all sets
% in the STUDY set.
% icathreshold - Threshold to compare icaweights
%
% Outputs:
% cluster - cell array of groups of datasets
%
% Authors: Arnaud Delorme, SCCN, INC, UCSD, July 2009-
% 2016 change: as of May 2016, the function now compares the product of the
% weight and the sphere matrices instead of just the weight
% matrices.
% 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
% Coding notes: Useful information on functions and global variables used.
function cluster = std_findsameica(ALLEEG, varargin);
% 6/2/2014 Ramon : Allow ica threshold as input.
if nargin == 1
icathreshold = 2e-5;
elseif nargin == 2;
icathreshold = varargin{1};
end
cluster = { [1] };
for index = 2:length(ALLEEG)
found = 0;
for c = 1:length(cluster)
w1 = ALLEEG(cluster{c}(1)).icaweights*ALLEEG(cluster{c}(1)).icasphere;
w2 = ALLEEG(index).icaweights*ALLEEG(index).icasphere;
if all(size(w1) == size(w2))
%if isequal(ALLEEG(cluster{c}(1)).icaweights, ALLEEG(index).icaweights)
if sum(sum(abs(w1-w2))) < icathreshold
cluster{c}(end+1) = index;
found = 1;
break;
end;
end;
end;
if ~found
cluster{end+1} = index;
end;
end;
|
github
|
lcnhappe/happe-master
|
std_plotcurve.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_plotcurve.m
| 29,673 |
utf_8
|
b474f6ed97d0a5964d1b1a07a72ee958
|
% std_plotcurve() - plot ERP or spectral traces for a STUDY component
% or channel cluster
% Usage:
% >> std_plotcurve( axvals, data, 'key', 'val', ...)
% Inputs:
% axvals - [vector or cell array] axis values for the data.
% data - [cell array] mean data for each subject group and/or data
% condition. For example, to plot mean ERPs from a STUDY
% for epochs of 800 frames in two conditions from three groups
% of 12 subjects:
%
% >> data = { [800x12] [800x12] [800x12];... % 3 groups, cond 1
% [800x12] [800x12] [800x12] }; % 3 groups, cond 2
% >> std_plotcurve(erp_ms,data);
%
% By default, parametric statistics are computed across subjects
% in the three groups. (group,condition) ERP averages are plotted.
% See below and >> help statcond
% for more information about the statistical computations. For
% plotting multiple channels, use the second dimension. For
% example data = { [800x64x12] [800x64x12] } for 12 subjects,
% 64 channels and 800 data points. The 'chanlocs' option must be
% used as well to specify channel positions.
%
% Optional display parameters:
% 'datatype' - ['erp'|'spec'] data type {default: 'erp'}
% 'titles' - [cell array of string] titles for each of the subplots.
% { default: none}
%
% Statistics options:
% 'groupstats' - [cell] One p-value array per group {default: {}}
% 'condstats' - [cell] One p-value array per condition {default: {}}
% 'interstats' - [cell] Interaction p-value arrays {default: {}}
% 'threshold' - [NaN|real<<1] Significance threshold. NaN -> plot the
% p-values themselves on a different figure. When possible,
% significance regions are indicated below the data.
% {default: NaN}
%
% Curve plotting options (ERP and spectrum):
% 'plotgroups' - ['together'|'apart'] 'together' -> plot mean results
% for subject groups in the same figure panel in different
% colors. 'apart' -> plot group results on different figure
% panels {default: 'apart'}
% 'plotconditions' - ['together'|'apart'] 'together' -> plot mean results
% for data conditions on the same figure panel in
% different
% colors. 'apart' -> plot conditions on different figure
% panel. Note: 'plotgroups' and 'plotconditions' arguments
% cannot both be 'together' {default: 'apart'}
% 'legend' - ['on'|'off'] turn plot legend on/off {default: 'off'}
% 'colors' - [cell] cell array of colors
% 'plotdiff' - ['on'|'off'] plot difference between two groups
% or conditions plotted together.
% 'plotstderr' - ['on'|'off'|'diff'|'nocurve'|'diffnocurve'] plots in
% a surface indicating the standard error. 'diff' only
% does it for the difference (requires 'plotdiff' 'on'
% above). 'nocurve' does not plot the mean. This functionality
% does not work for all data configuration {default: 'off'}
% 'figure' - ['on'|'off'] creates a new figure ('on'). The 'off' mode
% plots all of the groups and conditions on the same pannel.
% 'plotsubjects' - ['on'|'off'] overplot traces for individual components
% or channels {default: 'off'}
% 'singlesubject' - ['on'|'off'] set to 'on' to plot single subject.
% {default: 'off'}
% 'ylim' - [min max] ordinate limits for ERP and spectrum plots
% {default: all available data}
%
% Scalp map plotting options:
% 'chanlocs' - [struct] channel locations structure
%
% Author: Arnaud Delorme, CERCO, CNRS, 2006-
%
% See also: pop_erspparams(), pop_erpparams(), pop_specparams(), statcond()
function std_plotcurve(allx, data, varargin)
pgroup = [];
pcond = [];
pinter = [];
if nargin < 2
help std_plotcurve;
return;
end;
opt = finputcheck( varargin, { 'ylim' 'real' [] [];
'filter' 'real' [] [];
'threshold' 'real' [] NaN;
'unitx' 'string' [] 'ms';
'chanlocs' 'struct' [] struct('labels', {});
'plotsubjects' 'string' { 'on','off' } 'off';
'condnames' 'cell' [] {}; % just for legends
'groupnames' 'cell' [] {}; % just for legends
'figtag' 'string' [] 'tmp_curvetag';
'groupstats' 'cell' [] {};
'condstats' 'cell' [] {};
'interstats' 'cell' [] {};
'titles' 'cell' [] {};
'colors' 'cell' [] {};
'figure' 'string' { 'on','off' } 'on';
'plottopo' 'string' { 'on','off' } 'off';
'plotstderr' 'string' { 'on','off','diff','nocurve' } 'off';
'plotdiff' 'string' { 'on','off' } 'off';
'legend' { 'string','cell' } { { 'on','off' } {} } 'off';
'datatype' 'string' { 'ersp','itc','erp','spec' } 'erp';
'plotgroups' 'string' { 'together','apart' } 'apart';
'plotmode' 'string' { 'test','condensed' } 'test'; % deprecated
'plotconditions' 'string' { 'together','apart' } 'apart' }, 'std_plotcurve');
% opt.figure = 'off'; % test by nima
if isstr(opt), error(opt); end;
opt.singlesubject = 'off';
if length(opt.chanlocs) > 1, opt.plottopo = 'on'; end;
if strcmpi(opt.plottopo, 'on') && size(data{1},3) == 1, opt.singlesubject = 'on'; end;
%if size(data{1},2) == 1, opt.singlesubject = 'on'; end;
if all(all(cellfun('size', data, 2)==1)) opt.singlesubject = 'on'; end;
if any(any(cellfun('size', data, 2)==1)), opt.groupstats = {}; opt.condstats = {}; end;
if strcmpi(opt.datatype, 'spec'), opt.unit = 'Hz'; end;
if strcmpi(opt.plotsubjects, 'on')
opt.plotgroups = 'apart';
opt.plotconditions = 'apart';
end;
if strcmpi(opt.plotconditions, 'together') && ~isempty(opt.groupstats), opt.plotconditions = 'apart'; end;
if strcmpi(opt.plotgroups, 'together') && ~isempty(opt.condstats) , opt.plotgroups = 'apart'; end;
if isstr(opt.legend), opt.legend = {}; end;
if isempty(opt.titles), opt.titles = cell(10,10); opt.titles(:) = { '' }; end;
if length(data(:)) == length(opt.legend(:)),
opt.legend = reshape(opt.legend, size(data))';
opt.legend(cellfun(@isempty, data)) = [];
opt.legend = (opt.legend)';
end;
% color matrix
% -----------------------
onecol = { 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' };
manycol = { 'b' 'g' 'm' 'c' 'r' 'k' 'y' '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' };
modifier = { '-' '--' '-.' ':' '-' '--' '-.' ':' '-' '--' '-.' ':' };
if strcmpi(opt.plotgroups, 'together') || strcmpi(opt.plotconditions, 'together') || strcmpi(opt.figure, 'off')
col = manycol;
else col = onecol;
end;
if ~isempty(opt.colors), col = opt.colors; end;
nonemptycell = find(~cellfun(@isempty, data));
if strcmpi(opt.plotsubjects, 'off')
% both group and conditions s
if strcmpi(opt.plotconditions, 'together') && strcmpi(opt.plotgroups, 'together')
dim1 = max(size(data));
dim2 = min(size(data));
coldata = col([1:dim1]);
for iRow = 2:dim2
coldata(iRow,:) = coldata(1,:);
for iCol = 1:dim1
coldata{iRow,iCol} = [ coldata{iRow,iCol} modifier{iRow} ];
end;
end;
if size(coldata,1) ~= size(data,1), coldata = coldata'; end;
else
coldata = manycol;
end;
coldata = reshape(coldata(1:length(data(:))), size(data));
else
coldata = cell(size(data));
end;
% Fill empty cells with NaNs (This allow to plot all conditions on the same panel even when there is some missing data)
% --------------------------
if strcmpi(opt.plotconditions, 'together') || strcmpi(opt.plotgroups , 'together')
emptyindx = find(cellfun(@isempty,data));
if ~isempty(emptyindx)
for icell = 1:length(emptyindx)
if max(size(data{emptyindx(icell)})) == 0
data{emptyindx(icell)} = nan;
end
end
end
end
% remove empty entries
% --------------------
datapresent = ~cellfun(@isempty, data);
if size(data,1) > 1, for c = size(data,1):-1:1, if sum(datapresent(c,:)) == 0, data(c,:) = []; coldata(c,:) = []; if ~strcmpi(opt.plotconditions, 'together') opt.titles(c,:) = []; end; if ~isempty(opt.groupstats), opt.groupstats(c) = []; end; end; end; end;
if size(data,2) > 1, for g = size(data,2):-1:1, if sum(datapresent(:,g)) == 0, data(:,g) = []; coldata(:,g) = []; if ~strcmpi(opt.plotgroups , 'together') opt.titles(:,g) = []; end; if ~isempty(opt.condstats ), opt.condstats( g) = []; end; end; end; end;
if strcmpi(opt.plotsubjects, 'off'), tmpcol = coldata'; tmpcol = tmpcol(:)'; end;
% number of columns and rows to plot
% ----------------------------------
nc = size(data,1);
ng = size(data,2);
if strcmpi(opt.plotgroups, 'together'), ngplot = 1; else ngplot = ng; end;
if strcmpi(opt.plotconditions, 'together'), ncplot = 1; else ncplot = nc; end;
if nc >= ng, opt.subplot = 'transpose';
else opt.subplot = 'normal';
end;
if isempty(opt.condnames)
for c=1:nc, opt.condnames{c} = sprintf('Cond. %d', c); end;
if nc == 1, opt.condnames = { '' }; end;
end;
if isempty(opt.groupnames)
for g=1:ng, opt.groupnames{g} = sprintf('Group. %d', g); end;
if ng == 1, opt.groupnames = { '' }; end;
end;
% plotting paramters
% ------------------
if ng > 1 && ~isempty(opt.groupstats), addc = 1; else addc = 0; end;
if nc > 1 && ~isempty(opt.condstats ), addr = 1; else addr = 0; end;
if length(opt.threshold) > 1, opt.threshold = opt.threshold(1); end;
if strcmpi(opt.singlesubject, 'off') ...
&& ( ~isempty(opt.condstats) || ~isempty(opt.groupstats) ) % only for curves
plottag = 0;
if strcmpi(opt.plotgroups, 'together') && isempty(opt.condstats) && ~isempty(opt.groupstats) && ~isnan(opt.threshold), addc = 0; plottag = 1; end;
if strcmpi(opt.plotconditions , 'together') && ~isempty(opt.condstats) && isempty(opt.groupstats) && ~isnan(opt.threshold), addr = 0; plottag = 1; end;
if ~isnan(opt.threshold) && plottag == 0 && strcmpi(opt.figure, 'on')
disp('Warning: cannot plot condition/group on the same panel while using a fixed');
disp(' threshold, unless you only compute statistics for ether groups or conditions');
opt.plotgroups = 'apart';
opt.plotconditions = 'apart';
end;
end;
% resize data to match points x channels x subjects
% or points x 1 x components
% -------------------------------------------------
for index = 1:length(data(:))
if length(opt.chanlocs) ~= size(data{index},2) && (length(opt.chanlocs) == 1 || isempty(opt.chanlocs))
data{index} = reshape(data{index}, [ size(data{index},1) 1 size(data{index},2) ]);
end;
end;
% compute significance mask
% --------------------------
if ~isempty(opt.interstats), pinter = opt.interstats{3}; end;
if ~isnan(opt.threshold) && ( ~isempty(opt.groupstats) || ~isempty(opt.condstats) )
pcondplot = opt.condstats;
pgroupplot = opt.groupstats;
pinterplot = pinter;
maxplot = 1;
else
for ind = 1:length(opt.condstats), pcondplot{ind} = -log10(opt.condstats{ind}); end;
for ind = 1:length(opt.groupstats), pgroupplot{ind} = -log10(opt.groupstats{ind}); end;
if ~isempty(pinter), pinterplot = -log10(pinter); end;
maxplot = 3;
end;
% labels
% ------
if strcmpi(opt.unitx, 'ms'), xlab = 'Time (ms)'; ylab = 'Potential (\muV)';
else xlab = 'Frequency (Hz)'; ylab = 'Log Power Spectral Density 10*log_{10}(\muV^{2}/Hz)'; % ylab = 'Power (10*log_{10}(\muV^{2}))';
end;
if ~isnan(opt.threshold), statopt = { 'xlabel' xlab };
else statopt = { 'logpval' 'on' 'xlabel' xlab 'ylabel' '-log10(p)' 'ylim' [0 maxplot] };
end;
% adjust figure size
% ------------------
if strcmpi(opt.figure, 'on')
figure('color', 'w','Tag', opt.figtag);
pos = get(gcf, 'position');
basewinsize = 200/max(nc,ng)*3;
if strcmpi(opt.plotgroups, 'together') pos(3) = 200*(1+addc);
else pos(3) = 200*(ng+addc);
end;
if strcmpi(opt.plotconditions , 'together') pos(4) = 200*(1+addr);
else pos(4) = 200*(nc+addr);
end;
if strcmpi(opt.subplot, 'transpose'), set(gcf, 'position', [ pos(1) pos(2) pos(4) pos(3)]);
else set(gcf, 'position', pos);
end;
else
opt.subplot = 'noplot';
end;
tmplim = [Inf -Inf];
colcount = 1; % only when plotting all conditions on the same figure
tmpcol = col;
for c = 1:ncplot
for g = 1:ngplot
if strcmpi(opt.figure, 'off'), tmpcol(1) = []; end; % knock off colors
if strcmpi(opt.plotgroups, 'together'), hdl(c,g)=mysubplot(ncplot+addr, ngplot+addc, 1 + (c-1)*(ngplot+addc), opt.subplot); ci = g;
elseif strcmpi(opt.plotconditions, 'together'), hdl(c,g)=mysubplot(ncplot+addr, ngplot+addc, g, opt.subplot); ci = c;
else hdl(c,g)=mysubplot(ncplot+addr, ngplot+addc, g + (c-1)*(ngplot+addc), opt.subplot); ci = 1;
end;
if ~isempty(data{c,g})
% read all data from one condition or group
% -----------------------------------------
dimreduced_sizediffers = 0;
if ncplot ~= nc && ngplot ~= ng
maxdim = max(max(cellfun(@(x)(size(x, ndims(x))), data)));
for cc = 1:size(data,1)
for gg = 1:size(data,2)
tmptmpdata = real(data{cc,gg});
if cc == 1 && gg == 1, tmpdata = NaN*zeros([size(tmptmpdata,1) size(tmptmpdata,2) maxdim length(data(:))]); end;
tmpdata(:,:,1:size(tmptmpdata,3),gg+((cc-1)*ng)) = tmptmpdata;
end;
end;
elseif ncplot ~= nc % plot conditions together
for ind = 2:size(data,1), if numel(size(data{ind,1})) ~= numel(size(data{1})) || any(size(data{ind,1}) ~= size(data{1})), dimreduced_sizediffers = 1; end; end;
for cc = 1:nc
[trash,order] = sort(cellfun(@length,data(:,g)),'descend'); clear trash;
tmptmpdata = real(data{order(cc),g});
if dimreduced_sizediffers
tmptmpdata = nan_mean(tmptmpdata,ndims(tmptmpdata)); % average across last dim
end;
if cc == 1 && ndims(tmptmpdata) == 3, tmpdata = zeros([size(tmptmpdata) nc]); end;
if cc == 1 && ndims(tmptmpdata) == 2, tmpdata = zeros([size(tmptmpdata) 1 nc]); end;
if ~any(isnan(tmptmpdata))
tmpdata(:,:,:,order(cc)) = tmptmpdata;
else
tmpdata(:,:,:,order(cc)) = nan;
end
end;
elseif ngplot ~= ng % plot groups together
for ind = 2:size(data,2), if numel(size(data{1,ind})) ~= numel(size(data{1})) || any((size(data{1,ind}) ~= size(data{1}))), dimreduced_sizediffers = 1; end; end;
for gg = 1:ng
[trash,order] = sort(cellfun(@length,data(c,:)),'descend'); clear trash;
tmptmpdata = real(data{c,order(gg)});
if dimreduced_sizediffers
tmptmpdata = nan_mean(tmptmpdata,ndims(tmptmpdata));
end;
if gg == 1 && ndims(tmptmpdata) == 3, tmpdata = zeros([size(tmptmpdata) ng]); end;
if gg == 1 && ndims(tmptmpdata) == 2, tmpdata = zeros([size(tmptmpdata) 1 ng]); end;
if ~any(isnan(tmptmpdata))
tmpdata(:,:,:,order(gg)) = tmptmpdata;
else
tmpdata(:,:,:,order(gg)) = nan;
end
end;
else
tmpdata = real(data{c,g});
end;
% plot difference
% ---------------
if ~strcmpi(opt.plotdiff, 'off')
if ngplot ~= ng || ncplot ~= nc
if size(tmpdata,3) == 2
tmpdata(:,:,end+1) = tmpdata(:,:,2)-tmpdata(:,:,1);
opt.legend{end+1} = [ opt.legend{2} '-' opt.legend{1} ];
elseif size(tmpdata,4) == 2
tmpdata(:,:,:,end+1) = tmpdata(:,:,:,2)-tmpdata(:,:,:,1);
opt.legend{end+1} = [ opt.legend{2} '-' opt.legend{1} ];
else
disp('Cannot plot difference, more than 2 indep. variable values');
end;
else
disp('Cannot plot difference, indep. variable value must be plotted together');
end;
end;
if ~isempty(opt.filter), tmpdata = myfilt(tmpdata, 1000/(allx(2)-allx(1)), 0, opt.filter); end;
% plotting options
% ----------------
plotopt = { allx };
% -------------------------------------------------------------
% tmpdata is of size "points x channels x subject x conditions"
% or "points x 1 x components x conditions"
% -------------------------------------------------------------
if ~dimreduced_sizediffers && strcmpi(opt.plotsubjects, 'off') % average accross subjects
tmpstd = squeeze(real(std(tmpdata,[],3)))/sqrt(size(tmpdata,3)); tmpstd = squeeze(permute(tmpstd, [2 1 3])); tmpdata = squeeze(real(nan_mean(tmpdata,3)));
end;
tmpdata = squeeze(permute(tmpdata, [2 1 3 4]));
% -----------------------------------------------------------------
% tmpdata is now of size "channels x points x subject x conditions"
% -----------------------------------------------------------------
if strcmpi(opt.plottopo, 'on'), highlight = 'background'; else highlight = 'bottom'; end;
if strcmpi(opt.plotgroups, 'together') && isempty(opt.condstats) && ...
~isnan(opt.threshold) && ~isempty(opt.groupstats)
plotopt = { plotopt{:} 'maskarray' };
tmpdata = { tmpdata pgroupplot{c}' };
elseif strcmpi(opt.plotconditions, 'together') && isempty(opt.groupstats) && ...
~isnan(opt.threshold) && ~isempty(opt.condstats)
plotopt = { plotopt{:} 'maskarray' };
tmpdata = { tmpdata pcondplot{g}' };
end;
plotopt = { plotopt{:} 'highlightmode', highlight };
if strcmpi(opt.plotsubjects, 'on')
plotopt = { plotopt{:} 'plotmean' 'on' 'plotindiv' 'on' };
else
plotopt = { plotopt{:} 'plotmean' 'off' };
end;
plotopt = { plotopt{:} 'ylim' opt.ylim 'xlabel' xlab 'ylabel' ylab };
if ncplot ~= nc || ngplot ~= ng
plotopt = { plotopt{:} 'legend' opt.legend };
end;
if strcmpi(opt.plottopo, 'on') && length(opt.chanlocs) > 1
metaplottopo(tmpdata, 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ...
'plotargs', { plotopt{:} }, 'datapos', [2 3], 'title', opt.titles{c,g});
elseif iscell(tmpdata)
if ~all(isnan(tmpdata{1}))
plotcurve( allx, tmpdata{1}, 'colors', tmpcol, 'maskarray', tmpdata{2}, plotopt{3:end}, 'title', opt.titles{c,g});
else
plotcurve( allx, nan(size(tmpdata{1},2),length(allx)), 'colors', tmpcol, 'maskarray', tmpdata{2}, plotopt{3:end}, 'title', opt.titles{c,g});
end
else
if isempty(findstr(opt.plotstderr, 'nocurve'))
if all(isnan(tmpdata))
plotcurve( allx, nan(size(tmpdata,2),length(allx)), 'colors', tmpcol, plotopt{2:end}, 'traceinfo', 'on', 'title', opt.titles{c,g});
else
plotcurve( allx, tmpdata, 'colors', tmpcol, plotopt{2:end}, 'traceinfo', 'on', 'title', opt.titles{c,g});
end
end;
if ~strcmpi(opt.plotstderr, 'off')
if ~dimreduced_sizediffers
if ~isempty(findstr(opt.plotstderr, 'diff')), begind = 3; else begind = 1; end;
set(gcf, 'renderer', 'OpenGL')
for tmpi = begind:size(tmpdata,1)
hold on; chandle = fillcurves( allx, tmpdata(tmpi,:)-tmpstd(tmpi,:), tmpdata(tmpi,:)+tmpstd(tmpi,:), tmpcol{tmpi}); hold on;
numfaces = size(get(chandle(1), 'Vertices'),1);
set(chandle(1), 'FaceVertexCData', repmat([1 1 1], [numfaces 1]), 'Cdatamapping', 'direct', 'facealpha', 0.3, 'edgecolor', 'none');
end;
else
disp('Some conditions have more subjects than others, cannot plot standard error');
end;
end;
end;
end;
if strcmpi(opt.plottopo, 'off'), % only non-topographic
xlim([allx(1) allx(end)]); hold on;
if isempty(opt.ylim)
tmp = ylim;
tmplim = [ min(tmplim(1), tmp(1)) max(tmplim(2), tmp(2)) ];
else
ylim(opt.ylim);
end;
end;
% statistics accross groups
% -------------------------
if g == ngplot && ng > 1 && ~isempty(opt.groupstats)
if ~strcmpi(opt.plotgroups, 'together') || ~isempty(opt.condstats) || isnan(opt.threshold)
if strcmpi(opt.plotgroups, 'together'), mysubplot(ncplot+addr, ngplot+addc, 2 + (c-1)*(ngplot+addc), opt.subplot); ci = g;
elseif strcmpi(opt.plotconditions, 'together'), mysubplot(ncplot+addr, ngplot+addc, ngplot + 1, opt.subplot); ci = c;
else mysubplot(ncplot+addr, ngplot+addc, ngplot + 1 + (c-1)*(ngplot+addc), opt.subplot); ci = 1;
end;
if strcmpi(opt.plotconditions, 'together'), condnames = 'Conditions'; else condnames = opt.condnames{c}; end;
if ~isnan(opt.threshold)
if strcmpi(opt.plottopo, 'on'),
metaplottopo({zeros(size(pgroupplot{c}')) pgroupplot{c}'}, 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ...
'plotargs', { allx 'maskarray' statopt{:} }, 'datapos', [2 3], 'title', opt.titles{c, g+1});
else plotcurve(allx, zeros(size(allx)), 'maskarray', mean(pgroupplot{c},2), 'ylim', [0.1 1], 'title', opt.titles{c, g+1}, statopt{:});
end;
else
if strcmpi(opt.plottopo, 'on'),
metaplottopo(pgroupplot{c}', 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ...
'plotargs', { allx statopt{:} }, 'datapos', [2 3], 'title', opt.titles{c, g+1});
else plotcurve(allx, mean(pgroupplot{c},2), 'title', opt.titles{c, g+1}, statopt{:});
end;
end;
end;
end;
end;
end;
for g = 1:ng
% statistics accross conditions
% -----------------------------
if ~isempty(opt.condstats) && nc > 1
if ~strcmpi(opt.plotconditions, 'together') || ~isempty(opt.groupstats) || isnan(opt.threshold)
if strcmpi(opt.plotgroups, 'together'), mysubplot(ncplot+addr, ngplot+addc, 1 + c*(ngplot+addc), opt.subplot); ci = g;
elseif strcmpi(opt.plotconditions, 'together'), mysubplot(ncplot+addr, ngplot+addc, g + ngplot+addc, opt.subplot); ci = c;
else mysubplot(ncplot+addr, ngplot+addc, g + c*(ngplot+addc), opt.subplot); ci = 1;
end;
if strcmpi(opt.plotgroups, 'together'), groupnames = 'Groups'; else groupnames = opt.groupnames{g}; end;
if ~isnan(opt.threshold)
if strcmpi(opt.plottopo, 'on'),
metaplottopo({zeros(size(pcondplot{g}')) pcondplot{g}'}, 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ...
'plotargs', { allx 'maskarray' statopt{:} }, 'datapos', [2 3], 'title', opt.titles{end, g});
else plotcurve(allx, zeros(size(allx)), 'maskarray', mean(pcondplot{g},2), 'ylim', [0.1 1], 'title', opt.titles{end, g}, statopt{:});
end;
else
if strcmpi(opt.plottopo, 'on'),
metaplottopo(pcondplot{g}', 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ...
'plotargs', { allx statopt{:} }, 'datapos', [2 3], 'title', opt.titles{end, g});
else plotcurve(allx, mean(pcondplot{g},2), 'title', opt.titles{end, g}, statopt{:});
end;
end;
end;
end;
end;
% statistics accross group and conditions
% ---------------------------------------
if ~isempty(opt.groupstats) && ~isempty(opt.condstats) && ng > 1 && nc > 1
mysubplot(ncplot+addr, ngplot+addc, ngplot + 1 + ncplot*(ngplot+addr), opt.subplot);
if ~isnan(opt.threshold)
if strcmpi(opt.plottopo, 'on'),
metaplottopo({zeros(size(pinterplot')) pinterplot'}, 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ...
'plotargs', { allx 'maskarray' statopt{:} }, 'datapos', [2 3], 'title', opt.titles{end, end});
else plotcurve(allx, zeros(size(allx)), 'maskarray', mean(pinterplot,2), 'ylim', [0.1 1], 'title', opt.titles{end, end}, statopt{:});
xlabel(xlab); ylabel('-log10(p)');
end;
else
if strcmpi(opt.plottopo, 'on'),
metaplottopo(pinterplot', 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ...
'plotargs', { allx statopt{:} }, 'datapos', [2 3], 'title', opt.titles{end, end});
else plotcurve(allx, mean(pinterplot,2), 'title', opt.titles{end, end}, statopt{:});
end;
end;
end;
% axis limit
% ----------
for c = 1:ncplot
for g = 1:ngplot
if isempty(opt.ylim) && strcmpi(opt.plottopo, 'off')
set(hdl(c,g), 'ylim', tmplim);
end;
end;
end;
if strcmpi(opt.plottopo, 'off') && length(hdl(:)) > 1
axcopy;
% remove axis labels (for most but not all)
% ------------------
if strcmpi(opt.subplot, 'transpose')
for c = 1:size(hdl,2)
for g = 1:size(hdl,1)
axes(hdl(g,c));
if c ~= 1 && size(hdl,2) ~=1, xlabel(''); legend off; end;
if g ~= 1 && size(hdl,1) ~= 1, ylabel(''); legend off; end;
end;
end;
else
for c = 1:size(hdl,1)
for g = 1:size(hdl,2)
axes(hdl(c,g));
if g ~= 1 && size(hdl,2) ~=1, ylabel(''); legend off; end;
if c ~= size(hdl,1) && size(hdl,1) ~= 1, xlabel(''); legend off; end;
end;
end;
end;
end;
% mysubplot (allow to transpose if necessary)
% -------------------------------------------
function hdl = mysubplot(nr,nc,ind,subplottype);
r = ceil(ind/nc);
c = ind -(r-1)*nc;
if strcmpi(subplottype, 'transpose'), hdl = subplot(nc,nr,(c-1)*nr+r);
elseif strcmpi(subplottype, 'normal'), hdl = subplot(nr,nc,(r-1)*nc+c);
elseif strcmpi(subplottype, 'noplot'), hdl = gca;
else error('Unknown subplot type');
end;
% rapid filtering for ERP
% -----------------------
function tmpdata2 = myfilt(tmpdata, srate, lowpass, highpass);
bscorrect = 1;
if bscorrect
% Getting initial baseline
bs_val1 = mean(tmpdata,1);
bs1 = repmat(bs_val1, size(tmpdata,1), 1);
end
% Filtering
tmpdata2 = reshape(tmpdata, size(tmpdata,1), size(tmpdata,2)*size(tmpdata,3)*size(tmpdata,4));
tmpdata2 = eegfiltfft(tmpdata2',srate, lowpass, highpass)';
tmpdata2 = reshape(tmpdata2, size(tmpdata,1), size(tmpdata,2), size(tmpdata,3), size(tmpdata,4));
if bscorrect
% Getting after-filter baseline
bs_val2 = mean(tmpdata2,1);
bs2 = repmat(bs_val2, size(tmpdata2,1), 1);
% Correcting the baseline
realbs = bs1-bs2;
tmpdata2 = tmpdata2 + realbs;
end
|
github
|
lcnhappe/happe-master
|
std_movie.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_movie.m
| 5,749 |
utf_8
|
b76bc3cff273bfdc46ca097d380720fa
|
% std_topomovie - make movie in the frequency domain
%
% Usage:
% >> [STUDY] = std_movie(STUDY, ALLEEG, key1, val1, key2, val2, ...);
%
% Inputs:
% STUDY - STUDY structure comprising some or all of the EEG datasets in ALLEEG.
% ALLEEG - vector of EEG dataset structures for the dataset(s) in the STUDY,
% typically created using load_ALLEEG().
% 'channels' - [numeric vector] specific channel group to plot. By
% default, the grand mean channel spectrum is plotted (using the
% same format as for the cluster component means described above)
% 'moviemode' - ['erp'|'spec'|'ersptime'] movie mode. Currently only
% 'spec' is implemented.
% 'erspfreq' - [min max] frequency range when making movie of ERSP. The
% ERSP values are averaged over the selected frequency
% range. Not implemented
% 'limitbeg' - [min max] limits at the beginning of the movie
% 'limitend' - [min max] limits at the end of the movie
% 'freqslim' - [freqs] array of landmark frequencies to set color
% limits.
% 'movieparams' - [low inc high] lower limit, higher limit and increment. If
% increment is omited, movie is generate at every possible
% increment (max freq resolution or max time resolution)
%
% Authors: Arnaud Delorme, CERCO, August, 2006
%
% See also: std_specplot(), std_erppplot(), std_erspplot()
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [STUDY, M] = std_movie(STUDY, ALLEEG, varargin);
if nargin < 2
help std_specplot;
return;
end;
[opt addparams ] = finputcheck( varargin, ...
{ 'erspfreq' 'real' [] [];
'movieparams' 'real' [] [];
'channels' 'cell' [] {};
'freqslim' 'real' [] [];
'limitbeg' 'real' [] [];
'limitend' 'real' [] [];
'moviemode' 'string' { 'ersptime','erp','spec' } 'spec' }, 'std_movie', 'ignore');
if isstr(opt), error(opt); end;
tmpchanlocs = ALLEEG(1).chanlocs;
if isempty(opt.channels), opt.channels = { tmpchanlocs.labels }; end;
if ~strcmpi(opt.moviemode, 'spec'), error('Only spec has been implemented so far'); end;
% read data once
% --------------
STUDY = std_specplot(STUDY, ALLEEG, 'channels', opt.channels, 'topofreq', [10 11]); close;
% find first data channel with info
% ---------------------------------
for cind = 1:length(STUDY.changrp)
if ~isempty(STUDY.changrp(cind).specdata), break; end;
end;
% generate movie
% --------------
if isempty(opt.movieparams),
opt.movieparams(1) = STUDY.changrp(cind).specfreqs(1);
opt.movieparams(2) = STUDY.changrp(cind).specfreqs(end);
end;
if length(opt.movieparams) == 2
opt.movieparams(3) = opt.movieparams(2);
opt.movieparams(2) = STUDY.changrp(cind).specfreqs(2)-STUDY.changrp(cind).specfreqs(1);
end;
if length(opt.movieparams) == 3
opt.movieparams = [opt.movieparams(1):opt.movieparams(2):opt.movieparams(3)];
end;
% find limits
% -----------
if isempty(opt.limitbeg)
[STUDY specdata] = std_specplot(STUDY, ALLEEG, 'channels', opt.channels, 'topofreq', opt.movieparams(1)); close;
opt.limitbeg = [ min(specdata{1}) max(specdata{1}) ];
[STUDY specdata] = std_specplot(STUDY, ALLEEG, 'channels', opt.channels, 'topofreq', opt.movieparams(end)); close;
opt.limitend = [ min(specdata{1}) max(specdata{1}) ];
end;
lowlims = linspace(opt.limitbeg(1), opt.limitend(1), length(opt.movieparams));
highlims = linspace(opt.limitbeg(2), opt.limitend(2), length(opt.movieparams));
% limits at specific frequencies
% ------------------------------
if ~isempty(opt.freqslim)
if opt.freqslim(1) ~= opt.movieparams(1) , opt.freqslim = [ opt.movieparams(1) opt.freqslim ]; end;
if opt.freqslim(end) ~= opt.movieparams(end), opt.freqslim = [ opt.freqslim opt.movieparams(end) ]; end;
for ind = 1:length(opt.freqslim)
[tmp indf(ind)] = min(abs(opt.freqslim(ind) - opt.movieparams));
[STUDY specdata] = std_specplot(STUDY, ALLEEG, 'channels', opt.channels, 'topofreq', opt.movieparams(indf(ind))); close;
minimum(ind) = min(specdata{1});
maximum(ind) = max(specdata{1});
end;
indf(1) = 0;
lowlims = [ ];
highlims = [ ];
for ind = 2:length(opt.freqslim)
lowlims = [lowlims linspace(minimum(ind-1), minimum(ind), indf(ind)-indf(ind-1)) ];
highlims = [highlims linspace(maximum(ind-1), maximum(ind), indf(ind)-indf(ind-1)) ];
end;
end;
% make movie
% ----------
for ind = 1:length(opt.movieparams)
STUDY = std_specplot(STUDY, ALLEEG, 'channels', opt.channels, 'topofreq', opt.movieparams(ind), 'caxis', [lowlims(ind) highlims(ind)]);
pos = get(gcf, 'position');
set(gcf, 'position', [pos(1) pos(2) pos(3)*2 pos(4)*2]);
M(ind) = getframe(gcf);
close;
end;
figure; axis off; movie(M);
|
github
|
lcnhappe/happe-master
|
std_readfile.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_readfile.m
| 15,609 |
utf_8
|
5f6b1005263321cdba24e80b92827d6c
|
% std_readfile() - Read data file containing STUDY measures.
%
% Usage:
% >> [data param range1 range2] = std_readfile(filename, 'key', val);
%
% Inputs:
% filename - [string] read specific file, for instance 's1.daterp'
% containing ERP data for dataset "s1.set". It is also
% possible to provide only the "base" file name "s1" and
% function will load the appropriate file based on the
% selected input measure (measure input).
%
% Optional inputs:
% 'channels' - [cell or integer] channel labels - for instance
% { 'cz' 'pz' } - or indices - for instance [1 2 3]
% of channels to load from the data file.
% 'components' - [integer] component index in the selected EEG dataset for which
% to read the ERSP
% 'timelimits' - [min max] ERSP time (latency in ms) range of interest
% 'freqlimits' - [min max] ERSP frequency range (in Hz) of interest
% 'measure' - ['erp'|'spec'|'ersp'|'itc'|'timef'|'erspbase'|'erspboot'
% 'itcboot'|'erpim'] data measure to read. If a full file name
% is provided, the data measure is selected automatically.
% 'getparamsonly' - ['on'|'off'] only read file parameters not data.
%
% Outputs:
% data - the multi-channel or multi-component data. The size of this
% output depends on the number of dimension (for ERSP or ERP
% for instance). The last dimension is channels or components.
% params - structure containing parameters saved with the data file.
% range1 - time points (ERP, ERSP) or frequency points (spectrum)
% range2 - frequency points (ERSP, ITCs)
%
% Examples:
% % the examples below read all data channels for the selected files
% [ersp params times freqs] = std_readfiles('s1.datersp');
% [erp params times] = std_readfiles('s1.daterp');
% [erp params times] = std_readfiles('s1.daterp', timerange', [-100 500]);
%
% Authors: Arnaud Delorme, SCCN, INC, UCSD, May 2010
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, 2010, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% dimensions
% time x freqs x channel_comps x subjects_trials
function [measureData, parameters, measureRange1, measureRange2, events, setinfoTrialIndices] = std_readfile(fileBaseName, varargin);
if nargin < 1
help std_readfile;
return;
end;
opt = finputcheck(varargin, { 'components' 'integer' [] [];
'getparamonly' 'string' { 'on','off' } 'off';
'singletrials' 'string' { 'on','off' } 'off';
'concatenate' 'string' { 'on','off' } 'off'; % ERPimage only
'channels' 'cell' [] {};
'setinfoinds' 'integer' [] [];
'measure' 'string' { 'erpim','ersp','erspboot','erspbase','itc','itcboot','spec','erp','timef' } 'erp';
'timelimits' 'real' [] []; % ERPimage, ERP, ERSP, ITC
'triallimits' 'real' [] []; % ERPimage only
'freqlimits' 'real' [] []; % SPEC, ERSP, ITC
'dataindices' 'integer' [] [] }, 'std_readdatafile');
if isstr(opt), error(opt); end;
if ~isempty(opt.triallimits), opt.freqlimits = opt.triallimits; end;
if strcmpi(opt.concatenate, 'on'), opt.singletrials = 'on'; end;
if isstruct(fileBaseName), fileBaseName = { fileBaseName.filebase };
else fileBaseName = { fileBaseName };
end;
if ~isempty(opt.channels) && length(opt.channels) < length(fileBaseName)
opt.channels(2:length(fileBaseName)) = opt.channels(1);
end;
% get file extension
% ------------------
if ~isempty(opt.channels) || (~isempty(opt.dataindices) && opt.dataindices(1) < 0) , dataType = 'chan';
else dataType = 'comp';
end;
[tmp1 tmp2 currentFileExt] = fileparts(fileBaseName{1});
if length(currentFileExt) > 3 && (strcmpi(currentFileExt(2:4), 'dat') || strcmpi(currentFileExt(2:4), 'ica'))
opt.measure = currentFileExt(5:end);
if strcmpi(currentFileExt(2:4), 'dat'), dataType = 'chan';
else dataType = 'comp';
end;
fileExt = '';
else
if strcmpi(dataType, 'chan'), fileExt = [ '.dat' opt.measure ];
else fileExt = [ '.ica' opt.measure ];
end;
end;
if nargin > 5 && strcmpi(opt.singletrials, 'on')
indFlag = true;
else indFlag = false;
end;
% get fields to read
% ------------------
erspFreqOnly = 0;
switch opt.measure
case 'erpim' , fieldExt = '';
case 'erp' , fieldExt = '';
case 'spec' , fieldExt = '';
case 'ersp' , fieldExt = '_ersp';
case 'itc' , fieldExt = '_itc';
case 'timef' , fieldExt = '_timef';
case 'erspbase', fieldExt = '_erspbase'; fileExt = fileExt(1:end-4); erspFreqOnly = 1;
case 'erspboot', fieldExt = '_erspboot'; fileExt = fileExt(1:end-4); erspFreqOnly = 1;
case 'itcboot' , fieldExt = '_itcboot'; fileExt = fileExt(1:end-4); erspFreqOnly = 1;
end;
% get channel or component indices
% --------------------------------
if ~isempty(opt.channels) && isnumeric(opt.channels)
opt.dataindices = opt.channels;
elseif ~isempty(opt.channels)
%if length(fileBaseName) > 1, error('Cannot read channel labels when reading more than 1 input file'); end;
for iFile = 1:length(fileBaseName)
filename = [ fileBaseName{iFile} fileExt ];
try,
warning('off', 'MATLAB:load:variableNotFound');
fileData = load( '-mat', filename, 'labels', 'chanlabels' );
warning('on', 'MATLAB:load:variableNotFound');
catch, fileData = [];
end;
if isfield(fileData, 'labels'), chan.chanlocs = struct('labels', fileData.labels);
elseif isfield(fileData, 'chanlabels') chan.chanlocs = struct('labels', fileData.chanlabels);
else error('Cannot use file to lookup channel names, the file needs to be recomputed');
end;
opt.dataindices(iFile) = std_chaninds(chan, opt.channels{iFile});
end;
elseif ~isempty(opt.components)
opt.dataindices = opt.components;
else opt.dataindices = abs(opt.dataindices);
end;
% file names and indices must have the same number of values
% ----------------------------------------------------------
if strcmpi(opt.getparamonly, 'on'), opt.dataindices = 1; end;
if length(fileBaseName ) == 1, fileBaseName( 1:length(opt.dataindices)) = fileBaseName; end;
if length(opt.dataindices) == 1, opt.dataindices(1:length(fileBaseName )) = opt.dataindices; end;
if length(opt.dataindices) ~= length(fileBaseName) && ~isempty(opt.dataindices), error('Number of files and number of indices must be the same'); end;
% scan datasets
% -------------
measureRange1 = [];
measureRange2 = [];
measureData = [];
parameters = [];
events = {};
setinfoTrialIndices = [];
% read only specific fields
% -------------------------
counttrial = 0;
for fInd = 1:length(opt.dataindices) % usually only one value
fieldsToRead = [ dataType int2str(opt.dataindices(fInd)) fieldExt ];
try,
warning('off', 'MATLAB:load:variableNotFound');
fileData = load( '-mat', [ fileBaseName{fInd} fileExt ], 'parameters', 'freqs', 'times', 'events', 'chanlocsforinterp', fieldsToRead );
warning('on', 'MATLAB:load:variableNotFound');
catch
error( [ 'Cannot read file ''' fileBaseName{fInd} fileExt '''' ]);
end;
% get output for parameters and measure ranges
% --------------------------------------------
if isfield(fileData, 'chanlocsforinterp'), chanlocsforinterp = fileData.chanlocsforinterp; end;
if isfield(fileData, 'parameters')
parameters = removedup(fileData.parameters);
for index = 1:length(parameters), if iscell(parameters{index}), parameters{index} = { parameters{index} }; end; end;
parameters = struct(parameters{:});
end;
if isfield(fileData, 'times'), measureRange1 = fileData.times; end;
if isfield(fileData, 'freqs'), measureRange2 = fileData.freqs; end;
if isfield(fileData, 'events'), events{fInd} = fileData.events; end;
% if the function is only called to get parameters
% ------------------------------------------------
if strcmpi(opt.getparamonly, 'on'),
measureRange1 = indicesselect(measureRange1, opt.timelimits);
measureRange2 = indicesselect(measureRange2, opt.freqlimits);
if strcmpi(opt.measure, 'spec'), measureRange1 = measureRange2; end;
parameters.singletrials = 'off';
if strcmpi(opt.measure, 'timef')
parameters.singletrials = 'on';
elseif strcmpi(opt.measure, 'erp') || strcmpi(opt.measure, 'spec')
if strcmpi(dataType, 'chan')
if size(fileData.chan1,1) > 1 && size(fileData.chan1,2) > 1
parameters.singletrials = 'on';
end;
else
if size(fileData.comp1,1) > 1 && size(fileData.comp1,2) > 1
parameters.singletrials = 'on';
end;
end;
end;
return;
end;
% copy fields to output variables
% -------------------------------
if isfield(fileData, fieldsToRead)
fieldData = getfield(fileData, fieldsToRead);
if isempty(fieldData)
tmpSize = size(fieldData);
tmpSize(tmpSize == 0) = 1;
fieldData = ones(tmpSize)*NaN;
end;
if isstr(fieldData), eval( [ 'fieldData = ' fieldData ] ); end;
% average single trials if necessary
% ----------------------------------
if strcmpi(opt.measure, 'erp') || strcmpi(opt.measure, 'spec')
if strcmpi(opt.singletrials, 'off') && size(fieldData,1) > 1 && size(fieldData,2) > 1
fieldData = mean(fieldData,2);
end;
end;
% array reservation
% -----------------
if fInd == 1
sizeFD = size(fieldData);
if length(sizeFD) == 2 && (sizeFD(1) == 1 || sizeFD(2) == 1), sizeFD = sizeFD(1)*sizeFD(2); end;
if length(sizeFD) == 2 && (sizeFD(1) == 0 || sizeFD(2) == 0), sizeFD = max(sizeFD(1)); end;
if strcmpi(opt.singletrials, 'off'), measureData = zeros([ sizeFD length(opt.dataindices) ], 'single');
else measureData = zeros([ sizeFD ], 'single');
end;
if indFlag,
setinfoTrialIndices = zeros(1, size(measureData,ndims(measureData)), 'int16');
if length(opt.setinfoinds) ~= length(opt.dataindices) error('For single trial output, the "setinfoinds" parameter must be set'); end;
end;
nDimData = length(sizeFD);
end;
% copy data to output variable
% ----------------------------
if nDimData == 1, measureData(:,fInd) = fieldData;
else
if strcmpi(opt.singletrials, 'off')
if nDimData == 2, measureData(:,:,fInd) = fieldData;
else measureData(:,:,:,fInd) = fieldData;
end;
else
if nDimData == 2, measureData(:,counttrial+1:counttrial+size(fieldData,2)) = fieldData;
else measureData(:,:,counttrial+1:counttrial+size(fieldData,2)) = fieldData;
end;
setinfoTrialIndices(counttrial+1:counttrial+size(fieldData,2)) = opt.setinfoinds(fInd);
counttrial = counttrial+size(fieldData,2);
end;
end;
elseif ~isempty(findstr('comp', fieldsToRead))
error( sprintf([ 'Field "%s" not found in file %s' 10 'Try recomputing measure.' ], fieldsToRead, [ fileBaseName{fInd} fileExt ]));
else
error(['Problem loading data, most likely your design has' 10 ...
'conditions with no trials or missing channels' 10 ...
'If you think this is a bug, report it on Bugzilla for EEGLAB' ]);
% the case below is for the rare case where all the channels are read and the end of the array needs to be trimmed
% error('There is a problem with your data, please enter a bug report and upload your data at http://sccn.ucsd.edu/eeglab/bugzilla');
if nDimData == 1, measureData(:,1:(fInd-1)) = [];
elseif nDimData == 2, measureData(:,:,1:(fInd-1)) = [];
else measureData(:,:,:,1:(fInd-1)) = [];
end;
break;
end;
end;
% special ERP image
% -----------------
if ~isempty(events)
len = length(events{1});
events = [ events{:} ];
if strcmpi(opt.singletrials, 'off') && ~isempty(events), events = reshape(events, len, length(events)/len); end;
end;
% select plotting or clustering time/freq range
% ---------------------------------------------
if ~isempty(measureRange1) && ~erspFreqOnly
[measureRange1 indBegin indEnd] = indicesselect(measureRange1, opt.timelimits);
if ~isempty(measureData)
if strcmpi(opt.measure, 'erp') || ( strcmpi(opt.measure, 'erpim') && strcmpi(opt.singletrials, 'on') )
measureData = measureData(indBegin:indEnd,:,:);
else measureData = measureData(:,indBegin:indEnd,:);
end;
end;
end;
if isempty(measureRange2) && size(measureData,1) > 1 && size(measureData,2) > 1 % for ERPimage
measureRange2 = [1:size(measureData,1)];
end;
if ~isempty(measureRange2)
[measureRange2 indBegin indEnd] = indicesselect(measureRange2, opt.freqlimits);
if ~isempty(measureData)
measureData = measureData(indBegin:indEnd,:,:);
end;
if strcmpi(opt.measure, 'spec'), measureRange1 = measureRange2; end;
end;
% remove duplicates in the list of parameters
% -------------------------------------------
function cella = removedup(cella)
[tmp indices] = unique_bc(cella(1:2:end));
if length(tmp) ~= length(cella)/2
%fprintf('Warning: duplicate ''key'', ''val'' parameter(s), keeping the last one(s)\n');
end;
cella = cella(sort(union(indices*2-1, indices*2)));
% find indices for selection of measure
% -------------------------------------
function [measureRange indBegin indEnd] = indicesselect(measureRange, measureLimits);
indBegin = 1;
indEnd = length(measureRange);
if ~isempty(measureRange) && ~isempty(measureLimits) && (measureLimits(1) > measureRange(1) || measureLimits(end) < measureRange(end))
indBegin = min(find(measureRange >= measureLimits(1)));
indEnd = max(find(measureRange <= measureLimits(end)));
measureRange = measureRange(indBegin:indEnd);
end;
|
github
|
lcnhappe/happe-master
|
std_figtitle.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_figtitle.m
| 11,976 |
utf_8
|
8d0cdf735518b04d1c27c37441ecc076
|
% std_figtitle() - Generate plotting figure titles in a cell array
%
% Usage:
% >> celltxt = std_figtitle(key1, val1, key2, val2);
%
% Inputs:
% 'subject' - [string] Subject name
% 'datatype' - [string] data type (For example 'erp')
% 'chanlabels' - [cell array or string] channel names
% 'compnames' - [cell array or string] component names
% 'condnames' - [cell array] names of conditions
% 'cond2names' - [cell array] names of conditions
% 'vals' - [cell array or real array] value for plot panel (for
% example, 0 ms)
% 'valsunit' - [cell array or string] unit value (i.e. ms)
%
% Optional statistical titles:
% 'condstat' - ['on'|'off'] default is 'off'
% 'cond2stat' - ['on'|'off'] default is 'off'
% 'mcorrect' - [string] correction for multiple comparisons. Default is
% empty.
% 'statistics' - [string] type of statictics
% 'threshold' - [real] treshold value
%
% Optional grouping:
% 'condgroup' - ['on'|'off'] group conditions together default is 'off'
% 'cond2group' - ['on'|'off'] default is 'off'
%
% Outputs:
% celltxt - cell array of text string, one for each set of condition
%
% Example:
% std_figtitle('subject', 'toto', 'condnames', { 'test1' 'test2' }, ...
% 'vals' , { [100] [4] }, 'valsunit', { 'ms' 'Hz' })
%
% Authors: Arnaud Delorme, SCCN/UCSD, Feb 2010
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [all_titles alllegends ] = std_figtitle(varargin)
if nargin < 1
help std_figtitle;
return;
end;
alllegends = {};
opt = finputcheck( varargin, { 'chanlabels' {'cell','string'} [] {};
'condnames' {'cell','string'} [] '';
'cond2names' {'cell','string'} [] '';
'condstat' 'string' {'on','off'} 'off';
'cond2stat' 'string' {'on','off'} 'off';
'condgroup' 'string' {'on','off','together','apart'} 'off';
'cond2group' 'string' {'on','off','together','apart'} 'off';
'plotmode' 'string' {'normal','condensed'} 'normal';
'plotsubjects' 'string' {'on','off'} 'off';
'threshold' 'real' [] NaN;
'statistics' 'string' [] '';
'mcorrect' 'string' [] '';
'datatype' 'string' [] '';
'clustname' 'string' [] '';
'compnames' {'cell','string'} [] {};
'vals' {'cell','real'} [] {}; % just for titles
'valsunit' {'cell','string'} [] {}; % just for titles
'subject' 'string' [] '' }, 'std_figtitle'); %, 'ignore');
if isstr(opt), error(opt); end;
if ~iscell(opt.vals), opt.vals = { opt.vals }; end;
ncori = length(opt.condnames);
nc2ori = length(opt.cond2names);
if ~isempty(opt.vals) && ~isempty(opt.vals{1}) && ~isnan(opt.vals{1}(1)), opt.condgroup = 'off'; opt.cond2group = 'off'; end;
if strcmpi(opt.plotmode, 'condensed'), opt.condgroup = 'on'; opt.cond2group = 'on'; end;
if strcmpi(opt.plotsubjects, 'on'), opt.condgroup = 'off'; opt.cond2group = 'off'; end;
if strcmpi(opt.plotsubjects, 'on')
opt.condgroup = 'apart';
opt.cond2group = 'apart';
end;
if strcmpi(opt.condgroup, 'on'), opt.condgroup = 'together'; end;
if strcmpi(opt.cond2group, 'on'), opt.cond2group = 'together'; end;
if strcmpi(opt.condgroup, 'together') && strcmpi(opt.cond2stat, 'on'), opt.condgroup = 'apart'; end;
if strcmpi(opt.cond2group, 'together') && strcmpi(opt.condstat , 'on') , opt.cond2group = 'apart'; end;
if ~( strcmpi(opt.condgroup, 'together') && strcmpi(opt.cond2group, 'together') )
if strcmpi(opt.condgroup, 'together'), alllegends = opt.condnames ; opt.condnames = ''; end;
if strcmpi(opt.cond2group, 'together'), alllegends = opt.cond2names; opt.cond2names = ''; end;
end;
if ~iscell(opt.valsunit), opt.valsunit = { opt.valsunit }; end;
if ~iscell(opt.chanlabels), opt.chanlabels = { opt.chanlabels }; end;
if ~iscell(opt.condnames), opt.condnames = { opt.condnames }; end;
if ~iscell(opt.cond2names), opt.cond2names = { opt.cond2names }; end;
if isempty(opt.condnames), opt.condnames{1} = ''; end;
if isempty(opt.cond2names), opt.cond2names{1} = ''; end;
for c1 = 1:length(opt.condnames)
for c2 = 1:length(opt.cond2names)
% value (ms or Hz)
% ----------------
fig_title1 = '';
for i = 1:length(opt.vals)
if ~isempty(opt.vals{i}) && ~isnan(opt.vals{i}(1))
if opt.vals{i}(1) == opt.vals{i}(end), fig_title1 = [ num2str(opt.vals{i}(1)) '' opt.valsunit{i} fig_title1];
else fig_title1 = [ num2str(opt.vals{i}(1)) '-' num2str(opt.vals{i}(2)) '' opt.valsunit{i} fig_title1 ];
end;
if length(opt.vals) > i, fig_title1 = [ ' & ' fig_title1 ]; end;
end;
end;
% conditions
% ----------
if ~isempty(opt.condnames{c1})
fig_title1 = [ value2str(opt.condnames{c1}) ', ' fig_title1];
end;
if ~isempty(opt.cond2names{c2})
fig_title1 = [ value2str(opt.cond2names{c2}) ', ' fig_title1];
end;
% channel labels, component name, subject name and datatype
% ---------------------------------------------------------
fig_title2 = '';
if length( opt.chanlabels ) == 1 && ~isempty( opt.chanlabels{1} )
fig_title2 = [ opt.chanlabels{1} ', ' fig_title2 ];
end;
% cluster and component name
% --------------------------
if ~isempty( opt.clustname )
if ~isempty( opt.compnames )
if iscell( opt.compnames )
compstr = [ 'C' num2str(opt.compnames{min(c1,size(opt.compnames,1)),min(c2,size(opt.compnames,2))}) ];
else compstr = [ opt.compnames ];
end;
else compstr = '';
end;
if ~isempty( opt.subject )
if ~isempty( compstr )
fig_title2 = [ opt.subject '/' compstr ', ' fig_title2 ];
else fig_title2 = [ opt.subject ', ' fig_title2 ];
end;
elseif ~isempty( compstr )
fig_title2 = [ compstr ', ' fig_title2 ];
end;
if ~isempty( opt.datatype )
fig_title2 = [ opt.clustname ' ' opt.datatype ', ' fig_title2 ];
else fig_title2 = [ opt.clustname ', ' fig_title2 ];
end;
else
if ~isempty( opt.compnames )
if iscell( opt.compnames )
else fig_title2 = [ 'C' num2str(opt.compnames{c1,c2}) ', ' fig_title2 ];
fig_title2 = [ opt.compnames ', ' fig_title2 ];
end;
end;
% subject and data type
% ---------------------
if ~isempty( opt.subject )
if ~isempty( opt.datatype )
fig_title2 = [ opt.subject ' ' opt.datatype ', ' fig_title2 ];
else fig_title2 = [ opt.subject ', ' fig_title2 ];
end;
elseif ~isempty( opt.datatype )
fig_title2 = [ opt.datatype ' - ' fig_title2 ];
end;
end;
if strcmpi(opt.cond2group, 'together') && strcmpi(opt.condgroup, 'together')
fig_title = fig_title2;
if ~isempty(fig_title1) && length(fig_title1) > 1 && strcmpi(fig_title1(end-1:end), ', '), fig_title1(end-1:end) = []; end;
if ~isempty(fig_title1) && length(fig_title1) > 1 && strcmpi(fig_title1(end-1:end), '- '), fig_title1(end-1:end) = []; end;
alllegends{c1, c2} = fig_title1;
else
fig_title = [ fig_title2 fig_title1 ];
end;
if ~isempty(fig_title) && length(fig_title) > 1 && strcmpi(fig_title(end-1:end), ', '), fig_title(end-1:end) = []; end;
if ~isempty(fig_title) && length(fig_title) > 1 && strcmpi(fig_title(end-1:end), '- '), fig_title(end-1:end) = []; end;
all_titles{c1,c2} = fig_title;
end;
end;
if ~isempty(alllegends)
alllegends = alllegends';
alllegends = alllegends(:)';
% convert legends to string if necessary
% --------------------------------------
for ileg = 1:length(alllegends),
alllegends{ileg} = value2str(alllegends{ileg});
end;
end;
% statistic titles
% ----------------
if isnan(opt.threshold),
basicstat = '(p-value)';
else
if length(opt.threshold) >= 1
basicstat = sprintf([ '(p<%.' thresh_pres(opt.threshold(1)) 'f)'], opt.threshold(1));
end;
if length(opt.threshold) >= 2
basicstat = [ basicstat(1:end-1) sprintf([' red;p<%.' thresh_pres(opt.threshold(2)) 'f brown)'], opt.threshold(2)) ];
end;
if length(opt.threshold) >= 3
basicstat = [ basicstat(1:end-1) sprintf([';\np<%.' thresh_pres(opt.threshold(3)) 'f black)' ], opt.threshold(3)) ];
end;
end;
if ~isempty(opt.statistics), basicstat = [ basicstat ' ' opt.statistics ]; end;
if ~isempty(opt.mcorrect) && ~strcmpi(opt.mcorrect, 'none'), basicstat = [ basicstat ' with ' opt.mcorrect ]; end;
if strcmpi(opt.condstat, 'on')
rown = size(all_titles,1)+1;
for c2 = 1:length(opt.cond2names)
all_titles{rown, c2} = [ value2str(opt.cond2names{c2}) ' ' basicstat ];
end;
end;
if strcmpi(opt.cond2stat, 'on')
coln = size(all_titles,2)+1;
for c1 = 1:length(opt.condnames)
all_titles{c1, coln} = [ value2str(opt.condnames{c1}) ' ' basicstat ];
end;
end;
if strcmpi(opt.condstat, 'on') && strcmpi(opt.cond2stat, 'on')
all_titles{rown, coln} = [ 'Interaction ' basicstat ];
end;
function pres = thresh_pres(thresh_pres);
if (round(thresh_pres*100)-thresh_pres*100) == 0
pres = 2;
elseif (round(thresh_pres*1000)-thresh_pres*1000) == 0
pres = 3;
else
pres = -round(log10(thresh_pres))+1;
end;
pres = num2str(pres);
% convert
% -------
function str = value2str(value)
if isstr(value)
str = value;
elseif isnumeric(value)
if length(value) == 1
str = num2str(value);
else
str = num2str(value(1));
if length(value) <= 5
for ind = 2:length(value)
str = [ str ' & ' num2str(value(ind)) ];
end;
else
str = [ str ' & ' num2str(value(2)) ' & ...' ];
end;
end;
else % cell array
str = value{1};
for ind = 2:length(value)
str = [ str ' & ' value{ind} ];
end;
end;
|
github
|
lcnhappe/happe-master
|
std_chantopo.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/functions/studyfunc/std_chantopo.m
| 9,652 |
utf_8
|
28bf5cd485d8031d2b9e2dc3180c2738
|
% std_chantopo() - plot ERP/spectral/ERSP topoplot at a specific
% latency/frequency.
% Usage:
% >> std_chantopo( data, 'key', 'val', ...)
% Inputs:
% data - [cell array] mean data for each subject group and/or data
% condition. These arrays are usually returned by function
% std_erspplot and std_erpplot. For example
%
% >> data = { [1x64x12] [1x64x12 }; % 2 groups of 12 subjects, 64 channels
% >> std_chantopo(data, 'chanlocs', 'chanlocfile.txt');
%
% Scalp map plotting option (mandatory):
% 'chanlocs' - [struct] channel location structure
%
% Other scalp map plotting options:
% 'chanlocs' - [struct] channel location structure
% 'topoplotopt' - [cell] topoplot options. Default is { 'style', 'both',
% 'shading', 'interp' }. See topoplot help for details.
% 'ylim' - [min max] ordinate limits for ERP and spectrum plots
% {default: all available data}
% 'caxis' - [min max] same as above
%
% Optional display parameters:
% 'datatype' - ['erp'|'spec'] data type {default: 'erp'}
% 'titles' - [cell array of string] titles for each of the subplots.
% { default: none}
% 'subplotpos' - [addr addc posr posc] perform ploting in existing figure.
% Add "addr" rows, "addc" columns and plot the scalp
% topographies starting at position (posr,posc).
%
% Statistics options:
% 'groupstats' - [cell] One p-value array per group {default: {}}
% 'condstats' - [cell] One p-value array per condition {default: {}}
% 'interstats' - [cell] Interaction p-value arrays {default: {}}
% 'threshold' - [NaN|real<<1] Significance threshold. NaN -> plot the
% p-values themselves on a different figure. When possible,
% significance regions are indicated below the data.
% {default: NaN}
% 'binarypval' - ['on'|'off'] if a threshold is set, show only significant
% channels as red dots. Default is 'off'.
%
% Author: Arnaud Delorme, CERCO, CNRS, 2006-
%
% See also: pop_erspparams(), pop_erpparams(), pop_specparams(), statcond()
function std_chantopo(data, varargin)
pgroup = [];
pcond = [];
pinter = [];
if nargin < 2
help std_chantopo;
return;
end;
opt = finputcheck( varargin, { 'ylim' 'real' [] [];
'titles' 'cell' [] cell(20,20);
'threshold' 'real' [] NaN;
'chanlocs' 'struct' [] struct('labels', {});
'groupstats' 'cell' [] {};
'condstats' 'cell' [] {};
'interstats' 'cell' [] {};
'subplotpos' 'integer' [] [];
'topoplotopt' 'cell' [] { 'style', 'both' };
'binarypval' 'string' { 'on','off' } 'on';
'datatype' 'string' { 'ersp','itc','erp','spec' } 'erp';
'caxis' 'real' [] [] }, 'std_chantopo', 'ignore'); %, 'ignore');
if isstr(opt), error(opt); end;
if ~isempty(opt.ylim), opt.caxis = opt.ylim; end;
if isnan(opt.threshold), opt.binarypval = 'off'; end;
if strcmpi(opt.binarypval, 'on'), opt.ptopoopt = { 'style' 'blank' }; else opt.ptopoopt = opt.topoplotopt; end;
% remove empty entries
datapresent = ~cellfun(@isempty, data);
for c = size(data,1):-1:1, if sum(datapresent(c,:)) == 0, data(c,:) = []; opt.titles(c,:) = []; if ~isempty(opt.groupstats), opt.groupstats(c) = []; end; end; end;
for g = size(data,2):-1:1, if sum(datapresent(:,g)) == 0, data(:,g) = []; opt.titles(:,g) = []; if ~isempty(opt.condstats ), opt.condstats( g) = []; end; end; end;
nc = size(data,1);
ng = size(data,2);
if nc >= ng, opt.transpose = 'on';
else opt.transpose = 'off';
end;
% plotting paramters
% ------------------
if ng > 1 & ~isempty(opt.groupstats), addc = 1; else addc = 0; end;
if nc > 1 & ~isempty(opt.condstats ), addr = 1; else addr = 0; end;
if ~isempty(opt.subplotpos),
if strcmpi(opt.transpose, 'on'), opt.subplotpos = opt.subplotpos([2 1 4 3]); end;
addr = opt.subplotpos(1);
addc = opt.subplotpos(2);
posr = opt.subplotpos(4);
posc = opt.subplotpos(3);
else posr = 0;
posc = 0;
end;
% compute significance mask
% -------------------------
if ~isempty(opt.interstats), pinter = opt.interstats{3}; end;
if ~isnan(opt.threshold(1)) && ( ~isempty(opt.groupstats) || ~isempty(opt.condstats) )
pcondplot = opt.condstats;
pgroupplot = opt.groupstats;
pinterplot = pinter;
maxplot = 1;
else
for ind = 1:length(opt.condstats), pcondplot{ind} = -log10(opt.condstats{ind}); end;
for ind = 1:length(opt.groupstats), pgroupplot{ind} = -log10(opt.groupstats{ind}); end;
if ~isempty(pinter), pinterplot = -log10(pinter); end;
maxplot = 3;
end;
% adjust figure size
% ------------------
if isempty(opt.subplotpos)
fig = figure('color', 'w');
pos = get(fig, 'position');
set(fig, 'position', [ pos(1)+15 pos(2)+15 pos(3)/2.5*(nc+addr), pos(4)/2*(ng+addc) ]);
pos = get(fig, 'position');
if strcmpi(opt.transpose, 'off'), set(gcf, 'position', [ pos(1) pos(2) pos(4) pos(3)]);
else set(gcf, 'position', pos);
end;
end
% topoplot
% --------
tmpc = [inf -inf];
for c = 1:nc
for g = 1:ng
hdl(c,g) = mysubplot(nc+addr, ng+addc, g + posr + (c-1+posc)*(ng+addc), opt.transpose);
if ~isempty(data{c,g})
tmpplot = double(mean(data{c,g},3));
if ~all(isnan(tmpplot))
if ~isreal(tmpplot), error('This function cannot plot complex values'); end;
topoplot( tmpplot, opt.chanlocs, opt.topoplotopt{:});
if isempty(opt.caxis)
tmpc = [ min(min(tmpplot), tmpc(1)) max(max(tmpplot), tmpc(2)) ];
else
caxis(opt.caxis);
end;
title(opt.titles{c,g}, 'interpreter', 'none');
else
axis off;
end;
else
axis off;
end;
% statistics accross groups
% -------------------------
if g == ng & ng > 1 & ~isempty(opt.groupstats)
hdl(c,g+1) = mysubplot(nc+addr, ng+addc, g + posr + 1 + (c-1+posc)*(ng+addc), opt.transpose);
topoplot( pgroupplot{c}, opt.chanlocs, opt.ptopoopt{:});
title(opt.titles{c,g+1});
caxis([-maxplot maxplot]);
end;
end;
end;
% color scale
% -----------
if isempty(opt.caxis)
for c = 1:nc
for g = 1:ng
axes(hdl(c,g));
caxis(tmpc);
end;
end;
end;
for g = 1:ng
% statistics accross conditions
% -----------------------------
if ~isempty(opt.condstats) && nc > 1
hdl(nc+1,g) = mysubplot(nc+addr, ng+addc, g + posr + (c+posc)*(ng+addc), opt.transpose);
topoplot( pcondplot{g}, opt.chanlocs, opt.ptopoopt{:});
title(opt.titles{nc+1,g});
caxis([-maxplot maxplot]);
end;
end;
% statistics accross group and conditions
% ---------------------------------------
if ~isempty(opt.condstats) && ~isempty(opt.groupstats) && ng > 1 && nc > 1
hdl(nc+1,ng+1) = mysubplot(nc+addr, ng+addc, g + posr + 1 + (c+posc)*(ng+addc), opt.transpose);
topoplot( pinterplot, opt.chanlocs, opt.ptopoopt{:});
title(opt.titles{nc+1,ng+1});
caxis([-maxplot maxplot]);
end;
% color bars
% ----------
axes(hdl(nc,ng));
cbar_standard(opt.datatype, ng);
if isnan(opt.threshold(1)) && (nc ~= size(hdl,1) || ng ~= size(hdl,2))
axes(hdl(end,end));
cbar_signif(ng, maxplot);
end;
% remove axis labels
% ------------------
for c = 1:size(hdl,1)
for g = 1:size(hdl,2)
if g ~= 1 && size(hdl,2) ~=1, ylabel(''); end;
if c ~= size(hdl,1) && size(hdl,1) ~= 1, xlabel(''); end;
end;
end;
% colorbar for ERSP and scalp plot
% --------------------------------
function cbar_standard(datatype, ng);
pos = get(gca, 'position');
tmpc = caxis;
fact = fastif(ng == 1, 40, 20);
tmp = axes('position', [ pos(1)+pos(3)+pos(3)/fact pos(2) pos(3)/fact pos(4) ]);
set(gca, 'unit', 'normalized');
if strcmpi(datatype, 'itc')
cbar(tmp, 0, tmpc, 10); ylim([0.5 1]);
else cbar(tmp, 0, tmpc, 5);
end;
% colorbar for significance
% -------------------------
function cbar_signif(ng, maxplot);
% Retrieving Defaults
icadefs;
pos = get(gca, 'position');
tmpc = caxis;
fact = fastif(ng == 1, 40, 20);
tmp = axes('position', [ pos(1)+pos(3)+pos(3)/fact pos(2) pos(3)/fact pos(4) ]);
map = colormap(DEFAULT_COLORMAP);
n = size(map,1);
cols = [ceil(n/2):n]';
image([0 1],linspace(0,maxplot,length(cols)),[cols cols]);
%cbar(tmp, 0, tmpc, 5);
tick = linspace(0, maxplot, maxplot+1);
set(gca, 'ytickmode', 'manual', 'YAxisLocation', 'right', 'xtick', [], ...
'ytick', tick, 'yticklabel', round(10.^-tick*1000)/1000);
xlabel('');
colormap(DEFAULT_COLORMAP);
% mysubplot (allow to transpose if necessary)
% -------------------------------------------
function hdl = mysubplot(nr,nc,ind,transp);
r = ceil(ind/nc);
c = ind -(r-1)*nc;
if strcmpi(transp, 'on'), hdl = subplot(nc,nr,(c-1)*nr+r);
else hdl = subplot(nr,nc,(r-1)*nc+c);
end;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.