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
|
lcnbeapp/beapp-master
|
std_clustmaxelec.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
pop_studydesign.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_createclust.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_checkconsist.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_readersp.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_moveoutlier.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
pop_savestudy.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
pop_chanplot.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_erpimage.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_cell2setcomps.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_editset.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_readitc.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
pop_loadstudy.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_readspecgram.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_pacplot.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
pop_dipparams.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_precomp.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_rebuilddesign.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
pop_clustedit.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_findsameica.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_plotcurve.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_movie.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_readfile.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_figtitle.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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
|
lcnbeapp/beapp-master
|
std_chantopo.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/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;
|
github
|
lcnbeapp/beapp-master
|
std_uniformfiles.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/studyfunc/std_uniformfiles.m
| 3,122 |
utf_8
|
4338ced427d77d85832ff2965d6735b9
|
% std_uniformfiles() - Check uniform channel distribution accross data files
%
% Usage:
% >> boolval = std_uniformfiles(STUDY, ALLEEG);
%
% Inputs:
% STUDY - EEGLAB STUDY
%
% Outputs:
% boolval - [-1|0|1] 0 if non uniform, 1 if uniform, -1 if error
%
% Authors: Arnaud Delorme, SCCN/UCSD, CERCO/CNRS, 2010-
% Copyright (C) Arnaud Delorme
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function uniformlabels = std_uniformfiles( STUDY, ALLEEG );
if nargin < 2
help std_checkconsist;
return;
end;
filetypes = { 'daterp' 'datspec' 'datersp' 'datitc' 'dattimef' };
% set channel interpolation mode
% ------------------------------
uniformlabels = [];
count = 1;
selectedtypes = {};
for index = 1:length(filetypes)
% scan datasets
% -------------
[ tmpstruct compinds filepresent ] = std_fileinfo(ALLEEG, filetypes{index});
% check if the structures are equal
% ---------------------------------
if ~isempty(tmpstruct)
if any(filepresent == 0)
uniformlabels = -1;
return;
else
firstval = tmpstruct(1).labels;
uniformlabels(count) = length(firstval);
for dat = 2:length(tmpstruct)
tmpval = tmpstruct(dat).labels;
if ~isequal(firstval, tmpval)
uniformlabels(count) = 0;
end;
end;
selectedtypes{count} = filetypes{index};
count = count+1;
end;
end;
end;
% check output
% ------------
if any(uniformlabels == 0)
if any(uniformlabels) == 1
disp('Warning: conflict between datafiles - all should have the same channel distribution');
for index = 1:length(selectedtypes)
if uniformlabels(index)
fprintf(' Data files with extention "%s" have interpolated channels\n', selectedtypes{index});
else fprintf(' Data files with extention "%s" have non-interpolated channels\n', selectedtypes{index});
end;
end;
uniformlabels = -1;
else
uniformlabels = 0;
end;
else
if ~(length(unique(uniformlabels)) == 1)
fprintf('Warning: Data files have different number of channel in each file\n');
for index = 1:length(selectedtypes)
fprintf(' Data files with extention "%s" have %d channels\n', selectedtypes{index}, uniformlabels(index));
end;
end;
uniformlabels = 1;
end;
|
github
|
lcnbeapp/beapp-master
|
iseeglabdeployed.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/iseeglabdeployed.m
| 154 |
utf_8
|
cb8716ae372b37132bb2a58c54d09cd0
|
% iseeglabdeployed - true for EEGLAB compile version and false otherwise
function val = iseeglabdeployed
try
val = isdeployed;
catch
val = 0;
end
|
github
|
lcnbeapp/beapp-master
|
eeg_getversion.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/eeg_getversion.m
| 1,551 |
utf_8
|
a6ee3614031195b8aaf40cfab1251520
|
% eeg_getversion() - obtain EEGLAB version number
%
% Usage:
% >> vers = eeg_getversion;
% >> [vers vnum] = eeg_getversion;
%
% Outputs:
% vers = [string] EEGLAB version number
% vnum = [float] numerical value for the version. For example 11.3.2.4b
% is converted to 11.324
%
% Authors: Arnaud Delorme, SCCN/INC/UCSD, 2010
% Copyright (C) 2010 Arnaud Delorme, SCCN/INC/UCSD
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
function [vers, versnum, releaseDate] = eeg_getversion;
vers = '';
filepath = fileparts(which('eeglab.m'));
filename = dir(fullfile(filepath, 'Contents.m'));
releaseDate = filename.date;
if isempty(filename), return; end;
fid = fopen(fullfile(filepath, filename.name), 'r');
fgetl(fid);
versionline = fgetl(fid);
vers = versionline(11:end);
fclose(fid);
tmpvers = vers;
if isempty(str2num(tmpvers(end))), tmpvers(end) = []; end;
indsDot = find(tmpvers == '.' );
tmpvers(indsDot(2:end)) = [];
versnum = str2num(tmpvers);
|
github
|
lcnbeapp/beapp-master
|
gethelpvar.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/gethelpvar.m
| 9,432 |
utf_8
|
7d60bb94c02933e99c9a469f683938dc
|
% gethelpvar() - convert a Matlab m-file help-message header
% into out variables
% Usage:
% >> [vartext, varnames] = gethelpvar( filein, varlist);
%
% Inputs:
% filein - input filename (with .m extension)
% varlist - optional list of variable to return. If absent
% retrun all variables.
%
% Outputs:
% vartext - variable text
% varnames - name of the varialbe returned;
%
% Notes: see help2html() for file format
%
% Example: >> gethelpvar( 'gethelpvar.m', 'filein')
%
% Author: Arnaud Delorme, Salk Institute 20 April 2002
%
% See also: help2html()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [alltext, allvars] = gethelpvar( filename, varlist )
if nargin < 1
help gethelpvar;
return;
end;
% input file
% ----------
fid = fopen( filename, 'r');
if fid == -1
error('File not found');
end;
cont = 1;
% scan file
% -----------
str = fgets( fid );
% if first line is the name of the function, reload
if str(1) ~= '%', str = fgets( fid ); end;
% state variables
% -----------
maindescription = 1;
varname = [];
oldvarname = [];
vartext = [];
newvar = 0;
allvars = {};
alltext = {};
indexout = 1;
while (str(1) == '%')
str = deblank(str(2:end-1));
% --- DECODING INPUT
newvar = 0;
str = deblank2(str);
if ~isempty(str)
% find a title
% ------------
i2d = findstr(str, ':');
newtitle = 0;
if ~isempty(i2d)
i2d = i2d(1);
switch lower(str(1:i2d))
case { 'usage:' 'authors:' 'author:' 'notes:' 'note:' 'input:' ...
'inputs:' 'outputs:' 'output' 'example:' 'examples:' 'see also:' }, newtitle = 1;
end;
if (i2d == length(str)) & (str(1) ~= '%'), newtitle = 1; end;
end;
if newtitle
tilehtml = str(1:i2d);
newtitle = 1;
oldvarname = varname;
oldvartext = vartext;
if i2d < length(str)
%vartext = formatstr(str(i2d+1:end), g.refcall);
vartext = str(i2d+1:end);
else vartext = [];
end;
varname = [];
else
% not a title
% ------------
% scan lines
[tok1 strrm] = strtok( str );
[tok2 strrm] = strtok( strrm );
if ~isempty(tok2) & ( isequal(tok2,'-') | isequal(tok2,'=')) % new variable
newvar = 1;
oldvarname = varname;
oldvartext = vartext;
varname = tok1;
strrm = deblank(strrm); % remove tail blanks
strrm = deblank(strrm(end:-1:1)); % remove initial blanks
%strrm = formatstr( strrm(end:-1:1), g.refcall);
strrm = strrm(end:-1:1);
vartext = strrm;
else
% continue current text
str = deblank(str); % remove tail blanks
str = deblank(str(end:-1:1)); % remove initial blanks
%str = formatstr( str(end:-1:1), g.refcall );
str = str(end:-1:1);
if isempty(vartext)
vartext = str;
else
if ~isempty(varname)
vartext = [ vartext 10 str]; % espace if in array
else
if length(vartext)>3 & all(vartext( end-2:end) == '.')
vartext = [ deblank2(vartext(1:end-3)) 10 str]; % espace if '...'
else
vartext = [ vartext 10 str]; % CR otherwise
end;
end;
end;
end;
newtitle = 0;
end;
% --- END OF DECODING
str = fgets( fid );
% test if last entry
% ------------------
if str(1) ~= '%'
if ~newtitle
if ~isempty(oldvarname)
allvars{indexout} = oldvarname;
alltext{indexout} = oldvartext;
indexout = indexout + 1;
%fprintf( fo, [ '</tr>' g.normrow g.normcol1 g.var '</td>\n' ], oldvarname);
%fprintf( fo, [ g.normcol2 g.vartext '</td></tr>\n' ], oldvartext);
else
if ~isempty(oldvartext)
%fprintf( fo, [ g.normcol2 g.tabtext '</td></tr>\n' ], oldvartext);
end;
end;
newvar = 1;
oldvarname = varname;
oldvartext = vartext;
end;
end;
% test if new input for an array
% ------------------------------
if newvar | newtitle
if maindescription
if ~isempty(oldvartext) % FUNCTION TITLE
maintext = oldvartext;
maindescription = 0;
functioname = oldvarname( 1:findstr( oldvarname, '()' )-1);
%fprintf( fo, [g.normrow g.normcol1 g.functionname '</td>\n'],upper(functioname));
%fprintf( fo, [g.normcol2 g.description '</td></tr>\n'], [ upper(oldvartext(1)) oldvartext(2:end) ]);
% INSERT IMAGE IF PRESENT
%imagename = [ htmlfile( 1:findstr( htmlfile, functioname )-1) functioname '.jpg' ];
%if exist( imagename ) % do not make link if the file does not exist
%fprintf(fo, [ g.normrow g.doublecol ...
% '<CENTER><BR><A HREF="' imagename '" target="_blank"><img SRC=' imagename ...
% ' height=150 width=200></A></CENTER></td></tr>' ]);
%end;
end;
elseif ~isempty(oldvarname)
allvars{indexout} = oldvarname;
alltext{indexout} = oldvartext;
indexout = indexout + 1;
%fprintf( fo, [ '</tr>' g.normrow g.normcol1 g.var '</td>\n' ], oldvarname);
%fprintf( fo, [ g.normcol2 g.vartext '</td></tr>\n' ], oldvartext);
else
if ~isempty(oldvartext)
%fprintf( fo, [ g.normcol2 g.text '</td></tr>\n' ], oldvartext);
end;
end;
end;
% print title
% -----------
if newtitle
%fprintf( fo, [ g.normrow g.doublecol '<BR></td></tr>' g.normrow g.normcol1 g.title '</td>\n' ], tilehtml);
if str(1) ~= '%' % last input
%fprintf( fo, [ g.normcol2 g.text '</td></tr>\n' ], vartext);
end;
oldvarname = [];
oldvartext = [];
end;
else
str = fgets( fid );
end;
end;
fclose( fid );
% remove quotes of variables
% --------------------------
for index = 1:length(allvars)
if allvars{index}(1) == '''', allvars{index} = eval( allvars{index} ); end;
end;
if exist('varlist') == 1
if ~iscell(varlist), varlist = { varlist }; end;
newtxt = mat2cell(zeros(length(varlist), 1), length(varlist), 1); % preallocation
for index = 1:length(varlist)
loc = strmatch( varlist{index}, allvars);
if ~isempty(loc)
newtxt{index} = alltext{loc(1)};
else
disp([ 'warning: variable ''' varlist{index} ''' not found']);
newtxt{index} = '';
end;
end;
alltext = newtxt;
end;
return;
% -----------------
% sub-functions
% -----------------
function str = deblank2( str ); % deblank two ways
str = deblank(str(end:-1:1)); % remove initial blanks
str = deblank(str(end:-1:1)); % remove tail blanks
return;
function strout = formatstr( str, refcall );
[tok1 strrm] = strtok( str );
strout = [];
while ~isempty(tok1)
tokout = functionformat( tok1, refcall );
if isempty( strout)
strout = tokout;
else
strout = [strout ' ' tokout ];
end;
[tok1 strrm] = strtok( strrm );
end;
return;
function tokout = functionformat( tokin, refcall );
tokout = tokin; % default
[test, realtokin, tail] = testfunc1( tokin );
if ~test, [test, realtokin, tail] = testfunc2( tokin ); end;
if test
i1 = findstr( refcall, '%s');
i2 = findstr( refcall(i1(1):end), '''');
if isempty(i2) i2 = length( refcall(i1(1):end) )+1; end;
filename = [ realtokin refcall(i1+2:i1+i2-2)];
if exist( filename ) % do not make link if the file does not exist
tokout = sprintf( [ '<A HREF="' refcall '">%s</A>' tail ' ' ], realtokin, realtokin );
end;
end;
return;
function [test, realtokin, tail] = testfunc1( tokin ) % test if is string is 'function()[,]'
test = 0; realtokin = ''; tail = '';
if ~isempty( findstr( tokin, '()' ) )
realtokin = tokin( 1:findstr( tokin, '()' )-1);
if length(realtokin) < (length(tokin)-2) tail = tokin(end); else tail = []; end;
test = 1;
end;
return;
function [test, realtokin, tail] = testfunc2( tokin ) % test if is string is 'FUNCTION[,]'
test = 0; realtokin = ''; tail = '';
if all( upper(tokin) == tokin)
if tokin(end) == ','
realtokin = tokin(1:end-1);
tail = ',';
else
realtokin = tokin;
end;
testokin = realtokin;
testokin(findstr(testokin, '_')) = 'A';
testokin(findstr(testokin, '2')) = 'A';
if all(double(testokin) > 64) & all(double(testokin) < 91)
test = 1;
end;
realtokin = lower(realtokin);
end;
return;
|
github
|
lcnbeapp/beapp-master
|
eeg_retrieve.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/eeg_retrieve.m
| 2,820 |
utf_8
|
fc0ecd37ff8b71e41ef51d43a4aca461
|
% eeg_retrieve() - Retrieve an EEG dataset from the variable
% containing all datasets (standard: ALLEEG).
%
% Usage: >> EEG = eeg_retrieve( ALLEEG, index );
%
% Inputs:
% ALLEEG - variable containing all datasets
% index - index of the dataset to retrieve
%
% Outputs:
% EEG - output dataset. The workspace variable EEG is also updated
% ALLEEG - updated ALLEEG structure
% CURRENTSET - workspace variable index of the current dataset
%
% Note: The function performs >> EEG = ALLEEG(index);
% It also runs eeg_checkset() on it.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeg_store(), eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG, ALLEEG, CURRENTSET] = eeg_retrieve( ALLEEG, CURRENTSET);
if nargin < 2
help eeg_retrieve;
return;
end;
%try
eeglab_options;
try, % check whether recent changes to this dataset have been saved or not
%--------------------------------------------------------------------
tmpsaved = { ALLEEG.saved };
tmpsaved = tmpsaved(CURRENTSET);
catch, tmpsaved = 'no';
end;
if length(CURRENTSET) > 1 & option_storedisk
[ EEG tmpcom ] = eeg_checkset(ALLEEG(CURRENTSET)); % do not load data if several datasets
if length(CURRENTSET) ~= length(ALLEEG)
[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);
else
ALLEEG = EEG;
end;
else
if CURRENTSET ~= 0
[ EEG tmpcom ] = eeg_checkset(ALLEEG(CURRENTSET), 'loaddata');
[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);
else
EEG = eeg_emptyset; % empty dataset
return;
end;
end;
% retain saved field
% ------------------
for index = 1:length(CURRENTSET)
ALLEEG(CURRENTSET(index)).saved = tmpsaved{index};
EEG(index).saved = tmpsaved{index};
end;
%catch
% fprintf('Warning: cannot retrieve dataset with index %d\n', CURRENTSET);
% return;
%end;
return;
|
github
|
lcnbeapp/beapp-master
|
vararg2str.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/vararg2str.m
| 6,803 |
utf_8
|
547476651c6901a530169197da722d2d
|
% vararg2str() - transform arguments into string for evaluation
% using the eval() command
%
% Usage:
% >> strout = vararg2str( allargs );
% >> strout = vararg2str( allargs, inputnames, inputnum, nostrconv );
%
% Inputs:
% allargs - Cell array containing all arguments
% inputnames - Cell array of input names for these arguments, if any.
% inputnum - Vector of indices for all inputs. If present, the
% string output may by replaced by varargin{num}.
% Include NaN in the vector to avoid specific parameters
% being converted in this way.
% nostrconv - Vector of 0s and 1s indicating where the string
% should be not be converted.
%
% Outputs:
% strout - output string
%
% Author: Arnaud Delorme, CNL / Salk Institute, 9 April 2002
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 9 April 2002
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function strout = vararg2str(allargs, inputnam, inputnum, int2str );
if nargin < 1
help vararg2str;
return;
end;
if isempty(allargs)
strout = '';
return;
end;
% default arguments
% -----------------
if nargin < 2
inputnam(1:length(allargs)) = {''};
else
if length(inputnam) < length(allargs)
inputnam(end+1:length(allargs)) = {''};
end;
end;
if nargin < 3
inputnum(1:length(allargs)) = NaN;
else
if length(inputnum) < length(allargs)
inputnum(end+1:length(allargs)) = NaN;
end;
end;
if nargin < 4
int2str(1:length(allargs)) = 0;
else
if length(int2str) < length(allargs)
int2str(end+1:length(allargs)) = 0;
end;
end;
if ~iscell( allargs )
allargs = { allargs };
end;
% actual conversion
% -----------------
strout = '';
for index = 1:length(allargs)
tmpvar = allargs{index};
if ~isempty(inputnam{index})
strout = [ strout ',' inputnam{index} ];
else
if isstr( tmpvar )
if int2str(index)
strout = [ strout ',' tmpvar ];
else
strout = [ strout ',' str2str( tmpvar ) ];
end;
elseif isnumeric( tmpvar ) | islogical( tmpvar )
strout = [ strout ',' array2str( tmpvar ) ];
elseif iscell( tmpvar )
tmpres = vararg2str( tmpvar );
comas = find( tmpres == ',' );
tmpres(comas) = ' ';
strout = [ strout ',{' tmpres '}' ];
elseif isstruct(tmpvar)
strout = [ strout ',' struct2str( tmpvar ) ];
else
error('Unrecognized input');
end;
end;
end;
if ~isempty(strout)
strout = strout(2:end);
end;
% convert string to string
% ------------------------
function str = str2str( array )
if isempty( array), str = ''''''; return; end;
str = '';
for index = 1:size(array,1)
tmparray = deblank(array(index,:));
if isempty(tmparray)
str = [ str ','' ''' ];
else
str = [ str ',''' doublequotes(tmparray) '''' ];
end;
end;
if size(array,1) > 1
str = [ 'strvcat(' str(2:end) ')'];
else
str = str(2:end);
end;
return;
% convert array to string
% -----------------------
function str = array2str( array )
if isempty( array), str = '[]'; return; end;
if prod(size(array)) == 1, str = num2str(array); return; end;
if size(array,1) == 1, str = [ '[' contarray(array) '] ' ]; return; end;
if size(array,2) == 1, str = [ '[' contarray(array') ']'' ' ]; return; end;
str = '';
for index = 1:size(array,1)
str = [ str ';' contarray(array(index,:)) ];
end;
str = [ '[' str(2:end) ']' ];
return;
% convert struct to string
% ------------------------
function str = struct2str( structure )
if isempty( structure )
str = 'struct([])'; return;
end;
str = '';
allfields = fieldnames( structure );
for index = 1:length( allfields )
strtmp = '';
eval( [ 'allcontent = { structure.' allfields{index} ' };' ] ); % getfield generates a bug
str = [ str, '''' allfields{index} ''',{' vararg2str( allcontent ) '},' ];
end;
str = [ 'struct(' str(1:end-1) ')' ];
return;
% double the quotes in strings
% ----------------------------
function str = doublequotes( str )
quoteloc = union_bc(findstr( str, ''''), union(findstr(str, '%'), findstr(str, '\')));
if ~isempty(quoteloc)
for index = length(quoteloc):-1:1
str = [ str(1:quoteloc(index)) str(quoteloc(index):end) ];
end;
end;
return;
% test continuous arrays
% ----------------------
function str = contarray( array )
array = double(array);
tmpind = find( round(array) ~= array );
if prod(size(array)) == 1
str = num2str(array);
return;
end;
if size(array,1) == 1 & size(array,2) == 2
str = [num2str(array(1)) ' ' num2str(array(2))];
return;
end;
if isempty(tmpind) | all(isnan(array(tmpind)))
str = num2str(array(1));
skip = 0;
indent = array(2) - array(1);
for index = 2:length(array)
if array(index) ~= array(index-1)+indent | indent == 0
if skip <= 1
if skip == 0
str = [str ' ' num2str(array(index))];
else
str = [str ' ' num2str(array(index-1)) ' ' num2str(array(index))];
end;
else
if indent == 1
str = [str ':' num2str(array(index-1)) ' ' num2str(array(index))];
else
str = [str ':' num2str(indent) ':' num2str(array(index-1)) ' ' num2str(array(index))];
end;
end;
skip = 0;
indent = array(index) - array(index-1);
else
skip = skip + 1;
end;
end;
if array(index) == array(index-1)+indent
if skip ~= 0
if indent == 1
str = [str ':' num2str(array(index)) ];
elseif indent == 0
str = [str ' ' num2str(array(index)) ];
else
str = [str ':' num2str(indent) ':' num2str(array(index)) ];
end;
end;
end;
else
if length(array) < 10
str = num2str(array(1));
for index = 2:length(array)
str = [str ' ' num2str(array(index)) ];
end;
else
str = num2str(double(array));
end;
end;
|
github
|
lcnbeapp/beapp-master
|
unique_bc.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/unique_bc.m
| 717 |
utf_8
|
1ac4b80ca073d969c0b6d0e7a0db1f3d
|
% unique_bc - unique backward compatible with Matlab versions prior to 2013a
function [C,IA,IB] = unique_bc(A,varargin);
errorFlag = error_bc;
v = version;
indp = find(v == '.');
v = str2num(v(1:indp(2)-1));
if v > 7.19, v = floor(v) + rem(v,1)/10; end;
if nargin > 2
ind = strmatch('legacy', varargin);
if ~isempty(ind)
varargin(ind) = [];
end;
end;
if v >= 7.14
[C,IA,IB] = unique(A,varargin{:},'legacy');
if errorFlag
[C2,IA2] = unique(A,varargin{:});
if ~isequal(C, C2) || ~isequal(IA, IA2) || ~isequal(IB, IB2)
warning('backward compatibility issue with call to unique function');
end;
end;
else
[C,IA,IB] = unique(A,varargin{:});
end;
|
github
|
lcnbeapp/beapp-master
|
setdiff_bc.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/setdiff_bc.m
| 704 |
utf_8
|
6ff610d1b3099610817bea2fc877650d
|
% setdiff_bc - setdiff backward compatible with Matlab versions prior to 2013a
function [C,IA] = setdiff_bc(A,B,varargin);
errorFlag = error_bc;
v = version;
indp = find(v == '.');
v = str2num(v(1:indp(2)-1));
if v > 7.19, v = floor(v) + rem(v,1)/10; end;
if nargin > 2
ind = strmatch('legacy', varargin);
if ~isempty(ind)
varargin(ind) = [];
end;
end;
if v >= 7.14
[C,IA] = setdiff(A,B,varargin{:},'legacy');
if errorFlag
[C2,IA2] = setdiff(A,B,varargin{:});
if (~isequal(C, C2) || ~isequal(IA, IA2))
warning('backward compatibility issue with call to setdiff function');
end;
end;
else
[C,IA] = setdiff(A,B,varargin{:});
end;
|
github
|
lcnbeapp/beapp-master
|
union_bc.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/union_bc.m
| 724 |
utf_8
|
958b5b56de3e20c3892b2d7809e830fd
|
% union_bc - union backward compatible with Matlab versions prior to 2013a
function [C,IA,IB] = union_bc(A,B,varargin);
errorFlag = error_bc;
v = version;
indp = find(v == '.');
v = str2num(v(1:indp(2)-1));
if v > 7.19, v = floor(v) + rem(v,1)/10; end;
if nargin > 2
ind = strmatch('legacy', varargin);
if ~isempty(ind)
varargin(ind) = [];
end;
end;
if v >= 7.14
[C,IA,IB] = union(A,B,varargin{:},'legacy');
if errorFlag
[C2,IA2,IB2] = union(A,B,varargin{:});
if (~isequal(C, C2) || ~isequal(IA, IA2) || ~isequal(IB, IB2))
warning('backward compatibility issue with call to union function');
end;
end;
else
[C,IA,IB] = union(A,B,varargin{:});
end;
|
github
|
lcnbeapp/beapp-master
|
getkeyval.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/getkeyval.m
| 4,294 |
utf_8
|
f3f11db9f974963b9b8b34e48f778ae9
|
% getkeyval() - get variable value from a 'key', 'val' sequence string.
%
% Usage:
% >> val = getkeyval( keyvalstr, varname, mode, defaultval);
%
% Inputs:
% keyvalstr - string containing 'key', 'val' arguments
% varname - string for the name of the variable or index
% of the value to retrieve (assuming arguments are
% separated by comas).
% mode - if the value extracted is an integer array, the
% 'mode' variable can contain a subset of indexes to return.
% If mode is 'present', then either 0 or 1 is returned
% depending on wether the variable is present.
% defaultval - default value if the varible is not found
%
% Outputs:
% val - a value for the variable
%
% Note: this function is helpful for finding arguments in string commands
% stored in command history.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 29 July 2002
%
% See also: gethelpvar()
% Copyright (C) 2002 [email protected], Arnaud Delorme, CNL / Salk Institute
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function txt = getkeyval(lastcom, var, mode, default)
% mode can be present for 0 and 1 if the variable is present
if nargin < 1
help getkeyval;
return;
end;
if nargin < 4
default = '';
end;
if isempty(lastcom)
txt = default; return;
end;
if nargin < 3
mode = '';
end;
if isstr(mode) & strcmp(mode, 'present')
if ~isempty(findstr(var, lastcom))
txt = 1; return;
else
txt = 0; return;
end;
end;
if isnumeric(var)
comas = findstr(lastcom, ',');
if length(comas) >= var
txt = lastcom(comas(var-1)+1:comas(var)-1);
tmpval = eval( txt );
if isempty(tmpval), txt = '';
else txt = vararg2str( tmpval );
end;
return;
% txt = deblank(txt(end:-1:1));
% txt = deblank(txt(end:-1:1));
%
% if ~isempty(txt) & txt(end) == '}', txt = txt(2:end-1); end;
% if ~isempty(txt)
% txt = deblank(txt(end:-1:1));
% txt = deblank(txt(end:-1:1));
% end;
% if ~isempty(txt) & txt(end) == ']', txt = txt(2:end-1); end;
% if ~isempty(txt)
% txt = deblank(txt(end:-1:1));
% txt = deblank(txt(end:-1:1));
% end;
% if ~isempty(txt) & txt(end) == '''', txt = txt(2:end-1); end;
else
txt = default;
end;
%fprintf('%s:%s\n', var, txt);
return;
else
comas = findstr(lastcom, ','); % finding all comas
comas = [ comas findstr(lastcom, ');') ]; % and end of lines
varloc = findstr(lastcom, var);
if ~isempty(varloc)
% finding comas surrounding 'val' var in 'key', 'val' sequence
comas = comas(find(comas >varloc(end)));
txt = lastcom(comas(1)+1:comas(2)-1);
txt = deblank(txt(end:-1:1));
txt = deblank(txt(end:-1:1));
if strcmp(mode, 'full')
parent = findstr(lastcom, '}');
if ~isempty(parent)
comas = comas(find(comas >parent(1)));
txt = lastcom(comas(1)+1:comas(2)-1);
end;
txt = [ '''' var ''', ' txt ];
elseif isnumeric(mode)
txt = str2num(txt);
if ~isempty(mode)
if length(txt) >= max(mode)
if all(isnan(txt(mode))), txt = '';
else txt = num2str(txt(mode));
end;
elseif length(txt) >= mode(1)
if all(isnan(txt(mode(1)))), txt = '';
else txt = num2str(txt(mode(1)));
end;
else
txt = default;
end;
else
txt = num2str(txt);
end;
elseif txt(1) == ''''
txt = txt(2:end-1); % remove quotes for text
end;
else
txt = default;
end;
end;
%fprintf('%s:%s\n', var, txt);
|
github
|
lcnbeapp/beapp-master
|
is_sccn.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/is_sccn.m
| 388 |
utf_8
|
99847041e8b1f185a51f93939d33b819
|
% is_sccn() - returns 1 if computer is located at SCCN (Swartz Center
% for computational Neuroscience) and 0 otherwise
function bool = is_sccn;
bool = 0;
domnane = ' ';
try
eval([ 'if isunix, [tmp domname] = unix(''hostname -d'');' ...
'end;' ...
'bool = strcmpi(domname(1:end-1), ''ucsd.edu'');' ], '');
catch,
end;
|
github
|
lcnbeapp/beapp-master
|
gettext.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/gettext.m
| 2,465 |
utf_8
|
414488f77905ebf88c561e892df73cd7
|
% gettext() - This function prints a dialog box on screen and waits for
% the user to enter a string. There is a cancel button which
% returns a value of [].
% Usage:
% >> out = gettext(label1,label2,...,label7);
%
% Author: Colin Humphries, CNL / Salk Institute, La Jolla, 1997
% Copyright (C) 1997 Colin Humphries, Salk Institute
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
function out = gettext(label1,label2,label3,label4,label5,label6,label7);
global is_text_entered
is_text_entered = 0;
for i = 1:nargin
eval(['leng(i) = length(label',num2str(i),');'])
end
figurelength = 15*1.0*max(leng);
if figurelength < 240
figurelength = 290;
end
figureheight = 80+nargin*18;
% Set figure
figure('Position',[302 396 figurelength figureheight],'color',[.6 .6 .6],'NumberTitle','off')
f1 = gcf;
ax = axes('Units','Pixels','Position',[0 0 figurelength figureheight],'Visible','off','XLim',[0 figurelength],'YLim',[0 figureheight]);
for i = 1:nargin
eval(['text(figurelength/2,',num2str(figureheight-(i-1)*18-20),',label',num2str(i),',''color'',''k'',''FontSize'',16,''HorizontalAlignment'',''center'')'])
end
% Set up uicontrols
TIMESTRING = ['global is_text_entered;is_text_entered = 1;clear is_text_entered'];
u = uicontrol('Style','Edit','Units','Pixels','Position',[15 20 figurelength-95 25],'HorizontalAlignment','left','Callback',TIMESTRING);
TIMESTRING = ['global is_text_entered;is_text_entered = 2;clear is_text_entered'];
v = uicontrol('Style','Pushbutton','Units','Pixels','Position',[figurelength-70 20 55 25],'String','Cancel','Callback',TIMESTRING);
while(is_text_entered == 0)
drawnow
end
if is_text_entered == 1
out = get(u,'string');
else
out = [];
end
clear is_text_entered
delete(f1)
|
github
|
lcnbeapp/beapp-master
|
eeg_getdatact.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/eeg_getdatact.m
| 12,037 |
utf_8
|
bc4bb0dfeb0f9183cb320544ba36fbdd
|
% eeg_getdatact() - get EEG data from a specified dataset or
% component activity
%
% Usage:
% >> signal = eeg_getdatact( EEG );
% >> signal = eeg_getdatact( EEG, 'key', 'val');
%
% Inputs:
% EEG - Input dataset
%
% Optional input:
% 'channel' - [integer array] read only specific channels.
% Default is to read all data channels.
% 'component' - [integer array] read only specific components
% 'projchan' - [integer or cell array] channel(s) onto which the component
% should be projected.
% 'rmcomps' - [integer array] remove selected components from data
% channels. This is only to be used with channel data not
% when selecting components.
% 'trialindices' - [integer array] only read specific trials. Default is
% to read all trials.
% 'samples' - [integer array] only read specific samples. Default is
% to read all samples.
% 'reshape' - ['2d'|'3d'] reshape data. Default is '3d' when possible.
% 'verbose' - ['on'|'off'] verbose mode. Default is 'on'.
%
% Outputs:
% signal - EEG data or component activity
%
% Author: Arnaud Delorme, SCCN & CERCO, CNRS, 2008-
%
% See also: eeg_checkset()
% Copyright (C) 15 Feb 2002 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [data boundaries] = eeg_getdatact( EEG, varargin);
data = [];
if nargin < 1
help eeg_getdatact;
return;
end;
% reading data from several datasets and concatening it
% -----------------------------------------------------
if iscell(EEG) || (~isstr(EEG) && length(EEG) > 1)
% decode some arguments
% ---------------------
trials = cell(1,length(EEG));
rmcomps = cell(1,length(EEG));
for iArg = length(varargin)-1:-2:1
if strcmpi(varargin{iArg}, 'trialindices')
trials = varargin{iArg+1};
varargin(iArg:iArg+1) = [];
elseif strcmpi(varargin{iArg}, 'rmcomps')
rmcomps = varargin{iArg+1};
varargin(iArg:iArg+1) = [];
end;
end;
if isnumeric(rmcomps), rmtmp = rmcomps; rmcomps = cell(1,length(EEG)); rmcomps(:) = { rmtmp }; end;
% concatenate datasets
% --------------------
data = [];
boundaries = [];
for dat = 1:length(EEG)
if iscell(EEG)
[tmpdata datboundaries] = eeg_getdatact(EEG{dat}, 'trialindices', trials{dat}, 'rmcomps', rmcomps{dat}, varargin{:} );
else [tmpdata datboundaries] = eeg_getdatact(EEG(dat), 'trialindices', trials{dat}, 'rmcomps', rmcomps{dat}, varargin{:} );
end;
if isempty(data),
data = tmpdata;
boundaries = datboundaries;
else
if all([ EEG.trials ] == 1) % continuous data
if size(data,1) ~= size(tmpdata,1), error('Datasets to be concatenated do not have the same number of channels'); end;
% adding boundaries
if ~isempty(datboundaries)
boundaries = [boundaries datboundaries size(data,2)];
else
boundaries = [boundaries size(data,2)];
end;
data(:,end+1:end+size(tmpdata,2)) = tmpdata; % concatenating trials
else
if size(data,1) ~= size(tmpdata,1), error('Datasets to be concatenated do not have the same number of channels'); end;
if size(data,2) ~= size(tmpdata,2), error('Datasets to be concatenated do not have the same number of time points'); end;
data(:,:,end+1:end+size(tmpdata,3)) = tmpdata; % concatenating trials
end;
end;
end;
return;
end;
% if string load dataset
% ----------------------
if isstr(EEG)
EEG = pop_loadset('filename', EEG, 'loadmode', 'info');
end;
opt = finputcheck(varargin, { ...
'channel' 'integer' {} [];
'verbose' 'string' { 'on','off' } 'on';
'reshape' 'string' { '2d','3d' } '3d';
'projchan' {'integer','cell' } { {} {} } [];
'component' 'integer' {} [];
'samples' 'integer' {} [];
'interp' 'struct' { } struct([]);
'trialindices' {'integer','cell'} { {} {} } [];
'rmcomps' {'integer','cell'} { {} {} } [] }, 'eeg_getdatact');
if isstr(opt), error(opt); end;
channelNotDefined = 0;
if isempty(opt.channel), opt.channel = [1:EEG.nbchan]; channelNotDefined = 1;
elseif isequal(opt.channel, [1:EEG.nbchan]) && ~isempty(opt.interp) channelNotDefined = 1;
end;
if isempty(opt.trialindices), opt.trialindices = [1:EEG.trials]; end;
if iscell( opt.trialindices), opt.trialindices = opt.trialindices{1}; end;
if iscell(opt.rmcomps ), opt.rmcomps = opt.rmcomps{1}; end;
if (~isempty(opt.rmcomps) | ~isempty(opt.component)) & isempty(EEG.icaweights)
error('No ICA weight in dataset');
end;
if strcmpi(EEG.data, 'in set file')
EEG = pop_loadset('filename', EEG.filename, 'filepath', EEG.filepath);
end;
% get data boundaries if continuous data
% --------------------------------------
boundaries = [];
if nargout > 1 && EEG.trials == 1 && ~isempty(EEG.event) && isfield(EEG.event, 'type') && isstr(EEG.event(1).type)
if ~isempty(opt.samples)
disp('WARNING: eeg_getdatact.m, boundaries are not accurate when selecting data samples');
end;
tmpevent = EEG.event;
tmpbound = strmatch('boundary', lower({ tmpevent.type }));
if ~isempty(tmpbound)
boundaries = [tmpevent(tmpbound).latency ]-0.5;
end;
end;
% getting channel or component activation
% ---------------------------------------
filename = fullfile(EEG.filepath, [ EEG.filename(1:end-4) '.icaact' ] );
if ~isempty(opt.component) & ~isempty(EEG.icaact)
data = EEG.icaact(opt.component,:,:);
elseif ~isempty(opt.component) & exist(filename)
% reading ICA file
% ----------------
data = repmat(single(0), [ length(opt.component) EEG.pnts EEG.trials ]);
fid = fopen( filename, 'r', 'ieee-le'); %little endian (see also pop_saveset)
if fid == -1, error( ['file ' filename ' could not be open' ]); end;
for ind = 1:length(opt.component)
fseek(fid, (opt.component(ind)-1)*EEG.pnts*EEG.trials*4, -1);
data(ind,:) = fread(fid, [EEG.trials*EEG.pnts 1], 'float32')';
end;
fclose(fid);
elseif ~isempty(opt.component)
if isempty(EEG.icaact)
data = eeg_getdatact( EEG );
data = (EEG.icaweights(opt.component,:)*EEG.icasphere)*data(EEG.icachansind,:);
else
data = EEG.icaact(opt.component,:,:);
end;
else
if isnumeric(EEG.data) % channel
data = EEG.data;
else % channel but no data loaded
filename = fullfile(EEG.filepath, EEG.data);
fid = fopen( filename, 'r', 'ieee-le'); %little endian (see also pop_saveset)
if fid == -1
error( ['file ' filename ' not found. If you have renamed/moved' 10 ...
'the .set file, you must also rename/move the associated data file.' ]);
else
if strcmpi(opt.verbose, 'on')
fprintf('Reading float file ''%s''...\n', filename);
end;
end;
% old format = .fdt; new format = .dat (transposed)
% -------------------------------------------------
datformat = 0;
if length(filename) > 3
if strcmpi(filename(end-2:end), 'dat')
datformat = 1;
end;
end;
EEG.datfile = EEG.data;
% reading data file
% -----------------
eeglab_options;
if length(opt.channel) == EEG.nbchan && option_memmapdata
fclose(fid);
data = mmo(filename, [EEG.nbchan EEG.pnts EEG.trials], false);
%data = memmapdata(filename, [EEG.nbchan EEG.pnts EEG.trials]);
else
if datformat
if length(opt.channel) == EEG.nbchan || ~isempty(opt.interp)
data = fread(fid, [EEG.trials*EEG.pnts EEG.nbchan], 'float32')';
else
data = repmat(single(0), [ length(opt.channel) EEG.pnts EEG.trials ]);
for ind = 1:length(opt.channel)
fseek(fid, (opt.channel(ind)-1)*EEG.pnts*EEG.trials*4, -1);
data(ind,:) = fread(fid, [EEG.trials*EEG.pnts 1], 'float32')';
end;
opt.channel = [1:size(data,1)];
end;
else
data = fread(fid, [EEG.nbchan Inf], 'float32');
end;
fclose(fid);
end;
end;
% subracting components from data
% -------------------------------
if ~isempty(opt.rmcomps)
if strcmpi(opt.verbose, 'on')
fprintf('Removing %d artifactual components\n', length(opt.rmcomps));
end;
rmcomps = eeg_getdatact( EEG, 'component', opt.rmcomps); % loaded from file
rmchan = [];
rmchanica = [];
for index = 1:length(opt.channel)
tmpicaind = find(opt.channel(index) == EEG.icachansind);
if ~isempty(tmpicaind)
rmchan = [ rmchan index ];
rmchanica = [ rmchanica tmpicaind ];
end;
end;
data(rmchan,:) = data(rmchan,:) - EEG.icawinv(rmchanica,opt.rmcomps)*rmcomps(:,:);
%EEG = eeg_checkset(EEG, 'loaddata');
%EEG = pop_subcomp(EEG, opt.rmcomps);
%data = EEG.data(opt.channel,:,:);
%if strcmpi(EEG.subject, 'julien') & strcmpi(EEG.condition, 'oddball') & strcmpi(EEG.group, 'after')
% jjjjf
%end;
end;
if ~isempty(opt.interp)
EEG.data = data;
EEG.event = [];
EEG.epoch = [];
EEG = eeg_interp(EEG, opt.interp, 'spherical');
data = EEG.data;
if channelNotDefined, opt.channel = [1:EEG.nbchan]; end;
end;
if ~isequal(opt.channel, [1:EEG.nbchan])
data = data(intersect(opt.channel,[1:EEG.nbchan]),:,:);
end;
end;
% projecting components on data channels
% --------------------------------------
if ~isempty(opt.projchan)
if iscell(opt.projchan)
opt.projchan = std_chaninds(EEG, opt.projchan);
end;
finalChanInds = [];
for iChan = 1:length(opt.projchan)
tmpInd = find(EEG.icachansind == opt.projchan(iChan));
if isempty(tmpInd)
error(sprintf('Warning: can not backproject component on channel %d (not used for ICA)\n', opt.projchan(iChan)));
end;
finalChanInds = [ finalChanInds tmpInd ];
end;
data = EEG.icawinv(finalChanInds, opt.component)*data(:,:);
end;
if size(data,2)*size(data,3) ~= EEG.pnts*EEG.trials
disp('WARNING: The file size on disk does not correspond to the dataset, file has been truncated');
end;
try,
if EEG.trials == 1, EEG.pnts = size(data,2); end;
if strcmpi(opt.reshape, '3d')
data = reshape(data, size(data,1), EEG.pnts, EEG.trials);
else data = reshape(data, size(data,1), EEG.pnts*EEG.trials);
end;
catch
error('The file size on disk does not correspond to the dataset information.');
end;
% select trials
% -------------
if length(opt.trialindices) ~= EEG.trials
data = data(:,:,opt.trialindices);
end;
if ~isempty(opt.samples)
data = data(:,opt.samples,:);
end;
|
github
|
lcnbeapp/beapp-master
|
eeg_readoptions.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/eeg_readoptions.m
| 3,419 |
utf_8
|
4104fa6db19f22201a63ba183b0d2f5f
|
% eeg_readoptions() - Read EEGLAB memory options file (eeg_options) into a
% structure variable (opt).
%
% Usage:
% [ header, opt ] = eeg_readoptions( filename, opt );
%
% Input:
% filename - [string] name of the option file
% opt - [struct] option structure containing backup values
%
% Outputs:
% header - [string] file header.
% opt - [struct] option structure containing an array of 3 fields
% varname -> all variable names.
% value -> value for each variable name
% description -> all description associated with each variable
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2006-
%
% See also: eeg_options(), eeg_editoptions()
% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, 2006-
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ header, opt ] = eeg_readoptions( filename, opt_backup );
if nargin < 1
help eeg_readoptions;
return;
end;
if nargin < 2
opt_backup = [];
end;
if isstr(filename)
fid = fopen(filename, 'r');
else fid = filename;
end;
% skip header
% -----------
header = '';
str = fgets( fid );
while (str(1) == '%')
header = [ header str];
str = fgets( fid );
end;
% read variables values and description
% --------------------------------------
str = fgetl( fid ); % jump a line
index = 1;
opt = [];
while (str(1) ~= -1)
if str(1) == '%'
opt(index).description = str(3:end-1);
opt(index).value = [];
opt(index).varname = '';
else
[ opt(index).varname str ] = strtok(str); % variable name
[ equal str ] = strtok(str); % =
[ opt(index).value str ] = strtok(str); % value
[ tmp str ] = strtok(str); % ;
[ tmp dsc ] = strtok(str); % comment
dsc = deblank( dsc(end:-1:1) );
opt(index).description = deblank( dsc(end:-1:1) );
opt(index).value = str2num( opt(index).value );
end;
str = fgets( fid ); % jump a line
index = index+1;
end;
fclose(fid);
% replace in backup structure if any
% ----------------------------------
if ~isempty(opt_backup)
if ~isempty(opt)
for index = 1:length(opt_backup)
ind = strmatch(opt_backup(index).varname, { opt.varname }, 'exact');
if ~isempty(ind) & ~isempty(opt_backup(index).varname)
opt_backup(index).value = opt(ind).value;
end;
end;
end;
opt = opt_backup;
end;
|
github
|
lcnbeapp/beapp-master
|
hlp_argstruct2linearcell.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/hlp_argstruct2linearcell.m
| 1,953 |
utf_8
|
cf2a64e0864d59a83ffeefe20c9f2b09
|
% hlp_argstruct2linearcell() - Linearize configation output of arg_guipanel
%
% Usage:
% >> cellval = hlp_argstruct2linearcells( cfg );
%
% Inputs:
% cfg - output configuration structure from arg_guipanel
%
% Output:
% cellval - cell array of output values
%
% Author: Arnaud Delorme, SCCN & CERCO, CNRS, 2013-
% Copyright (C) 2013 Arnaud Delorme
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function cellval = hlp_argstruct2linearcell(cfg);
cellval = {};
if isstruct(cfg)
ff = fieldnames(cfg);
for iField = 1:length(ff)
if ~strcmpi(ff{iField}, 'arg_direct')
if strcmpi(ff{iField}, 'arg_selection')
cellval = { cfg.arg_selection cellval{:} };
else
val = cfg.(ff{iField});
if isstruct(val)
val = hlp_argstruct2linearcell(val);
cellval = { cellval{:} ff{iField} val{:} };
elseif iscell(val)
cellval = { cellval{:} ff{iField} vararg2str(val) };
else
cellval = { cellval{:} ff{iField} val };
end;
end;
end;
end
else
cellval = cfg;
end;
|
github
|
lcnbeapp/beapp-master
|
eeg_checkset.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/eeg_checkset.m
| 67,343 |
utf_8
|
74bd5c7e30d59db57d1939717b297f08
|
% eeg_checkset() - check the consistency of the fields of an EEG dataset
% Also: See EEG dataset structure field descriptions below.
%
% Usage: >> [EEGOUT,changes] = eeg_checkset(EEG); % perform all checks
% except 'makeur'
% >> [EEGOUT,changes] = eeg_checkset(EEG, 'keyword'); % perform 'keyword' check(s)
%
% Inputs:
% EEG - EEGLAB dataset structure or (ALLEEG) array of EEG structures
%
% Optional keywords:
% 'icaconsist' - if EEG contains several datasets, check whether they have
% the same ICA decomposition
% 'epochconsist' - if EEG contains several datasets, check whether they have
% identical epoch lengths and time limits.
% 'chanconsist' - if EEG contains several datasets, check whether they have
% the same number of channela and channel labels.
% 'data' - check whether EEG contains data (EEG.data)
% 'loaddata' - load data array (if necessary)
% 'savedata' - save data array (if necessary - see EEG.saved below)
% 'contdata' - check whether EEG contains continuous data
% 'epoch' - check whether EEG contains epoched or continuous data
% 'ica' - check whether EEG contains an ICA decomposition
% 'besa' - check whether EEG contains component dipole locations
% 'event' - check whether EEG contains an event array
% 'makeur' - remake the EEG.urevent structure
% 'checkur' - check whether the EEG.urevent structure is consistent
% with the EEG.event structure
% 'chanlocsize' - check the EEG.chanlocs structure length; show warning if
% necessary.
% 'chanlocs_homogeneous' - check whether EEG contains consistent channel
% information; if not, correct it.
% 'eventconsistency' - check whether EEG.event information are consistent;
% rebuild event* subfields of the 'EEG.epoch' structure
% (can be time consuming).
% Outputs:
% EEGOUT - output EEGLAB dataset or dataset array
% changes - change code: 'no' = no changes; 'yes' = the EEG
% structure was modified
%
% ===========================================================
% The structure of an EEG dataset under EEGLAB (as of v5.03):
%
% Basic dataset information:
% EEG.setname - descriptive name|title for the dataset
% EEG.filename - filename of the dataset file on disk
% EEG.filepath - filepath (directory/folder) of the dataset file(s)
% EEG.trials - number of epochs (or trials) in the dataset.
% If data are continuous, this number is 1.
% EEG.pnts - number of time points (or data frames) per trial (epoch).
% If data are continuous (trials=1), the total number
% of time points (frames) in the dataset
% EEG.nbchan - number of channels
% EEG.srate - data sampling rate (in Hz)
% EEG.xmin - epoch start latency|time (in sec. relative to the
% time-locking event at time 0)
% EEG.xmax - epoch end latency|time (in seconds)
% EEG.times - vector of latencies|times in seconds (one per time point)
% EEG.ref - ['common'|'averef'|integer] reference channel type or number
% EEG.history - cell array of ascii pop-window commands that created
% or modified the dataset
% EEG.comments - comments about the nature of the dataset (edit this via
% menu selection Edit > About this dataset)
% EEG.etc - miscellaneous (technical or temporary) dataset information
% EEG.saved - ['yes'|'no'] 'no' flags need to save dataset changes before exit
%
% The data:
% EEG.data - two-dimensional continuous data array (chans, frames)
% ELSE, three-dim. epoched data array (chans, frames, epochs)
%
% The channel locations sub-structures:
% EEG.chanlocs - structure array containing names and locations
% of the channels on the scalp
% EEG.urchanlocs - original (ur) dataset chanlocs structure containing
% all channels originally collected with these data
% (before channel rejection)
% EEG.chaninfo - structure containing additional channel info
% EEG.ref - type of channel reference ('common'|'averef'|+/-int]
% EEG.splinefile - location of the spline file used by headplot() to plot
% data scalp maps in 3-D
%
% The event and epoch sub-structures:
% EEG.event - event structure containing times and nature of experimental
% events recorded as occurring at data time points
% EEG.urevent - original (ur) event structure containing all experimental
% events recorded as occurring at the original data time points
% (before data rejection)
% EEG.epoch - epoch event information and epoch-associated data structure array (one per epoch)
% EEG.eventdescription - cell array of strings describing event fields.
% EEG.epochdescription - cell array of strings describing epoch fields.
% --> See the http://sccn.ucsd.edu/eeglab/maintut/eeglabscript.html for details
%
% ICA (or other linear) data components:
% EEG.icasphere - sphering array returned by linear (ICA) decomposition
% EEG.icaweights - unmixing weights array returned by linear (ICA) decomposition
% EEG.icawinv - inverse (ICA) weight matrix. Columns gives the projected
% topographies of the components to the electrodes.
% EEG.icaact - ICA activations matrix (components, frames, epochs)
% Note: [] here means that 'compute_ica' option has bee set
% to 0 under 'File > Memory options' In this case,
% component activations are computed only as needed.
% EEG.icasplinefile - location of the spline file used by headplot() to plot
% component scalp maps in 3-D
% EEG.chaninfo.icachansind - indices of channels used in the ICA decomposition
% EEG.dipfit - array of structures containing component map dipole models
%
% Variables indicating membership of the dataset in a studyset:
% EEG.subject - studyset subject code
% EEG.group - studyset group code
% EEG.condition - studyset experimental condition code
% EEG.session - studyset session number
%
% Variables used for manual and semi-automatic data rejection:
% EEG.specdata - data spectrum for every single trial
% EEG.specica - data spectrum for every single trial
% EEG.stats - statistics used for data rejection
% EEG.stats.kurtc - component kurtosis values
% EEG.stats.kurtg - global kurtosis of components
% EEG.stats.kurta - kurtosis of accepted epochs
% EEG.stats.kurtr - kurtosis of rejected epochs
% EEG.stats.kurtd - kurtosis of spatial distribution
% EEG.reject - statistics used for data rejection
% EEG.reject.entropy - entropy of epochs
% EEG.reject.entropyc - entropy of components
% EEG.reject.threshold - rejection thresholds
% EEG.reject.icareject - epochs rejected by ICA criteria
% EEG.reject.gcompreject - rejected ICA components
% EEG.reject.sigreject - epochs rejected by single-channel criteria
% EEG.reject.elecreject - epochs rejected by raw data criteria
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% 01-26-02 chandeg events and trial condition format -ad
% 01-27-02 debug when trial condition is empty -ad
% 02-15-02 remove icawinv recompute for pop_epoch -ad & ja
% 02-16-02 remove last modification and test icawinv separatelly -ad
% 02-16-02 empty event and epoch check -ad
% 03-07-02 add the eeglab options -ad
% 03-07-02 corrected typos and rate/point calculation -ad & ja
% 03-15-02 add channel location reading & checking -ad
% 03-15-02 add checking of ICA and epochs with pop_up windows -ad
% 03-27-02 recorrected rate/point calculation -ad & sm
function [EEG, res] = eeg_checkset( EEG, varargin );
msg = '';
res = 'no';
com = sprintf('EEG = eeg_checkset( EEG );');
if nargin < 1
help eeg_checkset;
return;
end;
if isempty(EEG), return; end;
if ~isfield(EEG, 'data'), return; end;
% checking multiple datasets
% --------------------------
if length(EEG) > 1
if nargin > 1
switch varargin{1}
case 'epochconsist', % test epoch consistency
% ----------------------
res = 'no';
datasettype = unique_bc( [ EEG.trials ] );
if datasettype(1) == 1 & length(datasettype) == 1, return; % continuous data
elseif datasettype(1) == 1, return; % continuous and epoch data
end;
allpnts = unique_bc( [ EEG.pnts ] );
allxmin = unique_bc( [ EEG.xmin ] );
if length(allpnts) == 1 & length(allxmin) == 1, res = 'yes'; end;
return;
case 'chanconsist' % test channel number and name consistency
% ----------------------------------------
res = 'yes';
chanlen = unique_bc( [ EEG.nbchan ] );
anyempty = unique_bc( cellfun( 'isempty', { EEG.chanlocs }) );
if length(chanlen) == 1 & all(anyempty == 0)
tmpchanlocs = EEG(1).chanlocs;
channame1 = { tmpchanlocs.labels };
for i = 2:length(EEG)
tmpchanlocs = EEG(i).chanlocs;
channame2 = { tmpchanlocs.labels };
if length(intersect(channame1, channame2)) ~= length(channame1), res = 'no'; end;
end;
else res = 'no';
end;
return;
case 'icaconsist' % test ICA decomposition consistency
% ----------------------------------
res = 'yes';
anyempty = unique_bc( cellfun( 'isempty', { EEG.icaweights }) );
if length(anyempty) == 1 & anyempty(1) == 0
ica1 = EEG(1).icawinv;
for i = 2:length(EEG)
if ~isequal(EEG(1).icawinv, EEG(i).icawinv)
res = 'no';
end;
end;
else res = 'no';
end;
return;
end;
end;
end;
% reading these option take time because
% of disk access
% --------------
eeglab_options;
% standard checking
% -----------------
ALLEEG = EEG;
for inddataset = 1:length(ALLEEG)
EEG = ALLEEG(inddataset);
% additional checks
% -----------------
res = -1; % error code
if ~isempty( varargin)
for index = 1:length( varargin )
switch varargin{ index }
case 'data',; % already done at the top
case 'contdata',;
if EEG.trials > 1
errordlg2(strvcat('Error: function only works on continuous data'), 'Error');
return;
end;
case 'ica',
if isempty(EEG.icaweights)
errordlg2(strvcat('Error: no ICA decomposition. use menu "Tools > Run ICA" first.'), 'Error');
return;
end;
case 'epoch',
if EEG.trials == 1
errordlg2(strvcat('Extract epochs before running that function', 'Use Tools > Extract epochs'), 'Error');
return
end;
case 'besa',
if ~isfield(EEG, 'sources')
errordlg2(strvcat('No dipole information', '1) Export component maps: Tools > Localize ... BESA > Export ...' ...
, '2) Run BESA to localize the equivalent dipoles', ...
'3) Import the BESA dipoles: Tools > Localize ... BESA > Import ...'), 'Error');
return
end;
case 'event',
if isempty(EEG.event)
errordlg2(strvcat('Requires events. You need to add events first.', ...
'Use "File > Import event info" or "File > Import epoch info"'), 'Error');
return;
end;
case 'chanloc',
tmplocs = EEG.chanlocs;
if isempty(tmplocs) || ~isfield(tmplocs, 'theta') || all(cellfun('isempty', { tmplocs.theta }))
errordlg2( strvcat('This functionality requires channel location information.', ...
'Enter the channel file name via "Edit > Edit dataset info".', ...
'For channel file format, see ''>> help readlocs'' from the command line.'), 'Error');
return;
end;
case 'chanlocs_homogeneous',
tmplocs = EEG.chanlocs;
if isempty(tmplocs) || ~isfield(tmplocs, 'theta') || all(cellfun('isempty', { tmplocs.theta }))
errordlg2( strvcat('This functionality requires channel location information.', ...
'Enter the channel file name via "Edit > Edit dataset info".', ...
'For channel file format, see ''>> help readlocs'' from the command line.'), 'Error');
return;
end;
if ~isfield(EEG.chanlocs, 'X') || isempty(EEG.chanlocs(1).X)
EEG.chanlocs = convertlocs(EEG.chanlocs, 'topo2all');
res = [ inputname(1) ' = eeg_checkset(' inputname(1) ', ''chanlocs_homogeneous'' ); ' ];
end;
case 'chanlocsize',
if ~isempty(EEG.chanlocs)
if length(EEG.chanlocs) > EEG.nbchan
questdlg2(strvcat('Warning: there is one more electrode location than', ...
'data channels. EEGLAB will consider the last electrode to be the', ...
'common reference channel. If this is not the case, remove the', ...
'extra channel'), 'Warning', 'Ok', 'Ok');
end;
end;
case 'makeur',
if ~isempty(EEG.event)
if isfield(EEG.event, 'urevent'),
EEG.event = rmfield(EEG.event, 'urevent');
disp('eeg_checkset note: re-creating the original event table (EEG.urevent)');
else
disp('eeg_checkset note: creating the original event table (EEG.urevent)');
end;
EEG.urevent = EEG.event;
for index = 1:length(EEG.event)
EEG.event(index).urevent = index;
end;
end;
case 'checkur',
if ~isempty(EEG.event)
if isfield(EEG.event, 'urevent') & ~isempty(EEG.urevent)
urlatencies = [ EEG.urevent.latency ];
[newlat tmpind] = sort(urlatencies);
if ~isequal(newlat, urlatencies)
EEG.urevent = EEG.urevent(tmpind);
[tmp tmpind2] = sort(tmpind);
for index = 1:length(EEG.event)
EEG.event(index).urevent = tmpind2(EEG.event(index).urevent);
end;
end;
end;
end;
case 'eventconsistency',
[EEG res] = eeg_checkset(EEG);
if isempty(EEG.event), return; end;
% check events (slow)
% ------------
if isfield(EEG.event, 'type')
eventInds = arrayfun(@(x)isempty(x.type), EEG.event);
if any(eventInds)
if all(arrayfun(@(x)isnumeric(x.type), EEG.event))
for ind = find(eventInds), EEG.event(ind).type = NaN; end;
else for ind = find(eventInds), EEG.event(ind).type = 'empty'; end;
end;
end;
if ~all(arrayfun(@(x)ischar(x.type), EEG.event)) && ~all(arrayfun(@(x)isnumeric(x.type), EEG.event))
disp('Warning: converting all event types to strings');
for ind = 1:length(EEG.event)
EEG.event(ind).type = num2str(EEG.event(ind).type);
end;
EEG = eeg_checkset(EEG, 'eventconsistency');
end;
end;
% remove the events which latency are out of boundary
% ---------------------------------------------------
if isfield(EEG.event, 'latency')
if isfield(EEG.event, 'type') && ischar(EEG.event(1).type)
if strcmpi(EEG.event(1).type, 'boundary') & isfield(EEG.event, 'duration')
if EEG.event(1).duration < 1
EEG.event(1) = [];
elseif EEG.event(1).latency > 0 & EEG.event(1).latency < 1
EEG.event(1).latency = 0.5;
end;
end;
end;
try, tmpevent = EEG.event; alllatencies = [ tmpevent.latency ];
catch, error('Checkset: error empty latency entry for new events added by user');
end;
I1 = find(alllatencies < 0.5);
I2 = find(alllatencies > EEG.pnts*EEG.trials+1); % The addition of 1 was included
% because, if data epochs are extracted from -1 to
% time 0, this allow to include the last event in
% the last epoch (otherwise all epochs have an
% event except the last one
if (length(I1) + length(I2)) > 0
fprintf('eeg_checkset warning: %d/%d events had out-of-bounds latencies and were removed\n', ...
length(I1) + length(I2), length(EEG.event));
EEG.event(union(I1, I2)) = [];
end;
end;
if isempty(EEG.event), return; end;
% save information for non latency fields updates
% -----------------------------------------------
difffield = [];
if ~isempty(EEG.event) && isfield(EEG.event, 'epoch')
% remove fields with empty epochs
% -------------------------------
removeevent = [];
try, tmpevent = EEG.event; allepochs = [ tmpevent.epoch ];
removeevent = find( allepochs < 1 | allepochs > EEG.trials);
if ~isempty(removeevent)
disp([ 'eeg_checkset warning: ' int2str(length(removeevent)) ' event had invalid epoch numbers and were removed']);
end;
catch,
for indexevent = 1:length(EEG.event)
if isempty( EEG.event(indexevent).epoch ) || ~isnumeric(EEG.event(indexevent).epoch) ...
| EEG.event(indexevent).epoch < 1 || EEG.event(indexevent).epoch > EEG.trials
removeevent = [removeevent indexevent];
disp([ 'eeg_checkset warning: event ' int2str(indexevent) ' has an invalid epoch number: removed']);
end;
end;
end;
EEG.event(removeevent) = [];
tmpevent = EEG.event;
allepochs = [ tmpevent.epoch ];
% uniformize fields content for the different epochs
% --------------------------------------------------
% THIS WAS REMOVED SINCE SOME FIELDS ARE ASSOCIATED WITH THE EVENT AND NOT WITH THE EPOCH
% I PUT IT BACK, BUT IT DOES NOT ERASE NON-EMPTY VALUES
difffield = fieldnames(EEG.event);
difffield = difffield(~(strcmp(difffield,'latency')|strcmp(difffield,'epoch')|strcmp(difffield,'type')));
for index = 1:length(difffield)
tmpevent = EEG.event;
allvalues = { tmpevent.(difffield{index}) };
try
valempt = cellfun('isempty', allvalues);
catch
valempt = mycellfun('isempty', allvalues);
end;
arraytmpinfo = cell(1,EEG.trials);
% spetial case of duration
% ------------------------
if strcmp( difffield{index}, 'duration')
if any(valempt)
fprintf(['eeg_checkset: found empty values for field ''' difffield{index} ...
''' (filling with 0)\n']);
end;
for indexevent = find(valempt)
EEG.event(indexevent).duration = 0;
end;
else
% get the field content
% ---------------------
indexevent = find(~valempt);
arraytmpinfo(allepochs(indexevent)) = allvalues(indexevent);
% uniformize content for all epochs
% ---------------------------------
indexevent = find(valempt);
tmpevent = EEG.event;
[tmpevent(indexevent).(difffield{index})] = arraytmpinfo{allepochs(indexevent)};
EEG.event = tmpevent;
if any(valempt)
fprintf(['eeg_checkset: found empty values for field ''' difffield{index} '''\n']);
fprintf([' filling with values of other events in the same epochs\n']);
end;
end;
end;
end;
if isempty(EEG.event), return; end;
% uniformize fields (str or int) if necessary
% -------------------------------------------
fnames = fieldnames(EEG.event);
for fidx = 1:length(fnames)
fname = fnames{fidx};
tmpevent = EEG.event;
allvalues = { tmpevent.(fname) };
try
% find indices of numeric values among values of this event property
valreal = ~cellfun('isclass', allvalues, 'char');
catch
valreal = mycellfun('isclass', allvalues, 'double');
end;
format = 'ok';
if ~all(valreal) % all valreal ok
format = 'str';
if all(valreal == 0) % all valreal=0 ok
format = 'ok';
end;
end;
if strcmp(format, 'str')
fprintf('eeg_checkset note: value format of event field ''%s'' made uniform\n', fname);
% get the field content
% ---------------------
for indexevent = 1:length(EEG.event)
if valreal(indexevent)
EEG.event = setfield(EEG.event, { indexevent }, fname, num2str(allvalues{indexevent}) );
end;
end;
end;
end;
% check boundary events
% ---------------------
tmpevent = EEG.event;
if isfield(tmpevent, 'type') && ~isnumeric(tmpevent(1).type)
allEventTypes = { tmpevent.type };
boundsInd = strmatch('boundary', allEventTypes);
if ~isempty(boundsInd),
bounds = [ tmpevent(boundsInd).latency ];
% remove last event if necessary
if EEG.trials==1;%this if block added by James Desjardins (Jan 13th, 2014)
if round(bounds(end)-0.5+1) >= size(EEG.data,2), EEG.event(boundsInd(end)) = []; bounds(end) = []; end; % remove final boundary if any
end
% The first boundary below need to be kept for
% urevent latency calculation
% if bounds(1) < 0, EEG.event(bounds(1)) = []; end; % remove initial boundary if any
indDoublet = find(bounds(2:end)-bounds(1:end-1)==0);
if ~isempty(indDoublet)
disp('Warning: duplicate boundary event removed');
for indBound = 1:length(indDoublet)
EEG.event(boundsInd(indDoublet(indBound)+1)).duration = EEG.event(boundsInd(indDoublet(indBound)+1)).duration+EEG.event(boundsInd(indDoublet(indBound))).duration;
end;
EEG.event(boundsInd(indDoublet)) = [];
end;
end;
end;
if isempty(EEG.event), return; end;
% check that numeric format is double (Matlab 7)
% -----------------------------------
allfields = fieldnames(EEG.event);
if ~isempty(EEG.event)
for index = 1:length(allfields)
tmpval = EEG.event(1).(allfields{index});
if isnumeric(tmpval) && ~isa(tmpval, 'double')
for indexevent = 1:length(EEG.event)
tmpval = getfield(EEG.event, { indexevent }, allfields{index} );
EEG.event = setfield(EEG.event, { indexevent }, allfields{index}, double(tmpval));
end;
end;
end;
end;
% check duration field, replace empty by 0
% ----------------------------------------
if isfield(EEG.event, 'duration')
tmpevent = EEG.event;
try, valempt = cellfun('isempty' , { tmpevent.duration });
catch, valempt = mycellfun('isempty', { tmpevent.duration });
end;
if any(valempt),
for index = find(valempt)
EEG.event(index).duration = 0;
end;
end;
end;
% resort events
% -------------
if isfield(EEG.event, 'latency')
try,
if isfield(EEG.event, 'epoch')
TMPEEG = pop_editeventvals(EEG, 'sort', { 'epoch' 0 'latency' 0 });
else
TMPEEG = pop_editeventvals(EEG, 'sort', { 'latency' 0 });
end;
if ~isequal(TMPEEG.event, EEG.event)
EEG = TMPEEG;
disp('Event resorted by increasing latencies.');
end;
catch,
disp('eeg_checkset: problem when attempting to resort event latencies.');
end;
end;
% check latency of first event
% ----------------------------
if ~isempty(EEG.event)
if isfield(EEG.event, 'latency')
if EEG.event(1).latency < 0.5
EEG.event(1).latency = 0.5;
end;
end;
end;
% build epoch structure
% ---------------------
try,
if EEG.trials > 1 & ~isempty(EEG.event)
% erase existing event-related fields
% ------------------------------
if ~isfield(EEG,'epoch')
EEG.epoch = [];
end
if ~isempty(EEG.epoch)
if length(EEG.epoch) ~= EEG.trials
disp('Warning: number of epoch entries does not match number of dataset trials;');
disp(' user-defined epoch entries will be erased.');
EEG.epoch = [];
else
fn = fieldnames(EEG.epoch);
EEG.epoch = rmfield(EEG.epoch,fn(strncmp('event',fn,5)));
end
end
% set event field
% ---------------
tmpevent = EEG.event;
eventepoch = [tmpevent.epoch];
epochevent = cell(1,EEG.trials);
destdata = epochevent;
EEG.epoch(length(epochevent)).event = [];
for k=1:length(epochevent)
epochevent{k} = find(eventepoch==k);
end
tmpepoch = EEG.epoch;
[tmpepoch.event] = epochevent{:};
EEG.epoch = tmpepoch;
maxlen = max(cellfun(@length,epochevent));
% copy event information into the epoch array
% -------------------------------------------
eventfields = fieldnames(EEG.event)';
eventfields = eventfields(~strcmp(eventfields,'epoch'));
tmpevent = EEG.event;
for k = 1:length(eventfields)
fname = eventfields{k};
switch fname
case 'latency'
sourcedata = round(eeg_point2lat([tmpevent.(fname)],[tmpevent.epoch],EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3) * 10^8 )/10^8;
sourcedata = num2cell(sourcedata);
case 'duration'
sourcedata = num2cell([tmpevent.(fname)]/EEG.srate*1000);
otherwise
sourcedata = {tmpevent.(fname)};
end
if maxlen == 1
destdata = cell(1,length(epochevent));
destdata(~cellfun('isempty',epochevent)) = sourcedata([epochevent{:}]);
else
for l=1:length(epochevent)
destdata{l} = sourcedata(epochevent{l});
end
end
tmpepoch = EEG.epoch;
[tmpepoch.(['event' fname])] = destdata{:};
EEG.epoch = tmpepoch;
end
end;
catch,
errordlg2(['Warning: minor problem encountered when generating' 10 ...
'the EEG.epoch structure (used only in user scripts)']); return;
end;
case { 'loaddata' 'savedata' 'chanconsist' 'icaconsist' 'epochconsist' }, res = '';
otherwise, error('eeg_checkset: unknown option');
end;
end;
end;
res = [];
% check name consistency
% ----------------------
if ~isempty(EEG.setname)
if ~ischar(EEG.setname)
EEG.setname = '';
else
if size(EEG.setname,1) > 1
disp('eeg_checkset warning: invalid dataset name, removed');
EEG.setname = '';
end;
end;
else
EEG.setname = '';
end;
% checking history and convert if necessary
% -----------------------------------------
if isfield(EEG, 'history') & size(EEG.history,1) > 1
allcoms = cellstr(EEG.history);
EEG.history = deblank(allcoms{1});
for index = 2:length(allcoms)
EEG.history = [ EEG.history 10 deblank(allcoms{index}) ];
end;
end;
% read data if necessary
% ----------------------
if ischar(EEG.data) & nargin > 1
if strcmpi(varargin{1}, 'loaddata')
EEG.data = eeg_getdatact(EEG);
end;
end;
% save data if necessary
% ----------------------
if nargin > 1
% datfile available?
% ------------------
datfile = 0;
if isfield(EEG, 'datfile')
if ~isempty(EEG.datfile)
datfile = 1;
end;
end;
% save data
% ---------
if strcmpi(varargin{1}, 'savedata') & option_storedisk
error('eeg_checkset: cannot call savedata any more');
% the code below is deprecated
if ~ischar(EEG.data) % not already saved
disp('Writing previous dataset to disk...');
if datfile
tmpdata = reshape(EEG.data, EEG.nbchan, EEG.pnts*EEG.trials);
floatwrite( tmpdata', fullfile(EEG.filepath, EEG.datfile), 'ieee-le');
EEG.data = EEG.datfile;
end;
EEG.icaact = [];
% saving dataset
% --------------
filename = fullfile(EEG(1).filepath, EEG(1).filename);
if ~ischar(EEG.data) & option_single, EEG.data = single(EEG.data); end;
v = version;
if str2num(v(1)) >= 7, save( filename, '-v6', '-mat', 'EEG'); % Matlab 7
else save( filename, '-mat', 'EEG');
end;
if ~ischar(EEG.data), EEG.data = 'in set file'; end;
res = sprintf('%s = eeg_checkset( %s, ''savedata'');', inputname(1), inputname(1));
end;
end;
end;
% numerical format
% ----------------
if isnumeric(EEG.data)
v = version;
EEG.icawinv = double(EEG.icawinv); % required for dipole fitting, otherwise it crashes
EEG.icaweights = double(EEG.icaweights);
EEG.icasphere = double(EEG.icasphere);
if ~isempty(findstr(v, 'R11')) | ~isempty(findstr(v, 'R12')) | ~isempty(findstr(v, 'R13'))
EEG.data = double(EEG.data);
EEG.icaact = double(EEG.icaact);
else
try,
if isa(EEG.data, 'double') & option_single
EEG.data = single(EEG.data);
EEG.icaact = single(EEG.icaact);
end;
catch,
disp('WARNING: EEGLAB ran out of memory while converting dataset to single precision.');
disp(' Save dataset (preferably saving data to a separate file; see File > Memory options).');
disp(' Then reload it.');
end;
end;
end;
% verify the type of the variables
% --------------------------------
% data dimensions -------------------------
if isnumeric(EEG.data) && ~isempty(EEG.data)
if ~isequal(size(EEG.data,1), EEG.nbchan)
disp( [ 'eeg_checkset warning: number of columns in data (' int2str(size(EEG.data,1)) ...
') does not match the number of channels (' int2str(EEG.nbchan) '): corrected' ]);
res = com;
EEG.nbchan = size(EEG.data,1);
end;
if (ndims(EEG.data)) < 3 & (EEG.pnts > 1)
if mod(size(EEG.data,2), EEG.pnts) ~= 0
if popask( [ 'eeg_checkset error: the number of frames does not divide the number of columns in the data.' 10 ...
'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the command line)'])
error('eeg_checkset error: user abort');
%res = com;
%EEG.pnts = size(EEG.data,2);
%EEG = eeg_checkset(EEG);
%return;
else
res = com;
return;
%error( 'eeg_checkset error: number of points does not divide the number of columns in data');
end;
else
if EEG.trials > 1
disp( 'eeg_checkset note: data array made 3-D');
res = com;
end;
if size(EEG.data,2) ~= EEG.pnts
EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts, size(EEG.data,2)/EEG.pnts);
end;
end;
end;
% size of data -----------
if size(EEG.data,3) ~= EEG.trials
disp( ['eeg_checkset warning: 3rd dimension size of data (' int2str(size(EEG.data,3)) ...
') does not match the number of epochs (' int2str(EEG.trials) '), corrected' ]);
res = com;
EEG.trials = size(EEG.data,3);
end;
if size(EEG.data,2) ~= EEG.pnts
disp( [ 'eeg_checkset warning: number of columns in data (' int2str(size(EEG.data,2)) ...
') does not match the number of points (' int2str(EEG.pnts) '): corrected' ]);
res = com;
EEG.pnts = size(EEG.data,2);
end;
end;
% parameters consistency
% -------------------------
if round(EEG.srate*(EEG.xmax-EEG.xmin)+1) ~= EEG.pnts
fprintf( 'eeg_checkset note: upper time limit (xmax) adjusted so (xmax-xmin)*srate+1 = number of frames\n');
if EEG.srate == 0
EEG.srate = 1;
end;
EEG.xmax = (EEG.pnts-1)/EEG.srate+EEG.xmin;
res = com;
end;
% deal with event arrays
% ----------------------
if ~isfield(EEG, 'event'), EEG.event = []; res = com; end;
if ~isempty(EEG.event)
if EEG.trials > 1 & ~isfield(EEG.event, 'epoch')
if popask( [ 'eeg_checkset error: the event info structure does not contain an ''epoch'' field.' ...
'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the commandline)'])
error('eeg_checkset error(): user abort');
%res = com;
%EEG.event = [];
%EEG = eeg_checkset(EEG);
%return;
else
res = com;
return;
%error('eeg_checkset error: no epoch field in event structure');
end;
end;
else
EEG.event = [];
end;
if isempty(EEG.event)
EEG.eventdescription = {};
end;
if ~isfield(EEG, 'eventdescription') | ~iscell(EEG.eventdescription)
EEG.eventdescription = cell(1, length(fieldnames(EEG.event)));
res = com;
else
if ~isempty(EEG.event)
if length(EEG.eventdescription) > length( fieldnames(EEG.event))
EEG.eventdescription = EEG.eventdescription(1:length( fieldnames(EEG.event)));
elseif length(EEG.eventdescription) < length( fieldnames(EEG.event))
EEG.eventdescription(end+1:length( fieldnames(EEG.event))) = {''};
end;
end;
end;
% create urevent if continuous data
% ---------------------------------
%if ~isempty(EEG.event) & ~isfield(EEG, 'urevent')
% EEG.urevent = EEG.event;
% disp('eeg_checkset note: creating the original event table (EEG.urevent)');
% for index = 1:length(EEG.event)
% EEG.event(index).urevent = index;
% end;
%end;
if isfield(EEG, 'urevent') & isfield(EEG.urevent, 'urevent')
EEG.urevent = rmfield(EEG.urevent, 'urevent');
end;
% deal with epoch arrays
% ----------------------
if ~isfield(EEG, 'epoch'), EEG.epoch = []; res = com; end;
% check if only one epoch
% -----------------------
if EEG.trials == 1
if isfield(EEG.event, 'epoch')
EEG.event = rmfield(EEG.event, 'epoch'); res = com;
end;
if ~isempty(EEG.epoch)
EEG.epoch = []; res = com;
end;
end;
if ~isfield(EEG, 'epochdescription'), EEG.epochdescription = {}; res = com; end;
if ~isempty(EEG.epoch)
if isstruct(EEG.epoch), l = length( EEG.epoch);
else l = size( EEG.epoch, 2);
end;
if l ~= EEG.trials
if popask( [ 'eeg_checkset error: the number of epoch indices in the epoch array/struct (' ...
int2str(l) ') is different from the number of epochs in the data (' int2str(EEG.trials) ').' 10 ...
'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the commandline)'])
error('eeg_checkset error: user abort');
%res = com;
%EEG.epoch = [];
%EEG = eeg_checkset(EEG);
%return;
else
res = com;
return;
%error('eeg_checkset error: epoch structure size invalid');
end;
end;
else
EEG.epoch = [];
end;
% check ica
% ---------
if ~isfield(EEG, 'icachansind')
if isempty(EEG.icaweights)
EEG.icachansind = []; res = com;
else
EEG.icachansind = [1:EEG.nbchan]; res = com;
end;
elseif isempty(EEG.icachansind)
if isempty(EEG.icaweights)
EEG.icachansind = []; res = com;
else
EEG.icachansind = [1:EEG.nbchan]; res = com;
end;
end;
if ~isempty(EEG.icasphere)
if ~isempty(EEG.icaweights)
if size(EEG.icaweights,2) ~= size(EEG.icasphere,1)
if popask( [ 'eeg_checkset error: number of columns in weights array (' int2str(size(EEG.icaweights,2)) ')' 10 ...
'does not match the number of rows in the sphere array (' int2str(size(EEG.icasphere,1)) ')' 10 ...
'Should EEGLAB remove ICA information ?' 10 '(press Cancel to fix the problem from the commandline)'])
res = com;
EEG.icasphere = [];
EEG.icaweights = [];
EEG = eeg_checkset(EEG);
return;
else
error('eeg_checkset error: user abort');
res = com;
return;
%error('eeg_checkset error: invalid weight and sphere array sizes');
end;
end;
if isnumeric(EEG.data)
if length(EEG.icachansind) ~= size(EEG.icasphere,2)
if popask( [ 'eeg_checkset error: number of elements in ''icachansind'' (' int2str(length(EEG.icachansind)) ')' 10 ...
'does not match the number of columns in the sphere array (' int2str(size(EEG.icasphere,2)) ')' 10 ...
'Should EEGLAB remove ICA information ?' 10 '(press Cancel to fix the problem from the commandline)'])
res = com;
EEG.icasphere = [];
EEG.icaweights = [];
EEG = eeg_checkset(EEG);
return;
else
error('eeg_checkset error: user abort');
res = com;
return;
%error('eeg_checkset error: invalid weight and sphere array sizes');
end;
end;
if isempty(EEG.icaact) | (size(EEG.icaact,1) ~= size(EEG.icaweights,1)) | (size(EEG.icaact,2) ~= size(EEG.data,2))
EEG.icaweights = double(EEG.icaweights);
EEG.icawinv = double(EEG.icawinv);
% scale ICA components to RMS microvolt
if option_scaleicarms
if ~isempty(EEG.icawinv)
if mean(mean(abs(pinv(EEG.icaweights * EEG.icasphere)-EEG.icawinv))) < 0.0001
disp('Scaling components to RMS microvolt');
scaling = repmat(sqrt(mean(EEG(1).icawinv(:,:).^2))', [1 size(EEG.icaweights,2)]);
EEG.etc.icaweights_beforerms = EEG.icaweights;
EEG.etc.icasphere_beforerms = EEG.icasphere;
EEG.icaweights = EEG.icaweights .* scaling;
EEG.icawinv = pinv(EEG.icaweights * EEG.icasphere);
end;
end;
end;
if ~isempty(EEG.data) && option_computeica
fprintf('eeg_checkset: recomputing the ICA activation matrix ...\n');
res = com;
% Make compatible with Matlab 7
if any(isnan(EEG.data(:)))
tmpdata = EEG.data(EEG.icachansind,:);
fprintf('eeg_checkset: recomputing ICA ignoring NaN indices ...\n');
tmpindices = find(~sum(isnan(tmpdata))); % was: tmpindices = find(~isnan(EEG.data(1,:)));
EEG.icaact = zeros(size(EEG.icaweights,1), size(tmpdata,2)); EEG.icaact(:) = NaN;
EEG.icaact(:,tmpindices) = (EEG.icaweights*EEG.icasphere)*tmpdata(:,tmpindices);
else
EEG.icaact = (EEG.icaweights*EEG.icasphere)*EEG.data(EEG.icachansind,:); % automatically does single or double
end;
EEG.icaact = reshape( EEG.icaact, size(EEG.icaact,1), EEG.pnts, EEG.trials);
end;
end;
end;
if isempty(EEG.icawinv)
EEG.icawinv = pinv(EEG.icaweights*EEG.icasphere); % a priori same result as inv
res = com;
end;
else
disp( [ 'eeg_checkset warning: weights matrix cannot be empty if sphere matrix is not, correcting ...' ]);
res = com;
EEG.icasphere = [];
end;
if option_computeica
if ~isempty(EEG.icaact) & ndims(EEG.icaact) < 3 & (EEG.trials > 1)
disp( [ 'eeg_checkset note: independent component made 3-D' ]);
res = com;
EEG.icaact = reshape(EEG.icaact, size(EEG.icaact,1), EEG.pnts, EEG.trials);
end;
else
if ~isempty(EEG.icaact)
fprintf('eeg_checkset: removing ICA activation matrix (as per edit options) ...\n');
end;
EEG.icaact = [];
end;
else
if ~isempty( EEG.icaweights ), EEG.icaweights = []; res = com; end;
if ~isempty( EEG.icawinv ), EEG.icawinv = []; res = com; end;
if ~isempty( EEG.icaact ), EEG.icaact = []; res = com; end;
end;
if isempty(EEG.icaact)
EEG.icaact = [];
end;
% -------------
% check chanlocs
% -------------
if ~isfield(EEG, 'chaninfo')
EEG.chaninfo = [];
end;
if ~isempty( EEG.chanlocs )
% reference (use EEG structure)
% ---------
if ~isfield(EEG, 'ref'), EEG.ref = ''; end;
if strcmpi(EEG.ref, 'averef')
ref = 'average';
else ref = '';
end;
if ~isfield( EEG.chanlocs, 'ref')
EEG.chanlocs(1).ref = ref;
end;
charrefs = cellfun('isclass',{EEG.chanlocs.ref},'char');
if any(charrefs) ref = ''; end
for tmpind = find(~charrefs)
EEG.chanlocs(tmpind).ref = ref;
end
if ~isstruct( EEG.chanlocs)
if exist( EEG.chanlocs ) ~= 2
disp( [ 'eeg_checkset warning: channel file does not exist or is not in Matlab path: filename removed from EEG struct' ]);
EEG.chanlocs = [];
res = com;
else
res = com;
try, EEG.chanlocs = readlocs( EEG.chanlocs );
disp( [ 'eeg_checkset: channel file read' ]);
catch, EEG.chanlocs = []; end;
end;
else
if ~isfield(EEG.chanlocs,'labels')
disp('eeg_checkset warning: no field label in channel location structure, removing it');
EEG.chanlocs = [];
res = com;
end;
end;
if isstruct( EEG.chanlocs)
if length( EEG.chanlocs) ~= EEG.nbchan && length( EEG.chanlocs) ~= EEG.nbchan+1 && ~isempty(EEG.data)
disp( [ 'eeg_checkset warning: number of channels different in data and channel file/struct: channel file/struct removed' ]);
EEG.chanlocs = [];
res = com;
end;
end;
% force Nosedir to +X (done here because of DIPFIT)
% -------------------
if isfield(EEG.chaninfo, 'nosedir')
if strcmpi(EEG.chaninfo.nosedir, '+x')
rotate = 0;
elseif all(isfield(EEG.chanlocs,{'X','Y','theta','sph_theta'}))
disp('EEG checkset note for expert users: Noze direction now set to default +X in EEG.chanlocs and EEG.dipfit.');
if strcmpi(EEG.chaninfo.nosedir, '+y')
rotate = 270;
elseif strcmpi(EEG.chaninfo.nosedir, '-x')
rotate = 180;
else rotate = 90;
end;
for index = 1:length(EEG.chanlocs)
if ~isempty(EEG.chanlocs(index).theta)
rotategrad = rotate/180*pi;
coord = (EEG.chanlocs(index).Y + EEG.chanlocs(index).X*sqrt(-1))*exp(sqrt(-1)*-rotategrad);
EEG.chanlocs(index).Y = real(coord);
EEG.chanlocs(index).X = imag(coord);
EEG.chanlocs(index).theta = EEG.chanlocs(index).theta -rotate;
EEG.chanlocs(index).sph_theta = EEG.chanlocs(index).sph_theta+rotate;
if EEG.chanlocs(index).theta <-180, EEG.chanlocs(index).theta =EEG.chanlocs(index).theta +360; end;
if EEG.chanlocs(index).sph_theta>180 , EEG.chanlocs(index).sph_theta=EEG.chanlocs(index).sph_theta-360; end;
end;
end;
if isfield(EEG, 'dipfit')
if isfield(EEG.dipfit, 'coord_transform')
if isempty(EEG.dipfit.coord_transform)
EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1];
end;
EEG.dipfit.coord_transform(6) = EEG.dipfit.coord_transform(6)+rotategrad;
end;
end;
end;
EEG.chaninfo.nosedir = '+X';
end;
% general checking of channels
% ----------------------------
EEG = eeg_checkchanlocs(EEG);
if EEG.nbchan ~= length(EEG.chanlocs)
EEG.chanlocs = [];
EEG.chaninfo = [];
disp('Warning: the size of the channel location structure does not match with');
disp(' number of channels. Channel information have been removed.');
end;
end;
EEG.chaninfo.icachansind = EEG.icachansind; % just a copy for programming convinience
%if ~isfield(EEG, 'urchanlocs')
% EEG.urchanlocs = EEG.chanlocs;
% for index = 1:length(EEG.chanlocs)
% EEG.chanlocs(index).urchan = index;
% end;
% disp('eeg_checkset note: creating backup chanlocs structure (urchanlocs)');
%end;
% check reference
% ---------------
if ~isfield(EEG, 'ref')
EEG.ref = 'common';
end;
if ischar(EEG.ref) & strcmpi(EEG.ref, 'common')
if length(EEG.chanlocs) > EEG.nbchan
disp('Extra common reference electrode location detected');
EEG.ref = EEG.nbchan+1;
end;
end;
% DIPFIT structure
% ----------------
if ~isfield(EEG,'dipfit') || isempty(EEG.dipfit)
EEG.dipfit = []; res = com;
else
try
% check if dipfitdefs is present
dipfitdefs;
if isfield(EEG.dipfit, 'vol') & ~isfield(EEG.dipfit, 'hdmfile')
if exist('pop_dipfit_settings')
disp('Old DIPFIT structure detected: converting to DIPFIT 2 format');
EEG.dipfit.hdmfile = template_models(1).hdmfile;
EEG.dipfit.coordformat = template_models(1).coordformat;
EEG.dipfit.mrifile = template_models(1).mrifile;
EEG.dipfit.chanfile = template_models(1).chanfile;
EEG.dipfit.coord_transform = [];
EEG.saved = 'no';
res = com;
end;
end;
if isfield(EEG.dipfit, 'hdmfile')
if length(EEG.dipfit.hdmfile) > 8
if strcmpi(EEG.dipfit.hdmfile(end-8), template_models(1).hdmfile(end-8)), EEG.dipfit.hdmfile = template_models(1).hdmfile; end;
if strcmpi(EEG.dipfit.hdmfile(end-8), template_models(2).hdmfile(end-8)), EEG.dipfit.hdmfile = template_models(2).hdmfile; end;
end;
if length(EEG.dipfit.mrifile) > 8
if strcmpi(EEG.dipfit.mrifile(end-8), template_models(1).mrifile(end-8)), EEG.dipfit.mrifile = template_models(1).mrifile; end;
if strcmpi(EEG.dipfit.mrifile(end-8), template_models(2).mrifile(end-8)), EEG.dipfit.mrifile = template_models(2).mrifile; end;
end;
if length(EEG.dipfit.chanfile) > 8
if strcmpi(EEG.dipfit.chanfile(end-8), template_models(1).chanfile(end-8)), EEG.dipfit.chanfile = template_models(1).chanfile; end;
if strcmpi(EEG.dipfit.chanfile(end-8), template_models(2).chanfile(end-8)), EEG.dipfit.chanfile = template_models(2).chanfile; end;
end;
end;
if isfield(EEG.dipfit, 'coord_transform')
if isempty(EEG.dipfit.coord_transform)
EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1];
end;
elseif ~isempty(EEG.dipfit)
EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1];
end;
catch
e = lasterror;
if ~strcmp(e.identifier,'MATLAB:UndefinedFunction')
% if we got some error aside from dipfitdefs not being present, rethrow it
rethrow(e);
end
end
end;
% check events (fast)
% ------------
if isfield(EEG.event, 'type')
tmpevent = EEG.event(1:min(length(EEG.event), 100));
if ~all(cellfun(@ischar, { tmpevent.type })) && ~all(cellfun(@isnumeric, { tmpevent.type }))
disp('Warning: converting all event types to strings');
for ind = 1:length(EEG.event)
EEG.event(ind).type = num2str(EEG.event(ind).type);
end;
EEG = eeg_checkset(EEG, 'eventconsistency');
end;
end;
% EEG.times (only for epoched datasets)
% ---------
if ~isfield(EEG, 'times') || isempty(EEG.times) || length(EEG.times) ~= EEG.pnts
EEG.times = linspace(EEG.xmin*1000, EEG.xmax*1000, EEG.pnts);
end;
if ~isfield(EEG, 'history') EEG.history = ''; res = com; end;
if ~isfield(EEG, 'splinefile') EEG.splinefile = ''; res = com; end;
if ~isfield(EEG, 'icasplinefile') EEG.icasplinefile = ''; res = com; end;
if ~isfield(EEG, 'saved') EEG.saved = 'no'; res = com; end;
if ~isfield(EEG, 'subject') EEG.subject = ''; res = com; end;
if ~isfield(EEG, 'condition') EEG.condition = ''; res = com; end;
if ~isfield(EEG, 'group') EEG.group = ''; res = com; end;
if ~isfield(EEG, 'session') EEG.session = []; res = com; end;
if ~isfield(EEG, 'urchanlocs') EEG.urchanlocs = []; res = com; end;
if ~isfield(EEG, 'specdata') EEG.specdata = []; res = com; end;
if ~isfield(EEG, 'specicaact') EEG.specicaact = []; res = com; end;
if ~isfield(EEG, 'comments') EEG.comments = ''; res = com; end;
if ~isfield(EEG, 'etc' ) EEG.etc = []; res = com; end;
if ~isfield(EEG, 'urevent' ) EEG.urevent = []; res = com; end;
if ~isfield(EEG, 'ref') | isempty(EEG.ref) EEG.ref = 'common'; res = com; end;
% create fields if absent
% -----------------------
if ~isfield(EEG, 'reject') EEG.reject.rejjp = []; res = com; end;
listf = { 'rejjp' 'rejkurt' 'rejmanual' 'rejthresh' 'rejconst', 'rejfreq' ...
'icarejjp' 'icarejkurt' 'icarejmanual' 'icarejthresh' 'icarejconst', 'icarejfreq'};
for index = 1:length(listf)
name = listf{index};
elecfield = [name 'E'];
if ~isfield(EEG.reject, elecfield), EEG.reject.(elecfield) = []; res = com; end;
if ~isfield(EEG.reject, name)
EEG.reject.(name) = [];
res = com;
elseif ~isempty(EEG.reject.(name)) && isempty(EEG.reject.(elecfield))
% check if electrode array is empty with rejection array is not
nbchan = fastif(strcmp(name, 'ica'), size(EEG.icaweights,1), EEG.nbchan);
EEG.reject = setfield(EEG.reject, elecfield, zeros(nbchan, length(getfield(EEG.reject, name)))); res = com;
end;
end;
if ~isfield(EEG.reject, 'rejglobal') EEG.reject.rejglobal = []; res = com; end;
if ~isfield(EEG.reject, 'rejglobalE') EEG.reject.rejglobalE = []; res = com; end;
% track version of EEGLAB
% -----------------------
tmpvers = eeg_getversion;
if ~isfield(EEG.etc, 'eeglabvers') || ~isequal(EEG.etc.eeglabvers, tmpvers)
EEG.etc.eeglabvers = tmpvers;
EEG = eeg_hist( EEG, ['EEG.etc.eeglabvers = ''' tmpvers '''; % this tracks which version of EEGLAB is being used, you may ignore it'] );
res = com;
end;
% default colors for rejection
% ----------------------------
if ~isfield(EEG.reject, 'rejmanualcol') EEG.reject.rejmanualcol = [1.0000 1 0.783]; res = com; end;
if ~isfield(EEG.reject, 'rejthreshcol') EEG.reject.rejthreshcol = [0.8487 1.0000 0.5008]; res = com; end;
if ~isfield(EEG.reject, 'rejconstcol') EEG.reject.rejconstcol = [0.6940 1.0000 0.7008]; res = com; end;
if ~isfield(EEG.reject, 'rejjpcol') EEG.reject.rejjpcol = [1.0000 0.6991 0.7537]; res = com; end;
if ~isfield(EEG.reject, 'rejkurtcol') EEG.reject.rejkurtcol = [0.6880 0.7042 1.0000]; res = com; end;
if ~isfield(EEG.reject, 'rejfreqcol') EEG.reject.rejfreqcol = [0.9596 0.7193 1.0000]; res = com; end;
if ~isfield(EEG.reject, 'disprej') EEG.reject.disprej = { }; end;
if ~isfield(EEG, 'stats') EEG.stats.jp = []; res = com; end;
if ~isfield(EEG.stats, 'jp') EEG.stats.jp = []; res = com; end;
if ~isfield(EEG.stats, 'jpE') EEG.stats.jpE = []; res = com; end;
if ~isfield(EEG.stats, 'icajp') EEG.stats.icajp = []; res = com; end;
if ~isfield(EEG.stats, 'icajpE') EEG.stats.icajpE = []; res = com; end;
if ~isfield(EEG.stats, 'kurt') EEG.stats.kurt = []; res = com; end;
if ~isfield(EEG.stats, 'kurtE') EEG.stats.kurtE = []; res = com; end;
if ~isfield(EEG.stats, 'icakurt') EEG.stats.icakurt = []; res = com; end;
if ~isfield(EEG.stats, 'icakurtE') EEG.stats.icakurtE = []; res = com; end;
% component rejection
% -------------------
if ~isfield(EEG.stats, 'compenta') EEG.stats.compenta = []; res = com; end;
if ~isfield(EEG.stats, 'compentr') EEG.stats.compentr = []; res = com; end;
if ~isfield(EEG.stats, 'compkurta') EEG.stats.compkurta = []; res = com; end;
if ~isfield(EEG.stats, 'compkurtr') EEG.stats.compkurtr = []; res = com; end;
if ~isfield(EEG.stats, 'compkurtdist') EEG.stats.compkurtdist = []; res = com; end;
if ~isfield(EEG.reject, 'threshold') EEG.reject.threshold = [0.8 0.8 0.8]; res = com; end;
if ~isfield(EEG.reject, 'threshentropy') EEG.reject.threshentropy = 600; res = com; end;
if ~isfield(EEG.reject, 'threshkurtact') EEG.reject.threshkurtact = 600; res = com; end;
if ~isfield(EEG.reject, 'threshkurtdist') EEG.reject.threshkurtdist = 600; res = com; end;
if ~isfield(EEG.reject, 'gcompreject') EEG.reject.gcompreject = []; res = com; end;
if length(EEG.reject.gcompreject) ~= size(EEG.icaweights,1)
EEG.reject.gcompreject = zeros(1, size(EEG.icaweights,1));
end;
% remove old fields
% -----------------
if isfield(EEG, 'averef'), EEG = rmfield(EEG, 'averef'); end;
if isfield(EEG, 'rt' ), EEG = rmfield(EEG, 'rt'); end;
% store in new structure
% ----------------------
if isstruct(EEG)
if ~exist('ALLEEGNEW','var')
ALLEEGNEW = EEG;
else
ALLEEGNEW(inddataset) = EEG;
end;
end;
end;
% recorder fields
% ---------------
fieldorder = { 'setname' ...
'filename' ...
'filepath' ...
'subject' ...
'group' ...
'condition' ...
'session' ...
'comments' ...
'nbchan' ...
'trials' ...
'pnts' ...
'srate' ...
'xmin' ...
'xmax' ...
'times' ...
'data' ...
'icaact' ...
'icawinv' ...
'icasphere' ...
'icaweights' ...
'icachansind' ...
'chanlocs' ...
'urchanlocs' ...
'chaninfo' ...
'ref' ...
'event' ...
'urevent' ...
'eventdescription' ...
'epoch' ...
'epochdescription' ...
'reject' ...
'stats' ...
'specdata' ...
'specicaact' ...
'splinefile' ...
'icasplinefile' ...
'dipfit' ...
'history' ...
'saved' ...
'etc' };
for fcell = fieldnames(EEG)'
fname = fcell{1};
if ~any(strcmp(fieldorder,fname))
fieldorder{end+1} = fname;
end
end
try
ALLEEGNEW = orderfields(ALLEEGNEW, fieldorder);
EEG = ALLEEGNEW;
catch
disp('Couldn''t order data set fields properly.');
end;
if exist('ALLEEGNEW','var')
EEG = ALLEEGNEW;
end;
if ~isa(EEG, 'eegobj') && option_eegobject
EEG = eegobj(EEG);
end;
return;
function num = popask( text )
ButtonName=questdlg2( text, ...
'Confirmation', 'Cancel', 'Yes','Yes');
switch lower(ButtonName),
case 'cancel', num = 0;
case 'yes', num = 1;
end;
function res = mycellfun(com, vals, classtype);
res = zeros(1, length(vals));
switch com
case 'isempty',
for index = 1:length(vals), res(index) = isempty(vals{index}); end;
case 'isclass'
if strcmp(classtype, 'double')
for index = 1:length(vals), res(index) = isnumeric(vals{index}); end;
else
error('unknown cellfun command');
end;
otherwise error('unknown cellfun command');
end;
|
github
|
lcnbeapp/beapp-master
|
ismember_bc.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/ismember_bc.m
| 711 |
utf_8
|
565a06126820e316b2bf233d652bf24c
|
% ismember_bc - ismember backward compatible with Matlab versions prior to 2013a
function [C,IA] = ismember_bc(A,B,varargin);
errorFlag = error_bc;
v = version;
indp = find(v == '.');
v = str2num(v(1:indp(2)-1));
if v > 7.19, v = floor(v) + rem(v,1)/10; end;
if nargin > 2
ind = strmatch('legacy', varargin);
if ~isempty(ind)
varargin(ind) = [];
end;
end;
if v >= 7.14
[C,IA] = ismember(A,B,varargin{:},'legacy');
if errorFlag
[C2,IA2] = ismember(A,B,varargin{:});
if (~isequal(C, C2) || ~isequal(IA, IA2))
warning('backward compatibility issue with call to ismember function');
end;
end;
else
[C,IA] = ismember(A,B,varargin{:});
end;
|
github
|
lcnbeapp/beapp-master
|
intersect_bc.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/intersect_bc.m
| 752 |
utf_8
|
72bc774f899f5fb5e3b75d2c1ef99049
|
% intersect_bc - intersect backward compatible with Matlab versions prior to 2013a
function [C,IA,IB] = intersect_bc(A,B,varargin);
errorFlag = error_bc;
v = version;
indp = find(v == '.');
v = str2num(v(1:indp(2)-1));
if v > 7.19, v = floor(v) + rem(v,1)/10; end;
if nargin > 2
ind = strmatch('legacy', varargin);
if ~isempty(ind)
varargin(ind) = [];
end;
end;
if v >= 7.14
[C,IA,IB] = intersect(A,B,varargin{:},'legacy');
if errorFlag
[C2,IA2,IB2] = intersect(A,B,varargin{:});
if (~isequal(C, C2) || ~isequal(IA, IA2) || ~isequal(IB, IB2))
warning('backward compatibility issue with call to intersect function');
end;
end;
else
[C,IA,IB] = intersect(A,B,varargin{:});
end;
|
github
|
lcnbeapp/beapp-master
|
plugin_getweb.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/plugin_getweb.m
| 6,337 |
utf_8
|
d6ad7bd9e33713cfe1317b4e55cd3c3f
|
function plugin = plugin_getweb(type, pluginOri, mode)
if nargin < 1, help plugin_getweb; return; end;
if nargin < 2, pluginOri = []; end;
if nargin < 3, mode = 'merge'; end; % 'merge' or 'newlist'
% convert plugin list format if necessary
if isfield(pluginOri, 'plugin'), pluginOri = plugin_convert(pluginOri); end;
try
disp( [ 'Retreiving URL with ' type ' extensions...' ] );
if strcmpi(type, 'import')
[tmp status] = plugin_urlread('http://sccn.ucsd.edu/wiki/Plugin_list_import');
else
[tmp status] = plugin_urlread('http://sccn.ucsd.edu/wiki/Plugin_list_process');
end;
catch,
error('Cannot connect to the Internet to retrieve extension list');
end;
% retreiving download statistics
try
disp( [ 'Retreiving download statistics...' ] );
[stats status] = plugin_urlread('http://sccn.ucsd.edu/eeglab/plugin_uploader/plugin_getcountall.php');
stats = textscan(stats, '%s%d%s%s');
catch,
stats = {};
disp('Cannot connect to the Internet to retrieve statistics for extensions');
end;
if status == 0
error('Cannot connect to the Internet to retrieve extension list');
end;
% parse the web page
% ------------------
try
plugin = parseTable(tmp);
catch
error('Cannot parse extension list - please contact [email protected]');
end;
% find correspondance with plugin list
% ------------------------------------
if ~isempty(pluginOri)
currentNames = lower({ pluginOri.name });
else currentNames = {};
end;
allMatch = [];
for iRow = 1:length(plugin)
% fix links
if isfield(plugin, 'zip'), plugin(iRow).zip = strrep(plugin(iRow).zip, '&', '&'); end;
% get number of downloads
if ~isempty(stats)
indMatch = strmatch(plugin(iRow).name, stats{1}, 'exact');
if ~isempty(indMatch)
plugin(iRow).downloads = stats{2}(indMatch(1));
if length(stats) > 2 && ~isempty(stats{3}{indMatch(1)})
plugin(iRow).version = stats{3}{indMatch(1)};
plugin(iRow).zip = stats{4}{indMatch(1)};
end;
else plugin(iRow).downloads = 0;
end;
else plugin(iRow).downloads = 0;
end;
% match with existiting plugins
indMatch = strmatch(lower(plugin(iRow).name), currentNames, 'exact');
if isempty(indMatch)
plugin(iRow).currentversion = '-';
plugin(iRow).installed = 0;
plugin(iRow).installorupdate = 1;
plugin(iRow).status = 'notinstalled';
else
if length(indMatch) > 1
disp([ 'Warning: duplicate extension ' plugin(iRow).name ' instaled' ]);
end;
plugin(iRow).currentversion = pluginOri(indMatch).currentversion;
plugin(iRow).foldername = pluginOri(indMatch).foldername;
plugin(iRow).status = pluginOri(indMatch).status;
plugin(iRow).installed = 1;
if strcmpi(plugin(iRow).currentversion, plugin(iRow).version)
plugin(iRow).installorupdate = 0;
else
plugin(iRow).installorupdate = 1;
end;
allMatch = [ allMatch indMatch(:)' ];
end;
end;
% put all the installed plugins first
% -----------------------------------
if ~isempty(plugin)
[tmp reorder] = sort([plugin.installed], 'descend');
plugin = plugin(reorder);
% plugin(1).currentversion = '0.9';
% plugin(1).version = '1';
% plugin(1).foldername = 'test';
% plugin(1).installed = 1;
% plugin(1).installorupdate = 1;
% plugin(1).description = 'test';
% plugin(1).webdoc = 'test';
% plugin(1).name = 'test';
end;
if strcmpi(mode, 'merge') && ~isempty(pluginOri)
indices = setdiff([1:length(pluginOri)], allMatch);
fields = fieldnames(pluginOri);
lenPlugin = length(plugin);
for indPlugin = 1:length(indices)
for indField = 1:length(fields)
value = getfield(pluginOri, { indices(indPlugin) }, fields{ indField });
plugin = setfield(plugin , { lenPlugin+indPlugin }, fields{ indField }, value);
end;
end;
end;
% parse the web table
% ===================
function plugin = parseTable(tmp);
plugin = [];
if isempty(tmp), return; end;
% get table content
% -----------------
tableBeg = findstr('Plug-in name', tmp);
tableEnd = findstr('</table>', tmp(tableBeg:end));
tableContent = tmp(tableBeg:tableBeg+tableEnd-2);
endFirstLine = findstr('</tr>', tableContent);
tableContent = tableContent(endFirstLine(1)+5:end);
% parse table entries
% -------------------
posBegRow = findstr('<tr>' , tableContent);
posEndRow = findstr('</tr>', tableContent);
if length(posBegRow) ~= length(posEndRow) || isempty(posBegRow)
error('Cannot connect to the Internet to retrieve plugin list');
end;
for iRow = 1:length(posBegRow)
rowContent = tableContent(posBegRow(iRow)+4:posEndRow(iRow)-1);
posBegCol = findstr('<td>' , rowContent);
posEndCol = findstr('</td>', rowContent);
for iCol = 1:length(posBegCol)
table{iRow,iCol} = rowContent(posBegCol(iCol)+4:posEndCol(iCol)-1);
end;
end;
%% extract zip link and plugin name from first column
% --------------------------------------------------
%href="http://www.unicog.org/pm/uploads/MEG/ADJUST_PLUGIN.zip" class="external text" title="http://www.unicog.org/pm/uploads/MEG/ADJUST_PLUGIN.zip" rel="nofollow">ADJUST PLUGIN</a></td
for iRow = 1:size(table,1)
% get link
[plugin(iRow).name plugin(iRow).webdoc] = parsehttplink(table{iRow,1});
plugin(iRow).version = table{iRow,2};
tmp = deblank(table{iRow,3}(end:-1:1));
plugin(iRow).description = deblank(tmp(end:-1:1));
[tmp plugin(iRow).zip] = parsehttplink(table{iRow,4});
end;
function [txt link] = parsehttplink(currentRow)
openTag = find(currentRow == '<');
closeTag = find(currentRow == '>');
if isempty(openTag)
link = '';
txt = currentRow;
else
% parse link
link = currentRow(openTag(1)+1:closeTag(1)-1);
hrefpos = findstr('href', link);
link = link(hrefpos:end);
quoteInd = find(link == '"');
link = link(quoteInd(1)+1:quoteInd(2)-1);
for iTag = length(openTag):-1:1
currentRow(openTag(iTag):closeTag(iTag)) = [];
end;
txt = currentRow;
end;
|
github
|
lcnbeapp/beapp-master
|
eeg_checkchanlocs.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/eeg_checkchanlocs.m
| 8,655 |
utf_8
|
2664c683e10493731ebda7dfec52968f
|
% eeg_checkchanlocs() - Check the consistency of the channel locations structure
% of an EEGLAB dataset.
%
% Usage:
% >> EEG = eeg_checkchanlocs( EEG, 'key1', value1, 'key2', value2, ... );
% >> [chanlocs chaninfo] = eeg_checkchanlocs( chanlocs, chaninfo, 'key1', value1, 'key2', value2, ... );
%
% Inputs:
% EEG - EEG dataset
% chanlocs - EEG.chanlocs structure
% chaninfo - EEG.chaninfo structure
%
% Outputs:
% EEG - new EEGLAB dataset with updated channel location structures
% EEG.chanlocs, EEG.urchanlocs, EEG.chaninfo
% chanlocs - updated channel location structure
% chaninfo - updated chaninfo structure
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, March 2, 2011
% Copyright (C) SCCN/INC/UCSD, March 2, 2011, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% Hey Arno -- this is a quick fix to make an analysis work for Makoto
% I think the old version had a bug...
function [chans, chaninfo, chanedit]= eeg_checkchanlocs(chans, chaninfo);
if nargin < 1
help eeg_checkchanlocs;
return;
end;
if nargin < 2
chaninfo = [];
end;
processingEEGstruct = 0;
if isfield(chans, 'data')
processingEEGstruct = 1;
tmpEEG = chans;
chans = tmpEEG.chanlocs;
chaninfo = tmpEEG.chaninfo;
end;
if ~isfield(chans, 'datachan')
[chanedit,dummy,complicated] = insertchans(chans, chaninfo);
else
chanedit = chans;
complicated = true;
end;
nosevals = { '+X' '-X' '+Y' '-Y' };
if ~isfield(chaninfo, 'plotrad'), chaninfo.plotrad = []; end;
if ~isfield(chaninfo, 'shrink'), chaninfo.shrink = []; end;
if ~isfield(chaninfo, 'nosedir'), chaninfo.nosedir = nosevals{1}; end;
% handles deprecated fields
% -------------------------
plotrad = [];
if isfield(chanedit, 'plotrad'),
plotrad = chanedit(1).plotrad;
chanedit = rmfield(chanedit, 'plotrad');
if isstr(plotrad) & ~isempty(str2num(plotrad)), plotrad = str2num(plotrad); end;
chaninfo.plotrad = plotrad;
end;
if isfield(chanedit, 'shrink') && ~isempty(chanedit(1).shrink)
shrinkorskirt = 1;
if ~isstr(chanedit(1).shrink)
plotrad = 0.5/(1-chanedit(1).shrink); % convert old values
end;
chanedit = rmfield(chanedit, 'shrink');
chaninfo.plotrad = plotrad;
end;
% set non-existent fields to []
% -----------------------------
fields = { 'labels' 'theta' 'radius' 'X' 'Y' 'Z' 'sph_theta' 'sph_phi' 'sph_radius' 'type' 'ref' 'urchan' };
fieldtype = { 'str' 'num' 'num' 'num' 'num' 'num' 'num' 'num' 'num' 'str' 'str' 'num' };
check_newfields = true; %length(fieldnames(chanedit)) < length(fields);
if ~isempty(chanedit)
for index = 1:length(fields)
if check_newfields && ~isfield(chanedit, fields{index})
% new field
% ---------
if strcmpi(fieldtype{index}, 'num')
chanedit = setfield(chanedit, {1}, fields{index}, []);
else
for indchan = 1:length(chanedit)
chanedit = setfield(chanedit, {indchan}, fields{index}, '');
end;
end;
else
% existing fields
% ---------------
allvals = {chanedit.(fields{index})};
if strcmpi(fieldtype{index}, 'num')
if ~all(cellfun('isclass',allvals,'double'))
numok = cellfun(@isnumeric, allvals);
if any(numok == 0)
for indConvert = find(numok == 0)
chanedit = setfield(chanedit, {indConvert}, fields{index}, []);
end;
end;
end
else
strok = cellfun('isclass', allvals,'char');
if strcmpi(fields{index}, 'labels'), prefix = 'E'; else prefix = ''; end;
if any(strok == 0)
for indConvert = find(strok == 0)
try
strval = [ prefix num2str(getfield(chanedit, {indConvert}, fields{index})) ];
chanedit = setfield(chanedit, {indConvert}, fields{index}, strval);
catch
chanedit = setfield(chanedit, {indConvert}, fields{index}, '');
end;
end;
end;
end;
end;
end;
end;
if ~isequal(fieldnames(chanedit)',fields)
try
chanedit = orderfields(chanedit, fields);
catch, end;
end
% check if duplicate channel label
% --------------------------------
if isfield(chanedit, 'labels')
tmp = sort({chanedit.labels});
if any(strcmp(tmp(1:end-1),tmp(2:end)))
disp('Warning: some channels have the same label');
end
end;
% check for empty channel label
% -----------------------------
if isfield(chanedit, 'labels')
indEmpty = find(cellfun(@isempty, {chanedit.labels}));
if ~isempty(indEmpty)
tmpWarning = warning('backtrace');
warning backtrace off;
warning('channel labels should not be empty, creating unique labels');
warning(tmpWarning);
for index = indEmpty
chanedit(index).labels = sprintf('E%d', index);
end;
end;
end;
% remove fields
% -------------
if isfield(chanedit, 'sph_phi_besa' ), chanedit = rmfield(chanedit, 'sph_phi_besa'); end;
if isfield(chanedit, 'sph_theta_besa'), chanedit = rmfield(chanedit, 'sph_theta_besa'); end;
% reconstruct the chans structure
% -------------------------------
if complicated
[chans chaninfo.nodatchans] = getnodatchan( chanedit );
if ~isfield(chaninfo, 'nodatchans'), chaninfo.nodatchans = []; end;
if isempty(chanedit)
for iField = 1:length(fields)
chanedit = setfield(chanedit, fields{iField}, []);
end;
end;
else
chans = rmfield(chanedit,'datachan');
chaninfo.nodatchans = [];
end
if processingEEGstruct
tmpEEG.chanlocs = chans;
tmpEEG.chaninfo = chaninfo;
chans = tmpEEG;
end;
% ---------------------------------------------
% separate data channels from non-data channels
% ---------------------------------------------
function [chans, fidsval] = getnodatchan(chans)
if isfield(chans,'datachan')
[chans(cellfun('isempty',{chans.datachan})).datachan] = deal(0);
fids = [chans.datachan] == 0;
fidsval = chans(fids);
chans = rmfield(chans(~fids),'datachan');
else
fids = [];
end;
% ----------------------------------------
% fuse data channels and non-data channels
% ----------------------------------------
function [chans, chaninfo,complicated] = insertchans(chans, chaninfo, nchans)
if nargin < 3, nchans = length(chans); end;
[chans.datachan] = deal(1);
complicated = false; % whether we need complicated treatment of datachans & co further down the road.....
if isfield(chans,'type')
mask = strcmpi({chans.type},'FID') | strcmpi({chans.type},'IGNORE');
if any(mask)
[chans(mask).datachan] = deal(0);
complicated = true;
end
end
if length(chans) > nchans & nchans ~= 0 % reference at the end of the structure
chans(end).datachan = 0;
complicated = true;
end;
if isfield(chaninfo, 'nodatchans')
if ~isempty(chaninfo.nodatchans) && isstruct(chaninfo.nodatchans)
chanlen = length(chans);
for index = 1:length(chaninfo.nodatchans)
fields = fieldnames( chaninfo.nodatchans );
ind = chanlen+index;
for f = 1:length( fields )
chans = setfield(chans, { ind }, fields{f}, getfield( chaninfo.nodatchans, { index }, fields{f}));
end;
chans(ind).datachan = 0;
complicated = true;
end;
chaninfo = rmfield(chaninfo, 'nodatchans');
% put these channels first
% ------------------------
% tmp = chans(chanlen+1:end);
% chans(length(tmp)+1:end) = chans(1:end-length(tmp));
% chans(1:length(tmp)) = tmp;
end;
end;
|
github
|
lcnbeapp/beapp-master
|
removepath.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/removepath.m
| 513 |
utf_8
|
34d13ec0480b1b9ac75172c48ddc833e
|
% remove all path with a given parent path
% varargin contains a list of path to exclude
function removepath(parentpath, varargin)
if isempty(parentpath), return; end;
folder = path;
if ispc, sep = ';'; else sep = ':'; end;
indSep = find(folder == sep);
indSep = [ 0 indSep length(folder)+1 ];
for iSep = 1:length(indSep)-1
curPath = folder(indSep(iSep)+1:indSep(iSep+1)-1);
if ~isempty(strfind(curPath, parentpath)) && ~any(strmatch(curPath, varargin, 'exact'))
rmpath(curPath);
end;
end;
|
github
|
lcnbeapp/beapp-master
|
pop_editoptions.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/pop_editoptions.m
| 12,372 |
utf_8
|
4b1d33adb233aa9407e0e2d68d052b5b
|
% pop_editoptions() - Edit memory-saving eeglab() options. These are stored in
% a file 'eeg_options.m'. With no argument, pop up a window
% to allow the user to set/unset these options. Store
% user choices in a new 'eeg_options.m' file in the
% working directory.
%
% Usage: >> pop_editoptions;
% >> pop_editoptions( 'key1', value1, 'key2', value2, ...);
%
% Graphic interface inputs:
% "If set, keep at most one dataset in memory ..." - [checkbox] If set, EEGLAB will only retain the current
% dataset in memory. All other datasets will be automatically
% read and writen to disk. All EEGLAB functionalities are preserved
% even for dataset stored on disk.
% "If set, write data in same file as dataset ..." - [checkbox] Set -> dataset data (EEG.data) are
% saved in the EEG structure in the standard Matlab dataset (.set) file.
% Unset -> The EEG.data are saved as a transposed stream of 32-bit
% floats in a separate binary file. As of Matlab 4.51, the order
% of the data in the binary file is as in the transpose of EEG.data
% (i.e., as in EEG.data', frames by channels). This allows quick
% reading of single channels from the data, e.g. when comparing
% channels across datasets. The stored files have the extension
% .dat instead of the pre-4.51, non-transposed .fdt. Both file types
% are read by the dataset load function. Command line equivalent is
% option_savematlab.
% "Precompute ICA activations" - [checkbox] If set, all the ICA activation
% time courses are precomputed (this requires more RAM).
% Command line equivalent: option_computeica.
% "If set, remember old folder when reading dataset" - [checkbox] this option
% is convinient if the file you are working on are not in the
% current folder.
%
% Commandline keywords:
% 'option_computeica' - [0|1] If 1, compute the ICA component activitations and
% store them in a new variable. If 0, compute ICA activations
% only when needed (& only partially, if possible) and do not
% store the results).
% NOTE: Turn OFF the options above when working with very large datasets or on
% computers with limited memory.
% 'option_savematlab' - [0|1] If 1, datasets are saved as single Matlab .set files.
% If 0, dataset data are saved in separate 32-bit binary float
% .dat files. See the corresponding GUI option above for details.
% Outputs:
% In the output workspace, variables 'option_computeica',
% and 'option_savematlab' are updated, and a new 'eeg_options.m' file may be
% written to the working directory. The copy of 'eeg_options.m' placed in your
% working directory overwrites system defaults whenever EEGLAB operates in this
% directory (assuming your working directory is in your MATLABPATH - see path()).
% To adjust these options system-wide, edit the master "eeg_options.m" file in the
% EEGLAB directory heirarchy.
%
% Author: Arnaud Delorme, SCCN / INC / UCSD, March 2002
%
% See also: eeg_options(), eeg_readoptions()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 09 March 2002, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function com = pop_editoptions(varargin);
com = '';
datasets_in_memory = 0;
if nargin > 0
if ~isstr(varargin{1})
datasets_in_memory = varargin{1};
varargin = {};
end;
end;
% parse the eeg_options file
% ----------------------------
eeglab_options;
if iseeglabdeployed
filename = fullfile(eeglabexefolder,'eeg_options.txt');
eegoptionbackup = fullfile(eeglabexefolder,'eeg_optionsbackup.txt');
else
% folder for eeg_options file (also update the eeglab_options)
if ~isempty(EEGOPTION_PATH)
homefolder = EEGOPTION_PATH;
elseif ispc
if ~exist('evalc'), eval('evalc = @(x)(eval(x));'); end;
homefolder = deblank(evalc('!echo %USERPROFILE%'));
else homefolder = '~';
end;
filename = fullfile(homefolder, 'eeg_options.m');
eegoptionbackup = which('eeg_optionsbackup.m');
end;
fid = fopen( filename, 'r+'); % existing file
storelocal = 0;
if fid == -1
filepath = homefolder;
filename = 'eeg_options.m';
fid = fopen( fullfile(filepath, filename), 'w'); % new file possible?
if fid == -1
error([ 'Cannot write into HOME folder: ' homefolder 10 'You may specify another folder for the eeg_option.m' 10 'file by editing the icadefs.m file' ]);
end;
fclose(fid);
delete(fullfile(filepath, filename));
% read variables values and description
% --------------------------------------
[ header opt ] = eeg_readoptions( eegoptionbackup );
else
[filepath filename ext] = fileparts(filename);
filename = [ filename ext ];
fprintf('Using option file in directory %s\n', filepath);
% read variables values and description
% --------------------------------------
[ header opt ] = eeg_readoptions( eegoptionbackup );
[ header opt ] = eeg_readoptions( fid, opt ); % use opt from above as default
end;
if nargin < 2
geometry = { [6 1] };
tmpfile = fullfile(filepath, filename);
cb_file = [ '[filename, filepath] = uiputfile(''eeg_options.txt'', ''Pick a folder to save option file'');' ...
'if filename(1) ~= 0,' ...
' filepath = fullfile(filepath, ''eeg_options.m'');' ...
' set(gcf, ''userdata'', filepath);' ...
' if length(filepath) > 100,' ...
' filepath = [ ''...'' filepath(end-100:end) ];' ...
' end;' ...
' set(findobj(gcf, ''tag'', ''filename''), ''string'', filepath);' ...
'end;' ...
'clear filepath;' ];
uilist = { ...
{ 'Style', 'text', 'string', '', 'fontweight', 'bold' }, ...
{ 'Style', 'text', 'string', 'Set/Unset', 'fontweight', 'bold' } };
% add all fields to graphic interface
% -----------------------------------
for index = 1:length(opt)
% format the description to fit a help box
% ----------------------------------------
descrip = { 'string', opt(index).description }; % strmultiline(description{ index }, 80, 10) };
% create the gui for this variable
% --------------------------------
geometry = { geometry{:} [4 0.3 0.1] };
if strcmpi(opt(index).varname, 'option_storedisk') & datasets_in_memory
cb_nomodif = [ 'set(gcbo, ''value'', ~get(gcbo, ''value''));' ...
'warndlg2(strvcat(''This option may only be modified when at most one dataset is stored in memory.''));' ];
elseif strcmpi(opt(index).varname, 'option_memmapdata')
cb_nomodif = [ 'if get(gcbo, ''value''), warndlg2(strvcat(''Matlab memory is beta, use at your own risk'')); end;' ];
elseif strcmpi(opt(index).varname, 'option_donotusetoolboxes')
cb_nomodif = [ 'if get(gcbo, ''value''), warndlg2([''You have selected the option to disable'' 10 ''Matlab toolboxes. Use with caution.'' 10 ''Matlab toolboxes will be removed from'' 10 ''your path. Unlicking this option later will not'' 10 ''add back the toolboxes. You will need'' 10 ''to add them back manually. If you are unsure'' 10 ''if you want to disable Matlab toolboxes'' 10 ''deselect the option now.'' ]); end;' ];
else
cb_nomodif = '';
end;
if ~isempty(opt(index).value)
uilist = { uilist{:}, { 'Style', 'text', descrip{:}, 'horizontalalignment', 'left' }, ...
{ 'Style', 'checkbox', 'string', ' ', 'value', opt(index).value 'callback' cb_nomodif } { } };
else
uilist = { uilist{:}, { 'Style', 'text', descrip{:}, 'fontweight' 'bold', 'horizontalalignment', 'left' }, ...
{ } { } };
end;
end;
% change option file
uilist = { uilist{:} {} ...
{ 'Style', 'text', 'string', 'Option file:' 'fontweight', 'bold' }, ...
{ 'Style', 'text', 'string', tmpfile 'tag' 'filename' }, ...
{} { 'Style', 'pushbutton', 'string', '...' 'callback' cb_file } };
geometry = { geometry{:} [1] [1 6 0.1 0.8] };
[results userdat ] = inputgui( geometry, uilist, 'pophelp(''pop_editoptions'');', 'Memory options - pop_editoptions()', ...
[], 'normal');
if ~isempty(userdat)
filepath = fileparts(userdat);
args = { 'filename' filename };
end;
if length(results) == 0, return; end;
% decode inputs
% -------------
args = {};
count = 1;
for index = 1:length(opt)
if ~isempty(opt(index).varname)
args = { args{:}, opt(index).varname, results{count} };
count = count+1;
end;
end;
else
% no interactive inputs
% ---------------------
args = varargin;
end;
% change default folder option
% ----------------------------
W_MAIN = findobj('tag', 'EEGLAB');
if ~isempty(W_MAIN)
tmpuserdata = get(W_MAIN, 'userdata');
tmpuserdata{3} = filepath;
set(W_MAIN, 'userdata', tmpuserdata);
end;
% decode inputs
% -------------
for index = 1:2:length(args)
ind = strmatch(args{index}, { opt.varname }, 'exact');
if isempty(ind)
if strcmpi(args{index}, 'option_savematlab')
disp('pop_editoptions: option_savematlab is obsolete, use option_savetwofiles instead');
ind = strmatch('option_savetwofiles', { opt.varname }, 'exact');
opt(ind).value = ~args{index+1};
else
error(['Variable name ''' args{index} ''' is invalid']);
end;
else
opt(ind).value = args{index+1};
end;
end;
% write to eeg_options file
% -------------------------
fid = fopen( fullfile(filepath, filename), 'w');
addpath(filepath);
if fid == -1
error('File writing error, check writing permission');
end;
fprintf(fid, '%s\n', header);
for index = 1:length(opt)
if isempty(opt(index).varname)
fprintf( fid, '%% %s\n', opt(index).description);
else
fprintf( fid, '%s = %d ; %% %s\n', opt(index).varname, opt(index).value, opt(index).description);
end;
end;
fclose(fid);
% clear it from the MATLAB function cache
clear(fullfile(filepath,filename));
% generate the output text command
% --------------------------------
com = 'pop_editoptions(';
for index = 1:2:length(args)
com = sprintf( '%s ''%s'', %d,', com, args{index}, args{index+1});
end;
com = [com(1:end-1) ');'];
wtmp = warning;
warning off;
clear functions
warning(wtmp);
% ---------------------------
function chopedtext = choptext( tmptext )
chopedtext = '';
while length(tmptext) > 30
blanks = findstr( tmptext, ' ');
[tmp I] = min( abs(blanks - 30) );
chopedtext = [ chopedtext ''' 10 ''' tmptext(1:blanks(I)) ];
tmptext = tmptext(blanks(I)+1:end);
end;
chopedtext = [ chopedtext ''' 10 ''' tmptext];
chopedtext = chopedtext(7:end);
return;
function num = popask( text )
ButtonName=questdlg2( text, ...
'Confirmation', 'Cancel', 'Yes','Yes');
switch lower(ButtonName),
case 'cancel', num = 0;
case 'yes', num = 1;
end;
|
github
|
lcnbeapp/beapp-master
|
pop_delset.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/pop_delset.m
| 2,422 |
utf_8
|
44b38052f003e12e39320b5613f097ae
|
% pop_delset() - Delete a dataset from the variable containing
% all datasets.
%
% Usage: >> ALLEEG = pop_delset(ALLEEG, indices);
%
% Inputs:
% ALLEEG - array of EEG datasets
% indices - indices of datasets to delete. None -> a pop_up window asks
% the user to choose. Index < 0 -> it's positive is given as
% the default in the pop-up window (ex: -3 -> default 3).
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: pop_copyset(), eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% load a set and store it in the current set
% ------------------------------------------
function [ALLSET, command] = pop_delset(ALLSET, set_in);
command = '';
if nargin < 1
help pop_delset;
return;
end;
if isempty( ALLSET )
error('Cannot delete dataset. Restart eeglab to clear all dataset information');
return;
end;
if nargin < 2 | set_in < 0
% which set to delete
% -----------------
promptstr = { 'Dataset(s) to delete:' };
if nargin == 2
inistr = { int2str(-set_in) };
else
inistr = { '1' };
end;
result = inputdlg2( promptstr, 'Delete dataset -- pop_delset()', 1, inistr, 'pop_delset');
size_result = size( result );
if size_result(1) == 0 return; end;
set_in = eval( [ '[' result{1} ']' ] );
end;
if isempty(set_in)
return;
end;
A = fieldnames( ALLSET );
A(:,2) = cell(size(A));
A = A';
for i = set_in
try
ALLSET(i) = struct(A{:});
%ALLSET = setfield(ALLSET, {set_in}, A{:}, cell(size(A)));
catch
error('Error: no such dataset');
return;
end;
end;
command = sprintf('%s = pop_delset( %s, [%s] );', inputname(1), inputname(1), int2str(set_in));
return;
|
github
|
lcnbeapp/beapp-master
|
pop_rejmenu.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/pop_rejmenu.m
| 23,728 |
utf_8
|
6acbdd38985f06d47dd90f857a5d8679
|
% pop_rejmenu() - Main menu for rejecting trials in an EEG dataset
%
% Usage: >> pop_rejmenu(INEEG, typerej);
%
% Inputs:
% INEEG - input dataset
% typerej - data to reject on (0 = component activations;
% 1 = raw electrode data). {Default: 1 = reject on raw data}
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeglab(), pop_eegplot(), pop_eegthresh, pop_rejtrend()
% pop_rejkurt(), pop_jointprob(), pop_rejspec()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function pop_rejmenu( EEG, icacomp );
if icacomp == 0
if isempty( EEG.icasphere )
disp('Error: you must first run ICA on the data'); return;
end;
end;
if icacomp == 1 rejtitle = 'Reject trials using data statistics - pop_rejmenu()'; tagmenu = 'rejtrialraw';
else rejtitle = 'Reject trials using component activity statistics - pop_rejmenu()'; tagmenu = 'rejtrialica';
end;
if ~isempty( findobj('tag', tagmenu))
error('cannot open two identical windows; close the first one first');
end;
figure('visible', 'off', 'numbertitle', 'off', 'name', rejtitle, 'tag', tagmenu);
% definition of callbacks
% -----------------------
checkstatus = [ 'rejstatus = get( findobj(''parent'', gcbf, ''tag'', ''rejstatus''), ''value'');' ...
'if rejstatus == 3,' ...
' EEG.reject.disprej = {};' ...
' if get( findobj(''parent'', gcbf, ''tag'', ''IManual''), ''value''), EEG.reject.disprej{1} = ''manual''; end;' ...
' if get( findobj(''parent'', gcbf, ''tag'', ''IThresh''), ''value''), EEG.reject.disprej{2} = ''thresh''; end;' ...
' if get( findobj(''parent'', gcbf, ''tag'', ''IConst''), ''value''), EEG.reject.disprej{3} = ''const''; end;' ...
' if get( findobj(''parent'', gcbf, ''tag'', ''IEnt''), ''value''), EEG.reject.disprej{4} = ''jp''; end;' ...
' if get( findobj(''parent'', gcbf, ''tag'', ''IKurt''), ''value''), EEG.reject.disprej{5} = ''kurt''; end;' ...
' if get( findobj(''parent'', gcbf, ''tag'', ''IFreq''), ''value''), EEG.reject.disprej{6} = ''freq''; end;' ...
'end;' ...
'rejstatus = rejstatus-1;' ]; % from 1-3 range, go to 0-2 range
if icacomp, ICAPREFIX = '';
else ICAPREFIX = 'ica';
end;
% tmp_comall is used when returning from eegplot
tmp_comall = [ 'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ...
'''''), ''''tag'''', ''''mantrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejmanual)));' ...
'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ...
'''''), ''''tag'''', ''''threshtrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejthresh)));' ...
'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ...
'''''), ''''tag'''', ''''freqtrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejfreq)));' ...
'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ...
'''''), ''''tag'''', ''''consttrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejconst)));' ...
'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ...
'''''), ''''tag'''', ''''enttrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejjp)));' ...
'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ...
'''''), ''''tag'''', ''''kurttrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejkurt)));' ];
cb_manual = [ checkstatus ...
'pop_eegplot( EEG, ' int2str( icacomp ) ', rejstatus, 0,''' tmp_comall ''');' ...
'clear rejstatus;' ];
% -----------------------------------------------------
cb_compthresh = [ ' posthresh = get( findobj(''parent'', gcbf, ''tag'', ''threshpos''), ''string'' );' ...
' negthresh = get( findobj(''parent'', gcbf, ''tag'', ''threshneg''), ''string'' );' ...
' startime = get( findobj(''parent'', gcbf, ''tag'', ''threshstart''), ''string'' );' ...
' endtime = get( findobj(''parent'', gcbf, ''tag'', ''threshend''), ''string'' );' ...
' elecrange = get( findobj(''parent'', gcbf, ''tag'', ''threshelec''), ''string'' );' ...
checkstatus ...
'[EEG Itmp LASTCOM] = pop_eegthresh( EEG,' int2str(icacomp) ...
', elecrange, negthresh, posthresh, str2num(startime)/1000, str2num(endtime)/1000, rejstatus, 0,''' tmp_comall ''');' ...
'EEG = eegh(LASTCOM, EEG);' ...
'clear com Itmp elecrange posthresh negthresh startime endtime rejstatus;' ];
% ' set(findobj(''parent'', gcbf, ''tag'', ''threshtrial''), ''string'', num2str(EEG.trials - length(Itmp)));' ...
% 'eegh(LASTCOM);' ...
% 'clear Itmp elecrange posthresh negthresh startime endtime rejstatus;' ];
% -----------------------------------------------------
cb_compfreq = [ ' posthresh = get( findobj(''parent'', gcbf, ''tag'', ''freqpos''), ''string'' );' ...
' negthresh = get( findobj(''parent'', gcbf, ''tag'', ''freqneg''), ''string'' );' ...
' startfreq = get( findobj(''parent'', gcbf, ''tag'', ''freqstart''), ''string'' );' ...
' endfreq = get( findobj(''parent'', gcbf, ''tag'', ''freqend''), ''string'' );' ...
' elecrange = get( findobj(''parent'', gcbf, ''tag'', ''freqelec''), ''string'' );' ...
checkstatus ...
'[EEG Itmp LASTCOM] = pop_rejspec( EEG,' int2str(icacomp) ...
', elecrange, negthresh, posthresh, startfreq, endfreq, rejstatus, 0,''' tmp_comall ''');' ...
'EEG = eegh(LASTCOM, EEG);' ...
'clear Itmp elecrange posthresh negthresh startfreq endfreq rejstatus;' ];
% -----------------------------------------------------
cb_compconstrej = [ ' minslope = get( findobj(''parent'', gcbf, ''tag'', ''constpnts''), ''string'' );' ...
' minstd = get( findobj(''parent'', gcbf, ''tag'', ''conststd''), ''string'' );' ...
' elecrange = get( findobj(''parent'', gcbf, ''tag'', ''constelec''), ''string'' );' ...
checkstatus ...
'[rej LASTCOM] = pop_rejtrend(EEG,' int2str(icacomp) ', elecrange, ''' ...
int2str(EEG.pnts) ''', minslope, minstd, rejstatus, 0,''' tmp_comall ''');' ...
'EEG = eegh(LASTCOM, EEG);' ...
'clear rej elecrange minslope minstd rejstatus;' ];
% -----------------------------------------------------
cb_compenthead = [ ' locthresh = get( findobj(''parent'', gcbf, ''tag'', ''entloc''), ''string'' );', ...
' globthresh = get( findobj(''parent'', gcbf, ''tag'', ''entglob''), ''string'' );', ...
' elecrange = get( findobj(''parent'', gcbf, ''tag'', ''entelec''), ''string'' );' ];
cb_compenttail = [ ' set( findobj(''parent'', gcbf, ''tag'', ''entloc''), ''string'', num2str(locthresh) );', ...
' set( findobj(''parent'', gcbf, ''tag'', ''entglob''), ''string'', num2str(globthresh) );', ...
' set( findobj(''parent'', gcbf, ''tag'', ''enttrial''), ''string'', num2str(nrej) );' ...
'EEG = eegh(LASTCOM, EEG);' ...
'clear nrej elecrange locthresh globthresh rejstatus;' ];
cb_compentplot = [ cb_compenthead ...
'[EEG locthresh globthresh nrej LASTCOM] = pop_jointprob( EEG, ' int2str(icacomp) ...
', elecrange, locthresh, globthresh, 0, 0,''' tmp_comall ''');', ...
cb_compenttail ];
cb_compentcalc = [ cb_compenthead ...
'[EEG locthresh globthresh nrej LASTCOM] = pop_jointprob( EEG, ' int2str(icacomp) ...
', [ str2num(elecrange) ], str2num(locthresh), str2num(globthresh), 0, 0);', ...
cb_compenttail ];
cb_compenteeg = [ cb_compenthead ...
checkstatus ...
'[EEG locthresh globthresh nrej LASTCOM] = pop_jointprob( EEG, ' int2str(icacomp) ...
', elecrange, locthresh, globthresh, rejstatus, 0, 1,''' tmp_comall ''');', ...
cb_compenttail ];
% -----------------------------------------------------
cb_compkurthead =[ ' locthresh = get( findobj(''parent'', gcbf, ''tag'', ''kurtloc''), ''string'' );', ...
' globthresh = get( findobj(''parent'', gcbf, ''tag'', ''kurtglob''), ''string'' );', ...
' elecrange = get( findobj(''parent'', gcbf, ''tag'', ''kurtelec''), ''string'' );' ];
cb_compkurttail =[ ' set( findobj(''parent'', gcbf, ''tag'', ''kurtloc''), ''string'', num2str(locthresh) );', ...
' set( findobj(''parent'', gcbf, ''tag'', ''kurtglob''), ''string'', num2str(globthresh) );', ...
' set( findobj(''parent'', gcbf, ''tag'', ''kurttrial''), ''string'', num2str(nrej) );' ...
'EEG = eegh(LASTCOM, EEG);' ...
'clear nrej elecrange locthresh globthresh rejstatus;' ];
cb_compkurtplot = [ cb_compkurthead ...
'[EEG locthresh globthresh nrej LASTCOM] = pop_rejkurt( EEG, ' int2str(icacomp) ...
', elecrange, locthresh, globthresh, 0, 0,''' tmp_comall ''');', ...
cb_compkurttail ];
cb_compkurtcalc = [ cb_compkurthead ...
'[EEG locthresh globthresh nrej LASTCOM] = pop_rejkurt( EEG, ' int2str(icacomp) ...
', [ str2num(elecrange) ], str2num(locthresh), str2num(globthresh), 0, 0);', ...
cb_compkurttail ];
cb_compkurteeg = [ cb_compkurthead ...
checkstatus ...
'[EEG locthresh globthresh nrej LASTCOM] = pop_rejkurt( EEG, ' int2str(icacomp) ...
', elecrange, locthresh, globthresh, rejstatus, 0, 1,''' tmp_comall ''');', ...
cb_compkurttail ];
% -----------------------------------------------------
cb_reject = [ 'set( findobj(''parent'', gcbf, ''tag'', ''rejstatus''), ''value'', 3);' ... % force status to 3
checkstatus ...
'[EEG LASTCOM] = eeg_rejsuperpose(EEG,' int2str(icacomp) ',1,1,1,1,1,1,1); EEG = eegh(LASTCOM, EEG);' ...
'if isempty(find(EEG.reject.rejglobal)),' ...
' warndlg2(strvcat(''No epoch selected...'', ''When using thresholding, click update'',''marks in the EEG plotting window''));' ...
'else,' ...
' [EEG LASTCOM] = pop_rejepoch( EEG, EEG.reject.rejglobal, 1);' ...
' if ~isempty(LASTCOM), ' ...
' EEG = eegh(LASTCOM, EEG); [ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET); eegh(LASTCOM);' ...
' end; eeglab redraw; close(gcbf);' ...
'end;' ];
cb_clear = [ 'close gcbf; EEG = rmfield( EEG, ''reject''); EEG.reject.rejmanual = [];' ...
'EEG=eeg_checkset(EEG); pop_rejmenu(' inputname(1) ',' int2str(icacomp) ');' ];
cb_close = [ 'close gcbf;' ...
'disp(''Marks stored in dataset'');' ...
'[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);' ...
'eegh(''[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);'');'];
lisboxoptions = { 'string', [ 'Show only the new trials marked for rejection by the measure selected above|' ...
'Show previous and new trials marked for rejection by the measure selected above|' ...
'Show all trials marked for rejection by the measure selected above or checked below'], 'tag', 'rejstatus', 'value', 1, 'callback', ...
[ 'if get(gcbo, ''value'') == 3,' ...
' set(findobj(''parent'', gcbf, ''style'', ''checkbox''), ''enable'', ''on'');' ...
'else' ...
' set(findobj(''parent'', gcbf, ''style'', ''checkbox''), ''enable'', ''off'');' ...
'end;' ] };
chanliststr = [fastif(icacomp,'Electrode(s)','Component(s)') ];
chanlistval = fastif(icacomp, [ '1:' int2str(EEG.nbchan) ], [ '1:' int2str(size(EEG.icaweights,1)) ]);
% assess previous rejections
% --------------------------
sizeman = 0;
sizethresh = 0;
sizetrend = 0;
sizejp = 0;
sizekurt = 0;
sizespec = 0;
if icacomp == 1
if ~isempty(EEG.reject.rejmanual), sizeman = length(find(EEG.reject.rejmanual)); end;
if ~isempty(EEG.reject.rejconst), sizetrend = length(find(EEG.reject.rejconst)); end;
if ~isempty(EEG.reject.rejjp), sizejp = length(find(EEG.reject.rejjp)); end;
if ~isempty(EEG.reject.rejkurt), sizekurt = length(find(EEG.reject.rejkurt)); end;
if ~isempty(EEG.reject.rejfreq), sizespec = length(find(EEG.reject.rejfreq)); end;
else
if ~isempty(EEG.reject.icarejmanual), sizeman = length(find(EEG.reject.icarejmanual)); end;
if ~isempty(EEG.reject.icarejconst), sizetrend = length(find(EEG.reject.icarejconst)); end;
if ~isempty(EEG.reject.icarejjp), sizejp = length(find(EEG.reject.icarejjp)); end;
if ~isempty(EEG.reject.icarejkurt), sizekurt = length(find(EEG.reject.icarejkurt)); end;
if ~isempty(EEG.reject.icarejfreq), sizespec = length(find(EEG.reject.icarejfreq)); end;
end;
stdl = [0.25 1.2 0.8 1.2 0.8]; % standard line
titl = [0.9 0.18 1.55]; % title line
geometry = { [0.883 0.195 .2 .45 .4 .4] ...
[1] titl stdl stdl stdl stdl ...
[1] titl stdl stdl stdl ...
[1] titl stdl stdl stdl ...
[1] titl stdl stdl stdl ...
[1] titl stdl stdl stdl stdl ...
[1] [1] [1] [1 1 1] [1 1 1] ...
[1] [1 1 1]};
listui = {{'Style', 'text', 'string', 'Mark trials by appearance', 'fontweight', 'bold' }, ...
{ 'Style', 'pushbutton', 'string', '', 'tag', 'butmanual', ...
'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejmanualcol); if length(tmpcolor) ~= 1,' ...
'EEG.reject.rejmanualcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] },...
{ } { 'Style', 'pushbutton', 'string', fastif(icacomp,'Scroll Data','Scroll Acts.'), 'callback', cb_manual }, ...
{ 'Style', 'text', 'string', 'Marked trials' }, ...
{ 'Style', 'text', 'string', int2str(sizeman), 'tag', 'mantrial' }, ...
{ }, ...
... % ---------------------------------------------------------------------------
{ 'Style', 'text', 'string', 'Find abnormal values', 'fontweight', 'bold' }, ...
{ 'Style', 'pushbutton', 'string', '', 'tag', 'butthresh', ...
'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejthreshcol); if length(tmpcolor) ~= 1,' ...
'EEG.reject.rejthreshcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] }, { },...
...
{ }, { 'Style', 'text', 'string', ['Upper limit(s) ' fastif(icacomp,'(uV)', '(std. dev.)')] }, ...
{ 'Style', 'edit', 'string', '25', 'tag', 'threshpos' }, ...
{ 'Style', 'text', 'string', ['Lower limit(s) ' fastif(icacomp,'(uV)', '(std. dev.)')] }, ...
{ 'Style', 'edit', 'string', '-25', 'tag', 'threshneg' }, ...
...
{ }, { 'Style', 'text', 'string', 'Start time(s) (ms)' }, ...
{ 'Style', 'edit', 'string', int2str(EEG.xmin*1000), 'tag', 'threshstart' }, ...
{ 'Style', 'text', 'string', 'Ending time(s) (ms)' }, ...
{ 'Style', 'edit', 'string', int2str(EEG.xmax*1000), 'tag', 'threshend' }, ...
...
{ }, { 'Style', 'text', 'string', chanliststr }, ...
{ 'Style', 'edit', 'string', chanlistval, 'tag', 'threshelec' }, ...
{ 'Style', 'text', 'string', 'Currently marked trials' }, ...
{ 'Style', 'text', 'string', int2str(sizethresh), 'tag', 'threshtrial' }, ...
...
{ }, { 'Style', 'pushbutton', 'string', 'Calc / Plot', 'callback', cb_compthresh }, ...
{ }, { },{ 'Style', 'pushbutton', 'string', 'HELP', 'callback', 'pophelp(''pop_eegthresh'');' }, ...
... % ---------------------------------------------------------------------------
{ }, { 'Style', 'text', 'string', 'Find abnormal trends', 'fontweight', 'bold' }, ...
{ 'Style', 'pushbutton', 'string', '', 'tag', 'buttrend', ...
'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejconstcol); if length(tmpcolor) ~= 1,' ...
'EEG.reject.rejconstcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] }, { },...
...
{ }, { 'Style', 'text', 'string', ['Max slope ' fastif(icacomp, ...
'(uV/epoch)', ...
'(std. dev./epoch)') ] }, ...
{ 'Style', 'edit', 'string', '50', 'tag', 'constpnts' }, ...
{ 'Style', 'text', 'string', 'R-squared limit (0 to 1)' }, ...
{ 'Style', 'edit', 'string', '0.3', 'tag', 'conststd' }, ...
...
{ }, { 'Style', 'text', 'string', chanliststr }, ...
{ 'Style', 'edit', 'string', chanlistval, 'tag', 'constelec' }, ...
{ 'Style', 'text', 'string', 'Currently marked trials' }, ...
{ 'Style', 'text', 'string', int2str(sizetrend), 'tag', 'consttrial' }, ...
...
{ }, { 'Style', 'pushbutton', 'string', 'Calc / Plot', 'callback', cb_compconstrej }, ...
{ }, { }, { 'Style', 'pushbutton', 'string', 'HELP', 'callback', 'pophelp(''pop_rejtrend'');' }, ...
... % ---------------------------------------------------------------------------
{ }, { 'Style', 'text', 'string', 'Find improbable data', 'fontweight', 'bold' }, ...
{ 'Style', 'pushbutton', 'string', '', 'tag', 'butjp', ...
'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejjpcol); if length(tmpcolor) ~= 1,' ...
'EEG.reject.rejjpcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] }, { },...
...
{ }, { 'Style', 'text', 'string', fastif(icacomp, 'Single-channel limit (std. dev.)', 'Single-comp. limit (std. dev.)') }, ...
{ 'Style', 'edit', 'string', fastif(icacomp, '5', '20'), 'tag', 'entloc' }, ...
{ 'Style', 'text', 'string', fastif(icacomp, 'All channels limit (std. dev.)', 'All comp. limit (std. dev.)') }, ...
{ 'Style', 'edit', 'string', '5', 'tag', 'entglob' }, ...
...
{ }, { 'Style', 'text', 'string', chanliststr }, ...
{ 'Style', 'edit', 'string', chanlistval, 'tag', 'entelec' }, ...
{ 'Style', 'text', 'string', 'Currently marked trials' }, ...
{ 'Style', 'text', 'string', int2str(sizejp), 'tag', 'enttrial' }, ...
...
{ }, { 'Style', 'pushbutton', 'string', 'Calculate', 'callback', cb_compentcalc }, ...
{ 'Style', 'pushbutton', 'string', 'Scroll Data', 'callback', cb_compenteeg }, ...
{ 'Style', 'pushbutton', 'string', 'PLOT', 'callback', cb_compentplot }, ...
{ 'Style', 'pushbutton', 'string', 'HELP', 'callback', 'pophelp(''pop_jointprob'');' }, ...
... % ---------------------------------------------------------------------------
{ }, { 'Style', 'text', 'string', 'Find abnormal distributions', 'fontweight', 'bold' }, ...
{ 'Style', 'pushbutton', 'string', '', 'tag', 'butkurt', ...
'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejkurtcol); if length(tmpcolor) ~= 1,' ...
'EEG.reject.rejkurtcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] }, { },...
...
{ }, { 'Style', 'text', 'string', fastif(icacomp, 'Single-channel limit (std. dev.)', 'Single-comp. limit (std. dev.)') }, ...
{ 'Style', 'edit', 'string', fastif(icacomp, '5', '20'), 'tag', 'kurtloc' }, ...
{ 'Style', 'text', 'string', fastif(icacomp, 'All channels limit (std. dev.)', 'All comp. limit (std. dev.)') }, ...
{ 'Style', 'edit', 'string', '5', 'tag', 'kurtglob' }, ...
...
{ }, { 'Style', 'text', 'string', chanliststr }, ...
{ 'Style', 'edit', 'string', chanlistval, 'tag', 'kurtelec' }, ...
{ 'Style', 'text', 'string', 'Currently marked trials' }, ...
{ 'Style', 'text', 'string', int2str(sizekurt), 'tag', 'kurttrial' }, ...
...
{ }, { 'Style', 'pushbutton', 'string', 'Calculate', 'callback', cb_compkurtcalc }, ...
{ 'Style', 'pushbutton', 'string', 'Scroll Data', 'callback', cb_compkurteeg }, ...
{ 'Style', 'pushbutton', 'string', 'PLOT', 'callback', cb_compkurtplot }, ...
{ 'Style', 'pushbutton', 'string', 'HELP', 'callback', 'pophelp(''pop_rejkurt'');' }, ...
... % ---------------------------------------------------------------------------
{ }, { 'Style', 'text', 'string', 'Find abnormal spectra (slow)', 'fontweight', 'bold' }, ...
{ 'Style', 'pushbutton', 'string', '', 'tag', 'butspec', ...
'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejfreqcol); if length(tmpcolor) ~= 1,' ...
'EEG.reject.rejfreqcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] }, { },...
...
{ }, { 'Style', 'text', 'string', 'Upper limit(s) (dB)' }, ...
{ 'Style', 'edit', 'string', '25', 'tag', 'freqpos' }, ...
{ 'Style', 'text', 'string', 'Lower limit(s) (dB)' }, ...
{ 'Style', 'edit', 'string', '-25', 'tag', 'freqneg' }, ...
...
{ }, { 'Style', 'text', 'string', 'Low frequency(s) (Hz)' }, ...
{ 'Style', 'edit', 'string', '0', 'tag', 'freqstart' }, ...
{ 'Style', 'text', 'string', 'High frequency(s) (Hz)' }, ...
{ 'Style', 'edit', 'string', '50', 'tag', 'freqend' }, ...
...
{ }, { 'Style', 'text', 'string', chanliststr }, ...
{ 'Style', 'edit', 'string', chanlistval, 'tag', 'freqelec' }, ...
{ 'Style', 'text', 'string', 'Currently marked trials' }, ...
{ 'Style', 'text', 'string', int2str(sizespec), 'tag', 'freqtrial' }, ...
...
{ }, { 'Style', 'pushbutton', 'string', 'Calc / Plot', 'callback', cb_compfreq }, ...
{ }, { },{ 'Style', 'pushbutton', 'string', 'HELP', 'callback', 'pophelp(''pop_rejspec'');' }, ...
...
{}, ... % ---------------------------------------------------------------------------
...
{ 'Style', 'text', 'string', 'Plotting options', 'fontweight', 'bold' }, ...
{ 'style', 'listbox', lisboxoptions{:}, 'value', 3 }, ...
{ 'style', 'checkbox', 'String', 'Abnormal appearance', 'tag', 'IManual', 'value', 1, ...
'callback', 'set(gcbo, ''value'', 1); disp(''This checkbox must be set so that you may mark/unmark data epochs'');'}, ...
{ 'style', 'checkbox', 'String', 'Abnormal values', 'tag', 'IThresh', 'value', 1}, ...
{ 'style', 'checkbox', 'String', 'Abnormal trends', 'tag', 'IConst', 'value', 1}, ...
{ 'style', 'checkbox', 'String', 'Improbable epochs', 'tag', 'IEnt', 'value', 1}, ...
{ 'style', 'checkbox', 'String', 'Abnormal distributions', 'tag', 'IKurt', 'value', 1}, ...
{ 'style', 'checkbox', 'String', 'Abnormal spectra', 'tag', 'IFreq', 'value', 1}, ...
...
{ }, ...
{ 'Style', 'pushbutton', 'string', 'CLOSE (KEEP MARKS)', 'callback', cb_close }, ...
{ 'Style', 'pushbutton', 'string', 'CLEAR ALL MARKS', 'callback', cb_clear }, ...
{ 'Style', 'pushbutton', 'string', 'REJECT MARKED TRIALS', 'callback', cb_reject }};
allh = supergui( gcf, geometry, [], listui{:});
% { 'style', 'checkbox', 'String', ['Include ' fastif(icacomp, 'ica data', 'raw data')], 'tag', 'IOthertype', 'value', 1}, { }, ...
set(gcf, 'userdata', { allh });
set(findobj('parent', gcf', 'tag', 'butmanual'), 'backgroundcolor', EEG.reject.rejmanualcol);
set(findobj('parent', gcf', 'tag', 'butthresh'), 'backgroundcolor', EEG.reject.rejthreshcol);
set(findobj('parent', gcf', 'tag', 'buttrend'), 'backgroundcolor', EEG.reject.rejconstcol);
set(findobj('parent', gcf', 'tag', 'butjp'), 'backgroundcolor', EEG.reject.rejjpcol);
set(findobj('parent', gcf', 'tag', 'butkurt'), 'backgroundcolor', EEG.reject.rejkurtcol);
set(findobj('parent', gcf', 'tag', 'butspec'), 'backgroundcolor', EEG.reject.rejfreqcol);
set( findobj('parent', gcf, 'tag', 'rejstatus'), 'style', 'popup');
|
github
|
lcnbeapp/beapp-master
|
plugin_extract.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/plugin_extract.m
| 13,795 |
utf_8
|
7b0ac3bbdf7c634198dacd247b55052a
|
function restartEeglabFlag = plugin_extract(type, pluginlist, page)
if nargin < 3, page = 1; end;
% type may be 'import' or 'process'
restartEeglabFlag = false;
pluginsPerPage = 15;
% check the presence of unzip
%str = evalc('!unzip');
%if length(str) < 200
% error([ '"unzip" could not be found. Instal unzip and make sure' 10 'it is accessible under Matlab by adding the program to' 10 'the path and typing "!unzip"' ]);
%end;
if ~isstruct(type)
plugin = plugin_getweb(type, pluginlist, 'newlist');
% sort plugins by download score
[tmp scoreOrder] = sort([ plugin.downloads ], 2, 'descend');
plugin = plugin(scoreOrder);
else
plugin = type;
end;
% select page
allPlugins = plugin;
numPlugin = length(plugin);
moreThanOnePage = 0;
if numPlugin > pluginsPerPage
plugin = plugin(pluginsPerPage*(page-1)+1:min(length(plugin),pluginsPerPage*page));
moreThanOnePage = 1;
end;
% find which menu to show
newInstallFlag = false;
installedFlag = false;
deactivatedFlag = false;
for iPlugin = length(plugin):-1:1
if ~plugin(iPlugin).installed, newInstallFlag = true; end;
if plugin(iPlugin).installed && ~strcmpi(plugin(iPlugin).status, 'deactivated'), installedFlag = true; end;
if strcmpi(plugin(iPlugin).status, 'deactivated'), deactivatedFlag = true; end;
end;
uilist = {};
geom = {};
geomvert = [];
pluginIndices = [];
callback = [ 'tmptag = get(gcbo, ''tag'');' ...
'if tmptag(3) == ''1'', tmptag(3) = ''2''; else tmptag(3) = ''1''; end;' ...
'if get(gcbo, ''value''), set(findobj(gcbf, ''tag'', tmptag), ''value'', 0); end; clear tmptag;' ];
% ------------------
% plugins to install
% ------------------
maxchar = 60;
geom = {};
lineGeom = [ 0.28 0.28 0.95 0.6 0.6 3 0.35 ];
if newInstallFlag
uilist = { {} { 'style' 'text' 'string' 'Extensions available for install on the internet' 'fontweight' 'bold' 'fontsize' 18 'tag' 'title' } };
uilist = { uilist{:} { 'style' 'text' 'string' 'I' 'tag' 'install' } { } ...
{ 'style' 'text' 'string' 'Plugin' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Vers.' 'tag' 'verweb' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Score' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Description' 'fontweight' 'bold' } {}};
geom = { [1 5.5] lineGeom };
geomvert = [1 1];
for iRow = 1:length(plugin)
if ~plugin(iRow).installed && ~strcmpi(plugin(iRow).status, 'deactivated')
% text for description
description = plugin(iRow).description;
if length(description) > maxchar+2
description = [ description(1:min(maxchar,length(description))) '...' ];
end;
enableWebDoc = fastif(isempty(plugin(iRow).webdoc), 'off', 'on');
userdata = '';
if plugin(iRow).installed && plugin(iRow).installorupdate, userdata = 'colortored'; end;
uilist = { uilist{:}, ...
{ 'style' 'checkbox' 'string' '' 'value' 0 'enable' 'on' }, ...
{ 'style' 'checkbox' 'string' '' 'visible' 'off' }, ...
{ 'style' 'text' 'string' plugin(iRow).name }, ...
{ 'style' 'text' 'string' plugin(iRow).version 'tag' 'latestversion' 'userdata' userdata }, ...
{ 'style' 'text' 'string' int2str(plugin(iRow).downloads) }, ...
{ 'style' 'text' 'string' description }, ...
{ 'style' 'pushbutton' 'string' 'Doc' 'enable' enableWebDoc 'callback' myweb(plugin(iRow).webdoc) } };
geom = { geom{:}, lineGeom };
geomvert = [ geomvert 1];
pluginIndices = [ pluginIndices iRow ];
end;
end;
end;
% -----------------
% installed plugins
% -----------------
if installedFlag
uilist = { uilist{:} {} {} { 'style' 'text' 'string' 'Installed extensions' 'fontweight' 'bold' 'fontsize' 18 'tag' 'title' } };
uilist = { uilist{:} { 'style' 'text' 'string' 'I' 'tag' 'update' } ...
{ 'style' 'text' 'string' 'I' 'tag' 'deactivate' } ...
{ 'style' 'text' 'string' 'Plugin' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Vers.' 'tag' 'verweb' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Score' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Description' 'fontweight' 'bold' } {}};
geom = { geom{:} 1 [1 5.5] lineGeom };
geomvert = [geomvert 1 1 1];
for iRow = 1:length(plugin)
if plugin(iRow).installed && ~strcmpi(plugin(iRow).status, 'deactivated')
% text for description
description = plugin(iRow).description;
if length(description) > maxchar+2
description = [ description(1:min(maxchar,length(description))) '...' ];
end;
enableWebDoc = fastif(isempty(plugin(iRow).webdoc), 'off', 'on');
userdata = '';
if plugin(iRow).installorupdate,
textnew = [ 'Click update to install version ' plugin(iRow).version ' now available on the web' ];
userdata = 'colortored';
else
textnew = description;
end;
uilist = { uilist{:}, ...
{ 'style' 'checkbox' 'string' '' 'value' 0 'enable' fastif(plugin(iRow).installorupdate, 'on', 'off') 'tag' [ 'cb1' int2str(iRow) ] 'callback' callback }, ...
{ 'style' 'checkbox' 'string' '' 'enable' 'on' 'tag' [ 'cb2' int2str(iRow) ] 'callback' callback }, ...
{ 'style' 'text' 'string' plugin(iRow).name }, ...
{ 'style' 'text' 'string' plugin(iRow).currentversion 'tag' 'latestversion'}, ...
{ 'style' 'text' 'string' int2str(plugin(iRow).downloads) }, ...
{ 'style' 'text' 'string' textnew 'userdata' userdata }, ...
{ 'style' 'pushbutton' 'string' 'Doc' 'enable' enableWebDoc 'callback' myweb(plugin(iRow).webdoc) } };
geom = { geom{:}, lineGeom };
geomvert = [ geomvert 1];
pluginIndices = [ pluginIndices iRow ];
end;
end;
end;
% -------------------
% deactivated plugins
% -------------------
%geom = { geom{:} 1 1 };
%geomvert = [geomvert 0.5 1];
%uilist = { uilist{:} {} { 'style' 'text' 'string' 'To manage deactivated plugins, use menu item File > Manage plugins > Manage deactivated plugins' } };
if deactivatedFlag
uilist = { uilist{:} {} {} { 'style' 'text' 'string' 'List of deactivated extensions ' 'fontweight' 'bold' 'fontsize' 18 'tag' 'title' } };
uilist = { uilist{:} ...
{ 'style' 'text' 'string' 'I' 'tag' 'reactivate' } ...
{ 'style' 'text' 'string' 'I' 'tag' 'remove1' } ...
{ 'style' 'text' 'string' 'Plugin' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Vers.' 'tag' 'verweb' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Score' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'Description' 'fontweight' 'bold' } {}};
geom = { geom{:} 1 [1 5.5] lineGeom };
geomvert = [geomvert 1 1 1];
for iRow = 1:length(plugin)
if strcmpi(plugin(iRow).status, 'deactivated')
% text for description
description = plugin(iRow).description;
if length(description) > maxchar+2
description = [ description(1:min(maxchar,length(description))) '...' ];
end;
userdata = '';
enableWebDoc = fastif(isempty(plugin(iRow).webdoc), 'off', 'on');
uilist = { uilist{:}, ...
{ 'style' 'checkbox' 'string' '' 'tag' [ 'cb1' int2str(iRow) ] 'callback' callback }, ...
{ 'style' 'checkbox' 'string' '' 'tag' [ 'cb2' int2str(iRow) ] 'callback' callback }, ...
{ 'style' 'text' 'string' plugin(iRow).name }, ...
{ 'style' 'text' 'string' plugin(iRow).version 'tag' 'latestversion' }, ...
{ 'style' 'text' 'string' int2str(plugin(iRow).downloads) }, ...
{ 'style' 'text' 'string' description }, ...
{ 'style' 'pushbutton' 'string' 'Doc' 'enable' enableWebDoc 'callback' myweb(plugin(iRow).webdoc) } };
geom = { geom{:}, lineGeom };
geomvert = [ geomvert 1];
pluginIndices = [ pluginIndices iRow ];
end;
end;
end;
evalStr = [ 'uisettxt(gcf, ''update'' , ''Update'' , ''rotation'', 90, ''fontsize'', 14);' ...
'uisettxt(gcf, ''deactivate'' , ''Deactivate'' , ''rotation'', 90, ''fontsize'', 14);' ...
'uisettxt(gcf, ''install'' , ''Install'' , ''rotation'', 90, ''fontsize'', 14);' ...
'uisettxt(gcf, ''reactivate'' , ''Reactivate'' , ''rotation'', 90, ''fontsize'', 14);' ...
'uisettxt(gcf, ''remove1'' , ''Remove'' , ''rotation'', 90, ''fontsize'', 14);' ...
'set(findobj(gcf, ''tag'', ''title''), ''fontsize'', 16);' ...
'tmpobj = findobj(gcf, ''userdata'', ''colortored'');' ...
'set(tmpobj, ''Foregroundcolor'', [1 0 0]);' ...
'tmppos = get(gcf, ''position'');' ...
'set(gcf, ''position'', [tmppos(1:2) 800 tmppos(4)]);' ...
'clear tmpobj tmppos;' ...
];
if 1
% version with button
if page == 1, enablePpage = 'off'; else enablePpage = 'on'; end;
if page*pluginsPerPage > numPlugin, enableNpage = 'off'; else enableNpage = 'on'; end;
callBackPpage = [ 'tmpobj = get(gcbf, ''userdata''); close gcbf; restartEeglabFlag = plugin_extract(tmpobj, [], ' int2str(page-1) '); clear tmpobj;' ];
callBackNpage = [ 'tmpobj = get(gcbf, ''userdata''); close gcbf; restartEeglabFlag = plugin_extract(tmpobj, [], ' int2str(page+1) '); clear tmpobj;' ];
uilist = { uilist{:}, {} { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', '< Prev. page', 'tag' 'ppage' 'callback', callBackPpage 'enable' enablePpage } };
uilist = { uilist{:}, { 'width' 80 'align' 'left' 'stickto' 'on', 'Style', 'pushbutton', 'string', 'Next page >', 'tag' 'npage' 'callback', callBackNpage 'enable' enableNpage } };
uilist = { uilist{:}, { 'width' 80 'align' 'right' 'Style', 'pushbutton', 'string', 'Cancel', 'tag' 'cancel' 'callback', 'close gcbf' } };
uilist = { uilist{:}, { 'width' 80 'align' 'right' 'stickto' 'on' 'Style', 'pushbutton', 'tag', 'ok', 'string', 'OK', 'callback', 'set(gcbo, ''userdata'', ''retuninginputui'');' } };
geom = { geom{:} [1] [1 1 1 1] };
geomvert = [ geomvert 1 1];
res = inputgui('uilist', uilist, 'geometry', geom, 'geomvert', geomvert, 'eval', evalStr, 'addbuttons', 'off', 'skipline', 'off', 'userdata', allPlugins);
try, restartEeglabFlag = evalin('base', 'restartEeglabFlag;'); catch, end;
evalin('base', 'clear restartEeglabFlag;');
else
% no buttons
res = inputgui('uilist', uilist, 'geometry', geom, 'geomvert', geomvert, 'eval', evalStr);
end;
if isempty(res), return; end;
% decode inputs
% -------------
for iRow = 1:length(pluginIndices)
plugin(pluginIndices(iRow)).install = res{(iRow-1)*2+1};
plugin(pluginIndices(iRow)).remove = res{(iRow-1)*2+2};
end;
% install plugins
% ---------------
firstPlugin = 1;
for iRow = 1:length(plugin)
if plugin(iRow).install
restartEeglabFlag = true;
if ~firstPlugin, disp('---------------------------------'); end; firstPlugin = 0;
if strcmpi(plugin(iRow).status, 'deactivated')
fprintf('Reactivating extension %s\n', plugin(iRow).name);
plugin_reactivate(plugin(iRow).foldername);
if plugin(iRow).installorupdate
res = questdlg2([ 'Extension ' plugin(iRow).foldername ' has been reactivated but' 10 'a new version is available. Do you want to install it?' ], 'Warning', 'No', 'Yes', 'Yes');
if strcmpi(res, 'yes')
plugin_deactivate(plugin(iRow).foldername);
if plugin_install(plugin(iRow).zip, plugin(iRow).name, plugin(iRow).version) == -1
plugin_reactivate(plugin(iRow).foldername);
else
plugin_remove(plugin(iRow).foldername);
end;
end;
end;
else
if plugin(iRow).installed
fprintf('Updating extension %s\n', plugin(iRow).name);
plugin_deactivate(plugin(iRow).foldername);
if plugin_install(plugin(iRow).zip, plugin(iRow).name, plugin(iRow).version) == -1
plugin_reactivate(plugin(iRow).foldername);
else
plugin_remove(plugin(iRow).foldername);
end;
else
fprintf('Installing extension %s\n', plugin(iRow).name);
plugin_install(plugin(iRow).zip, plugin(iRow).name, plugin(iRow).version);
end;
end;
elseif plugin(iRow).remove
if ~firstPlugin, disp('---------------------------------'); end; firstPlugin = 0;
restartEeglabFlag = true;
if strcmpi(plugin(iRow).status, 'deactivated')
fprintf('Removing extension %s\n', plugin(iRow).name);
plugin_remove(plugin(iRow).foldername);
else
fprintf('Deactivating extension %s\n', plugin(iRow).name);
plugin_deactivate(plugin(iRow).foldername);
end;
end;
end;
function str = myweb(url);
%if isempty(strfind(url, 'wiki'))
% str = [ 'web(''' url ''');' ];
%else
str = [ 'web(''' url ''', ''-browser'');' ];
%end;
|
github
|
lcnbeapp/beapp-master
|
eeg_store.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/eeg_store.m
| 5,423 |
utf_8
|
d4bd75d1e701aaaba164772acc07725e
|
% eeg_store() - store specified EEG dataset(s) in the ALLEG variable
% containing all current datasets, after first checking
% dataset consistency using eeg_checkset().
%
% Usage: >> [ALLEEG EEG index] = eeg_store(ALLEEG, EEG);
% >> [ALLEEG EEG index] = eeg_store(ALLEEG, EEG, index);
%
% Inputs:
% ALLEEG - variable containing all current EEGLAB datasets
% EEG - dataset(s) to store - usually the current dataset.
% May also be an array of datasets; these will be
% checked and stored separately in ALLEEG.
% index - (optional), ALLEEG index (or indices) to use to store
% the new dataset(s). If no index is given, eeg_store()
% uses the lowest empty slot(s) in the ALLEEG array.
% Outputs:
% ALLEEG - array of all current datasets
% EEG - EEG dataset (after syntax checking)
% index - index of the new dataset
%
% Note: When 3 arguments are given, after checking the consistency of
% the input dataset structures this function simply performs
% >> ALLEEG(index) = EEG;
%
% Typical use:
% >> [ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG);
% creates a new dataset in variable ALLEEG.
% >> [ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);
% overwrites the current dataset in variable ALLEEG.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeglab(), eeg_checkset(), eeg_retrieve()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% uses the global variable EEG ALLEEG CURRENTSET
% store set
% ------------------
function [ALLEEG, EEG, storeSetIndex] = eeg_store(ALLEEG, EEG, storeSetIndex, varargin);
% check parameter consistency
% ------------------------------
if nargin >= 3
if length(EEG) ~= length(storeSetIndex) & storeSetIndex(1) ~= 0
error('Length of input dataset structure must equal the length of the index array');
end;
end;
% considering multiple datasets
% -----------------------------
if length(EEG) > 1
TMPEEG = EEG;
if nargin >= 3 & storeSetIndex(1) ~= 0
for index=1:length(TMPEEG)
EEG = TMPEEG(index);
tmpsaved = EEG.saved;
if strcmpi(tmpsaved, 'justloaded'), tmpsaved = 'yes'; end;
[ALLEEG, EEG] = eeg_store(ALLEEG, EEG, storeSetIndex(index), varargin{:});
ALLEEG(storeSetIndex(index)).saved = tmpsaved;
TMPEEG(index).saved = tmpsaved;
end;
else
for index=1:length(TMPEEG)
EEG = TMPEEG(index);
tmpsaved = EEG.saved;
if strcmpi(tmpsaved, 'justloaded'), tmpsaved = 'yes'; end;
[ALLEEG, EEG, storeSetIndex(index)] = eeg_store(ALLEEG, EEG);
ALLEEG(storeSetIndex(index)).saved = tmpsaved;
TMPEEG(index).saved = tmpsaved;
end;
end;
EEG = TMPEEG;
return;
end;
if nargin < 3
% creating new dataset
% -> erasing file information
% ---------------------------
EEG.filename = '';
EEG.filepath = '';
EEG.datfile = '';
end;
if isempty(varargin) % no text output and no check (study loading)
[ EEG com ] = eeg_checkset(EEG);
else
com = '';
end;
if nargin > 2,
if storeSetIndex == 0 || strcmpi(EEG.saved, 'justloaded')
EEG.saved = 'yes'; % just loaded
else
EEG.saved = 'no';
end;
elseif strcmpi(EEG.saved, 'justloaded')
EEG.saved = 'yes';
else
EEG.saved = 'no';
end;
EEG = eeg_hist(EEG, com);
% find first free index
% ---------------------
findindex = 0;
if nargin < 3, findindex = 1;
elseif storeSetIndex == 0, findindex = 1;
end;
if findindex
i = 1;
while (i<2000)
try
if isempty(ALLEEG(i).data);
storeSetIndex = i; i = 2000;
end;
i = i+1;
catch
storeSetIndex = i; i = 2000;
end;
end;
if isempty(varargin) % no text output and no check
fprintf('Creating a new ALLEEG dataset %d\n', storeSetIndex);
end;
else
if isempty(storeSetIndex) | storeSetIndex == 0
storeSetIndex = 1;
end;
end;
if ~isempty( ALLEEG )
try
ALLEEG(storeSetIndex) = EEG;
catch
allfields = fieldnames( EEG );
for i=1:length( allfields )
eval( ['ALLEEG(' int2str(storeSetIndex) ').' allfields{i} ' = EEG.' allfields{i} ';' ]);
end;
if ~isfield(EEG, 'datfile') & isfield(ALLEEG, 'datfile')
ALLEEG(storeSetIndex).datfile = '';
end;
end;
else
ALLEEG = EEG;
if storeSetIndex ~= 1
ALLEEG(storeSetIndex+1) = EEG;
ALLEEG(1) = ALLEEG(storeSetIndex); % empty
ALLEEG(storeSetIndex) = ALLEEG(storeSetIndex+1);
ALLEEG = ALLEEG(1:storeSetIndex);
end;
end;
return;
|
github
|
lcnbeapp/beapp-master
|
eeg_eval.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/eeg_eval.m
| 4,224 |
utf_8
|
a33398d975e05e64806a16536fdcca32
|
% eeg_eval() - apply eeglab function to a collection of input datasets
%
% Usage:
% >> OUTEEG = eeg_eval(funcname, INEEG, 'key1', value1, 'key2', value2 ...);
%
% Inputs:
% funcname - [string] name of the function
% INEEG - EEGLAB input dataset(s)
%
% Optional inputs
% 'params' - [cell array] funcname parameters.
% 'warning' - ['on'|'off'] warning pop-up window if several dataset
% stored on disk that will be automatically overwritten.
% Default is 'on'.
%
% Outputs:
% OUTEEG - output dataset(s)
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2005
%
% see also: eeglab()
% Copyright (C) 2005 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG, com] = eeg_eval( funcname, EEG, varargin);
com = '';
if nargin < 2
help eeg_eval;
return;
end;
% check input parameters
% ----------------------
g = finputcheck( varargin, { 'params' 'cell' {} {};
'warning' 'string' { 'on','off' } 'on' }, 'eeg_eval');
if isstr(g), error(g); end;
% warning pop up
% --------------
eeglab_options;
if strcmpi(g.warning, 'on')
if ~option_storedisk
res = questdlg2(strvcat( 'When processing multiple datasets, it is not', ...
'possible to enter new names for the newly created', ...
'datasets and old datasets are overwritten.', ...
'You may still cancel this operation though.'), ...
'Multiple dataset warning', 'Cancel', 'Proceed', 'Proceed');
else
res = questdlg2( [ 'Data files on disk will be automatically overwritten.' 10 ...
'Are you sure you want to proceed with this operation?' ], ...
'Confirmation', 'Cancel', 'Proceed', 'Proceed');
end;
switch lower(res),
case 'cancel', return;
case 'proceed',;
end;
end;
% execute function
% ----------------
v = version;
if str2num(v(1)) == '5' % Matlab 5
command = [ 'TMPEEG = ' funcname '( TMPEEG, ' vararg2str(g.params) ');' ];
else
eval( [ 'func = @' funcname ';' ] );
end;
NEWEEG = [];
for i = 1:length(EEG)
fprintf('Processing group dataset %d of %d named: %s ****************\n', i, length(EEG), EEG(i).setname);
TMPEEG = eeg_retrieve(EEG, i);
if v(1) == '5', eval(command); % Matlab 5
else TMPEEG = feval(func, TMPEEG, g.params{:}); % Matlab 6 and higher
end;
TMPEEG = eeg_checkset(TMPEEG);
TMPEEG.saved = 'no';
if option_storedisk
TMPEEG = pop_saveset(TMPEEG, 'savemode', 'resave');
TMPEEG = update_datafield(TMPEEG);
end;
NEWEEG = eeg_store(NEWEEG, TMPEEG, i);
if option_storedisk
NEWEEG(i).saved = 'yes'; % eeg_store by default set it to no
end;
end;
EEG = NEWEEG;
% history
% -------
if nargout > 1
com = sprintf('%s = %s( %s,%s);', funcname, inputname(2), funcname, inputname(2), vararg2str(g.params));
end;
function EEG = update_datafield(EEG);
if ~isfield(EEG, 'datfile'), EEG.datfile = ''; end;
if ~isempty(EEG.datfile)
EEG.data = EEG.datfile;
else
EEG.data = 'in set file';
end;
EEG.icaact = [];
|
github
|
lcnbeapp/beapp-master
|
eegh.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/eegh.m
| 4,073 |
utf_8
|
71f03408b617f0adfa6816bce5a1adbd
|
% eegh() - history function.
%
% Usage:
% >> eegh( arg );
% >> eegh( arg1, arg2 );
%
% Inputs:
% - With no argument, it return the command history.
% - arg is a string: with a string argument it pulls the command
% onto the stack.
% - arg is a number>0: execute the element in the stack at the
% required position.
% - arg is a number<0: unstack the required number of elements
% - arg is 0 : clear stack
% - arg1 is 'find' and arg2 is a string, try to find the closest command
% in the stack containing the string
% - arg1 is a string and arg2 is a structure, also add the history to
% the structure in filed 'history'.
%
% Global variables used:
% LASTCOM - last command
% ALLCOM - all the commands
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, 2001
%
% See also:
% eeglab() (a graphical interface for eeg plotting, space frequency
% decomposition, ICA, ... under Matlab for which this command
% was designed).
% Copyright (C) 2001 Arnaud Delorme, SCCN/INC/UCSD, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% To increase/decrease the maximum depth of the stack, edit the eeg_consts file
function str = eegh( command, str );
mode = 1; % mode = 1, full print, mode = 0, truncated print
global ALLCOM;
%if nargin == 2
% fprintf('2: %s\n', command);
%elseif nargin == 1
% fprintf('1: %s\n', command);
%end;
if nargin < 1
if isempty(ALLCOM)
fprintf('No history\n');
else
for index = 1:length(ALLCOM)
if mode == 0, txt = ALLCOM{ index }; fprintf('%d: ', index);
else txt = ALLCOM{ length(ALLCOM)-index+1 };
end;
if (length(txt) > 72) & (mode == 0)
fprintf('%s...\n', txt(1:70) );
else
fprintf('%s\n', txt );
end;
end;
end;
if nargout > 0
str = strvcat(ALLCOM);
end;
elseif nargin == 1
if isempty( command )
return;
end;
if isstr( command )
if ~isempty(ALLCOM) && isequal(ALLCOM{1}, command), return; end;
if isempty(ALLCOM)
ALLCOM = { command };
else
ALLCOM = { command ALLCOM{:}};
end;
global LASTCOM;
LASTCOM = command;
else
if command == 0
ALLCOM = [];
else if command < 0
ALLCOM = ALLCOM( -command+1:end ); % unstack elements
else
txt = ALLCOM{command};
if length(txt) > 72
fprintf('%s...\n', txt(1:70) );
else
fprintf('%s\n', txt );
end;
evalin( 'base', ALLCOM{command} ); % execute element
eegh( ALLCOM{command} ); % add to history
end;
end;
end;
else % nargin == 2
if ~isstruct(str)
if strcmp(command, 'find')
for index = 1:length(ALLCOM)
if ~isempty(findstr(ALLCOM{index}, str))
str = ALLCOM{index};
return;
end;
end;
str = [];
end;
else
% warning also some code present in eeg_store and pop_newset
if ~isempty(ALLCOM) && isequal(ALLCOM{1}, command), return; end;
eegh(command); % add to history
if ~isempty(command)
if length(str) == 1
str = eeg_hist(str, command);
else
for i = 1:length(str)
str(i) = eeg_hist(str(i), [ '% multiple datasets command: ' command ]);
end;
end;
end;
end;
end;
|
github
|
lcnbeapp/beapp-master
|
eeglabexefolder.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/eeglabexefolder.m
| 1,076 |
utf_8
|
bea2b2d54e501ccc2c6e113759384061
|
% eeglabexefolder - return the exe folder for EEGLAB. This function is only
% relevant for the compiled version of EEGLAB.
%
% Author: Arnaud Delorme, SCCN & CERCO, CNRS, 2008-
% Copyright (C) 15 Feb 2002 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function str = eeglabexefolder;
str = ctfroot;
inds = find(str == filesep);
str = str(1:inds(end)-1);
|
github
|
lcnbeapp/beapp-master
|
eeg_hist.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/eeg_hist.m
| 1,405 |
utf_8
|
5da5613eba9f720215dbf40a723b2008
|
% eeg_hist() - history for EEGLAB dataset.
%
% Usage:
% >> EEGOUT = eeg_hist( EEGIN, command );
%
% Inputs:
% EEGIN - input dataset
% command - [string] eeglab command
%
% Global variables used:
% EEGOUT - output dataset with updated history field
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, Dec 2003
%
% See also: eegh(), eeglab()
% Copyright (C) 2003 Arnaud Delorme, SCCN/INC/UCSD, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function EEG = eeg_hist( EEG, command );
if nargin < 2
help eeg_hist;
end;
if ~isfield(EEG, 'history')
EEG.history = '';
end;
if ~isempty(command)
try
EEG.history = [ EEG.history 10 command ];
catch
EEG.history = strvcat(EEG.history, command);
end;
end;
|
github
|
lcnbeapp/beapp-master
|
plugin_movepath.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/plugin_movepath.m
| 4,313 |
utf_8
|
3227a2fd281e8711ca0580850c1c0f20
|
%plugin_movepath()- Given a path to a plugin folder, this function will
% put the plugin at the bottom of the path.
%
% Usage:
% plugin_movepath('x','begin'); % Put plugin 'x' at the top of the path
% plugin_movepath('x','end'); % Put plugin 'x' at the bottom of the path
% plugin_movepath('x','begin','warns',1); % Put plugin 'x' at the top of the path and show warnings
%
% Inputs:
% foldername - [string] Plugin name or part of it
% pluginpos - {'begin','end'} Position to move the plugin in the path.
% To the top ('begin') or to the bottom ('end').
% Optional inputs:
% warns -[0,1] Allow isplay [1] or do not display [0] warnings.
% Warnings are restored at the end of the process. Default[0]
% Outputs:
% oldpath - Original MATLAB path before entering this function
% newpath - MATLAB path after being modified by this function
%
% Author: Ramon Martinez-Cancino and Arnaud Delorme, SCCN, 2016
%
% Copyright (C) 2016 Ramon Martinez-Cancino,INC, SCCN
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function[oldpath, newpath] = plugin_movepath(foldername,pluginpos, varargin)
oldpath = []; newpath = [];
try
options = varargin;
if ~isempty( varargin ),
for i = 1:2:numel(options)
g.(options{i}) = options{i+1};
end
else g = []; end;
catch
disp('plugin_movepath() error: calling convention {''key'', value, ... } error'); return;
end;
try g.warns; catch, g.warns = 0; end; % NO warnings by default
% Checking entries
if sum(strcmp(pluginpos,{'begin','end'})) ~= 1
fprintf(2,'plugin_movepath error: Invalid function argument\n');
return;
end
% Look in the plugin list for the plugin name provided
global PLUGINLIST
hitindx = find(~cellfun(@isempty,strfind(lower({PLUGINLIST.plugin}),lower(foldername))));
if isempty(hitindx)
fprintf(2,'plugin_movepath error: Unidentified plugin folder\n')
return;
else
eeglabfolder = fileparts(which('eeglab.m'));
pluginfolder = fullfile(eeglabfolder,'plugins',PLUGINLIST(hitindx).foldername );
end
% Backing up old path
if ismatlab
oldpath = matlabpath;
else
oldpath = path;
end;
% Retreiving path
comp = computer;
if strcmpi(comp(1:2), 'PC')
newpathtest = [ pluginfolder ';' ];
else
newpathtest = [ pluginfolder ':' ];
end;
ind = strfind(oldpath, newpathtest);
% Checking out if the work is already done
if strcmp(pluginpos,'begin') && ind == 1, return; end;
if strcmp(pluginpos,'end') && strcmp(oldpath(end-length(pluginfolder):end),pluginfolder), return; end;
% Shooting down warnings
if ~g.warns
tmpwarn = warning;
warning off;
end
% Remove folder and subfolders from path
rmpath(genpath(pluginfolder));
% Add folder to the path again in the requested position
if strcmp(pluginpos,'begin')
addpath(genpath(pluginfolder),'-begin');
fprintf(1,['EEGLAB warning: to avoid name conflict ' PLUGINLIST(hitindx).foldername ' functions relocated at the end of the path\n']);
elseif strcmp(pluginpos,'end')
addpath(genpath(pluginfolder),'-end');
fprintf(1,['EEGLAB warning: to avoid name conflict ' PLUGINLIST(hitindx).foldername ' functions relocated at the end of the path\n']);
end
% Restoring warnings
if ~g.warns
warning(tmpwarn);
end
newpath = path; % Retreiving new path
% required here because path not added yet
% to the admin folder
function res = ismatlab;
v = version;
if v(1) > '4'
res = 1;
else
res = 0;
end;
|
github
|
lcnbeapp/beapp-master
|
eeglab_error.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/eeglab_error.m
| 3,159 |
utf_8
|
52bd326118eafedfeaaa94a2741cbedc
|
% eeglab_error() - generate an eeglab error.
%
% Usage: >> eeglab_error;
%
% Inputs: none, simply capture the last error generated.
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2006-
%
% see also: eeglab()
% Copyright (C) 2006 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function eeglab_error
% handling errors
% ----------------
tmplasterr = lasterr;
[iseeglaberror tmplasterr header] = testeeglaberror(tmplasterr);
ft_error = false;
if iseeglaberror
tmp = lasterror; % Add more information to eeglab errors JRI, RMC
tmplasterr = sprintf('%s,\n\n (Error occurred in function %s() at line %d)',...
tmplasterr, tmp.stack(1).name, tmp.stack(1).line);
errordlg2(tmplasterr, header);
else
try
tmp = lasterror;
if length(tmp.stack(1).name) && all(tmp.stack(1).name(1:3) == 'ft_')
ft_error = true;
end;
tmperr = [ 'EEGLAB error in function ' tmp.stack(1).name '() at line ' int2str(tmp.stack(1).line) ':' 10 10 lasterr ];
catch % Matlab 5 and when the stack is empty
tmperr = [ 'EEGLAB error:' 10 10 tmplasterr ];
end;
if ~ft_error
tmperr = [ tmperr 10 10 'If you think this is a bug, please submit a detailed ' 10 ...
'description of how to reproduce the problem (and upload' 10 ...
'a small dataset) at http://sccn.ucsd.edu/eeglab/bugzilla' ];
else
tmperr = [ tmperr 10 10 'This is a problem with FIELDTRIP. The Fieldtrip version you downloaded' 10 ...
'is corrupted. Please manually replace Fieldtrip with an earlier version' 10 ...
'and/or email the Fieldtrip developpers so they can fix the issue.' ];
end;
errordlg2(tmperr, header);
end;
function [ val str header ] = testeeglaberror(str)
header = 'EEGLAB error';
val = 0;
try,
if strcmp(str(1:5), 'Error'),
val = 1;
str = str(12:end); %Corrected extraction of function name, occurs after 'Error using ' JRI, RMC
indendofline = find(str == 10);
funcname = str(1:indendofline(1)-1);
str = str(indendofline(1)+1:end);
header = [ funcname ' error' ];
end;
catch
end;
|
github
|
lcnbeapp/beapp-master
|
plugin_installstartup.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/adminfunc/plugin_installstartup.m
| 3,762 |
utf_8
|
37419d82594718647942d0ca8356c632
|
% plugin_installstartup() - install popular toolboxes when EEGLAB starts
%
% Usage:
% >> restartEeglabFlag = plugin_installstartup; % pop up window
%
% Outputs:
% restartEeglabFlag - [0|1] restart EEGLAB
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Oct. 29, 2013-
% Copyright (C) 2013 Arnaud Delorme, SCCN, INC, UCSD, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function restartEeglabFlag = plugin_installstartup
% { 'style' 'checkbox' 'string' 'Neuroelectromagnetic Forward Head Modeling Toolbox (NFT): Advanced source localization tools - beta (Zeynep Akalin Acar, 100 Mb)' 'value' 1 'enable' 'on' } ...
uilist = { { 'style' 'text' 'String' 'Download and install some popular third party EEGLAB plug-ins' 'fontweight', 'bold','tag', 'title'} ...
{ } ...
{ 'style' 'checkbox' 'string' 'Brain Vision Analyser data import plugin (40 Kb)' 'value' 1 'enable' 'on' } ...
{ 'style' 'checkbox' 'string' 'ANT data import plugin (800 Kb)' 'value' 1 'enable' 'on' } ...
{ 'style' 'checkbox' 'string' 'Measure Projection Toolbox (MPT) for ulti-subject ICA analysis (415 Mb)' 'value' 1 'enable' 'on' } ...
{ 'style' 'checkbox' 'string' 'Source Information Flow Toolbox (SIFT) for causal analysis of EEG sources (600 Mb)' 'value' 1 'enable' 'on' } ...
{ 'style' 'checkbox' 'string' 'BCILAB for real-time and offline BCI platform (200 Mb)' 'value' 1 'enable' 'on' } ...
{ 'style' 'checkbox' 'string' 'LIMO for linear analysis of MEEG data using single trials (2.5 Mb)' 'value' 1 'enable' 'on' } ...
{ } ...
{ 'style' 'radiobutton' 'string' 'Do not show this query again' 'value' 0 } ...
{} ...
{ 'style' 'text' 'String' 'Note: manage plug-in tools using EEGLAB menu item, "File > Plug-ins > Manage plug-ins"' } ...
{} ...
{ 'Style', 'pushbutton', 'string', 'Do not install now', 'tag' 'cancel' 'callback', 'set(gcbf, ''userdata'', ''cancel'');' } { } ...
{ 'Style', 'pushbutton', 'string', 'Install plugins now', 'tag', 'ok', 'callback', 'set(gcbf, ''userdata'', ''ok'');' } ...
};
geomline = [1];
geom = { [1] [1] geomline geomline geomline geomline geomline geomline [1] geomline [1] [1] [1] [1 1 1]};
geomvert = [ 1 0.5 1 1 1 1 1 1 0.3 1 0.3 1 1 1];
%result = inputgui( 'geometry', geom, 'uilist', uilist, 'helpcom', 'pophelp(''plugin_installstartup'')', 'title', 'Install popular plugins', 'geomvert', geomvert, 'eval', evalstr);
fig = figure('visible', 'off');
[tmp1 tmp2 handles] = supergui( 'geomhoriz', geom, 'uilist', uilist, 'title', 'Install popular plugins', 'geomvert', geomvert, 'fig', fig); %, 'eval', evalstr);
set(findobj(fig, 'tag', 'title'), 'fontsize', 16);
waitfor( fig, 'userdata');
% decode inputs
handles
results = cellfun(@(x)(get
get(handles, 'value')
|
github
|
lcnbeapp/beapp-master
|
topoplot.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/topoplot.m
| 70,628 |
utf_8
|
583a17ef238d3edc7ac2be5e6f200825
|
% topoplot() - plot a topographic map of a scalp data field in a 2-D circular view
% (looking down at the top of the head) using interpolation on a fine
% cartesian grid. Can also show specified channnel location(s), or return
% an interpolated value at an arbitrary scalp location (see 'noplot').
% By default, channel locations below head center (arc_length 0.5) are
% shown in a 'skirt' outside the cartoon head (see 'plotrad' and 'headrad'
% options below). Nose is at top of plot; left is left; right is right.
% Using option 'plotgrid', the plot may be one or more rectangular grids.
% Usage:
% >> topoplot(datavector, EEG.chanlocs); % plot a map using an EEG chanlocs structure
% >> topoplot(datavector, 'my_chan.locs'); % read a channel locations file and plot a map
% >> topoplot('example'); % give an example of an electrode location file
% >> [h grid_or_val plotrad_or_grid, xmesh, ymesh]= ...
% topoplot(datavector, chan_locs, 'Input1','Value1', ...);
% Required Inputs:
% datavector - single vector of channel values. Else, if a vector of selected subset
% (int) channel numbers -> mark their location(s) using 'style' 'blank'.
% chan_locs - name of an EEG electrode position file (>> topoplot example).
% Else, an EEG.chanlocs structure (>> help readlocs or >> topoplot example)
% Optional inputs:
% 'maplimits' - 'absmax' -> scale map colors to +/- the absolute-max (makes green 0);
% 'maxmin' -> scale colors to the data range (makes green mid-range);
% [lo.hi] -> use user-definined lo/hi limits
% {default: 'absmax'}
% 'style' - 'map' -> plot colored map only
% 'contour' -> plot contour lines only
% 'both' -> plot both colored map and contour lines
% 'fill' -> plot constant color between contour lines
% 'blank' -> plot electrode locations only {default: 'both'}
% 'electrodes' - 'on','off','labels','numbers','ptslabels','ptsnumbers'. To set the 'pts'
% marker,,see 'Plot detail options' below. {default: 'on' -> mark electrode
% locations with points ('.') unless more than 64 channels, then 'off'}.
% 'plotchans' - [vector] channel numbers (indices) to use in making the head plot.
% {default: [] -> plot all chans}
% 'chantype' - cell array of channel type(s) to plot. Will also accept a single quoted
% string type. Channel type for channel k is field EEG.chanlocs(k).type.
% If present, overrides 'plotchans' and also 'chaninfo' with field
% 'chantype'. Ex. 'EEG' or {'EEG','EOG'} {default: all, or 'plotchans' arg}
% 'plotgrid' - [channels] Plot channel data in one or more rectangular grids, as
% specified by [channels], a position matrix of channel numbers defining
% the topographic locations of the channels in the grid. Zero values are
% given the figure background color; negative integers, the color of the
% polarity-reversed channel values. Ex: >> figure; ...
% >> topoplot(values,'chanlocs','plotgrid',[11 12 0; 13 14 15]);
% % Plot a (2,3) grid of data values from channels 11-15 with one empty
% grid cell (top right) {default: no grid plot}
% 'nosedir' - ['+X'|'-X'|'+Y'|'-Y'] direction of nose {default: '+X'}
% 'chaninfo' - [struct] optional structure containing fields 'nosedir', 'plotrad'
% and/or 'chantype'. See these (separate) field definitions above, below.
% {default: nosedir +X, plotrad 0.5, all channels}
% 'plotrad' - [0.15<=float<=1.0] plotting radius = max channel arc_length to plot.
% See >> topoplot example. If plotrad > 0.5, chans with arc_length > 0.5
% (i.e. below ears-eyes) are plotted in a circular 'skirt' outside the
% cartoon head. See 'intrad' below. {default: max(max(chanlocs.radius),0.5);
% If the chanlocs structure includes a field chanlocs.plotrad, its value
% is used by default}.
% 'headrad' - [0.15<=float<=1.0] drawing radius (arc_length) for the cartoon head.
% NOTE: Only headrad = 0.5 is anatomically correct! 0 -> don't draw head;
% 'rim' -> show cartoon head at outer edge of the plot {default: 0.5}
% 'intrad' - [0.15<=float<=1.0] radius of the scalp map interpolation area (square or
% disk, see 'intsquare' below). Interpolate electrodes in this area and use
% this limit to define boundaries of the scalp map interpolated data matrix
% {default: max channel location radius}
% 'intsquare' - ['on'|'off'] 'on' -> Interpolate values at electrodes located in the whole
% square containing the (radius intrad) interpolation disk; 'off' -> Interpolate
% values from electrodes shown in the interpolation disk only {default: 'on'}.
% 'conv' - ['on'|'off'] Show map interpolation only out to the convext hull of
% the electrode locations to minimize extrapolation. Use this option ['on'] when
% plotting pvalues {default: 'off'}
% 'noplot' - ['on'|'off'|[rad theta]] do not plot (but return interpolated data).
% Else, if [rad theta] are coordinates of a (possibly missing) channel,
% returns interpolated value for channel location. For more info,
% see >> topoplot 'example' {default: 'off'}
% 'verbose' - ['on'|'off'] comment on operations on command line {default: 'on'}.
%
% Plot detail options:
% 'drawaxis' - ['on'|'off'] draw axis on the top left corner.
% 'emarker' - Matlab marker char | {markerchar color size linewidth} char, else cell array
% specifying the electrode 'pts' marker. Ex: {'s','r',32,1} -> 32-point solid
% red square. {default: {'.','k',[],1} where marker size ([]) depends on the number
% of channels plotted}.
% 'emarker2' - {markchans}|{markchans marker color size linewidth} cell array specifying
% an alternate marker for specified 'plotchans'. Ex: {[3 17],'s','g'}
% {default: none, or if {markchans} only are specified, then {markchans,'o','r',10,1}}
% 'hcolor' - color of the cartoon head. Use 'hcolor','none' to plot no head. {default: 'k' = black}
% 'shading' - 'flat','interp' {default: 'flat'}
% 'numcontour' - number of contour lines {default: 6}
% 'contourvals' - values for contour {default: same as input values}
% 'pmask' - values for masking topoplot. Array of zeros and 1 of the same size as the input
% value array {default: []}
% 'color' - color of the contours {default: dark grey}
% 'whitebk ' - ('on'|'off') make the background color white (e.g., to print empty plotgrid channels)
% {default: 'off'}
% 'gridscale' - [int > 32] size (nrows) of interpolated scalp map data matrix {default: 67}
% 'colormap' - (n,3) any size colormap {default: existing colormap}
% 'circgrid' - [int > 100] number of elements (angles) in head and border circles {201}
% 'emarkercolor' - cell array of colors for 'blank' option.
% 'plotdisk' - ['on'|'off'] plot disk instead of dots for electrodefor 'blank' option. Size of disk
% is controled by input values at each electrode. If an imaginary value is provided,
% plot partial circle with red for the real value and blue for the imaginary one.
%
% Dipole plotting options:
% 'dipole' - [xi yi xe ye ze] plot dipole on the top of the scalp map
% from coordinate (xi,yi) to coordinates (xe,ye,ze) (dipole head
% model has radius 1). If several rows, plot one dipole per row.
% Coordinates returned by dipplot() may be used. Can accept
% an EEG.dipfit.model structure (See >> help dipplot).
% Ex: ,'dipole',EEG.dipfit.model(17) % Plot dipole(s) for comp. 17.
% 'dipnorm' - ['on'|'off'] normalize dipole length {default: 'on'}.
% 'diporient' - [-1|1] invert dipole orientation {default: 1}.
% 'diplen' - [real] scale dipole length {default: 1}.
% 'dipscale' - [real] scale dipole size {default: 1}.
% 'dipsphere' - [real] size of the dipole sphere. {default: 85 mm}.
% 'dipcolor' - [color] dipole color as Matlab code code or [r g b] vector
% {default: 'k' = black}.
% Outputs:
% handle - handle of the colored surface.If
% contour only is plotted, then is the handle of
% the countourgroup. (If no surface or contour is plotted,
% return "gca", the handle of the current plot)
% grid_or_val - [matrix] the interpolated data image (with off-head points = NaN).
% Else, single interpolated value at the specified 'noplot' arg channel
% location ([rad theta]), if any.
% plotrad_or_grid - IF grid image returned above, then the 'plotrad' radius of the grid.
% Else, the grid image
% xmesh, ymesh - x and y values of the returned grid (above)
%
% Chan_locs format:
% See >> topoplot 'example'
%
% Examples:
%
% To plot channel locations only:
% >> figure; topoplot([],EEG.chanlocs,'style','blank','electrodes','labelpoint','chaninfo',EEG.chaninfo);
%
% Notes: - To change the plot map masking ring to a new figure background color,
% >> set(findobj(gca,'type','patch'),'facecolor',get(gcf,'color'))
% - Topoplots may be rotated. From the commandline >> view([deg 90]) {default: [0 90])
% - When plotting pvalues make sure to use the option 'conv' to minimize extrapolation effects
%
% Authors: Andy Spydell, Colin Humphries, Arnaud Delorme & Scott Makeig
% CNL / Salk Institute, 8/1996-/10/2001; SCCN/INC/UCSD, Nov. 2001 -
%
% See also: timtopo(), envtopo()
% Deprecated options:
% 'shrink' - ['on'|'off'|'force'|factor] Deprecated. 'on' -> If max channel arc_length
% > 0.5, shrink electrode coordinates towards vertex to plot all channels
% by making max arc_length 0.5. 'force' -> Normalize arc_length
% so the channel max is 0.5. factor -> Apply a specified shrink
% factor (range (0,1) = shrink fraction). {default: 'off'}
% 'electcolor' {'k'} ... electrode marking details and their {defaults}.
% 'emarker' {'.'}|'emarkersize' {14}|'emarkersizemark' {40}|'efontsize' {var} -
% electrode marking details and their {defaults}.
% 'ecolor' - color of the electrode markers {default: 'k' = black}
% 'interplimits' - ['electrodes'|'head'] 'electrodes'-> interpolate the electrode grid;
% 'head'-> interpolate the whole disk {default: 'head'}.
% Unimplemented future options:
% Copyright (C) Colin Humphries & Scott Makeig, CNL / Salk Institute, Aug, 1996
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% Topoplot Version 2.1
% Early development history:
% Begun by Andy Spydell and Scott Makeig, NHRC, 7-23-96
% 8-96 Revised by Colin Humphries, CNL / Salk Institute, La Jolla CA
% -changed surf command to imagesc (faster)
% -can now handle arbitrary scaling of electrode distances
% -can now handle non integer angles in chan_locs
% 4-4-97 Revised again by Colin Humphries, reformatted by SM
% -added parameters
% -changed chan_locs format
% 2-26-98 Revised by Colin
% -changed image back to surface command
% -added fill and blank styles
% -removed extra background colormap entry (now use any colormap)
% -added parameters for electrode colors and labels
% -now each topoplot axes use the caxis command again.
% -removed OUTPUT parameter
% 3-11-98 changed default emarkersize, improve help msg -sm
% 5-24-01 made default emarkersize vary with number of channels -sm
% 01-25-02 reformated help & license, added link -ad
% 03-15-02 added readlocs and the use of eloc input structure -ad
% 03-25-02 added 'labelpoint' options and allow Values=[] -ad &sm
% 03-25-02 added details to "Unknown parameter" warning -sm & ad
function [handle,Zi,grid,Xi,Yi] = topoplot(Values,loc_file,varargin)
%
%%%%%%%%%%%%%%%%%%%%%%%% Set defaults %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
icadefs % read defaults MAXTOPOPLOTCHANS and DEFAULT_ELOC and BACKCOLOR
if ~exist('BACKCOLOR') % if icadefs.m does not define BACKCOLOR
BACKCOLOR = [.93 .96 1]; % EEGLAB standard
end
whitebk = 'off'; % by default, make gridplot background color = EEGLAB screen background color
persistent warningInterp;
plotgrid = 'off';
plotchans = [];
noplot = 'off';
handle = [];
Zi = [];
chanval = NaN;
rmax = 0.5; % actual head radius - Don't change this!
INTERPLIMITS = 'head'; % head, electrodes
INTSQUARE = 'on'; % default, interpolate electrodes located though the whole square containing
% the plotting disk
default_intrad = 1; % indicator for (no) specified intrad
MAPLIMITS = 'absmax'; % absmax, maxmin, [values]
GRID_SCALE = 67; % plot map on a 67X67 grid
CIRCGRID = 201; % number of angles to use in drawing circles
AXHEADFAC = 1.3; % head to axes scaling factor
CONTOURNUM = 6; % number of contour levels to plot
STYLE = 'both'; % default 'style': both,straight,fill,contour,blank
HEADCOLOR = [0 0 0]; % default head color (black)
CCOLOR = [0.2 0.2 0.2]; % default contour color
ELECTRODES = []; % default 'electrodes': on|off|label - set below
MAXDEFAULTSHOWLOCS = 64;% if more channels than this, don't show electrode locations by default
EMARKER = '.'; % mark electrode locations with small disks
ECOLOR = [0 0 0]; % default electrode color = black
EMARKERSIZE = []; % default depends on number of electrodes, set in code
EMARKERLINEWIDTH = 1; % default edge linewidth for emarkers
EMARKERSIZE1CHAN = 20; % default selected channel location marker size
EMARKERCOLOR1CHAN = 'red'; % selected channel location marker color
EMARKER2CHANS = []; % mark subset of electrode locations with small disks
EMARKER2 = 'o'; % mark subset of electrode locations with small disks
EMARKER2COLOR = 'r'; % mark subset of electrode locations with small disks
EMARKERSIZE2 = 10; % default selected channel location marker size
EMARKER2LINEWIDTH = 1;
EFSIZE = get(0,'DefaultAxesFontSize'); % use current default fontsize for electrode labels
HLINEWIDTH = 2; % default linewidth for head, nose, ears
BLANKINGRINGWIDTH = .035;% width of the blanking ring
HEADRINGWIDTH = .007;% width of the cartoon head ring
SHADING = 'flat'; % default 'shading': flat|interp
shrinkfactor = []; % shrink mode (dprecated)
intrad = []; % default interpolation square is to outermost electrode (<=1.0)
plotrad = []; % plotting radius ([] = auto, based on outermost channel location)
headrad = []; % default plotting radius for cartoon head is 0.5
squeezefac = 1.0;
MINPLOTRAD = 0.15; % can't make a topoplot with smaller plotrad (contours fail)
VERBOSE = 'off';
MASKSURF = 'off';
CONVHULL = 'off'; % dont mask outside the electrodes convex hull
DRAWAXIS = 'off';
PLOTDISK = 'off';
CHOOSECHANTYPE = 0;
ContourVals = Values;
PMASKFLAG = 0;
COLORARRAY = { [1 0 0] [0.5 0 0] [0 0 0] };
%COLORARRAY2 = { [1 0 0] [0.5 0 0] [0 0 0] };
gb = [0 0];
COLORARRAY2 = { [gb 0] [gb 1/4] [gb 2/4] [gb 3/4] [gb 1] };
%%%%%% Dipole defaults %%%%%%%%%%%%
DIPOLE = [];
DIPNORM = 'on';
DIPSPHERE = 85;
DIPLEN = 1;
DIPSCALE = 1;
DIPORIENT = 1;
DIPCOLOR = [0 0 0];
NOSEDIR = '+X';
CHANINFO = [];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%%%%%%%%%%%%%%%%%%%%%%% Handle arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if nargin< 1
help topoplot;
return
end
% calling topoplot from Fieldtrip
% -------------------------------
fieldtrip = 0;
if nargin < 2, loc_file = []; end;
if isstruct(Values) | ~isstruct(loc_file), fieldtrip == 1; end;
if isstr(loc_file), if exist(loc_file) ~= 2, fieldtrip == 1; end; end;
if fieldtrip
error('Wrong calling format, are you trying to use the topoplot Fieldtrip function?');
end;
nargs = nargin;
if nargs == 1
if isstr(Values)
if any(strcmp(lower(Values),{'example','demo'}))
fprintf(['This is an example of an electrode location file,\n',...
'an ascii file consisting of the following four columns:\n',...
' channel_number degrees arc_length channel_name\n\n',...
'Example:\n',...
' 1 -18 .352 Fp1 \n',...
' 2 18 .352 Fp2 \n',...
' 5 -90 .181 C3 \n',...
' 6 90 .181 C4 \n',...
' 7 -90 .500 A1 \n',...
' 8 90 .500 A2 \n',...
' 9 -142 .231 P3 \n',...
'10 142 .231 P4 \n',...
'11 0 .181 Fz \n',...
'12 0 0 Cz \n',...
'13 180 .181 Pz \n\n',...
...
'In topoplot() coordinates, 0 deg. points to the nose, positive\n',...
'angles point to the right hemisphere, and negative to the left.\n',...
'The model head sphere has a circumference of 2; the vertex\n',...
'(Cz) has arc_length 0. Locations with arc_length > 0.5 are below\n',...
'head center and are plotted outside the head cartoon.\n',...
'Option plotrad controls how much of this lower-head "skirt" is shown.\n',...
'Option headrad controls if and where the cartoon head will be drawn.\n',...
'Option intrad controls how many channels will be included in the interpolation.\n',...
])
return
end
end
end
if nargs < 2
loc_file = DEFAULT_ELOC;
if ~exist(loc_file)
fprintf('default locations file "%s" not found - specify chan_locs in topoplot() call.\n',loc_file)
error(' ')
end
end
if isempty(loc_file)
loc_file = 0;
end
if isnumeric(loc_file) & loc_file == 0
loc_file = DEFAULT_ELOC;
end
if nargs > 2
if ~(round(nargs/2) == nargs/2)
error('Odd number of input arguments??')
end
for i = 1:2:length(varargin)
Param = varargin{i};
Value = varargin{i+1};
if ~isstr(Param)
error('Flag arguments must be strings')
end
Param = lower(Param);
switch Param
case 'conv'
CONVHULL = lower(Value);
if ~strcmp(CONVHULL,'on') & ~strcmp(CONVHULL,'off')
error('Value of ''conv'' must be ''on'' or ''off''.');
end
case 'colormap'
if size(Value,2)~=3
error('Colormap must be a n x 3 matrix')
end
colormap(Value)
case 'plotdisk'
PLOTDISK = lower(Value);
if ~strcmp(PLOTDISK,'on') & ~strcmp(PLOTDISK,'off')
error('Value of ''plotdisk'' must be ''on'' or ''off''.');
end
case 'intsquare'
INTSQUARE = lower(Value);
if ~strcmp(INTSQUARE,'on') & ~strcmp(INTSQUARE,'off')
error('Value of ''intsquare'' must be ''on'' or ''off''.');
end
case 'emarkercolors'
COLORARRAY = Value;
case {'interplimits','headlimits'}
if ~isstr(Value)
error('''interplimits'' value must be a string')
end
Value = lower(Value);
if ~strcmp(Value,'electrodes') & ~strcmp(Value,'head')
error('Incorrect value for interplimits')
end
INTERPLIMITS = Value;
case 'verbose'
VERBOSE = Value;
case 'nosedir'
NOSEDIR = Value;
if isempty(strmatch(lower(NOSEDIR), { '+x', '-x', '+y', '-y' }))
error('Invalid nose direction');
end;
case 'chaninfo'
CHANINFO = Value;
if isfield(CHANINFO, 'nosedir'), NOSEDIR = CHANINFO.nosedir; end;
if isfield(CHANINFO, 'shrink' ), shrinkfactor = CHANINFO.shrink; end;
if isfield(CHANINFO, 'plotrad') & isempty(plotrad), plotrad = CHANINFO.plotrad; end;
if isfield(CHANINFO, 'chantype')
chantype = CHANINFO.chantype;
if ischar(chantype), chantype = cellstr(chantype); end
CHOOSECHANTYPE = 1;
end
case 'chantype'
chantype = Value;
CHOOSECHANTYPE = 1;
if ischar(chantype), chantype = cellstr(chantype); end
if ~iscell(chantype), error('chantype must be cell array. e.g. {''EEG'', ''EOG''}'); end
case 'drawaxis'
DRAWAXIS = Value;
case 'maplimits'
MAPLIMITS = Value;
case 'masksurf'
MASKSURF = Value;
case 'circgrid'
CIRCGRID = Value;
if isstr(CIRCGRID) | CIRCGRID<100
error('''circgrid'' value must be an int > 100');
end
case 'style'
STYLE = lower(Value);
case 'numcontour'
CONTOURNUM = Value;
case 'electrodes'
ELECTRODES = lower(Value);
if strcmpi(ELECTRODES,'pointlabels') | strcmpi(ELECTRODES,'ptslabels') ...
| strcmpi(ELECTRODES,'labelspts') | strcmpi(ELECTRODES,'ptlabels') ...
| strcmpi(ELECTRODES,'labelpts')
ELECTRODES = 'labelpoint'; % backwards compatability
elseif strcmpi(ELECTRODES,'pointnumbers') | strcmpi(ELECTRODES,'ptsnumbers') ...
| strcmpi(ELECTRODES,'numberspts') | strcmpi(ELECTRODES,'ptnumbers') ...
| strcmpi(ELECTRODES,'numberpts') | strcmpi(ELECTRODES,'ptsnums') ...
| strcmpi(ELECTRODES,'numspts')
ELECTRODES = 'numpoint'; % backwards compatability
elseif strcmpi(ELECTRODES,'nums')
ELECTRODES = 'numbers'; % backwards compatability
elseif strcmpi(ELECTRODES,'pts')
ELECTRODES = 'on'; % backwards compatability
elseif ~strcmp(ELECTRODES,'off') ...
& ~strcmpi(ELECTRODES,'on') ...
& ~strcmp(ELECTRODES,'labels') ...
& ~strcmpi(ELECTRODES,'numbers') ...
& ~strcmpi(ELECTRODES,'labelpoint') ...
& ~strcmpi(ELECTRODES,'numpoint')
error('Unknown value for keyword ''electrodes''');
end
case 'dipole'
DIPOLE = Value;
case 'dipsphere'
DIPSPHERE = Value;
case 'dipnorm'
DIPNORM = Value;
case 'diplen'
DIPLEN = Value;
case 'dipscale'
DIPSCALE = Value;
case 'contourvals'
ContourVals = Value;
case 'pmask'
ContourVals = Value;
PMASKFLAG = 1;
case 'diporient'
DIPORIENT = Value;
case 'dipcolor'
DIPCOLOR = Value;
case 'emarker'
if ischar(Value)
EMARKER = Value;
elseif ~iscell(Value) | length(Value) > 4
error('''emarker'' argument must be a cell array {marker color size linewidth}')
else
EMARKER = Value{1};
end
if length(Value) > 1
ECOLOR = Value{2};
end
if length(Value) > 2
EMARKERSIZE = Value{3};
end
if length(Value) > 3
EMARKERLINEWIDTH = Value{4};
end
case 'emarker2'
if ~iscell(Value) | length(Value) > 5
error('''emarker2'' argument must be a cell array {chans marker color size linewidth}')
end
EMARKER2CHANS = abs(Value{1}); % ignore channels < 0
if length(Value) > 1
EMARKER2 = Value{2};
end
if length(Value) > 2
EMARKER2COLOR = Value{3};
end
if length(Value) > 3
EMARKERSIZE2 = Value{4};
end
if length(Value) > 4
EMARKER2LINEWIDTH = Value{5};
end
case 'shrink'
shrinkfactor = Value;
case 'intrad'
intrad = Value;
if isstr(intrad) | (intrad < MINPLOTRAD | intrad > 1)
error('intrad argument should be a number between 0.15 and 1.0');
end
case 'plotrad'
plotrad = Value;
if isstr(plotrad) | (plotrad < MINPLOTRAD | plotrad > 1)
error('plotrad argument should be a number between 0.15 and 1.0');
end
case 'headrad'
headrad = Value;
if isstr(headrad) & ( strcmpi(headrad,'off') | strcmpi(headrad,'none') )
headrad = 0; % undocumented 'no head' alternatives
end
if isempty(headrad) % [] -> none also
headrad = 0;
end
if ~isstr(headrad)
if ~(headrad==0) & (headrad < MINPLOTRAD | headrad>1)
error('bad value for headrad');
end
elseif ~strcmpi(headrad,'rim')
error('bad value for headrad');
end
case {'headcolor','hcolor'}
HEADCOLOR = Value;
case {'contourcolor','ccolor'}
CCOLOR = Value;
case {'electcolor','ecolor'}
ECOLOR = Value;
case {'emarkersize','emsize'}
EMARKERSIZE = Value;
case {'emarkersize1chan','emarkersizemark'}
EMARKERSIZE1CHAN= Value;
case {'efontsize','efsize'}
EFSIZE = Value;
case 'shading'
SHADING = lower(Value);
if ~any(strcmp(SHADING,{'flat','interp'}))
error('Invalid shading parameter')
end
if strcmpi(SHADING,'interp') && isempty(warningInterp)
warning('Using interpolated shading in scalp topographies prevent to export them as vectorized figures');
warningInterp = 1;
end;
case 'noplot'
noplot = Value;
if ~isstr(noplot)
if length(noplot) ~= 2
error('''noplot'' location should be [radius, angle]')
else
chanrad = noplot(1);
chantheta = noplot(2);
noplot = 'on';
end
end
case 'gridscale'
GRID_SCALE = Value;
if isstr(GRID_SCALE) | GRID_SCALE ~= round(GRID_SCALE) | GRID_SCALE < 32
error('''gridscale'' value must be integer > 32.');
end
case {'plotgrid','gridplot'}
plotgrid = 'on';
gridchans = Value;
case 'plotchans'
plotchans = Value(:);
if find(plotchans<=0)
error('''plotchans'' values must be > 0');
end
% if max(abs(plotchans))>max(Values) | max(abs(plotchans))>length(Values) -sm ???
case {'whitebk','whiteback','forprint'}
whitebk = Value;
otherwise
error(['Unknown input parameter ''' Param ''' ???'])
end
end
end
if strcmpi(whitebk, 'on')
BACKCOLOR = [ 1 1 1 ];
end;
if isempty(find(strcmp(varargin,'colormap')))
cmap = colormap(DEFAULT_COLORMAP);
else
cmap = colormap;
end
cmaplen = size(cmap,1);
if strcmp(STYLE,'blank') % else if Values holds numbers of channels to mark
if length(Values) < length(loc_file)
ContourVals = zeros(1,length(loc_file));
ContourVals(Values) = 1;
Values = ContourVals;
end;
end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%% test args for plotting an electrode grid %%%%%%%%%%%%%%%%%%%%%%
%
if strcmp(plotgrid,'on')
STYLE = 'grid';
gchans = sort(find(abs(gridchans(:))>0));
% if setdiff(gchans,unique(gchans))
% fprintf('topoplot() warning: ''plotgrid'' channel matrix has duplicate channels\n');
% end
if ~isempty(plotchans)
if intersect(gchans,abs(plotchans))
fprintf('topoplot() warning: ''plotgrid'' and ''plotchans'' have channels in common\n');
end
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%% misc arg tests %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isempty(ELECTRODES) % if electrode labeling not specified
if length(Values) > MAXDEFAULTSHOWLOCS % if more channels than default max
ELECTRODES = 'off'; % don't show electrodes
else % else if fewer chans,
ELECTRODES = 'on'; % do
end
end
if isempty(Values)
STYLE = 'blank';
end
[r,c] = size(Values);
if r>1 & c>1,
error('input data must be a single vector');
end
Values = Values(:); % make Values a column vector
ContourVals = ContourVals(:); % values for contour
if ~isempty(intrad) & ~isempty(plotrad) & intrad < plotrad
error('intrad must be >= plotrad');
end
if ~strcmpi(STYLE,'grid') % if not plot grid only
%
%%%%%%%%%%%%%%%%%%%% Read the channel location information %%%%%%%%%%%%%%%%%%%%%%%%
%
if isstr(loc_file)
[tmpeloc labels Th Rd indices] = readlocs( loc_file);
elseif isstruct(loc_file) % a locs struct
[tmpeloc labels Th Rd indices] = readlocs( loc_file );
% Note: Th and Rd correspond to indices channels-with-coordinates only
else
error('loc_file must be a EEG.locs struct or locs filename');
end
Th = pi/180*Th; % convert degrees to radians
allchansind = 1:length(Th);
if ~isempty(plotchans)
if max(plotchans) > length(Th)
error('''plotchans'' values must be <= max channel index');
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% channels to plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(plotchans)
plotchans = intersect_bc(plotchans, indices);
end;
if ~isempty(Values) & ~strcmpi( STYLE, 'blank') & isempty(plotchans)
plotchans = indices;
end
if isempty(plotchans) & strcmpi( STYLE, 'blank')
plotchans = indices;
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%% filter for channel type(s), if specified %%%%%%%%%%%%%%%%%%%%%
%
if CHOOSECHANTYPE,
newplotchans = eeg_chantype(loc_file,chantype);
plotchans = intersect_bc(newplotchans, plotchans);
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%% filter channels used for components %%%%%%%%%%%%%%%%%%%%%
%
if isfield(CHANINFO, 'icachansind') & ~isempty(Values) & length(Values) ~= length(tmpeloc)
% test if ICA component
% ---------------------
if length(CHANINFO.icachansind) == length(Values)
% if only a subset of channels are to be plotted
% and ICA components also use a subject of channel
% we must find the new indices for these channels
plotchans = intersect_bc(CHANINFO.icachansind, plotchans);
tmpvals = zeros(1, length(tmpeloc));
tmpvals(CHANINFO.icachansind) = Values;
Values = tmpvals;
tmpvals = zeros(1, length(tmpeloc));
tmpvals(CHANINFO.icachansind) = ContourVals;
ContourVals = tmpvals;
end;
end;
%
%%%%%%%%%%%%%%%%%%% last channel is reference? %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if length(tmpeloc) == length(Values) + 1 % remove last channel if necessary
% (common reference channel)
if plotchans(end) == length(tmpeloc)
plotchans(end) = [];
end;
end;
%
%%%%%%%%%%%%%%%%%%% remove infinite and NaN values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if length(Values) > 1
inds = union_bc(find(isnan(Values)), find(isinf(Values))); % NaN and Inf values
plotchans = setdiff_bc(plotchans, inds);
end;
if strcmp(plotgrid,'on')
plotchans = setxor(plotchans,gchans); % remove grid chans from head plotchans
end
[x,y] = pol2cart(Th,Rd); % transform electrode locations from polar to cartesian coordinates
plotchans = abs(plotchans); % reverse indicated channel polarities
allchansind = allchansind(plotchans);
Th = Th(plotchans);
Rd = Rd(plotchans);
x = x(plotchans);
y = y(plotchans);
labels = labels(plotchans); % remove labels for electrodes without locations
labels = strvcat(labels); % make a label string matrix
if ~isempty(Values) & length(Values) > 1
Values = Values(plotchans);
ContourVals = ContourVals(plotchans);
end;
%
%%%%%%%%%%%%%%%%%% Read plotting radius from chanlocs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isempty(plotrad) & isfield(tmpeloc, 'plotrad'),
plotrad = tmpeloc(1).plotrad;
if isstr(plotrad) % plotrad shouldn't be a string
plotrad = str2num(plotrad) % just checking
end
if plotrad < MINPLOTRAD | plotrad > 1.0
fprintf('Bad value (%g) for plotrad.\n',plotrad);
error(' ');
end
if strcmpi(VERBOSE,'on') & ~isempty(plotrad)
fprintf('Plotting radius plotrad (%g) set from EEG.chanlocs.\n',plotrad);
end
end;
if isempty(plotrad)
plotrad = min(1.0,max(Rd)*1.02); % default: just outside the outermost electrode location
plotrad = max(plotrad,0.5); % default: plot out to the 0.5 head boundary
end % don't plot channels with Rd > 1 (below head)
if isempty(intrad)
default_intrad = 1; % indicator for (no) specified intrad
intrad = min(1.0,max(Rd)*1.02); % default: just outside the outermost electrode location
else
default_intrad = 0; % indicator for (no) specified intrad
if plotrad > intrad
plotrad = intrad;
end
end % don't interpolate channels with Rd > 1 (below head)
if isstr(plotrad) | plotrad < MINPLOTRAD | plotrad > 1.0
error('plotrad must be between 0.15 and 1.0');
end
%
%%%%%%%%%%%%%%%%%%%%%%% Set radius of head cartoon %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isempty(headrad) % never set -> defaults
if plotrad >= rmax
headrad = rmax; % (anatomically correct)
else % if plotrad < rmax
headrad = 0; % don't plot head
if strcmpi(VERBOSE, 'on')
fprintf('topoplot(): not plotting cartoon head since plotrad (%5.4g) < 0.5\n',...
plotrad);
end
end
elseif strcmpi(headrad,'rim') % force plotting at rim of map
headrad = plotrad;
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Shrink mode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(shrinkfactor) | isfield(tmpeloc, 'shrink'),
if isempty(shrinkfactor) & isfield(tmpeloc, 'shrink'),
shrinkfactor = tmpeloc(1).shrink;
if strcmpi(VERBOSE,'on')
if isstr(shrinkfactor)
fprintf('Automatically shrinking coordinates to lie above the head perimter.\n');
else
fprintf('Automatically shrinking coordinates by %3.2f\n', shrinkfactor);
end;
end
end;
if isstr(shrinkfactor)
if strcmpi(shrinkfactor, 'on') | strcmpi(shrinkfactor, 'force') | strcmpi(shrinkfactor, 'auto')
if abs(headrad-rmax) > 1e-2
fprintf(' NOTE -> the head cartoon will NOT accurately indicate the actual electrode locations\n');
end
if strcmpi(VERBOSE,'on')
fprintf(' Shrink flag -> plotting cartoon head at plotrad\n');
end
headrad = plotrad; % plot head around outer electrodes, no matter if 0.5 or not
end
else % apply shrinkfactor
plotrad = rmax/(1-shrinkfactor);
headrad = plotrad; % make deprecated 'shrink' mode plot
if strcmpi(VERBOSE,'on')
fprintf(' %g%% shrink applied.');
if abs(headrad-rmax) > 1e-2
fprintf(' Warning: With this "shrink" setting, the cartoon head will NOT be anatomically correct.\n');
else
fprintf('\n');
end
end
end
end; % if shrink
%
%%%%%%%%%%%%%%%%% Issue warning if headrad ~= rmax %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if headrad ~= 0.5 & strcmpi(VERBOSE, 'on')
fprintf(' NB: Plotting map using ''plotrad'' %-4.3g,',plotrad);
fprintf( ' ''headrad'' %-4.3g\n',headrad);
fprintf('Warning: The plotting radius of the cartoon head is NOT anatomically correct (0.5).\n')
end
%
%%%%%%%%%%%%%%%%%%%%% Find plotting channels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
pltchans = find(Rd <= plotrad); % plot channels inside plotting circle
if strcmpi(INTSQUARE,'on') % interpolate channels in the radius intrad square
intchans = find(x <= intrad & y <= intrad); % interpolate and plot channels inside interpolation square
else
intchans = find(Rd <= intrad); % interpolate channels in the radius intrad circle only
end
%
%%%%%%%%%%%%%%%%%%%%% Eliminate channels not plotted %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
allx = x;
ally = y;
intchans; % interpolate using only the 'intchans' channels
pltchans; % plot using only indicated 'plotchans' channels
if length(pltchans) < length(Rd) & strcmpi(VERBOSE, 'on')
fprintf('Interpolating %d and plotting %d of the %d scalp electrodes.\n', ...
length(intchans),length(pltchans),length(Rd));
end;
% fprintf('topoplot(): plotting %d channels\n',length(pltchans));
if ~isempty(EMARKER2CHANS)
if strcmpi(STYLE,'blank')
error('emarker2 not defined for style ''blank'' - use marking channel numbers in place of data');
else % mark1chans and mark2chans are subsets of pltchans for markers 1 and 2
[tmp1 mark1chans tmp2] = setxor(pltchans,EMARKER2CHANS);
[tmp3 tmp4 mark2chans] = intersect_bc(EMARKER2CHANS,pltchans);
end
end
if ~isempty(Values)
if length(Values) == length(Th) % if as many map Values as channel locs
intValues = Values(intchans);
intContourVals = ContourVals(intchans);
Values = Values(pltchans);
ContourVals = ContourVals(pltchans);
end;
end; % now channel parameters and values all refer to plotting channels only
allchansind = allchansind(pltchans);
intTh = Th(intchans); % eliminate channels outside the interpolation area
intRd = Rd(intchans);
intx = x(intchans);
inty = y(intchans);
Th = Th(pltchans); % eliminate channels outside the plotting area
Rd = Rd(pltchans);
x = x(pltchans);
y = y(pltchans);
labels= labels(pltchans,:);
%
%%%%%%%%%%%%%%% Squeeze channel locations to <= rmax %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
squeezefac = rmax/plotrad;
intRd = intRd*squeezefac; % squeeze electrode arc_lengths towards the vertex
Rd = Rd*squeezefac; % squeeze electrode arc_lengths towards the vertex
% to plot all inside the head cartoon
intx = intx*squeezefac;
inty = inty*squeezefac;
x = x*squeezefac;
y = y*squeezefac;
allx = allx*squeezefac;
ally = ally*squeezefac;
% Note: Now outermost channel will be plotted just inside rmax
else % if strcmpi(STYLE,'grid')
intx = rmax; inty=rmax;
end % if ~strcmpi(STYLE,'grid')
%
%%%%%%%%%%%%%%%% rotate channels based on chaninfo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(lower(NOSEDIR), '+x')
rotate = 0;
else
if strcmpi(lower(NOSEDIR), '+y')
rotate = 3*pi/2;
elseif strcmpi(lower(NOSEDIR), '-x')
rotate = pi;
else rotate = pi/2;
end;
allcoords = (inty + intx*sqrt(-1))*exp(sqrt(-1)*rotate);
intx = imag(allcoords);
inty = real(allcoords);
allcoords = (ally + allx*sqrt(-1))*exp(sqrt(-1)*rotate);
allx = imag(allcoords);
ally = real(allcoords);
allcoords = (y + x*sqrt(-1))*exp(sqrt(-1)*rotate);
x = imag(allcoords);
y = real(allcoords);
end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Make the plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~strcmpi(STYLE,'blank') % if draw interpolated scalp map
if ~strcmpi(STYLE,'grid') % not a rectangular channel grid
%
%%%%%%%%%%%%%%%% Find limits for interpolation %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if default_intrad % if no specified intrad
if strcmpi(INTERPLIMITS,'head') % intrad is 'head'
xmin = min(-rmax,min(intx)); xmax = max(rmax,max(intx));
ymin = min(-rmax,min(inty)); ymax = max(rmax,max(inty));
else % INTERPLIMITS = rectangle containing electrodes -- DEPRECATED OPTION!
xmin = max(-rmax,min(intx)); xmax = min(rmax,max(intx));
ymin = max(-rmax,min(inty)); ymax = min(rmax,max(inty));
end
else % some other intrad specified
xmin = -intrad*squeezefac; xmax = intrad*squeezefac; % use the specified intrad value
ymin = -intrad*squeezefac; ymax = intrad*squeezefac;
end
%
%%%%%%%%%%%%%%%%%%%%%%% Interpolate scalp map data %%%%%%%%%%%%%%%%%%%%%%%%
%
xi = linspace(xmin,xmax,GRID_SCALE); % x-axis description (row vector)
yi = linspace(ymin,ymax,GRID_SCALE); % y-axis description (row vector)
try
[Xi,Yi,Zi] = griddata(inty,intx,double(intValues),yi',xi,'v4'); % interpolate data
[Xi,Yi,ZiC] = griddata(inty,intx,double(intContourVals),yi',xi,'v4'); % interpolate data
catch,
[Xi,Yi,Zi] = griddata(inty,intx,intValues',yi,xi'); % interpolate data (Octave)
[Xi,Yi,ZiC] = griddata(inty,intx,intContourVals',yi,xi'); % interpolate data
end;
%
%%%%%%%%%%%%%%%%%%%%%%% Mask out data outside the head %%%%%%%%%%%%%%%%%%%%%
%
mask = (sqrt(Xi.^2 + Yi.^2) <= rmax); % mask outside the plotting circle
ii = find(mask == 0);
Zi(ii) = NaN; % mask non-plotting voxels with NaNs
ZiC(ii) = NaN; % mask non-plotting voxels with NaNs
grid = plotrad; % unless 'noplot', then 3rd output arg is plotrad
%
%%%%%%%%%% Return interpolated value at designated scalp location %%%%%%%%%%
%
if exist('chanrad') % optional first argument to 'noplot'
chantheta = (chantheta/360)*2*pi;
chancoords = round(ceil(GRID_SCALE/2)+GRID_SCALE/2*2*chanrad*[cos(-chantheta),...
-sin(-chantheta)]);
if chancoords(1)<1 ...
| chancoords(1) > GRID_SCALE ...
| chancoords(2)<1 ...
| chancoords(2)>GRID_SCALE
error('designated ''noplot'' channel out of bounds')
else
chanval = Zi(chancoords(1),chancoords(2));
grid = Zi;
Zi = chanval; % return interpolated value instead of Zi
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%% Return interpolated image only %%%%%%%%%%%%%%%%%
%
if strcmpi(noplot, 'on')
if strcmpi(VERBOSE,'on')
fprintf('topoplot(): no plot requested.\n')
end
return;
end
%
%%%%%%%%%%%%%%%%%%%%%%% Calculate colormap limits %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isstr(MAPLIMITS)
if strcmp(MAPLIMITS,'absmax')
amax = max(max(abs(Zi)));
amin = -amax;
elseif strcmp(MAPLIMITS,'maxmin') | strcmp(MAPLIMITS,'minmax')
amin = min(min(Zi));
amax = max(max(Zi));
else
error('unknown ''maplimits'' value.');
end
elseif length(MAPLIMITS) == 2
amin = MAPLIMITS(1);
amax = MAPLIMITS(2);
else
error('unknown ''maplimits'' value');
end
delta = xi(2)-xi(1); % length of grid entry
end % if ~strcmpi(STYLE,'grid')
%
%%%%%%%%%%%%%%%%%%%%%%%%%% Scale the axes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%cla % clear current axis
hold on
h = gca; % uses current axes
% instead of default larger AXHEADFAC
if squeezefac<0.92 & plotrad-headrad > 0.05 % (size of head in axes)
AXHEADFAC = 1.05; % do not leave room for external ears if head cartoon
% shrunk enough by the 'skirt' option
end
set(gca,'Xlim',[-rmax rmax]*AXHEADFAC,'Ylim',[-rmax rmax]*AXHEADFAC);
% specify size of head axes in gca
unsh = (GRID_SCALE+1)/GRID_SCALE; % un-shrink the effects of 'interp' SHADING
%
%%%%%%%%%%%%%%%%%%%%%%%% Plot grid only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
disp('Warning: When plotting pvalues in totoplot, use option ''conv'' to minimize extrapolation effects');
if strcmpi(STYLE,'grid') % plot grid only
%
% The goal below is to make the grid cells square - not yet achieved in all cases? -sm
%
g1 = size(gridchans,1);
g2 = size(gridchans,2);
gmax = max([g1 g2]);
Xi = linspace(-rmax*g2/gmax,rmax*g2/gmax,g1+1);
Xi = Xi+rmax/g1; Xi = Xi(1:end-1);
Yi = linspace(-rmax*g1/gmax,rmax*g1/gmax,g2+1);
Yi = Yi+rmax/g2; Yi = Yi(1:end-1); Yi = Yi(end:-1:1); % by trial and error!
%
%%%%%%%%%%% collect the gridchans values %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
gridvalues = zeros(size(gridchans));
for j=1:size(gridchans,1)
for k=1:size(gridchans,2)
gc = gridchans(j,k);
if gc > 0
gridvalues(j,k) = Values(gc);
elseif gc < 0
gridvalues(j,k) = -Values(gc);
else
gridvalues(j,k) = nan; % not-a-number = no value
end
end
end
%
%%%%%%%%%%% reset color limits for grid plot %%%%%%%%%%%%%%%%%%%%%%%%%
%
if isstr(MAPLIMITS)
if strcmp(MAPLIMITS,'maxmin') | strcmp(MAPLIMITS,'minmax')
amin = min(min(gridvalues(~isnan(gridvalues))));
amax = max(max(gridvalues(~isnan(gridvalues))));
elseif strcmp(MAPLIMITS,'absmax')
% 11/21/2005 Toby edit
% This should now work as specified. Before it only crashed (using
% "plotgrid" and "maplimits>absmax" options).
amax = max(max(abs(gridvalues(~isnan(gridvalues)))));
amin = -amax;
%amin = -max(max(abs([amin amax])));
%amax = max(max(abs([amin amax])));
else
error('unknown ''maplimits'' value');
end
elseif length(MAPLIMITS) == 2
amin = MAPLIMITS(1);
amax = MAPLIMITS(2);
else
error('unknown ''maplimits'' value');
end
%
%%%%%%%%%% explicitly compute grid colors, allowing BACKCOLOR %%%%%%
%
gridvalues = 1+floor(cmaplen*(gridvalues-amin)/(amax-amin));
gridvalues(find(gridvalues == cmaplen+1)) = cmaplen;
gridcolors = zeros([size(gridvalues),3]);
for j=1:size(gridchans,1)
for k=1:size(gridchans,2)
if ~isnan(gridvalues(j,k))
gridcolors(j,k,:) = cmap(gridvalues(j,k),:);
else
if strcmpi(whitebk,'off')
gridcolors(j,k,:) = BACKCOLOR; % gridchans == 0 -> background color
% This allows the plot to show 'space' between separate sub-grids or strips
else % 'on'
gridcolors(j,k,:) = [1 1 1]; BACKCOLOR; % gridchans == 0 -> white for printing
end
end
end
end
%
%%%%%%%%%% draw the gridplot image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
handle=imagesc(Xi,Yi,gridcolors); % plot grid with explicit colors
axis square
%
%%%%%%%%%%%%%%%%%%%%%%%% Plot map contours only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(STYLE,'contour') % plot surface contours only
[cls chs] = contour(Xi,Yi,ZiC,CONTOURNUM,'k');
handle = chs; % handle to a contourgroup object
% for h=chs, set(h,'color',CCOLOR); end
%
%%%%%%%%%%%%%%%%%%%%%%%% Else plot map and contours %%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(STYLE,'both') % plot interpolated surface and surface contours
if strcmp(SHADING,'interp')
tmph = surface(Xi*unsh,Yi*unsh,zeros(size(Zi))-0.1,Zi,...
'EdgeColor','none','FaceColor',SHADING);
else % SHADING == 'flat'
tmph = surface(Xi-delta/2,Yi-delta/2,zeros(size(Zi))-0.1,Zi,...
'EdgeColor','none','FaceColor',SHADING);
end
if strcmpi(MASKSURF, 'on')
set(tmph, 'visible', 'off');
handle = tmph;
end;
warning off;
if ~PMASKFLAG
[cls chs] = contour(Xi,Yi,ZiC,CONTOURNUM,'k');
else
ZiC(find(ZiC > 0.5 )) = NaN;
[cls chs] = contourf(Xi,Yi,ZiC,0,'k');
subh = get(chs, 'children');
for indsubh = 1:length(subh)
numfaces = size(get(subh(indsubh), 'XData'),1);
set(subh(indsubh), 'FaceVertexCData', ones(numfaces,3), 'Cdatamapping', 'direct', 'facealpha', 0.5, 'linewidth', 2);
end;
end;
handle = tmph; % surface handle
for h=chs, set(h,'color',CCOLOR); end
warning on;
%
%%%%%%%%%%%%%%%%%%%%%%%% Else plot map only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(STYLE,'straight') | strcmp(STYLE,'map') % 'straight' was former arg
if strcmp(SHADING,'interp') % 'interp' mode is shifted somehow... but how?
tmph = surface(Xi*unsh,Yi*unsh,zeros(size(Zi)),Zi,'EdgeColor','none',...
'FaceColor',SHADING);
else
tmph = surface(Xi-delta/2,Yi-delta/2,zeros(size(Zi)),Zi,'EdgeColor','none',...
'FaceColor',SHADING);
end
if strcmpi(MASKSURF, 'on')
set(tmph, 'visible', 'off');
handle = tmph;
end;
handle = tmph; % surface handle
%
%%%%%%%%%%%%%%%%%% Else fill contours with uniform colors %%%%%%%%%%%%%%%%%%
%
elseif strcmp(STYLE,'fill')
[cls chs] = contourf(Xi,Yi,Zi,CONTOURNUM,'k');
handle = chs; % handle to a contourgroup object
% for h=chs, set(h,'color',CCOLOR); end
% <- 'not line objects.' Why does 'both' work above???
else
error('Invalid style')
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Set color axis %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% caxis([amin amax]); % set coloraxis
% 7/30/2014 Ramon: +-5% for the color limits were added
cax_sgn = sign([amin amax]); % getting sign
caxis([amin+cax_sgn(1)*(0.05*abs(amin)) amax+cax_sgn(2)*(0.05*abs(amax))]); % Adding 5% to the color limits
else % if STYLE 'blank'
%
%%%%%%%%%%%%%%%%%%%%%%% Draw blank head %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(noplot, 'on')
if strcmpi(VERBOSE,'on')
fprintf('topoplot(): no plot requested.\n')
end
return;
end
%cla
hold on
set(gca,'Xlim',[-rmax rmax]*AXHEADFAC,'Ylim',[-rmax rmax]*AXHEADFAC)
% pos = get(gca,'position');
% fprintf('Current axes size %g,%g\n',pos(3),pos(4));
if strcmp(ELECTRODES,'labelpoint') | strcmp(ELECTRODES,'numpoint')
text(-0.6,-0.6, ...
[ int2str(length(Rd)) ' of ' int2str(length(tmpeloc)) ' electrode locations shown']);
text(-0.6,-0.7, [ 'Click on electrodes to toggle name/number']);
tl = title('Channel locations');
set(tl, 'fontweight', 'bold');
end;
end % STYLE 'blank'
if exist('handle') ~= 1
handle = gca;
end;
if ~strcmpi(STYLE,'grid') % if not plot grid only
%
%%%%%%%%%%%%%%%%%%% Plot filled ring to mask jagged grid boundary %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
hwidth = HEADRINGWIDTH; % width of head ring
hin = squeezefac*headrad*(1- hwidth/2); % inner head ring radius
if strcmp(SHADING,'interp')
rwidth = BLANKINGRINGWIDTH*1.3; % width of blanking outer ring
else
rwidth = BLANKINGRINGWIDTH; % width of blanking outer ring
end
rin = rmax*(1-rwidth/2); % inner ring radius
if hin>rin
rin = hin; % dont blank inside the head ring
end
if strcmp(CONVHULL,'on') %%%%%%%%% mask outside the convex hull of the electrodes %%%%%%%%%
cnv = convhull(allx,ally);
cnvfac = round(CIRCGRID/length(cnv)); % spline interpolate the convex hull
if cnvfac < 1, cnvfac=1; end;
CIRCGRID = cnvfac*length(cnv);
startangle = atan2(allx(cnv(1)),ally(cnv(1)));
circ = linspace(0+startangle,2*pi+startangle,CIRCGRID);
rx = sin(circ);
ry = cos(circ);
allx = allx(:)'; % make x (elec locations; + to nose) a row vector
ally = ally(:)'; % make y (elec locations, + to r? ear) a row vector
erad = sqrt(allx(cnv).^2+ally(cnv).^2); % convert to polar coordinates
eang = atan2(allx(cnv),ally(cnv));
eang = unwrap(eang);
eradi =spline(linspace(0,1,3*length(cnv)), [erad erad erad], ...
linspace(0,1,3*length(cnv)*cnvfac));
eangi =spline(linspace(0,1,3*length(cnv)), [eang+2*pi eang eang-2*pi], ...
linspace(0,1,3*length(cnv)*cnvfac));
xx = eradi.*sin(eangi); % convert back to rect coordinates
yy = eradi.*cos(eangi);
yy = yy(CIRCGRID+1:2*CIRCGRID);
xx = xx(CIRCGRID+1:2*CIRCGRID);
eangi = eangi(CIRCGRID+1:2*CIRCGRID);
eradi = eradi(CIRCGRID+1:2*CIRCGRID);
xx = xx*1.02; yy = yy*1.02; % extend spline outside electrode marks
splrad = sqrt(xx.^2+yy.^2); % arc radius of spline points (yy,xx)
oob = find(splrad >= rin); % enforce an upper bound on xx,yy
xx(oob) = rin*xx(oob)./splrad(oob); % max radius = rin
yy(oob) = rin*yy(oob)./splrad(oob); % max radius = rin
splrad = sqrt(xx.^2+yy.^2); % arc radius of spline points (yy,xx)
oob = find(splrad < hin); % don't let splrad be inside the head cartoon
xx(oob) = hin*xx(oob)./splrad(oob); % min radius = hin
yy(oob) = hin*yy(oob)./splrad(oob); % min radius = hin
ringy = [[ry(:)' ry(1) ]*(rin+rwidth) yy yy(1)];
ringx = [[rx(:)' rx(1) ]*(rin+rwidth) xx xx(1)];
ringh2= patch(ringy,ringx,ones(size(ringy)),BACKCOLOR,'edgecolor','none'); hold on
% plot(ry*rmax,rx*rmax,'b') % debugging line
else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% mask the jagged border around rmax %%%%%%%%%%%%%%%5%%%%%%
circ = linspace(0,2*pi,CIRCGRID);
rx = sin(circ);
ry = cos(circ);
ringx = [[rx(:)' rx(1) ]*(rin+rwidth) [rx(:)' rx(1)]*rin];
ringy = [[ry(:)' ry(1) ]*(rin+rwidth) [ry(:)' ry(1)]*rin];
if ~strcmpi(STYLE,'blank')
ringh= patch(ringx,ringy,0.01*ones(size(ringx)),BACKCOLOR,'edgecolor','none'); hold on
end
% plot(ry*rmax,rx*rmax,'b') % debugging line
end
%f1= fill(rin*[rx rX],rin*[ry rY],BACKCOLOR,'edgecolor',BACKCOLOR); hold on
%f2= fill(rin*[rx rX*(1+rwidth)],rin*[ry rY*(1+rwidth)],BACKCOLOR,'edgecolor',BACKCOLOR);
% Former line-style border smoothing - width did not scale with plot
% brdr=plot(1.015*cos(circ).*rmax,1.015*sin(circ).*rmax,... % old line-based method
% 'color',HEADCOLOR,'Linestyle','-','LineWidth',HLINEWIDTH); % plot skirt outline
% set(brdr,'color',BACKCOLOR,'linewidth',HLINEWIDTH + 4); % hide the disk edge jaggies
%
%%%%%%%%%%%%%%%%%%%%%%%%% Plot cartoon head, ears, nose %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if headrad > 0 % if cartoon head to be plotted
%
%%%%%%%%%%%%%%%%%%% Plot head outline %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
headx = [[rx(:)' rx(1) ]*(hin+hwidth) [rx(:)' rx(1)]*hin];
heady = [[ry(:)' ry(1) ]*(hin+hwidth) [ry(:)' ry(1)]*hin];
if ~isstr(HEADCOLOR) | ~strcmpi(HEADCOLOR,'none')
%ringh= patch(headx,heady,ones(size(headx)),HEADCOLOR,'edgecolor',HEADCOLOR,'linewidth', HLINEWIDTH); hold on
headx = [rx(:)' rx(1)]*hin;
heady = [ry(:)' ry(1)]*hin;
ringh= plot(headx,heady);
set(ringh, 'color',HEADCOLOR,'linewidth', HLINEWIDTH); hold on
end
% rx = sin(circ); rX = rx(end:-1:1);
% ry = cos(circ); rY = ry(end:-1:1);
% for k=2:2:CIRCGRID
% rx(k) = rx(k)*(1+hwidth);
% ry(k) = ry(k)*(1+hwidth);
% end
% f3= fill(hin*[rx rX],hin*[ry rY],HEADCOLOR,'edgecolor',HEADCOLOR); hold on
% f4= fill(hin*[rx rX*(1+hwidth)],hin*[ry rY*(1+hwidth)],HEADCOLOR,'edgecolor',HEADCOLOR);
% Former line-style head
% plot(cos(circ).*squeezefac*headrad,sin(circ).*squeezefac*headrad,...
% 'color',HEADCOLOR,'Linestyle','-','LineWidth',HLINEWIDTH); % plot head outline
%
%%%%%%%%%%%%%%%%%%% Plot ears and nose %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
base = rmax-.0046;
basex = 0.18*rmax; % nose width
tip = 1.15*rmax;
tiphw = .04*rmax; % nose tip half width
tipr = .01*rmax; % nose tip rounding
q = .04; % ear lengthening
EarX = [.497-.005 .510 .518 .5299 .5419 .54 .547 .532 .510 .489-.005]; % rmax = 0.5
EarY = [q+.0555 q+.0775 q+.0783 q+.0746 q+.0555 -.0055 -.0932 -.1313 -.1384 -.1199];
sf = headrad/plotrad; % squeeze the model ears and nose
% by this factor
if ~isstr(HEADCOLOR) | ~strcmpi(HEADCOLOR,'none')
plot3([basex;tiphw;0;-tiphw;-basex]*sf,[base;tip-tipr;tip;tip-tipr;base]*sf,...
2*ones(size([basex;tiphw;0;-tiphw;-basex])),...
'Color',HEADCOLOR,'LineWidth',HLINEWIDTH); % plot nose
plot3(EarX*sf,EarY*sf,2*ones(size(EarX)),'color',HEADCOLOR,'LineWidth',HLINEWIDTH) % plot left ear
plot3(-EarX*sf,EarY*sf,2*ones(size(EarY)),'color',HEADCOLOR,'LineWidth',HLINEWIDTH) % plot right ear
end
end
%
% %%%%%%%%%%%%%%%%%%% Show electrode information %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
plotax = gca;
axis square % make plotax square
axis off
pos = get(gca,'position');
xlm = get(gca,'xlim');
ylm = get(gca,'ylim');
% textax = axes('position',pos,'xlim',xlm,'ylim',ylm); % make new axes so clicking numbers <-> labels
% will work inside head cartoon patch
% axes(textax);
axis square % make textax square
pos = get(gca,'position');
set(plotax,'position',pos);
xlm = get(gca,'xlim');
set(plotax,'xlim',xlm);
ylm = get(gca,'ylim');
set(plotax,'ylim',ylm); % copy position and axis limits again
axis equal;
set(gca, 'xlim', [-0.525 0.525]); set(plotax, 'xlim', [-0.525 0.525]);
set(gca, 'ylim', [-0.525 0.525]); set(plotax, 'ylim', [-0.525 0.525]);
%get(textax,'pos') % test if equal!
%get(plotax,'pos')
%get(textax,'xlim')
%get(plotax,'xlim')
%get(textax,'ylim')
%get(plotax,'ylim')
if isempty(EMARKERSIZE)
EMARKERSIZE = 10;
if length(y)>=160
EMARKERSIZE = 3;
elseif length(y)>=128
EMARKERSIZE = 3;
elseif length(y)>=100
EMARKERSIZE = 3;
elseif length(y)>=80
EMARKERSIZE = 4;
elseif length(y)>=64
EMARKERSIZE = 5;
elseif length(y)>=48
EMARKERSIZE = 6;
elseif length(y)>=32
EMARKERSIZE = 8;
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Mark electrode locations only %%%%%%%%%%%%%%%%%%%%%%%%%%
%
ELECTRODE_HEIGHT = 2.1; % z value for plotting electrode information (above the surf)
if strcmp(ELECTRODES,'on') % plot electrodes as spots
if isempty(EMARKER2CHANS)
hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
else % plot markers for normal chans and EMARKER2CHANS separately
hp2 = plot3(y(mark1chans),x(mark1chans),ones(size((mark1chans)))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
hp2b = plot3(y(mark2chans),x(mark2chans),ones(size((mark2chans)))*ELECTRODE_HEIGHT,...
EMARKER2,'Color',EMARKER2COLOR,'markerfacecolor',EMARKER2COLOR,'linewidth',EMARKER2LINEWIDTH,'markersize',EMARKERSIZE2);
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Print electrode labels only %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'labels') % print electrode names (labels)
for i = 1:size(labels,1)
text(double(y(i)),double(x(i)),...
ELECTRODE_HEIGHT,labels(i,:),'HorizontalAlignment','center',...
'VerticalAlignment','middle','Color',ECOLOR,...
'FontSize',EFSIZE)
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Mark electrode locations plus labels %%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'labelpoint')
if isempty(EMARKER2CHANS)
hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
else
hp2 = plot3(y(mark1chans),x(mark1chans),ones(size((mark1chans)))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
hp2b = plot3(y(mark2chans),x(mark2chans),ones(size((mark2chans)))*ELECTRODE_HEIGHT,...
EMARKER2,'Color',EMARKER2COLOR,'markerfacecolor',EMARKER2COLOR,'linewidth',EMARKER2LINEWIDTH,'markersize',EMARKERSIZE2);
end
for i = 1:size(labels,1)
hh(i) = text(double(y(i)+0.01),double(x(i)),...
ELECTRODE_HEIGHT,labels(i,:),'HorizontalAlignment','left',...
'VerticalAlignment','middle','Color', ECOLOR,'userdata', num2str(allchansind(i)), ...
'FontSize',EFSIZE, 'buttondownfcn', ...
['tmpstr = get(gco, ''userdata'');'...
'set(gco, ''userdata'', get(gco, ''string''));' ...
'set(gco, ''string'', tmpstr); clear tmpstr;'] );
end
%
%%%%%%%%%%%%%%%%%%%%%%% Mark electrode locations plus numbers %%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'numpoint')
if isempty(EMARKER2CHANS)
hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
else
hp2 = plot3(y(mark1chans),x(mark1chans),ones(size((mark1chans)))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
hp2b = plot3(y(mark2chans),x(mark2chans),ones(size((mark2chans)))*ELECTRODE_HEIGHT,...
EMARKER2,'Color',EMARKER2COLOR,'markerfacecolor',EMARKER2COLOR,'linewidth',EMARKER2LINEWIDTH,'markersize',EMARKERSIZE2);
end
for i = 1:size(labels,1)
hh(i) = text(double(y(i)+0.01),double(x(i)),...
ELECTRODE_HEIGHT,num2str(allchansind(i)),'HorizontalAlignment','left',...
'VerticalAlignment','middle','Color', ECOLOR,'userdata', labels(i,:) , ...
'FontSize',EFSIZE, 'buttondownfcn', ...
['tmpstr = get(gco, ''userdata'');'...
'set(gco, ''userdata'', get(gco, ''string''));' ...
'set(gco, ''string'', tmpstr); clear tmpstr;'] );
end
%
%%%%%%%%%%%%%%%%%%%%%% Print electrode numbers only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'numbers')
for i = 1:size(labels,1)
text(double(y(i)),double(x(i)),...
ELECTRODE_HEIGHT,int2str(allchansind(i)),'HorizontalAlignment','center',...
'VerticalAlignment','middle','Color',ECOLOR,...
'FontSize',EFSIZE)
end
%
%%%%%%%%%%%%%%%%%%%%%% Mark emarker2 electrodes only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'off') & ~isempty(EMARKER2CHANS)
hp2b = plot3(y(mark2chans),x(mark2chans),ones(size((mark2chans)))*ELECTRODE_HEIGHT,...
EMARKER2,'Color',EMARKER2COLOR,'markerfacecolor',EMARKER2COLOR,'linewidth',EMARKER2LINEWIDTH,'markersize',EMARKERSIZE2);
end
%
%%%%%%%% Mark specified electrode locations with red filled disks %%%%%%%%%%%%%%%%%%%%%%
%
try,
if strcmpi(STYLE,'blank') % if mark-selected-channel-locations mode
for kk = 1:length(1:length(x))
if abs(Values(kk))
if PLOTDISK
angleRatio = real(Values(kk))/(real(Values(kk))+imag(Values(kk)))*360;
radius = real(Values(kk))+imag(Values(kk));
allradius = [0.02 0.03 0.037 0.044 0.05];
radius = allradius(radius);
hp2 = disk(y(kk),x(kk),radius, [1 0 0], 0 , angleRatio, 16);
if angleRatio ~= 360
hp2 = disk(y(kk),x(kk),radius, [0 0 1], angleRatio, 360, 16);
end;
else
tmpcolor = COLORARRAY{max(1,min(Values(kk), length(COLORARRAY)))};
hp2 = plot3(y(kk),x(kk),ELECTRODE_HEIGHT,EMARKER,'Color', tmpcolor, 'markersize', EMARKERSIZE1CHAN);
hp2 = disk(y(kk),x(kk),0.04, tmpcolor, 0, 360, 10);
end;
end;
end
end
catch, end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%% Plot dipole(s) on the scalp map %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(DIPOLE)
hold on;
tmp = DIPOLE;
if isstruct(DIPOLE)
if ~isfield(tmp,'posxyz')
error('dipole structure is not an EEG.dipfit.model')
end
DIPOLE = []; % Note: invert x and y from dipplot usage
DIPOLE(:,1) = -tmp.posxyz(:,2)/DIPSPHERE; % -y -> x
DIPOLE(:,2) = tmp.posxyz(:,1)/DIPSPHERE; % x -> y
DIPOLE(:,3) = -tmp.momxyz(:,2);
DIPOLE(:,4) = tmp.momxyz(:,1);
else
DIPOLE(:,1) = -tmp(:,2); % same for vector input
DIPOLE(:,2) = tmp(:,1);
DIPOLE(:,3) = -tmp(:,4);
DIPOLE(:,4) = tmp(:,3);
end;
for index = 1:size(DIPOLE,1)
if ~any(DIPOLE(index,:))
DIPOLE(index,:) = [];
end
end;
DIPOLE(:,1:4) = DIPOLE(:,1:4)*rmax*(rmax/plotrad); % scale radius from 1 -> rmax (0.5)
DIPOLE(:,3:end) = (DIPOLE(:,3:end))*rmax/100000*(rmax/plotrad);
if strcmpi(DIPNORM, 'on')
for index = 1:size(DIPOLE,1)
DIPOLE(index,3:4) = DIPOLE(index,3:4)/norm(DIPOLE(index,3:end))*0.2;
end;
end;
DIPOLE(:, 3:4) = DIPORIENT*DIPOLE(:, 3:4)*DIPLEN;
PLOT_DIPOLE=1;
if sum(DIPOLE(1,3:4).^2) <= 0.00001
if strcmpi(VERBOSE,'on')
fprintf('Note: dipole is length 0 - not plotted\n')
end
PLOT_DIPOLE = 0;
end
if 0 % sum(DIPOLE(1,1:2).^2) > plotrad
if strcmpi(VERBOSE,'on')
fprintf('Note: dipole is outside plotting area - not plotted\n')
end
PLOT_DIPOLE = 0;
end
if PLOT_DIPOLE
for index = 1:size(DIPOLE,1)
hh = plot( DIPOLE(index, 1), DIPOLE(index, 2), '.');
set(hh, 'color', DIPCOLOR, 'markersize', DIPSCALE*30);
hh = line( [DIPOLE(index, 1) DIPOLE(index, 1)+DIPOLE(index, 3)]', ...
[DIPOLE(index, 2) DIPOLE(index, 2)+DIPOLE(index, 4)]',[10 10]);
set(hh, 'color', DIPCOLOR, 'linewidth', DIPSCALE*30/7);
end;
end;
end;
end % if ~ 'gridplot'
%
%%%%%%%%%%%%% Plot axis orientation %%%%%%%%%%%%%%%%%%%%
%
if strcmpi(DRAWAXIS, 'on')
axes('position', [0 0.85 0.08 0.1]);
axis off;
coordend1 = sqrt(-1)*3;
coordend2 = -3;
coordend1 = coordend1*exp(sqrt(-1)*rotate);
coordend2 = coordend2*exp(sqrt(-1)*rotate);
line([5 5+round(real(coordend1))]', [5 5+round(imag(coordend1))]', 'color', 'k');
line([5 5+round(real(coordend2))]', [5 5+round(imag(coordend2))]', 'color', 'k');
if round(real(coordend2))<0
text( 5+round(real(coordend2))*1.2, 5+round(imag(coordend2))*1.2-2, '+Y');
else text( 5+round(real(coordend2))*1.2, 5+round(imag(coordend2))*1.2, '+Y');
end;
if round(real(coordend1))<0
text( 5+round(real(coordend1))*1.2, 5+round(imag(coordend1))*1.2+1.5, '+X');
else text( 5+round(real(coordend1))*1.2, 5+round(imag(coordend1))*1.2, '+X');
end;
set(gca, 'xlim', [0 10], 'ylim', [0 10]);
end;
%
%%%%%%%%%%%%% Set EEGLAB background color to match head border %%%%%%%%%%%%%%%%%%%%%%%%
%
try,
set(gcf, 'color', BACKCOLOR);
catch,
end;
hold off
axis off
return
%
%%%%%%%%%%%%% Draw circle %%%%%%%%%%%%%%%%%%%%%%%%
%
function h2 = disk(X, Y, radius, colorfill, oriangle, endangle, segments)
A = linspace(oriangle/180*pi, endangle/180*pi, segments-1);
if endangle-oriangle == 360
A = linspace(oriangle/180*pi, endangle/180*pi, segments);
h2 = patch( [X + cos(A)*radius(1)], [Y + sin(A)*radius(end)], zeros(1,segments)+3, colorfill);
else A = linspace(oriangle/180*pi, endangle/180*pi, segments-1);
h2 = patch( [X X + cos(A)*radius(1)], [Y Y + sin(A)*radius(end)], zeros(1,segments)+3, colorfill);
end;
set(h2, 'FaceColor', colorfill);
set(h2, 'EdgeColor', 'none');
|
github
|
lcnbeapp/beapp-master
|
readegilocs.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/readegilocs.m
| 2,898 |
utf_8
|
db357ca683b59cbb87ff64dc2cc5bb0b
|
% readegilocs() - look up locations for EGI EEG dataset.
%
% Usage:
% >> EEG = readegilocs(EEG);
% >> EEG = readegilocs(EEG, fileloc);
%
% Inputs:
% EEG - EEGLAB data structure
%
% Optional input:
% fileloc - EGI channel location file
%
% Outputs:
% EEG - EEGLAB data structure with channel location structure
%
% Author: Arnaud Delorme, SCCN/UCSD
%
% See also: pop_readegi(), readegi()
% Copyright (C) 12 Nov 2002 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function EEG = readegilocs(EEG, fileloc);
if nargin < 1
help readegilocs;
return;
end;
% importing channel locations
% ---------------------------
found = 1;
if nargin < 2
switch EEG.nbchan
case { 32 33 }, fileloc = 'GSN-HydroCel-32.sfp';
case { 64 65 }, fileloc = 'GSN65v2_0.sfp';
case { 128 129 }, fileloc = 'GSN129.sfp';
case { 256 257 }, fileloc = 'GSN-HydroCel-257.sfp';
otherwise, found = 0;
end;
end;
if found
fprintf('EGI channel location automatically detected %s ********* WARNING please check that this the proper file\n', fileloc);
if EEG.nbchan == 64 || EEG.nbchan == 65 || EEG.nbchan == 256 || EEG.nbchan == 257
fprintf( [ 'Warning: this function assumes you have a 64-channel system Version 2\n' ...
' if this is not the case, update the channel location with the proper file' ]);
end;
% remove the last channel for 33 channels
peeglab = fileparts(which('eeglab.m'));
fileloc = fullfile(peeglab, 'sample_locs', fileloc);
locs = readlocs(fileloc);
locs(1).type = 'FID';
locs(2).type = 'FID';
locs(3).type = 'FID';
locs(end).type = 'REF';
if EEG.nbchan == 256 || EEG.nbchan == 257
if EEG.nbchan == 256
chaninfo.nodatchans = locs([end]);
locs([end]) = [];
end;
elseif mod(EEG.nbchan,2) == 0,
chaninfo.nodatchans = locs([1 2 3 end]);
locs([1 2 3 end]) = [];
else
chaninfo.nodatchans = locs([1 2 3]);
locs([1 2 3]) = [];
end; % remove reference
chaninfo.filename = fileloc;
EEG.chanlocs = locs;
EEG.urchanlocs = locs;
EEG.chaninfo = chaninfo;
end;
|
github
|
lcnbeapp/beapp-master
|
eyelike.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/eyelike.m
| 748 |
utf_8
|
83fb00bb12b75f143a88314e92ebe31f
|
% eyelike() - calculate a permutation matrix P and a scaling (diagonal) maxtrix S
% such that S*P*E is eyelike (so permutation acts on the rows of E).
% E must be a square matrix.
% Usage:
% >> [eyelike, S, P] = eyelike(E);
%
% Author: Benjamin Blankertz ([email protected]) 3/2/00
function [eyelikeres, S, P]= eyelike(E)
[N, M]= size(E);
if N ~= M
fprintf('eyeLike(): input matrix must be square.\n');
return
end
R= E./repmat(sum(abs(E),2),1,N);
Rabs= abs(R);
P= zeros(N);
for n=1:N
[so, si]= sort(-Rabs(:));
[chosenV, chosenH]= ind2sub([N N], si(1));
P(chosenH,chosenV)= 1;
Rabs(chosenV,:)= repmat(-inf, 1, N);
Rabs(:,chosenH)= repmat(-inf, N, 1);
end
S= diag(1./diag(P*E));
eyelikeres= S*P*E;
|
github
|
lcnbeapp/beapp-master
|
trial2eegplot.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/trial2eegplot.m
| 1,822 |
utf_8
|
5c1c543407f5710d59e780a95904b9d5
|
% trial2eegplot() - convert eeglab format to eeplot format of rejection window
%
% Usage:
% >> eegplotarray = trial2eegplot(rej, rejE, points, color);
%
% Inputs:
% rej - rejection vector (0 and 1) with one value per trial
% rejE - electrode rejection array (size nb_elec x trials) also
% made of 0 and 1.
% points - number of points per trials
% color - color of the windows for eegplot()
%
% Outputs:
% eegplotarray - array defining windows which is compatible with
% the function eegplot()
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eegtresh(), eeglab(), eegplot(), pop_rejepoch()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% ----------------------------------------------------------
function rejeegplot = trial2eegplot( rej, rejE, pnts, color)
rej = find(rej>0);
rejE = rejE(:, rej)';
rejeegplot = zeros(length(rej), size(rejE,2)+5);
rejeegplot(:, 6:end) = rejE;
rejeegplot(:, 1) = (rej(:)-1)*pnts;
rejeegplot(:, 2) = rej(:)*pnts-1;
rejeegplot(:, 3:5) = ones(size(rejeegplot,1),1)*color;
return
|
github
|
lcnbeapp/beapp-master
|
eegplot2event.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/eegplot2event.m
| 2,932 |
utf_8
|
f36ca0fc4d6df10d0b3f83cc6f657f74
|
% eegplot2event() - convert EEGPLOT rejections into events
% compatible with the eeg_eegrej function for rejecting
% continuous portions of datasets.
%
% Usage:
% >> [events] = eegplot2event( eegplotrej, type, colorin, colorout );
%
% Inputs:
% eegplotrej - EEGPLOT output (TMPREJ; see eegplot for more details)
% type - type of the event. Default -1.
% colorin - only extract rejection of specific colors (here a n x 3
% array must be given). Default: extract all rejections.
% colorout - do not extract rejection of specified colors.
%
% Outputs:
% events - array of events compatible with the eeg_eegrej function
% for rejecting continuous portions of datasets.
%
% Example:
% NEWEEG = eeg_eegrej(EEG,eegplot2event(TMPREJ, -1));
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eegplot(), eeg_multieegplot(), eegplot2trial(), eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function events = eegplot2event( TMPREJ, type, color, colorout )
if nargin < 1
help eegplot2event;
return;
end;
if nargin < 2
type = -1;
end;
% only take into account specific colors
% --------------------------------------
if exist('color') == 1
for index = 1:size(color,1)
tmpcol1 = TMPREJ(:,3) + 255*TMPREJ(:,4) + 255*255*TMPREJ(:,5);
tmpcol2 = color(index,1)+255*color(index,2)+255*255*color(index,3);
I = find( tmpcol1 == tmpcol2);
if isempty(I)
fprintf('Warning: color [%d %d %d] not found\n', ...
color(index,1), color(index,2), color(index,3));
end;
TMPREJ = TMPREJ(I,:);
end;
end;
% remove other specific colors
% ----------------------------
if exist('colorout') == 1
for index = 1:size(colorout,1)
tmpcol1 = TMPREJ(:,3) + 255*TMPREJ(:,4) + 255*255*TMPREJ(:,5);
tmpcol2 = colorout(index,1)+255*colorout(index,2)+255*255*colorout(index,3);
I = find( tmpcol1 ~= tmpcol2);
TMPREJ = TMPREJ(I,:);
end;
end;
events = [];
if ~isempty(TMPREJ)
events = TMPREJ(:,1:5);
events = [ type*ones(size(events,1), 1) ones(size(events,1), 1) round(events(:,1:2)) events(:,3:5)];
end;
return;
|
github
|
lcnbeapp/beapp-master
|
celltomat.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/celltomat.m
| 1,264 |
utf_8
|
2c99b2d1c464697b97f856035aa819f6
|
% celltomat() - convert cell array to matrix
%
% Usage: >> M = celltomat( C );
%
% Author: Arnaud Delorme, CNL / Salk Institute, Jan 25 2002
%
% Note: This function overloads the neuralnet toolbox function CELLTOMAT,
% but does not have all its capacities. Delete this version if you have
% the toolbox.
% Copyright (C) Jan 25 2002 Arnaud Delorme, CNL / Salk Institute
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function M = celltomat( C, varargin );
if nargin < 1
help celltomat;
return;
end;
M = zeros(size(C));
for i=1:size(C,1)
for j=1:size(C,2)
M(i,j) = C{i,j};
end;
end;
|
github
|
lcnbeapp/beapp-master
|
matsel.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/matsel.m
| 3,756 |
utf_8
|
3779008d46e2601576fba59179f48a0c
|
% matsel() - select rows, columns, and epochs from given multi-epoch data matrix
%
% Usage:
% >> [dataout] = matsel(data,frames,framelist);
% >> [dataout] = matsel(data,frames,framelist,chanlist);
% >> [dataout] = matsel(data,frames,framelist,chanlist,epochlist);
%
% Inputs:
% data - input data matrix (chans,frames*epochs)
% frames - frames (data columns) per epoch (0 -> frames*epochs)
% framelist - list of frames per epoch to select (0 -> 1:frames)
% chanlist - list of chans to select (0 -> 1:chans)
% epochlist - list of epochs to select (0 -> 1:epochs)
%
% Note: The size of dataout is (length(chanlist), length(framelist)*length(epochlist))
%
% Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 5-21-96
% Copyright (C) 5-21-96 Scott Makeig, SCCN/INC/UCSD, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 5-25-96 added chanlist, epochlist -sm
% 10-05-97 added out of bounds tests for chanlist and framelist -sm
% 02-04-00 truncate to epochs*frames if necessary -sm
% 01-25-02 reformated help & license -ad
function [dataout] = matsel(data,frames,framelist,chanlist,epochlist)
if nargin<1
help matsel
return
end
[chans framestot] = size(data);
if isempty(data)
fprintf('matsel(): empty data matrix!?\n')
help matsel
return
end
if nargin < 5,
epochlist = 0;
end
if nargin < 4,
chanlist = 0;
end
if nargin < 3,
fprintf('matsel(): needs at least 3 arguments.\n\n');
return
end
if frames == 0,
frames = framestot;
end
if framelist == 0,
framelist = [1:frames];
end
framesout = length(framelist);
if isempty(chanlist) | chanlist == 0,
chanlist = [1:chans];
end
chansout = length(chanlist);
epochs = floor(framestot/frames);
if epochs*frames ~= framestot
fprintf('matsel(): data length %d was not a multiple of %d frames.\n',...
framestot,frames);
data = data(:,1:epochs*frames);
end
if isempty(epochlist) | epochlist == 0,
epochlist = [1:epochs];
end
epochsout = length(epochlist);
if max(epochlist)>epochs
fprintf('matsel() error: max index in epochlist (%d) > epochs in data (%d)\n',...
max(epochlist),epochs);
return
end
if max(framelist)>frames
fprintf('matsel() error: max index in framelist (%d) > frames per epoch (%d)\n',...
max(framelist),frames);
return
end
if min(framelist)<1
fprintf('matsel() error: framelist min (%d) < 1\n', min(framelist));
return
end
if min(epochlist)<1
fprintf('matsel() error: epochlist min (%d) < 1\n', min(epochlist));
return
end
if max(chanlist)>chans
fprintf('matsel() error: chanlist max (%d) > chans (%d)\n',...
max(chanlist),chans);
return
end
if min(chanlist)<1
fprintf('matsel() error: chanlist min (%d) <1\n',...
min(chanlist));
return
end
dataout = zeros(chansout,framesout*epochsout);
for e=1:epochsout
dataout(:,framesout*(e-1)+1:framesout*e) = ...
data(chanlist,framelist+(epochlist(e)-1)*frames);
end
|
github
|
lcnbeapp/beapp-master
|
axcopy.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/axcopy.m
| 3,330 |
utf_8
|
1c1014b531a21afc497c89e4ffe2ef09
|
% axcopy() - Copy a Matlab figure axis and its graphic objects to a new pop-up window
% using the left mouse button.
%
% Usage: >> axcopy
% >> axcopy(fig)
% >> axcopy('noticks')
% >> axcopy(fig, command)
%
% Notes:
% 1) Clicking the left mouse button on a Matlab figure axis copies the graphic objects
% in the axis to a new (pop-up) figure window.
% 2) Option 'noticks' does not make x and y tickloabelmodes 'auto' in the pop-up.
% 2) The command option is an optional string that is evaluated in the new window
% when it pops up. This allows the user to customize the pop-up display.
% 3) Deleting the pop-up window containing the copied axis leaves the selected axis
% as the current graphic axis (gca).
% Authors: Tzyy-Ping Jung & Scott Makeig, SCCN/INC/UCSD, La Jolla, 2000
% Copyright (C) 2000 Tzyy-Ping Jung & Scott Makeig, SCCN/INC/UCSD, 3-16-00
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% requires copyaxes.m
% 4-2-00 added 'noticks' -sm
% 01-25-02 reformated help & license -ad
% 02-16-02 debuged exist('fig') -> exist('fig') == 1 -ad
% 02-16-02 added the ignore parent size option -ad
% 03-11-02 remove size option and added command option -ad
function axcopy(fig, command)
if (exist('fig') == 1) & strcmp(fig,'noticks')
noticks = 1;
if nargin> 1
shift
else
fig = [];
end
end
if ~(exist('fig') ==1) | isempty(fig) | fig == 0
fig = gcf;
end
if ~strcmpi(get(fig, 'type'), 'axes')
%hndl= findobj('parent',fig,'type','axes');
%--
childs = get(fig,'Children');
hndl = childs(find(strcmpi(get(childs,'Type'),'axes')));
else
hndl=fig;
end;
offidx=[];
if exist('command') ~= 1
comstr = 'copyaxis';
else
command_dbl = double(command);
comstr = double(['copyaxis(''' char(command_dbl) ''')']);
end;
for a=1:length(hndl) % make all axes visible
%allobjs = findobj('parent',hndl(a));
%--
allobjs = get(hndl(a),'Children');
for index = 1:length(allobjs)
if isempty(get(allobjs(index), 'ButtonDownFcn'))
set(allobjs(index), 'ButtonDownFcn', char(comstr));
end;
end;
end
if ~strcmpi(get(fig, 'type'), 'axes')
figure(fig);
else
figure(get(fig, 'parent'));
end;
if exist('command') ~= 1
set(hndl(a),'ButtonDownFcn','copyaxis');
else
% set(hndl,'ButtonDownFcn',['copyaxis(''' command ''')']);
comstr = double(['copyaxis(''' char(command_dbl) ''')']);
set(hndl,'ButtonDownFcn',char(comstr));
end;
%set(hndl,'ButtonDownFcn','copyaxis');
%if ~exist('noticks')
%axis on
%set(gca,'xticklabelmode','auto')
%set(gca,'yticklabelmode','auto')
%end
|
github
|
lcnbeapp/beapp-master
|
eegthresh.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/eegthresh.m
| 4,825 |
utf_8
|
fd6a3945cb7a5cd79d0869f38eaa59ca
|
% eegthresh() - reject trials with out-of-bounds channel values within a
% specified epoch time range.
%
% Usage:
% >> [Iin, Iout, newsignal, elec] = eegthresh( signal, frames, ...
% elecs, negthresh, posthresh, timerange, starttime,endtime);
%
% Required inputs:
% signal - 2-D data matrix [channels, frames*sweeps],
% or 3-D data matrix [channels, frames, sweeps]
% frames - number of points per epoch
% elecs - [int vector] electrode indices to reject on
% negthresh - minimum rejection threshold(s) in uV. This can be an array
% of values for individual electrodes. If fewer values than
% electrodes, the last value is used for the remaining
% electrodes.
% posthresh - maximum rejection threshold(s) in uV (same syntax as for
% negthresh)
% timerange - [mintime maxtime] time range limits of the signal
% starttime - Starting limit (in seconds or Hz) of range to perform
% rejection (same syntax as negthresh)
% endtime - Ending limit (in seconds or Hz) of range to perform
% rejection (same syntax as negthresh)
%
% Outputs:
% Iin - Indexes of epochs accepted
% Iout - Indexes of epochs rejected
% newsignal - input data after epoch rejection
% elec - electrode that triggered the rejections (array of 0s
% and 1s with the same number of columns as Iout
% and number of rows = number of electrodes).
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: pop_eegthresh(), eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [Iin, Iout, newsignal, elec] = eegthresh( signal, pnts, electrodes, negthresh, posthresh, timerange, starttime, endtime);
if nargin < 7
help eegthresh;
return;
end;
if starttime < timerange(1)
disp('eegthresh: starting point out of range, adjusted');
starttime = timerange(1);
end;
if endtime > timerange(2)
disp('eegthresh: ending point out of range, adjusted');
endtime = timerange(2);
end;
% complete thresholds values if necessary
%----------------------------------------
if size(posthresh,2) < size(electrodes,2)
posthresh = [ posthresh posthresh(end)*ones(1,size(electrodes,2)-size(posthresh,2))];
end;
if size(negthresh,2) < size(electrodes,2)
negthresh = [ negthresh negthresh(end)*ones(1,size(electrodes,2)-size(negthresh,2))];
end;
% complete timeselect values if necessary
%----------------------------------------
if size(starttime,2) < size(electrodes,2)
starttime = [ starttime starttime(end)*ones(1,size(electrodes,2)-size(starttime,2))];
end;
if size(endtime,2) < size(electrodes,2)
endtime = [ endtime endtime(end)*ones(1,size(electrodes,2)-size(endtime,2))];
end;
% find the maximum for each trial
%--------------------------------
sweeps = size(signal(1,:),2)/pnts;
signal = reshape(signal(electrodes,:), size(electrodes(:),1), pnts, sweeps);
% reject the selected trials
%---------------------------
elec = zeros(size(electrodes(:),1), sweeps);
allelec = zeros(1, sweeps);
for indexe = 1:size(electrodes(:),1)
% transform the time range
% ------------------------
framelowlimit = max(1,floor((starttime(indexe)-timerange(1))/(timerange(2)-timerange(1))*(pnts-1))+1);
framehighlimit = floor((endtime(indexe) -timerange(1))/(timerange(2)-timerange(1))*(pnts-1))+1;
% remove outliers
% ---------------
sigtmp = squeeze(signal(indexe,framelowlimit:framehighlimit,:));
if size(signal,3) == 1, sigtmp = sigtmp'; end;
sigmax = max(sigtmp, [], 1);
sigmin = min(sigtmp, [], 1);
elec(indexe,:) = ( sigmin < negthresh(indexe) ) | ( sigmax > posthresh(indexe) );
allelec = allelec | elec(indexe,:);
end;
Iout = find( allelec == 1 );
Iin = find( allelec == 0 );
elec = elec(:,Iout);
% reject the selected trials
%---------------------------
newsignal = reshape(signal, size(signal,1), pnts, sweeps);
if ~isempty(Iin)
newsignal = newsignal(:,:,Iin);
if ndims(signal) == 2
newsignal = newsignal(:,:);
end;
else
newsignal = [];
end;
return;
|
github
|
lcnbeapp/beapp-master
|
qqdiagram.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/qqdiagram.m
| 4,745 |
utf_8
|
f9f838e5edd084613e8c54cb85cbb56f
|
% qqdiagram() - Empirical quantile-quantile diagram.
%
% Description:
% The quantiles (percentiles) of the input distribution Y are plotted (Y-axis)
% against the corresponding quantiles of the input distribution X.
% If only X is given, the corresponding quantiles are plotted (Y-axis)
% against the quantiles of a Gaussian distribution ('Normal plot').
% Two black dots indicate the lower and upper quartiles.
% If the data in X and Y belong the same distribution the plot will be linear.
% In this case,the red and black reference lines (.-.-.-.-) will overlap.
% This will be true also if the data in X and Y belong to two distributions with
% the same shape, one distribution being rescaled and shifted with respect to the
% other.
% If only X is given, a line is plotted to indicate the mean of X, and a segment
% is plotted to indicate the standard deviation of X. If the data in X are normally
% distributed, the red and black reference lines (.-.-.-.-) will overlap.
%
% Usage:
% >> ah = qqdiagram( x, y, pk );
%
% Inputs:
% x - vector of observations
%
% Optional inputs:
% y - second vector of observation to compare the first to
% pk - the empirical quantiles will be estimated at the values in pk [0..1]
%
% Author: Luca Finelli, CNL / Salk Institute - SCCN, 20 August 2002
%
% Reference: Stahel W., Statistische Datenanalyse, Vieweg, Braunschweig/Wiesbaden, 1995
%
% See also:
% quantile(), signalstat(), eeglab()
% Copyright (C) 2002 Luca Finelli, Salk/SCCN, La Jolla, CA
%
% Reference: Stahel, W. Statistische Datenanalyse, Vieweg, Braunschweig/Wiesbaden 1995
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function qqdiagram( x , y, pk )
if nargin < 1
help qqdiagram;
return;
end;
if (nargin == 3 & (any(pk > 1) | any(pk < 0)))
error('qqdiagram(): elements in pk must be between 0 and 1');
end
if nargin==1
y=x;
nn=max(1000,10*length(y))+1;
x=randn(1,nn);
end
if nargin < 3
nx=sum(~isnan(x));
ny=sum(~isnan(y));
k=min(nx,ny);
pk=((1:k) - 0.5) ./ k; % values to estimate the empirical quantiles at
else
k=length(pk);
end
if nx==k
xx=sort(x(~isnan(x)));
else
xx=quantile(x(~isnan(x)),pk);
end
if ny==k
yy=sort(y(~isnan(y)));
else
yy=quantile(y(~isnan(y)),pk);
end
% QQ diagram
plot(xx,yy,'+')
hold on
% x-axis range
maxx=max(xx);
minx=min(xx);
rangex=maxx-minx;
xmin=minx-rangex/50;
xmax=maxx+rangex/50;
% Quartiles
xqrt1=quantile(x,0.25); xqrt3=quantile(x,0.75);
yqrt1=quantile(y,0.25); yqrt3=quantile(y,0.75);
plot([xqrt1 xqrt3],[yqrt1 yqrt3],'k-','LineWidth',2); % IQR range
% Drawing the line
sigma=(yqrt3-yqrt1)/(xqrt3-xqrt1);
cy=(yqrt1 + yqrt3)/2;
if nargin ==1
maxy=max(y);
miny=min(y);
rangey=maxy-miny;
ymin=miny-rangey/50;
ymax=maxy+rangey/50;
plot([(miny-cy)/sigma (maxy-cy)/sigma],[miny maxy],'r-.') % the line
% For normally distributed data, the slope of the plot line
% is equal to the ratio of the standard deviation of the distributions
plot([0 (maxy-mean(y))/std(y)],[mean(y) maxy],'k-.') % the ideal line
xlim=get(gca,'XLim');
plot([1 1],[ymin mean(y)+std(y)],'k--')
plot([1 1],[mean(y) mean(y)+std(y)],'k-','LineWidth',2)
% textx = 1.0;
% texty = mean(y)+3.0*rangey/50.0;
% text(double(textx), double(texty),' St. Dev.','horizontalalignment','center')
set(gca,'xtick',get(gca,'xtick')); % show that vertical line is at 1 sd
plot([0 0],[ymin mean(y)],'k--')
plot(xlim,[mean(y) mean(y)],'k--')
% text(double(xlim(1)), double(mean(y)+rangey/50),'Mean X')
plot([xqrt1 xqrt3],[yqrt1 yqrt3],'k.','MarkerSize',10)
set(gca,'XLim',[xmin xmax],'YLim',[ymin ymax])
xlabel('Standard Normal Quantiles')
ylabel('X Quantiles')
else
cx=(xqrt1 + xqrt3)/2;
maxy=cy+sigma*(max(x)-cx);
miny=cy-sigma*(cx-min(x));
plot([min(x) max(x)],[miny maxy],'r-.'); % the line
xlabel('X Quantiles');
ylabel('Y Quantiles');
end
|
github
|
lcnbeapp/beapp-master
|
loaddat.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/loaddat.m
| 1,775 |
utf_8
|
7d7aa4df464e400f37de47be51520ea6
|
% loaddat() - loading neuroscan format data file into matlab.
%
% Usage:
% >> [typeeeg, rt, response, n] = loaddat( filename );
%
% Inputs:
% filename - input Neuroscan .dat file
%
% Outputs:
% typeeeg - type of the sweeps
% rt - reaction time of the subject
% response - response of the subject
% n - number of sweeps
%
% See also: loadeeg()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [tmptypeeeg, tmprt, tmpresponseeeg, n] = loaddat( FILENAME)
if nargin<1
fprintf('Not enought arguments\n');
help loaddat
return;
end;
BOOL='int16';
ULONG='int32';
FLOAT='float32';
fid=fopen(FILENAME,'r','ieee-le');
if fid<0
fprintf(2,['Error LOADEEG: File ' FILENAME ' not found\n']);
return;
end;
% skip the first 20 lines
% -----------------------
for index=1:20 fgetl(fid); end;
% read the matrix
% ---------------
tmpMat = fscanf(fid, '%f', [5, inf]);
tmptypeeeg = tmpMat(3,:);
tmpresponseeeg = tmpMat(4,:);
tmprt = tmpMat(5,:);
n = size( tmpMat, 2);
fclose(fid);
return;
|
github
|
lcnbeapp/beapp-master
|
cbar.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/cbar.m
| 6,149 |
utf_8
|
d94610ba8d3cbc14b360527461547953
|
% cbar() - Display full or partial color bar
%
% Usage:
% >> cbar % create a vertical cbar on the right side of a figure
% >> cbar(type) % specify direction as 'vert' or 'horiz'
% >> cbar(type,colors) % specify which colormap colors to plot
% else
% >> cbar(axhandle) % specify the axes to draw cbar in
%
% >> h = cbar(type|axhandle,colors, minmax, grad)
%
% Inputs:
% type - ['vert'|'horiz'] direction of the cbar {default: 'vert')
% ELSE axhandle = handle of axes to draw the cbar
% colors - vector of colormap indices to display, or integer to truncate upper
% limit by.
% (int n -> display colors [1:end-n]) {default: 0}
% minmax - [min, max] range of values to label on colorbar
% grad - [integer] number of tick labels. {default: 5}.
%
% Example:
% >> colormap('default') % default colormap is 64-color 'jet'
% >> cbar('vert',33:64); % plot a vertical cbar colored green->red
% % useful for showing >0 (warm) and 0 (green)
% % values only in a green=0 plot
%
% Author: Colin Humphries, Arnaud Delorme, CNL / Salk Institute, Feb. 1998-
%
% See also: colorbar()
% Copyright (C) Colin Humphries, CNL / Salk Institute, Feb. 1998
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 12-13-98 added minmax arg -Scott Makeig
% 01-25-02 reformated help & license, added links -ad
function [handle]=cbar(arg,colors,minmax, grad)
if nargin < 2
colors = 0;
end
posscale = 'off';
if nargin < 1
arg = 'vert';
ax = [];
else
if isempty(arg)
arg = 0;
end
if arg(1) == 0
ax = [];
arg = 'vert';
elseif strcmpi(arg, 'pos')
ax = [];
arg = 'vert';
posscale = 'on';
else
if ischar(arg)
ax = [];
else
ax = arg;
arg = [];
end
end
end
if nargin>2
if size(minmax,1) ~= 1 | size(minmax,2) ~= 2
help cbar
fprintf('cbar() : minmax arg must be [min,max]\n');
return
end
end
if nargin < 4
grad = 5;
end;
%obj = findobj('tag','cbar','parent',gcf);
%if ~isempty(obj) & ~isempty(arg)
% arg = [];
% ax = obj;
%end
try
icadefs;
catch
warning('cbar.m unable to find icadefs.m');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Choose colorbar position
%%%%%%%%%%%%%%%%%%%%%%%%%%%
if (length(colors) == 1) & (colors == 0)
t = caxis;
else
t = [0 1];
end
if ~isempty(arg)
if strcmp(arg,'vert')
cax = gca;
pos = get(cax,'Position');
stripe = 0.04;
edge = 0.01;
space = .02;
% set(cax,'Position',[pos(1) pos(2) pos(3)*(1-stripe-edge-space) pos(4)])
% rect = [pos(1)+(1-stripe-edge)*pos(3) pos(2) stripe*pos(3) pos(4)];
set(cax,'Position',[pos(1) pos(2) pos(3) pos(4)])
rect = [pos(1)+pos(3)+space pos(2) stripe*pos(3) pos(4)];
ax = axes('Position', rect);
elseif strcmp(arg,'horiz')
cax = gca;
pos = get(cax,'Position');
stripe = 0.075;
space = .1;
set(cax,'Position',...
[pos(1) pos(2)+(stripe+space)*pos(4) pos(3) (1-stripe-space)*pos(4)])
rect = [pos(1) pos(2) pos(3) stripe*pos(4)];
ax = axes('Position', rect);
end
else
pos = get(ax,'Position');
if pos(3) > pos(4)
arg = 'horiz';
else
arg = 'vert';
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Draw colorbar using image()
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if exist('DEFAULT_COLORMAP', 'var')
map = colormap(eval( [ DEFAULT_COLORMAP '(' int2str(max(size(colormap,1), max(colors))) ')' ]));
else
map = colormap;
end
n = size(map,1);
if length(colors) == 1
if strcmp(arg,'vert')
if strcmpi(posscale, 'on')
image([0 1],[0 t(2)],[ceil(n/2):n-colors]');
else
image([0 1],t,[1:n-colors]');
end;
set(ax,'xticklabelmode','manual')
set(ax,'xticklabel',[],'YAxisLocation','right')
else
image(t,[0 1],[1:n-colors]);
set(ax,'yticklabelmode','manual')
set(ax,'yticklabel',[],'YAxisLocation','right')
end
set(ax,'Ydir','normal','YAxisLocation','right')
else % length > 1
if max(colors) > n
error('Color vector excedes size of colormap')
end
if strcmp(arg,'vert')
image([0 1],t,[colors]');
set(ax,'xticklabelmode','manual')
set(ax,'xticklabel',[])
else
image([0 1],t,[colors]);
set(ax,'yticklabelmode','manual')
set(ax,'yticklabel',[],'YAxisLocation','right')
end
set(ax,'Ydir','normal','YAxisLocation','right')
end
%%%%%%%%%%%%%%%%%%%%%%%%%
% Adjust cbar ticklabels
%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin > 2
if strcmp(arg,'vert')
Cax = get(ax,'Ylim');
else
Cax = get(ax,'Xlim');
end;
CBTicks = [Cax(1):(Cax(2)-Cax(1))/(grad-1):Cax(2)]; % caxis tick positions
CBLabels = [minmax(1):(minmax(2)-minmax(1))/(grad-1):minmax(2)]; % tick labels
dec = floor(log10(max(abs(minmax)))); % decade of largest abs value
CBLabels = ([minmax]* [ linspace(1,0, grad);linspace(0, 1, grad)]);
%[1.0 .75 .50 .25 0.0; 0.0 .25 .50 .75 1.0]);
if dec<1
CBLabels = round(CBLabels*10^(1-dec))*10^(dec-1);
elseif dec == 1
CBLabels = round(CBLabels*10^(2-dec))*10^(dec-2);
else
CBLabels = round(CBLabels);
end
% minmax
% CBTicks
% CBLabels
if strcmp(arg,'vert')
set(ax,'Ytick',CBTicks);
set(ax,'Yticklabel',CBLabels);
else
set(ax,'Xtick',CBTicks);
set(ax,'Xticklabel',CBLabels);
end
end
handle = ax;
%%%%%%%%%%%%%%%%%%
% Adjust cbar tag
%%%%%%%%%%%%%%%%%%
set(ax,'tag','cbar');
if exist('DEFAULT_COLORMAP', 'var')
colormap(DEFAULT_COLORMAP);
end
|
github
|
lcnbeapp/beapp-master
|
readlocs.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/readlocs.m
| 33,881 |
utf_8
|
7e1d85669932dffeca11a8fad52e02ca
|
% readlocs() - read electrode location coordinates and other information from a file.
% Several standard file formats are supported. Users may also specify
% a custom column format. Defined format examples are given below
% (see File Formats).
% Usage:
% >> eloc = readlocs( filename );
% >> EEG.chanlocs = readlocs( filename, 'key', 'val', ... );
% >> [eloc, labels, theta, radius, indices] = ...
% readlocs( filename, 'key', 'val', ... );
% Inputs:
% filename - Name of the file containing the electrode locations
% {default: 2-D polar coordinates} (see >> help topoplot )
%
% Optional inputs:
% 'filetype' - ['loc'|'sph'|'sfp'|'xyz'|'asc'|'polhemus'|'besa'|'chanedit'|'custom']
% Type of the file to read. By default the file type is determined
% using the file extension (see below under File Formats),
% 'loc' an EEGLAB 2-D polar coordinates channel locations file
% Coordinates are theta and radius (see definitions below).
% 'sph' Matlab spherical coordinates (Note: spherical
% coordinates used by Matlab functions are different
% from spherical coordinates used by BESA - see below).
% 'sfp' EGI Cartesian coordinates (NOT Matlab Cartesian - see below).
% 'xyz' Matlab/EEGLAB Cartesian coordinates (NOT EGI Cartesian).
% z is toward nose; y is toward left ear; z is toward vertex
% 'asc' Neuroscan polar coordinates.
% 'polhemus' or 'polhemusx' - Polhemus electrode location file recorded
% with 'X' on sensor pointing to subject (see below and readelp()).
% 'polhemusy' - Polhemus electrode location file recorded with
% 'Y' on sensor pointing to subject (see below and readelp()).
% 'besa' BESA-'.elp' spherical coordinates. (Not MATLAB spherical -
% see below).
% 'chanedit' - EEGLAB channel location file created by pop_chanedit().
% 'custom' - Ascii file with columns in user-defined 'format' (see below).
% 'importmode' - ['eeglab'|'native'] for location files containing 3-D cartesian electrode
% coordinates, import either in EEGLAB format (nose pointing toward +X).
% This may not always be possible since EEGLAB might not be able to
% determine the nose direction for scanned electrode files. 'native' import
% original carthesian coordinates (user can then specify the position of
% the nose when calling the topoplot() function; in EEGLAB the position
% of the nose is stored in the EEG.chaninfo structure). {default 'eeglab'}
% 'format' - [cell array] Format of a 'custom' channel location file (see above).
% {default: if no file type is defined. The cell array contains
% labels defining the meaning of each column of the input file.
% 'channum' [positive integer] channel number.
% 'labels' [string] channel name (no spaces).
% 'theta' [real degrees] 2-D angle in polar coordinates.
% positive => rotating from nose (0) toward left ear
% 'radius' [real] radius for 2-D polar coords; 0.5 is the head
% disk radius and limit for topoplot() plotting).
% 'X' [real] Matlab-Cartesian X coordinate (to nose).
% 'Y' [real] Matlab-Cartesian Y coordinate (to left ear).
% 'Z' [real] Matlab-Cartesian Z coordinate (to vertex).
% '-X','-Y','-Z' Matlab-Cartesian coordinates pointing opposite
% to the above.
% 'sph_theta' [real degrees] Matlab spherical horizontal angle.
% positive => rotating from nose (0) toward left ear.
% 'sph_phi' [real degrees] Matlab spherical elevation angle.
% positive => rotating from horizontal (0) upwards.
% 'sph_radius' [real] distance from head center (unused).
% 'sph_phi_besa' [real degrees] BESA phi angle from vertical.
% positive => rotating from vertex (0) towards right ear.
% 'sph_theta_besa' [real degrees] BESA theta horiz/azimuthal angle.
% positive => rotating from right ear (0) toward nose.
% 'ignore' ignore column}.
% The input file may also contain other channel information fields.
% 'type' channel type: 'EEG', 'MEG', 'EMG', 'ECG', others ...
% 'calib' [real near 1.0] channel calibration value.
% 'gain' [real > 1] channel gain.
% 'custom1' custom field #1.
% 'custom2', 'custom3', 'custom4', etc. more custom fields
% 'skiplines' - [integer] Number of header lines to skip (in 'custom' file types only).
% Note: Characters on a line following '%' will be treated as comments.
% 'readchans' - [integer array] indices of electrodes to read. {default: all}
% 'center' - [(1,3) real array or 'auto'] center of xyz coordinates for conversion
% to spherical or polar, Specify the center of the sphere here, or 'auto'.
% This uses the center of the sphere that best fits all the electrode
% locations read. {default: [0 0 0]}
% Outputs:
% eloc - structure containing the channel names and locations (if present).
% It has three fields: 'eloc.labels', 'eloc.theta' and 'eloc.radius'
% identical in meaning to the EEGLAB struct 'EEG.chanlocs'.
% labels - cell array of strings giving the names of the electrodes. NOTE: Unlike the
% three outputs below, includes labels of channels *without* location info.
% theta - vector (in degrees) of polar angles of the electrode locations.
% radius - vector of polar-coordinate radii (arc_lengths) of the electrode locations
% indices - indices, k, of channels with non-empty 'locs(k).theta' coordinate
%
% File formats:
% If 'filetype' is unspecified, the file extension determines its type.
%
% '.loc' or '.locs' or '.eloc':
% polar coordinates. Notes: angles in degrees:
% right ear is 90; left ear -90; head disk radius is 0.5.
% Fields: N angle radius label
% Sample: 1 -18 .511 Fp1
% 2 18 .511 Fp2
% 3 -90 .256 C3
% 4 90 .256 C4
% ...
% Note: In previous releases, channel labels had to contain exactly
% four characters (spaces replaced by '.'). This format still works,
% though dots are no longer required.
% '.sph':
% Matlab spherical coordinates. Notes: theta is the azimuthal/horizontal angle
% in deg.: 0 is toward nose, 90 rotated to left ear. Following this, performs
% the elevation (phi). Angles in degrees.
% Fields: N theta phi label
% Sample: 1 18 -2 Fp1
% 2 -18 -2 Fp2
% 3 90 44 C3
% 4 -90 44 C4
% ...
% '.elc':
% Cartesian 3-D electrode coordinates scanned using the EETrak software.
% See readeetraklocs().
% '.elp':
% Polhemus-.'elp' Cartesian coordinates. By default, an .elp extension is read
% as PolhemusX-elp in which 'X' on the Polhemus sensor is pointed toward the
% subject. Polhemus files are not in columnar format (see readelp()).
% '.elp':
% BESA-'.elp' spherical coordinates: Need to specify 'filetype','besa'.
% The elevation angle (phi) is measured from the vertical axis. Positive
% rotation is toward right ear. Next, perform azimuthal/horizontal rotation
% (theta): 0 is toward right ear; 90 is toward nose, -90 toward occiput.
% Angles are in degrees. If labels are absent or weights are given in
% a last column, readlocs() adjusts for this. Default labels are E1, E2, ...
% Fields: Type label phi theta
% Sample: EEG Fp1 -92 -72
% EEG Fp2 92 72
% EEG C3 -46 0
% EEG C4 46 0
% ...
% '.xyz':
% Matlab/EEGLAB Cartesian coordinates. Here. x is towards the nose,
% y is towards the left ear, and z towards the vertex. Note that the first
% column (x) is -Y in a Matlab 3-D plot, the second column (y) is X in a
% matlab 3-D plot, and the third column (z) is Z.
% Fields: channum x y z label
% Sample: 1 .950 .308 -.035 Fp1
% 2 .950 -.308 -.035 Fp2
% 3 0 .719 .695 C3
% 4 0 -.719 .695 C4
% ...
% '.asc', '.dat':
% Neuroscan-.'asc' or '.dat' Cartesian polar coordinates text file.
% '.sfp':
% BESA/EGI-xyz Cartesian coordinates. Notes: For EGI, x is toward right ear,
% y is toward the nose, z is toward the vertex. EEGLAB converts EGI
% Cartesian coordinates to Matlab/EEGLAB xyz coordinates.
% Fields: label x y z
% Sample: Fp1 -.308 .950 -.035
% Fp2 .308 .950 -.035
% C3 -.719 0 .695
% C4 .719 0 .695
% ...
% '.ced':
% ASCII file saved by pop_chanedit(). Contains multiple MATLAB/EEGLAB formats.
% Cartesian coordinates are as in the 'xyz' format (above).
% Fields: channum label theta radius x y z sph_theta sph_phi ...
% Sample: 1 Fp1 -18 .511 .950 .308 -.035 18 -2 ...
% 2 Fp2 18 .511 .950 -.308 -.035 -18 -2 ...
% 3 C3 -90 .256 0 .719 .695 90 44 ...
% 4 C4 90 .256 0 -.719 .695 -90 44 ...
% ...
% The last columns of the file may contain any other defined fields (gain,
% calib, type, custom).
%
% Fieldtrip structure:
% If a Fieltrip structure is given as input, an EEGLAB
% chanlocs structure is returned
%
% Author: Arnaud Delorme, Salk Institute, 8 Dec 2002
%
% See also: readelp(), writelocs(), topo2sph(), sph2topo(), sph2cart()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 28 Feb 2002
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [eloc, labels, theta, radius, indices] = readlocs( filename, varargin );
if nargin < 1
help readlocs;
return;
end;
% NOTE: To add a new channel format:
% ----------------------------------
% 1) Add a new element to the structure 'chanformat' (see 'ADD NEW FORMATS HERE' below):
% 2) Enter a format 'type' for the new file format,
% 3) Enter a (short) 'typestring' description of the format
% 4) Enter a longer format 'description' (possibly multiline, see ex. (1) below)
% 5) Enter format file column labels in the 'importformat' field (see ex. (2) below)
% 6) Enter the number of header lines to skip (if any) in the 'skipline' field
% 7) Document the new channel format in the help message above.
% 8) After testing, please send the new version of readloca.m to us
% at [email protected] with a sample locs file.
% The 'chanformat' structure is also used (automatically) by the writelocs()
% and pop_readlocs() functions. You do not need to edit these functions.
chanformat(1).type = 'polhemus';
chanformat(1).typestring = 'Polhemus native .elp file';
chanformat(1).description = [ 'Polhemus native coordinate file containing scanned electrode positions. ' ...
'User must select the direction ' ...
'for the nose after importing the data file.' ];
chanformat(1).importformat = 'readelp() function';
% ---------------------------------------------------------------------------------------------------
chanformat(2).type = 'besa';
chanformat(2).typestring = 'BESA spherical .elp file';
chanformat(2).description = [ 'BESA spherical coordinate file. Note that BESA spherical coordinates ' ...
'are different from Matlab spherical coordinates' ];
chanformat(2).skipline = 0; % some BESA files do not have headers
chanformat(2).importformat = { 'type' 'labels' 'sph_theta_besa' 'sph_phi_besa' 'sph_radius' };
% ---------------------------------------------------------------------------------------------------
chanformat(3).type = 'xyz';
chanformat(3).typestring = 'Matlab .xyz file';
chanformat(3).description = [ 'Standard 3-D cartesian coordinate files with electrode labels in ' ...
'the first column and X, Y, and Z coordinates in columns 2, 3, and 4' ];
chanformat(3).importformat = { 'channum' '-Y' 'X' 'Z' 'labels'};
% ---------------------------------------------------------------------------------------------------
chanformat(4).type = 'sfp';
chanformat(4).typestring = 'BESA or EGI 3-D cartesian .sfp file';
chanformat(4).description = [ 'Standard BESA 3-D cartesian coordinate files with electrode labels in ' ...
'the first column and X, Y, and Z coordinates in columns 2, 3, and 4.' ...
'Coordinates are re-oriented to fit the EEGLAB standard of having the ' ...
'nose along the +X axis.' ];
chanformat(4).importformat = { 'labels' '-Y' 'X' 'Z' };
chanformat(4).skipline = 0;
% ---------------------------------------------------------------------------------------------------
chanformat(5).type = 'loc';
chanformat(5).typestring = 'EEGLAB polar .loc file';
chanformat(5).description = [ 'EEGLAB polar .loc file' ];
chanformat(5).importformat = { 'channum' 'theta' 'radius' 'labels' };
% ---------------------------------------------------------------------------------------------------
chanformat(6).type = 'sph';
chanformat(6).typestring = 'Matlab .sph spherical file';
chanformat(6).description = [ 'Standard 3-D spherical coordinate files in Matlab format' ];
chanformat(6).importformat = { 'channum' 'sph_theta' 'sph_phi' 'labels' };
% ---------------------------------------------------------------------------------------------------
chanformat(7).type = 'asc';
chanformat(7).typestring = 'Neuroscan polar .asc file';
chanformat(7).description = [ 'Neuroscan polar .asc file, automatically recentered to fit EEGLAB standard' ...
'of having ''Cz'' at (0,0).' ];
chanformat(7).importformat = 'readneurolocs';
% ---------------------------------------------------------------------------------------------------
chanformat(8).type = 'dat';
chanformat(8).typestring = 'Neuroscan 3-D .dat file';
chanformat(8).description = [ 'Neuroscan 3-D cartesian .dat file. Coordinates are re-oriented to fit ' ...
'the EEGLAB standard of having the nose along the +X axis.' ];
chanformat(8).importformat = 'readneurolocs';
% ---------------------------------------------------------------------------------------------------
chanformat(9).type = 'elc';
chanformat(9).typestring = 'ASA .elc 3-D file';
chanformat(9).description = [ 'ASA .elc 3-D coordinate file containing scanned electrode positions. ' ...
'User must select the direction ' ...
'for the nose after importing the data file.' ];
chanformat(9).importformat = 'readeetraklocs';
% ---------------------------------------------------------------------------------------------------
chanformat(10).type = 'chanedit';
chanformat(10).typestring = 'EEGLAB complete 3-D file';
chanformat(10).description = [ 'EEGLAB file containing polar, cartesian 3-D, and spherical 3-D ' ...
'electrode locations.' ];
chanformat(10).importformat = { 'channum' 'labels' 'theta' 'radius' 'X' 'Y' 'Z' 'sph_theta' 'sph_phi' ...
'sph_radius' 'type' };
chanformat(10).skipline = 1;
% ---------------------------------------------------------------------------------------------------
chanformat(11).type = 'custom';
chanformat(11).typestring = 'Custom file format';
chanformat(11).description = 'Custom ASCII file format where user can define content for each file columns.';
chanformat(11).importformat = '';
% ---------------------------------------------------------------------------------------------------
% ----- ADD MORE FORMATS HERE -----------------------------------------------------------------------
% ---------------------------------------------------------------------------------------------------
listcolformat = { 'labels' 'channum' 'theta' 'radius' 'sph_theta' 'sph_phi' ...
'sph_radius' 'sph_theta_besa' 'sph_phi_besa' 'gain' 'calib' 'type' ...
'X' 'Y' 'Z' '-X' '-Y' '-Z' 'custom1' 'custom2' 'custom3' 'custom4' 'ignore' 'not def' };
% ----------------------------------
% special mode for getting the info
% ----------------------------------
if isstr(filename) & strcmp(filename, 'getinfos')
eloc = chanformat;
labels = listcolformat;
return;
end;
g = finputcheck( varargin, ...
{ 'filetype' 'string' {} '';
'importmode' 'string' { 'eeglab','native' } 'eeglab';
'defaultelp' 'string' { 'besa','polhemus' } 'polhemus';
'skiplines' 'integer' [0 Inf] [];
'elecind' 'integer' [1 Inf] [];
'format' 'cell' [] {} }, 'readlocs');
if isstr(g), error(g); end;
if ~isempty(g.format), g.filetype = 'custom'; end;
if isstr(filename)
% format auto detection
% --------------------
if strcmpi(g.filetype, 'autodetect'), g.filetype = ''; end;
g.filetype = strtok(g.filetype);
periods = find(filename == '.');
fileextension = filename(periods(end)+1:end);
g.filetype = lower(g.filetype);
if isempty(g.filetype)
switch lower(fileextension),
case {'loc' 'locs' 'eloc'}, g.filetype = 'loc'; % 5/27/2014 Ramon: 'eloc' option introduced.
case 'xyz', g.filetype = 'xyz';
fprintf( [ 'WARNING: Matlab Cartesian coord. file extension (".xyz") detected.\n' ...
'If importing EGI Cartesian coords, force type "sfp" instead.\n'] );
case 'sph', g.filetype = 'sph';
case 'ced', g.filetype = 'chanedit';
case 'elp', g.filetype = g.defaultelp;
case 'asc', g.filetype = 'asc';
case 'dat', g.filetype = 'dat';
case 'elc', g.filetype = 'elc';
case 'eps', g.filetype = 'besa';
case 'sfp', g.filetype = 'sfp';
otherwise, g.filetype = '';
end;
fprintf('readlocs(): ''%s'' format assumed from file extension\n', g.filetype);
else
if strcmpi(g.filetype, 'locs'), g.filetype = 'loc'; end
if strcmpi(g.filetype, 'eloc'), g.filetype = 'loc'; end
end;
% assign format from filetype
% ---------------------------
if ~isempty(g.filetype) & ~strcmpi(g.filetype, 'custom') ...
& ~strcmpi(g.filetype, 'asc') & ~strcmpi(g.filetype, 'elc') & ~strcmpi(g.filetype, 'dat')
indexformat = strmatch(lower(g.filetype), { chanformat.type }, 'exact');
g.format = chanformat(indexformat).importformat;
if isempty(g.skiplines)
g.skiplines = chanformat(indexformat).skipline;
end;
if isempty(g.filetype)
error( ['readlocs() error: The filetype cannot be detected from the \n' ...
' file extension, and custom format not specified']);
end;
end;
% import file
% -----------
if strcmp(g.filetype, 'asc') | strcmp(g.filetype, 'dat')
eloc = readneurolocs( filename );
eloc = rmfield(eloc, 'sph_theta'); % for the conversion below
eloc = rmfield(eloc, 'sph_theta_besa'); % for the conversion below
if isfield(eloc, 'type')
for index = 1:length(eloc)
type = eloc(index).type;
if type == 69, eloc(index).type = 'EEG';
elseif type == 88, eloc(index).type = 'REF';
elseif type >= 76 & type <= 82, eloc(index).type = 'FID';
else eloc(index).type = num2str(eloc(index).type);
end;
end;
end;
elseif strcmp(g.filetype, 'elc')
eloc = readeetraklocs( filename );
%eloc = read_asa_elc( filename ); % from fieldtrip
%eloc = struct('labels', eloc.label, 'X', mattocell(eloc.pnt(:,1)'), 'Y', ...
% mattocell(eloc.pnt(:,2)'), 'Z', mattocell(eloc.pnt(:,3)'));
eloc = convertlocs(eloc, 'cart2all');
eloc = rmfield(eloc, 'sph_theta'); % for the conversion below
eloc = rmfield(eloc, 'sph_theta_besa'); % for the conversion below
elseif strcmp(lower(g.filetype(1:end-1)), 'polhemus') | ...
strcmp(g.filetype, 'polhemus')
try,
[eloc labels X Y Z]= readelp( filename );
if strcmp(g.filetype, 'polhemusy')
tmp = X; X = Y; Y = tmp;
end;
for index = 1:length( eloc )
eloc(index).X = X(index);
eloc(index).Y = Y(index);
eloc(index).Z = Z(index);
end;
catch,
disp('readlocs(): Could not read Polhemus coords. Trying to read BESA .elp file.');
[eloc, labels, theta, radius, indices] = readlocs( filename, 'defaultelp', 'besa', varargin{:} );
end;
else
% importing file
% --------------
if isempty(g.skiplines), g.skiplines = 0; end;
if strcmpi(g.filetype, 'chanedit')
array = loadtxt( filename, 'delim', 9, 'skipline', g.skiplines, 'blankcell', 'off');
else
array = load_file_or_array( filename, g.skiplines);
end;
if size(array,2) < length(g.format)
fprintf(['readlocs() warning: Fewer columns in the input than expected.\n' ...
' See >> help readlocs\n']);
elseif size(array,2) > length(g.format)
fprintf(['readlocs() warning: More columns in the input than expected.\n' ...
' See >> help readlocs\n']);
end;
% removing lines BESA
% -------------------
if isempty(array{1,2})
disp('BESA header detected, skipping three lines...');
array = load_file_or_array( filename, g.skiplines-1);
if isempty(array{1,2})
array = load_file_or_array( filename, g.skiplines-1);
end;
end;
% xyz format, is the first col absent
% -----------------------------------
if strcmp(g.filetype, 'xyz')
if size(array, 2) == 4
array(:, 2:5) = array(:, 1:4);
end;
end;
% removing comments and empty lines
% ---------------------------------
indexbeg = 1;
while isempty(array{indexbeg,1}) | ...
(isstr(array{indexbeg,1}) & array{indexbeg,1}(1) == '%' )
indexbeg = indexbeg+1;
end;
array = array(indexbeg:end,:);
% converting file
% ---------------
for indexcol = 1:min(size(array,2), length(g.format))
[str mult] = checkformat(g.format{indexcol});
for indexrow = 1:size( array, 1)
if mult ~= 1
eval ( [ 'eloc(indexrow).' str '= -array{indexrow, indexcol};' ]);
else
eval ( [ 'eloc(indexrow).' str '= array{indexrow, indexcol};' ]);
end;
end;
end;
end;
% handling BESA coordinates
% -------------------------
if isfield(eloc, 'sph_theta_besa')
if isfield(eloc, 'type')
if isnumeric(eloc(1).type)
disp('BESA format detected ( Theta | Phi )');
for index = 1:length(eloc)
eloc(index).sph_phi_besa = eloc(index).labels;
eloc(index).sph_theta_besa = eloc(index).type;
eloc(index).labels = '';
eloc(index).type = '';
end;
eloc = rmfield(eloc, 'labels');
end;
end;
if isfield(eloc, 'labels')
if isnumeric(eloc(1).labels)
disp('BESA format detected ( Elec | Theta | Phi )');
for index = 1:length(eloc)
eloc(index).sph_phi_besa = eloc(index).sph_theta_besa;
eloc(index).sph_theta_besa = eloc(index).labels;
eloc(index).labels = eloc(index).type;
eloc(index).type = '';
eloc(index).radius = 1;
end;
end;
end;
try
eloc = convertlocs(eloc, 'sphbesa2all');
eloc = convertlocs(eloc, 'topo2all'); % problem with some EGI files (not BESA files)
catch, disp('Warning: coordinate conversion failed'); end;
fprintf('Readlocs: BESA spherical coords. converted, now deleting BESA fields\n');
fprintf(' to avoid confusion (these fields can be exported, though)\n');
eloc = rmfield(eloc, 'sph_phi_besa');
eloc = rmfield(eloc, 'sph_theta_besa');
% converting XYZ coordinates to polar
% -----------------------------------
elseif isfield(eloc, 'sph_theta')
try
eloc = convertlocs(eloc, 'sph2all');
catch, disp('Warning: coordinate conversion failed'); end;
elseif isfield(eloc, 'X')
try
eloc = convertlocs(eloc, 'cart2all');
catch, disp('Warning: coordinate conversion failed'); end;
else
try
eloc = convertlocs(eloc, 'topo2all');
catch, disp('Warning: coordinate conversion failed'); end;
end;
% inserting labels if no labels
% -----------------------------
if ~isfield(eloc, 'labels')
fprintf('readlocs(): Inserting electrode labels automatically.\n');
for index = 1:length(eloc)
eloc(index).labels = [ 'E' int2str(index) ];
end;
else
% remove trailing '.'
for index = 1:length(eloc)
if isstr(eloc(index).labels)
tmpdots = find( eloc(index).labels == '.' );
eloc(index).labels(tmpdots) = [];
end;
end;
end;
% resorting electrodes if number not-sorted
% -----------------------------------------
if isfield(eloc, 'channum')
if ~isnumeric(eloc(1).channum)
error('Channel numbers must be numeric');
end;
allchannum = [ eloc.channum ];
if any( sort(allchannum) ~= allchannum )
fprintf('readlocs(): Re-sorting channel numbers based on ''channum'' column indices\n');
[tmp newindices] = sort(allchannum);
eloc = eloc(newindices);
end;
eloc = rmfield(eloc, 'channum');
end;
else
if isstruct(filename)
% detect Fieldtrip structure and convert it
% -----------------------------------------
if isfield(filename, 'pnt')
neweloc = [];
for index = 1:length(filename.label)
neweloc(index).labels = filename.label{index};
neweloc(index).X = filename.pnt(index,1);
neweloc(index).Y = filename.pnt(index,2);
neweloc(index).Z = filename.pnt(index,3);
end;
eloc = neweloc;
eloc = convertlocs(eloc, 'cart2all');
else
eloc = filename;
end;
else
disp('readlocs(): input variable must be a string or a structure');
end;
end;
if ~isempty(g.elecind)
eloc = eloc(g.elecind);
end;
if nargout > 2
if isfield(eloc, 'theta')
tmptheta = { eloc.theta }; % check which channels have (polar) coordinates set
else tmptheta = cell(1,length(eloc));
end;
if isfield(eloc, 'theta')
tmpx = { eloc.X }; % check which channels have (polar) coordinates set
else tmpx = cell(1,length(eloc));
end;
indices = find(~cellfun('isempty', tmptheta));
indices = intersect_bc(find(~cellfun('isempty', tmpx)), indices);
indices = sort(indices);
indbad = setdiff_bc(1:length(eloc), indices);
tmptheta(indbad) = { NaN };
theta = [ tmptheta{:} ];
end;
if nargout > 3
if isfield(eloc, 'theta')
tmprad = { eloc.radius }; % check which channels have (polar) coordinates set
else tmprad = cell(1,length(eloc));
end;
tmprad(indbad) = { NaN };
radius = [ tmprad{:} ];
end;
%tmpnum = find(~cellfun('isclass', { eloc.labels }, 'char'));
%disp('Converting channel labels to string');
for index = 1:length(eloc)
if ~isstr(eloc(index).labels)
eloc(index).labels = int2str(eloc(index).labels);
end;
end;
labels = { eloc.labels };
if isfield(eloc, 'ignore')
eloc = rmfield(eloc, 'ignore');
end;
% process fiducials if any
% ------------------------
fidnames = { 'nz' 'lpa' 'rpa' 'nasion' 'left' 'right' 'nazion' 'fidnz' 'fidt9' 'fidt10' 'cms' 'drl' };
for index = 1:length(fidnames)
ind = strmatch(fidnames{index}, lower(labels), 'exact');
if ~isempty(ind), eloc(ind).type = 'FID'; end;
end;
return;
% interpret the variable name
% ---------------------------
function array = load_file_or_array( varname, skiplines );
if isempty(skiplines),
skiplines = 0;
end;
if exist( varname ) == 2
array = loadtxt(varname,'verbose','off','skipline',skiplines,'blankcell','off');
else % variable in the global workspace
% --------------------------
try, array = evalin('base', varname);
catch, error('readlocs(): cannot find the named file or variable, check syntax');
end;
end;
return;
% check field format
% ------------------
function [str, mult] = checkformat(str)
mult = 1;
if strcmpi(str, 'labels'), str = lower(str); return; end;
if strcmpi(str, 'channum'), str = lower(str); return; end;
if strcmpi(str, 'theta'), str = lower(str); return; end;
if strcmpi(str, 'radius'), str = lower(str); return; end;
if strcmpi(str, 'ignore'), str = lower(str); return; end;
if strcmpi(str, 'sph_theta'), str = lower(str); return; end;
if strcmpi(str, 'sph_phi'), str = lower(str); return; end;
if strcmpi(str, 'sph_radius'), str = lower(str); return; end;
if strcmpi(str, 'sph_theta_besa'), str = lower(str); return; end;
if strcmpi(str, 'sph_phi_besa'), str = lower(str); return; end;
if strcmpi(str, 'gain'), str = lower(str); return; end;
if strcmpi(str, 'calib'), str = lower(str); return; end;
if strcmpi(str, 'type') , str = lower(str); return; end;
if strcmpi(str, 'X'), str = upper(str); return; end;
if strcmpi(str, 'Y'), str = upper(str); return; end;
if strcmpi(str, 'Z'), str = upper(str); return; end;
if strcmpi(str, '-X'), str = upper(str(2:end)); mult = -1; return; end;
if strcmpi(str, '-Y'), str = upper(str(2:end)); mult = -1; return; end;
if strcmpi(str, '-Z'), str = upper(str(2:end)); mult = -1; return; end;
if strcmpi(str, 'custom1'), return; end;
if strcmpi(str, 'custom2'), return; end;
if strcmpi(str, 'custom3'), return; end;
if strcmpi(str, 'custom4'), return; end;
error(['readlocs(): undefined field ''' str '''']);
|
github
|
lcnbeapp/beapp-master
|
erpimage.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/erpimage.m
| 157,376 |
utf_8
|
deef1ab9cf000fdabbc8e026c72c4366
|
% erpimage() - Plot a colored image of a collection of single-trial data epochs, optionally
% sorted on and/or aligned to an input sorting variable and smoothed across
% trials with a Gaussian weighted moving-average. (To return event-aligned data
% without plotting, use eegalign()). Optionally sort trials on value, amplitude
% or phase within a specified latency window. Optionally plot the ERP mean
% and std. dev.and moving-window spectral amplitude and inter-trial coherence
% at aselected or peak frequency. Optionally 'time warp' the single trial
% time-domain (potential) or power data to align the plotted data to a series
% of events with varying latencies that occur in each trial. Click on
% individual figures parts to examine them separately and zoom (using axcopy()).
% Usage:
% >> figure; erpimage(data,[],times); % image trials as colored lines in input order
%
% >> figure; [outdata,outvar,outtrials,limits,axhndls, ...
% erp,amps,cohers,cohsig,ampsig,outamps,...
% phsangls,phsamp,sortidx,erpsig] ...
% = erpimage(data,sortvar,times,'title',avewidth,decimate,...
% 'key', 'val', ...); % use options
% Required input:
% data = [vector or matrix] Single-channel input data to image.
% Formats (1,frames*trials) or (frames,trials)
%
% Optional ordered inputs {with defaults}:
%
% sortvar = [vector | []] Variable to sort epochs on (length(sortvar) = nepochs)
% Example: sortvar may by subject response time in each epoch (in ms)
% {default|[]: plot in input order}
% times = [vector | []] vector of latencies (in ms) for each epoch time point.
% Else [startms ntimes srate] = [start latency (ms), time points
% (=frames) per epoch, sampling rate (Hz)]. Else [] -> 0:nframes-1
% {default: []}
% 'title' = ['string'] Plot title {default: none}
% avewidth = [positive scalar (may be non-integer)]. If avg_type is set to 'boxcar'
% (the default), this is the number of trials used to smooth
% (vertically) with a moving-average. If avg_type is set to
% 'Gaussian,' this is the standard deviation (in units of
% trials) of the Gaussian window used to smooth (vertically)
% with a moving-average. Gaussian window extends three
% standard deviations below and three standard deviations above window
% center (trials beyond window are not incorporated into average). {default: no
% smoothing}
% decimate = Factor to decimate|interpolate ntrials by (may be non-integer)
% Else, if this is large (> sqrt(ntrials)), output this many epochs.
% {default|0->1}
%
% Optional unordered 'keyword',argument pairs:
%
% Re-align data epochs:
% 'align' = [latency] Time-lock data to sortvar. Plot sortvar at given latency
% (in ms). Else Inf -> plot sortvar at median sortvar latency
% {default: do not align}
% 'timewarp' = {[events], [warpms], {colors}} Time warp ERP, amplitude and phase
% time-courses before smoothing. 'events' is a matrix whose columns
% specify the latencies (in ms) at which a series of successive events occur
% in each trial. 'warpms' is an optional vector of latencies (in ms) to which
% the series of events should be time locked. (Note: Epoch start and end
% should not be declared as events or warpms}. If 'warpms' is absent or [],
% the median of each 'events' column will be used. {colors} contains a
% list of Matlab linestyles to use for vertical lines marking the occurrence
% of the time warped events. If '', no line will be drawn for this event
% column. If fewer colors than event columns, cycles through the given color
% labels. Note: Not compatible with 'vert' (below).
% 'renorm' = ['yes'|'no'| formula] Normalize sorting variable to epoch
% latency range and plot. 'yes'= autoscale. formula must be a linear
% transformation in the format 'a*x+b'
% Example of formula: '3*x+2'. {default: 'no'}
% If sorting by string values like event type, suggested formulas for:
% letter string: '1000*x', number string: '30000*x-1500'
% 'noplot' = ['on'|'off'] Do not plot sortvar {default: Plot sortvar if in times range}
% 'NoShow' = ['on'|'off'] Do not plot erpimage, simply return outputs {default: 'off'}
%
% Sort data epochs:
% 'nosort' = ['on'|'off'] Do not sort data epochs. {default: Sort data epochs by
% sortvar (see sortvar input above)}
% 'replace_ties' = ['yes'|'no'] Replace trials with the same value of
% sortvar with the mean of those trials. Only works if sorting trials
% by sortvar. {default: 'no'}
% 'valsort' = [startms endms direction] Sort data on (mean) value
% between startms and (optional) endms. Direction is 1 or -1.
% If -1, plot max-value epoch at bottom {default: sort on sortvar}
% 'phasesort' = [ms_center prct freq maxfreq topphase] Sort epochs by phase in
% a 3-cycle window centered at latency ms_center (ms).
% Percentile (prct) in range [0,100] gives percent of trials
% to reject for (too) low amplitude. Else, if in range [-100,0],
% percent of trials to reject for (too) high amplitude;
% freq (Hz) is the phase-sorting frequency. With optional
% maxfreq, sort by phase at freq of max power in the data in
% the range [freq,maxfreq] (Note: 'phasesort' arg freq overrides
% the frequency specified in 'coher'). With optional topphase,
% sort by phase, putting topphase (degrees, in range [-180,180])
% at the top of the image. Note: 'phasesort' now uses circular
% smoothing. Use 'cycles' (below) for wavelet length.
% {default: [0 25 8 13 180]}
% 'ampsort' = [center_ms prcnt freq maxfreq] Sort epochs by amplitude.
% (See 'phasesort' above). If ms_center is 'Inf', then sorting
% is by mean power across the time window specified by 'sortwin'
% below. If third arg, freq, is < 0, sort by mean power in the range
% [ abs(freq) maxfreq ].
% 'sortwin' = [start_ms end_ms] If center_ms == Inf in 'ampsort' arg (above), sorts
% by mean amplitude across window centers shifted from start_ms
% to end_ms by 10 ms.
% 'showwin' = ['on'|'off'] Show sorting window behind ERP trace. {default: 'off'}
%
% Plot time-varying spectral amplitude instead of potential:
% 'plotamps' = ['on'|'off'] Image amplitudes at each trial and latency instead of
% potential values. Note: Currently requires 'coher' (below) with alpha signif.
% Use 'cycles' (see below) > (its default) 3 for better frequency specificity,
% {default: plot potential, not amplitudes, with no minimum}. The average power
% (in log space) before time 0 is automatically removed. Note that the
% 'baseline' parameter has no effect on 'plotamps'. Instead use
% change "baselinedb" or "basedB" in the 'limits' parameter. By default
% the baseline is removed before time 0.
%
% Specify plot parameters:
% 'limits' = [lotime hitime minerp maxerp lodB hidB locoher hicoher basedB]
% Plot axes limits. Can use NaN (or nan, but not Nan) for missing items
% and omit late items. Use last input, basedB, to set the
% baseline dB amplitude in 'plotamps' plots {default: from data}
% 'sortvar_limits' = [min max] minimum and maximum sorting variable
% values to image. This only affects visualization of
% ERPimage and ERPs (not smoothing). Cannot be used
% if sorting by any factor besides sortvar (e.g.,
% phase).
% 'signif' = [lo_dB, hi_dB, coher_signif_level] Use precomputed significance
% thresholds (as from outputs ampsig, cohsig) to save time. {default: none}
% 'caxis' = [lo hi] Set color axis limits. Else [fraction] Set caxis limits at
% (+/-)fraction*max(abs(data)) {default: symmetrical in dB, based on data limits}
%
% Add epoch-mean ERP to plot:
% 'erp' = ['on'|'off'|1|2|3|4] Plot ERP time average of the trials below the
% image. If 'on' or 1, a single ERP (the mean of all trials) is shown. If 2,
% two ERPs (super and sub median trials) are shown. If 3, the trials are split into
% tertiles and their three ERPs are shown. If 4, the trials are split into quartiles
% and four ERPs are shown. Note, if you want negative voltage plotted up, change YDIR
% to -1 in icadefs.m. If 'erpalpha' option is used, any values of 'erp' greater than
% 1 will be reset to 1. {default no ERP plotted}
% 'erpalpha' = [alpha] Visualizes two-sided significance threshold (i.e., a two-tailed test) for the
% null hypothesis of a zero mean, symmetric distribution (range: [.001 0.1]). Thresholds
% are determined via a permutation test. Requires 'erp' to be a value other than 'off'.
% If 'erp' is set to a value greater than 1, it is reset to 1 to increase plot readability.
% {default: no alpha significance thresholds plotted}
% 'erpstd' = ['on'|'off'] Plot ERP +/- stdev. Requires 'erp' {default: no std. dev. plotted}
% 'erp_grid' = If 'erp_grid' is added as an option voltage axis dashed grid lines will be
% added to the ERP plot to facilitate judging ERP amplitude
% 'rmerp' = ['on'|'off'] Subtract the average ERP from each trial before processing {default: no}
%
% Add time/frequency information:
% 'coher' = [freq] Plot ERP average plus mean amplitude & coherence at freq (Hz)
% Else [minfrq maxfrq] = same, but select frequency with max power in
% given range. (Note: the 'phasesort' freq (above) overwrites these
% parameters). Else [minfrq maxfrq alpha] = plot coher. signif. level line
% at probability alpha (range: [0,0.1]) {default: no coher, no alpha level}
% 'srate' = [freq] Specify the data sampling rate in Hz for amp/coher (if not
% implicit in third arg, times) {default: as defined in icadefs.m}
% 'cycles' = [float] Number of cycles in the wavelet time/frequency decomposition {default: 3}
%
% Add plot features:
% 'cbar' = ['on'|'off'] Plot color bar to right of ERP-image {default no}
% 'cbar_title' = [string] The title for the color bar (e.g., '\muV' for
% microvolts).
% 'topo' = {map,chan_locs,eloc_info} Plot a 2-D scalp map at upper left of image.
% map may be a single integer, representing the plotted data channel,
% or a vector of scalp map channel values. chan_locs may be a channel locations
% file or a chanlocs structure (EEG.chanlocs). See '>> topoplot example'
% eloc_info (EEG.chaninfo), if empty ([]) or absent, implies the 'X' direction
% points towards the nose and all channels are plotted {default: no scalp map}
% 'spec' = [loHz,hiHz] Plot the mean data spectrum at upper right of image.
% 'specaxis' = ['log'|'lin] Use 'lin' for linear spectrum frequency scaling,
% else 'log' for log scaling {default: 'log'}
% 'horz' = [epochs_vector] Plot horizontal lines at specified epoch numbers.
% 'vert' = [times_vector] Plot vertical dashed lines at specified latencies
% 'auxvar' = [size(nvars,ntrials) matrix] Plot auxiliary variable(s) for each trial
% as separate traces. Else, 'auxvar',{[matrix],{colorstrings}}
% to specify N trace colors. Ex: colorstrings = {'r','bo-','','k:'}
% (see also: 'vert' and 'timewarp' above). {default: none}
% 'sortvarpercent' = [float vector] Plot percentiles for the sorting variable
% for instance, [0.1 0.5 0.9] plots the 10th percentile, the median
% and the 90th percentile.
% Plot options:
% 'noxlabel' = ['on'|'off'] Do not plot "Time (ms)" on the bottom x-axis
% 'yerplabel' = ['string'] ERP ordinate axis label (default is ERP). Print uV with '\muV'
% 'avg_type' = ['boxcar'|'Gaussian'] The type of moving average used to smooth
% the data. 'Boxcar' smoothes the data by simply taking the mean of
% a certain number of trials above and below each trial.
% 'Gaussian' does the same but first weights the trials
% according to a Gaussian distribution (e.g., nearby trials
% receive greater weight). The Gaussian is better than the
% boxcar in that it rather evenly filters out high frequency
% vertical components in the ERPimage. See 'avewidth' argument
% description for more information. {default: boxcar}
% 'img_trialax_label' = ['string'] The label of the axis corresponding to trials in the ERPimage
% (e.g., 'Reaction Time'). Note, if img_trialax_label is set to something
% besides 'Trials' or [], the tick marks on this axis will be set in units
% of the sorting variable. This is a useful alternative to plotting the
% sorting variable when the sorting variable is not in milliseconds. This
% option is not effective if sorting by amplitude, phase, or EEG value. {default: 'Trials'}
% 'img_trialax_ticks' = Vector of sorting variable values at which tick marks (e.g., [300 350 400 450]
% for reaction time in msec) will appear on the trial axis of the erpimage. Tick mark
% values should be given in units img_trialax_label (e.g., 'Trials' or msec).
% This option is not effective if sorting by amplitude, phase, or EEG value.
% {default: automatic}
% 'baseline' = [low_boundary high_boundary] a time window (in msec) whose mean amplitude in
% each trial will be removed from each trial (e.g., [-100 0]) after filtering.
% Useful in conjunction with 'filt' option to re-basline trials after they have been
% filtered. Not necessary if data have already been baselined and erpimage
% processing does not affect baseline amplitude {default: no further baselining
% of data}.
% 'baselinedb' = [low_boundary high_boundary] a time window (in msec) whose mean amplitude in
% each trial will be removed from each trial (e.g., [-100 0]). Use basedB in limits
% to remove a fixed value. Default is time before 0. If you do not want to use a
% baseline for amplitude plotting, enter a NaN value.
% 'filt' = [low_boundary high_boundary] a two element vector indicating the frequency
% cut-offs for a 3rd order Butterworth filter that will be applied to each
% trial of data. If low_boundary=0, the filter is a low pass filter. If
% high_boundary=srate/2, then the filter is a high pass filter. If both
% boundaries are between 0 and srate/2, then the filter is a bandpass filter.
% If both boundaries are between 0 and -srate/2, then the filter is a bandstop
% filter (with boundaries equal to the absolute values of low_boundary and
% high_boundary). Note, using this option requires the 'srate' option to be
% specified and the signal processing toolbox function butter.m. You should
% probably use the 'baseline' option as well since the mean prestimulus baseline
% may no longer be 0 after the filter is applied {default: no filtering}
%
% Optional outputs:
% outdata = (times,epochsout) data matrix (after smoothing)
% outvar = (1,epochsout) actual values trials are sorted on (after smoothing).
% if 'sortvarpercent' is used, this variable contains a cell array with
% { sorted_values { sorted_percent1 ... sorted_percentN } }
% outtrials = (1,epochsout) smoothed trial numbers
% limits = (1,10) array, 1-9 as in 'limits' above, then analysis frequency (Hz)
% axhndls = vector of 1-7 plot axes handles (img,cbar,erp,amp,coh,topo,spec)
% erp = plotted ERP average
% amps = mean amplitude time course
% coher = mean inter-trial phase coherence time course
% cohsig = coherence significance level
% ampsig = amplitude significance levels [lo high]
% outamps = matrix of imaged amplitudes (from option 'plotamps')
% phsangls = vector of sorted trial phases at the phase-sorting frequency
% phsamp = vector of sorted trial amplitudes at the phase-sorting frequency
% sortidx = indices of input data epochs in the sorting order
% erpsig = trial average significance levels [2,frames]
%
% Example: >> figure;
% erpimage(data,RTs,[-400 256 256],'Test',1,1,...
% 'erp','cbar','vert',-350);
% Plots an ERP-image of 1-s data epochs sampled at 256 Hz, sorted by RTs, with
% title ('Test'), and sorted epochs not smoothed or decimated (1,1). Overplots
% the (unsmoothed) RT latencies on the colored ERP-image. Also plots the
% epoch-mean (ERP), a color bar, and a dashed vertical line at -350 ms.
%
% Authors: Scott Makeig, Tzyy-Ping Jung & Arnaud Delorme,
% CNL/Salk Institute, La Jolla, 3-2-1998 -
%
% See also: phasecoher, rmbase, cbar, movav
% Copyright (C) Scott Makeig & Tzyy-Ping Jung, CNL / Salk Institute, La Jolla 3-2-98
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% Uses external toolbox functions: phasecoher(), rmbase(), cbar(), movav()
% Uses included functions: plot1trace(), phasedet()
% UNIMPLEMENTED - 'allcohers',[data2] -> image the coherences at each latency & epoch.
% Requires arg 'coher' with alpha significance.
% Shows projection on grand mean coherence vector at each latency
% and trial. {default: no}
%% LOG COMMENTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data,outsort,outtrials,limits,axhndls,erp,amps,cohers,cohsig,ampsig,allamps,phaseangles,phsamp,sortidx,erpsig] = erpimage(data,sortvar,times,titl,avewidth,decfactor,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11,arg12,arg13,arg14,arg15,arg16,arg17,arg18,arg19,arg20,arg21,arg22,arg23,arg24,arg25,arg26,arg27,arg28,arg29,arg30,arg31,arg32,arg33,arg34,arg35,arg36,arg37,arg38,arg39,arg40,arg41,arg42,arg43,arg44,arg45,arg46,arg47,arg48,arg49,arg50,arg51,arg52,arg53,arg54,arg55,arg56,arg57,arg58,arg59,arg60,arg61,arg62,arg63,arg64,arg65,arg66)
%
%% %%%%%%%%%%%%%%%%% Define defaults %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Initialize optional output variables:
warning off;
erp = []; amps = []; cohers = []; cohsig = []; ampsig = [];
allamps = []; phaseangles = []; phsamp = []; sortidx = [];
auxvar = []; erpsig = []; winloc = [];winlocs = [];
timeStretchColors = {};
YES = 1; % logical variables
NO = 0;
DEFAULT_BASELINE_END = 0; % ms
TIMEX = 1; % 1 -> plot time on x-axis;
% 0 -> plot trials on x-axis
BACKCOLOR = [0.8 0.8 0.8]; % grey background
try, icadefs; catch, end;
% read BACKCOLOR for plot from defs file (edit this)
% read DEFAULT_SRATE for coher,phase,allamps, etc.
% read YDIR for plotting ERP
% Fix plotting text and line style parameters
SORTWIDTH = 2.5; % Linewidth of plotted sortvar
ZEROWIDTH = 3.0; % Linewidth of vertical 0 line
VERTWIDTH = 2.5; % Linewidth of optional vertical lines
HORZWIDTH = 2.1; % Linewidth of optional vertical lines
SIGNIFWIDTH = 1.9; % Linewidth of red significance lines for amp, coher
DOTSTYLE = 'k--'; % line style to use for vetical dotted/dashed lines
LINESTYLE = '-'; % solid line
LABELFONT = 10; % font sizes for axis labels, tick labels
TICKFONT = 10;
PLOT_HEIGHT = 0.2; % fraction of y dim taken up by each time series axes
YGAP = 0.03; % fraction gap between time axes
YEXPAND = 1.3; % expansion factor for y-axis about erp, amp data limits
DEFAULT_SDEV = 1/7; % smooth trials with this window size by default if Gaussian window
DEFAULT_AVEWIDTH = 1; % smooth trials with this window size by default
DEFAULT_DECFACTOR = 1; % decimate by this factor by default
DEFAULT_CYCLES = 3; % use this many cycles in amp,coher computation window
cycles = DEFAULT_CYCLES;
DEFAULT_CBAR = NO;% do not plot color bar by default
DEFAULT_PHARGS = [0 25 8 13]; % Default arguments for phase sorting
DEFAULT_ALPHA = 0.01;
alpha = 0; % default alpha level for coherence significance
MIN_ERPALPHA = 0.001; % significance bounds for ERP
MAX_ERPALPHA = 0.1;
NoShowVar = NO; % show sortvar by default
Nosort = NO; % sort on sortvar by default
Caxflag = NO; % use default caxis by default
timestretchflag = NO; % Added -JH
mvavg_type='boxcar'; % use the original rectangular moving average -DG
erp_grid = NO; % add y-tick grids to ERP plot -DG
cbar_title = []; % title to add above ERPimage color bar (e.g., '\muV') -DG
img_ylab = 'Trials'; % make the ERPimage y-axis in units of the sorting variable -DG
img_ytick_lab = []; % the values at which tick marks will appear on the trial axis of the ERPimage (the y-axis by default).
%Note, this is in units of the sorting variable if img_ylab~='Trials', otherwise it is in units of trials -DG
baseline = []; %time window of each trial whose mean amp will be used to baseline the trial -DG
baselinedb = []; %time window of each trial whose mean power will be used to baseline the trial
flt=[]; %frequency domain filter parameters -DG
sortvar_limits=[]; %plotting limits for sorting variable/trials; limits only affect visualization, not smoothing -DG
replace_ties = NO; %if YES, trials with the exact same value of a sorting variable will be replaced by their average -DG
erp_vltg_ticks=[]; %if non-empty, these are the voltage axis ticks for the ERP plot
Caxis = [];
caxfraction = [];
Coherflag = NO; % don't compute or show amp,coher by default
Cohsigflag= NO; % default: do not compute coherence significance
Allampsflag=NO; % don't image the amplitudes by default
Allcohersflag=NO; % don't image the coherence amplitudes by default
Topoflag = NO; % don't plot a topoplot in upper left
Specflag = NO; % don't plot a spectrum in upper right
SpecAxisflag = NO; % don't change the default spectrum axis type from default
SpecAxis = 'log'; % default log frequency spectrum axis (if Specflag)
Erpflag = NO; % don't show erp average by default
Erpstdflag= NO;
Erpalphaflag= NO;
Alignflag = NO; % don't align data to sortvar by default
Colorbar = NO; % if YES, plot a colorbar to right of erp image
Limitflag = NO; % plot whole times range by default
Phaseflag = NO; % don't sort by phase
Ampflag = NO; % don't sort by amplitude
Sortwinflag = NO; % sort by amplitude over a window
Valflag = NO; % don't sort by value
Srateflag = NO; % srate not given
Vertflag = NO;
Horzflag = NO;
titleflag = NO;
NoShowflag = NO;
Renormflag = NO;
Showwin = NO;
yerplabel = 'ERP';
yerplabelflag = NO;
verttimes = [];
horzepochs = [];
NoTimeflag= NO; % by default DO print "Time (ms)" below bottom axis
Signifflag= NO; % compute significance instead of receiving it
Auxvarflag= NO;
plotmodeflag= NO;
plotmode = 'normal';
Cycleflag = NO;
signifs = NaN;
coherfreq = nan; % amp/coher-calculating frequency
freq = 0; % phase-sorting frequency
srate = DEFAULT_SRATE; % from icadefs.m
aligntime = nan;
timelimits= nan;
topomap = []; % topo map vector
lospecHz = []; % spec lo frequency
topphase = 180; % default top phase for 'phase' option
renorm = 'no';
NoShow = 'no';
Rmerp = 'no';
percentiles = [];
percentileflag = NO;
erp_ptiles = 1;
minerp = NaN; % default limits
maxerp = NaN;
minamp = NaN;
maxamp = NaN;
mincoh = NaN;
maxcoh = NaN;
baseamp =NaN;
allamps = []; % default return
ax1 = NaN; % default axes handles
axcb = NaN;
ax2 = NaN;
ax3 = NaN;
ax4 = NaN;
timeStretchRef = [];
timeStretchMarks = [];
tsurdata = []; % time-stretched data before smoothing (for timestretched-erp computation)
% If time-stretching is off, this variable remains empty
%
%% %%%%%%%%%%%%%%%%% Test, fill in commandline args %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if nargin < 1
help erpimage
return
end
data = squeeze(data);
if nargin < 3 | isempty(times)
if size(data,1)==1 || size(data,2)==1
fprintf('\nerpimage(): either input a times vector or make data size = (frames,trials).\n')
return
end
times = 1:size(data,1);
NoTimesPassed= 1;
end
if nargin < 2 | isempty(sortvar)
sortvar = 1:size(data,2);
NoShowVar = 1; % don't plot the dummy sortvar
end
framestot = size(data,1)*size(data,2);
ntrials = length(sortvar);
if ntrials < 2
help erpimage
fprintf('\nerpimage(): too few trials.\n');
return
end
frames = floor(framestot/ntrials);
if frames*ntrials ~= framestot
help erpimage
fprintf(...
'\nerpimage(); length of sortvar doesn''t divide number of data elements??\n')
return
end
if nargin < 6
decfactor = 0;
end
if nargin < 5
avewidth = DEFAULT_AVEWIDTH;
end
if nargin<4
titl = ''; % default no title
end
if nargin<3
times = NO;
end
if (length(times) == 1) | (times == NO), % make default times
times = 0:frames-1;
srate = 1000*(length(times)-1)/(times(length(times))-times(1));
fprintf('Using sampling rate %g Hz.\n',srate);
elseif length(times) == 3
mintime = times(1);
frames = times(2);
srate = times(3);
times = mintime:1000/srate:mintime+(frames-1)*1000/srate;
fprintf('Using sampling rate %g Hz.\n',srate);
else
% Note: might use default srate read from icadefs here...
srate = 1000*(length(times)-1)/(times(end)-times(1));
end
if length(times) ~= frames
fprintf(...
'\nerpimage(): length(data)(%d) ~= length(sortvar)(%d) * length(times)(%d).\n\n',...
framestot, length(sortvar), length(times));
return
end
if decfactor == 0,
decfactor = DEFAULT_DECFACTOR;
elseif decfactor > ntrials
fprintf('Setting variable decfactor to max %d.\n',ntrials)
decfactor = ntrials;
end
%
%% %%%%%%%%%%%%%%% Collect optional args %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if nargin > 6
flagargs = [];
a = 6;
while a < nargin % for each remaining Arg
a = a + 1;
Arg = eval(['arg' int2str(a-6)]);
if Caxflag == YES
if size(Arg,1) ~= 1 || size(Arg,2) > 2
help erpimage
fprintf('\nerpimage(): caxis arg must be a scalar or (1,2) vector.\n');
return
end
if size(Arg,2) == 2
Caxis = Arg;
else
caxfraction = Arg;
end
Caxflag = NO;
elseif timestretchflag == YES % Added -JH
timeStretchMarks = Arg{1};
timeStretchMarks = round(1+(timeStretchMarks-times(1))*srate/1000); % convert from ms to frames -sm
[smc smr] = find(diff(timeStretchMarks') < 0);
if ~isempty(smr)
fprintf('\nerpimage(): Timewarp event latencies not in ascending order in trial %d.\n',smr)
return
end
timeStretchMarks = [ ...
repmat(1, [size(timeStretchMarks,1), 1]), ...% Epoch begins
timeStretchMarks, ...
repmat(length(times), [size(timeStretchMarks,1), 1])]; % Epoch ends
if length(Arg) < 2 || isempty(Arg{2})
timeStretchRef = median(timeStretchMarks);
else
timeStretchRef = Arg{2};
timeStretchRef = round(1+(timeStretchRef-times(1))*srate/1000); % convert from ms to frames -sm
timeStretchRef = [1 timeStretchRef length(times)]; % add epoch beginning, end
end
if length(Arg) < 3 || isempty(Arg{3})
timeStretchColors = {};
else
timeStretchColors = Arg{3};
end
fprintf('The %d events specified in each trial will be time warped to latencies:',length(timeStretchRef)-2);
fprintf(' %.0f', times(1)+1000*(timeStretchRef(2:end-1)-1)/srate); % converted from frames to ms -sm
fprintf(' ms\n');
timestretchflag = NO;
elseif Coherflag == YES
if length(Arg) > 3 || length(Arg) < 1
help erpimage
fprintf('\nerpimage(): coher arg must be size <= 3.\n');
return
end
coherfreq = Arg(1);
if size(Arg,2) == 1
coherfreq = Arg(1);
else
coherfreq = Arg(1:2);
end;
if size(Arg,2) == 3
Cohsigflag = YES;
alpha = Arg(3);
if alpha < 0 || alpha > 0.1
fprintf('\nerpimage(): alpha value %g out of bounds.\n',alpha);
return
end
end
Coherflag = NO;
Erpflag = YES; % plot amp, coher below erp time series
elseif Topoflag == YES;
if length(Arg) < 2
help erpimage
fprintf('\nerpimage(): topo arg must be a list of length 2 or 3.\n');
return
end
topomap = Arg{1};
eloc_file = Arg{2};
if length(Arg) > 2, eloc_info = Arg{3};
else eloc_info = [];
end;
Topoflag = NO;
elseif Specflag == YES;
if length(Arg) ~= 2
error('\nerpimage(): ''spec'' flag argument must be a numeric array of length 2.\n');
return
end
lospecHz = Arg(1);
hispecHz = Arg(2);
Specflag = NO;
elseif SpecAxisflag == YES;
SpecAxis = Arg;
if ~strcmpi(SpecAxis,'lin') && ~strcmpi(SpecAxis,'log')
error('\nerpimage(): spectrum axis type must be ''lin'' or ''log''.\n');
return
end
if strcmpi(SpecAxis,'lin')
SpecAxis = 'linear'; % convert to MATLAB Xscale keyword
end
SpecAxisflag = NO;
elseif Renormflag == YES
renorm = Arg;
Renormflag = NO;
elseif NoShowflag == YES
NoShow = Arg;
if strcmpi(NoShow, 'off'), NoShow = 'no'; end;
NoShowflag = NO;
elseif Alignflag == YES
aligntime = Arg;
Alignflag = NO;
elseif percentileflag == YES
percentiles = Arg;
percentileflag = NO;
elseif Limitflag == YES
% [lotime hitime loerp hierp loamp hiamp locoher hicoher]
if size(Arg,1) ~= 1 || size(Arg,2) < 2 || size(Arg,2) > 9
help erpimage
fprintf('\nerpimage(): limits arg must be a vector sized (1,2<->9).\n');
return
end
if ~isnan(Arg(1)) & (Arg(2) <= Arg(1))
help erpimage
fprintf('\nerpimage(): time limits out of order or out of range.\n');
return
end
if Arg(1) < min(times)
Arg(1) = min(times);
fprintf('Adjusting mintime limit to first data value %g\n',min(times));
end
if Arg(2) > max(times)
Arg(2) = max(times);
fprintf('Adjusting maxtime limit to last data value %g\n',max(times));
end
timelimits = Arg(1:2);
if length(Arg)> 2
minerp = Arg(3);
end
if length(Arg)> 3
maxerp = Arg(4);
end
if ~isnan(maxerp) & maxerp <= minerp
help erpimage
fprintf('\nerpimage(): erp limits args out of order.\n');
return
end
if length(Arg)> 4
minamp = Arg(5);
end
if length(Arg)> 5
maxamp = Arg(6);
end
if maxamp <= minamp
help erpimage
fprintf('\nerpimage(): amp limits args out of order.\n');
return
end
if length(Arg)> 6
mincoh = Arg(7);
end
if length(Arg)> 7
maxcoh = Arg(8);
end
if maxcoh <= mincoh
help erpimage
fprintf('\nerpimage(): coh limits args out of order.\n');
return
end
if length(Arg)>8
baseamp = Arg(9); % for 'allamps'
end
Limitflag = NO;
elseif Srateflag == YES
srate = Arg(1);
Srateflag = NO;
elseif Cycleflag == YES
cycles = Arg;
Cycleflag = NO;
elseif Auxvarflag == YES;
if isa(Arg,'cell')==YES && length(Arg)==2
auxvar = Arg{1};
auxcolors = Arg{2};
elseif isa(Arg,'cell')==YES
fprintf('\nerpimage(): auxvars argument must be a matrix or length-2 cell array.\n');
return
else
auxvar = Arg; % no auxcolors specified
end
[xr,xc] = size(auxvar);
lns = length(sortvar);
if xr ~= lns && xc ~= lns
error('\nerpimage(): auxvar columns different from the number of epochs in data');
elseif xr == lns && xc ~= lns
auxvar = auxvar'; % exchange rows/cols
end
Auxvarflag = NO;
elseif Vertflag == YES
verttimes = Arg;
Vertflag = NO;
elseif Horzflag == YES
horzepochs = Arg;
Horzflag = NO;
elseif yerplabelflag == YES
yerplabel = Arg;
yerplabelflag = NO;
elseif Signifflag == YES
signifs = Arg; % [low_amp hi_amp coher]
if length(signifs) ~= 3
fprintf('\nerpimage(): signif arg [%g] must have 3 values\n',Arg);
return
end
Signifflag = NO;
elseif Allcohersflag == YES
data2=Arg;
if size(data2) ~= size(data)
fprintf('\nerpimage(): allcohers data matrix must be the same size as data.\n');
return
end
Allcohersflag = NO;
elseif Phaseflag == YES
n = length(Arg);
if n > 5
error('\nerpimage(): Too many arguments for keyword ''phasesort''');
end
phargs = Arg;
if phargs(3) < 0
error('\nerpimage(): Invalid negative frequency argument for keyword ''phasesort''');
end
if n>=4
if phargs(4) < 0
error('\nerpimage(): Invalid negative argument for keyword ''phasesort''');
end
end
if min(phargs(1)) < times(1) | max(phargs(1)) > times(end)
error('\nerpimage(): time for phase sorting filter out of bound.');
end
if phargs(2) >= 100 | phargs(2) < -100
error('\nerpimage(): %-argument for keyword ''phasesort'' must be (-100;100)');
end
if length(phargs) >= 4 & phargs(3) > phargs(4)
error('\nerpimage(): Phase sorting frequency range must be increasing.');
end
if length(phargs) == 5
topphase = phargs(5);
end
Phaseflag = NO;
elseif Sortwinflag == YES % 'ampsort' mean amplitude over a time window
n = length(Arg);
sortwinarg = Arg;
if n > 2
error('\nerpimage(): Too many arguments for keyword ''sortwin''');
end
if min(sortwinarg(1)) < times(1) | max(sortwinarg(1)) > times(end)
error('\nerpimage(): start time for value sorting out of bounds.');
end
if n > 1
if min(sortwinarg(2)) < times(1) | max(sortwinarg(2)) > times(end)
error('\nerpimage(): end time for value sorting out of bounds.');
end
end
if n > 1 & sortwinarg(1) > sortwinarg(2)
error('\nerpimage(): Value sorting time range must be increasing.');
end
Sortwinflag = NO;
elseif Ampflag == YES % 'ampsort',[center_time,prcnt_reject,minfreq,maxfreq]
n = length(Arg);
if n > 4
error('\nerpimage(): Too many arguments for keyword ''ampsort''');
end
ampargs = Arg;
% if ampargs(3) < 0
% error('\nerpimage(): Invalid negative argument for keyword ''ampsort''');
% end
if n>=4
if ampargs(4) < 0
error('\nerpimage(): Invalid negative argument for keyword ''ampsort''');
end
end
if ~isinf(ampargs(1))
if min(ampargs(1)) < times(1) | max(ampargs(1)) > times(end)
error('\nerpimage(): time for amplitude sorting filter out of bounds.');
end
end
if ampargs(2) >= 100 | ampargs(2) < -100
error('\nerpimage(): percentile argument for keyword ''ampsort'' must be (-100;100)');
end
if length(ampargs) == 4 & abs(ampargs(3)) > abs(ampargs(4))
error('\nerpimage(): Amplitude sorting frequency range must be increasing.');
end
Ampflag = NO;
elseif Valflag == YES % sort by potential value in a given window
% Usage: 'valsort',[mintime,maxtime,direction]
n = length(Arg);
if n > 3
error('\nerpimage(): Too many arguments for keyword ''valsort''');
end
valargs = Arg;
if min(valargs(1)) < times(1) | max(valargs(1)) > times(end)
error('\nerpimage(): start time for value sorting out of bounds.');
end
if n > 1
if min(valargs(2)) < times(1) | max(valargs(2)) > times(end)
error('\nerpimage(): end time for value sorting out of bounds.');
end
end
if n > 1 & valargs(1) > valargs(2)
error('\nerpimage(): Value sorting time range must be increasing.');
end
if n==3 & (~isnumeric(valargs(3)) | valargs(3)==0)
error('\nerpimage(): Value sorting direction must be +1 or -1.');
end
Valflag = NO;
elseif plotmodeflag == YES
plotmode = Arg; plotmodeflag = NO;
elseif titleflag == YES
titl = Arg; titleflag = NO;
elseif Erpalphaflag == YES
erpalpha = Arg(1);
if erpalpha < MIN_ERPALPHA | erpalpha > MAX_ERPALPHA
fprintf('\nerpimage(): erpalpha value is out of bounds [%g, %g]\n',...
MIN_ERPALPHA,MAX_ERPALPHA);
return
end
Erpalphaflag = NO;
% -----------------------------------------------------------------------
% -----------------------------------------------------------------------
% -----------------------------------------------------------------------
elseif strcmpi(Arg,'avg_type')
if a < nargin,
a=a+1;
Arg = eval(['arg' int2str(a-6)]);
if strcmpi(Arg, 'Gaussian'), mvavg_type='gaussian';
elseif strcmpi(Arg, 'Boxcar'), mvavg_type='boxcar';
else error('\nerpimage(): Invalid value for optional argument ''avg_type''.');
end;
else
error('\nerpimage(): Optional argument ''avg_type'' needs to be assigned a value.');
end
elseif strcmp(Arg,'nosort')
Nosort = YES;
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), Nosort = YES; a = a+1;
elseif strcmpi(Arg, 'off') Nosort = NO; a = a+1;
end;
end;
elseif strcmp(Arg,'showwin')
Showwin = YES;
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), Showwin = YES; a = a+1;
elseif strcmpi(Arg, 'off') Showwin = NO; a = a+1;
end;
end;
elseif strcmp(Arg,'noplot') % elseif strcmp(Arg,'NoShow') % by Luca & Ramon
NoShowVar = YES;
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), NoShowVar = YES; a = a+1;
elseif strcmpi(Arg, 'off'), NoShowVar = NO; a = a+1;
end;
end;
elseif strcmpi(Arg,'replace_ties')
if a < nargin,
a = a+1;
temp = eval(['arg' int2str(a-6)]);
if strcmpi(temp,'on'),
replace_ties = YES;
elseif strcmpi(temp,'off') replace_ties = NO;
else
error('\nerpimage(): Argument ''replace_ties'' needs to be followed by the string ''on'' or ''off''.');
end
else
error('\nerpimage(): Argument ''replace_ties'' needs to be followed by the string ''on'' or ''off''.');
end
elseif strcmpi(Arg,'sortvar_limits')
if a < nargin,
a = a+1;
sortvar_limits = eval(['arg' int2str(a-6)]);
if ischar(sortvar_limits) || length(sortvar_limits)~=2
error('\nerpimage(): Argument ''sortvar_limits'' needs to be followed by a two element vector.');
end
else
error('\nerpimage(): Argument ''sortvar_limits'' needs to be followed by a two element vector.');
end
elseif strcmpi(Arg,'erp')
Erpflag = YES;
erp_ptiles=1;
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), Erpflag = YES; erp_ptiles=1; a = a+1;
elseif strcmpi(Arg, 'off') Erpflag = NO; a = a+1;
elseif strcmpi(Arg,'1') | (Arg==1) Erplag = YES; erp_ptiles=1; a=a+1;
elseif strcmpi(Arg,'2') | (Arg==2) Erplag = YES; erp_ptiles=2; a=a+1;
elseif strcmpi(Arg,'3') | (Arg==3) Erplag = YES; erp_ptiles=3; a=a+1;
elseif strcmpi(Arg,'4') | (Arg==4) Erplag = YES; erp_ptiles=4; a=a+1;
end;
end;
elseif strcmpi(Arg,'rmerp')
Rmerp = 'yes';
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), Rmerp = 'yes'; a = a+1;
elseif strcmpi(Arg, 'off') Rmerp = 'no'; a = a+1;
end;
end;
elseif strcmp(Arg,'cbar') | strcmp(Arg,'colorbar')
Colorbar = YES;
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), Colorbar = YES; a = a+1;
elseif strcmpi(Arg, 'off') Colorbar = NO; a = a+1;
end;
end;
elseif (strcmp(Arg,'allamps') | strcmp(Arg,'plotamps'))
Allampsflag = YES;
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), Allampsflag = YES; a = a+1;
elseif strcmpi(Arg, 'off') Allampsflag = NO; a = a+1;
end;
end;
elseif strcmpi(Arg,'erpstd')
Erpstdflag = YES;
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), Erpstdflag = YES; a = a+1;
elseif strcmpi(Arg, 'off') Erpstdflag = NO; a = a+1;
end;
end;
elseif strcmp(Arg,'noxlabel') | strcmp(Arg,'noxlabels') | strcmp(Arg,'nox')
NoTimeflag = YES;
if a < nargin,
Arg = eval(['arg' int2str(a+1-6)]);
if strcmpi(Arg, 'on'), NoTimeflag = YES; a = a+1;
elseif strcmpi(Arg, 'off') NoTimeflag = NO; a = a+1;
end;
end;
elseif strcmp(Arg,'plotmode')
plotmodeflag = YES;
elseif strcmp(Arg,'sortvarpercent')
percentileflag = YES;
elseif strcmp(Arg,'renorm')
Renormflag = YES;
elseif strcmp(Arg,'NoShow')
NoShowflag = YES;
elseif strcmp(Arg,'caxis')
Caxflag = YES;
elseif strcmp(Arg,'title')
titleflag = YES;
elseif strcmp(Arg,'coher')
Coherflag = YES;
elseif strcmp(Arg,'timestretch') | strcmp(Arg,'timewarp') % Added -JH
timestretchflag = YES;
elseif strcmp(Arg,'allcohers')
Allcohersflag = YES;
elseif strcmp(Arg,'topo') | strcmp(Arg,'topoplot')
Topoflag = YES;
elseif strcmp(Arg,'spec') | strcmp(Arg,'spectrum')
Specflag = YES;
elseif strcmp(Arg,'Specaxis') || strcmp(Arg,'specaxis') || strcmp(Arg,'SpecAxis')
SpecAxisflag = YES;
elseif strcmpi(Arg,'erpalpha')
Erpalphaflag = YES;
elseif strcmp(Arg,'align')
Alignflag = YES;
elseif strcmp(Arg,'limits')
Limitflag = YES;
elseif (strcmp(Arg,'phase') | strcmp(Arg,'phasesort'))
Phaseflag = YES;
elseif strcmp(Arg,'ampsort')
Ampflag = YES;
elseif strcmp(Arg,'sortwin')
Sortwinflag = YES;
elseif strcmp(Arg,'valsort')
Valflag = YES;
elseif strcmp(Arg,'auxvar')
Auxvarflag = YES;
elseif strcmp(Arg,'cycles')
Cycleflag = YES;
elseif strcmpi(Arg,'yerplabel')
yerplabelflag = YES;
elseif strcmpi(Arg,'srate')
Srateflag = YES;
elseif strcmpi(Arg,'erp_grid')
erp_grid = YES;
elseif strcmpi(Arg,'baseline')
if a < nargin,
a = a+1;
baseline = eval(['arg' int2str(a-6)]);
else
error('\nerpimage(): Argument ''baseline'' needs to be followed by a two element vector.');
end
elseif strcmpi(Arg,'baselinedb')
if a < nargin,
a = a+1;
baselinedb = eval(['arg' int2str(a-6)]);
if length(baselinedb) > 2, error('''baselinedb'' need to be a 2 argument vector'); end;
else
error('\nerpimage(): Argument ''baselinedb'' needs to be followed by a two element vector.');
end
elseif strcmpi(Arg,'filt')
if a < nargin,
a = a+1;
flt = eval(['arg' int2str(a-6)]);
else
error('\nerpimage(): Argument ''filt'' needs to be followed by a two element vector.');
end
elseif strcmpi(Arg,'erp_vltg_ticks')
if a < nargin,
a = a+1;
erp_vltg_ticks=eval(['arg' int2str(a-6)]);
else
error('\nerpimage(): Argument ''erp_vltg_ticks'' needs to be followed by a vector.');
end
elseif strcmpi(Arg,'img_trialax_label')
if a < nargin,
a = a+1;
img_ylab = eval(['arg' int2str(a-6)]);
else
error('\nerpimage(): Argument ''img_trialax_label'' needs to be followed by a string.');
end;
elseif strcmpi(Arg,'img_trialax_ticks')
if a < nargin,
a = a+1;
img_ytick_lab = eval(['arg' int2str(a-6)]);
else
error('\nerpimage(): Argument ''img_trialax_ticks'' needs to be followed by a vector of values at which tick marks will appear.');
end;
elseif strcmpi(Arg,'cbar_title')
if a < nargin,
a = a+1;
cbar_title = eval(['arg' int2str(a-6)]);
else
error('\nerpimage(): Argument ''cbar_title'' needs to be followed by a string.');
end;
elseif strcmp(Arg,'vert') || strcmp(Arg,'verttimes')
Vertflag = YES;
elseif strcmp(Arg,'horz') || strcmp(Arg,'horiz') || strcmp(Arg,'horizontal')
Horzflag = YES;
elseif strcmp(Arg,'signif') || strcmp(Arg,'signifs') || strcmp(Arg,'sig') || strcmp(Arg,'sigs')
Signifflag = YES;
else
help erpimage
if isstr(Arg)
fprintf('\nerpimage(): unknown arg %s\n',Arg);
else
fprintf('\nerpimage(): unknown arg %d, size(%d,%d)\n',a,size(Arg,1),size(Arg,2));
end
return
end
end % Arg
end
if exist('img_ylab','var') || exist('img_ytick_lab','var'),
oops=0;
if exist('phargs','var'),
fprintf('********* Warning *********\n');
fprintf('Options ''img_ylab'' and ''img_ytick_lab'' have no effect when sorting by phase.\n');
oops=0;
elseif exist('valargs','var'),
fprintf('********* Warning *********\n');
fprintf('Options ''img_ylab'' and ''img_ytick_lab'' have no effect when sorting by EEG voltage.\n');
oops=0;
elseif exist('ampargs','var'),
fprintf('********* Warning *********\n');
fprintf('Options ''img_ylab'' and ''img_ytick_lab'' have no effect when sorting by frequency amplitude.\n');
oops=0;
end
if oops
img_ylab=[];
img_ytick_lab=[];
end
end
if Caxflag == YES ...
|Coherflag == YES ...
|Alignflag == YES ...
|Limitflag == YES
help erpimage
fprintf('\nerpimage(): missing option arg.\n')
return
end
if (Allampsflag | exist('data2')) & ( any(isnan(coherfreq)) | ~Cohsigflag )
fprintf('\nerpimage(): allamps and allcohers flags require coher freq, srate, and cohsig.\n');
return
end
if Allampsflag & exist('data2')
fprintf('\nerpimage(): cannot image both allamps and allcohers.\n');
return
end
if ~exist('srate') | srate <= 0
fprintf('\nerpimage(): Data srate must be specified and > 0.\n');
return
end
if ~isempty(auxvar)
% whos auxvar
if size(auxvar,1) ~= ntrials & size(auxvar,2) ~= ntrials
fprintf('\nerpimage(): auxvar size should be (N,ntrials), e.g., (N,%d)\n',...
ntrials);
return
end
if size(auxvar,1) == ntrials & size(auxvar,2) ~= ntrials % make (N,frames)
auxvar = auxvar';
end
if size(auxvar,2) ~= ntrials
fprintf('\nerpimage(): auxvar size should be (N,ntrials), e.g., (N,%d)\n',...
ntrials);
return
end
if exist('auxcolors')==YES % if specified
if isa(auxcolors,'cell')==NO % if auxcolors is not a cell array
fprintf(...
'\nerpimage(): auxcolors argument to auxvar flag must be a cell array.\n');
return
end
end
elseif exist('timeStretchRef') & ~isempty(timeStretchRef)
if ~isnan(aligntime)
fprintf(['\nerpimage(): options "align" and ' ...
'"timewarp" are not compatiable.\n']);
return;
end
if ~isempty(timeStretchColors)
if length(timeStretchColors) < length(timeStretchRef)
nColors = length(timeStretchColors);
for k=nColors+1:length(timeStretchRef)-2
timeStretchColors = { timeStretchColors{:} timeStretchColors{1+rem(k-1,nColors)}};
end
end
timeStretchColors = {'' timeStretchColors{:} ''};
else
timeStretchColors = { 'k--'};
for k=2:length(timeStretchRef)
timeStretchColors = { timeStretchColors{:} 'k--'};
end
end
auxvarInd = 1-strcmp('',timeStretchColors); % indicate which lines to draw
newauxvars = ((timeStretchRef(find(auxvarInd))-1)/srate+times(1)/1000) * 1000; % convert back to ms
fprintf('Overwriting vert with auxvar\n');
verttimes = [newauxvars'];
verttimesColors = {timeStretchColors{find(auxvarInd)}};
newauxvars = repmat(newauxvars, [1 ntrials]);
if isempty(auxvar) % Initialize auxvar & auxcolors
% auxvar = newauxvars;
auxcolors = {timeStretchColors{find(auxvarInd)}};
else % Append auxvar & auxcolors
if ~exist('auxcolors')
% Fill with default color (k-- for now)
auxcolors = {};
for j=1:size(auxvar,1)
auxcolors{end+1} = 'k--';
end
end
for j=find(auxvarInd)
auxcolors{end+1} = timeStretchColors{j};
end
auxvar = [auxvar; newauxvars];
end
end
% No need to turn off ERP anymore; we now time-stretch potentials
% separately (see tsurdata below) so the (warped) ERP is actually meaningful
if exist('phargs')
if phargs(3) > srate/2
fprintf(...
'\nerpimage(): Phase-sorting frequency (%g Hz) must be less than Nyquist rate (%g Hz).',...
phargs(3),srate/2);
end
if frames < cycles*srate/phargs(3)
fprintf('\nerpimage(): phase-sorting freq. (%g) too low: epoch length < %d cycles.\n',...
phargs(3),cycles);
return
end
if length(phargs)==4 & phargs(4) > srate/2
phargs(4) = srate/2;
end
if length(phargs)==5 & (phargs(5)>180 | phargs(5) < -180)
fprintf('\nerpimage(): coher topphase (%g) out of range.\n',topphase);
return
end
end
if exist('ampargs')
if abs(ampargs(3)) > srate/2
fprintf(...
'\nerpimage(): amplitude-sorting frequency (%g Hz) must be less than Nyquist rate (%g Hz).',...
abs(ampargs(3)),srate/2);
end
if frames < cycles*srate/abs(ampargs(3))
fprintf('\nerpimage(): amplitude-sorting freq. (%g) too low: epoch length < %d cycles.\n',...
abs(ampargs(3)),cycles);
return
end
if length(ampargs)==4 & abs(ampargs(4)) > srate/2
ampargs(4) = srate/2;
fprintf('> Reducing max ''ampsort'' frequency to Nyquist rate (%g Hz)\n',srate/2)
end
end
if ~any(isnan(coherfreq))
if coherfreq(1) <= 0 | srate <= 0
fprintf('\nerpimage(): coher frequency (%g) out of range.\n',coherfreq(1));
return
end
if coherfreq(end) > srate/2 | srate <= 0
fprintf('\nerpimage(): coher frequency (%g) out of range.\n',coherfreq(end));
return
end
if frames < cycles*srate/coherfreq(1)
fprintf('\nerpimage(): coher freq. (%g) too low: epoch length < %d cycles.\n',...
coherfreq(1),cycles);
return
end
end
if isnan(timelimits)
timelimits = [min(times) max(times)];
end
if ~isstr(aligntime) & ~isnan(aligntime)
if ~isinf(aligntime) ...
& (aligntime < timelimits(1) | aligntime > timelimits(2))
help erpimage
fprintf('\nerpimage(): requested align time outside of time limits.\n');
return
end
end
%
%% %%%%%%%%%%%%%% Replace nan's with 0s %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
nans = find(isnan(data));
if length(nans)
fprintf('Replaced %d nan in data with 0s.\n');
data(nans) = 0;
end
%
%% %%%%%%%%%%%% Reshape data to (frames,ntrials) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if size(data,2) ~= ntrials
if size(data,1)>1
% fprintf('frames %d, ntrials %d length(data) %d\n',frames,ntrials,length(data));
data=reshape(data,1,frames*ntrials);
end
data=reshape(data,frames,ntrials);
end
fprintf('Plotting input data as %d epochs of %d frames sampled at %3.1f Hz.\n',...
ntrials,frames,srate);
%
%% %%%%%%%%%%%% Reshape data2 to (frames,ntrials) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if exist('data2') == 1
if size(data2,2) ~= ntrials
if size(data2,1)>1
data2=reshape(data2,1,frames*ntrials);
end
data2=reshape(data2,frames,ntrials);
end
end
%
%% %%%%%%%%%%%%% if sortvar=NaN, remove lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -ad
%
if any(isnan(sortvar))
nanlocs = find(isnan(sortvar));
fprintf('Removing %d trials with NaN sortvar values.\n', length(nanlocs));
data(:,nanlocs) = [];
sortvar(nanlocs) = [];
if exist('data2') == 1
data2(:,nanlocs) = [];
end;
if ~isempty(auxvar)
auxvar(:,nanlocs) = [];
end
if ~isempty(verttimes)
if size(verttimes,1) == ntrials
verttimes(nanlocs,:) = [];
end;
end;
ntrials = size(data,2);
if ntrials <= 1, close(gcf); error('\nerpimage(): Too few trials'); end;
end;
%% Create moving average window %%
if strcmpi(mvavg_type,'Gaussian'),
%construct Gaussian window to weight trials
if avewidth == 0,
avewidth = DEFAULT_SDEV;
elseif avewidth < 1,
help erpimage
fprintf('\nerpimage(): Variable avewidth cannot be < 1.\n')
fprintf('\nerpimage(): avewidth needs to be a positive integer.\n')
return
end
wt_wind=exp(-0.5*([-3*avewidth:3*avewidth]/avewidth).^2)';
wt_wind=wt_wind/sum(wt_wind); %normalize to unit sum
avewidth=length(wt_wind);
if avewidth > ntrials
avewidth=floor((ntrials-1)/6);
if avewidth==0,
avewidth=DEFAULT_SDEV; %should be a window with one time point (smallest possible)
end
wt_wind=exp(-0.5*([-3*avewidth:3*avewidth]/avewidth).^2)';
wt_wind=wt_wind/sum(wt_wind);
fprintf('avewidth is too big for this number of trials.\n');
fprintf('Changing avewidth to maximum possible size: %d\n',avewidth);
avewidth=length(wt_wind);
end
else
%construct rectangular "boxcar" window to equally weight trials within
%window
if avewidth == 0,
avewidth = DEFAULT_AVEWIDTH;
elseif avewidth < 1
help erpimage
fprintf('\nerpimage(): Variable avewidth cannot be < 1.\n')
return
elseif avewidth > ntrials
fprintf('Setting variable avewidth to max %d.\n',ntrials)
avewidth = ntrials;
end
wt_wind=ones(1,avewidth)/avewidth;
end
%% Filter data with Butterworth filter (if requested) %%%%%%%%%%%%
%
if ~isempty(flt)
%error check
if length(flt)~=2,
error('\nerpimage(): ''filt'' parameter argument should be a two element vector.');
elseif max(flt)>(srate/2),
error('\nerpimage(): ''filt'' parameters need to be less than or equal to sampling rate/2 (i.e., %f).',srate/2);
elseif (flt(2)==(srate/2)) && (flt(1)==0),
error('\nerpimage(): If second element of ''filt'' parameter is srate/2, then the first element must be greater than 0.');
elseif abs(flt(2))<=abs(flt(1)),
error('\nerpimage(): Second element of ''filt'' parameters must be greater than first in absolute value.');
elseif (flt(1)<0) || (flt(2)<0),
if (flt(1)>=0) || (flt(2)>=0),
error('\nerpimage(): BOTH parameters of ''filt'' need to be greater than or equal to zero OR need to be negative.');
end
if min(flt)<=(-srate/2),
error('\nerpimage(): ''filt'' parameters need to be greater than sampling rate/2 (i.e., -%f) when creating a stop band.',srate/2);
end
end
fprintf('\nFiltering data with 3rd order Butterworth filter: ');
if (flt(1)==0),
%lowpass filter the data
[B A]=butter(3,flt(2)*2/srate,'low');
fprintf('lowpass at %.0f Hz\n',flt(2));
elseif (flt(2)==(srate/2)),
%highpass filter the data
[B A]=butter(3,flt(1)*2/srate,'high');
fprintf('highpass at %.0f Hz\n',flt(1));
elseif (flt(1)<0)
%bandstop filter the data
flt=-flt;
[B A]=butter(3,flt*2/srate,'stop');
fprintf('stopband from %.0f to %.0f Hz\n',flt(1),flt(2));
else
%bandpass filter the data
[B A]=butter(3,flt*2/srate);
fprintf('bandpass from %.0f to %.0f Hz\n',flt(1),flt(2));
end
s=size(data);
for trial=1:s(2),
data(:,trial)=filtfilt(B,A,double(data(:,trial)));
end
if isempty(baseline)
fprintf('Note, you might want to re-baseline the data using the erpimage ''baseline'' option.\n\n');
end
end
%% Mean Baseline Each Trial (if requested) %%
if ~isempty(baseline),
%check argument values for errors
if baseline(2)<baseline(1),
error('\nerpimage(): First element of ''baseline'' argument needs to be less than or equal to second argument.');
elseif baseline(2)<times(1),
error('\nerpimage(): Second element of ''baseline'' argument needs to be greater than or equal to epoch start time %.1f.',times(1));
elseif baseline(1)>times(end),
error('\nerpimage(): First element of ''baseline'' argument needs to be less than or equal to epoch end time %.1f.',times(end));
end
%convert msec into time points
if baseline(1)<times(1),
strt_pt=1;
else
strt_pt=find_crspnd_pt(baseline(1),times,1:length(times));
strt_pt=ceil(strt_pt);
end
if baseline(end)>times(end),
end_pt=length(times);
else
end_pt=find_crspnd_pt(baseline(2),times,1:length(times));
end_pt=floor(end_pt);
end
fprintf('\nRemoving pre-stimulus mean baseline from %.1f to %.1f msec.\n\n',times(strt_pt),times(end_pt));
bsln_mn=mean(data(strt_pt:end_pt,:),1);
data=data-repmat(bsln_mn,length(times),1);
end
%
%% %%%%%%%%%%%%%%%%% Renormalize sortvar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
switch lower(renorm)
case 'yes',
disp('\nerpimage warning: *** sorting variable renormalized ***');
sortvar = (sortvar-min(sortvar)) / (max(sortvar) - min(sortvar)) * ...
0.5 * (max(times) - min(times)) + min(times) + 0.4*(max(times) - min(times));
case 'no',;
otherwise,
if ~isempty(renorm)
locx = findstr('x', lower(renorm));
if length(locx) ~= 1, error('\nerpimage: unrecognized renormalizing formula'); end;
eval( [ 'sortvar =' renorm(1:locx-1) 'sortvar' renorm(locx+1:end) ';'] );
end;
end;
%
%% %%%%%%%%%%%%%%%%% Align data to sortvar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isstr(aligntime) | ~isnan(aligntime)
if ~isstr(aligntime) & isinf(aligntime)
aligntime= median(sortvar);
fprintf('Aligning data to median sortvar.\n');
% Alternative below: trimmed median - ignore top/bottom 5%
% ssv = sort(sortvar); % ssv = 'sorted sortvar'
% aligntime= median(ssv(ceil(ntrials/20)):floor(19*ntrials/20));
end
if ~isstr(aligntime)
fprintf('Realigned sortvar plotted at %g ms.\n',aligntime);
aligndata=zeros(frames,ntrials); % begin with matrix of zeros()
shifts = zeros(1,ntrials);
for t=1:ntrials, %%%%%%%%% foreach trial %%%%%%%%%
shft = round((aligntime-sortvar(t))*srate/1000);
shifts(t) = shft;
if shft>0, % shift right
if frames-shft > 0
aligndata(shft+1:frames,t)=data(1:frames-shft,t);
else
fprintf('No aligned data for epoch %d - shift (%d frames) too large.\n',t,shft);
end
elseif shft < 0 % shift left
if frames+shft > 0
aligndata(1:frames+shft,t)=data(1-shft:frames,t);
else
fprintf('No aligned data for epoch %d - shift (%d frames) too large.\n',t,shft);
end
else % shft == 0
aligndata(:,t) = data(:,t);
end
end % end trial
if ~isempty(auxvar)
auxvar = auxvar+shifts;
end;
fprintf('Shifted epochs by %d to %d frames.\n',min(shifts),max(shifts));
data = aligndata; % now data is aligned to sortvar
else
aligntime = str2num(aligntime);
if isinf(aligntime), aligntime= median(sortvar); end;
end;
end
%
%% %%%%%%%%%%%%%%%%%%%% Remove the ERP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(Rmerp, 'yes')
data = data - repmat(nan_mean(data')', [1 size(data,2)]);
end;
%
%% %%%%%%%%%%%%% Sort the data trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if exist('phargs') == 1 % if phase-sort the data trials
if length(phargs) >= 4 & phargs(3) ~= phargs(4) % find max frequency
% in specified band
if exist('psd') == 2 % requires Signal Processing Toolbox
fprintf('Computing data spectrum using psd().\n');
[pxx,freqs] = psd(data(:),max(1024, pow2(ceil(log2(frames)))),srate,frames,0);
else % EEGLAB native work-around
fprintf('Computing data spectrum using spec().\n');
[pxx,freqs] = spec(data(:),max(1024, pow2(ceil(log2(frames)))),srate,frames,0);
end;
% gf = gcf; % figure;plot(freqs,pxx); %xx=axis; %axis([phargs(3) phargs(4) xx(3) xx(4)]); %figure(gf);
pxx = 10*log10(pxx);
n = find(freqs >= phargs(3) & freqs <= phargs(4));
if ~length(n)
freq = (phargs(3)+phargs(4))/2;
end
[dummy maxx] = max(pxx(n));
freq = freqs(n(maxx));
else
freq = phargs(3); % else use specified frequency
end
fprintf('Sorting trials on phase at %.2g Hz.\n',freq);
[amps, cohers, cohsig, ampsig, allamps, allphs] = ...
phasecoher(data,length(times),srate,freq,cycles,0, ...
[], [], timeStretchRef, timeStretchMarks);
phwin = phargs(1);
[dummy minx] = min(abs(times-phwin)); % closest time to requested
winlen = floor(cycles*srate/freq);
winloc = minx-linspace(floor(winlen/2), floor(-winlen/2), winlen+1);
tmprange = find(winloc>0 & winloc<=frames);
winloc = winloc(tmprange); % sorting window times
winlocs = winloc;
%
%%%%%%%%%%%%%%%%%%%% Compute phsamp and phaseangles %%%%%%%%%%%%%%%%%%%%
%
% $$$ [phaseangles phsamp] = phasedet(data,frames,srate,winloc,freq);
phaseangles = allphs(minx,:);
phsamp = allamps(minx,:);
% $$$ % hist(phaseangles,50);
% $$$ % return
% $$$
% $$$ %
% $$$ % Print facts on commandline %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% $$$ %
% $$$ if length(tmprange) ~= winlen+1
% $$$ filtersize = cycles * length(tmprange) / (winlen+1);
% $$$ timecenter = median(winloc)/srate*1000+times(1); % center of window in ms
% $$$ phaseangles = phaseangles + 2*pi*(timecenter-phargs(1))*freq;
% $$$ fprintf('Sorting data epochs by phase at frequency %2.1f Hz: \n', freq);
% $$$ fprintf(...
% $$$ ' Data time limits reached -> now uses a %1.1f cycles (%1.0f ms) window centered at %1.0f ms\n', ...
% $$$ filtersize, 1000/freq*filtersize, timecenter);
% $$$ fprintf(...
% $$$ ' Filter length is %d; Phase has been linearly interpolated to latency at %1.0f ms.\n', ...
% $$$ length(winloc), phargs(1));
% $$$ else
% $$$ fprintf(...
% $$$ 'Sorting data epochs by phase at %2.1f Hz in a %1.1f-cycle (%1.0f ms) window centered at %1.0f ms.\n',...
% $$$ freq,cycles,1000/freq*cycles,times(minx));
% $$$ fprintf('Phase is computed using a wavelet of %d frames.\n',length(winloc));
% $$$ end;
%
% Reject small (or large) phsamp trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
phargs(2) = phargs(2)/100; % convert rejection rate from % to fraction
amprej = phargs(2);
[tmp ampsortidx] = sort(phsamp); % sort amplitudes
if amprej>=0
ampsortidx = ampsortidx(ceil(amprej*length(ampsortidx))+1:end); % if amprej==0, select all trials
fprintf('Retaining %d epochs (%g percent) with largest power at the analysis frequency,\n',...
length(ampsortidx),100*(1-amprej));
else % amprej < 0
amprej = 1+amprej; % subtract from end
ampsortidx = ampsortidx(1:floor(amprej*length(ampsortidx)));
fprintf('Retaining %d epochs (%g percent) with smallest power at the analysis frequency,\n',...
length(ampsortidx),amprej*100);
end
%
% Remove low|high-amplitude trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
data = data(:,ampsortidx); % amp-sort the data, removing rejected-amp trials
phsamp = phsamp(ampsortidx); % amp-sort the amps
phaseangles = phaseangles(ampsortidx); % amp-sort the phaseangles
sortvar = sortvar(ampsortidx); % amp-sort the trial indices
ntrials = length(ampsortidx); % number of trials retained
if ~isempty(auxvar)
auxvar = auxvar(:,ampsortidx);
end
if ~isempty(timeStretchMarks)
timeStretchMarks = timeStretchMarks(:,ampsortidx);
end
%
% Sort remaining data by phase angle %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
phaseangles = -phaseangles;
topphase = (topphase/360)*2*pi; % convert from degrees to radians
ip = find(phaseangles>topphase);
phaseangles(ip) = phaseangles(ip)-2*pi; % rotate so topphase at top of plot
[phaseangles sortidx] = sort(phaseangles); % sort trials on (rotated) phase
data = data(:,sortidx); % sort data by phase
phsamp = phsamp(sortidx); % sort amps by phase
sortvar = sortvar(sortidx); % sort input sortvar by phase
if ~isempty(auxvar)
auxvar = auxvar(:,sortidx);
end
if ~isempty(timeStretchMarks)
timeStretchMarks = timeStretchMarks(:,sortidx);
end
phaseangles = -phaseangles; % Note: phsangles now descend from pi
% TEST auxvar = 360 + (1000/256)*(256/5)*phaseangles/(2*pi); % plot phase+360 in ms for test
fprintf('Size of data = [%d,%d]\n',size(data,1),size(data,2));
sortidx = ampsortidx(sortidx); % return original trial indices in final sorted order
%
% %%%%%%%%%%%%%%% Sort data by amplitude %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif exist('ampargs') == 1 % if amplitude-sort
if length(ampargs) == 4 % find max frequency in specified band
if exist('psd') == 2
fprintf('Computing data spectrum using psd().\n');
[pxx,freqs] = psd(data(:),max(1024, pow2(ceil(log2(frames)))),srate,frames,0);
else
fprintf('Computing data spectrum using spec().\n');
[pxx,freqs] = spec(data(:),max(1024, pow2(ceil(log2(frames)))),srate,frames,0);
end;
pxx = 10*log10(pxx);
if ampargs(3) == ampargs(4)
[freq n] = min(abs(freqs - ampargs(3)));
else
n = find(freqs >= abs(ampargs(3)) & freqs <= abs(ampargs(4)));
end;
if ~length(n)
freq = mean([abs(ampargs(3)),abs(ampargs(4))]);
end
if ampargs(3)>=0
[dummy maxx] = max(pxx(n));
freq = freqs(n(maxx)); % use the highest-power frequency
else
freq = freqs(n); % use all frequencies in the specified range
end
else
freq = abs(ampargs(3)); % else use specified frequency
end
if length(freq) == 1
fprintf('Sorting data epochs by amplitude at frequency %2.1f Hz \n', freq);
else
fprintf('Sorting data epochs by amplitude at %d frequencies (%2.1f Hz to %.1f Hz) \n',...
length(freq),freq(1),freq(end));
end
SPECWININCR = 10; % make spectral sorting time windows increment by 10 ms
if isinf(ampargs(1))
ampwins = sortwinarg(1):SPECWININCR:sortwinarg(2);
else
ampwins = ampargs(1);
end
if ~isinf(ampargs(1)) % single time given
if length(freq) == 1
fprintf(' in a %1.1f-cycle (%1.0f ms) time window centered at %1.0f ms.\n',...
cycles,1000/freq(1)*cycles,ampargs(1));
else
fprintf(' in %1.1f-cycle (%1.0f-%1.0f ms) time windows centered at %1.0f ms.\n',...
cycles,1000/freq(1)*cycles,1000/freq(end)*cycles,ampargs(1));
end
else % range of times
[dummy sortwin_st ] = min(abs(times-ampwins(1)));
[dummy sortwin_end] = min(abs(times-ampwins(end)));
if length(freq) == 1
fprintf(' in %d %1.1f-cycle (%1.0f ms) time windows centered from %1.0f to %1.0f ms.\n',...
length(ampwins),cycles,1000/freq(1)*cycles,times(sortwin_st),times(sortwin_end));
else
fprintf(' in %d %1.1f-cycle (%1.0f-%1.0f ms) time windows centered from %1.0f to %1.0f ms.\n',...
length(ampwins),cycles,1000/freq(1)*cycles,1000/freq(end)*cycles,times(sortwin_st),times(sortwin_end));
end
end
phsamps = 0; %%%%%%%%%%%%%%%%%%%%%%%%%% sort by (mean) amplitude %%%%%%%%%%%%%%%%%%%%%%%%%%
minxs = [];
for f = 1:length(freq) % use one or range of frequencies
frq = freq(f);
[amps, cohers, cohsig, ampsig, allamps, allphs] = ...
phasecoher(data,length(times),srate,frq,cycles,0, ...
[], [], timeStretchRef, timeStretchMarks);
for ampwin = ampwins
[dummy minx] = min(abs(times-ampwin)); % find nearest time point to requested
minxs = [minxs minx];
winlen = floor(cycles*srate/frq);
% winloc = minx-[winlen:-1:0]; % ending time version
winloc = minx-linspace(floor(winlen/2), floor(-winlen/2), winlen+1);
tmprange = find(winloc>0 & winloc<=frames);
winloc = winloc(tmprange); % sorting window frames
if f==1
winlocs = [winlocs;winloc]; % store tme windows
end
% $$$ [phaseangles phsamp] = phasedet(data,frames,srate,winloc,frq);
% $$$ phsamps = phsamps+phsamps; % accumulate amplitudes across 'sortwin'
phaseangles = allphs(minx,:);
phsamps = phsamps+allamps(minx,:); % accumulate amplitudes across 'sortwin'
end
end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if length(tmprange) ~= winlen+1 % ?????????
filtersize = cycles * length(tmprange) / (winlen+1);
timecenter = median(winloc)/srate*1000+times(1); % center of window in ms
phaseangles = phaseangles + 2*pi*(timecenter-ampargs(1))*freq(end);
fprintf(...
' Data time limits reached -> now uses a %1.1f cycles (%1.0f ms) window centered at %1.0f ms\n', ...
filtersize, 1000/freq(1)*filtersize, timecenter);
fprintf(...
' Wavelet length is %d; Phase has been linearly interpolated to latency et %1.0f ms.\n', ...
length(winloc(1,:)), ampargs(1));
end
if length(freq) == 1
fprintf('Amplitudes are computed using a wavelet of %d frames.\n',length(winloc(1,:)));
end
%
% Reject small (or large) phsamp trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
ampargs(2) = ampargs(2)/100; % convert rejection rate from % to fraction
[tmp n] = sort(phsamps); % sort amplitudes
if ampargs(2)>=0
n = n(ceil(ampargs(2)*length(n))+1:end); % if rej 0, select all trials
fprintf('Retaining %d epochs (%g percent) with largest power at the analysis frequency,\n',...
length(n),100*(1-ampargs(2)));
else % ampargs(2) < 0
ampargs(2) = 1+ampargs(2); % subtract from end
n = n(1:floor(ampargs(2)*length(n)));
fprintf(...
'Retaining %d epochs (%g percent) with smallest power at the analysis frequency,\n',...
length(n),ampargs(2)*100);
end
%
% Remove low|high-amplitude trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
data = data(:,n); % amp-sort the data, removing rejected-amp trials
phsamps = phsamps(n); % amp-sort the amps
phaseangles = phaseangles(n); % amp-sort the phaseangles
sortvar = sortvar(n); % amp-sort the trial indices
ntrials = length(n); % number of trials retained
if ~isempty(auxvar)
auxvar = auxvar(:,n);
end
%
% Sort remaining data by amplitude %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
[phsamps sortidx] = sort(phsamps); % sort trials on amplitude
data = data(:,sortidx); % sort data by amp
phaseangles = phaseangles(sortidx); % sort angles by amp
sortvar = sortvar(sortidx); % sort input sortvar by amp
if ~isempty(auxvar)
auxvar = auxvar(:,sortidx);
end
fprintf('Size of data = [%d,%d]\n',size(data,1),size(data,2));
sortidx = n(sortidx); % return original trial indices in final sorted order
%
%%%%%%%%%%%%%%%%%%%%%% Don't Sort trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif Nosort == YES
fprintf('Not sorting data on input sortvar.\n');
sortidx = 1:ntrials;
%
%%%%%%%%%%%%%%%%%%%%%% Sort trials on (mean) value %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif exist('valargs')
[sttime stframe] = min(abs(times-valargs(1)));
sttime = times(stframe);
if length(valargs)>1
[endtime endframe] = min(abs(times-valargs(2)));
endtime = times(endframe);
else
endframe = stframe;
endtime = times(endframe);
end
if length(valargs)==1 || sttime == endtime
fprintf('Sorting data on value at time %4.0f ms.\n',sttime);
elseif length(valargs)>1
fprintf('Sorting data on mean value between %4.0f and %4.0f ms.\n',...
sttime,endtime);
end
if endframe>stframe
sortval = mean(data(stframe:endframe,:));
else
sortval = data(stframe,:);
end
[sortval,sortidx] = sort(sortval);
if length(valargs)>2
if valargs(3) <0
sortidx = sortidx(end:-1:1); % plot largest values on top
% if direction < 0
end
end
data = data(:,sortidx);
sortvar = sortvar(sortidx); % sort input sortvar by amp
if ~isempty(auxvar)
auxvar = auxvar(:,sortidx);
end
if ~isempty(phaseangles)
phaseangles = phaseangles(sortidx); % sort angles by amp
end
winloc = [stframe,endframe];
winlocs = winloc;
%
%%%%%%%%%%%%%%%%%%%%%% Sort trials on sortvar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
else
fprintf('Sorting data on input sortvar.\n');
[sortvar,sortidx] = sort(sortvar);
data = data(:,sortidx);
if ~isempty(auxvar)
auxvar = auxvar(:,sortidx);
end
uni_svar=unique_bc(sortvar);
n_ties=0;
tie_dist=zeros(1,length(uni_svar));
loop_ct=0;
for tie_loop=uni_svar,
ids=find(sortvar==tie_loop);
n_ids=length(ids);
if n_ids>1,
if replace_ties==YES,
mn=mean(data(:,ids),2);
data(:,ids)=repmat(mn,1,n_ids);
if ~isempty(auxvar)
mn=mean(auxvar(:,ids),2);
auxvar(:,ids) = repmat(mn,1,n_ids);
end
end
n_ties=n_ties+n_ids;
loop_ct=loop_ct+1;
tie_dist(loop_ct)=n_ids;
end
end
fprintf('%.2f%c of the trials (i.e., %d out of %d) have the same sortvar value as at least one other trial.\n', ...
100*n_ties/length(sortvar),37,n_ties,length(sortvar));
fprintf('Distribution of number ties per unique value of sortvar:\n');
if exist('prctile')
try
fprintf('Min: %d, 25th ptile: %d, Median: %d, 75th ptile: %d, Max: %d\n',min(tie_dist),round(prctile(tie_dist,25)), ...
round(median(tie_dist)),round(prctile(tie_dist,75)),max(tie_dist));
catch
end;
end;
if replace_ties==YES,
fprintf('Trials with tied sorting values will be replaced by their mean.\n');
end
fprintf('\n');
end
%if max(sortvar)<0
% fprintf('Changing the sign of sortvar: making it positive.\n');
% sortvar = -sortvar;
%end
%
%% %%%%%%%%%%%%%%%%% Adjust decfactor if phargs or ampargs %%%%%%%%%%%%%%%%%%%%%
%
if decfactor < 0
decfactor = -decfactor;
invdec = 1;
else
invdec = 0;
end;
if decfactor > sqrt(ntrials) % if large, output this many trials
n = 1:ntrials;
if exist('phargs') & length(phargs)>1
if phargs(2)>0
n = n(ceil(phargs(2)*ntrials)+1:end); % trials after rejection
elseif phargs(2)<0
n = n(1:floor(phargs(2)*length(n))); % trials after rejection
end
elseif exist('ampargs') & length(ampargs)>1
if ampargs(2)>0
n = n(ceil(ampargs(2)*ntrials)+1:end); % trials after rejection
elseif ampargs(2)<0
n = n(1:floor(ampargs(2)*length(n))); % trials after rejection
end
end
if invdec
decfactor = (length(n)-avewidth)/decfactor;
else
decfactor = length(n)/decfactor;
end;
end
if ~isreal(decfactor), decfactor = imag(decfactor); end;
%
%% %%%%%%%%%%%%%%%% Smooth data using moving average %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
urdata = data; % save data to compute amp, coher on unsmoothed data
if ~Allampsflag & ~exist('data2') % if imaging potential,
if length(timeStretchRef) > 0 & length(timeStretchMarks) > 0
%
% Perform time-stretching here -JH %%%%%%%%%%%%%%%%
%
for t=1:size(data,2)
M = timewarp(timeStretchMarks(t,:)', timeStretchRef');
data(:,t) = M*data(:,t);
end
end
tsurdata = data;
% Time-stretching ends here %%%%%%%%%%%%%%
if avewidth > 1 || decfactor > 1
if Nosort == YES
fprintf('Smoothing the data using a window width of %g epochs ',avewidth);
else
fprintf('Smoothing the sorted epochs with a %g-epoch moving window.',...
avewidth);
end
fprintf('\n');
fprintf(' and a decimation factor of %g\n',decfactor);
if ~exist('phargs') % if not phase-sorted trials
[data,outtrials] = movav(data,1:ntrials,avewidth,decfactor,[],[],wt_wind);
% Note: movav() here sorts using square window
[outsort,outtrials] = movav(sortvar,1:ntrials,avewidth,decfactor,[],[],wt_wind);
else % if phase-sorted trials, use circular / wrap-around smoothing
backhalf = floor(avewidth/2);
fronthalf = floor((avewidth-1)/2);
if avewidth > 2
[data,outtrials] = movav([data(:,[(end-backhalf+1):end]),...
data,...
data(:,[1:fronthalf])],...
[1:(ntrials+backhalf+fronthalf)],avewidth,decfactor,[],[],wt_wind);
[outsort,outtrials] = movav([sortvar((end-backhalf+1):end),...
sortvar,...
sortvar(1:fronthalf)],...
1:(ntrials+backhalf+fronthalf),avewidth,decfactor,[],[],wt_wind);
% Shift elements of outtrials so the first element is 1
outtrials = outtrials - outtrials(1) + 1;
else % avewidth==2
[data,outtrials] = movav([data(:,end),data],...
[1:(ntrials+1)],avewidth,decfactor,[],[],wt_wind);
% Note: movav() here sorts using square window
[outsort,outtrials] = movav([sortvar(end) sortvar],...
1:(ntrials+1),avewidth,decfactor,[],[],wt_wind);
% Shift elements of outtrials so the first element is 1
outtrials = outtrials - outtrials(1) + 1;
end
end
for index=1:length(percentiles)
outpercent{index} = compute_percentile( sortvar, percentiles(index), outtrials, avewidth);
end;
if ~isempty(auxvar)
if ~exist('phargs') % if not phase-sorted trials
[auxvar,tmp] = movav(auxvar,1:ntrials,avewidth,decfactor,[],[],wt_wind);
else % if phase-sorted trials
if avewidth>2
[auxvar,tmp] = movav([auxvar(:,[(end-backhalf+1):end]),...
auxvar,...
auxvar(:,[1:fronthalf])],...
[1:(ntrials+backhalf+fronthalf)],avewidth,decfactor,[],[],wt_wind);
% Shift elements of tmp so the first element is 1
tmp = tmp - tmp(1) + 1;
else % avewidth==2
[auxvar,tmp] = movav([auxvar(:,end),auxvar],[1:(ntrials+1)],avewidth,decfactor,[],[],wt_wind);
% Shift elements of tmp so the first element is 1
tmp = tmp - tmp(1) + 1;
end
end
end
% if ~isempty(sortvar_limits),
% fprintf('Output data will be %d frames by %d smoothed trials.\n',...
% frames,length(outtrials));
% fprintf('Outtrials: %3.2f to %4.2f\n',min(outtrials),max(outtrials));
% end
else % don't smooth
outtrials = 1:ntrials;
outsort = sortvar;
end
%
%%%%%%%%%%%%%%%%%%%%%%%%% Find color axis limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(Caxis)
mindat = Caxis(1);
maxdat = Caxis(2);
fprintf('Using the specified caxis range of [%g,%g].\n', mindat, maxdat);
else
mindat = min(min(data));
maxdat = max(max(data));
maxdat = max(abs([mindat maxdat])); % make symmetrical about 0
mindat = -maxdat;
if ~isempty(caxfraction)
adjmax = (1-caxfraction)/2*(maxdat-mindat);
mindat = mindat+adjmax;
maxdat = maxdat-adjmax;
fprintf(...
'The caxis range will be %g times the sym. abs. data range -> [%g,%g].\n',...
caxfraction,mindat,maxdat);
else
fprintf(...
'The caxis range will be the sym. abs. data range -> [%g,%g].\n',...
mindat,maxdat);
end
end
end % if ~Allampsflag & ~exist('data2')
%
%% %%%%%%%%%%%%%%%%%%%%%%%% Set time limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isnan(timelimits(1))
timelimits = [min(times) max(times)];
end
fprintf('Data will be plotted between %g and %g ms.\n',timelimits(1),timelimits(2));
%
%% %%%%%%%%%%% Image the aligned/sorted/smoothed data %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
if ~any(isnan(coherfreq)) % if plot three time axes
image_loy = 3*PLOT_HEIGHT;
elseif Erpflag == YES % elseif if plot only one time axes
image_loy = 1*PLOT_HEIGHT;
else % else plot erp-image only
image_loy = 0*PLOT_HEIGHT;
end
gcapos=get(gca,'Position');
delete(gca)
if isempty(topomap)
image_top = 1;
else
image_top = 0.9;
end
ax1=axes('Position',...
[gcapos(1) gcapos(2)+image_loy*gcapos(4) ...
gcapos(3) (image_top-image_loy)*gcapos(4)]);
end;
ind = isnan(data); % find nan's in data
[i j]=find(ind==1);
if ~isempty(i)
data(i,j) = 0; % plot shifted nan data as 0 (=green)
end
%
%% %%%%%%%%%%% Determine coherence freqeuncy %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if length(coherfreq) == 2 & coherfreq(1) ~= coherfreq(2) & freq <= 0
% find max frequency in specified band - should use Matlab pwelch()?
if exist('psd') == 2 % from Signal Processing Toolbox
[pxx,tmpfreq] = psd(urdata(:),max(1024,pow2(ceil(log2(frames)))),srate,frames,0);
else % substitute from EEGLAB
[pxx,tmpfreq] = spec(urdata(:),max(1024,pow2(ceil(log2(frames)))),srate,frames,0);
end;
pxx = 10*log10(pxx);
n = find(tmpfreq >= coherfreq(1) & tmpfreq <= coherfreq(2));
% [tmpfreq(n) pxx(n)]
% coherfreqs = coherfreq; % save for debugging spectrum plotting
if ~length(n)
coherfreq = coherfreq(1);
end
[dummy maxx] = max(pxx(n));
coherfreq = tmpfreq(n(maxx));
else
coherfreq = coherfreq(1);
end
if ~Allampsflag & ~exist('data2') %%%%%%%% Plot ERP image %%%%%%%%%%
%Stretch the data array
% $$$ keyboard;
if strcmpi(NoShow, 'no')
if TIMEX
h_eim=imagesc(times,outtrials,data',[mindat,maxdat]);% plot time on x-axis
set(gca,'Ydir','normal');
axis([timelimits(1) timelimits(2) ...
min(outtrials) max(outtrials)]);
else
h_eim=imagesc(outtrials,times,data,[mindat,maxdat]); % plot trials on x-axis
axis([min(outtrials) max(outtrials)...
timelimits(1) timelimits(2)]);
end
try colormap(DEFAULT_COLORMAP); catch, end;
hold on
drawnow
end;
elseif Allampsflag %%%%%%%%%%%%%%%% Plot allamps instead of data %%%%%%%%%%%%%%
if freq > 0
coherfreq = mean(freq); % use phase-sort frequency
end
if ~isnan(signifs) % plot received significance levels
fprintf(['Computing and plotting received ERSP and ITC signif. ' ...
'levels...\n']);
[amps,cohers,cohsig,ampsig,allamps] = ...
phasecoher(urdata,length(times),srate,coherfreq,cycles,0, ...
[], [], timeStretchRef, timeStretchMarks);
% Note: need to receive cohsig and ampsig to get allamps <---
ampsig = signifs([1 2]); % assume these already in dB
cohsig = signifs(3);
elseif alpha>0 % compute significance levels
fprintf('Computing and plotting %g ERSP and ITC signif. level...\n',alpha);
[amps,cohers,cohsig,ampsig,allamps] = ...
phasecoher(urdata,length(times),srate,coherfreq, ...
cycles, alpha, [], [], ...
timeStretchRef, timeStretchMarks');
% Note: need to receive cohsig and ampsig to get allamps
fprintf('Coherence significance level: %g\n',cohsig);
else % no plotting of significance
[amps,cohers,cohsig,ampsig,allamps] = ...
phasecoher(urdata,length(times),srate,coherfreq, ...
cycles,0,[], [], timeStretchRef, timeStretchMarks);
% Note: need to receive cohsig and ampsig to get allamps
end
% fprintf('#1 Size of allamps = [%d %d]\n',size(allamps,1),size(allamps,2));
base = find(times<=DEFAULT_BASELINE_END);
if length(base)<2
base = 1:floor(length(times)/4); % default first quarter-epoch
end
fprintf('Using %g to %g ms as amplitude baseline.\n',...
times(1),times(base(end)));
% fprintf('#2 Size of allamps = [%d %d]\n',size(allamps,1),size(allamps,2));
% fprintf('Subtracting the mean baseline log amplitude \n');
%fprintf('Subtracting the mean baseline log amplitude %g\n',baseall);
% allamps = allamps./baseall;
% fprintf('#3 Size of allamps = [%d %d]\n',size(allamps,1),size(allamps,2));
if avewidth > 1 || decfactor > 1
if Nosort == YES
fprintf(...
'Smoothing the amplitude epochs using a window width of %g epochs ',...
avewidth);
else % sort trials
fprintf(...
'Smoothing the sorted amplitude epochs with a %g-epoch moving window.',...
avewidth);
end
fprintf('\n');
fprintf(' and a decimation factor of %g\n',decfactor);
%fprintf('4 Size of allamps = [%d %d]\n',size(allamps,1),size(allamps,2));
if exist('phargs') % if phase-sorted trials, use circular/wrap-around smoothing
backhalf = floor(avewidth/2);
fronthalf = floor((avewidth-1)/2);
if avewidth > 2
[allamps,outtrials] = movav([allamps(:,[(end-backhalf+1):end]),...
allamps,...
allamps(:,[1:fronthalf])],...
[1:(ntrials+backhalf+fronthalf)],avewidth,decfactor,[],[],wt_wind);
% Note: sort using square window
[outsort,outtrials] = movav([sortvar((end-backhalf+1):end),...
sortvar,...
sortvar(1:fronthalf)],...
1:(ntrials+backhalf+fronthalf),avewidth,decfactor,[],[],wt_wind);
% Shift elements of outtrials so the first element is 1
outtrials = outtrials - outtrials(1) + 1;
if ~isempty(auxvar)
[auxvar,tmp] = movav([auxvar(:,[(end-backhalf+1):end]),...
auxvar,...
auxvar(:,[1:fronthalf])],...
[1:(ntrials+backhalf+fronthalf)],avewidth,decfactor,[],[],wt_wind);
% Shift elements of outtrials so the first element is 1
outtrials = outtrials - outtrials(1) + 1;
end
else % avewidth==2
[allamps,outtrials] = movav([allamps(:,end),allamps],...
[1:(ntrials+1)],avewidth,decfactor,[],[],wt_wind);
% Note: sort using square window
[outsort,outtrials] = movav([sortvar(end) sortvar],...
1:(ntrials+1),avewidth,decfactor,[],[],wt_wind);
% Shift elements of outtrials so the first element is 1
outtrials = outtrials - outtrials(1) + 1;
[auxvar,tmp] = movav([auxvar(:,end),auxvar],[1:(ntrials+1)],avewidth,decfactor,[],[],wt_wind);
% Shift elements of tmp so the first element is 1
tmp = tmp - tmp(1) + 1;
end
else % if trials not phase sorted, no wrap-around
[allamps,outtrials] = movav(allamps,1:ntrials,avewidth,decfactor,[],[],wt_wind);
%fprintf('5 Size of allamps = [%d %d]\n',size(allamps,1),size(allamps,2));
[outsort,outtrials] = movav(sortvar,1:ntrials,avewidth,decfactor,[],[],wt_wind);
if ~isempty(auxvar)
[auxvar,tmp] = movav(auxvar,1:ntrials,avewidth,decfactor,[],[],wt_wind);
end
end
for index=1:length(percentiles)
outpercent{index} = compute_percentile( sortvar, percentiles(index), outtrials, avewidth);
end;
fprintf('Output allamps data will be %d frames by %d smoothed trials.\n',...
frames,length(outtrials));
else % if no smoothing
outtrials = 1:ntrials;
outsort = sortvar;
end
allamps = 20*log10(allamps); % convert allamps to dB
amps = 20*log10(amps); % convert latency mean amps to dB
ampsig = 20*log10(ampsig); % convert amplitude signif thresholds to dB
if alpha>0
fprintf('Amplitude significance levels: [%g %g] dB\n',ampsig(1),ampsig(2));
end
if isnan(baseamp) % if not specified in 'limits'
[amps,baseamp] = rmbase(amps,length(times),base); % subtract the dB baseline (baseamp)
% amps are the means at each latency
allamps = allamps - baseamp; % subtract dB baseline from allamps
% amplitude
ampsig = ampsig - baseamp; % subtract dB baseline from ampsig
else % if baseamp specified in 'limits' (as last argument 'basedB', see help)
amps = amps-baseamp; % use specified (log) baseamp
allamps = allamps - baseamp; % subtract dB baseline
if isnan(signifs);
ampsig = ampsig-baseamp; % subtract dB baseline
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%%% Find color axis limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(Caxis)
mindat = Caxis(1);
maxdat = Caxis(2);
fprintf('Using the specified caxis range of [%g,%g].\n',...
mindat,maxdat);
else
% Changed -JH
% 0.8 is Scott's suggestion to make the erp image show small
% variations better
maxdat = 0.8 * max(max(abs(allamps)));
mindat = -maxdat;
% $$$ mindat = min(min(allamps));
% $$$ maxdat = max(max(allamps));
% $$$ maxdat = max(abs([mindat maxdat])); % make symmetrical about 0
% $$$ mindat = -maxdat;
if ~isempty(caxfraction)
adjmax = (1-caxfraction)/2*(maxdat-mindat);
mindat = mindat+adjmax;
maxdat = maxdat-adjmax;
fprintf(...
'The caxis range will be %g times the sym. abs. data range -> [%g,%g].\n',...
caxfraction,mindat,maxdat);
else
fprintf(...
'The caxis range will be the sym. abs. data range -> [%g,%g].\n',...
mindat,maxdat);
end
end
%
%%%%%%%%%%%%%%%%%%%%% Image amplitudes at coherfreq %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
fprintf('Plotting amplitudes at freq %g Hz instead of potentials.\n',coherfreq);
if TIMEX
imagesc(times,outtrials,allamps',[mindat,maxdat]);% plot time on x-axis
set(gca,'Ydir','normal');
axis([timelimits(1) timelimits(2) ...
min(outtrials) max(outtrials)]);
else
imagesc(outtrials,times,allamps,[mindat,maxdat]); % plot trials on x-axis
axis([min(outtrials) max(outtrials)...
timelimits(1) timelimits(2)]);
end
try colormap(DEFAULT_COLORMAP); catch, end;
drawnow
hold on
end;
data = allamps;
elseif exist('data2') %%%%%% Plot allcohers instead of data %%%%%%%%%%%%%%%%%%%
%%%%%%%%% UNDOCUMENTED AND DEPRECATED OPTION %%%%%%%%%%%%
if freq > 0
coherfreq = mean(freq); % use phase-sort frequency
end
if alpha>0
fprintf('Computing and plotting %g coherence significance level...\n',alpha);
% [amps,cohers,cohsig,ampsig,allcohers] = ...
% crosscoher(urdata,data2,length(times),srate,coherfreq,cycles,alpha);
fprintf('Inter-Trial Coherence significance level: %g\n',cohsig);
fprintf('Amplitude significance levels: [%g %g]\n',ampsig(1),ampsig(2));
else
% [amps,cohers,cohsig,ampsig,allcohers] = ...
% crosscoher(urdata,data2,length(times),srate,coherfreq,cycles,0);
end
if ~exist('allcohers')
fprintf('\nerpimage(): allcohers not returned....\n')
return
end
allamps = allcohers; % output variable
% fprintf('Size allcohers = (%d, %d)\n',size(allcohers,1),size(allcohers,2));
% fprintf('#1 Size of allcohers = [%d %d]\n',size(allcohers,1),size(allcohers,2));
base = find(times<=0);
if length(base)<2
base = 1:floor(length(times)/4); % default first quarter-epoch
end
amps = 20*(log10(amps) - log10(mean(amps))); % convert to dB
%amps = 20*log10(amps); % convert to dB
ampsig = 20*(log10(ampsig) - log10(mean(amps))); % convert to dB
%ampsig = 20*log10(ampsig); % convert to dB
if isnan(baseamp)
[amps,baseamp] = rmbase(amps,length(times),base); % remove baseline
else
amps = amps - baseamp;
end
% fprintf('#2 Size of allcohers = [%d %d]\n',size(allcohers,1),size(allcohers,2));
if avewidth > 1 || decfactor > 1
if Nosort == YES
fprintf(...
'Smoothing the amplitude epochs using a window width of %g epochs '...
,avewidth);
else
fprintf(...
'Smoothing the sorted amplitude epochs with a %g-epoch moving window.'...
,avewidth);
end
fprintf('\n');
fprintf(' and a decimation factor of %g\n',decfactor);
% fprintf('4 Size of allcohers = [%d %d]\n',size(allcohers,1),size(allcohers,2));
[allcohers,outtrials] = movav(allcohers,1:ntrials,avewidth,decfactor,[],[],wt_wind);
% fprintf('5 Size of allcohers = [%d %d]\n',size(allcohers,1),size(allcohers,2));
[outsort,outtrials] = movav(sortvar,1:ntrials,avewidth,decfactor,[],[],wt_wind);
% fprintf('Output data will be %d frames by %d smoothed trials.\n',...
% frames,length(outtrials));
else
outtrials = 1:ntrials;
outsort = sortvar;
end
%
%%%%%%%%%%%%%%%%%%%%%%%%% Find color axis limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(Caxis)
mindat = Caxis(1);
maxdat = Caxis(2);
fprintf('Using the specified caxis range of [%g,%g].\n',...
mindat,maxdat);
else
mindat = -1;
maxdat = 1
fprintf(...
'The caxis range will be the sym. abs. data range [%g,%g].\n',...
mindat,maxdat);
end
%
%%%%%%%%%%%%%%%%%%%%% Image coherences at coherfreq %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
fprintf('Plotting coherences at freq %g Hz instead of potentials.\n',coherfreq);
if TIMEX
imagesc(times,outtrials,allcohers',[mindat,maxdat]);% plot time on x-axis
set(gca,'Ydir','normal');
axis([timelimits(1) timelimits(2) ...
min(outtrials) max(outtrials)]);
else
imagesc(outtrials,times,allcohers,[mindat,maxdat]); % plot trials on x-axis
axis([min(outtrials) max(outtrials)...
timelimits(1) timelimits(2)]);
end
try colormap(DEFAULT_COLORMAP); catch, end;
drawnow
hold on
end;
end
%Change limits on ERPimage y-axis if requested
if ~isempty(sortvar_limits)
if exist('phargs','var'),
fprintf('********* Warning *********\n');
fprintf('Specifying sorting variable limits has no effect when sorting by phase.\n');
elseif exist('valargs','var'),
fprintf('********* Warning *********\n');
fprintf('Specifying sorting variable limits has no effect when sorting by mean EEG voltage.\n');
elseif exist('ampargs','var'),
fprintf('********* Warning *********\n');
fprintf('Specifying sorting variable limits has no effect when sorting by frequency amp.\n');
else
v=axis;
img_mn=find_crspnd_pt(sortvar_limits(1),outsort,outtrials);
if isempty(img_mn),
img_mn=1;
sortvar_limits(1)=outsort(1);
end
img_mx=find_crspnd_pt(sortvar_limits(2),outsort,outtrials);
if isempty(img_mx),
img_mx=length(outsort);
sortvar_limits(2)=outsort(img_mx);
end
axis([v(1:2) img_mn img_mx]);
id1=find(sortvar>=sortvar_limits(1));
id2=find(sortvar<=sortvar_limits(2));
id=intersect_bc(id1,id2);
fprintf('%d epochs fall within sortvar limits.\n',length(id));
urdata=urdata(:,id);
if ~isempty(tsurdata),
tsurdata=tsurdata(:,id);
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%% End plot image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmpi(NoShow, 'no')
v=axis;
fprintf('Output data will be %d frames by %d smoothed trials.\n',...
frames,v(4)-v(3)+1);
fprintf('Outtrials: %3.2f to %4.2f\n',v(3),v(4));
end;
%
%%%%%%%%%%%%%%%%%%%%% Compute y-axis tick values and labels (if requested) %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
if ~isempty(img_ylab) && ~strcmpi(img_ylab,'Trials')
%make ERPimage y-tick labels in units of sorting variable
if isempty(sortvar_limits),
mn=min(outsort);
mx=max(outsort);
else
mn=sortvar_limits(1);
mx=sortvar_limits(2);
end
ord=orderofmag(mx-mn);
rng_rnd=round([mn mx]/ord)*ord;
if isempty(img_ytick_lab)
img_ytick_lab=[rng_rnd(1):ord:rng_rnd(2)];
in_range=find((img_ytick_lab>=mn) & (img_ytick_lab<=mx));
img_ytick_lab=img_ytick_lab(in_range);
else
img_ytick_lab=unique_bc(img_ytick_lab); %make sure it is sorted
in_range=find((img_ytick_lab>=mn) & (img_ytick_lab<=mx));
if length(img_ytick_lab)~=length(in_range),
fprintf('\n***Warning***\n');
fprintf('''img_trialax_ticks'' exceed smoothed sorting variable values. Max/min values are %f/%f.\n\n',mn,mx);
img_ytick_lab=img_ytick_lab(in_range);
end
end
n_tick=length(img_ytick_lab);
img_ytick=zeros(1,n_tick);
for tickloop=1:n_tick,
img_ytick(tickloop)=find_crspnd_pt(img_ytick_lab(tickloop),outsort,outtrials);
end
elseif ~isempty(img_ylab), %make ERPimage y-tick labels in units of Trials
if isempty(img_ytick_lab)
v=axis; %note: sorting variable limits have already been used to determine range of ERPimage y-axis
mn=v(3);
mx=v(4);
ord=orderofmag(mx-mn);
rng_rnd=round([mn mx]/ord)*ord;
img_ytick=[rng_rnd(1):ord:rng_rnd(2)];
in_range=find((img_ytick>=mn) & (img_ytick<=mx));
img_ytick=img_ytick(in_range);
else
img_ytick=img_ytick_lab;
end
end
end;
%% %%%%%%%%%%%%%%%%%%%%%%%%% plot vert lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(verttimes)
if size(verttimes,1) ~= 1 & size(verttimes,2) == 1 & size(verttimes,1) ~= ntrials
verttimes = verttimes';
end
if size(verttimes,1) ~= 1 & size(verttimes,1) ~= ntrials
fprintf('\nerpimage(): vert arg matrix must have 1 or %d rows\n',ntrials);
return
end;
if strcmpi(NoShow, 'no')
if size(verttimes,1) == 1
fprintf('Plotting %d lines at times: ',size(verttimes,2));
else
fprintf('Plotting %d traces starting at times: ',size(verttimes,2));
end
for vt = verttimes % for each column
fprintf('%g ',vt(1));
if isnan(aligntime) % if NOT re-aligned data
if TIMEX % overplot vt on image
if length(vt)==1
mydotstyle = DOTSTYLE;
if exist('auxcolors') & ...
length(verttimes) == length(auxcolors)
mydotstyle = auxcolors{find(verttimes == vt)};
end
plot([vt vt],[0 max(outtrials)],mydotstyle,'Linewidth',VERTWIDTH);
elseif length(vt)==ntrials
[outvt,ix] = movav(vt,1:ntrials,avewidth,decfactor,[],[],wt_wind);
plot(outvt,outtrials,DOTSTYLE,'Linewidth',VERTWIDTH);
end
else
if length(vt)==1
plot([0 max(outtrials)],[vt vt],DOTSTYLE,'Linewidth',VERTWIDTH);
elseif length(vt)==ntrials
[outvt,ix] = movav(vt,1:ntrials,avewidth,decfactor,[],[],wt_wind);
plot(outtrials,outvt,DOTSTYLE,'Linewidth',VERTWIDTH);
end
end
else % re-aligned data
if TIMEX % overplot vt on image
if length(vt)==ntrials
[outvt,ix] = movav(vt,1:ntrials,avewidth,decfactor,[],[],wt_wind);
plot(aligntime+outvt-outsort,outtrials,DOTSTYLE,'LineWidth',VERTWIDTH);
elseif length(vt)==1
plot(aligntime+vt-outsort,outtrials,DOTSTYLE,'LineWidth',VERTWIDTH);
end
else
if length(vt)==ntrials
[outvt,ix] = movav(vt,1:ntrials,avewidth,decfactor,[],[],wt_wind);
plot(outtrials,aligntime+outvt-outsort,DOTSTYLE,'LineWidth',VERTWIDTH);
elseif length(vt)==1
plot(outtrials,aligntime+vt-outsort,DOTSTYLE,'LineWidth',VERTWIDTH);
end
end
end
end
%end
fprintf('\n');
end;
end
%
%% %%%%%%%%%%%%%%%%%%%%%%%%% plot horizontal ('horz') lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(horzepochs)
if size(horzepochs,1) > 1 & size(horzepochs,1) > 1
fprintf('\nerpimage(): horz arg must be a vector\n');
return
end;
if strcmpi(NoShow, 'no')
if ~isempty(img_ylab) && ~strcmpi(img_ylab,'Trials'),
%trial axis in units of sorting variable
mx=max(outsort);
mn=min(outsort);
fprintf('Plotting %d lines at epochs corresponding to sorting variable values: ',length(horzepochs));
for he = horzepochs % for each horizontal line
fprintf('%g ',he);
%find trial number corresponding to this value of sorting
%variable:
if (he>mn) && (he<mx)
he_ep=find_crspnd_pt(he,outsort,outtrials);
if TIMEX % overplot he_ep on image
plot([timelimits(1) timelimits(2)],[he_ep he_ep],LINESTYLE,'Linewidth',HORZWIDTH);
else
plot([he_ep he_ep], [timelimits(1) timelimits(2)],LINESTYLE,'Linewidth',HORZWIDTH);
end
end
end
else %trial axis in units of trials
fprintf('Plotting %d lines at epochs: ',length(horzepochs));
for he = horzepochs % for each horizontal line
fprintf('%g ',he);
if TIMEX % overplot he on image
plot([timelimits(1) timelimits(2)],[he he],LINESTYLE,'Linewidth',HORZWIDTH);
else
plot([he he], [timelimits(1) timelimits(2)],LINESTYLE,'Linewidth',HORZWIDTH);
end
end
end
fprintf('\n');
end;
end
if strcmpi(NoShow, 'no')
set(gca,'FontSize',TICKFONT)
hold on;
end;
%
%% %%%%%%%%% plot vertical line at 0 or align time %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
if ~isnan(aligntime) % if trials time-aligned
if times(1) <= aligntime & times(frames) >= aligntime
plot([aligntime aligntime],[min(outtrials) max(outtrials)],...
'k','Linewidth',ZEROWIDTH); % plot vertical line at time 0
% plot vertical line at aligntime
end
else % trials not time-aligned
if times(1) <= 0 & times(frames) >= 0
plot([0 0],[min(outtrials) max(outtrials)],...
'k','Linewidth',ZEROWIDTH); % plot smoothed sortwvar
end
end
end;
if strcmpi(NoShow, 'no') & ( min(outsort) < timelimits(1) ...
|max(outsort) > timelimits(2))
ur_outsort = outsort; % store the pre-adjusted values
fprintf('Not all sortvar values within time vector limits: \n')
fprintf(' outliers will be shown at nearest limit.\n');
i = find(outsort< timelimits(1));
outsort(i) = timelimits(1);
i = find(outsort> timelimits(2));
outsort(i) = timelimits(2);
end
if strcmpi(NoShow, 'no')
if TIMEX
if Nosort == YES
l=ylabel(img_ylab);
if ~isempty(img_ylab) && ~strcmpi(img_ylab,'Trials')
set(gca,'ytick',img_ytick,'yticklabel',img_ytick_lab);
end
else
if exist('phargs','var')
l=ylabel('Phase-sorted Trials');
elseif exist('ampargs','var')
l=ylabel('Amplitude-sorted Trials');
elseif exist('valargs','var')
l=ylabel('Voltage-sorted Trials');
else
l=ylabel(img_ylab);
if ~isempty(img_ylab)
set(gca,'ytick',img_ytick);
end
if ~strcmpi(img_ylab,'Trials')
set(gca,'yticklabel',img_ytick_lab);
end
end
end
else % if switch x<->y axes
if Nosort == YES & NoTimeflag==NO
l=xlabel(img_ylab);
if ~isempty(img_ylab) && ~strcmpi(img_ylab,'Trials')
set(gca,'xtick',img_ytick,'xticklabel',img_ytick_lab);
end
else
if exist('phargs')
l=ylabel('Phase-sorted Trials');
elseif NoTimeflag == NO
l=xlabel('Sorted Trials');
else
l=xlabel(img_ylab);
if ~isempty(img_ylab) && ~strcmpi(img_ylab,'Trials')
set(gca,'xtick',img_ytick,'xticklabel',img_ytick_lab);
end
end
end
end
set(l,'FontSize',LABELFONT);
if ~strcmpi(plotmode, 'topo')
t=title(titl);
set(t,'FontSize',LABELFONT);
else
NAME_OFFSETX = 0.1;
NAME_OFFSETY = 0.2;
xx = xlim; xmin = xx(1); xdiff = xx(2)-xx(1); xpos = double(xmin+NAME_OFFSETX*xdiff);
yy = ylim; ymax = yy(2); ydiff = yy(2)-yy(1); ypos = double(ymax-NAME_OFFSETY*ydiff);
t=text(xpos, ypos,titl);
axis off;
end;
set(gca,'Box','off');
set(gca,'Fontsize',TICKFONT);
set(gca,'color',BACKCOLOR);
if Erpflag == NO & NoTimeflag == NO
if exist('NoTimesPassed')~=1
l=xlabel('Time (ms)');
else
l=xlabel('Frames');
end
set(l,'Fontsize',LABELFONT);
end
end;
%
%% %%%%%%%%%%%%%%%%%% Overplot sortvar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
if NoShowVar == YES
fprintf('Not overplotting sorted sortvar on data.\n');
elseif isnan(aligntime) % plot sortvar on un-aligned data
if Nosort == NO;
fprintf('Overplotting sorted sortvar on data.\n');
end
hold on;
if TIMEX % overplot sortvar
plot(outsort,outtrials,'k','LineWidth',SORTWIDTH);
else
plot(outtrials,outsort,'k','LineWidth',SORTWIDTH);
end
drawnow
else % plot re-aligned zeros on sortvar-aligned data
if Nosort == NO;
fprintf('Overplotting sorted sortvar on data.\n');
end
hold on;
if TIMEX % overplot re-aligned 0 time on image
plot([aligntime aligntime],[min(outtrials) max(outtrials)],...
'k','LineWidth',SORTWIDTH);
else
plot([[min(outtrials) max(outtrials)],aligntime aligntime],...
'k','LineWidth',SORTWIDTH);
end
fprintf('Overplotting realigned times-zero on data.\n');
hold on;
if TIMEX % overplot realigned sortvar on image
plot(0+aligntime-outsort,outtrials,'k','LineWidth',ZEROWIDTH);
else
plot(0+outtrials,aligntime-outsort,'k','LineWidth',ZEROWIDTH);
end
drawnow
end
end;
%
%% %%%%%%%%%%%%%%%%%% Overplot auxvar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
if ~isempty(auxvar)
fprintf('Overplotting auxvar(s) on data.\n');
hold on;
auxtrials = outtrials(:)' ; % make row vector
if exist('auxcolors')~=1 % If no auxcolors specified
auxcolors = cell(1,size(auxvar,1));
for c=1:size(auxvar,1)
auxcolors(c) = {'k'}; % plot auxvars as black trace(s)
end
end
if length(auxcolors) < size(auxvar,1)
nauxColors = length(auxcolors);
for k=nauxColors+1:size(auxvar,1)
auxcolors = { auxcolors{:} auxcolors{1+rem(k-1,nauxColors)}};
end
end
for c=1:size(auxvar,1)
auxcolor = auxcolors{c};
if ~isempty(auxcolor)
if isnan(aligntime) % plot auxvar on un-aligned data
if TIMEX % overplot auxvar
plot(auxvar(c,:)',auxtrials',auxcolor,'LineWidth',SORTWIDTH);
else
plot(auxtrials',auxvar(c,:)',auxcolor,'LineWidth',SORTWIDTH);
end
drawnow
else % plot re-aligned zeros on sortvar-aligned data
if TIMEX % overplot realigned 0-time on image
plot(auxvar(c,:)',auxtrials',auxcolor,'LineWidth',ZEROWIDTH);
else
plot(0+auxtrials',aligntime-auxvar(c,:)',auxcolor,'LineWidth',ZEROWIDTH);
end
drawnow
end % aligntime
end % if auxcolor
end % c
end % auxvar
if exist('outpercent')
for index = 1:length(outpercent)
if isnan(aligntime) % plot auxvar on un-aligned data
plot(outpercent{index},outtrials,'k','LineWidth',SORTWIDTH);
else
plot(aligntime-outpercent{index},outtrials,'k','LineWidth',SORTWIDTH);
end;
end;
end;
end;
%
%% %%%%%%%%%%%%%%%%%%%%%% Plot colorbar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
if Colorbar == YES
pos=get(ax1,'Position');
axcb=axes('Position',...
[pos(1)+pos(3)+0.02 pos(2) ...
0.03 pos(4)]);
cbar(axcb,0,[mindat,maxdat]); % plot colorbar to right of image
title(cbar_title);
set(axcb,'fontsize',TICKFONT,'xtick',[]);
% drawnow
axes(ax1); % reset current axes to the erpimage
end
end;
%
%% %%%%%%%%%%%%%%%%%%%%% Compute ERP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
erp = [];
if Erpflag == YES
if exist('erpalpha')
if erp_ptiles>1,
fprintf(['\nOnly plotting one ERP (i.e., not plotting ERPs from %d percentile splits) ' ...
'because ''erpalpha'' option was chosen. You can''t plot both.\n\n'],erp_ptiles)
end
[erp erpsig] = nan_mean(fastif(length(tsurdata) > 0, tsurdata',urdata'), ...
erpalpha);
fprintf(' Mean ERP (p<%g) significance threshold: +/-%g\n', ...
erpalpha,mean(erpsig));
else
%potentially make ERPs of 50%, 33%, or 25% split of trials
n_trials=size(urdata,2);
trials_step=round(n_trials/erp_ptiles);
erp=zeros(erp_ptiles,size(urdata,1));
for ploop=1:erp_ptiles,
ptile_trials=[1:trials_step]+(ploop-1)*trials_step;
if max(ptile_trials)>n_trials,
ptile_trials=ptile_trials(1):n_trials;
end
if length(tsurdata) > 0
erp(ploop,:) = nan_mean(tsurdata(:,ptile_trials)');
else
erp(ploop,:) = nan_mean(urdata(:,ptile_trials)');
end;
end
% else
%orig line
%[erp] = nan_mean(fastif(length(tsurdata) > 0, tsurdata', urdata'));
%end
end % compute average ERP, ignoring nan's
end;
if Erpflag == YES & strcmpi(NoShow, 'no')
axes(ax1); % reset current axes to the erpimage
xtick = get(ax1,'Xtick'); % remember x-axis tick locations
xticklabel = get(ax1,'Xticklabel'); % remember x-axis tick locations
set(ax1, 'xticklabel', []);
widthxticklabel = size(xticklabel,2);
xticklabel = cellstr(xticklabel);
for tmpindex = 1:length(xticklabel)
if length(xticklabel{tmpindex}) < widthxticklabel
spaces = char(ones(1,ceil((widthxticklabel-length(xticklabel{tmpindex}))/2) )*32);
xticklabel{tmpindex} = [spaces xticklabel{tmpindex}];
end;
end;
xticklabel = strvcat(xticklabel);
if Erpstdflag == YES
stdev = nan_std(urdata');
end;
%
%%%%%% Plot ERP time series below image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isnan(maxerp)
fac = 10;
maxerp = 0;
while maxerp == 0
maxerp = round(fac*YEXPAND*max(erp))/fac; % minimal decimal places
fac = 10*fac;
end
if Erpstdflag == YES
fac = fac/10;
maxerp = max(maxerp, round(fac*YEXPAND*max(erp+stdev))/fac);
end;
if ~isempty(erpsig)
erpsig = [erpsig;-1*erpsig];
maxerp = max(maxerp, round(fac*YEXPAND*max(erpsig))/fac);
end
maxerp=max(maxerp);
end
if isnan(minerp)
fac = 1;
minerp = 0;
while minerp == 0
minerp = round(fac*YEXPAND*min(erp))/fac; % minimal decimal places
fac = 10*fac;
end
if Erpstdflag == YES
fac = fac/10;
minerp = min(minerp, round(fac*YEXPAND*min(erp-stdev))/fac);
end;
if ~isempty(erpsig)
minerp = min(minerp, round(fac*YEXPAND*min(erpsig))/fac);
end
minerp=min(minerp);
end
limit = [timelimits(1:2) minerp maxerp];
if ~isnan(coherfreq)
set(ax1,'Xticklabel',[]); % remove tick labels from bottom of image
ax2=axes('Position',...
[gcapos(1) gcapos(2)+2/3*image_loy*gcapos(4) ...
gcapos(3) (image_loy/3-YGAP)*gcapos(4)]);
else
ax2=axes('Position',...
[gcapos(1) gcapos(2) ...
gcapos(3) image_loy*gcapos(4)]);
end
fprintf('Plotting the ERP trace below the ERP image\n');
if Erpstdflag == YES
if Showwin
tmph = plot1trace(ax2,times,erp,limit,[],stdev,times(winlocs),erp_grid,erp_vltg_ticks); % plot ERP +/-stdev
else
tmph = plot1trace(ax2,times,erp,limit, [], stdev,[],erp_grid,erp_vltg_ticks); % plot ERP +/-stdev
end
elseif ~isempty('erpsig')
if Showwin
tmph = plot1trace(ax2,times,erp,limit,erpsig,[],times(winlocs),erp_grid,erp_vltg_ticks); % plot ERP and 0+/-alpha threshold
else
tmph = plot1trace(ax2,times,erp,limit,erpsig,[],[],erp_grid,erp_vltg_ticks); % plot ERP and 0+/-alpha threshold
end
else % plot ERP alone - no significance or std dev plotted
if Showwin
tmph = plot1trace(ax2,times,erp,limit,[],[],times(winlocs),erp_grid,erp_vltg_ticks); % plot ERP alone
else
tmph = plot1trace(ax2,times,erp,limit,[],[],[],erp_grid,erp_vltg_ticks); % plot ERP alone
end
end;
if ~isnan(aligntime)
line([aligntime aligntime],[limit(3:4)*1.1],'Color','k','LineWidth',ZEROWIDTH); % x=median sort value
line([0 0],[limit(3:4)*1.1],'Color','k','LineWidth',ZEROWIDTH); % x=median sort value
% remove y axis
if length(tmph) > 1
delete(tmph(end));
end;
end
set(ax2,'Xtick',xtick); % use same Xticks as erpimage above
if ~isnan(coherfreq)
set(ax2,'Xticklabel',[]); % remove tick labels from ERP x-axis
else % bottom axis
set(ax2,'Xticklabel',xticklabel); % add ticklabels to ERP x-axis
end
if isnan(coherfreq) % if no amp and coher plots below . . .
if TIMEX & NoTimeflag == NO
if exist('NoTimesPassed')~=1
l=xlabel('Time (ms)');
else
l=xlabel('Frames');
end
set(l,'FontSize',LABELFONT);
% $$$ else
% $$$ if exist('NoTimesPassed')~=1
% $$$ l=ylabel('Time (ms)');
% $$$ else
% $$$ l=ylabel('Frames');
% $$$ end
% $$$ set(l,'FontSize',LABELFONT);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% plot vert lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(verttimes)
if size(verttimes,1) == ntrials
vts=sort(verttimes);
vts = vts(ceil(ntrials/2),:); % plot median verttimes values if a matrix
else
vts = verttimes(:)'; % make verttimes a row vector
end
for vt = vts
if isnan(aligntime)
if TIMEX % overplot vt on ERP
mydotstyle = DOTSTYLE;
if exist('auxcolors') & ...
length(verttimes) == length(verttimesColors)
mydotstyle = verttimesColors{find(verttimes == vt)};
end
plot([vt vt],[limit(3:4)],mydotstyle,'Linewidth',VERTWIDTH);
else
plot([min(outtrials) max(outtrials)],[limit(3:4)],DOTSTYLE,...
'Linewidth',VERTWIDTH);
end
else
if TIMEX % overplot realigned vt on ERP
plot(repmat(median(aligntime+vt-outsort),1,2),[limit(3),limit(4)],...
DOTSTYLE,'LineWidth',VERTWIDTH);
else
plot([limit(3),limit(4)],repmat(median(aligntime+vt-outsort),1,2),...
DOTSTYLE,'LineWidth',VERTWIDTH);
end
end
end
end
limit = double(limit);
ydelta = double(1/10*(limit(2)-limit(1)));
ytextoffset = double(limit(1)-1.1*ydelta);
ynumoffset = double(limit(1)-0.3*ydelta); % double for Matlab 7
%Far left axis max and min labels not needed now that there are tick
%marks
%t=text(ynumoffset,0.7*limit(3), num2str(limit(3)));
%set(t,'HorizontalAlignment','right','FontSize',TICKFONT)
%t=text(ynumoffset,0.7*limit(4), num2str(limit(4)));
%set(t,'HorizontalAlignment','right','FontSize',TICKFONT)
ynum = 0.7*(limit(3)+limit(4))/2;
t=text(ytextoffset,ynum,yerplabel,'Rotation',90);
set(t,'HorizontalAlignment','center','FontSize',LABELFONT)
if ~exist('YDIR')
error('\nerpimage(): Default YDIR not read from ''icadefs.m''');
end
if YDIR == 1
set(ax2,'ydir','normal')
else
set(ax2,'ydir','reverse')
end
set(ax2,'Fontsize',TICKFONT);
set(ax2,'Box','off','color',BACKCOLOR);
drawnow
end
%
%% %%%%%%%%%%%%%%%%%%% Plot amp, coher time series %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isnan(coherfreq)
if freq > 0
coherfreq = mean(freq); % use phase-sort frequency
end
%
%%%%%% Plot amp axis below ERP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~Allampsflag %%%% don't repeat computation if already done for 'allamps'
fprintf('Computing and plotting amplitude at %g Hz.\n',coherfreq);
if ~isnan(signifs) | Cohsigflag==NO % don't compute or plot signif. levels
[amps,cohers] = phasecoher(urdata,size(times,2),srate,coherfreq,cycles);
if ~isnan(signifs)
ampsig = signifs([1 2]);
fprintf('Using supplied amplitude significance levels: [%g,%g]\n',...
ampsig(1),ampsig(2));
cohsig = signifs(3);
fprintf('Using supplied coherence significance level: %g\n',cohsig);
end
else % compute amps, cohers with significance
fprintf(...
'Computing and plotting %g coherence significance level at %g Hz...\n',...
alpha, coherfreq);
[amps,cohers,cohsig,ampsig] = ...
phasecoher(urdata,size(times,2),srate,coherfreq,cycles,alpha);
fprintf('Coherence significance level: %g\n',cohsig);
ampsig = 20*log10(ampsig); % convert to dB
end
amps = 20*log10(amps); % convert to dB
if isnan(baseamp) % if baseamp not specified in 'limits'
if ~isempty(baselinedb) && isnan(baselinedb(1))
disp('Not removing amplitude baseline');
else
if isempty(baselinedb)
baselinedb = [times(1) DEFAULT_BASELINE_END];
end;
base = find(times >= baselinedb(1) & times<=baselinedb(end)); % use default baseline end point (ms)
if length(base)<2
base = 1:floor(length(times)/4); % default first quarter-epoch
fprintf('Using %g to %g ms as amplitude baseline.\n',...
times(1),times(base(end)));
end
[amps,baseamp] = rmbase(amps,length(times),base); % remove dB baseline
fprintf('Removed baseline amplitude of %d dB for plotting.\n',baseamp);
end;
else % if 'basedB' specified in 'limits' (in dB)
fprintf('Removing specified baseline amplitude of %d dB for plotting.\n',...
baseamp);
amps = amps-baseamp; % remove specified dB baseline
end
fprintf('Data amplitude levels: [%g %g] dB\n',min(amps),max(amps));
if alpha>0 % if computed significance levels
ampsig = ampsig - baseamp;
fprintf('Data amplitude significance levels: [%g %g] dB\n',ampsig(1),ampsig(2));
end
end % ~Allampsflag
if strcmpi(NoShow, 'no')
axis('off') % rm ERP axes axis and labels
v=axis;
minampERP=v(3);
maxampERP=v(4);
if ~exist('ynumoffset')
limit = [timelimits(1:2) -max(abs([minampERP maxampERP])) max(abs([minampERP maxampERP]))];
limit = double(limit);
ydelta = double(1/10*(limit(2)-limit(1)));
ytextoffset = double(limit(1)-1.1*ydelta);
ynumoffset = double(limit(1)-0.3*ydelta); % double for Matlab 7
end
t=text(double(ynumoffset),double(maxampERP),num2str(maxampERP,3));
set(t,'HorizontalAlignment','right','FontSize',TICKFONT);
t=text(double(ynumoffset),double(minampERP), num2str(minampERP,3));
set(t,'HorizontalAlignment','right','FontSize',TICKFONT);
ax3=axes('Position',...
[gcapos(1) gcapos(2)+1/3*image_loy*gcapos(4) ...
gcapos(3) (image_loy/3-YGAP)*gcapos(4)]);
if isnan(maxamp) % if not specified
fac = 1;
maxamp = 0;
while maxamp == 0
maxamp = floor(YEXPAND*fac*max(amps))/fac; % minimal decimal place
fac = 10*fac;
end
maxamp = maxamp + 10/fac;
if Cohsigflag
if ampsig(2)>maxamp
if ampsig(2)>0
maxamp = 1.01*(ampsig(2));
else
maxamp = 0.99*(ampsig(2));
end
end
end
end
if isnan(maxamp), maxamp = 0; end % In case the above iteration went on
% until fac = Inf and maxamp = NaN again.
if isnan(minamp) % if not specified
fac = 1;
minamp = 0;
while minamp == 0
minamp = floor(YEXPAND*fac*max(-amps))/fac; % minimal decimal place
fac = 10*fac;
end
minamp = minamp + 10/fac;
minamp = -minamp;
if Cohsigflag
if ampsig(1)< minamp
if ampsig(1)<0
minamp = 1.01*(ampsig(1));
else
minamp = 0.99*(ampsig(1));
end
end
end
end
if isnan(minamp), minamp = 0; end % In case the above iteration went on
% until fac = Inf and minamp = NaN again.
fprintf('Plotting the ERSP amplitude trace below the ERP\n');
fprintf('Min, max plotting amplitudes: [%g, %g] dB\n',minamp,maxamp);
fprintf(' relative to baseamp: %g dB\n',baseamp);
if Cohsigflag
ampsiglims = [repmat(ampsig(1)-mean(ampsig),1,length(times))];
ampsiglims = [ampsiglims;-1*ampsiglims];
plot1trace(ax3,times,amps,[timelimits minamp(1) maxamp(1)],ampsiglims,[],[],0); % plot AMP
else
plot1trace(ax3,times,amps,[timelimits minamp(1) maxamp(1)],[],[],[],0); % plot AMP
end
if ~isnan(aligntime)
line([aligntime aligntime],[minamp(1) maxamp(1)]*1.1,'Color','k');
% x=median sort value
end
if exist('xtick') % Added -JH
set(ax3,'Xtick',xtick);
end
set(ax3,'Xticklabel',[]); % remove tick labels from bottom of image
set(ax3,'Yticklabel',[]); % remove tick labels from left of image
set(ax3,'YColor',BACKCOLOR);
axis('off');
set(ax3,'Box','off','color',BACKCOLOR);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% plot vert marks %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(verttimes)
if size(verttimes,1) == ntrials
vts=sort(verttimes);
vts = vts(ceil(ntrials/2),:); % plot median values if a matrix
else
vts=verttimes(:)';
end
for vt = vts
if isnan(aligntime)
if TIMEX % overplot vt on amp
mydotstyle = DOTSTYLE;
if exist('auxcolors') & ...
length(verttimes) == length(verttimesColors)
mydotstyle = verttimesColors{find(verttimes == vt)};
end
plot([vt vt],[minamp(1) maxamp(1)],mydotstyle,...
'Linewidth',VERTWIDTH);
else
plot([min(outtrials) max(outtrials)],[minamp(1) maxamp(1)], ...
DOTSTYLE,...
'Linewidth',VERTWIDTH);
end
else
if TIMEX % overplot realigned vt on amp
plot(repmat(median(aligntime+vt-outsort),1,2), ...
[minamp(1),maxamp(1)],DOTSTYLE,...
'LineWidth',VERTWIDTH);
else
plot([minamp,maxamp],repmat(median(aligntime+vt-outsort),1,2), ...
DOTSTYLE,...
'LineWidth',VERTWIDTH);
end
end
end
end
if 0 % Cohsigflag % plot amplitude significance levels
hold on
plot([timelimits(1) timelimits(2)],[ampsig(1) ampsig(1)] - mean(ampsig),'r',...
'linewidth',SIGNIFWIDTH);
plot([timelimits(1) timelimits(2)],[ampsig(2) ampsig(2)] - mean(ampsig),'r',...
'linewidth',SIGNIFWIDTH);
end
if ~exist('ynumoffset')
limit = [timelimits(1:2) -max(abs([minamp maxamp])) max(abs([minamp maxamp]))];
limit = double(limit);
ydelta = double(1/10*(limit(2)-limit(1)));
ytextoffset = double(limit(1)-1.1*ydelta);
ynumoffset = double(limit(1)-0.3*ydelta); % double for Matlab 7
end
t=text(ynumoffset,maxamp, num2str(maxamp,3));
set(t,'HorizontalAlignment','right','FontSize',TICKFONT);
t=text(ynumoffset,0, num2str(0));
set(t,'HorizontalAlignment','right','FontSize',TICKFONT);
t=text(ynumoffset,minamp, num2str(minamp,3));
set(t,'HorizontalAlignment','right','FontSize',TICKFONT);
t=text(ytextoffset,(maxamp+minamp)/2,'ERSP','Rotation',90);
set(t,'HorizontalAlignment','center','FontSize',LABELFONT);
axtmp = axis;
dbtxt= text(1/13*(axtmp(2)-axtmp(1))+axtmp(1), ...
11/13*(axtmp(4)-axtmp(3))+axtmp(3), ...
[num2str(baseamp,4) ' dB']);
set(dbtxt,'fontsize',TICKFONT);
drawnow;
set(ax3, 'xlim', timelimits);
set(ax3, 'ylim', [minamp(1) maxamp(1)]);
%
%%%%%% Make coher axis below amp %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
ax4=axes('Position',...
[gcapos(1) gcapos(2) ...
gcapos(3) (image_loy/3-YGAP)*gcapos(4)]);
if isnan(maxcoh)
fac = 1;
maxcoh = 0;
while maxcoh == 0
maxcoh = floor(YEXPAND*fac*max(cohers))/fac; % minimal decimal place
fac = 10*fac;
end
maxcoh = maxcoh + 10/fac;
if maxcoh>1
maxcoh=1; % absolute limit
end
end
if isnan(mincoh)
mincoh = 0;
end
fprintf('Plotting the ITC trace below the ERSP\n');
if Cohsigflag % plot coherence significance level
cohsiglims = [repmat(cohsig,1,length(times));zeros(1,length(times))];
coh_handle = plot1trace(ax4,times,cohers,[timelimits mincoh maxcoh],cohsiglims,[],[],0);
% plot COHER, fill sorting window
else
coh_handle = plot1trace(ax4,times,cohers,[timelimits mincoh maxcoh],[],[],[],0); % plot COHER
end
if ~isnan(aligntime)
line([aligntime aligntime],[[mincoh maxcoh]*1.1],'Color','k');
% x=median sort value
end
% set(ax4,'Xticklabel',[]); % remove tick labels from bottom of
% image
if exist('xtick')
set(ax4,'Xtick',xtick);
set(ax4,'Xticklabel',xticklabel);
end
set(ax4,'Ytick',[]);
set(ax4,'Yticklabel',[]); % remove tick labels from left of image
set(ax4,'YColor',BACKCOLOR);
if ~isempty(verttimes)
if size(verttimes,1) == ntrials
vts=sort(verttimes);
vts = vts(ceil(ntrials/2),:); % plot median values if a matrix
else
vts = verttimes(:)'; % make verttimes a row vector
end
for vt = vts
if isnan(aligntime)
if TIMEX % overplot vt on coher
mydotstyle = DOTSTYLE;
if exist('auxcolors') & ...
length(verttimes) == length(verttimesColors)
mydotstyle = verttimesColors{find(verttimes == vt)};
end
plot([vt vt],[mincoh maxcoh],mydotstyle,'Linewidth',VERTWIDTH);
else
plot([min(outtrials) max(outtrials)],...
[mincoh maxcoh],DOTSTYLE,'Linewidth',VERTWIDTH);
end
else
if TIMEX % overplot realigned vt on coher
plot(repmat(median(aligntime+vt-outsort),1,2),...
[mincoh,maxcoh],DOTSTYLE,'LineWidth',VERTWIDTH);
else
plot([mincoh,maxcoh],repmat(median(aligntime+vt-outsort),1,2),...
DOTSTYLE,'LineWidth',VERTWIDTH);
end
end
end
end
t=text(ynumoffset,0, num2str(0));
set(t,'HorizontalAlignment','right','FontSize',TICKFONT);
t=text(ynumoffset,maxcoh, num2str(maxcoh));
set(t,'HorizontalAlignment','right','FontSize',TICKFONT);
t=text(ytextoffset,maxcoh/2,'ITC','Rotation',90);
set(t,'HorizontalAlignment','center','FontSize',LABELFONT);
drawnow
%if Cohsigflag % plot coherence significance level
%hold on
%plot([timelimits(1) timelimits(2)],[cohsig cohsig],'r',...
%'linewidth',SIGNIFWIDTH);
%end
set(ax4,'Box','off','color',BACKCOLOR);
set(ax4,'Fontsize',TICKFONT);
if NoTimeflag==NO
if exist('NoTimesPassed')~=1
l=xlabel('Time (ms)');
else
l=xlabel('Frames');
end
set(l,'Fontsize',LABELFONT);
end
axtmp = axis;
hztxt=text(10/13*(axtmp(2)-axtmp(1))+axtmp(1), ...
8/13*(axtmp(4)-axtmp(3))+axtmp(3), ...
[num2str(coherfreq,4) ' Hz']);
set(hztxt,'fontsize',TICKFONT);
end;% NoShow
else
amps = []; % null outputs unless coherfreq specified
cohers = [];
end
if VERS >= 8.04
axhndls = {ax1 axcb ax2 ax3 ax4};
else
axhndls = [ax1 axcb ax2 ax3 ax4];
end
if exist('ur_outsort')
outsort = ur_outsort; % restore outsort clipped values, if any
end
if nargout<1
data = []; % don't spew out data if no args out and no ;
end
%
%% %%%%%%%%%%%%% Plot a topoplot() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if (~isempty(topomap)) & strcmpi(NoShow, 'no')
h(12)=axes('Position',...
[gcapos(1)+0.10*gcapos(3) gcapos(2)+0.92*gcapos(4),...
0.20*gcapos(3) 0.14*gcapos(4)]);
% h(12) = subplot('Position',[.10 .86 .20 .14]);
fprintf('Plotting a topo map in upper left.\n');
eloc_info.plotrad = [];
if length(topomap) == 1
try
topoplot(topomap,eloc_file,'electrodes','off', ...
'style', 'blank', 'emarkersize1chan', 10, 'chaninfo', eloc_info);
catch
fprintf('topoplot() plotting failed.\n');
end;
else
try
topoplot(topomap,eloc_file,'electrodes','off', 'chaninfo', eloc_info);
catch
fprintf('topoplot() plotting failed.\n');
end;
end;
axis('square')
if VERS >= 8.04
axhndls = {axhndls h(12)};
else
axhndls = [axhndls h(12)];
end
end
%
%% %%%%%%%%%%%%% Plot a spectrum %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
SPECFONT = 10;
if (~isempty(lospecHz)) && strcmpi(NoShow, 'no')
h(13)=axes('Position',...
[gcapos(1)+0.82*gcapos(3) ...
gcapos(2)+0.96*gcapos(4),...
0.15*gcapos(3)*(0.8/gcapos(3))^0.5 ...
0.10*gcapos(4)*(0.8/gcapos(4))^0.5]);
% h(13) = subplot('Position',[.75 .88 .15 .10]);
fprintf('Plotting the data spectrum in upper right.\n');
winlength = frames;
if winlength > 512
for k=2:5
if rem(winlength,k) == 0
break
end
end
winlength = winlength/k;
end
% [Pxx, Pxxc, F] = PSD(X,NFFT,Fs,WINDOW,NOVERLAP,P)
if exist('psd') == 2
[Pxx,F] = psd(reshape(urdata,1,size(urdata,1)*size(urdata,2)),...
max(1024,pow2(ceil(log2(frames)))),srate,frames,0,0.05);
% [Pxx,F] = psd(reshape(urdata,1,size(urdata,1)*size(urdata,2)),512,srate,winlength,0,0.05);
else
[Pxx,F] = spec(reshape(urdata,1,size(urdata,1)*size(urdata,2)),...
max(1024,pow2(ceil(log2(frames)))),srate,frames,0);
% [Pxx,F] = spec(reshape(urdata,1,size(urdata,1)*size(urdata,2)),512,srate,winlength,0);
end;
plot(F,10*log10(Pxx));
goodfs = find(F>= lospecHz & F <= hispecHz);
maxgfs = max(10*log10(Pxx(goodfs)));
mingfs = min(10*log10(Pxx(goodfs)));
axis('square')
axis([lospecHz hispecHz mingfs-1 maxgfs+1]);
set(h(13),'Box','off','color',BACKCOLOR);
set(h(13),'Fontsize',SPECFONT);
set(h(13),'Xscale',SpecAxis); % added 'log' or 'linear' freq axis scaling -SM 5/31/12
l=ylabel('dB');
set(l,'Fontsize',SPECFONT);
if ~isnan(coherfreq)
hold on; plot([coherfreq,coherfreq],[mingfs maxgfs],'r');
end
if VERS >= 8.04
axhndls = {axhndls h(13)};
else
axhndls = [axhndls h(13)];
end
end
%
%% %%%%%%%%%%%%% save plotting limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
limits = [min(times) max(times) minerp maxerp minamp maxamp mincoh maxcoh];
limits = [limits baseamp coherfreq]; % add coherfreq to output limits array
%
%% %%%%%%%%%%%%% turn on axcopy() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
axcopy(gcf);
% eegstr = 'img=get(gca,''''children''''); if (strcmp(img(end),''''type''''),''''image''''), img=get(img(end),''''CData''''); times=get(img(end),''''Xdata''''); clf; args = [''''limits'''' '''','''' times(1) '''','''' times(end)]; if exist(''''EEG'''')==1, args = [args '''','''' ''''srate'''' '''','''' EEG.srate]; end eegplot(img,args); end';
% axcopy(gcf,eegstr);
end;
% returning outsort
if exist('outpercent')
outsort = { outsort outpercent };
end;
fprintf('Done.\n\n');
%
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%% End erpimage() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(NoShow, 'no')
axes('position',gcapos);
axis off
end;
warning on;
return
%
%% %%%%%%%%%%%%%%%%% function plot1trace() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
function [plot_handle] = plot1trace(ax,times,trace,axlimits,signif,stdev,winlocs,erp_grid,erp_vltg_ticks)
%function [plot_handle] = plot1trace(ax,times,trace,axlimits,signif,stdev,winlocs,erp_grid,erp_vltg_ticks)
% If signif is [], plot trace +/- stdev
% Else if signif, plot trace and signif(1,:)&signif(2,:) fill.
% Else, plot trace alone.
% If winlocs not [], plot grey back image(s) in sort window
% winlocs(1,1)-> winlocs(1,end) (ms)
% ...
% winlocs(end,1)-> winlocs(end,end) (ms)
FILLCOLOR = [.66 .76 1];
WINFILLCOLOR = [.88 .92 1];
ERPDATAWIDTH = 2;
ERPZEROWIDTH = 2;
axes(ax);
if nargin<9,
erp_vltg_ticks=[]; %if erp_vltg_ticks is not empty, those will be the ticks used on the y-axis (voltage axis for ERPs)
end
if ~isempty(winlocs)
for k=1:size(winlocs,1)
winloc = winlocs(k,:);
fillwinx = [winloc winloc(end:-1:1)];
hannwin = makehanning(length(winloc));
hannwin = hannwin./max(hannwin); % make max = 1
hannwin = hannwin(:)'; % make row vector
if ~isempty(axlimits) & sum(isnan(axlimits))==0
% fillwiny = [repmat(axlimits(3),1,length(winloc)) repmat(axlimits(4),1,length(winloc))];
fillwiny = [hannwin*axlimits(3) hannwin*axlimits(4)];
else
% fillwiny = [repmat(min(trace)*1.1,1,length(winloc)) repmat(max(trace)*1.1,1,length(winloc))];
fillwiny = [hannwin*2*min(trace) hannwin*2*max(trace)];
end
fillwh = fill(fillwinx,fillwiny, WINFILLCOLOR); hold on % plot 0+alpha
set(fillwh,'edgecolor',WINFILLCOLOR-[.00 .00 0]); % make edges NOT highlighted
end
end
if ~isempty(signif);% (2,times) array giving upper and lower signif limits
filltimes = [times times(end:-1:1)];
if size(signif,1) ~=2 | size(signif,2) ~= length(times)
fprintf('plot1trace(): signif array must be size (2,frames)\n')
return
end
fillsignif = [signif(1,:) signif(2,end:-1:1)];
fillh = fill(filltimes,fillsignif, FILLCOLOR); hold on % plot 0+alpha
set(fillh,'edgecolor',FILLCOLOR-[.02 .02 0]); % make edges slightly highlighted
% [plot_handle] = plot(times,signif, 'r','LineWidth',1); hold on % plot 0+alpha
% [plot_handle] = plot(times,-1*signif, 'r','LineWidth',1); hold on % plot 0-alpha
end
if ~isempty(stdev)
[st1] = plot(times,trace+stdev, 'r--','LineWidth',1); hold on % plot trace+stdev
[st2] = plot(times,trace-stdev, 'r--','LineWidth',1); hold on % plot trace-stdev
end
%linestyles={'r','m','c','b'};
% 'LineStyle',linestyles{traceloop}); hold on
linecolor={[0 0 1],[.25 0 .75],[.75 0 .25],[1 0 0]};
plot_handle=zeros(1,size(trace,1));
for traceloop=1:size(trace,1),
[plot_handle(traceloop)] = plot(times,trace(traceloop,:),'LineWidth',ERPDATAWIDTH, ...
'color',linecolor{traceloop}); hold on
end
%Assume that multiple traces are equally sized divisions of data
switch size(trace,1),
case 2
legend('Lower 50%','Higher 50%');
case 3
legend('Lowest 33%','Middle 33%','Highest 33%');
case 4
legend('Lowest 25%','2nd Lowest 25%','3rd Lowest 25%','Highest 25%');
end
if ~isempty(axlimits) && sum(isnan(axlimits))==0
if axlimits(2)>axlimits(1) && axlimits(4)>axlimits(3)
axis([axlimits(1:2) 1.1*axlimits(3:4)])
end
l1=line([axlimits(1:2)],[0 0], 'Color','k',...
'linewidth',ERPZEROWIDTH); % y=zero-line
timebar=0;
l2=line([1 1]*timebar,axlimits(3:4)*1.1,'Color','k',...
'linewidth',ERPZEROWIDTH); % x=zero-line
%y-ticks
if isempty(erp_vltg_ticks),
shrunk_ylimits=axlimits(3:4)*.8;
ystep=(shrunk_ylimits(2)-shrunk_ylimits(1))/4;
if ystep>1,
ystep=round(ystep);
else
ord=orderofmag(ystep);
ystep=round(ystep/ord)*ord;
end
if (sign(shrunk_ylimits(2))*sign(shrunk_ylimits(1)))==1, %y shrunk_ylimits don't include 0
erp_yticks=shrunk_ylimits(1):ystep:shrunk_ylimits(2);
else %y limits include 0
% erp_yticks=0:ystep:shrunk_ylimits(2); %ensures 0 is a tick point
% erp_yticks=[erp_yticks [0:-ystep:shrunk_ylimits(1)]];
erp_yticks=0:ystep:axlimits(4); %ensures 0 is a tick point
erp_yticks=[erp_yticks [0:-ystep:axlimits(3)]];
end
if erp_grid,
set(gca,'ytick',unique(erp_yticks),'ygrid','on');
else
set(gca,'ytick',unique(erp_yticks));
end
else
set(gca,'ytick',erp_vltg_ticks);
end
end
%make ERP traces on top
kids=get(gca,'children')';
for hndl_loop=plot_handle,
id=find(kids==hndl_loop);
kids(id)=[];
kids=[hndl_loop kids];
end
set(gca,'children',kids');
plot_handle=[plot_handle l1 l2];
%
%% %%%%%%%%%%%%%%%%% function phasedet() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% phasedet() - function used in erpimage.m
% Constructs a complex filter at frequency freq
%
function [ang,amp,win] = phasedet(data,frames,srate,nwin,freq)
% Typical values:
% frames = 768;
% srate = 256; % Hz
% nwin = [200:300];
% freq = 10; % Hz
data = reshape(data,[frames prod(size(data))/frames]);
% number of cycles depends on window size
% number of cycles automatically reduced if smaller window
% Note: as the number of cycles changes, the frequency shifts
% a little -- this should be fixed
win = exp(2i*pi*freq(:)*[1:length(nwin)]/srate);
win = win .* repmat(makehanning(length(nwin))',length(freq),1);
%tmp =gcf; figure; plot(real(win)); figure(tmp);
%fprintf('ANY NAN ************************* %d\n', any(any(isnan( data(nwin,:)))));
tmpdata = data(nwin,:) - repmat(mean(data(nwin,:), 1), [size(data,1) 1]);
resp = win * tmpdata;
ang = angle(resp);
amp = abs(resp);
%
%% %%%%%%%%%%%% function prctle() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
function prctl = prctle(data,pc); % return percentile of a distribution
[prows pcols] = size(pc);
if prows ~= 1 & pcols ~= 1
error('\nerpimage(): pc must be a scalar or a vector.');
end
if any(pc > 100) | any(pc < 0)
error('\nerpimage(): pc must be between 0 and 100');
end
[i,j] = size(data);
sortdata = sort(data);
if i==1 | j==1 % if data is a vector
i = max(i,j); j = 1;
if i == 1,
fprintf(' prctle() note: input data is a single scalar!\n')
y = data*ones(length(pc),1); % if data is scalar, return it
return;
end
sortdata = sortdata(:);
end
pt = [0 100*((1:i)-0.5)./i 100];
sortdata = [min(data); sortdata; max(data)];
prctl = interp1(pt,sortdata,pc);
%
%% %%%%%%%%%%%%%%%%%%%%% function nan_mean() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% nan_mean() - Take the column means of a matrix, ignoring NaN values.
% Return significance bounds if alpha (0 < alpha< <1) is given.
%
function [out, outalpha] = nan_mean(in,alpha)
NPERM = 500;
intrials = size(in,1);
inframes = size(in,2);
nans = find(isnan(in));
in(nans) = 0;
sums = sum(in);
nonnans = ones(size(in));
nonnans(nans) = 0;
nonnans = sum(nonnans);
nononnans = find(nonnans==0);
nonnans(nononnans) = 1;
out = sum(in)./nonnans;
outalpha = [];
if nargin>1
if NPERM < round(3/alpha)
NPERM = round(3/alpha);
end
fprintf('Performing a permuration test using %d permutations to determine ERP significance thresholds... ',NPERM);
permerps = zeros(NPERM,inframes);
for n=1:NPERM
signs = sign(randn(1,intrials)'-0.5);
permerps(n,:) = sum(repmat(signs,1,inframes).*in)./nonnans;
if ~rem(n,50)
fprintf('%d ',n);
end
end
fprintf('\n');
permerps = sort(abs(permerps));
alpha_bnd = floor(2*alpha*NPERM); % two-sided probability threshold
outalpha = permerps(end-alpha_bnd,:);
end
out(nononnans) = NaN;
%
%% %%%%%%%%%%%%%%%%%%%%% function nan_std() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
function out = nan_std(in)
nans = find(isnan(in));
in(nans) = 0;
nonnans = ones(size(in));
nonnans(nans) = 0;
nonnans = sum(nonnans);
nononnans = find(nonnans==0);
nonnans(nononnans) = 1;
out = sqrt((sum(in.^2)-sum(in).^2./nonnans)./(nonnans-1));
out(nononnans) = NaN;
% symmetric hanning function
function w = makehanning(n)
if ~rem(n,2)
w = 0.5*(1 - cos(2*pi*(1:n/2)'/(n+1)));
w = [w; w(end:-1:1)];
else
w = 0.5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1)));
w = [w; w(end-1:-1:1)];
end
%
%% %%%%%%%%%%%%%%%%%%%%% function compute_percentile() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
function outpercent = compute_percentile(sortvar, percent, outtrials, winsize);
ntrials = length(sortvar);
outtrials=round(outtrials);
sortvar = [ sortvar sortvar sortvar ];
winvals = [round(-winsize/2):round(winsize/2)];
outpercent = zeros(size(outtrials));
for index = 1:length(outtrials)
sortvarval = sortvar(outtrials(index)+ntrials+winvals);
sortvarval = sort(sortvarval);
outpercent(index) = sortvarval(round((length(winvals)-1)*percent)+1);
end;
%
%% %%%%%%%%%%%%%%%%%%%%% function orderofmag() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
function ord=orderofmag(val)
%function ord=orderofmag(val)
%
% Returns the order of magnitude of the value of 'val' in multiples of 10
% (e.g., 10^-1, 10^0, 10^1, 10^2, etc ...)
% used for computing erpimage trial axis tick labels as an alternative for
% plotting sorting variable
val=abs(val);
if val>=1
ord=1;
val=floor(val/10);
while val>=1,
ord=ord*10;
val=floor(val/10);
end
return;
else
ord=1/10;
val=val*10;
while val<1,
ord=ord/10;
val=val*10;
end
return;
end
%
%% %%%%%%%%%%%%%%%%%%%%% function find_crspnd_pt() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
function y_pt=find_crspnd_pt(targ,vals,outtrials)
%function id=find_crspnd_pt(targ,vals,outtrials)
%
% Inputs:
% targ - desired value of sorting variable
% vals - a vector of observed sorting variables (possibly smoothed)
% outtrials - a vector of y-axis values corresponding to trials in the
% ERPimage (this will just be 1:n_trials if there's no
% smoothing)
%
% Output:
% y_pt - y-axis value (in units of trials) corresponding to "targ".
% If "targ" matches more than one y-axis pt, the median point is
% returned. If "targ" falls between two points, y_pt is linearly
% interpolated.
%
% Note: targ and vals should be in the same units (e.g., milliseconds)
%find closest point above
abv=find(vals>=targ);
if isempty(abv),
%point lies outside of vals range, can't interpolate
y_pt=[];
return
end
abv=abv(1);
%find closest point below
blw=find(vals<=targ);
if isempty(blw),
%point lies outside of vals range, can't interpolate
y_pt=[];
return
end
blw=blw(end);
if (vals(abv)==vals(blw)),
%exact match
ids=find(vals==targ);
y_pt=median(outtrials(ids));
else
%interpolate point
%lst squares inear regression
B=regress([outtrials(abv) outtrials(blw)]',[ones(2,1) [vals(abv) vals(blw)]']);
%predict outtrial point from target value
y_pt=[1 targ]*B;
end
|
github
|
lcnbeapp/beapp-master
|
readegi.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/readegi.m
| 5,517 |
utf_8
|
de08c5adb26f9e5f5987d0b8a286debe
|
% readegi() - read EGI Simple Binary datafile (versions 2,3,4,5,6,7).
% Return header info, EEG data, and any event data.
% Usage:
% >> [head, TrialData, EventData, CatIndex] = readegi(filename, dataChunks, forceversion)
%
% Required Input:
% filename = EGI data filename
%
% Optional Input:
% dataChunks = vector containing desired frame numbers(for unsegmented
% datafiles) or segments (for segmented files). If this
% input is empty or is not provided then all data will be
% returned.
% forceversion = integer from 2 to 7 which overrides the EGI version read from the
% file header. This has been occasionally necessary in cases where
% the file format was incorrectly indicated in the header.
% Outputs:
% head = struct containing header info (see readegihdr() )
% TrialData = EEG channel data
% EventData = event codes
% CatIndex = segment category indices
%
% Author: Cooper Roddey, SCCN, 13 Nov 2002
%
% Note: code derived from C source code written by
% Tom Renner at EGI, Inc.
%
% See also: readegihdr()
% Copyright (C) 2002 , Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [head, TrialData, EventData, SegmentCatIndex] = readegi(filename, dataChunks,forceversion)
if nargin <1 | nargin > 3,
help readegi;
return;
end
if nargout < 2 | nargout > 4,
error('2 to 4 output args required');
end
if ~exist('dataChunks','var')
dataChunks = [];
end
if ~isvector(dataChunks)
error('dataChunks must either be empty or a vector');
end
[fid,message] = fopen(filename,'rb','b');
if (fid < 0),
error(message);
end
% get our header structure
fprintf('Importing binary EGI data file ...\n');
if exist('forceversion')
head = readegihdr(fid,forceversion);
else
head = readegihdr(fid);
end
% do we have segmented data?
segmented = 0;
switch(head.version),
case {2,4,6}
segmented = 0;
case {3,5,7}
segmented = 1;
end
% each type of event has a dedicated "channel"
FrameVals = head.nchan + head.eventtypes;
if (segmented)
desiredSegments = dataChunks;
if isempty(desiredSegments),
desiredSegments = [1:head.segments];
end
nsegs = length(desiredSegments);
TrialData = zeros(FrameVals,head.segsamps*nsegs);
readexpected = FrameVals*head.segsamps*nsegs;
else
desiredFrames = dataChunks;
if isempty(desiredFrames),
desiredFrames = [1:head.samples];
end
nframes = length(desiredFrames);
TrialData = zeros(FrameVals,nframes);
readexpected = FrameVals*nframes;
end
% get datatype from version number
switch(head.version)
case {2,3}
datatype = 'integer*2';
case {4,5}
datatype = 'float32';
case {6,7}
datatype = 'float64';
otherwise,
error('Unknown data format');
end
% read in epoch data
readtotal = 0;
j=0;
SegmentCatIndex = [];
if (segmented),
for i=1:head.segments,
segcatind = fread(fid,1,'integer*2');
segtime = fread(fid,1,'integer*4');
[tdata, count] = ...
fread(fid,[FrameVals,head.segsamps],datatype);
% check if this segment is one of our desired ones
if ismember(i,desiredSegments)
j=j+1;
SegmentCatIndex(j) = segcatind;
SegmentStartTime(j) = segtime;
TrialData(:,[1+(j-1)*head.segsamps:j*head.segsamps]) = tdata;
readtotal = readtotal + count;
end
if (j >= nsegs), break; end;
end;
else
% read unsegmented data
% if dataChunks is empty, read all frames
if isempty(dataChunks)
[TrialData, readtotal] = fread(fid, [FrameVals,head.samples],datatype);
else % grab only the desiredFrames
% This could take a while...
for i=1:head.samples,
[tdata, count] = fread(fid, [FrameVals,1],datatype);
% check if this segment is a keeper
if ismember(i,desiredFrames),
j=j+1;
TrialData(:,j) = tdata;
readtotal = readtotal + count;
end
if (j >= nframes), break; end;
end
end
end
fclose(fid);
if ~isequal(readtotal, readexpected)
error('Number of values read not equal to the number expected.');
end
EventData = [];
if (head.eventtypes > 0),
EventData = TrialData(head.nchan+1:end,:);
TrialData = TrialData(1:head.nchan,:);
end
% convert from A/D units to microvolts
if ( head.bits ~= 0 & head.range ~= 0 )
TrialData = (head.range/(2^head.bits))*TrialData;
end
% convert event codes to char
% ---------------------------
head.eventcode = char(head.eventcode);
%--------------------------- isvector() ---------------
function retval = isvector(V)
s = size(V);
retval = ( length(s) < 3 ) & ( min(s) <= 1 );
%------------------------------------------------------
|
github
|
lcnbeapp/beapp-master
|
compvar.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/compvar.m
| 2,725 |
utf_8
|
7116923a815fb34f3c3c092817999c9e
|
% compvar() - project selected components and compute the variance of
% the original data they account for.
%
% Usage:
% >> [proj, variance] = compvar( data, wts_or_act, winv, components);
%
% Required Inputs:
% data - 2-D (channels, points) or 3-D (channels, frames, trials)
% data array.
% wts_or_act - {sphere weights} cell array containing the ICA sphere
% and weights matrices. May also be a 2-D (channels, points)
% or 3-D (channels, frames, trials) array of component
% activations.
% winv - inverse or pseudo-inverse of the product of the weights
% and sphere matrices returned by the ICA decompnumsition,
% i.e., inv(weights*sphere) or pinv(weights*sphere).
% components - array of component indices to back-project
%
% Outputs:
% proj - summed back-projections of the specified components
% pvaf - percent variance of the data that the selected
% components account for (range: 100% to -Inf%).
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ compproj, varegg ] = compvar( data, act, winv, compnums)
if nargin < 4
help compvar;
return;
end;
if iscell(act) && length(act) == 1
act = act{1};
end;
data = reshape(data, size(data,1), size(data,2)*size(data,3));
act = reshape(act , size(act ,1), size(act ,2)*size( act,3));
squaredata = sum(sum(data.^2)); % compute the grand sum-squared data
if iscell(act)
sphere = act{1};
weight = act{2};
act = (weight*sphere)*data;
end;
compproj = winv(:,compnums)*act(compnums,:)-data; % difference between data and back-projection
squarecomp = sum(sum(compproj.^2)); % the summed-square difference
varegg = 100*(1- squarecomp/squaredata); % compute pvaf of components in data
compproj = compproj+data; % restore back-projected data
return;
|
github
|
lcnbeapp/beapp-master
|
plotsphere.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/plotsphere.m
| 4,822 |
utf_8
|
5a1e3b5a681d7d5be1d6ad3d5a0d3f0e
|
% plotsphere() - This function is used to plot a sphere and
% project them onto specific surfaces. This may
% be used for plotting dipoles for instance.
%
% Usage:
% >> handle = plotsphere(pos, rad, 'key', 'val')
%
% Inputs:
% pos - [x y z] 3-D position of the sphere center
% rad - [real] sphere radius
%
% Optional inputs:
% 'nvert' - number of vertices. Default is 15.
% 'color' - sphere color. Default is red.
% 'proj' - [x y z] project sphere to 3-D axes. Enter NaN for not
% projecting. For instance [-40 NaN -80] will project
% the sphere on the y/z plane axis at position x=-40 and on
% the x/y plane at position z=-80.
% 'projcol' - color of projected spheres
% 'colormap' - [real] sphere colormap { default: jet }
%
% Output:
% handle - sphere graphic handle(s). If projected sphere are ploted
% handles of plotted projected spheres are also returned.
%
% Example:
% figure; plotsphere([3 2 2], 1, 'proj', [0 0 -1]);
% axis off; axis equal; lighting phong; camlight left; view([142 48])
%
% Authors: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2004
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright (C) Arnaud Delorme, 2004
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [handles] = plotsphere(pos, rad, varargin);
if nargin < 2
help plotsphere;
return;
end;
g = finputcheck(varargin, { 'color' { 'real','string' } [] [1 0 0];
'nvert' 'integer' [2 Inf] 15;
'proj' 'real' [] [];
'colormap' 'real' [] jet(64);
'projcol' { 'real','string' } [] [0 0 0] }, 'plotsphere');
if isstr(g), error(g); end;
% decode color if necessary
% -------------------------
if ~isstr(g.color) & length(g.color) == 1
g.color = g.colormap(g.color,:);
elseif isstr(g.color)
g.color = strcol2real(g.color);
end;
if ~isstr(g.projcol) & length(g.projcol) == 1
g.projcol = g.colormap(g.projcol,:);
elseif isstr(g.projcol)
g.projcol = strcol2real(g.projcol);
end;
% ploting sphere
% ==============
[xstmp ystmp zs] = sphere(g.nvert);
l=sqrt(xstmp.*xstmp+ystmp.*ystmp+zs.*zs);
normals = reshape([xstmp./l ystmp./l zs./l],[g.nvert+1 g.nvert+1 3]);
xs = pos(1) + rad*ystmp;
ys = pos(2) + rad*xstmp;
zs = pos(3) + rad*zs;
colorarray = repmat(reshape(g.color , 1,1,3), [size(zs,1) size(zs,2) 1]);
hold on;
handles = surf(xs, ys, zs, colorarray, 'tag', 'tmpmov', 'EdgeColor','none', 'VertexNormals', normals, ...
'backfacelighting', 'lit', 'facelighting', 'phong', 'facecolor', 'interp', 'ambientstrength', 0.3);
%axis off; axis equal; lighting phong; camlight left; rotate3d
% plot projections
% ================
if ~isempty(g.proj)
colorarray = repmat(reshape(g.projcol, 1,1,3), [size(zs,1) size(zs,2) 1]);
if ~isnan(g.proj(1)), handles(end+1) = surf(g.proj(1)*ones(size(xs)), ys, zs, colorarray, ...
'edgecolor', 'none', 'facelighting', 'none'); end;
if ~isnan(g.proj(2)), handles(end+1) = surf(xs, g.proj(2)*ones(size(ys)), zs, colorarray, ...
'edgecolor', 'none', 'facelighting', 'none'); end;
if ~isnan(g.proj(3)), handles(end+1) = surf(xs, ys, g.proj(3)*ones(size(zs)), colorarray, ...
'edgecolor', 'none', 'facelighting', 'none'); end;
end;
function color = strcol2real(color)
switch color
case 'r', color = [1 0 0];
case 'g', color = [0 1 0];
case 'b', color = [0 0 1];
case 'c', color = [0 1 1];
case 'm', color = [1 0 1];
case 'y', color = [1 1 0];
case 'k', color = [0 0 0];
case 'w', color = [1 1 1];
otherwise, error('Unknown color');
end;
|
github
|
lcnbeapp/beapp-master
|
projtopo.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/projtopo.m
| 4,459 |
utf_8
|
dd1586daff2737f20be375d9f4e19666
|
% projtopo() - plot projections of one or more ICA components along with
% the original data in a 2-d topographic array. Returns
% the data plotted. Click on subplot to examine separately.
% Usage:
% >> [projdata] = projtopo(data,weights,[compnums],'chan_locs',...
% 'title',[limits],colors,chans);
% Inputs:
% data = single epoch of runica() input data (chans,frames)
% weights = unimxing weight matrix (runica() weights*sphere)
% [compnums] = vector of component numbers to project and plot
% 'chan_locs' = channel locations file. Example: >> topoplot example
% Else [rows cols] for rectangular grid array
% Optional:
% 'title' = (short) plot title {default|0 -> none}
% [limits] = [xmin xmax ymin ymax] (x's in msec)
% {default|0|both y's 0 -> use data limits}
% colors = file of color codes, 3 chars per line ('.' = space)
% {default|0 -> default color order (black/white first)}
% chans = vector of channel numbers to plot {default|0: all}
%
% Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 04-02-98
%
% See also: plotproj(), topoplot()
% Copyright (C) 04-02-98 from plotproj() Scott Makeig, SCCN/INC/UCSD,
% [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% Without color arg, reads filename for PROJCOLORS from icadefs.m
% 03-15-00 added plotchans arg -sm
% 03-16-00 added axcopy() feature -sm & tpj
% 12-19-00 adjusted new icaproj() args -sm
% 12-20-00 removed argument "sphere" -sm
% 07-12-01 fixed nargin test to allow 8 args -sm & cmk
% 01-25-02 reformated help & license, added links -ad
function [projdata] = projtopo(data,weights,compnums,chan_locs,titl,limits,colors,plotchans)
icadefs % read default PROJCOLORS & MAXPLOTDATACHANS variables from icadefs.m
axsize = 0; % use plottopo() default
DEFAULT_TITLE = '';
%
% Substitute for missing arguments
%
if nargin < 7,
colors = 'white1st.col';
elseif colors==0 | isempty(colors)
colors = 'white1st.col';
end
if nargin < 6,
limits = 0;
end
if nargin < 5,
titl = 0;
end
if titl==0,
titl = DEFAULT_TITLE;
end
if nargin < 4 | nargin > 8
help projtopo
fprintf('projtopo(): requires 4-8 arguments.\n\n');
return
end
%
% Test data size
%
[chans,framestot] = size(data);
if ~exist('plotchans') | isempty(plotchans) | plotchans==0
plotchans = 1:chans; % default
end
frames = framestot; % assume one epoch
[wr,wc] = size(weights);
%
% Substitute for 0 arguments
%
if compnums == 0,
compnums = [1:wr];
end;
if size(compnums,1)>1, % handle column of compnums !
compnums = compnums';
end;
if length(compnums) > MAXPLOTDATACHANS,
fprintf(...
'projtopo(): cannot plot more than %d channels of data at once.\n',...
MAXPLOTDATACHANS);
return
end;
if max(compnums)>wr,
fprintf(...
'\n projtopo(): Component index (%d) > number of components (%d).\n', ...
max(compnums),wr);
return
end
fprintf('Reconstructing (%d chan, %d frame) data summing %d components.\n', ...
chans,frames,length(compnums));
%
% Compute projected data for single components
%
projdata = data;
fprintf('projtopo(): Projecting component(s) ');
for s=compnums, % for each component
fprintf('%d ',s);
proj = icaproj(data,weights,s); % let offsets distribute
projdata = [projdata proj]; % append projected data onto projdata
end;
fprintf('\n');
%
% Make the plot
%
% >> plottopo(data,'chan_locs',frames,limits,title,channels,axsize,colors,ydir)
plottopo(projdata,chan_locs,size(data,2),limits,titl,plotchans,axsize,colors);
% make the plottopo() plot
axcopy(gcf);
|
github
|
lcnbeapp/beapp-master
|
voltype.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/voltype.m
| 677 |
utf_8
|
28455ecff10043767463871fdedc4413
|
% VOLTYPE determines the type of volume conduction model
%
% Use as
% [type] = voltype(vol)
% to get a string describing the type, or
% [flag] = voltype(vol, desired)
% to get a boolean value.
%
% See also COMPUTE_LEADFIELD
% Copyright (C) 2007, Robert Oostenveld
%
function [type] = voltype(vol, desired)
if isfield(vol, 'type')
type = vol.type;
elseif isfield(vol, 'r') && prod(size(vol.r))==1
type = 'singlesphere';
elseif isfield(vol, 'r') && isfield(vol, 'o') && all(size(vol.r)==size(vol.o))
type = 'multisphere';
elseif isfield(vol, 'r')
type = 'concentric';
elseif isfield(vol, 'bnd')
type = 'bem';
end
if nargin>1
type = strcmp(type, desired);
end
|
github
|
lcnbeapp/beapp-master
|
strmultiline.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/strmultiline.m
| 3,151 |
utf_8
|
c1a6c98b7691f0623c7938d5cb68ae93
|
% strmultiline() - format a long string as a multi-line string.
%
% Usage:
% >> strout = strmultiline( strin, maxlen, delimiter);
%
% Inputs:
% strin - one-line or several-line string
% maxlen - maximum line length
% delimiter - enter 10 here to separate lines with character 10. Default is
% empty: lines are on different rows of the returned array.
% Outputs:
% strout - string with multiple line
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2005
%
% See also: eegfilt(), eegfiltfft(), eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function strout = strmultiline( strinori, maxlen, delimiter);
if nargin < 1
help strmultiline;
return;
end;
if nargin < 3
delimiter = [];
end;
% first format input string
% -------------------------
if ~isempty(find(strinori == 10))
tmpinds = [1 find(strinori == 10)+1 length(strinori)];
strinori = [ ' ' strinori ' ' ];
for ind = 2:length(tmpinds)
allstrs{ind} = strinori(tmpinds(ind-1)+1:tmpinds(ind)-1);
if isempty(allstrs{ind}), allstrs{ind} = ' '; end;
end;
strinori = strvcat(allstrs{:});
end;
if size(strinori,2) < maxlen, strout = strinori; return; end;
strout = [];
for index = 1:size(strinori,1) % scan lines
strin = deblank(strinori(index, :));
lines = {};
count = 1;
curline = '';
while ~isempty( strin )
[tok strin] = strtok(strin);
if length(curline) + length(tok) +1 > maxlen
lines{count} = curline;
curline = '';
count = count + 1;
end;
if isempty(curline) curline = tok;
else curline = [ curline ' ' tok ];
end;
end;
if ~isempty(curline), lines{count} = curline; end;
% type of delimiter
% -----------------
if isempty(delimiter)
if ~isempty(lines)
strouttmp = strvcat(lines{:});
else strouttmp = '';
end;
if isempty(strouttmp)
strouttmp = ones(1,maxlen)*' ';
elseif size(strouttmp, 2) < maxlen
strouttmp(:,end+1:maxlen) = ' ';
end;
strout = strvcat(strout, strouttmp);
else
strouttmp = lines{1};
for index = 2:length(lines)
strouttmp = [ strouttmp 10 lines{index} ];
end;
if index == 1, strout = strouttmp;
else strout = [ strout 10 strouttmp ];
end;
end;
end;
|
github
|
lcnbeapp/beapp-master
|
floatread.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/floatread.m
| 5,572 |
utf_8
|
942a49968bcce849dfc9d359ac7d2651
|
% floatread() - Read matrix from float file ssuming four byte floating point number
% Can use fseek() to read an arbitary (continguous) submatrix.
%
% Usage: >> a = floatread(filename,size,'format',offset)
%
% Inputs:
% filename - name of the file
% size - determine the number of float elements to be read and
% the dimensions of the resulting matrix. If the last element
% of 'size' is Inf, the size of the last dimension is determined
% by the file length. If size is 'square,' floatread() attempts
% to read a square 2-D matrix.
%
% Optional inputs:
% 'format' - the option FORMAT argument specifies the storage format as
% defined by fopen(). Default format ([]) is 'native'.
% offset - either the number of first floats to skip from the beginning of the
% float file, OR a cell array containing the dimensions of the original
% data matrix and a starting position vector in that data matrix.
%
% Example: % Read a [3 10] submatrix of a four-dimensional float matrix
% >> a = floatread('mydata.fdt',[3 10],'native',{[[3 10 4 5],[1,1,3,4]});
% % Note: The 'size' and 'offset' arguments must be compatible both
% % with each other and with the size and ordering of the float file.
%
% Author: Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998
%
% See also: floatwrite(), fopen()
% Copyright (C) Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 04-26-99 modified by Sigurd Enghoff to handle variable-sized and
% multi-dimensional data.
% 07-08-99 modified by Sigurd Enghoff, FORMAT argument added.
% 02-08-00 help updated for toolbox inclusion -sm
% 02-14-00 added segment arg -sm
% 08-14-00 added size 'square' option -sm
% 01-25-02 reformated help & license, added links -ad
function A = floatread(fname,Asize,fform,offset)
if nargin<2
help floatread
return
end
if ~exist('fform') | isempty(fform)|fform==0
fform = 'native';
end
if ~exist('offset')
offset = 0;
end
fid = fopen(fname,'rb',fform);
if fid>0
if exist('offset')
if iscell(offset)
if length(offset) ~= 2
error('offset must be a positive integer or a 2-item cell array');
end
datasize = offset{1};
startpos = offset{2};
if length(datasize) ~= length(startpos)
error('offset must be a positive integer or a 2-item cell array');
end
for k=1:length(datasize)
if startpos(k) < 1 | startpos(k) > datasize(k)
error('offset must be a positive integer or a 2-item cell array');
end
end
if length(Asize)> length(datasize)
error('offset must be a positive integer or a 2-item cell array');
end
for k=1:length(Asize)-1
if startpos(k) ~= 1
error('offset must be a positive integer or a 2-item cell array');
end
end
sizedim = length(Asize);
if Asize(sizedim) + startpos(sizedim) - 1 > datasize(sizedim)
error('offset must be a positive integer or a 2-item cell array');
end
for k=1:length(Asize)-1
if Asize(k) ~= datasize(k)
error('offset must be a positive integer or a 2-item cell array');
end
end
offset = 0;
jumpfac = 1;
for k=1:length(startpos)
offset = offset + jumpfac * (startpos(k)-1);
jumpfac = jumpfac * datasize(k);
end
elseif length(offset) > 1
error('offset must be a positive integer or a 2-item cell array');
end
% perform the fseek() operation
% -----------------------------
stts = fseek(fid,4*offset,'bof');
if stts ~= 0
error('floatread(): fseek() error.');
return
end
end
% determine what 'square' means
% -----------------------------
if ischar('Asize')
if iscell(offset)
if length(datasize) ~= 2 | datasize(1) ~= datasize(2)
error('size ''square'' must refer to a square 2-D matrix');
end
Asize = [datsize(1) datasize(2)];
elseif strcmp(Asize,'square')
fseek(fid,0,'eof'); % go to end of file
bytes = ftell(fid); % get byte position
fseek(fid,0,'bof'); % rewind
bytes = bytes/4; % nfloats
froot = sqrt(bytes);
if round(froot)*round(froot) ~= bytes
error('floatread(): filelength is not square.')
else
Asize = [round(froot) round(froot)];
end
end
end
A = fread(fid,prod(Asize),'float');
else
error('floatread() fopen() error.');
return
end
% fprintf(' %d floats read\n',prod(size(A)));
% interpret last element of Asize if 'Inf'
% ----------------------------------------
if Asize(end) == Inf
Asize = Asize(1:end-1);
A = reshape(A,[Asize length(A)/prod(Asize)]);
else
A = reshape(A,Asize);
end
fclose(fid);
|
github
|
lcnbeapp/beapp-master
|
writeeeg.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/writeeeg.m
| 9,957 |
utf_8
|
b80ba013a795acbaa4122e842203239c
|
% writeeeg - Generating CNT/EDF/BDF/GDF-files using BIOSIG toolbox. Note
% that the CNT file format is not fully functional. See also the
% writecnt.m Matlab function (there is no fully working
% Neuroscan writing function to our knowledge).
%
% writeeeg( filename, data, srate, 'key', 'val')
%
% Inputs:
% filename - [string] filename
% data - [float] continuous or epoched data (channels x times x
% epochs)
% srate - [float] sampling rate in Hz
%
% Optional keys:
% 'TYPE' - ['GDF'|'EDF'|'BDF'|'CFWB'|'CNT'] file format for writing
% default is 'EDF'.
% 'EVENT' - event structure (BIOSIG or EEGLAB format)
% 'Label' - cell array of channel labels. Warning, this input is
% case sensitive.
% 'SPR' - [integer] sample per block, default is 1000
%
% Other optional keys:
% 'Patient.id' - [string] person identification, max 80 char
% 'Patient.Sex' - [0|1|2] 0: undefined (default), 1: male, 2: female
% 'Patient.Birthday' - Default [1951 05 13 0 0 0];
% 'Patient.Name' - [string] default 'anonymous' for privacy protection
% 'Patient.Handedness' - [0|1|2|3] 0: unknown (default), 1:left, 2:right,
% 3: equal
% 'Patient.Weight' - [integer] default 0, undefined
% 'Patient.Height' - [integer] default 0, undefined
% 'Patient.Impairment.Heart' - [integer] 0: unknown 1: NO 2: YES 3: pacemaker
% 'Patient.Impairment.Visual' - [integer] 0: unknown 1: NO 2: YES
% 3: corrected (with visual aid)
% 'Patient.Smoking' - [integer] 0: unknown 1: NO 2: YES
% 'Patient.AlcoholAbuse' - [integer] 0: unknown 1: NO 2: YES
% 'Patient.DrugAbuse' - [integer] 0: unknown 1: NO 2: YES
%
% 'Manufacturer.Name - [string] default is 'BioSig/EEGLAB'
% 'Manufacturer.Model - [string] default is 'writeeeg.m'
% 'Manufacturer.Version - [string] default is current version in CVS repository
% 'Manufacturer.SerialNumber - [string] default is '00000000'
%
% 'T0' - recording time [YYYY MM DD hh mm ss.ccc]
% 'RID' - [string] StudyID/Investigation, default is empty
% 'REC.Hospital - [string] default is empty
% 'REC.Techician - [string] default is empty
% 'REC.Equipment - [string] default is empty
% 'REC.IPaddr - [integer array] IP address of recording system. Default is
% [127,0,0,1]
%
% Author: Arnaud Delorme, SCCN, UCSD/CERCO, 2009
% Based on BIOSIG, sopen and swrite
% Copyright (C) 22 March 2002 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function HDR = writeeeg(filename, x, srate, varargin)
% decode structures
HDR = [];
for i=1:2:length( varargin )
str = varargin{i};
val = varargin{i+1};
ind = strfind(str, '.');
if length(ind) == 2
HDR = setfield(HDR, varargin{i}(1:ind(1)-1), {1}, varargin{i}(ind(1)+1:ind(2)-1), ...
{1}, varargin{i}(ind(2)+1:end), val);
elseif length(ind) == 1
HDR = setfield(HDR, varargin{i}(1:ind-1), {1}, varargin{i}(ind+1:end), val);
else
HDR = setfield(HDR, varargin{i}, varargin{i+1});
end;
end;
HDR.FileName = filename;
HDR.FLAG.UCAL = 0;
% select file format
if ~isfield(HDR, 'EVENT'), HDR.EVENT = []; end;
if ~isfield(HDR, 'TYPE'), HDR.TYPE ='GDF'; end;
if ~isfield(HDR, 'Patient') HDR.Patient = []; end;
if ~isfield(HDR.Patient, 'ID') HDR.Patient.ID = 'P0000'; end;
if ~isfield(HDR.Patient, 'Sex') HDR.Patient.Sex = 0; end;
if ~isfield(HDR.Patient, 'Name') HDR.Patient.Name = 'Anonymous'; end;
if ~isfield(HDR.Patient, 'Handedness') HDR.Patient.Handedness = 0; end;% unknown, 1:left, 2:right, 3: equal
% description of recording device
if ~isfield(HDR,'Manufacturer') HDR.Manufacturer = []; end;
if ~isfield(HDR.Manufacturer, 'Name'), HDR.Manufacturer.Name = 'BioSig/EEGLAB'; end;
if ~isfield(HDR.Manufacturer, 'Model'), HDR.Manufacturer.Model = 'writeeeg.m'; end;
if ~isfield(HDR.Manufacturer, 'Version'), HDR.Manufacturer.Version = '$Revision'; end;
if ~isfield(HDR.Manufacturer, 'SerialNumber'), HDR.Manufacturer.SerialNumber = '00000000'; end;
% recording identification, max 80 char.
if ~isfield(HDR,'RID') HDR.RID = ''; end; %StudyID/Investigation [consecutive number];
if ~isfield(HDR,'REC') HDR.REC = []; end;
if ~isfield(HDR.REC, 'Hospital') HDR.REC.Hospital = ''; end;
if ~isfield(HDR.REC, 'Techician') HDR.REC.Techician = ''; end;
if ~isfield(HDR.REC, 'Equipment') HDR.REC.Equipment = ''; end;
if ~isfield(HDR.REC, 'IPaddr') HDR.REC.IPaddr = [127,0,0,1]; end; % IP address of recording system
if ~isfield(HDR.Patient, 'Weight') HDR.Patient.Weight = 0; end; % undefined
if ~isfield(HDR.Patient, 'Height') HDR.Patient.Height = 0; end; % undefined
if ~isfield(HDR.Patient, 'Birthday') HDR.Patient.Birthday = [1951 05 13 0 0 0]; end; % undefined
if ~isfield(HDR.Patient, 'Impairment') HDR.Patient.Impairment = []; end;
if ~isfield(HDR.Patient.Impairment, 'Heart') HDR.Patient.Impairment.Heart = 0; end; % 0: unknown 1: NO 2: YES 3: pacemaker
if ~isfield(HDR.Patient.Impairment, 'Visual') HDR.Patient.Impairment.Visual = 0; end; % 0: unknown 1: NO 2: YES 3: corrected (with visual aid)
if ~isfield(HDR.Patient,'Smoking') HDR.Patient.Smoking = 0; end; % 0: unknown 1: NO 2: YES
if ~isfield(HDR.Patient,'AlcoholAbuse') HDR.Patient.AlcoholAbuse = 0; end; % 0: unknown 1: NO 2: YES
if ~isfield(HDR.Patient,'DrugAbuse') HDR.Patient.DrugAbuse = 0; end; % 0: unknown 1: NO 2: YES
% recording time [YYYY MM DD hh mm ss.ccc]
if ~isfield(HDR,'T0') HDR.T0 = clock; end;
if ~isfield(HDR,'SPR') HDR.SPR = size(x,2); end;
if isfield(HDR,'label') HDR.Label = HDR.label; HDR = rmfield(HDR, 'label'); end;
if HDR.SPR > 1000, HDR.SPR = round(srate); end;
% channel identification, max 80 char. per channel
if ~isfield(HDR,'Label')
for i = 1:size(x,1)
chans{i} = sprintf('Chan %d', i);
end;
HDR.Label = chans;
end;
if iscell(HDR.Label), HDR.Label = char(HDR.Label{:}); end;
if ~isempty(HDR.EVENT)
if ~isfield(HDR.EVENT, 'TYP')
EVENT = [];
EVENT.CHN = zeros(length(HDR.EVENT),1);
EVENT.TYP = zeros(length(HDR.EVENT),1);
EVENT.POS = zeros(length(HDR.EVENT),1);
EVENT.DUR = ones( length(HDR.EVENT),1);
EVENT.VAL = zeros(length(HDR.EVENT),1)*NaN;
if isfield(HDR.EVENT, 'type')
for index = 1:length(HDR.EVENT)
HDR.EVENT(index).type = num2str(HDR.EVENT(index).type);
end;
alltypes = unique_bc( { HDR.EVENT.type } );
end;
for i = 1:length(HDR.EVENT)
if isfield(HDR.EVENT, 'type')
ind = str2num(HDR.EVENT(i).type);
if isempty(ind)
ind = strmatch(HDR.EVENT(i).type, alltypes, 'exact');
end;
EVENT.TYP(i) = ind;
end;
if isfield(HDR.EVENT, 'latency')
EVENT.POS(i) = HDR.EVENT(i).latency;
end;
if isfield(HDR.EVENT, 'duration')
EVENT.DUR(i) = HDR.EVENT(i).duration;
end;
end;
HDR.EVENT = EVENT;
HDR.EVENT.SampleRate = srate;
end;
end;
% reformat data
HDR.NRec = size(x,3);
x = double(x);
x = reshape(x, [size(x,1) size(x,2)*size(x,3) ]);
% recreate event channel
if isempty(HDR.EVENT)
HDR.EVENT.POS = [];
HDR.EVENT.TYP = [];
HDR.EVENT.POS = [];
HDR.EVENT.DUR = [];
HDR.EVENT.VAL = [];
HDR.EVENT.CHN = [];
elseif ~strcmpi(HDR.TYPE, 'GDF') % GDF can save events
disp('Recreating event channel');
x(end+1,:) = 0;
x(end,round(HDR.EVENT.POS')) = HDR.EVENT.TYP';
HDR.Label = char(HDR.Label, 'Status');
HDR.EVENT.POS = [];
end;
% number of channels
HDR.NS = size(x,1);
if ~isfield(HDR,'Transducer')
HDR.Transducer = cell(1,HDR.NS);
HDR.Transducer(:) = { '' };
end;
if ~isfield(HDR,'PhysDim')
HDR.PhysDim = cell(1,HDR.NS);
HDR.PhysDim(:) = { 'uV' };
end;
% Duration of one block in seconds
HDR.SampleRate = srate;
HDR.Dur = HDR.SPR/HDR.SampleRate;
% define datatypes and scaling factors
HDR.PhysMax = max(x, [], 2);
HDR.PhysMin = min(x, [], 2);
if strcmp(HDR.TYPE, 'GDF')
HDR.GDFTYP = 16*ones(1,HDR.NS); % float32
HDR.DigMax = ones(HDR.NS,1)*100; % FIXME: What are the correct values for float32?
HDR.DigMin = zeros(HDR.NS,1);
else
HDR.GDFTYP = 3*ones(1,HDR.NS); % int16
HDR.DigMin = repmat(-2^15, size(HDR.PhysMin));
HDR.DigMax = repmat(2^15-1, size(HDR.PhysMax));
end
HDR.Filter.Lowpass = zeros(1,HDR.NS)*NaN;
HDR.Filter.Highpass = zeros(1,HDR.NS)*NaN;
HDR.Filter.Notch = zeros(1,HDR.NS)*NaN;
HDR.VERSION = 2.11;
HDR = sopen(HDR,'w');
HDR = swrite(HDR, x');
HDR = sclose(HDR);
|
github
|
lcnbeapp/beapp-master
|
convertlocs.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/convertlocs.m
| 9,621 |
utf_8
|
9455542daae2061f96f576b6dc3d46da
|
% convertlocs() - Convert electrode locations between coordinate systems
% using the EEG.chanlocs structure.
%
% Usage: >> newchans = convertlocs( EEG, 'command');
%
% Input:
% chanlocs - An EEGLAB EEG dataset OR a EEG.chanlocs channel locations structure
% 'command' - ['cart2topo'|'sph2topo'|'sphbesa2topo'| 'sph2cart'|'topo2cart'|'sphbesa2cart'|
% 'cart2sph'|'sphbesa2sph'|'topo2sph'| 'cart2sphbesa'|'sph2sphbesa'|'topo2sphbesa'|
% 'cart2all'|'sph2all'|'sphbesa2all'|'topo2all']
% These command modes convert between four coordinate frames: 3-D Cartesian
% (cart), Matlab spherical (sph), Besa spherical (sphbesa), and 2-D polar (topo)
% 'auto' -- Here, the function finds the most complex coordinate frame
% and constrains all the others to this one. It searches first for Cartesian
% coordinates, then for spherical and finally for polar. Default is 'auto'.
%
% Optional input
% 'verbose' - ['on'|'off'] default is 'off'.
%
% Outputs:
% newchans - new EEGLAB channel locations structure
%
% Ex: CHANSTRUCT = convertlocs( CHANSTRUCT, 'cart2topo');
% % Convert Cartesian coordinates to 2-D polar (topographic).
%
% Author: Arnaud Delorme, CNL / Salk Institute, 22 Dec 2002
%
% See also: readlocs()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 22 Dec 2002, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function chans = convertlocs(chans, command, varargin);
if nargin < 1
help convertlocs;
return;
end;
if nargin < 2
command = 'auto';
end;
if nargin == 4 && strcmpi(varargin{2}, 'on')
verbose = 1;
else
verbose = 0; % off
end;
% test if value exists for default
% --------------------------------
if strcmp(command, 'auto')
if isfield(chans, 'X') && ~isempty(chans(1).X)
command = 'cart2all';
if verbose
disp('Make all coordinate frames uniform using Cartesian coords');
end;
else
if isfield(chans, 'sph_theta') && ~isempty(chans(1).sph_theta)
command = 'sph2all';
if verbose
disp('Make all coordinate frames uniform using spherical coords');
end;
else
if isfield(chans, 'sph_theta_besa') && ~isempty(chans(1).sph_theta_besa)
command = 'sphbesa2all';
if verbose
disp('Make all coordinate frames uniform using BESA spherical coords');
end;
else
command = 'topo2all';
if verbose
disp('Make all coordinate frames uniform using polar coords');
end;
end;
end;
end;
end;
% convert
% -------
switch command
case 'topo2sph',
theta = {chans.theta};
radius = {chans.radius};
indices = find(~cellfun('isempty', theta));
[sph_phi sph_theta] = topo2sph( [ [ theta{indices} ]' [ radius{indices}]' ] );
if verbose
disp('Warning: electrodes forced to lie on a sphere for polar to 3-D conversion');
end;
for index = 1:length(indices)
chans(indices(index)).sph_theta = sph_theta(index);
chans(indices(index)).sph_phi = sph_phi (index);
end;
if isfield(chans, 'sph_radius'),
meanrad = mean([ chans(indices).sph_radius ]);
if isempty(meanrad), meanrad = 1; end;
else
meanrad = 1;
end;
sph_radius(1:length(indices)) = {meanrad};
case 'topo2sphbesa',
chans = convertlocs(chans, 'topo2sph', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2sphbesa', varargin{:}); % search for spherical coords
case 'topo2cart'
chans = convertlocs(chans, 'topo2sph', varargin{:}); % search for spherical coords
if verbose
disp('Warning: spherical coordinates automatically updated');
end;
chans = convertlocs(chans, 'sph2cart', varargin{:}); % search for spherical coords
case 'topo2all',
chans = convertlocs(chans, 'topo2sph', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2sphbesa', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2cart', varargin{:}); % search for spherical coords
case 'sph2cart',
sph_theta = {chans.sph_theta};
sph_phi = {chans.sph_phi};
indices = find(~cellfun('isempty', sph_theta));
if ~isfield(chans, 'sph_radius'), sph_radius(1:length(indices)) = {1};
else sph_radius = {chans.sph_radius};
end;
inde = find(cellfun('isempty', sph_radius));
if ~isempty(inde)
meanrad = mean( [ sph_radius{:} ]);
sph_radius(inde) = { meanrad };
end;
[x y z] = sph2cart([ sph_theta{indices} ]'/180*pi, [ sph_phi{indices} ]'/180*pi, [ sph_radius{indices} ]');
for index = 1:length(indices)
chans(indices(index)).X = x(index);
chans(indices(index)).Y = y(index);
chans(indices(index)).Z = z(index);
end;
case 'sph2topo',
if verbose
% disp('Warning: all radii constrained to one for spherical to topo transformation');
end;
sph_theta = {chans.sph_theta};
sph_phi = {chans.sph_phi};
indices = find(~cellfun('isempty', sph_theta));
[chan_num,angle,radius] = sph2topo([ ones(length(indices),1) [ sph_phi{indices} ]' [ sph_theta{indices} ]' ], 1, 2); % using method 2
for index = 1:length(indices)
chans(indices(index)).theta = angle(index);
chans(indices(index)).radius = radius(index);
if ~isfield(chans, 'sph_radius') || isempty(chans(indices(index)).sph_radius)
chans(indices(index)).sph_radius = 1;
end;
end;
case 'sph2sphbesa',
% using polar coordinates
sph_theta = {chans.sph_theta};
sph_phi = {chans.sph_phi};
indices = find(~cellfun('isempty', sph_theta));
[chan_num,angle,radius] = sph2topo([ones(length(indices),1) [ sph_phi{indices} ]' [ sph_theta{indices} ]' ], 1, 2);
[sph_theta_besa sph_phi_besa] = topo2sph([angle radius], 1, 1);
for index = 1:length(indices)
chans(indices(index)).sph_theta_besa = sph_theta_besa(index);
chans(indices(index)).sph_phi_besa = sph_phi_besa(index);
end;
case 'sph2all',
chans = convertlocs(chans, 'sph2topo', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2sphbesa', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2cart', varargin{:}); % search for spherical coords
case 'sphbesa2sph',
% using polar coordinates
sph_theta_besa = {chans.sph_theta_besa};
sph_phi_besa = {chans.sph_phi_besa};
indices = find(~cellfun('isempty', sph_theta_besa));
[chan_num,angle,radius] = sph2topo([ones(length(indices),1) [ sph_theta_besa{indices} ]' [ sph_phi_besa{indices} ]' ], 1, 1);
%for index = 1:length(chans)
% chans(indices(index)).theta = angle(index);
% chans(indices(index)).radius = radius(index);
% chans(indices(index)).labels = int2str(index);
%end;
%figure; topoplot([],chans, 'style', 'blank', 'electrodes', 'labelpoint');
[sph_phi sph_theta] = topo2sph([angle radius], 2);
for index = 1:length(indices)
chans(indices(index)).sph_theta = sph_theta(index);
chans(indices(index)).sph_phi = sph_phi (index);
end;
case 'sphbesa2topo',
chans = convertlocs(chans, 'sphbesa2sph', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2topo', varargin{:}); % search for spherical coords
case 'sphbesa2cart',
chans = convertlocs(chans, 'sphbesa2sph', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2cart', varargin{:}); % search for spherical coords
case 'sphbesa2all',
chans = convertlocs(chans, 'sphbesa2sph', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2all', varargin{:}); % search for spherical coords
case 'cart2topo',
chans = convertlocs(chans, 'cart2sph', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2topo', varargin{:}); % search for spherical coords
case 'cart2sphbesa',
chans = convertlocs(chans, 'cart2sph', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2sphbesa', varargin{:}); % search for spherical coords
case 'cart2sph',
if verbose
disp('WARNING: If XYZ center has not been optimized, optimize it using Edit > Channel Locations');
end;
X = {chans.X};
Y = {chans.Y};
Z = {chans.Z};
indices = find(~cellfun('isempty', X));
[th phi radius] = cart2sph( [ X{indices} ], [ Y{indices} ], [ Z{indices} ]);
for index = 1:length(indices)
chans(indices(index)).sph_theta = th(index)/pi*180;
chans(indices(index)).sph_phi = phi(index)/pi*180;
chans(indices(index)).sph_radius = radius(index);
end;
case 'cart2all',
chans = convertlocs(chans, 'cart2sph', varargin{:}); % search for spherical coords
chans = convertlocs(chans, 'sph2all', varargin{:}); % search for spherical coords
end;
|
github
|
lcnbeapp/beapp-master
|
isscript.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/isscript.m
| 385 |
utf_8
|
5e35a8cefee4828cc65eeb2abb2502a7
|
% function checking if a specific file is a script%
function bool = isscript(fileName);
fid = fopen(fileName, 'r');
cont = true;
while cont && ~feof(fid)
l = strtok(fgetl(fid));
if ~isempty(l) && l(1) ~= '%'
if strcmpi(l, 'function')
bool = false; return;
else
bool = true; return;
end;
end;
end;
bool = true; return;
|
github
|
lcnbeapp/beapp-master
|
floatwrite.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/floatwrite.m
| 3,169 |
utf_8
|
8472e61c3208f7a445ec052e9cc52b4b
|
% floatwrite() - Write data matrix to float file.
%
% Usage: >> floatwrite(data,filename, 'format')
%
% Inputs:
% data - write matrix data to specified file as four-byte floating point numbers.
% filename - name of the file
% 'format' - The option FORMAT argument specifies the storage format as
% defined by fopen. Default format is 'native'.
% 'transp|normal' - save the data transposed (.dat files) or not.
%
% Author: Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998
%
% See also: floatread(), fopen()
% Copyright (C) Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 07-08-99 FORMAT argument added -se
% 02-08-00 new version included in toolbox -sm
% 01-25-02 reformated help & license, added links -ad
function A = floatwrite(A, fname, fform, transp)
if ~exist('fform')
fform = 'native';
end
if nargin < 4
transp = 'normal';
end;
if strcmpi(transp,'normal')
if strcmpi(class(A), 'mmo')
A = changefile(A, fname);
return;
elseif strcmpi(class(A), 'memmapdata')
% check file to overwrite
% -----------------------
[fpath1 fname1 ext1] = fileparts(fname);
[fpath2 fname2 ext2] = fileparts(A.data.Filename);
if isempty(fpath1), fpath1 = pwd; end;
fname1 = fullfile(fpath1, [fname1 ext1]);
fname2 = fullfile(fpath2, [fname2 ext2]);
if ~isempty(findstr(fname1, fname2))
disp('Warning: raw data already saved in memory mapped file (no need to resave it)');
return;
end;
fid = fopen(fname,'wb',fform);
if fid == -1, error('Cannot write output file, check permission and space'); end;
if size(A,3) > 1
for ind = 1:size(A,3)
tmpdata = A(:,:,ind);
fwrite(fid,tmpdata,'float');
end;
else
blocks = [ 1:round(size(A,2)/10):size(A,2)];
if blocks(end) ~= size(A,2), blocks = [blocks size(A,2)]; end;
for ind = 1:length(blocks)-1
tmpdata = A(:, blocks(ind):blocks(ind+1));
fwrite(fid,tmpdata,'float');
end;
end;
else
fid = fopen(fname,'wb',fform);
if fid == -1, error('Cannot write output file, check permission and space'); end;
fwrite(fid,A,'float');
end;
else
% save transposed
for ind = 1:size(A,1)
fwrite(fid,A(ind,:),'float');
end;
end;
fclose(fid);
|
github
|
lcnbeapp/beapp-master
|
kurt.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/kurt.m
| 1,697 |
utf_8
|
649871ee149fc000974e3081ac13ff98
|
% kurt() - return kurtosis of input data distribution
%
% Usage:
% >> k=kurt(data)
%
% Algorithm:
% Calculates kurtosis or normalized 4th moment of an input data vector
% Given a matrix, returns a row vector giving the kurtosis' of the columns
% (Ref: "Numerical Recipes," p. 612)
%
% Author: Martin Mckeown, CNL / Salk Institute, La Jolla, 10/2/96
% Copyright (C) Martin Mckeown, CNL / Salk Institute, La Jolla, 7/1996
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 2/28/97 - made to return separate kurtosis estimates of columns -Scott Makeig
% 01-25-02 reformated help & license, added links -ad
function [k] = kurt(data)
[r,c]=size(data);
if r==1,
kdata = data'; % if a row vector, make into a column vector
r = c;
else
kdata = data;
end
%fprintf('size of kdata = [%d,%d]\n',size(kdata,1),size(kdata,2));
mn = mean(kdata); % find the column means
diff = kdata-ones(r,1)*mn; % remove the column means
dsq = diff.*diff; % square the data
k = (sum(dsq.*dsq)./std(kdata).^4)./r - 3;
|
github
|
lcnbeapp/beapp-master
|
jointprob.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/jointprob.m
| 4,100 |
utf_8
|
6f1300fd6123684425efaaa56c1e95c1
|
% jointprob() - rejection of odd columns of a data array using
% joint probability of the values in that column (and
% using the probability distribution of all columns).
%
% Usage:
% >> [jp rej] = jointprob( signal );
% >> [jp rej] = jointprob( signal, threshold, jp, normalize, discret);
%
%
% Inputs:
% signal - one dimensional column vector of data values, two
% dimensional column vector of values of size
% sweeps x frames or three dimensional array of size
% component x sweeps x frames. If three dimensional,
% all components are treated independently.
% threshold - Absolute threshold. If normalization is used then the
% threshold is expressed in standard deviation of the
% mean. 0 means no threshold.
% jp - pre-computed joint probability (only perform thresholding).
% Default is the empty array [].
% normalize - 0 = do not not normalize entropy. 1 = normalize entropy.
% 2 is 20% trimming (10% low and 10% high) proba. before
% normalizing. Default is 0.
% discret - discretization variable for calculation of the
% discrete probability density. Default is 1000 points.
%
% Outputs:
% jp - normalized joint probability of the single trials
% (size component x sweeps)
% rej - rejected matrix (0 and 1, size comp x sweeps)
%
% Remark:
% The exact values of joint-probability depend on the size of a time
% step and thus cannot be considered as absolute.
%
% See also: realproba()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [jp, rej] = jointprob( signal, threshold, oldjp, normalize, discret );
if nargin < 1
help jointprob;
return;
end;
if nargin < 2
threshold = 0;
end;
if nargin < 3
oldjp = [];
end;
if nargin < 4
normalize = 0;
end;
if nargin < 5
discret = 1000;
end;
if size(signal,2) == 1 % transpose if necessary
signal = signal';
end;
[nbchan pnts sweeps] = size(signal);
jp = zeros(nbchan,sweeps);
if exist('oldjp') & ~isempty( oldjp ) % speed up the computation
jp = oldjp;
else
for rc = 1:nbchan
% COMPUTE THE DENSITY FUNCTION
% ----------------------------
[ dataProba sortbox ] = realproba( signal(rc, :), discret );
% compute all entropy
% -------------------
for index=1:sweeps
datatmp = dataProba((index-1)*pnts+1:index*pnts);
jp(rc, index) = - sum( log( datatmp ) );
% - sum( datatmp .* log( datatmp ) ); would be the entropy
end;
end;
% normalize the last dimension
% ----------------------------
if normalize
tmpjp = jp;
if normalize == 2,
tmpjp = sort(jp);
tmpjp = tmpjp(round(length(tmpjp)*0.1):end-round(length(tmpjp)*0.1));
end;
try,
switch ndims( signal )
case 2, jp = (jp-mean(tmpjp)) / std(tmpjp);
case 3, jp = (jp-mean(tmpjp,2)*ones(1,size(jp,2)))./ ...
(std(tmpjp,0,2)*ones(1,size(jp,2)));
end;
catch, error('Error while normalizing'); end;
end;
end
% reject
% ------
if threshold ~= 0
if length(threshold) > 1
rej = (threshold(1) > jp) | (jp > threshold(2));
else
rej = abs(jp) > threshold;
end;
else
rej = zeros(size(jp));
end;
return;
|
github
|
lcnbeapp/beapp-master
|
readneurodat.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/readneurodat.m
| 3,182 |
utf_8
|
2658232f1fb962a2bad82932ad309164
|
% readneurodat() - read neuroscan location file (.dat)
%
% Usage:
% >> [ CHANLOCS labels theta theta ] = readneurodat( filename );
%
% Inputs:
% filename - file name or matlab cell array { names x_coord y_coord }
%
% Outputs:
% CHANLOCS - [structure] EEGLAB channel location data structure. See
% help readlocs()
% labels - [cell arrya] channel labels
% theta - [float array]array containing 3-D theta angle electrode
% position (in degree)
% phi - [float array]array containing 3-D phi angle electrode
% position (in degree)
%
% Author: Arnaud Delorme, CNL / Salk Institute, 28 Nov 2003
%
% See also: readlocs(), readneurolocs()
% Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [chanlocs, labels, theta, phi] = readneurodat(filename);
if nargin < 1
help readneurodat;
return;
end;
% enter file name here
% --------------------
%tmp = loadtxt('/home/ftp/pub/locfiles/neuroscan/cap128.dat');
%tmp = loadtxt('/home/arno/temp/quik128.DAT');
tmp = loadtxt(filename);
% resort electrodes
% -----------------
[tmp2 tmpind] = sort(celltomat(tmp(:,1))');
tmp = tmp(tmpind,:);
% convert to polar coordinates
% ----------------------------
%figure; plot(celltomat(tmp(:,2)), celltomat(tmp(:,3)), '.');
[phi,theta] = cart2pol(celltomat(tmp(:,end-1)), celltomat(tmp(:,end)));
theta = theta/513.1617*44;
phi = phi/pi*180;
% convert to other types of coordinates
% -------------------------------------
labels = tmp(:,end-2)';
chanlocs = struct('labels', labels, 'sph_theta_besa', mattocell(theta)', 'sph_phi_besa', mattocell(phi)');
chanlocs = convertlocs( chanlocs, 'sphbesa2all');
for index = 1:length(chanlocs)
chanlocs(index).labels = num2str(chanlocs(index).labels);
end;
theta = theta/pi*180;
fprintf('Note: .dat file contain polar 2-D coordinates. EEGLAB will use these coordinates\n');
fprintf(' to recreated 3-D coordinates.\n');
fprintf('\n');
fprintf('Warning: if the channels are clustered in the middle or oddly spaced removed\n');
fprintf(' the peripheral channels and then used the optimize head function\n');
fprintf(' in the Channel Locations GUI. It seems that sometimes the peripherals\n');
fprintf(' are throwing off the spacing.\n');
|
github
|
lcnbeapp/beapp-master
|
shuffle.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/shuffle.m
| 1,610 |
utf_8
|
aef9a1bc7914b99d6e312694b0522085
|
% shuffle() - shuffle a given dimension in an array
%
% Usage: >> Y = shuffle(X)
% >> [Y = shuffle(X, DIM)
%
% Inputs:
% X - input array
% DIM - dimension index (default is firt non-singleton dimention)
%
% Outputs:
% Y - shuffled array
% I - forward indices (Y = X(I) if 1D)
% J - reverse indices (X(J) = Y if 1D)
%
% Author: Arnaud Delorme, SCCN/INC/UCSD USA, Dec 2000
% Copyright (C) Arnaud Delorme, SCCN/INC/UCSD USA, Dec 2000
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [x, i, j]=shuffle( y, dim)
if nargin < 1
help shuffle;
return;
end;
if nargin < 2
if size(y,1) ~= 1
dim = 1;
else
if size(y,2) ~= 1
dim = 2;
else
dim = 3;
end;
end;
end;
r =size(y, dim);
a = rand(1,r);
[tmp i] = sort(a);
switch dim
case 1
x = y(i,:,:,:,:);
case 2
x = y(:,i,:,:,:);
case 3
x = y(:,:,i,:,:);
case 4
x = y(:,:,:,i,:);
case 5
x = y(:,:,:,:,i);
end;
[tmp j] = sort(i); % unshuffle
return;
|
github
|
lcnbeapp/beapp-master
|
fastif.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/fastif.m
| 1,159 |
utf_8
|
ac76d723f5de7649f75655cbdb653c1a
|
% fastif() - fast if function.
%
% Usage:
% >> res = fastif(test, s1, s2);
%
% Input:
% test - logical test with result 0 or 1
% s1 - result if 1
% s2 - result if 0
%
% Output:
% res - s1 or s2 depending on the value of the test
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function res = fastif(s1, s2, s3);
if s1
res = s2;
else
res = s3;
end;
return;
|
github
|
lcnbeapp/beapp-master
|
chancenter.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/chancenter.m
| 3,837 |
utf_8
|
f0281f2036170701ee0f251a89f4663e
|
% chancenter() - recenter cartesian X,Y,Z channel coordinates
%
% Usage: >> [x y z newcenter] = chancenter(x,y,z,center);
%
% Optional inputs:
% x,y,z = 3D coordintates of the channels
% center = [X Y Z] known center different from [0 0 0]
% [] will optimize the center location according
% to the best sphere. Default is [0 0 0].
%
% Note: 4th input gui is obsolete. Use pop_chancenter instead.
%
% Authors: Arnaud Delorme, Luca Finelli & Scott Makeig SCCN/INC/UCSD,
% La Jolla, 11/1999-03/2002
%
% See also: spherror(), cart2topo()
% Copyright (C) 11/1999 Scott Makeig, SCCN/INC/UCSD, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 3-16-00 improved help message -sm
% 1-25-02 put spherror subfunction inside chancenter -ad
% 1-25-02 help pops-up if no arguments -ad
% 01-25-02 reformated help & license -ad
% 02-13-02 now center fitting works, need spherror outside chancenter -lf
% 02-14-02 radii are squeezed of squeeze in to fit topoplot circle -lf
% 03-31-02 center fitting is optional
% 04-01-02 automatic squeeze calculation -ad & sm
function [ x, y, z, newcenter, optim] = chancenter( x, y, z, center, gui)
optim = 0;
if nargin<4
help chancenter
return;
end;
if nargin > 4 & gui
error('Chancenter: 4th input'' gui'' is obsolete. Use pop_chancenter instead');
else
if isempty(center)
optim = 1;
center = [0 0 0];
end;
end;
options = {'MaxFunEvals',1000*length(center)};
x = x - center(1); % center the data
y = y - center(2);
z = z - center(3);
radius = (sqrt(x.^2+y.^2+z.^2)); % assume xyz values are on a sphere
if ~isempty(radius)
wobble = std(radius); % test if xyz values are on a sphere
else wobble = [];
end;
fprintf('Radius values: %g (mean) +/- %g (std)\n',mean(radius),wobble);
newcenter = center;
if wobble/mean(radius) > 0.01 & optim==1
% Find center
% ----------------------------------------------
fprintf('Optimizing center position...\n');
kk=0;
while wobble/mean(radius) > 0.01 & kk<5
try
newcenter = fminsearch('spherror',center,struct(options{:}),x,y,z);
catch
try
newcenter = fminsearch('spherror',center,options,x,y,z);
catch
newcenter = fminsearch('spherror',center,[], [], x,y,z);
end
end
nx = x - newcenter(1); % re-center the data
ny = y - newcenter(2);
nz = z - newcenter(3);
nradius = (sqrt(nx.^2+ny.^2+nz.^2)); % assume xyz values are on a sphere
newobble = std(nradius);
if newobble<wobble
center=newcenter;
fprintf('Wobble too strong (%3.2g%%)! Re-centering data on (%g,%g,%g)\n',...
100*wobble/mean(radius),newcenter(1),newcenter(2),newcenter(3))
x = nx; % re-center the data
y = ny;
z = nz;
radius=nradius;
wobble=newobble;
kk=kk+1;
else
newcenter = center;
kk=5;
end
end
fprintf('Wobble (%3.2g%%) after centering data on (%g,%g,%g)\n',...
100*wobble/mean(radius),center(1),center(2), ...
center(3))
%else
% fprintf('Wobble (%3.2g%%) after centering data on (%g,%g,%g)\n',...
% 100*wobble/mean(radius),center(1),center(2),center(3))
end
|
github
|
lcnbeapp/beapp-master
|
eegplot2trial.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/eegplot2trial.m
| 3,493 |
utf_8
|
070a4620dcbcefa6063fde095d9ae592
|
% eegplot2trial() - convert EEGPLOT rejections into trial and electrode
% rejections compatible with EEGLAB format.
%
% Usage:
% >> [trialrej elecrej] = eegplot2trial( eegplotrej, frames, ...
% sweeps, colorin, colorout );
%
% Inputs:
% eegplotrej - EEGPLOT output (TMPREJ; see eegplot for more details)
% frames - number of points per epoch
% sweeps - number of trials
% colorin - only extract rejection of specific colors (here a n x 3
% array must be given). Default: extract all rejections.
% colorout - do not extract rejection of specified colors.
%
% Outputs:
% trialrej - array of 0 and 1 depicting rejected trials (size sweeps)
% elecrej - array of 0 and 1 depicting rejected electrodes in
% all trials (size nbelectrodes x sweeps )
%
% Note: if colorin is used, colorout is ignored
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eegplot(), eeg_multieegplot(), eegplot2event(), eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [tmpsig, tmprejelec] = eegplot2trial( TMPREJINIT, pnts, sweeps, color, colorout );
if nargin < 3
help eegplot2trial;
return;
end;
% only take into account specific colors
% --------------------------------------
TMPREJINIT(:,3:5) = round(TMPREJINIT(:,3:5)*100)/100;
TMPREJ = [];
if exist('color') == 1 && ~isempty(color)
color = round(color*100)/100;
for index = 1:size(color,1)
tmpcol1 = TMPREJINIT(:,3) + 255*TMPREJINIT(:,4) + 255*255*TMPREJINIT(:,5);
tmpcol2 = color(index,1)+255*color(index,2)+255*255*color(index,3);
I = find( tmpcol1 == tmpcol2);
%if isempty(I)
% fprintf('Warning: color [%d %d %d] not found\n', ...
% color(index,1), color(index,2), color(index,3));
%end;
TMPREJ = [ TMPREJ; TMPREJINIT(I,:)];
end;
else
TMPREJ = TMPREJINIT;
% remove other specific colors
% ----------------------------
if exist('colorout') == 1
colorout = round(colorout*100)/100;
for index = 1:size(colorout,1)
tmpcol1 = TMPREJ(:,3) + 255*TMPREJ(:,4) + 255*255*TMPREJ(:,5);
tmpcol2 = colorout(index,1)+255*colorout(index,2)+255*255*colorout(index,3);
I = find( tmpcol1 == tmpcol2);
TMPREJ(I,:) = [];
end;
end;
end;
% perform the conversion
% ----------------------
tmprejelec = [];
tmpsig = zeros(1,sweeps);
if ~isempty(TMPREJ)
nbchan = size(TMPREJ,2)-5;
TMPREJ = sortrows(TMPREJ,1);
TMPREJ(find(TMPREJ(:,1) == 1),1) = 0;
tmpsig = TMPREJ(:,1)''/pnts+1;
I = find(tmpsig == round(tmpsig));
tmp = tmpsig(I);
tmpsig = zeros(1,sweeps);
tmpsig(tmp) = 1;
I = find(tmpsig);
tmprejelec = zeros( nbchan, sweeps);
tmprejelec(:,I) = TMPREJ(:,6:nbchan+5)';
end;
return;
|
github
|
lcnbeapp/beapp-master
|
reref.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/reref.m
| 9,677 |
utf_8
|
6e0667e9dd7ca782c44c657e960bafd0
|
% reref() - convert common reference EEG data to some other common reference
% or to average reference
% Usage:
% >> Dataout = reref(data); % convert all channels to average reference
% >> [Dataout Chanlocs] = reref(data, refchan, 'key', 'val');
% % convert data to new reference with options
% Inputs:
% data - 2-D or 3-D data matrix (chans,frames*epochs)
% refchan - reference channel number(s). There are three possibilities:
% 1) [] - compute average reference
% 2) [X]: re-reference to channel X
% 2) [X Y Z ...]: re-reference to the average of channel X Y Z ...
%
% Optional inputs:
% 'exclude' - [integer array] channel indices to exclude from re-referencing
% (e.g., event marker channels, etc.)
% 'keepref' - ['on'|'off'] keep reference channel in output (only usable
% when there are several references).
% 'elocs' - Current data electrode location structure (e.g., EEG.chanlocs).
% 'refloc' - Reference channel location single element structure or cell array
% {'label' theta radius} containing the name and polar coordinates
% of the current channel. Including this entry means that
% this channel will be included (reconstructed) in the
% output.
%
% Outputs:
% Dataout - Input data converted to the new reference
% Chanlocs - Updated channel locations structure
%
% Notes: 1) The average reference calculation implements two methods
% (see www.egi.com/Technotes/AverageReference.pdf)
% V'i = (Vi-Vref) - sum(Vi-Vref)/number_of_electrodes
%
% Authors: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2009-
% previous version: Arnaud Delorme & Scott Makeig, 1999-2002
% Deprecated inputs:
% These inputs are still accepted but not processed. The function returns
% accurate results irrespective of the entry of these options.
% 'refstate ' - ['common'|'averef'|[indices]] Current reference condition,
% ('averef') = average reference; ('common' or 0) = common
% reference. [indices] designate the current reference channel
% or channels if present in the data {default: 'common'}
% 'method' - ['standard'|'withref'] Do not ('standard') or do ('withref')
% include reference channel data in output {def: 'standard'}.
% Note: Option 'withref' not possible when multiple ref channel
% indices are given as argument to 'refstate' (below).
%
% ICA inputs:
% These inputs are still accepted but not the ICA conversion is now
% performed from within pop_reref()
% 'icaweights' - ICA weight matrix. Note: If this is ICA weights*sphere,
% then the 'icasphere' input below should be [] or identity.
% 'icasphere' - ICA sphere matrix (if any)
% 'icachansind' - Indices of the channels used in ICA decomposition
%
% Outputs:
% Wout - ICA weight matrix (former icaweights*icasphere)
% converted to new data reference
% Sout - ICA sphere matrix converted to an identity matrix
% ICAinds - New indices of channels used in ICA decomposition
% meandata - (1,dataframes) means removed from each data point
%
% 2) In conversion of the weight matrix to a new reference
% where WS = Wts*Sph and ica_act = WS*data, then
% data = inv(WS)*ica_act;
% If R*data are the re-referenced data,
% R*data= R*inv(WS)*ica_act;
% And Wout = inv(R*inv(WS));
% Now, Sout = eye(length(ICAinds));
% The re-referenced ICA component maps are now the
% columns of inv(Wout), and the icasphere matrix, Sout,
% is an identity matrix. Note: inv() -> pinv() when
% PCA dimension reduction is used during ICA decomposition.
% Copyright (C) 1999 Scott Makeig, SCCN/INC/UCSD, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 12/16/99 Corrected denomiator on the suggestion of Ian Nimmo-Smith, Cambridge UK
% 01-25-02 reformated help & license -ad
function [data, Elocs, morechans, W, S, icachansind, meandata] = reref(data, ref, varargin)
if nargin<1
help reref
return
end
if nargin < 2
ref = [];
end;
% check inputs
% ------------
g = finputcheck(varargin, { 'icaweight' 'real' [] [];
'icaweights' 'real' [] [];
'icasphere' 'real' [] [];
'icachansind' 'integer' [] [];
'method' 'string' { 'standard','withref' } 'standard';
'refstate' { 'string','integer' } { { 'common','averef' } [1 size(data,1)] } 'common'; % ot used but kept for backward compatib.
'exclude' 'integer' [1 size(data,1)] [];
'refloc' { 'cell','struct' } { [] [] } {};
'keepref' 'string' {'on','off' } 'off';
'elocs' {'integer','struct'} [] [] });
if isstr(g), error(g); end;
if ~isempty(g.icaweight)
g.icaweights = g.icaweight;
end;
if ~isempty(g.icaweights)
if isempty(g.icachansind),
g.icachansind = [1:size(g.icaweights,2)];
disp('Warning: reref() output has changed slightly since EEGLAB 5.02');
disp(' the 4th output argument is the indices of channels used for ICA instead');
disp(' of the mean reference value (which is now output argument 5)');
end;
end;
if isstr(ref), ref = { ref }; end;
if iscell(ref), ref = eeg_chaninds(g.elocs, ref); end;
if ~isempty(ref)
if ref > size(data,1)
error('reference channel index out of range');
end;
end;
[dim1 dim2 dim3] = size(data);
data = reshape(data, dim1, dim2*dim3);
% single reference not present in the data
% add it as blank data channel at the end
% ----------------------------------------
if ~isempty(g.refloc) == 1
if ~isempty(g.elocs)
if iscell(g.refloc)
data(end+1,:) = 0;
g.elocs(end+1).labels = g.refloc{1};
g.elocs(end ).theta = g.refloc{2};
g.elocs(end ).radius = g.refloc{3};
else
data(end+length(g.refloc),:) = 0;
for iLocs = 1:length(g.refloc)
g.elocs(end+1).labels = g.refloc(iLocs).labels;
fieldloc = fieldnames(g.elocs);
for ind = 1:length(fieldloc)
g.elocs(end) = setfield(g.elocs(end), fieldloc{ind}, getfield(g.refloc(iLocs), fieldloc{ind}));
end;
end;
end;
end;
[dim1 dim2 dim3] = size(data);
end;
% exclude some channels
% ---------------------
chansin = setdiff_bc([1:dim1], g.exclude);
nchansin = length(chansin);
% return mean data
% ----------------
if nargout > 4
meandata = sum(data(chansin,2))/nchansin;
end;
% generate rereferencing matrix
% -----------------------------
if 0 % alternate code - should work exactly the same
if isempty(ref)
ref=chansin; % average reference
end % if
chansout=chansin;
data(chansout,:)=data(chansout,:)-ones(nchansin,1)*mean(data(ref,:),1);
else
if ~isempty(ref) % not average reference
refmatrix = eye(nchansin); % begin with identity matrix
tmpref = ref;
for index = length(g.exclude):-1:1
tmpref(find(g.exclude(index) < tmpref)) = tmpref(find(g.exclude(index) < tmpref))-1;
end;
for index = 1:length(tmpref)
refmatrix(:,tmpref(index)) = refmatrix(:,tmpref(index))-1/length(tmpref);
end;
else % compute average reference
refmatrix = eye(nchansin)-ones(nchansin)*1/nchansin;
end;
chansout = chansin;
data(chansout,:) = refmatrix*data(chansin,:);
end;
% change reference in elocs structure
% -----------------------------------
if ~isempty(g.elocs)
if isempty(ref)
for ind = chansin
g.elocs(ind).ref = 'average';
end;
else
reftxt = { g.elocs(ref).labels };
if length(reftxt) == 1, reftxt = reftxt{1};
else
reftxt = cellfun(@(x)([x ' ']), reftxt, 'uniformoutput', false);
reftxt = [ reftxt{:} ];
end;
for ind = chansin
g.elocs(ind).ref = reftxt;
end;
end;
end;
% remove reference
% ----------------
morechans = [];
if strcmpi(g.keepref, 'off')
data(ref,:) = [];
if ~isempty(g.elocs)
morechans = g.elocs(ref);
g.elocs(ref) = [];
end;
end;
data = reshape(data, size(data,1), dim2, dim3);
% treat optional ica parameters
% -----------------------------
W = []; S = []; icachansind = [];
if ~isempty(g.icaweights)
disp('Warning: This function does not process ICA array anymore, use the pop_reref function instead');
end;
Elocs = g.elocs;
|
github
|
lcnbeapp/beapp-master
|
plotdata.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/plotdata.m
| 20,127 |
utf_8
|
dc7d1faf9633b845ff3de9c423067fc0
|
% plotdata() - plot concatenated multichannel data epochs in two-column format
%
% Usage: >> plotdata(data)
% >> plotdata(data,frames)
% >> plotdata(data,frames,limits,title,channames,colors,rtitle,ydir)
%
% Necessary input:
% data = data consisting of consecutive epochs of (chans,frames)
%
% Optional inputs:
% frames = time frames/points per epoch {default: 0 -> data length}
% [limits] = [xmin xmax ymin ymax] (x's in ms)
% {default|0 (or both y's 0) -> use data limits)
% 'title' = plot title {default|0 -> none}
% 'channames' = channel location file or structure (see readlocs())
% {default|0 -> channel numbers}
% 'colors' = file of color codes, 3 chars per line
% ( '.' = space) {default|0 -> default color order}
% 'rtitle' = right-side plot title {default|0 -> none}
% ydir = y-axis polarity (1 -> pos-up; -1 -> neg-up)
% {default|0 -> set from default YDIR in 'icadefs.m'}
%
% Authors: Scott Makeig, Arnaud Delorme, Tzyy-Ping Jung,
% SCCN/INC/UCSD, La Jolla, 05-01-96
%
% See also: plottopo(), timtopo(), envtopo(), headplot(), compmap(), eegmovie()
% Copyright (C) 05-01-96 Scott Makeig, Arnaud Delorme & Tzyy-Ping Jung,
% SCCN/INC/UCSD, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 5-1-96 from showerps.m -sm from showerp.m -tpj
% 5-3-96 added default channel numbering, frames & title -sm
% 5-17-96 added nargin tests below -sm
% 5-21-96 added right titles -sm
% 6-29-96 removed Postscript file query -sm
% 7-22-96 restored lines to fill printed page with figure -sm
% 7-29-96 added [channumbers] option for channames argument. -sm
% changed "channels" argument to "channames" in help statement above -sm
% 1-6-97 debugged min/max time and +/- printing -tpj & sm
% 3-3-97 restored previous Default axis parameters at end -sm
% 4-2-97 debugged 32-epoch plotting -sm
% 5-10-97 added no-args check -sm
% 5-20-97 read icadefs.m for MAXPLOTDATACHANS and MAXPLOTDATAEPOCHS -sm
% 6-23-97 use returns instead of errorcodes -sm
% 10-31-97 use normalized PaperUnits for US/A4 compatibility,
% fixed [xy]{min,max} printing, added clf, adding Clipping off,
% fixed scaling, added limits tests -sm & ch
% 11-19-97 removed an 'orient' command that caused problems printing -sm
% 07-15-98 added 'ydir' arg, made pos-up the default -sm
% 07-24-98 fixed 'ydir' arg, and pos-up default -sm
% 01-02-99 added warning about frames not dividing data length -sm
% 02-19-99 debugged axis limits -sm
% 11-21-01 add compatibility to load .loc files for channames -ad
% 01-25-02 reformated help & license, added links -ad
% 02-16-02 added axcopy -ad & sm
% 03-15-02 added readlocs and the use of eloc input structure -ad
% 03-15-02 added smart axcopy -ad
function plotdata(data,frames,limits,plottitle,channels,colors,righttitle,ydr)
if nargin < 1,
help plotdata
return
end
%
% Set defaults
%
FONTSIZE = 12; % font size to use for labels
TICKFONTSIZE=12; % font size to use for axis labels
icadefs; % read MAXPLOTDATACHANS constant from icadefs.m
% read YDIR
if ~exist('YDIR')
fprintf('YDIR not read from ''icadefs.m'' - plotting positive-up.\n');
YDIR = 1;
end
DEFAULT_SIGN = YDIR; % default to plotting positive-up (1) or negative-up (-1)
% Now, read sign from YDIR in icadefs.m
ISSPEC = 0; % default - 0 = not spectral data, 1 = pos-only spectra
axcolor= get(0,'DefaultAxesXcolor'); % find what the default x-axis color is
plotfile = 'plotdata.ps';
ls_plotfile = 'ls -l plotdata.ps';
%
%%%%%%%%%%%%%%%%%%%%%%%%%% Substitute defaults for missing parameters %%%%%
%
SIGN = DEFAULT_SIGN; % set default ydir from YDIR in icadefs.m
if nargin < 8
ydr = [];
end
if ~isempty(ydr)& ydr ~=0 % override default from commandline
if ydr == 1
SIGN = 1;
else
SIGN = -1;
end
end
if nargin < 7,
righttitle = 0;
end;
if nargin < 6
colors = 0;
end
if nargin < 5
channels = [1:size(data,1)]; % default channames = 1:chans
end
if nargin < 4
plottitle = 0; %CJH
end
limitset = 0;
if nargin < 3,
limits = 0;
elseif length(limits)>1
limitset = 1;
end
if nargin < 2,
frames = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%% Test parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
[chans,framestotal]=size(data); % data size
if frames <=0,
frames = framestotal; % default
datasets=1;
elseif frames==1,
fprintf('plotdata: cannot plot less than 2 frames per trace.\n');
return
datasets=1;
else
datasets = fix(framestotal/frames); % number of traces to overplot
if datasets*frames < framestotal
fprintf('\nWARNING: %d points at end of data will not be plotted.\n',...
framestotal-datasets*frames);
end
end;
if chans>MAXPLOTDATACHANS,
fprintf('plotdata: not set up to plot more than %d channels.\n',...
MAXPLOTDATACHANS);
return
end;
if datasets>MAXPLOTDATAEPOCHS
fprintf('plotdata: not set up to plot more than %d epochs.\n',...
MAXPLOTDATAEPOCHS);
return
end;
if datasets<1
fprintf('plotdata: cannot plot less than 1 epoch!\n');
return
end;
%
%%%%%%%%%%%%% Extend the size of the plotting area in the window %%%%%%%%%%%%
%
curfig = gcf;
h=figure(curfig);
set(h,'Color',BACKCOLOR); % set the background color
set(h,'PaperUnits','normalized'); % use percentages to avoid US/A4 difference
set(h,'PaperPosition',[0.0235308 0.0272775 0.894169 0.909249]); % equivalent
% orient portrait
axis('normal');
%
%%%%%%%%%%%%%%%%%%%% Read the channel names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isnumeric(channels) & channels(1)==0,
channels = [1:size(data,1)];
end;
if isnumeric(channels),
channames = num2str(channels(:)); %%CJH
else
[tmp channames] = readlocs(channels);
channames = strvcat(channames{:});
end;
% chid = fopen(channels,'r');
% if chid <3,
% fprintf('plotdata(): cannot open file %s.\n',channels);
% return
% end;
% if isempty( findstr( lower(channels), '.loc') )
% channames = fscanf(chid,'%s',[4 Inf]);
% channames = channames';
% else
% channames = fscanf(chid,'%d %f %f %s',[7 128]);
% channames = char(channames(4:7,:)');
% end;
% ii = find(channames == '.');
% channames(ii) = ' ';
%channames = channames';
% [r c] = size(channames);
%for i=1:r
% for j=1:c
% if channames(i,j)=='.',
% channames(i,j)=' ';
% end;
% end;
%end;
% end; % setting channames
%
%%%%%%%%%%%%%%%%%%%%%%%%% Read the color names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if colors ~=0,
if ~isstr(colors)
fprintf('plotdata(): color file name must be a string.\n');
return
end
cid = fopen(colors,'r');
% fprintf('cid = %d\n',cid);
if cid <3,
fprintf('plotdata: cannot open file %s.\n',colors);
return
end;
colors = fscanf(cid,'%s',[3 Inf]);
colors = colors';
[r c] = size(colors);
for i=1:r
for j=1:c
if colors(i,j)=='.',
colors(i,j)=' ';
end;
end;
end;
else % use default color order (no yellow!)
colors =['r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m '];
colors = [colors; colors]; % make > 64 available
end;
for c=1:size(colors,1) % make white traces black unless axis color is white
if colors(c,1)=='w' & axcolor~=[1 1 1]
colors(c,1)='k';
end
end
%
%%%%%%%%%%%%%%%%%%%%%%% Read and adjust limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if limits==0, % == 0 or [0 0 0 0]
xmin=0;
xmax=frames-1;
ymin=min(min(data));
ymax=max(max(data));
yrange = ymax-ymin;
ymin = ymin - 0.00*yrange;
ymax = ymax + 0.00*yrange;
else
if length(limits)~=4,
fprintf( ...
'plotdata: limits should be 0 or an array [xmin xmax ymin ymax].\n');
return
end;
xmin = limits(1);
xmax = limits(2);
ymin = limits(3);
ymax = limits(4);
end;
if xmax == 0 & xmin == 0,
x = (0:1:frames-1);
xmin = 0;
xmax = frames-1;
else
dx = (xmax-xmin)/(frames-1);
x=xmin*ones(1,frames)+dx*(0:frames-1); % compute x-values
end;
if xmax<=xmin,
fprintf('plotdata() - xmax must be > xmin.\n')
return
end
if ymax == 0 & ymin == 0,
ymax=double(max(max(data)));
ymin=double(min(min(data)));
yrange = ymax-ymin;
% ymin = ymin - 0.00*yrange;
% ymax = ymax + 0.00*yrange;
end
if ymax<=ymin,
fprintf('plotdata() - ymax must be > ymin.\n')
return
end
xlabel = 'Time (ms)';
if ymin >= 0 & xmin >= 0, % For all-positive (spectral) data
ISSPEC = 1;
SIGN = 1;
fprintf('\nPlotting positive up. Assuming data are spectra.\n');
xlabel = 'Freq (Hz)';
ymin = 0; % plot positive-up
end;
%
%%%%%%%%%%%%%%%%%%%%%%%% Set up plotting environment %%%%%%%%%%%%%%%%%%%%%%%%%
%
h = gcf;
% set(h,'YLim',[ymin ymax]); % set default plotting parameters
% set(h,'XLim',[xmin xmax]);
% set(h,'FontSize',18);
% set(h,'DefaultLineLineWidth',1); % for thinner postscript lines
%
%%%%%%%%%%%%%%%%%%%%%%%%%% Print plot info %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
clf; % clear the current figure
% print plottitle over (left) sbplot 1
if plottitle==0,
plottitle = '';
end
if righttitle==0,
righttitle = '';
end
if ~isempty(righttitle)
sbplot(ceil(chans/2),2,2), h=gca;%title([righttitle], 'FontSize',FONTSIZE); % title plot and
set(h,'FontSize',FONTSIZE); % choose font size
set(h,'YLim',[ymin ymax]); % set default plotting parameters
set(h,'XLim',[xmin xmax]);
end;
msg = ['\nPlotting %d traces of %d frames with colors: '];
for c=1:datasets
msg = [msg colors(mod(c-1,length(colors))+1,:)];
end
msg = [msg ' -> \n']; % print starting info on screen . . .
fprintf(...
'\n limits: [xmin,xmax,ymin,ymax] = [%4.1f %4.1f %4.2f %4.2f]\n',...
xmin,xmax,ymin,ymax);
fprintf(msg,datasets,frames);
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Plot traces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
xdiff=xmax-xmin;
ydiff=ymax-ymin;
for P=0:datasets-1, % for each data epoch
fprintf('\ntrace %d: ',P+1);
for I=1:chans, % for each data channel
index=(2*((rem(I-1,ceil(chans/2))+1)))-1+floor(2*(I-1)/chans);
% = 1 3 5 .. 2 4 6 ..
% plot down left side of page first
h=sbplot(ceil(chans/2),2,index); h=gca;
pos = get(h,'position');
set(h,'position',[pos(1)-pos(4)*0.5 pos(2), pos(3),pos(4)*2]); % increase sbplot-height
hold on;
set(h,'YLim',[ymin ymax]); % set default plotting parameters
set(h,'XLim',[xmin xmax]);
axislcolor = get(gca,'Xcolor'); %%CJH
%
%%%%%%%%%%%%%%%%%%%%% Plot two-sided time-series data %%%%%%%%%%%%%%%%%%%
%
if ~ISSPEC % not spectral data
ymin = double(ymin);
ymax = double(ymax);
if ymin == ymax, ymin = ymin-1; ymax = ymax+1; end;
plot(x,SIGN*data(I,1+P*frames:1+P*frames+frames-1),colors(mod(P,length(colors))+1));
if SIGN > 0
axis([xmin xmax ymin ymax]); % set axis bounds (pos up)
else
axis([xmin xmax -1*ymax -1*ymin]); % set axis bounds (neg up)
end
if P==datasets-1, % on last traces
if I==floor((chans+1)/2), % draw +/0 on lowest left plot
signx = double(xmin-0.04*xdiff);
if SIGN > 0 % pos up
axis('off');hl=text(signx,ymin,num2str(ymin,3)); % text ymin
axis('off');hi=text(signx,ymax,['+' num2str(ymax,3)]); % text +ymax
else % neg up
axis('off');hl=text(signx,-1*ymin,num2str(ymin,3)); % text ymin
axis('off');hi=text(signx,-1*ymax,['+' num2str(ymax,3)]); % text +ymax
end
set(hl,'FontSize',TICKFONTSIZE); % choose font size
set(hl,'HorizontalAlignment','right','Clipping','off');
set(hi,'FontSize',TICKFONTSIZE); % choose font size
set(hi,'HorizontalAlignment','right','Clipping','off');
end
if I==chans & limitset, % draw timescale on lowest right plot
ytick = double(-ymax-0.25*ydiff);
tick = [int2str(xmin)]; h=text(xmin,ytick,tick); % min time
set(h,'FontSize',TICKFONTSIZE); % choose font size
set(h,'HorizontalAlignment','center',...
'Clipping','off'); % center text
tick = [xlabel]; h=text(xmin+xdiff/2,ytick,tick); % xlabel
set(h,'FontSize',TICKFONTSIZE); % choose font size
set(h,'HorizontalAlignment','center',...
'Clipping','off'); % center text
tick = [int2str(xmax)]; h=text(xmax,ytick,tick); % max time
set(h,'FontSize',TICKFONTSIZE); % choose font size
set(h,'HorizontalAlignment','center',...
'Clipping','off'); % center text
end;
end;
%
%%%%%%%%%%%%%%%%%%%%% Plot spectral data positive-up [0,ymax] %%%%%%%%%%%%%%%%%%%%%%%%
%
else % ISSPEC
ymin=0;
plot(x,SIGN*data(I,1+P*frames:1+P*frames+frames-1),colors(mod(P,length(colors))+1));
ymaxm = ymax;
% ymin = 0.01;
% ymaxm = 10.^ceil(log(ymax)/log(10.));
% if ymaxm/2. > ymax,
% ymaxm = ymaxm/2.;
% end;
axis([xmin xmax ymin ymaxm]); % set axis values
if P==datasets-1, % on last trace
if I==floor((chans+1)/2), % draw +/0 on lowest left plot
signx = xmin-0.04*xdiff;
axis('off');h=text(signx,ymax,['+' num2str(ymax,3)]);
set(h,'FontSize',TICKFONTSIZE);
set(h,'HorizontalAlignment','right','Clipping','off');
axis('off');h=text(signx,0,'0');
set(h,'FontSize',TICKFONTSIZE);
set(h,'HorizontalAlignment','right','Clipping','off');
end;
if I==chans, % draw freq scale on lowest right plot
ytick = -0.25*ymax;
tick = [num2str(round(10*xmin)/10) ]; h=text(xmin,ytick,tick);
set(h,'FontSize',TICKFONTSIZE);
set(h,'HorizontalAlignment','center','Clipping','off');
tick = [xlabel]; h=text(xmin+xdiff/2,ytick,tick);
set(h,'FontSize',TICKFONTSIZE);
set(h,'HorizontalAlignment','center','Clipping','off');
tick = [num2str(round(10*xmax)/10) ]; h=text(xmax,ytick,tick);
set(h,'FontSize',TICKFONTSIZE);
set(h,'HorizontalAlignment','center','Clipping','off');
end; % if last chan
end % if last data
end; % if ~ISSPEC
%%%%%%%%%%%%%%%%%%%%%%% Print channel names and lines %%%%%%%%%%%%%%%%%%%%%%%%%%
if P==datasets-1
if ~ISSPEC
axis('off');
plot([0 0],[ymin ymax],'color',axislcolor); % draw vert %%CJH
% axis at time 0
else % ISSPEC
axis('off');plot([xmin xmin],[0 ymax],'color',axislcolor);
end
% secondx = 200; % draw second vert axis
% axis('off');plot([secondx secondx],[ymin ymax],'color',axislcolor);
axis('off');
plot([xmin xmax],[0 0],'color',axislcolor); % draw horizontal axis
if ~isempty(channels), % print channames
if ~ISSPEC
if ymin <= 0 & ymax >= 0,
yht = 0;
else
yht = nan_mean(SIGN*data(I,1+P*frames:1+P*frames+frames-1));
end
axis('off'),h=text(xmin-0.04*xdiff,double(yht),[channames(I,:)]);
set(h,'HorizontalAlignment','right'); % print before traces
set(h,'FontSize',FONTSIZE); % choose font size
% axis('off'),h=text(xmax+0.10*xdiff,yht,[channames(I,:)]);
% set(h,'HorizontalAlignment','left'); % print after traces
else % ISSPEC
axis('off'),h=text(xmin-0.04*xdiff,ymax/2,[channames(I,:)]);
set(h,'HorizontalAlignment','right'); % print before traces
set(h,'FontSize',FONTSIZE); % choose font size
% axis('off'),h=text(xmax+0.10*xdiff,ymax/2,[channames(I,:)]);
% set(h,'HorizontalAlignment','left'); % print after traces
end;
end;
end;
fprintf(' %d',I);
end; % subplot
end; % dataset
fprintf('\n');
%
%%%%%%%%%%%%%%%%%% Make printed figure fill page %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
curfig = gcf;
h=figure(curfig);
% set(h,'PaperPosition',[0.2 0.3 7.6 10]); % stretch out the plot on the page
%
%%%%%%%%%%%%%%%%%% Restore plot environment %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% set(h,'DefaultAxesYLim',aylim); % restore previous plotting parameters
% set(h,'DefaultAxesXLim',axlim);
% set(h,'DefaultAxesFontSize',axfont);
%%%%%%%%%%%%%%%%%% Add axcopy %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if plottitle
h = textsc(plottitle, 'title');
set(h, 'fontsize', FONTSIZE);
end;
axcopy(gcf, 'axis on');
if 0, % START DETOUR XXXXXXXXXXXXX
%
%%%%%%%%%%%%%%%%%% Save plot to disk if asked %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if plotfile ~= '', %
n=0; y=1;
answer = input('plotdata: Save plot as Postscript file? (y/n) ');
if answer==1,
fprintf('\nSaving figure as %s ... ',plotfile);
curfig = gcf;
h=figure(curfig);
% set(h,'PaperPosition',[0.2 0.3 7.6 10]);
% stretch out the plot on the page
eval (['print -dpsc ' plotfile]);
fprintf('saved. Move or remove file!\n');
unix(ls_plotfile);
end
end
end % END DETOUR XXXXXXXXXXXXX
function out = nan_mean(in)
nans = find(isnan(in));
in(nans) = 0;
sums = sum(in);
nonnans = ones(size(in));
nonnans(nans) = 0;
nonnans = sum(nonnans);
nononnans = find(nonnans==0);
nonnans(nononnans) = 1;
out = sum(in)./nonnans;
out(nononnans) = NaN;
|
github
|
lcnbeapp/beapp-master
|
snapread.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/snapread.m
| 5,372 |
utf_8
|
acab56fb5681e5c05feaebf418734cad
|
% snapread() - Read data in Snap-Master Standard Binary Data File Format
% Reads Snap-Master header and data matrix (nchans,nframes).
% Ref: Users Guide, Snap-Master for Windows (1997) p. 4-19
% Usage:
% >> data = snapread(filename); % read .SMA file data
% >> [data,params,events,head] = snapread(filename,seekframes);
% % save parameters, event list
% Inputs:
% filename = string containing whole filename of .SMA file to read
% seekframes = skip this many initial time points {default 0}
% Output:
% data = data matrix, size(nchans,nframes)
% params = [nchannels, nframes, srate]
% events = vector of event frames (lo->hi transitions on event channel);
% See source to set EVENT_CHANNEL and EVENT_THRESH.
% head = complete char file header
%
% Authors: Scott Makeig & Tzyy-Ping Jung, SCCN/INC/UCSD, La Jolla, January 31, 2000
% Copyright (C) January 31, 2000 from plotdata() Scott Makeig & Tzyy-Ping Jung, SCCN/INC/UCSD,
% [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% Scott Makeig & Tzyy-Ping Jung, CNL / Salk Institute / January 31, 2000
% 7-13-00 fixed fprintf count print bug -sm
% 7-13-00 added arg seekframes -sm & ss
% 7-13-00 added test for file length -sm & ss
% 2-15-02 change close('all') to fclose('all') -ad
% 2-15-02 reformated help & license -ad
function [data,params,events,head] = snapread(file,seekframes)
EVENT_CHANNEL = 1; % This channel assumed to store event pulses only!
EVENT_THRESH = 2.3; % Default event threshold (may need to adjust!!!!)
if nargin < 2
seekframes = 0;
end
data = [];
events = [];
params = [];
head = [];
%
%%%%%%%%%%%%%%%%%%%%%%%%%% Open file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
fid = fopen(file,'r', 'ieee-le');
if fid<1
fprintf('\nsnapread(): Could not open file %s.\n\n',file)
return
else
fprintf('\n Opened file %s for reading...\n',file);
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%% Read header %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Read header and extract info
numbegin=0;
head = [];
while ~numbegin,
line =fgets(fid);
head = [head line];
if (length(line)>=8 & line(1:8)=='"NCHAN%"')
nchans=str2num(line(findstr(line,'=')+1:end-1));
end
if (length(line)>= 12 & line(1:12)=='"NUM.POINTS"')
nframes=str2num(line(findstr(line,'=')+1:end-1));
end
if (length(line)>= 10 & line(1:10)=='"ACT.FREQ"')
srate=str2num(line(findstr(line,'=')+1:end-1));
end
if (length(line)>= 4 & line(1:4)=='"TR"')
head = head(1:length(head)-length(line));
line =fgets(fid); % get the time and date stamp line
numbegin=1;
end
end
params = [nchans, nframes, srate];
fprintf(' Number of channels: %d\n',nchans);
fprintf(' Number of data points: %d\n',nframes);
fprintf(' Sampling rate: %3.1f Hz\n',srate);
fseek(fid,1,0); % skip final hex-AA char
%
%%%%%%%%%%%%%%%%%%% Test for correct file length %%%%%%%%%%%%%%%%%%%%
%
datstart = ftell(fid); % save current position in file
fseek(fid,0,'eof'); % go to file end
datend = ftell(fid); % report position
discrep = (datend-datstart) - nchans*nframes*4;
if discrep ~= 0
fprintf(' ***> Note: File length does not match header information!\n')
fprintf(' Difference: %g frames\n',discrep/(4*nchans));
end
fseek(fid,datstart,'bof'); % seek back to data start
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Read data %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if seekframes > 0
fprintf(' Omitting first %d frames of data.\n',seekframes)
fprintf('moving %d bytes\n',seekframes*nchans*4);
fsq = fseek(fid,seekframes*nchans*4,'cof')
if fsq<0
fsqerr = ferror(fid);
fprintf('fseek() error: %s\n',fsqerr);
return
end
end
[data count] = fread(fid,[nchans,nframes],'float'); % read data frame
if count<nchans*(nframes-seekframes)
fprintf('\nsnapread(): Could not read %d data frames.\n Only %g read.\n\n',...
nframes,count/nchans);
return
else
fprintf('\n Read %d frames, each one sync channel(%d) and %d data channels.\n',...
nframes,EVENT_CHANNEL,nchans-1);
end
if nargout>2
fprintf(' Finding event transitions (>%g) on channel %d ...\n',...
EVENT_THRESH,EVENT_CHANNEL);
events = zeros(EVENT_CHANNEL,nframes);
for n=2:nframes
if abs(data(EVENT_CHANNEL,n-1)) < EVENT_THRESH ...
& abs(data(EVENT_CHANNEL,n)) > EVENT_THRESH
events(n) = 1;
end
end
fprintf(' Total of %d events found.\n',sum(events));
data = data(2:nchans,:); % eliminate channel 1
fprintf(' Event channel %d removed from output.\n',EVENT_CHANNEL);
params(1) = nchans-1;
end
fprintf('\n');
fclose('all');
|
github
|
lcnbeapp/beapp-master
|
cart2topo.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/cart2topo.m
| 5,225 |
utf_8
|
7ae7263796eecb060729861c9dd9b2fd
|
% cart2topo() - convert xyz-cartesian channel coordinates
% to polar topoplot() coordinates. Input data
% are points on a sphere centered at (0,0,0)
% or at optional input 'center'. This function
% is now DEPRECATED! See Important warning below.
%
% Usage: >> [th r] = cart2topo(xyz); % 3-column [x y z] position data
% >> [th r] = cart2topo(x,y,z); % separate x,y,z vectors
% >> [th r x y z] = cart2topo(xyz,'key', 'val', ...);
% >> [th r x y z] = cart2topo(x,y,z,'key', 'val', ...);
%
% Optional inputs:
% 'center' = [X Y Z] use a known sphere center {Default: [0 0 0]}
% 'squeeze' = plotting squeeze factor (0[default]->1). -1 -> optimize
% the squeeze factor automatically so that maximum radius is 0.5.
% 'optim' = [0|1] find the best-fitting sphere center minimizing the
% standard deviation of the radius values.
% 'gui' = ['on'|'off'] pops up a gui for optional arguments.
% Default is off.
%
% Example: >> [th r] = cart2topo(xyz,[1 0 4]);
%
% Notes: topoplot() does not plot channels with radius>0.5
% Shrink radii to within this range to plot all channels.
% [x y z] are returned after the optimization of the center
% and optionally squeezing r towards it by factor 'squeeze'
%
% Important:
% DEPRECATED: cart2topo() should NOT be used if elevation angle is less than 0
% (for electrodes below zero plane) since then it returns INNACURATE results.
% SUBSTITUTE: Use cart2topo = cart2sph() -> sph2topo().
%
% Authors: Scott Makeig, Luca Finelli & Arnaud Delorme SCCN/INC/UCSD,
% La Jolla, 11/1999-03/2002
%
% See also: topo2sph(), sph2topo(), chancenter()
% Copyright (C) 11/1999 Scott Makeig, SCCN/INC/UCSD, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 3-16-00 improved help message -sm
% 1-25-02 put spherror subfunction inside cart2topo -ad
% 1-25-02 help pops-up if no arguments -ad
% 01-25-02 reformated help & license -ad
% 02-13-02 now center fitting works, need spherror outside cart2topo -lf
% 02-14-02 radii are squeezed of squeeze in to fit topoplot circle -lf
% 03-31-02 center fitting is optional
% 04-01-02 automatic squeeze calculation -ad & sm
function [th,r,xx,yy,zz] = cart2topo(x,varargin)
if nargin<1
help cart2topo
return;
end;
if nargin >= 2
if ~ischar(varargin{1})
y = varargin{1};
z = varargin{2};
varargin = varargin(3:end);
end;
end;
if exist('y') ~= 1
if size(x,2)==3 % separate 3-column data
z = x(:,3);
y = x(:,2);
x = x(:,1);
else
error('Insufficient data in first argument');
end
end;
g = [];
if ~isempty(varargin)
try, g = struct(varargin{:});
catch, error('Argument error in the {''param'', value} sequence'); end;
end;
try, g.optim; catch, g.optim = 0; end;
try, g.squeeze; catch, g.squeeze = 0; end;
try, g.center; catch, g.center = [0 0 0]; end;
try, g.gui; catch, g.gui = 'off'; end;
if g.squeeze>1
fprintf('Warning: Squeeze must be less than 1.\n');
return
end
if ~isempty(g.center) & size(g.center,2) ~= 3
fprintf('Warning: Center must be [x y z].\n');
return
end
% convert to columns
x = -x(:); % minus os for consistency between measures
y = -y(:);
z = z(:);
if any(z < 0)
disp('WARNING: some electrodes lie below the z=0 plane, result may be innacurate')
disp(' Instead use cart2sph() then sph2topo().')
end;
if strcmp(g.gui, 'on')
[x y z newcenter] = chancenter(x, y, z, [], 1);
else
if g.optim == 1
[x y z newcenter] = chancenter(x, y, z, []);
else
[x y z newcenter] = chancenter(x, y, z, g.center);
end;
end;
radius = (sqrt(x.^2+y.^2+z.^2)); % assume xyz values are on a sphere
xx=-x; yy=-y; zz=z;
x = x./radius; % make radius 1
y = y./radius;
z = z./radius;
r = x; th=x;
for n=1:size(x,1)
if x(n)==0 & y(n)==0
r(n) = 0;
else
r(n) = pi/2-atan(z(n)./sqrt(x(n).^2+y(n).^2));
end
end
r = r/pi; % scale r to max 0.500
if g.squeeze < 0
g.squeeze = 1 - 0.5/max(r); %(2*max(r)-1)/(2*rmax);
fprintf('Electrodes will be squeezed together by %2.3g to show all\n', g.squeeze);
end;
r = r-g.squeeze*r; % squeeze electrodes in squeeze*100% to have all inside
for n=1:size(x,1)
if abs(y(n))<1e-6
if x(n)>0
th(n) = -90;
else % x(n) <= 0
th(n) = 90;
end
else
th(n) = atan(x(n)./y(n))*180/pi+90;
if y(n)<0
th(n) = th(n)+180;
end
end
if th(n)>180
th(n) = th(n)-360;
end
if th(n)<-180
th(n) = th(n)+360;
end
end
|
github
|
lcnbeapp/beapp-master
|
spec.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/spec.m
| 3,687 |
utf_8
|
02cf60598edf850b8ac8f112277a5be7
|
% spec() - power spectrum. This function replaces psd() function if the signal
% processing toolbox is not present. It uses the timef() function.
%
% Usage:
% >> [power freqs] = spec(X);
% >> [power freqs] = spec(X, nfft, fs, win, overlap);
%
% Inputs:
% X - data
% nfft - zero padding to length nfft
% fs - sampling frequency
% win - window size
% overlap - window overlap
%
% Outputs:
% power - spectral estimate (amplitude not dB)
% freqs - frequency array
%
% Note: this function is just an approximation of the psd() (not pwelch)
% method. We strongly recommend to use the psd function if you have
% access to it.
%
% Known problems:
% 1) normalization formula was determined manually by comparing
% with the output of the psd function on about 100 examples.
% 2) In case only one time window is necessary, the overlapping factor
% will be increased so that at least 2 windows are presents (the
% timef function cannot use a single time window).
% 3) FOR FILTERED DATA, THE POWER OVER THE FILTERED REGION IS WRONG
% (TOO HIGH)
% 4) the result of this function differs (in scale) from the pwelch
% function since the normalization is different for pwelch.
%
% Author: Arnaud Delorme, SCCN, Dec 2, 2003
% Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [power, freqs] = spec(X, nfft, fs, win, overlap);
if nargin < 1
help spec;
return;
end;
% default parameters
% ------------------
if nargin < 2
nfft = 256;
else
nfft = pow2(nextpow2(nfft));
end;
nfft = min(length(X), nfft);
if nargin < 3
fs = 2;
end;
if nargin < 4
win = nfft;
else
win = pow2(nextpow2(win));
end;
if win > length(X)
win = length(X);
end;
if log2(win) ~= round(log2(win))
win = pow2(floor(log2(win)));
end;
if nargin < 5
overlap = 0;
end;
% compute corresponding parameters for timef
% ------------------------------------------
padratio = pow2(nextpow2(nfft/win));
timesout = floor(length(X)/(win-overlap));
if timesout <= 1, timesout = 2; end;
[ersp itc mbase times freqs] = timef(X(:)', length(X), [0 length(X)]/fs*1000, fs, ...
0, 'padratio', padratio, 'timesout', timesout, 'winsize', win, 'maxfreq', fs/2, ...
'plotersp', 'off', 'plotitc', 'off', 'baseline', NaN, 'verbose', 'off');
ersp = 10.^(ersp/10); % back to amplitude
power = mean(ersp,2)*2.7/win; % this formula is a best approximation (I couldn't find the actual one)
% in practice the difference with psd is less than 0.1 dB
%power = 10*log10(power);
if nargout < 1
hold on;
h = plot(freqs, 10*log10(power));
set(h, 'linewidth', 2);
end;
return;
figure;
stdv = std(ersp, [], 2);
h = plot(freqs, power+stdv, 'r:');
set(h, 'linewidth', 2);
h = plot(freqs, power-stdv, 'r:');
set(h, 'linewidth', 2);
xlabel('Frequency (Hz)');
ylabel('Power (log)');
|
github
|
lcnbeapp/beapp-master
|
icavar.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/icavar.m
| 3,287 |
utf_8
|
20340418c38178274dabeb7cfd17572d
|
% icavar() - project ICA component activations through the ICA weight matrices
% to reconstitute the observed data using selected ICA components.
% Returns time course of variance on scalp for each component.
%
% Usage: >> [srcvar] = icavar(data,weights,sphere,compnums);
%
% Inputs:
% data - data matrix returned by runica()
% weights - weight matrix returned by runica()
% sphere - sphere matrix returned by runica() (default|0 -> eye(ncomps))
% compnums - list of component numbers (default|0 -> all)
%
% Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 11-30-1996
%
% See also: runica()
% Copyright (C) 11-30-1996 Scott Makeig, SCCN/INC/UCSD, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 04-03-97 made more efficient -sm
% 05-20-97 debugged variance calculation and made it more efficient -sm
% 06-07-97 changed order of args to conform to runica -sm
% 07-23-97 do not add back datamean to projections -sm
% 12-23-97 added compnums -sm
% 02-25-98 changed activations input to data -sm
% 07-20-98 use pinv() for inverting non-square weights -sm
% 01-25-02 reformated help & license, added links -ad
function [srcvar] = icavar(data,weights,sphere,compnums)
if nargin<2
help icavar
return
end
if size(weights,2) ~= size(sphere,1) | size(sphere,2) ~= size(data,1)
fprintf('icavar() - sizes of weights, sphere, and data incompatible.\n')
whos data weights sphere
return
end
activations = weights*sphere*data;
[ncomps,frames] = size(activations);
[wr,chans] = size(weights); % Note: ncomps may < data chans
if nargin<4
compnums = 0;
end
if compnums == 0,
compnums = 1:ncomps;
end
srcvar = zeros(length(compnums),frames);
if nargin < 3
sphere = 0;
end
if sphere == 0,
sphere = eye(ncomps);
end
project = weights*sphere;
if wr~=ncomps,
fprintf('icavar: Number of rows in activations and weights must be equal.\n');
return
end
% if wr<chans,
% fprintf('Filling out a square projection matrix with small noise.\n');
% for r=1:chans-wr,
% project = [project;0.00001*randn(1,chans)];
% end
% end
% project = inv(project); % invert projection matrix
if wr<chans
project = pinv(project);
else
project = inv(project);
end
fprintf('Projecting ICA component ');
nout = length(compnums);
for i=1:nout % for each component
comp = compnums(i);
fprintf('%d ',comp);
projdata = project(:,comp)*activations(comp,:); % reproject eeg data
srcvar(i,:) = sum(projdata.*projdata)/(chans-1);% compute variance at each time point
end
fprintf('\n');
|
github
|
lcnbeapp/beapp-master
|
eegrej.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/eegrej.m
| 6,611 |
utf_8
|
b882f67c5f4cfe3c0fbce6704b4faa70
|
% eegrej() - reject/excise arbitrary periods from continuous EEG data
% (e.g., EEG.data).
%
% Usage:
% >> [outdata newt newevents boundevents] = ...
% eegrej( indata, regions, timelength, eventlatencies);
%
% Inputs:
% indata - input data (channels, frames). If indata is a string,
% the function use the disk to perform the rejection
% regions - array of regions to suppress. [beg end] x number of
% regions. 'beg' and 'end' are expressed in term of points
% in the input dataset. The size() of the array should be
% (2, number of regions).
% timelength - length in time (s) of the input data. Only used to compute
% new total data length after rejections (newt).
% eventlatencies - vector of event latencies in data points.
% Default []=none.
%
% Outputs:
% outdata - output dataset
% newt - new total data length
% newevents - new event latencies. If the event was in a removed
% region, NaN is returned.
% boundevents - boundary events latencies
%
% Exemple:
% [outdat t] = eegrej( 'EEG.data', [1 100; 200 300]', [0 10]);
% this command pick up two regions in EEG.data (from point 1 to
% point 100, and point 200 to point 300) and put the result in
% the EEG.data variable in the global workspace (thus allowing
% to perform the operation even if EEG.data takes all the memory)
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [indata, times, events, boundevents] = eegrej( indata, regions, times, events )
if nargin < 2
help eegrej;
return;
end;
if nargin < 4
events = [];
end;
if isstr(indata)
datlen = evalin('base', [ 'size(' indata ',2)' ]);
else
datlen = size(indata, 2);
end;
reject = zeros(1,datlen);
% Checking for extreme values in regions (correcting round) RMC
regions = round(regions);
regions(regions > size(indata, 2)) = size(indata, 2);
regions(regions < 1) = 1;
regions = sortrows(sort(regions,2)); % Sorting regions %regions = sort(regions,1); RMC
for i=2:size(regions,1)
if regions(i-1,2) >= regions(i,1)
regions(i,1) = regions(i-1,2)+1;
end;
end;
for i=1:size(regions,1)
reject(regions(i,1):regions(i,2)) = 1;
end;
% recompute event times
% ---------------------
rmEvent = [];
rejectedEvents = {};
oriEvents = events;
if ~isempty(events)
eventLatencies = [ events.latency ];
oriEventLatencies = eventLatencies;
for i=1:size(regions,1)
% indices of removed events
rejectedEvents{i} = find( oriEventLatencies > regions(i,1) & oriEventLatencies < regions(i,2) );
rmEvent = [ rmEvent rejectedEvents{i} ];
% remove events within the selected regions
eventLatencies( oriEventLatencies > regions(i,1) ) = eventLatencies( oriEventLatencies > regions(i,1) )-(regions(i,2)-regions(i,1)+1);
%if i == 24, dsafds; end;
end;
for iEvent = 1:length(events)
events(iEvent).latency = eventLatencies(iEvent);
end;
events(rmEvent) = [];
end;
% generate boundaries latencies
% -----------------------------
boundevents = regions(:,1)-1;
for iRegion1=1:size(regions,1)
duration(iRegion1) = regions(iRegion1,2)-regions(iRegion1,1)+1;
% add nested boundary events
if ~isempty(events) && isstr(events(1).type) && isfield(events, 'duration')
selectedEvent = oriEvents(rejectedEvents{iRegion1});
indBound = strmatch('boundary', { selectedEvent.type });
duration(iRegion1) = duration(iRegion1) + sum([selectedEvent(indBound).duration]);
end;
for iRegion2=iRegion1+1:size(regions)
boundevents(iRegion2) = boundevents(iRegion2) - (regions(iRegion1,2)-regions(iRegion1,1)+1);
end;
end;
boundevents = boundevents+0.5;
boundevents(boundevents < 0) = [];
% reject data
% -----------
if isstr(indata)
disp('Using disk to reject data');
increment = 10000;
global elecIndices;
evalin('base', 'global elecIndices');
elecIndices = find(reject == 0);
evalin('base', 'fid = fopen(''tmpeegrej.fdt'', ''w'')');
evalin('base', ['numberrow = size(' indata ',1)']);
evalin('base', ['for indextmp=1:10000:length(elecIndices),', ...
' endtmp = min(indextmp+9999, length(elecIndices));' ...
' fwrite(fid,' indata '(:,elecIndices(indextmp:endtmp)), ''float'');'...
'end']);
evalin('base', 'fclose(fid)');
evalin('base', 'clear global elecIndices');
evalin('base', [ indata '=[]; clear ' indata '']);
evalin('base', 'fid = fopen(''tmpeegrej.fdt'', ''r'')');
evalin('base', [ indata '= fread(fid, [numberrow ' int2str(datlen) '], ''float'')']);
evalin('base', 'fclose(fid)');
evalin('base', 'clear numberrow indextmp endtmp fid');
evalin('base', 'delete(''tmpeegrej.fdt'')');
else
indata(:,reject == 1) = [];
end;
times = times * size(indata,2) / length(reject);
% merge boundary events
% ---------------------
for iBound = length(boundevents):-1:2
if boundevents(iBound) == boundevents(iBound-1)
duration(iBound-1) = duration(iBound-1)+duration(iBound);
boundevents(iBound) = [];
duration(iBound) = [];
end;
end;
if ~isempty(boundevents) && boundevents(end) > size(indata,2)
boundevents(end) = [];
end;
% insert boundary events
% ----------------------
for iRegion1=1:length(boundevents)
if boundevents(iRegion1) > 1 && boundevents(iRegion1) < size(indata,2)
events(end+1).type = 'boundary';
events(end).latency = boundevents(iRegion1);
events(end).duration = duration(iRegion1);
end;
end;
if ~isempty(events) && isfield(events, 'latency')
events([ events.latency ] < 1) = [];
alllatencies = [ events.latency ];
[tmp, sortind] = sort(alllatencies);
events = events(sortind);
end;
return;
|
github
|
lcnbeapp/beapp-master
|
sbplot.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/sbplot.m
| 4,612 |
utf_8
|
aac99a4963fad7c8aa7f4010998bc965
|
% sbplot() - create axes in arbitrary subplot grid positions and sizes
%
% Usage: >> axis_handle = sbplot(v,h,index)
% >> axis_handle = sbplot(v,h,[index1 index2])
% >> axis_handle = sbplot(v,h,[index1 index2],axprop,..)
% >> axis_handle = sbplot(v,h,[index1 index2],'ax',handle,axprop,..)
%
% Inputs:
% v,h - Integers giving the vertical and horizontal ranks of the tiling.
% index - Either a single subplot index, in which case the command
% is equivalent to subplot, or a two-element vector giving
% the indices of two corners of the sbplot() area according
% to subplot() convention (e.g., left-to-right, top-to-bottom).
% axprop - Any axes property(s), e.g., >> sbplot(3,3,3,'color','w')
% handle - Following keyword 'ax', sbplot tiles the given axes handle
% instead of the whole figure
%
% Output:
% axis_handle - matlab axis handle
%
% Note:
% sbplot is essentially the same as the subplot command except that
% sbplot axes may span multiple tiles. Also, sbplot() will not erase
% underlying axes.
%
% Examples: >> sbplot(3,3,6);plot(rand(1,10),'g');
% >> sbplot(3,3,[7 2]);plot(rand(1,10),'r');
% >> sbplot(8,7,47);plot(rand(1,10),'b');
%
% Authors: Colin Humphries, Arnaud Delorme & Scott Makeig, SCCN/INC/UCSD, La Jolla, June, 1998
% Copyright (C) June 1998, Colin Humphries & Scott Makeig, SCCN/INC/UCSD,
% [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% reformatted by Scott Makeig, 6/10/98
% 12/22/00 test nargin<3 -sm
% 01/21/01 added (recursive) axes option 'ax' -sm
% 01-25-02 reformated help & licence -ad
function [out] = sbplot(m,n,gridpos,varargin) % varargin is std. matlab arg list
if nargin<3
error(' requires >=3 arguments');
end
if nargin>3 & strcmp(varargin{1},'ax')
pos = get(varargin{2},'Position'); % sbplot(3,1,[2 3]) -> 0.4111 0.1100 0.4939 0.815
varargin = {varargin{3:end}};
else
pos = get(gcf,'DefaultAxesPosition'); % [0.1300 0.1100 0.7750 0.815]
end
Xpad = pos(1); % lower-left distance from left side of figure
Ypad = pos(2); % lower-left distance from bottom of figure
Xlen = pos(3); % axes width
Ylen = pos(4); % axes height
if n == 2
xspace = Xlen*0.27/(n-0.27); % xspace between axes as per subplot
else
xspace = (0.9*Xlen)*0.27/(n-0.9*0.27);
end
if m == 2
yspace = Ylen*0.27/(m-0.27); % yspace between axes as per subplot
else % WHY Xlen (.775) instead of Ylen (.815) ??
yspace = (0.9*Ylen)*0.27/(m-0.9*0.27);
end
xlength = (Xlen-xspace*(n-1))/n; % axes width
ylength = (Ylen-yspace*(m-1))/m; % axes height
% Convert tile indices to grid positions
if length(gridpos) == 1
xgridpos(1) = mod(gridpos,n); % grid position
if xgridpos(1) == 0
xgridpos(1) = n;
end
xgridpos(2) = 1; % grid length
ygridpos(1) = m-ceil(gridpos/n)+1; % grid position
ygridpos(2) = 1; % grid length
else
xgridpos(1) = mod(gridpos(1),n);
if xgridpos(1) == 0
xgridpos(1) = n;
end
tmp = mod(gridpos(2),n);
if tmp == 0
tmp = n;
end
if tmp > xgridpos(1)
xgridpos(2) = tmp-xgridpos(1)+1;
else
xgridpos(2) = xgridpos(1)-tmp+1;
xgridpos(1) = tmp;
end
ygridpos(1) = m-ceil(gridpos(1)/n)+1;
tmp = m-ceil(gridpos(2)/n)+1;
if tmp > ygridpos(1)
ygridpos(2) = tmp-ygridpos(1)+1;
else
ygridpos(2) = ygridpos(1)-tmp+1;
ygridpos(1) = tmp;
end
end
% Calculate axes coordinates
position(1) = Xpad+xspace*(xgridpos(1)-1)+xlength*(xgridpos(1)-1);
position(2) = Ypad+yspace*(ygridpos(1)-1)+ylength*(ygridpos(1)-1)-0.03;
position(3) = xspace*(xgridpos(2)-1)+xlength*xgridpos(2);
position(4) = yspace*(ygridpos(2)-1)+ylength*ygridpos(2);
% Create new axes
ax = axes('Position',position,varargin{:});
% Output axes handle
if nargout > 0
out = ax;
end
|
github
|
lcnbeapp/beapp-master
|
adjustlocs.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/adjustlocs.m
| 17,345 |
utf_8
|
540be08faa1b5d805504242c6d023cbb
|
% adjustlocs() - read neuroscan polar location file (.asc)
%
% Usage:
% >> chanlocs = adjustlocs( chanlocs );
% >> chanlocs = adjustlocs( chanlocs, 'key1', val1, 'key2', val2, ...);
%
% Inputs:
% chanlocs - EEGLAB channel location data structure. See
% help readlocs()
%
% Optional inputs:
% 'center' - [cell array] one or several electrode names to compute
% center location (if several electrodes are provided, the
% function use their iso-barycenter). Ex: { 'cz' } or
% { 'fz' 'pz' }.
% 'autocenter' - ['on'|'off'] attempt to automatically detect all symetrical
% electrode in the 10-20 system to compute the center.
% Default: 'on'.
% 'rotate' - [cell array] name and planar angle of landmark electrodes
% to use as template planar rotation. Ex: { 'c3', 90 }.
% 'autorotate' - ['on'|'off'] attempt to automatically detect
% electrode in the 10-20 system to compute the average
% planar rotation. Default 'on'.
% 'scale' - [cell array] name and phi angle of electrodes along
% horizontal central line. Ex: { 'c3' 44 }. Scale uniformly
% all direction. Use 'hscale' and 'vscale' for scaling x and
% y axis independently.
% 'hscale' - [cell array] name and phi angle of electrodes along
% honrizontal central line. Ex: { 'c3' 44 }.
% 'vscale' - [cell array] name and phi angle of one electrodes along
% central vertical axis. Ex: { 'fz' 44 }.
% 'autoscale' - ['on'|'off'] automatic scaling with 10-20 system used as
% reference. Default is 'on'.
% 'uniform' - ['on'|'off'] force the scaling to be uniform along the X
% and the Y axis. Default is 'on'.
% 'coordinates' - ['pol'|'sph'|'cart'] use polar coordinates ('pol'), sperical
% coordinates ('sph') or cartesian ('cart'). Default is 'sph'.
% (Note that using polar and spherical coordinates have the
% same effect, except that units are different).
% Default is 'sph'.
%
% Outputs:
% chanlocs - EEGLAB channel location data structure. See
% help readlocs()
%
% Note: operations are performed in the following order, first re-centering
% then planar rotation and finally sperical re-scaling.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 1 Dec 2003
%
% See also: readlocs()
% Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function chanlocs = adjustlocs( chanlocs, varargin)
if nargin < 1
help adjustlocs;
return;
end;
% check input parameters
% ----------------------
g = finputcheck( varargin, { 'hscale' 'cell' [] {};
'vscale' 'cell' [] {};
'scale' 'cell' [] {};
'center' 'cell' [] {};
'rotate' 'cell' [] {};
'autoscale' 'string' { 'on','off' } 'off';
'autocenter' 'string' { 'on','off' } 'on';
'autorotate' 'string' { 'on','off' } 'on';
'uniform' 'string' { 'on','off' } 'on';
'coordinates' 'string' { 'pol','sph','cart' } 'sph' });
if ischar(g), error(g); end;
names = { chanlocs.labels };
% auto center
% -----------
if strcmpi(g.autocenter, 'on') & isempty(g.center)
disp('Reading template 10-20 file');
locs1020 = readlocs('eeglab1020.ced');
% scan electrodes for horiz pos
% -----------------------------
tmpnames = lower(names);
tmpnames1020 = lower({ locs1020.labels });
[tmp indelec] = intersect_bc(tmpnames1020, tmpnames);
% remove non-symetrical electrodes
% --------------------------------
if ~isempty(indelec)
if find(indelec == 79), indelec(end+1) = 80; end; % for Cz
ind2remove = [];
for index = 1:length(indelec)
if mod(indelec(index),2)
if ~ismember(indelec(index)+1, indelec)
ind2remove = [ ind2remove index ];
end;
else
if ~ismember(indelec(index)-1, indelec)
ind2remove = [ ind2remove index ];
end;
end;
end;
indelec(ind2remove) = [];
if find(indelec == 80), indelec(end) = []; end; % for Cz
g.center = tmpnames1020(indelec);
end;
if isempty(g.center)
disp('No electrodes found for auto-centering')
else
disp([ num2str(length(g.center)) ' landmark electrodes found for position auto-centering' ])
end;
end;
% auto rotate
% -----------
if strcmpi(g.autorotate, 'on') & isempty(g.rotate)
if exist('locs1020') ~= 1
disp('Reading template 10-20 file');
locs1020 = readlocs('eeglab1020.ced');
end;
% scan electrodes for horiz pos
% -----------------------------
tmpnames = lower(names);
tmpnames1020 = lower({ locs1020.labels });
tmptheta1020 = { locs1020.theta };
[tmp indelec] = intersect_bc(tmpnames1020(1:end-1), tmpnames); % do not use cz
g.rotate(1:2:2*length(indelec)) = tmpnames1020 (indelec);
g.rotate(2:2:2*length(indelec)+1) = tmptheta1020(indelec);
if isempty(g.rotate)
disp('No electrodes found for auto planar rotation')
else
disp([ num2str(length(g.rotate)/2) ' landmark electrodes found for auto planar rotation' ])
end;
end;
% auto scale
% ----------
if strcmpi(g.autoscale, 'on') & isempty(g.hscale) & isempty(g.vscale)
if exist('locs1020') ~= 1
disp('Reading template 10-20 file');
locs1020 = readlocs('eeglab1020.ced');
end;
if strcmpi(g.uniform, 'off')
% remove all vertical electrodes for horizontal scaling
% -----------------------------------------------------
theta = [ locs1020.theta ];
indxh = find(abs(theta) == 90);
indxv = union_bc(find(theta == 0) , find(theta == 180));
locs1020horiz = locs1020(indxh);
locs1020vert = locs1020(indxv);
% scan electrodes for horiz pos
% -----------------------------
tmpnames = lower(names);
tmpnames1020 = lower({ locs1020horiz.labels });
tmpradius1020 = { locs1020horiz.radius };
[tmp indelec] = intersect_bc(tmpnames1020, tmpnames);
if isempty(indelec)
disp('No electrodes found for horiz. position spherical re-scaling')
else
disp([ num2str(length(indelec)) ' landmark electrodes found for horiz. position spherical re-scaling' ]);
if strcmpi(g.coordinates, 'cart')
g.hscale(2:2:2*length(indelec)+1) = [ locs1020horiz.Y ];
else
g.hscale(2:2:2*length(indelec)+1) = tmpradius1020(indelec);
end;
end;
% scan electrodes for vert. pos
% -----------------------------
tmpnames1020 = lower({ locs1020vert.labels });
tmpradius1020 = { locs1020vert.radius };
[tmp indelec] = intersect_bc(tmpnames1020, tmpnames);
if isempty(indelec)
disp('No electrodes found for vertical position spherical re-scaling')
else
disp([ num2str(length(indelec)) ' landmark electrodes found for vertical spherical re-scaling' ]);
g.vscale(1:2:2*length(indelec)) = tmpnames1020 (indelec);
if strcmpi(g.coordinates, 'cart')
g.vscale(2:2:2*length(indelec)+1) = [ locs1020vert.X ];
else
g.vscale(2:2:2*length(indelec)+1) = tmpradius1020(indelec);
end;
end;
else
% uniform scaling
% ---------------
tmpnames = lower(names);
tmpnames1020 = lower({ locs1020.labels });
tmpradius1020 = { locs1020.radius };
[tmp indelec] = intersect_bc(tmpnames1020, tmpnames);
if isempty(indelec)
disp('No electrodes found for uniform spherical re-scaling')
else
disp([ num2str(length(indelec)) ' landmark electrodes found for uniform spherical re-scaling' ]);
g.scale(1:2:2*length(indelec)) = tmpnames1020 (indelec);
if strcmpi(g.coordinates, 'cart')
tmpabsxyz = mattocell(abs([ locs1020.X ]+j*[ locs1020.Y ]));
g.scale(2:2:2*length(indelec)+1) = tmpabsxyz(indelec);
else
g.scale(2:2:2*length(indelec)+1) = tmpradius1020(indelec);
end;
end;
end;
if strcmpi(g.coordinates, 'sph')
g.coordinates = 'pol'; % use polar coordinates for scaling
end;
end;
% get X and Y coordinates
% -----------------------
if strcmpi(g.coordinates, 'sph') | strcmpi(g.coordinates, 'pol')
[X Y] = pol2cart( [ chanlocs.theta ]/180*pi, [ chanlocs.radius ]); Z = 1;
if strcmpi(g.coordinates, 'sph')
X = X/0.25*46;
Y = Y/0.25*46;
end;
else
X = [ chanlocs.X ];
Y = [ chanlocs.Y ];
Z = [ chanlocs.Z ];
end;
% recenter
% --------
if ~isempty(g.center)
for index = 1:length(g.center)
tmpindex = strmatch( lower(g.center{index}), lower(names), 'exact' );
if isempty(tmpindex)
error(['Electrode ''' g.center{index} ''' not found for re-centering']);
end;
indexelec(index) = tmpindex;
end;
showmsg('Using electrode', 'for re-centering', g.center);
centerx = mean(X(indexelec));
centery = mean(Y(indexelec));
X = X - centerx;
Y = Y - centery;
end;
% planar rotation
% ---------------
if ~isempty(g.rotate)
% find electrodes
% ---------------
clear elec;
for index = 1:2:length(g.rotate)
tmpindex = strmatch( lower(g.rotate{index}), lower(names), 'exact' );
if isempty(tmpindex)
error(['Electrode ''' g.rotate{index} ''' not found for left-right scaling']);
end;
elec((index+1)/2) = tmpindex;
end;
vals = [ g.rotate{2:2:end} ];
% compute average scaling factor
% ------------------------------
[ allangles tmp ] = cart2pol(X(elec), Y(elec));
allangles = allangles/pi*180;
diffangle = allangles - vals;
%diffangle2 = allangles + vals;
%if abs(diffangle1) > abs(diffangle2), diffangle = diffangle2;
%else diffangle = diffangle1;
%end;
tmpind = find(diffangle > 180); diffangle(tmpind) = diffangle(tmpind)-360;
tmpind = find(diffangle < -180); diffangle(tmpind) = diffangle(tmpind)+360;
anglerot = mean(diffangle);
tmpcplx = (X+j*Y)*exp(-j*anglerot/180*pi);
X = real(tmpcplx);
Y = imag(tmpcplx);
showmsg('Using electrode', ['for planar rotation (' num2str(anglerot,2) ' degrees)'], g.rotate(1:2:end));
end;
% computing scaling factors
% -------------------------
if ~isempty(g.scale)
% find electrodes
% ---------------
clear elec;
for index = 1:2:length(g.scale)
tmpindex = strmatch( lower(g.scale{index}), lower(names), 'exact' );
if isempty(tmpindex)
error(['Electrode ''' g.scale{index} ''' not found for left-right scaling']);
end;
elec((index+1)/2) = tmpindex;
end;
vals = [ g.scale{2:2:end} ];
% compute average scaling factor
% ------------------------------
nonzero = find(vals > 0);
hscalefact = mean(abs(Y(elec(nonzero))+j*X(elec(nonzero)))./vals(nonzero)); % *46/0.25; %/44/0.25;
vscalefact = hscalefact;
showmsg('Using electrode', ['for uniform spherical re-scaling (x' num2str(1/hscalefact,4) ')'], g.scale(1:2:end));
else
if ~isempty(g.hscale)
% find electrodes
% ---------------
clear elec;
for index = 1:2:length(g.hscale)
tmpindex = strmatch( lower(g.hscale{index}), lower(names), 'exact' );
if isempty(tmpindex)
error(['Electrode ''' g.hscale{index} ''' not found for left-right scaling']);
end;
elec((index+1)/2) = tmpindex;
end;
vals = [ g.hscale{2:2:end} ];
showmsg('Using electrode', [ 'for left-right spherical re-scaling (x' num2str(1/hscalefact,4) ')'], g.hscale(1:2:end));
% compute average scaling factor
% ------------------------------
hscalefact = mean(abs(Y(elec))./vals); % *46/0.25; %/44/0.25;
if isempty(g.vscale)
vscalefact = hscalefact;
end;
end;
if ~isempty(g.vscale)
% find electrodes
% ---------------
clear elec;
for index = 1:2:length(g.vscale)
tmpindex = strmatch( lower(g.vscale{index}), lower(names), 'exact' );
if isempty(tmpindex)
error(['Electrode ''' g.vscale{index} ''' not found for rear-front scaling']);
end;
elec((index+1)/2) = tmpindex;
end;
vals = [ g.vscale{2:2:end} ];
showmsg('Using electrode', ['for rear-front spherical re-scaling (x' num2str(1/vscalefact,4) ')'], g.vscale(1:2:end));
% compute average scaling factor
% ------------------------------
vscalefact = mean(abs(X(elec))./vals); % *46/0.25; %/44/0.25;
if isempty(g.vscale)
hscalefact = vscalefact;
end;
end;
end;
% uniform?
% --------
if strcmpi(g.uniform, 'on') & ( ~isempty(g.vscale) | ~isempty(g.hscale))
disp('uniform scaling: averaging left-right and rear-front scaling factor');
hscalefact = mean([hscalefact vscalefact]);
vscalefact = hscalefact;
end;
% scaling data
% ------------
if ~isempty(g.vscale) | ~isempty(g.hscale) | ~isempty(g.scale)
Y = Y/hscalefact;
X = X/vscalefact;
Z = Z/((hscalefact+vscalefact)/2);
end;
% updating structure
% ------------------
if strcmpi(g.coordinates, 'sph') | strcmpi(g.coordinates, 'pol')
[phi,theta] = cart2pol(Y, X);
phi = phi/pi*180;
if strcmpi(g.coordinates, 'pol')
theta = theta/0.25*46;
end;
% convert to other types of coordinates
% -------------------------------------
labels = names';
chanlocs = struct('labels', names, 'sph_theta_besa', mattocell(theta), ...
'sph_phi_besa', mattocell(phi), 'sph_radius', { chanlocs.sph_radius });
chanlocs = convertlocs( chanlocs, 'sphbesa2all');
else
for index = 1:length(chanlocs)
chanlocs(index).X = X(index);
chanlocs(index).Y = Y(index);
chanlocs(index).Z = Z(index);
end;
chanlocs = convertlocs(chanlocs, 'cart2all');
end;
function showmsg(begmsg, endmsg, struct);
if length(struct) <= 1
disp([ begmsg ' ''' struct{1} ''' ' endmsg]);
elseif length(struct) <= 2
disp([ begmsg ' ''' struct{1} ''' and ''' struct{2} ''' ' endmsg]);
elseif length(struct) <= 3
disp([ begmsg ' ''' struct{1} ''', ''' struct{2} ''' and ''' struct{3} ''' ' endmsg]);
else
disp([ begmsg ' ''' struct{1} ''', ''' struct{2} ''', ''' struct{3} ''' ... ' endmsg]);
end;
|
github
|
lcnbeapp/beapp-master
|
sph2topo.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/sigprocfunc/sph2topo.m
| 3,339 |
utf_8
|
44852faa1bc45208398680f08a50db29
|
% sph2topo() - Convert from a 3-column headplot file in spherical coordinates
% to 3-column topoplot() locs file in polar (not cylindrical) coords.
% Used for topoplot() and other 2-D topographic plotting programs.
% Assumes a spherical coordinate system in which horizontal angles
% have a range [-180,180] deg, with zero pointing to the right ear.
% In the output polar coordinate system, zero points to the nose.
% See >> help readlocs
% Usage:
% >> [chan_num,angle,radius] = sph2topo(input,shrink_factor,method);
%
% Inputs:
% input = [channo,az,horiz] = chan_number, azumith (deg), horiz. angle (deg)
% When az>0, horiz=0 -> right ear, 90 -> nose
% When az<0, horiz=0 -> left ear, -90 -> nose
% shrink_factor = arc_length shrinking factor>=1 (deprecated).
% 1 -> plot edge is 90 deg azimuth {default};
% 1.5 -> plot edge is +/-135 deg azimuth See
% >> help topoplot().
% method = [1|2], optional. 1 is for Besa compatibility, 2 is for
% compatibility with Matlab function cart2sph(). Default is 2
%
% Outputs:
% channo = channel number (as in input)
% angle = horizontal angle (0 -> nose; 90 -> right ear; -90 -> left ear)
% radius = arc_lengrh from vertex (Note: 90 deg az -> 0.5/shrink_factor);
% By topoplot() convention, radius=0.5 is the nasion-ear_canal plane.
% Use topoplot() 'plotrad' to plot chans with abs(az) > 90 deg.
%
% Author: Scott Makeig & Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 6/12/98
%
% See also: cart2topo(), topo2sph()
% Copyright (C) 6/12/98 Scott Makeig, SCCN/INC/UCSD, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% corrected left/right orientation mismatch, Blair Hicks 6/20/98
% changed name sph2pol() -> sph2topo() for compatibility -sm
% 01-25-02 reformated help & license -ad
% 01-25-02 changed computation so that it works with sph2topo -ad
function [channo,angle,radius] = sph2topo(input,factor, method)
chans = size(input,1);
angle = zeros(chans,1);
radius = zeros(chans,1);
if nargin < 1
help sph2topo
return
end
if nargin< 2
factor = 0;
end
if factor==0
factor = 1;
end
if factor < 1
help sph2topo
return
end
if size(input,2) ~= 3
help sph2topo
return
end
channo = input(:,1);
az = input(:,2);
horiz = input(:,3);
if exist('method')== 1 & method == 1
radius = abs(az/180)/factor;
i = find(az>=0);
angle(i) = 90-horiz(i);
i = find(az<0);
angle(i) = -90-horiz(i);
else
angle = -horiz;
radius = 0.5 - az/180;
end;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.