plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
lcnhappe/happe-master
pop_selectevent.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_selectevent.m
24,608
utf_8
4cc926ceeed20f4e4d5a975d4c884a9b
% pop_selectevent() - Find events in an EEG dataset. If the dataset % is the only input, a window pops up to % ask for the relevant parameter values. % % Usage: >> [EEGOUT,event_indices] = pop_selectevent( EEG, 'key1', value1, ... % 'key2', value2, ... ); % Input: % EEG - EEG dataset % % Optional inputs: % 'latency' - [latency_range] latency range of events to include % Ex: 'latency','400 <= 700' Include all events with % latnecy in the range [400,700] % 'omitlatency' - [latency_range] latency range of events to exclude % 'type' - [type_range] event type(s) to include % Ex: 'type',3 or [2 3 5] or 1:10 % 'omittype' - [type_range], type(s) of events to exclude % 'event' - [event_range], indices of events to include % 'omitevent' - [event_range], indices of events to exclude % 'USER_VAR' - [VAR_range], 'USER_VAR' is any user-defined field in % the event structure. Includes events with values of % field 'USER_VAR' in the specified range. Use [vector] % format for integers, 'min<max' format for real numbers. % 'omitUSER_VAR' - [VAR_range], 'USER_VAR' range of events to exclude % 'select' - ['normal'|'inverse'] invert the selection of events. % {Default is 'normal'} % 'deleteepochs' - ['on'|'off'] 'on' = Delete ALL epochs that do not include % any of the specified events {Default = 'on'}. % This option is relevant only for epoched datasets derived % from continuous datasets. % 'invertepochs' - ['on'|'off'] 'on' = Invert epoch selection. {Default = 'off'}. % 'deleteevents' - ['on'|'off'] 'on' = Delete ALL events except % the selected events. {Default = 'off'}. % 'renametype' - [string] rename the type of selected events with the % string given as parameter. {Default is [], do not rename % field}. % 'oldtypefield' - [string] in conjunction with the previous parameter, % create a new field (whose 'name' is provided as parameter) % to store the (old) type of the event whose type has been % renamed. {Default is [], do not create field}. % % Outputs: % EEGOUT - EEG dataset with the selected events only % event_indices - indexes of the selected events % % Ex: [EEGTARGETS,target_indices] = pop_selectevent(EEG,'type',[1 6 11 16 21]); % % % Returns ONLY THOSE epochs containing any of the 5 specified % types of target events. % % Note: By default, if several optional inputs are given, the function % performs their conjunction (&). % Boundary events are keeped by default??. (6/12/2014 Ramon) % % Author: Arnaud Delorme, CNL / Salk Institute, 27 Jan 2002- % % See also: eeg_eventformat(), pop_importevent() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 27 Jan 2002, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %02/01/2002 added inputgui and finalize function - ad %02/06/2002 work on the header and event format - sm & ad %02/09/2002 modify function according to new structure - ad %02/12/2002 add getepoch compatibility - ad %02/19/2002 add event indices & correct event selection - ad function [EEG, Ievent, com] = pop_selectevent(EEG, varargin); if nargin < 1 help pop_selectevent; return; end; Ievent = []; com =''; event_indices = []; % note that this function is also used for epochs % ----------------------------------------------- I = []; if isempty(EEG.event) disp('Getevent: cannot deal with empty event structure'); return; end; % remove the event field if present % --------------------------------- allfields = fieldnames(EEG.event); indexmatch = strmatch('urevent', allfields); if ~isempty(indexmatch) allfields = { allfields{1:indexmatch-1} allfields{indexmatch+1:end} }; end; if nargin<2 geometry = { [0.6 2.1 1.2 0.8 ] }; uilist = { ... { 'Style', 'text', 'string', 'Field', 'horizontalalignment', 'center', 'fontweight', 'bold' }, ... {} ... { 'Style', 'text', 'string', 'Selection', 'fontweight', 'bold' }, ... { 'Style', 'text', 'string', 'Set=NOT THESE', 'fontweight', 'bold' } }; % add all fields to graphic interface % ----------------------------------- ind1 = strmatch('type', allfields, 'exact'); ind2 = strmatch('latency' , allfields, 'exact'); ind3 = strmatch('duration', allfields, 'exact'); neworder = [ ind2 ind3 ind1 setdiff(1:length(allfields), [ind1 ind2 ind3]) ]; allfields = { allfields{neworder} }; for index = 1:length(allfields) % format the description to fit a help box % ---------------------------------------- if index <= length( EEG.eventdescription ) tmptext = EEG.eventdescription{ neworder(index) }; if ~isempty(tmptext) if size(tmptext,1) > 15, stringtext = [ tmptext(1,1:15) '...' ]; else stringtext = tmptext(1,:); end; else stringtext = 'no description'; tmptext = 'no description (use menu Edit > Event Field)'; end; else stringtext = 'no description'; tmptext = 'no description (use menu Edit > Event Field)'; end; descrip = { 'string', stringtext, 'callback', ['questdlg2(' vararg2str(tmptext) ... ',''Description of field ''''' allfields{index} ''''''', ''OK'', ''OK'');' ] }; % create the gui for this field % ----------------------------- textfield = allfields{index}; if strcmp(textfield, 'latency') | strcmp(textfield, 'duration') if EEG.trials > 1, textfield = [ textfield ' (ms)' ]; else textfield = [ textfield ' (s)' ]; end; middletxt = { { 'Style', 'text', 'string', 'min' } { 'Style', 'edit', 'string', '' 'tag' [ 'min' allfields{index} ] } ... { 'Style', 'text', 'string', 'max' } { 'Style', 'edit', 'string', '' 'tag' [ 'max' allfields{index} ] } }; middlegeom = [ 0.3 0.35 0.3 0.35 ]; elseif strcmp(textfield, 'type') commandtype = [ 'if ~isfield(EEG.event, ''type'')' ... ' errordlg2(''No type field'');' ... 'else' ... ' tmpevent = EEG.event;' ... ' if isnumeric(EEG.event(1).type),' ... ' [tmps,tmpstr] = pop_chansel(unique([ tmpevent.type ]));' ... ' else,' ... ' [tmps,tmpstr] = pop_chansel(unique({ tmpevent.type }));' ... ' end;' ... ' if ~isempty(tmps)' ... ' set(findobj(''parent'', gcbf, ''tag'', ''type''), ''string'', tmpstr);' ... ' end;' ... 'end;' ... 'clear tmps tmpv tmpevent tmpstr tmpfieldnames;' ]; middletxt = { { 'Style', 'edit', 'string', '' 'tag' 'type' } { 'Style', 'pushbutton', 'string', '...' 'callback' commandtype } }; middlegeom = [ 0.95 0.35 ]; else middletxt = { { 'Style', 'edit', 'string', '' 'tag' textfield } }; middlegeom = 1.3; end; geometry = { geometry{:} [0.55 0.65 middlegeom 0.1 0.22 0.1] }; uilist = { uilist{:}, ... { 'Style', 'text', 'string', textfield }, ... { 'Style', 'pushbutton', descrip{:}, 'horizontalalignment', 'left' }, ... middletxt{:}, ... { }, { 'Style', 'checkbox', 'string', ' ' 'tag' [ 'not' allfields{index} ] },{ } }; end; % event indices % ------------- uilist = { uilist{:} ... { 'Style', 'text', 'string', 'Event indices' }, ... { }, ... { 'Style', 'edit', 'string', '' 'tag' 'indices' }, ... { }, { 'Style', 'checkbox', 'string', ' ' 'tag' 'notindices' },{ } }; geometry = { geometry{:} [0.55 0.65 1.3 0.1 0.22 0.1] }; % rename/keep events % ------------------ geometry = { geometry{:} [1] [1] [.1 2 .3 .2] [.1 1.5 0.5 0.5] [.1 1 0.5 1] [.1 1 0.5 1] }; uilist = { uilist{:} { } ... { 'Style', 'text', 'string','Event selection', 'fontweight', 'bold' } ... {} { 'Style', 'checkbox', 'string','Select all events NOT selected above (Set this button and "all BUT" buttons (above) for logical OR)' 'tag' 'invertevent' } { } { } ... {} { 'Style', 'checkbox', 'string','Keep only selected events and remove all other events', ... 'value', fastif(EEG.trials>1, 0, 1) 'tag' 'rmevents' } { } { } ... {} { 'Style', 'text', 'string', 'Rename selected event type(s) as type:' } ... { 'Style', 'edit', 'string', '' 'tag' 'rename' } { } ... {} { 'Style', 'text', 'string', 'Retain old event type name(s) in (new) field named:' } ... { 'Style', 'edit', 'string', '' 'tag' 'retainfield' } { } }; % epoch selections % ---------------- if EEG.trials > 1 geometry = { geometry{:} [1] [0.1 2 0.5 0.5] [0.1 2 0.5 0.5]}; uilist = { uilist{:} ... { 'Style', 'text', 'string','Epoch selection', 'fontweight', 'bold' } ... { } { 'Style', 'checkbox', 'string','Remove epochs not referenced by any selected event', ... 'value', 1 'tag' 'rmepochs' } { } { } ... { } { 'Style', 'checkbox', 'string','Invert epoch selection', ... 'value', 0 'tag' 'invertepoch' } { } { } }; end; [results tmp2 tmp3 res] = inputgui( geometry, uilist, 'pophelp(''pop_selectevent'')', 'Select events -- pop_selectevent()'); if length(results) == 0, return; end; % decode inputs % ------------- args = {}; if ~res.notindices, args = { args{:}, 'event', eval( [ '[' res.indices ']' ]) }; else args = { args{:}, 'omitevent', eval( [ '[' res.indices ']' ]) }; end; for index = 1:length(allfields) textfield = allfields{index}; tmpflag = getfield(res, [ 'not' textfield ]); if strcmp(textfield, 'duration') | strcmp(textfield, 'latency') tmpres = []; minlat = getfield(res, [ 'min' textfield ]); maxlat = getfield(res, [ 'max' textfield ]); if ~isempty(minlat) & ~isempty(maxlat) tmpres = [ minlat '<=' maxlat ]; end; else tmpres = getfield(res, textfield); try, tmpres2 = eval( [ '[' tmpres ']' ] ); if ~isnumeric(tmpres2), if tmpres(1) == '''' tmpres = eval( [ '{' tmpres '}' ] ); else tmpres = parsetxt( tmpres ); end; else tmpres = tmpres2; end; catch, tmpres = parsetxt( tmpres ); end; end if ~isempty(tmpres) if ~tmpflag, args = { args{:}, textfield, tmpres }; else args = { args{:}, [ 'omit' textfield], tmpres }; end; end; end; if res.invertevent, args = { args{:}, 'select', 'inverse' }; end; if ~isempty(res.rename), args = { args{:}, 'renametype', res.rename }; end; if ~isempty(res.retainfield), args = { args{:}, 'oldtypefield', res.retainfield }; end; args = { args{:}, 'deleteevents', fastif(res.rmevents, 'on', 'off') }; if EEG.trials > 1 args = { args{:}, 'deleteepochs', fastif(res.rmepochs , 'on', 'off') }; args = { args{:}, 'invertepochs', fastif(res.invertepoch , 'on', 'off') }; end; else % no interactive inputs args = varargin; end; % setting default for the structure % --------------------------------- fieldlist = { 'event' 'integer' [] [1:length(EEG.event)] ; 'omitevent' 'integer' [] [] ; 'deleteepochs' 'string' { 'yes','no','on','off' } 'on' ; 'invertepochs' 'string' { 'on','off' } 'off' ; 'deleteevents' 'string' { 'yes','no','on','off' } 'off'; 'renametype' 'string' [] ''; 'oldtypefield' 'string' [] ''; 'select' 'string' { 'normal','inverse','remove','keep' } 'normal' }; for index = 1:length(allfields) fieldlist{end+1, 1} = allfields{index}; fieldlist{end , 2} = ''; fieldlist{end+1, 1} = [ 'omit' allfields{index} ]; fieldlist{end , 2} = ''; end; g = finputcheck( args, fieldlist, 'pop_selectevent'); if isstr(g), error(g); end; if isempty(g.event), g.event = [1:length(EEG.event)]; end; if strcmpi(g.select, 'remove'), g.select = 'inverse'; end; if strcmpi(g.select, 'keep' ), g.select = 'normal'; end; if strcmpi(g.deleteepochs, 'yes' ), g.deleteepochs = 'on'; end; if strcmpi(g.deleteepochs, 'no' ), g.deleteepochs = 'off'; end; if ~isempty(g.oldtypefield) & isempty(g.renametype) error('A name for the new type must be defined'); end; % select the events to keep % ------------------------- Ievent = g.event; Ieventrem = g.omitevent; for index = 1:length(allfields) % convert the value if the field is a string field % ------------------------------------------------ tmpvar = getfield(g, {1}, allfields{index}); if ~isempty(tmpvar) if isnumeric(tmpvar) if isstr(getfield( EEG.event, {1}, allfields{index})) for tmpind = 1:length(tmpvar) tmpvartmp{tmpind} = num2str(tmpvar(tmpind)); end; tmpvar = tmpvartmp; end; elseif isstr(tmpvar) & isempty( findstr(tmpvar, '<=')) if isnumeric(getfield( EEG.event, {1}, allfields{index})) error(['numerical values must be entered for field ''' allfields{index} '''']); end; end; end; if isstr(tmpvar) & isempty( findstr(tmpvar, '<=')) tmpvar = { tmpvar }; end; % scan each field of EEG.event % ---------------------------- if ~isempty( tmpvar ) if iscell( tmpvar ) % strings eval( [ 'tmpevent = EEG.event; tmpvarvalue = {tmpevent(:).' allfields{index} '};'] ); Ieventtmp = []; for index2 = 1:length( tmpvar ) tmpindex = transpose(find(strcmp(deblank(tmpvar{index2}), deblank(tmpvarvalue))));%Ramon: for bug 1318. Also for compatibility(strmatch will be deleted in next versions of MATLAB) %tmpindex = strmatch( tmpvar{index2}, tmpvarvalue, 'exact'); if isempty( tmpindex ), fprintf('Warning: ''%s'' field value ''%s'' not found\n', allfields{index}, tmpvar{index2}); end; Ieventtmp = unique_bc( [ Ieventtmp; tmpindex ]); end; Ievent = intersect_bc( Ievent, Ieventtmp ); elseif isstr( tmpvar ) % real range tmpevent = EEG.event; % ======== JRI BUGFIX 3/6/14 %eval( [ 'tmpvarvalue = [ tmpevent(:).' allfields{index} ' ];'] ); tmpvarvalue = safeConcatenate(EEG.event, allfields{index}); min = eval(tmpvar(1:findstr(tmpvar, '<=')-1)); max = eval(tmpvar(findstr(tmpvar, '<=')+2:end)); if strcmp(allfields{index}, 'latency') if EEG.trials > 1 tmpevent = EEG.event; tmpvarvalue = eeg_point2lat(tmpvarvalue, {tmpevent.epoch}, EEG.srate, ... [EEG.xmin EEG.xmax]*1000, 1E-3); else tmpvarvalue = eeg_point2lat(tmpvarvalue, ones(1,length(EEG.event)), EEG.srate, ... [EEG.xmin EEG.xmax], 1); end; end; if strcmp(allfields{index}, 'duration') if EEG.trials > 1, tmpvarvalue = tmpvarvalue/EEG.srate*1000; else tmpvarvalue = tmpvarvalue/EEG.srate; end; end; Ieventlow = find( tmpvarvalue >= min); Ieventhigh = find( tmpvarvalue <= max); Ievent = intersect_bc( Ievent, intersect( Ieventlow, Ieventhigh ) ); else if strcmp(allfields{index}, 'latency') fprintf(['pop_selectevent warning: latencies are continuous values\n' ... 'so you may use the ''a<=b'' notation to select these values\n']); end; % ======== JRI BUGFIX 3/6/14 %eval( [ 'tmpevent = EEG.event; tmpvarvalue = [ tmpevent(:).' allfields{index} ' ];'] ); tmpvarvalue = safeConcatenate(EEG.event, allfields{index}); Ieventtmp = []; for index2 = 1:length( tmpvar ) Ieventtmp = unique_bc( [ Ieventtmp find(tmpvarvalue == tmpvar(index2)) ] ); end; Ievent = intersect_bc( Ievent, Ieventtmp ); end; end; % scan each field of EEG.event (omit) % ----------------------------------- tmpvar = eval(['g.omit' allfields{index} ]); if eval(['isstr(EEG.event(1).' allfields{index} ')' ]) & isnumeric(tmpvar) & ~isempty(tmpvar) for tmpind = 1:length(tmpvar) tmpvartmp{tmpind} = num2str(tmpvar(tmpind)); end; tmpvar = tmpvartmp; end; if isstr(tmpvar) & isempty( findstr(tmpvar, '<=')) tmpvar = { tmpvar }; end; if ~isempty( tmpvar ) if iscell( tmpvar ) eval( [ 'tmpevent = EEG.event; tmpvarvalue = {tmpevent(:).' allfields{index} '};'] ); Ieventtmp = []; for index2 = 1:length( tmpvar ) tmpindex = strmatch( tmpvar{index2}, tmpvarvalue, 'exact'); if isempty( tmpindex ), fprintf('Warning: ''%s'' field value ''%s'' not found\n', allfields{index}, tmpvar{index2}); end; Ieventtmp = unique_bc( [ Ieventtmp; tmpindex ]); end; Ieventrem = union_bc( Ieventrem, Ieventtmp ); elseif isstr( tmpvar ) tmpevent = EEG.event; % ======== JRI BUGFIX 3/6/14 %eval( [ 'tmpvarvalue = [ tmpevent(:).' allfields{index} ' ];'] ); tmpvarvalue = safeConcatenate(EEG.event, allfields{index}); min = eval(tmpvar(1:findstr(tmpvar, '<=')-1)); max = eval(tmpvar(findstr(tmpvar, '<=')+2:end)); if strcmp(allfields{index}, 'latency') if EEG.trials > 1 tmpevent = EEG.event; tmpvarvalue = eeg_point2lat(tmpvarvalue, {tmpevent.epoch}, EEG.srate, ... [EEG.xmin EEG.xmax]*1000, 1E-3); else tmpvarvalue = eeg_point2lat(tmpvarvalue, ones(1,length(EEG.event)), EEG.srate, ... [EEG.xmin EEG.xmax], 1); end; end; if strcmp(allfields{index}, 'duration') if EEG.trials > 1, tmpvarvalue = tmpvarvalue/EEG.srate*1000; else tmpvarvalue = tmpvarvalue/EEG.srate; end; end; Ieventlow = find( tmpvarvalue > min); Ieventhigh = find( tmpvarvalue < max); Ieventrem = union_bc( Ieventrem, intersect( Ieventlow, Ieventhigh ) ); else if strcmp(allfields{index}, 'latency') fprintf(['pop_selectevent warning: latencies are continuous values\n' ... 'so you may use the ''a<=b'' notation to select these values\n']); end; tmpevent = EEG.event; % ======== JRI BUGFIX 3/6/14 %eval( [ 'tmpvarvalue = [ tmpevent(:).' allfields{index} ' ];'] ); tmpvarvalue = safeConcatenate(EEG.event, allfields{index}); Ieventtmp = []; for index2 = 1:length( tmpvar ) Ieventtmp = unique_bc( [ Ieventtmp find( tmpvarvalue ==tmpvar(index2)) ] ); end; Ieventrem = union_bc( Ieventrem, Ieventtmp ); end; end; end; Ievent = setdiff_bc( Ievent, Ieventrem); if strcmp(g.select, 'inverse') Ievent = setdiff_bc( [1:length(EEG.event)], Ievent ); end; % checking if trying to remove boundary events (in continuous data) if isfield(EEG.event, 'type') if isstr(EEG.event(1).type) & EEG.trials == 1 Ieventrem = setdiff_bc([1:length(EEG.event)], Ievent ); tmpevent = EEG.event; boundaryindex = strmatch('boundary', { tmpevent(Ieventrem).type }); if ~isempty(boundaryindex) boundaryindex = Ieventrem(boundaryindex); Ievent = [ Ievent boundaryindex ]; end; Ievent = sort(Ievent); else boundaryindex = []; end; else boundaryindex = []; end; % rename events if necessary % -------------------------- if ~isempty(g.renametype) fprintf('Pop_selectevent: renaming %d selected events (out of %d)\n', length(Ievent), length(EEG.event)); if ~isempty(g.oldtypefield) for index = setdiff_bc(Ievent, boundaryindex) eval([ 'EEG.event(index).' g.oldtypefield '= EEG.event(index).type;']); EEG.event(index).type = g.renametype; end; else for index = setdiff_bc(Ievent, boundaryindex) EEG.event(index).type = g.renametype; end; end; end; % Events: delete epochs % --------------------- if strcmp( lower(g.deleteepochs), 'on') & EEG.trials > 1 % ask for confirmation % -------------------- Iepoch = ones(1, EEG.trials); for index = 1:length(Ievent) Iepoch(EEG.event(Ievent(index)).epoch) = 0; end; if strcmpi(g.invertepochs, 'on') Iepoch = ~Iepoch; end; Iepoch = find(Iepoch == 0); if length(Iepoch) == 0, error('Empty dataset: all epochs have been removed'); end; if nargin < 2 ButtonName=questdlg2(strvcat([ 'Warning: delete ' num2str(EEG.trials-length(Iepoch)) ... ' (out of ' int2str(EEG.trials) ') un-referenced epochs ?' ]), ... 'Confirmation', ... 'Cancel', 'Ok','Ok'); else ButtonName = 'ok'; end; switch lower(ButtonName), case 'cancel', return; case 'ok', if strcmpi(g.deleteevents, 'on') EEG.event = EEG.event(Ievent); end; EEG = pop_select(EEG, 'trial', Iepoch); end % switch else % delete events if necessary % -------------------------- if strcmpi(g.deleteevents, 'on') EEG.event = EEG.event(Ievent); end; end; EEG = eeg_checkset(EEG, 'eventconsistency'); % generate the output command % --------------------------- argsout = {}; for index =1:2:length(args) if ~isempty(args{index+1}) argsout = { argsout{:} args{index} args{index+1}}; end; end; com = sprintf('EEG = pop_selectevent( %s, %s);', inputname(1), vararg2str(argsout)); % chop the text so that it fits into the description window % --------------------------------------------------------- function chopedtext = choptext( tmptext ) chopedtext = ''; while length(tmptext) > 30 blanks = findstr( tmptext, ' '); [tmp I] = min( abs(blanks - 30) ); chopedtext = [ chopedtext ''' 10 ''' tmptext(1:blanks(I)) ]; tmptext = tmptext(blanks(I)+1:end); end; chopedtext = [ chopedtext ''' 10 ''' tmptext]; chopedtext = chopedtext(7:end); return; % ======== JRI BUGFIX 3/6/14 % safely concatenate a numeric field that may contain empty values, replacing them with nans % --------------------------------------------------------- function tmpvarvalue = safeConcatenate(S, fieldname) try tmpvarvalue = {S.(fieldname)}; tmpvarvalue = cellfun(@(x) fastif(isempty(x),nan,x), tmpvarvalue); catch %keep this style for backwards compatibility? eval( [ 'tmpvarvalue = {S(:).' fieldname ' };'] ); for itmp = 1:length(tmpvarvalue), if isempty(tmpvarvalue{itmp}), tmpvarvalue{itmp} = nan; end end tmpvarvalue = cell2mat(tmpvarvalue); end % ======== JRI BUGFIX 3/6/14
github
lcnhappe/happe-master
pop_saveh.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_saveh.m
2,630
utf_8
946d5b48194c0957d6393b94d4905de1
% pop_saveh() - save the EEGLAB session command history stored in ALLCOM % or in the 'history' field of the current dataset % % Usage: % >> pop_saveh( ALLCOM, filename, filepath); % >> pop_saveh( EEG.history, filename, filepath); % % Inputs: % ALLCOM - cell array of strings containing the EEGLAB command history % EEG.history - history field of the current dataset % filename - name of the file to save to (optional, default "eeglabhist.m" % filepath - path of the file to save to (optional, default pwd) % % Author: Arnaud Delorme, CNL / Salk Institute, 22 March 2002 % % See also: eegh(), eeglab() % Copyright (C) 22 March 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-29-02 added update menu -ad function com = pop_saveh( allcoms, curfilename, curfilepath); com = ''; if nargin < 1 help pop_saveh; return; end; if nargin < 3 [curfilename, curfilepath] = uiputfile('eeglabhist.m', 'Save the EEGLAB session command history with .m extension -- pop_saveh()'); drawnow; if curfilename == 0 return; end; end; fid = fopen( [ curfilepath '/' curfilename ], 'w'); if fid == -1 error('pop_saveh(): Cannot open named file'); end; fprintf(fid, '%% EEGLAB history file generated on the %s\n', date); fprintf(fid, '%% ------------------------------------------------\n'); if iscell(allcoms) disp('Saving the EEGLAB session command history...'); for index = length(allcoms):-1:1 fprintf(fid, '%s\n', allcoms{index}); end; fprintf(fid, 'eeglab redraw;\n'); else disp('Saving the current EEG dataset command history...'); fprintf(fid, '%s\n', allcoms); end; fclose(fid); if iscell(allcoms) com = sprintf('pop_saveh( %s, ''%s'', ''%s'');', inputname(1), curfilename, curfilepath); else com = sprintf('pop_saveh( EEG.history, ''%s'', ''%s'');', curfilename, curfilepath); end; return;
github
lcnhappe/happe-master
pop_resample.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_resample.m
13,646
utf_8
933e0e2a8d283f5297fbe37c3fe21864
% pop_resample() - resample dataset (pop up window). % % Usage: % >> [OUTEEG] = pop_resample( INEEG ); % pop up interactive window % >> [OUTEEG] = pop_resample( INEEG, freq); % >> [OUTEEG] = pop_resample( INEEG, freq, fc, df); % % Graphical interface: % The edit box entitled "New sampling rate" contains the frequency in % Hz for resampling the data. Entering a value in this box is the same % as providing it in the 'freq' input from the command line. % % Inputs: % INEEG - input dataset % freq - frequency to resample (Hz) % % Optional inputs: % fc - anti-aliasing filter cutoff (pi rad / sample) % {default 0.9} % df - anti-aliasing filter transition band width (pi rad / % sample) {default 0.2} % % Outputs: % OUTEEG - output dataset % % Author: Arnaud Delorme, CNL/Salk Institute, 2001 % % Note: uses the resample() function from the signal processing toolbox % if present. Otherwise use griddata interpolation method (it should be % reprogrammed using spline interpolation for speed up). % % See also: resample(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-08-02 remove ica activity resampling (now set to []) -ad % 03-08-02 debug call to function help -ad % 04-05-02 recompute event latencies -ad function [EEG, command] = pop_resample( EEG, freq, fc, df); command = ''; if nargin < 1 help pop_resample; return; end; if isempty(EEG(1).data) disp('Pop_resample error: cannot resample empty dataset'); return; end; if nargin < 2 % popup window parameters % ----------------------- promptstr = {['New sampling rate']}; inistr = { num2str(EEG(1).srate) }; result = inputdlg2( promptstr, 'Resample current dataset -- pop_resample()', 1, inistr, 'pop_resample'); if length(result) == 0 return; end; freq = eval( result{1} ); end; % Default cutoff frequency (pi rad / smp) if nargin < 3 || isempty(fc) fc = 0.9; end % Default transition band width (pi rad / smp) if nargin < 4 || isempty(df) df = 0.2; end % fc in range? if fc < 0 || fc > 1 error('Anti-aliasing filter cutoff freqeuncy out of range.') end % process multiple datasets % ------------------------- if length(EEG) > 1 [ EEG command ] = eeg_eval( 'pop_resample', EEG, 'warning', 'on', 'params', { freq } ); return; end; % finding the best ratio % [p,q] = rat(freq/EEG.srate, 0.0001) % not used right now [p,q] = rat(freq/EEG.srate, 1e-12); % used! AW % set variable % ------------ EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts, EEG.trials); oldpnts = EEG.pnts; % resample for multiple channels % ------------------------- if isfield(EEG, 'event') & isfield(EEG.event, 'type') & isstr(EEG.event(1).type) tmpevent = EEG.event; bounds = strmatch('boundary', { tmpevent.type }); if ~isempty(bounds), disp('Data break detected and taken into account for resampling'); bounds = [ tmpevent(bounds).latency ]; bounds(bounds <= 0 | bounds > size(EEG.data,2)) = []; % Remove out of range boundaries bounds(mod(bounds, 1) ~= 0) = round(bounds(mod(bounds, 1) ~= 0) + 0.5); % Round non-integer boundary latencies end; bounds = [1 bounds size(EEG.data, 2) + 1]; % Add initial and final boundary event bounds = unique(bounds); % Sort (!) and remove doublets else bounds = [1 size(EEG.data,2) + 1]; % [1:size(EEG.data,2):size(EEG.data,2)*size(EEG.data,3)+1]; end; eeglab_options; if option_donotusetoolboxes usesigproc = 0; elseif exist('resample') == 2 usesigproc = 1; else usesigproc = 0; disp('Signal Processing Toolbox absent: using custom interpolation instead of resample() function.'); disp('This method uses cubic spline interpolation after anti-aliasing (see >> help spline)'); end; fprintf('resampling data %3.4f Hz\n', EEG.srate*p/q); eeglab_options; for index1 = 1:size(EEG.data,1) fprintf('%d ', index1); sigtmp = reshape(EEG.data(index1,:, :), oldpnts, EEG.trials); if index1 == 1 tmpres = []; indices = [1]; for ind = 1:length(bounds)-1 tmpres = [ tmpres; myresample( double( sigtmp(bounds(ind):bounds(ind+1)-1,:)), p, q, usesigproc, fc, df ) ]; indices = [ indices size(tmpres,1)+1 ]; end; if size(tmpres,1) == 1, EEG.pnts = size(tmpres,2); else EEG.pnts = size(tmpres,1); end; if option_memmapdata == 1 tmpeeglab = mmo([], [EEG.nbchan, EEG.pnts, EEG.trials]); else tmpeeglab = zeros(EEG.nbchan, EEG.pnts, EEG.trials); end; else for ind = 1:length(bounds)-1 tmpres(indices(ind):indices(ind+1)-1,:) = myresample( double( sigtmp(bounds(ind):bounds(ind+1)-1,:) ), p, q, usesigproc, fc, df); end; end; tmpeeglab(index1,:, :) = tmpres; end; fprintf('\n'); EEG.srate = EEG.srate*p/q; EEG.data = tmpeeglab; EEG.pnts = size(EEG.data,2); EEG.xmax = EEG.xmin + (EEG.pnts-1)/EEG.srate; % cko: recompute xmax, since we may have removed a few of the trailing samples EEG.times = linspace(EEG.xmin*1000, EEG.xmax*1000, EEG.pnts); % recompute all event latencies % ----------------------------- if isfield(EEG.event, 'latency') fprintf('resampling event latencies...\n'); if EEG.trials > 1 % Epoched data; not recommended warning( 'Resampling of epoched data is not recommended (due to anti-aliasing filtering)! Note: For epoched datasets recomputing urevent latencies is not supported. The urevent structure will be cleared.' ) for iEvt = 1:length( EEG.event ) EEG.event( iEvt ).latency = ( EEG.event( iEvt ).latency - ( EEG.event(iEvt).epoch - 1 ) * oldpnts - 1 ) * p / q + ( EEG.event(iEvt).epoch - 1 ) * EEG.pnts + 1; end EEG.urevent = []; else % Continuous data for iEvt = 1:length(EEG.event) % From >> help resample: Y is P/Q times the length of X (or the % ceiling of this if P/Q is not an integer). % That is, recomputing event latency by pnts / oldpnts will give % inaccurate results in case of multiple segments and rounded segment % length. Error is accumulated and can lead to several samples offset. % Blocker for boundary events. % Old version EEG.event(index1).latency = EEG.event(index1).latency * EEG.pnts /oldpnts; % Recompute event latencies relative to segment onset if strcmpi(EEG.event(iEvt).type, 'boundary') && mod(EEG.event(iEvt).latency, 1) == 0.5 % Workaround to keep EEGLAB style boundary events at -0.5 latency relative to DC event; actually incorrect iBnd = sum(EEG.event(iEvt).latency + 0.5 >= bounds); EEG.event(iEvt).latency = indices(iBnd) - 0.5; else iBnd = sum(EEG.event(iEvt).latency >= bounds); EEG.event(iEvt).latency = (EEG.event(iEvt).latency - bounds(iBnd)) * p / q + indices(iBnd); end end if isfield(EEG, 'urevent') & isfield(EEG.urevent, 'latency') try for iUrevt = 1:length(EEG.urevent) % Recompute urevent latencies relative to segment onset if strcmpi(EEG.urevent(iUrevt).type, 'boundary') && mod(EEG.urevent(iUrevt).latency, 1) == 0.5 % Workaround to keep EEGLAB style boundary events at -0.5 latency relative to DC event; actually incorrect iBnd = sum(EEG.urevent(iUrevt).latency + 0.5 >= bounds); EEG.urevent(iUrevt).latency = indices(iBnd) - 0.5; else iBnd = sum(EEG.urevent(iUrevt).latency >= bounds); EEG.urevent(iUrevt).latency = (EEG.urevent(iUrevt).latency - bounds(iBnd)) * p / q + indices(iBnd); end end; catch disp('pop_resample warning: ''urevent'' problem, reinitializing urevents'); EEG = rmfield(EEG, 'urevent'); end; end; end EEG = eeg_checkset(EEG, 'eventconsistency'); end; % resample for multiple channels ica EEG.icaact = []; % store dataset fprintf('resampling finished\n'); EEG.setname = [EEG.setname ' resampled']; command = sprintf('EEG = pop_resample( %s, %d);', inputname(1), freq); return; % resample if resample is not present % ----------------------------------- function tmpeeglab = myresample(data, p, q, usesigproc, fc, df) if length(data) < 2 tmpeeglab = data; return; end; %if size(data,2) == 1, data = data'; end; if usesigproc % padding to avoid artifacts at the beginning and at the end % Andreas Widmann May 5, 2011 %The pop_resample command introduces substantial artifacts at beginning and end %of data when raw data show DC offset (e.g. as in DC recorded continuous files) %when MATLAB Signal Processing Toolbox is present (and MATLAB resample.m command %is used). %Even if this artifact is short, it is a filtered DC offset and will be carried %into data, e.g. by later highpass filtering to a substantial amount (easily up %to several seconds). %The problem can be solved by padding the data at beginning and end by a DC %constant before resampling. % N = 10; % Resample default % nPad = ceil((max(p, q) * N) / q) * q; % # datapoints to pad, round to integer multiple of q for unpadding % tmpeeglab = resample([data(ones(1, nPad), :); data; data(end * ones(1, nPad), :)], pnts, new_pnts); % Conservative custom anti-aliasing FIR filter, see bug 1757 nyq = 1 / max([p q]); fc = fc * nyq; % Anti-aliasing filter cutoff frequency df = df * nyq; % Anti-aliasing filter transition band width m = pop_firwsord('kaiser', 2, df, 0.002); % Anti-aliasing filter kernel b = firws(m, fc, windows('kaiser', m + 1, 5)); % Anti-aliasing filter kernel b = p * b; % Normalize filter kernel to inserted zeros % figure; freqz(b, 1, 2^14, q * 1000) % Debugging only! Sampling rate hardcoded as it is unknown in this context. Manually adjust for debugging! % Padding, see bug 1017 nPad = ceil((m / 2) / q) * q; % Datapoints to pad, round to integer multiple of q for unpadding startPad = repmat(data(1, :), [nPad 1]); endPad = repmat(data(end, :), [nPad 1]); % Resampling tmpeeglab = resample([startPad; data; endPad], p, q, b); % Remove padding nPad = nPad * p / q; % # datapoints to unpad tmpeeglab = tmpeeglab(nPad + 1:end - nPad, :); % Remove padded data else % No Signal Processing toolbox % anti-alias filter % ----------------- % data = eegfiltfft(data', 256, 0, 128*pnts/new_pnts); % Downsample from 256 to 128 times the ratio of freq. % % Code was verified by Andreas Widdman March 2014 % % No! Only cutoff frequency for downsampling was confirmed. % % Upsampling doesn't work and FFT filtering introduces artifacts. % % Also see bug 1757. Replaced May 05, 2015, AW if p < q, nyq = p / q; else nyq = q / p; end fc = fc * nyq; % Anti-aliasing filter cutoff frequency df = df * nyq; % Anti-aliasing filter transition band width m = pop_firwsord('kaiser', 2, df, 0.002); % Anti-aliasing filter kernel b = firws(m, fc, windows('kaiser', m + 1, 5)); % Anti-aliasing filter kernel % figure; freqz(b, 1, 2^14, 1000) % Debugging only! Sampling rate hardcoded as it is unknown in this context. Manually adjust for debugging! if p < q % Downsampling, anti-aliasing filter data = firfiltdcpadded(b, data, 0); end % spline interpolation % -------------------- % X = [1:length(data)]; % nbnewpoints = length(data)*p/q; % nbnewpoints2 = ceil(nbnewpoints); % lastpointval = length(data)/nbnewpoints*nbnewpoints2; % XX = linspace( 1, lastpointval, nbnewpoints2); % New time axis scaling, May 06, 2015, AW X = 0:length(data) - 1; newpnts = ceil(length(data) * p / q); XX = (0:newpnts - 1) / (p / q); cs = spline( X, data); tmpeeglab = ppval(cs, XX)'; if p > q % Upsampling, anti-imaging filter tmpeeglab = firfiltdcpadded(b, tmpeeglab, 0); end end
github
lcnhappe/happe-master
eeg_eventformat.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_eventformat.m
3,014
utf_8
d06b550e78556cb151a924c2b32b19f9
% eeg_eventformat() - Convert the event information of a dataset from struct % to array or vice versa. % % Usage: >> [eventout fields] = eeg_eventformat( event, 'format', fields ); % % Inputs: % event - event array or structure % format - ['struct'|'array'] see below % fields - [optional] cell array of strings containing the names of % the event struct fields. If this field is empty, it uses % the following list for % the names of the fields { 'type' 'latency' 'var1' ... % 'var2' ... }. % Output: % eventout - output event array or structure % fields - output cell array with the name of the fields % % Event formats: % struct - Events are organised as an array of structs with at % least two fields ('type' and 'latency') % (Ex: reaction_time may be type 1). % array - events are organized as an array, the first column % representing the type, the second the latency and the % other ones user-defined variables. % % Note: 1) The event structure is defined only for continuous data % or epoched data derived from continuous data. % 2) The event 'struct' format is more comprehensible. % For instance, to see all the properties of event 7, % type >> EEG.event(7) % Unfortunately, structures are awkward for expert users to deal % with from the command line (Ex: To get an array of latencies, % >> [ EEG.event(:).latency ] ) % In array format, the same information is obtained by typing % >> EEG.event(:,2) % 3) This function automatically updates the 'eventfield' % cell array depending on the format. % % Author: Arnaud Delorme, CNL / Salk Institute, 27 Jan 2002 % % See also: eeglab(), pop_selectevent(), pop_importevent() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 27 Jan 2002, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 2/06/02 modifed header - sm & ad % 2/08/02 add field input - ad % 2/12/02 reprogrammed function using epochformat.m - ad function [event, eventfield] = eeg_eventformat(event, format, fields); if nargin < 2 help eeg_eventformat; return; end; if exist('fields') ~= 1, fields = { 'type', 'latency' }; end; [event eventfield] = eeg_epochformat( event, format, fields);
github
lcnhappe/happe-master
pop_newset.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_newset.m
27,050
utf_8
beafde40b79628c3a9ebfcfecb56c54e
% pop_newset() - Edit/save EEG dataset structure information. % % Usage: % >> [ALLEEG EEG CURRENTSET] = pop_newset( ALLEEG, EEG, CURRENTSET,... % 'key', val,...); % Inputs and outputs: % ALLEEG - array of EEG dataset structures % EEG - current dataset structure or structure array % CURRENTSET - index(s) of the current EEG dataset(s) in ALLEEG % % Optional inputs: % 'setname' - ['string'] name for the new dataset % 'comments' - ['string'] comments on the new dataset % 'overwrite' - ['on'|'off'] overwrite the old dataset % 'saveold' - ['filename'] filename in which to save the old dataset % 'savenew' - ['filename'] filename in which to save the new dataset % 'retrieve' - [index] retrieve the old dataset (ignore recent changes) % % Note: Calls eeg_store() which may modify the variable ALLEEG % containing the current dataset(s). % % Author: Arnaud Delorme, CNL / Salk Institute, 23 Arpil 2002 % % See also: eeg_store(), pop_editset(), eeglab() % Copyright (C) 23 Arpil 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 'aboutparent' - ['on'|'off'] insert reference to parent dataset in the comments % testing: both options must be tested with datasets that have 2 % files (.set and .dat) and with dataset using a single file % % Option when only one dataset is kept in memory % % *********** When STUDY present *********** % Study selected -> select single dataset % Study selected -> select multiple datasets % Several dataset selected -> select single dataset % Several dataset selected -> select other several datasets % Several dataset selected -> select study % Dataset (not modified) selected -> select study % Dataset (not modified) selected -> select multiple datasets % Dataset (not modified) selected -> select other single dataset % Dataset (not modified) selected -> create new dataset (eg. resample) % Dataset (modified) selected -> select study % Dataset (modified) selected -> select multiple datasets % Dataset (modified) selected -> select other single dataset % Dataset (modified) selected -> create new dataset (eg. resample) % *********** When study absent ************ % Several dataset selected -> select single dataset % Several dataset selected -> select other several datasets % Dataset (not modified) selected -> select multiple datasets % Dataset (not modified) selected -> select other single dataset % Dataset (not modified) selected -> create new dataset (eg. resample) % Dataset (modified) selected -> select multiple datasets % Dataset (modified) selected -> select other single dataset % Dataset (modified) selected -> create new dataset (eg. resample) % % Option when several datasets can be kept in memory % % *********** When STUDY present *********** % Study selected -> select single dataset % Study selected -> select multiple datasets % Several dataset selected -> select single dataset % Several dataset selected -> select other several datasets % Several dataset selected -> select study % Dataset (not modified) selected -> select study % Dataset (not modified) selected -> select multiple datasets % Dataset (not modified) selected -> select other single dataset % Dataset (not modified) selected -> create new dataset (eg. resample) % Dataset (modified) selected -> select study % Dataset (modified) selected -> select multiple datasets % Dataset (modified) selected -> select other single dataset % Dataset (modified) selected -> create new dataset (eg. resample) % *********** When study absent ************ % Several dataset selected -> select single dataset % Several dataset selected -> select other several datasets % Dataset (not modified) selected -> select multiple datasets % Dataset (not modified) selected -> select other single dataset % Dataset (not modified) selected -> create new dataset (eg. resample) % Dataset (modified) selected -> select multiple datasets % Dataset (modified) selected -> select other single dataset % Dataset (modified) selected -> create new dataset (eg. resample) function [ALLEEG, EEG, CURRENTSET, com] = pop_newset( ALLEEG, EEG, OLDSET, varargin); % pop_newset( ALLEEG, EEG, 1, 'retrieve', [], 'study', [1] (retreiving a study) verbose = 0; if nargin < 3 help pop_newset; return; end; CURRENTSET = OLDSET; com = sprintf('[ALLEEG EEG CURRENTSET] = pop_newset(ALLEEG, EEG, %s); ', vararg2str( { OLDSET varargin{:} } )); [g varargin] = finputcheck(varargin, { ... 'gui' 'string' { 'on';'off' } 'on'; % []=none; can be multiple numbers 'retrieve' 'integer' [] []; % []=none; can be multiple numbers 'study' 'integer' [0 1] 0; % important because change behavior for modified datasets }, 'pop_newset', 'ignore'); if isstr(g), error(g); end; eeglab_options; if length(EEG) > 1 % *************************************************** % case 1 -> multiple datasets in memory (none has to be saved), retrieving single dataset % *************************************************** if ~isempty(g.retrieve) [EEG, ALLEEG, CURRENTSET] = eeg_retrieve( ALLEEG, g.retrieve); elseif length(OLDSET) == length(EEG) % *************************************************** % case 2 -> multiple datasets processed, storing them % *************************************************** [ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, OLDSET); else % *************************************************** % case 3 -> multiple datasets processed, storing new copies (not used in EEGLAB) % *************************************************** if strcmpi(EEG(1).saved, 'justloaded') for ieeg = 1:length(EEG) [ALLEEG TMP OLDSET] = pop_newset(ALLEEG, EEG(ieeg), OLDSET); end; CURRENTSET = OLDSET; EEG = TMP; else [ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG); end; end; return; elseif ~isempty(g.retrieve) % command line call % *************************************************** % case 4 -> single dataset, does not have to be saved, % retrieving another dataset % *************************************************** if verbose, disp('Case 4'); end; if ~(option_storedisk & strcmpi(EEG.saved, 'no')) if strcmpi(EEG.saved, 'yes') & option_storedisk fprintf('pop_newset(): Dataset %d has not been modified since last save, so did not resave it.\n', OLDSET); EEG = update_datafield(EEG); tmpsave = EEG.saved; EEG = eeg_hist(EEG, com); [ALLEEG EEG] = eeg_store(ALLEEG, EEG, OLDSET); EEG.saved = tmpsave; % eeg_store automatically set it to 'no' ALLEEG(OLDSET).saved = tmpsave; end; if ~isempty(g.retrieve) [EEG, ALLEEG, CURRENTSET] = eeg_retrieve( ALLEEG, g.retrieve); end; return; end; end; if isempty(EEG) args = { 'retrieve', OLDSET }; % cancel elseif length(varargin) == 0 & length(EEG) == 1 & strcmpi(g.gui, 'on') % if several arguments, assign values % popup window parameters % ----------------------- text_new = 'What do you want to do with the new dataset?'; comcomment = ['tmpuserdat = get(gcbf, ''userdata'');' ... 'tmpuserdat = pop_comments(tmpuserdat, ''Edit dataset comments'');' ... 'set(gcbf, ''userdata'', tmpuserdat); clear tmpuserdat;']; comsavenew = ['[tmpfile tmppath] = uiputfile(''*.set'', ''Enter filename''); drawnow;' ... 'if tmpfile ~= 0,' ... ' set(findobj(''parent'', gcbf, ''tag'', ''filenamenew''), ''string'', fullfile(tmppath, tmpfile));' ... 'end;' ... 'clear tmpuserdat tmpfile tmppath;']; cb_savenew = [ 'set(findobj(gcbf, ''userdata'', ''filenamenew''), ''enable'', fastif(get(gcbo, ''value''), ''on'', ''off''));' ]; cb_saveold = [ 'set(findobj(gcbf, ''userdata'', ''filenameold''), ''enable'', fastif(get(gcbo, ''value''), ''on'', ''off''));' ]; comsaveold = ['[tmpfile tmppath] = uiputfile(''*.set'', ''Enter filename''); drawnow;' ... 'if tmpfile ~= 0,' ... ' set(findobj(''parent'', gcbf, ''tag'', ''filenameold''), ''string'', fullfile(tmppath, tmpfile));' ... 'end;' ... 'clear tmpuserdat tmpfile tmppath;']; enable_saveold = 'off'; enable_savenew = 'off'; value_saveold = 0; value_savenew = 0; value_owrt = 0; cb_owrt = ''; userdat = EEG.comments; % status of parent dataset etc... saved = 1; filenameold = ''; filenamenew = ''; if ~isempty(ALLEEG) & any(OLDSET ~= 0) & length(OLDSET) == 1 if strcmpi(ALLEEG(OLDSET).saved, 'no') saved = 0; if ~isempty(ALLEEG(OLDSET).filename) filenameold = fullfile(ALLEEG(OLDSET).filepath, ALLEEG(OLDSET).filename); end; end; end; overwrite_or_save = 0; have_to_save_new = 0; % *************************************************** % case 5 -> single dataset, has to be saved, one dataset to retreive and study present or several dataset to retrieve % *************************************************** if length(g.retrieve) > 1 | ( g.study & ~isempty(g.retrieve)) % selecting several datasets or a study is present if verbose, disp('Case 5'); end; text_new = 'Current dataset has not been saved. Saved it or reload it from disk.'; text_old = ''; have_to_save_new = 1; value_savenew = 1; enable_savenew = 'on'; filenamenew = fullfile(EEG.filepath, EEG.filename); cb_savenew = [ 'if ~get(gcbo, ''value'') & ~get(findobj(gcbf, ''tag'', ''cb_loadold''), ''value''),' ... ' set(gcbo, ''value'', 1);' ... ' warndlg2(strvcat(''You must enter a filename for the dataset or use the copy on disk!'','' '',' ... ' ''It must be saved or you must use the old dataset on disk because, by your current memory'',' ... ' ''option, only one full dataset or study can be kept in memory. Note that if you choose to'',' ... ' ''save the dataset, this will be taken into account in the study.''));' ... 'else, ' cb_savenew ... 'end;' ]; % *************************************************** % case 6 -> single dataset modified or not, study is present (the old % dataset has to be replaced to preserve study consistency) % *************************************************** elseif g.study == 1 & isempty(g.retrieve) if verbose, disp('Case 6'); end; if saved text_old = 'The old dataset has not been modified since last saved. What do you want to do with it?'; cb_saveold = ''; else text_old = 'Some changes have not been saved. What do you want to do with the old dataset?'; end; cb_owrt = [ ... ' set(gcbo, ''value'', 1);' ... ' warndlg2(strvcat(''Cannot unset the overwrite checkbox!'','' '',' ... '''The old dataset must be overwriten since all datasets'',' ... '''must be in the STUDY.''), ''warning'');' ]; value_owrt = 1; filenamenew = fullfile(EEG.filepath, EEG.filename); % *************************************************** % case 7 -> single dataset modified, study is absent, old copy has to % be flush to disk or overwritten % *************************************************** elseif ~saved & option_storedisk if verbose, disp('Case 7'); end; text_old = 'Some changes have not been saved. What do you want to do with the old dataset?'; cb_saveold = [ 'if ~get(findobj(gcbf, ''tag'', ''cb_owrt''), ''value''),' ... ' set(gcbo, ''value'', 1);' ... ' warndlg2(strvcat(''Cannot unset the save checkbox!'','' '',' ... '''By your selected memory option, only one full dataset'',' ... '''can be kept in memory. Thus, you must either'',' ... '''save or delete/overwrite the old dataset.''));' ... 'else, ' cb_saveold ... 'end;' ]; cb_owrt = [ 'if ~get(findobj(gcbf, ''tag'', ''cb_saveold''), ''value''),' ... ' set(gcbo, ''value'', 1);' ... ' warndlg2(strvcat(''Cannot unset the overwrite checkbox!'','' '',' ... '''By your memory option, only one full dataset'',' ... '''can be kept in memory. Thus, you must either'',' ... '''save or delete/overwrite the old dataset.''));' ... 'end;' ]; enable_saveold = 'on'; value_saveold = 1; overwrite_or_save = 1; elseif ~saved % *************************************************** % case 8 -> single dataset modified, study is absent, no constraint on saving % *************************************************** if verbose, disp('Case 8'); end; text_old = 'Some changes have not been saved. What do you want to do with the old dataset?'; else % *************************************************** % case 9 -> single dataset not modified, study is absent, no constraint on saving % *************************************************** if verbose, disp('Case 9'); end; text_old = 'What do you want to do with the old dataset (not modified since last saved)?'; cb_saveold = ''; cb_overwrite = 'Overwrite current dataset|New dataset'; end; geometry = { [1] [0.15 0.5 1 0.5] [0.15 0.5 1 0.5] [1] [1] [0.15 1.8 0.1 0.1] [0.15 0.5 1 0.5] }; geomvert = [ ]; uilist = { ... { 'style', 'text', 'string', text_new, 'fontweight', 'bold' } ... {} ... { 'Style', 'text', 'string', 'Name it:' } ... { 'Style', 'edit', 'string', EEG.setname 'tag' 'namenew' } ... { 'Style', 'pushbutton', 'string', 'Edit description', 'callback', comcomment } ... { 'Style', 'checkbox' , 'string', '', 'callback', cb_savenew 'value' value_savenew 'tag' 'cb_savenew' } ... { 'Style', 'text', 'string', 'Save it as file:' } ... { 'Style', 'edit', 'string', filenamenew, 'tag', 'filenamenew' 'userdata' 'filenamenew' 'enable' enable_savenew } ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', comsavenew 'userdata' 'filenamenew' 'enable' enable_savenew } ... { } ... { 'style', 'text', 'string', text_old 'fontweight' 'bold' } ... { 'Style', 'checkbox' , 'string', '' 'tag' 'cb_owrt' 'callback' cb_owrt 'value' value_owrt } ... { 'Style', 'text' , 'string', 'Overwrite it in memory (set=yes; unset=create a new dataset)' } {} ... { } ... { 'Style', 'checkbox' , 'string', '', 'callback', cb_saveold 'value' value_saveold 'tag' 'cb_saveold' } ... { 'Style', 'text' , 'string', 'Save it as file:' } ... { 'Style', 'edit' , 'string', filenameold, 'tag', 'filenameold' 'userdata' 'filenameold' 'enable' enable_saveold } ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', comsaveold 'userdata' 'filenameold' 'enable' enable_saveold } }; % remove old dataset if not present % --------------------------------- if OLDSET == 0 uilist = uilist(1:9); geometry = geometry(1:3); end; if isempty(cb_saveold) uilist(end-3:end) = []; geometry(end) = []; end; % update GUI for selecting multiple datasets % ------------------------------------------ if length(g.retrieve) > 1 | ( g.study & ~isempty(g.retrieve)) % selecting several datasets or a study is present uilist = uilist(1:9); geometry = geometry(1:3); if ~isempty(EEG.filename) cb_loadold = [ 'if ~get(gcbo, ''value'') & ~get(findobj(gcbf, ''tag'', ''cb_savenew''), ''value''),' ... ' set(gcbo, ''value'', 1);' ... ' warndlg2(strvcat(''You must enter a filename for the dataset or use the copy on disk!'','' '',' ... ' ''It must be saved or you must use the old dataset on disk because, by your current memory option, only one full'',' ... ' ''dataset or study can be kept in memory. This will also affect the'',' ... ' ''dataset at this position in the study.''));' ... 'end;' ]; uilist{end+1} = { 'Style', 'checkbox' , 'string', '', 'callback', cb_loadold 'tag' 'cb_loadold' }; uilist{end+1} = { 'Style', 'text', 'string', 'Reload copy from disk (will be done after optional saving above)' }; uilist{end+1} = {}; uilist{end+1} = {}; geometry = { geometry{:} [0.12 1.6 0.2 0.2] }; end; end; % remove new dataset if already saved % ----------------------------------- if ~isfield(EEG, 'saved') EEG = eeg_checkset(EEG); end; if strcmpi(EEG.saved, 'justloaded') | ~isempty(g.retrieve) if overwrite_or_save % only pop-up a window if some action has to be taken uilist = uilist(11:end); geometry = geometry(5:end); uilist(3) = {{ 'Style', 'text' , 'string', 'Delete it from memory (set=yes)' }}; elseif isempty(g.retrieve) % just loaded from disk % remove data from file for old dataset % ------------------------------------- if option_storedisk & ~isempty(ALLEEG) & OLDSET ~= 0 if ~isfield(ALLEEG(OLDSET), 'datfile'), ALLEEG(OLDSET).datfile = ''; end; ALLEEG(OLDSET) = update_datafield(ALLEEG(OLDSET)); end; [ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG, 0); % 0 means that it is saved on disk com = '[ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG, 0 );'; return; end; end; % show GUI (do not return if old dataset has to be saved or overwritten) % ---------------------------------------------------------------------- cont = 1; while cont [result userdat tmp tags] = inputgui( 'geometry', geometry, 'uilist', uilist, 'helpcom', 'pophelp(''pop_newset'');', ... 'title', 'Dataset info -- pop_newset()', ... 'userdata', userdat, 'geomvert', geomvert); try, tags.cb_owrt; catch, tags.cb_owrt = 0; end; try, tags.cb_savenew; catch, tags.cb_savenew = 0; end; try, tags.cb_saveold; catch, tags.cb_saveold = 0; end; try, tags.cb_loadold; catch, tags.cb_loadold = 0; end; try, tags.namenew; catch, tags.namenew = EEG.setname; end; try, tags.filenamenew; catch, tags.filenamenew = ''; end; cont = 0; if ~isempty(result) if overwrite_or_save & tags.cb_saveold % save but not overwrite if isempty(tags.filenameold) warndlg2(strvcat('Error: You must enter a filename for the old dataset!',' ', ... 'The old dataset must be saved because, by your', ... 'current memory option, only one full dataset', ... 'can be kept in memory. Thus, you must either', ... 'save or overwrite the old dataset.')); cont = 1; end; end; end; if have_to_save_new if isempty(result) % cancel com = ''; drawnow; return; else if isempty(tags.filenamenew) & tags.cb_savenew warndlg2(strvcat('Error: You must enter a filename for the dataset!',' ', ... 'It must be saved because, by your current memory option, only one full', ... 'dataset or study can be kept in memory. Note that all changes will be', ... 'taken into account when processing the STUDY.')); cont = 1; end; end; end; end; drawnow; % decode parameters % ----------------- args = {}; if length(result) == 0, if isempty(g.retrieve) if isempty(OLDSET), error('Cancel operation'); end; args = { 'retrieve', OLDSET }; % cancel else com = ''; return; end; else % new dataset % ----------- if ~strcmp(EEG.setname, tags.namenew ) args = { 'setname', tags.namenew }; end; if tags.cb_savenew if ~isempty(tags.filenamenew) args = { args{:} 'savenew', tags.filenamenew }; else disp('Warning: no filename given for new dataset, so it will not be saved to disk.'); end; end; if ~strcmp(EEG.comments, userdat) args = { args{:} 'comments', userdat }; end; if tags.cb_loadold args = { args{:} 'reload' 'on' }; end; % old dataset % ----------- if tags.cb_owrt args = { args{:} 'overwrite' 'on' }; end; if tags.cb_saveold if ~isempty(tags.filenameold) args = { args{:} 'saveold', tags.filenameold }; else disp('Warning: no file name given for the old dataset, so it will not be saved to disk.'); end; end; end; elseif length(EEG) > 1 % processing multiple datasets % ---------------------------- [ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG, OLDSET ); % it is possible to undo the operation here com = '[ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG, CURRENTSET );'; return; else % no interactive inputs args = varargin; end; % assigning values % ---------------- overWflag = 0; if isempty(g.retrieve) & ~isempty(EEG) if strcmpi(EEG.saved, 'justloaded') EEG.saved = 'yes'; else EEG.saved = 'no'; end; end; for ind = 1:2:length(args) switch lower(args{ind}) case 'setname' , EEG.setname = args{ind+1}; EEG = eeg_hist(EEG, [ 'EEG.setname=''' EEG.setname ''';' ]); case 'comments' , EEG.comments = args{ind+1}; case 'reload' , EEG = pop_loadset('filename', EEG.filename, 'filepath', EEG.filepath, 'loadmode', 'info'); [ALLEEG EEG] = eeg_store(ALLEEG, EEG, OLDSET); ALLEEG(OLDSET).saved = 'yes'; case 'retrieve' , if ~isempty(ALLEEG) & args{ind+1} ~= 0 EEG = eeg_retrieve(ALLEEG, args{ind+1}); else EEG = eeg_emptyset; end; com = ''; return; case { 'save' 'savenew' }, [filepath filename ext] = fileparts( args{ind+1} ); EEG = pop_saveset(EEG, [ filename ext ], filepath); case 'saveold', [filepath filename ext] = fileparts( args{ind+1} ); TMPEEG = pop_saveset(ALLEEG(OLDSET), [ filename ext ], filepath); [ALLEEG] = eeg_store(ALLEEG, TMPEEG, OLDSET); ALLEEG(OLDSET).saved = 'yes'; case 'overwrite' , if strcmpi(args{ind+1}, 'on') | strcmpi(args{ind+1}, 'yes') overWflag = 1; % so it can be done at the end end; otherwise, error(['pop_newset error: unrecognized key ''' args{ind} '''']); end; end; % remove data from file if necessary % ---------------------------------- if option_storedisk & ~isempty(ALLEEG) & OLDSET ~= 0 if ~isfield(ALLEEG, 'datfile'), ALLEEG(OLDSET).datfile = ''; end; ALLEEG(OLDSET) = update_datafield(ALLEEG(OLDSET)); end; % moving/erasing/creating datasets % -------------------------------- if ~isempty(g.retrieve) % in case the old dataset was modified % ------------------------------------ if strcmpi(EEG.saved, 'yes') [ALLEEG, EEG] = eeg_store( ALLEEG, EEG, OLDSET); ALLEEG(OLDSET).saved = 'yes'; EEG.saved = 'yes'; else [ALLEEG, EEG] = eeg_store( ALLEEG, EEG, OLDSET); end; % dataset retrieval % ----------------- if overWflag % delete old dataset ALLEEG = pop_delset( ALLEEG, OLDSET); end; [EEG, ALLEEG, CURRENTSET] = eeg_retrieve( ALLEEG, g.retrieve); else % new dataset % ----------- if overWflag if strcmpi(EEG.saved, 'yes') [ALLEEG, EEG] = eeg_store( ALLEEG, EEG, OLDSET); ALLEEG(OLDSET).saved = 'yes'; EEG.saved = 'yes'; else [ALLEEG, EEG] = eeg_store( ALLEEG, EEG, OLDSET); end; else if strcmpi(EEG.saved, 'yes') || strcmpi(EEG.saved, 'justloaded') [ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG, 0); % 0 means that it is saved on disk else [ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG); end; end; end; com = sprintf('[ALLEEG EEG CURRENTSET] = pop_newset(ALLEEG, EEG, %s); ', vararg2str( { OLDSET args{:} 'gui' 'off' } )); return; function num = popask( text ) ButtonName=questdlg2( text, ... 'Confirmation', 'Cancel', 'Yes','Yes'); switch lower(ButtonName), case 'cancel', num = 0; case 'yes', num = 1; end; function EEG = update_datafield(EEG); if ~isfield(EEG, 'datfile'), EEG.datfile = ''; end; if ~isempty(EEG.datfile) EEG.data = EEG.datfile; else EEG.data = 'in set file'; end; EEG.icaact = [];
github
lcnhappe/happe-master
pop_runscript.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_runscript.m
1,350
utf_8
e17c0b67edb0127bc40e128e564bcb2c
% pop_runscript() - Run Matlab script % % Usage: >> pop_runscript; % >> pop_runscript( filename ); % % Input: % filename - [string] name of the file. % % Author: Arnaud Delorme, SCCN / INC / UCSD, August 2009 % Copyright (C) Arnaud Delorme, August 2009 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function com = pop_runscript(filename); com = []; if nargin <1 [filename filepath] = uigetfile('*.*', 'Please select input script -- pop_runscript()'); if filename(1) == 0, return; end; filename = fullfile(filepath, filename); end; str = readtxtfile(filename); try evalin('base', str); catch lasterr end; com = sprintf('pop_runscript(''%s'');', filename);
github
lcnhappe/happe-master
pop_headplot.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_headplot.m
24,855
utf_8
67799c05e8a34f7685af4a550b6f3f80
% pop_headplot() - plot one or more spherically-splined EEG field maps % using a semi-realistic 3-D head model. Requires a % spline file, which is created first if not found. % This may take some time, but does not need to be % done again for this channel locations montage. A wait % bar will pop up to indicate how much time remains. % Usage: % To open input GUI: % >> EEGOUT = pop_headplot( EEG, typeplot) % To run as a script without further GUI input: % >> EEGOUT = pop_headplot( EEG, typeplot, ... % latencies/components, title, rowscols, 'key', 'val' ...); % Required Inputs: % EEG - EEG dataset structure % typeplot - 1=channel, 0=component {Default: 1} % % Required Inputs to bypass input GUI % latencies/components - If channels, array of epoch mean latencies (in ms), % Else, for components, array of component indices to plot. % % Optional inputs: % title - Plot title % rowscols - Vector of the form [m,n] where m is total vertical tiles and n % horizontal tiles per page. If the number of maps exceeds m*n, % multiple figures will be produced {def|0 -> 1 near-square page} % % Optional 'Key' 'Value' Paired Inputs % 'setup' - ['name_of_file_to_save.spl'] Make the headplot spline file % 'load' - ['name_of_file_to_load.spl'] Load the headplot spline file % 'colorbar' - ['on' or 'off'] Switch to turn colorbar on or off. {Default: 'on'} % others... - All other key-val calls are passed directly to headplot. % See >> help headplot % % Output: % EEGOUT - EEG dataset, possibly with a new or modified splinefile. % % Note: % A new figure is created only when the pop_up window is called or when % several channels/components are plotted. Therefore you may call this % command to draw single 3-D topographic maps in an existing figure. % % Headplot spline file is a matlab .mat file with the extension .spl. % % Author: Arnaud Delorme, CNL / Salk Institute, 20 March 2002 % % See also: headplot(), eegplot(), traditional() % Copyright (C) 20 March 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, com] = pop_headplot( EEG, typeplot, arg2, topotitle, rowcols, varargin); com = ''; if nargin < 1 help pop_headplot; return; end; if isempty(EEG.chanlocs) error('Pop_headplot: this dataset does not contain channel locations. Use menu item: Edit > Dataset info'); end; if nargin < 3 % Open GUI input window % remove old spline file % ---------------------- if isfield(EEG, 'splinefile') if ~isempty(EEG.splinefile) && exist(EEG.splinefile, 'file') splfile = dir(EEG.splinefile); byteperelec = splfile.bytes/EEG.nbchan; if byteperelec/EEG.nbchan < 625, % old head plot file EEG.splinefile = []; disp('Warning: Wrong montage or old-version spline file version detected and removed; new spline file required'); end; end; end; % show the file be recomputed % --------------------------- compute_file = 0; if typeplot == 1 % ********** data plot fieldname = 'splinefile'; if isempty(EEG.splinefile) && exist(EEG.splinefile, 'file') if length(EEG.icachansind) == EEG.nbchan & ~isempty(EEG.icasplinefile) EEG.splinefile = EEG.icasplinefile; else compute_file = 1; end; else compute_file = 1; end; else % ************* Component plot fieldname = 'icasplinefile'; if isempty(EEG.icasplinefile) && exist(EEG.icasplinefile, 'file') if length(EEG.icachansind) == EEG.nbchan & ~isempty(EEG.splinefile) EEG.icasplinefile = EEG.splinefile; else compute_file = 1; end; else compute_file = 1; end; end; if compute_file warndlg2( strvcat('headplot() must generate a spline file the first', ... 'time it is called or after changes in the channel location file.', ... 'You must also co-register your channel locations with the', ... 'head template. Using a standard 10-20 system montage, default', ... 'parameters should allow creating the correct spline file.'), 'Headplot() warning'); else pop_options = {}; end; % graphic interface % ----------------- template(1).keywords = { 'standard-10-5-cap385' }; template(1).transform = [ -0.355789 -6.33688 12.3705 0.0533239 0.0187461 -1.55264 1.06367 0.987721 0.932694 ]; %template(1).transform = [ -0.31937 -5.96928 13.1812 0.0509311 0.0172127 -1.55007 1.08221 1.00037 0.923518 ]; template(2).keywords = { 'standard_1005' }; template(2).transform = [ -1.13598 7.75226 11.4527 -0.0271167 0.0155306 -1.54547 0.912338 0.931611 0.806978 ]; % -0.732155 7.58141 11.8939 -0.0249659 0.0148571 0.0227427 0.932423 0.918943 0.793166 ]; template(3).keywords = { 'gsn' 'sfp' }; %template(3).transform = [ 0 -9 -9 -0.12 0 -1.6 9.7 10.7 11.5 ]; template(3).transform = [ 0.664455 -3.39403 -14.2521 -0.00241453 0.015519 -1.55584 11 10.1455 12]; template(4).keywords = { 'egi' 'elp' }; template(4).transform = [ 0.0773 -5.3235 -14.72 -0.1187 -0.0023 -1.5940 92.4 92.5 110.9 ]; transform = []; if isfield(EEG.chaninfo, 'filename') [tmp transform] = lookupchantemplate(lower(EEG.chaninfo.filename), template); end; if typeplot txt = sprintf('Making headplots for these latencies (from %d to %d ms):', round(EEG.xmin*1000), round(EEG.xmax*1000)); else %txt = ['Component numbers (negate index to invert component polarity):' 10 '(NaN -> empty subplot)(Ex: -1 NaN 3)']; txt = ['Component numbers to plot (negative numbers invert comp. polarities):' ]; end; if compute_file enableload = 'off'; enablecomp = 'on'; else enableload = 'on'; enablecomp = 'off'; end; cb_load = [ 'set(findobj(gcbf, ''tag'', ''load''), ''enable'', ''on'');' ... 'set(findobj(gcbf, ''tag'', ''comp''), ''enable'', ''off'');' ... 'set(findobj(gcbf, ''tag'', ''compcb''), ''value'', 0);' ]; cb_comp = [ 'set(findobj(gcbf, ''tag'', ''load''), ''enable'', ''off'');' ... 'set(findobj(gcbf, ''tag'', ''comp''), ''enable'', ''on'');' ... 'set(findobj(gcbf, ''tag'', ''loadcb''), ''value'', 0);' ]; cb_browseload = [ '[filename, filepath] = uigetfile(''*.spl'', ''Select a spline file'');' ... 'if filename ~=0,' ... ' set(findobj( gcbf, ''userdata'', ''load''), ''string'', fullfile(filepath,filename));' ... 'end;' ... 'clear filename filepath tagtest;' ]; cb_browsecomp = [ '[filename, filepath] = uiputfile(''*.spl'', ''Select a spline file'');' ... 'if filename ~=0,' ... ' set(findobj( gcbf, ''userdata'', ''coregfile''), ''string'', fullfile(filepath,filename));' ... 'end;' ... 'clear filename filepath tagtest;' ]; cb_browsemesh = [ '[filename, filepath] = uigetfile(''*.spl'', ''Select a spline file'');' ... 'if filename ~=0,' ... ' set(findobj( gcbf, ''userdata'', ''meshfile''), ''style'', ''edit'', ''callback'', '''', ''string'', fullfile(filepath,filename));' ... 'end;' ... 'clear filename filepath tagtest;' ]; cb_browsemeshchan = [ '[filename, filepath] = uigetfile(''*.spl'', ''Select a spline file'');' ... 'if filename ~=0,' ... ' set(findobj( gcbf, ''userdata'', ''meshchanfile''), ''style'', ''edit'', ''callback'', '''', ''string'', fullfile(filepath,filename));' ... 'end;' ... 'clear filename filepath tagtest;' ]; cb_selectcoreg = [ 'tmpmodel = get( findobj(gcbf, ''userdata'', ''meshfile'') , ''string''); tmpmodel = tmpmodel{get( findobj(gcbf, ''userdata'', ''meshfile'') , ''value'')};' ... 'tmploc2 = get( findobj(gcbf, ''userdata'', ''meshchanfile''), ''string''); tmploc2 = tmploc2{ get( findobj(gcbf, ''userdata'', ''meshchanfile'') , ''value'')};' ... 'tmploc1 = get( gcbo, ''userdata'');' ... 'tmptransf = get( findobj(gcbf, ''userdata'', ''coregtext''), ''string'');' ... '[tmp tmptransf] = coregister(tmploc1{1}, tmploc2, ''mesh'', tmpmodel, ''helpmsg'', ''on'',' ... ' ''chaninfo1'', tmploc1{2}, ''transform'', str2num(tmptransf));' ... 'if ~isempty(tmptransf), set( findobj(gcbf, ''userdata'', ''coregtext''), ''string'', num2str(tmptransf)); end;' ... 'clear tmpmodel tmploc2 tmploc1 tmp tmptransf;' ]; cb_helpload = [ 'warndlg2(strvcat(''If you have already generated a spline file for this channel location'',' ... '''structure, you may enter it here. Click on the "Use existing spline file or'',' ... '''structure" to activate the edit box first.''), ''Load file for headplot()'');' ]; cb_helpcoreg = [ 'warndlg2(strvcat(''Your channel locations must be co-registered with a 3-D head mesh to be plotted.'',' ... '''If you are using one of the template location files, the "Talairach transformation matrix"'',' ... '''field will be filled automatically (just enter an output file name and press "OK").'',' ... '''Otherwise press the "Manual coreg." button to perform co-registration.''), ''Load file for headplot()'');' ]; cb_selectmesh = [ 'set(findobj(gcbf, ''userdata'', ''meshchanfile''), ''value'', get(gcbo, ''value''));' ... 'set(findobj(gcbf, ''userdata'', ''meshfile'') , ''value'', get(gcbo, ''value''));' ... 'tmpdat = get(gcbf, ''userdata'');' ... 'set(findobj(gcbf, ''userdata'', ''coregtext''), ''string'', num2str(tmpdat{get(gcbo, ''value'')}));' ]; defaultmat = { 'mheadnew.mat' 'colin27headmesh.mat' }; defaultloc = { 'mheadnew.xyz' 'colin27headmesh.xyz' }; defaulttransform = { transform [0 -15 -15 0.05 0 -1.57 100 88 110] }; if iseeglabdeployed defaultmat = fullfile(eeglabexefolder, defaultmat); defaultloc = fullfile(eeglabexefolder, defaultloc); end; userdatatmp = { EEG.chanlocs EEG.chaninfo }; txt = { { 'style' 'text' 'string' 'Co-register channel locations with head mesh and compute a mesh spline file (each scalp montage needs a headplot() spline file)' 'fontweight' 'bold' } ... { 'style' 'checkbox' 'string' 'Use the following spline file or structure' 'userdata' 'loadfile' 'tag' 'loadcb' 'callback' cb_load 'value' ~compute_file } ... { 'style' 'edit' 'string' fastif(typeplot, EEG.splinefile, EEG.icasplinefile) 'userdata' 'load' 'tag' 'load' 'enable' enableload } ... { 'style' 'pushbutton' 'string' 'Browse' 'callback' cb_browseload 'tag' 'load' 'enable' enableload } ... { 'style' 'pushbutton' 'string' 'Help' 'callback' cb_helpload } ... { 'style' 'checkbox' 'string' 'Or (re)compute a new spline file named:' 'tag' 'compcb' 'callback' cb_comp 'value' compute_file } ... { 'style' 'edit' 'string' [fullfile(pwd, EEG.filename(1:length(EEG.filename)-3)),'spl'] 'userdata' 'coregfile' 'tag' 'comp' 'enable' enablecomp } ... { 'style' 'pushbutton' 'string' 'Browse' 'callback' cb_browsecomp 'tag' 'comp' 'enable' enablecomp } ... { 'style' 'pushbutton' 'string' 'Help' 'callback' cb_helpcoreg } ... { 'style' 'text' 'string' ' 3-D head mesh file' 'tag' 'comp' 'enable' enablecomp } ... { 'style' 'popupmenu' 'string' defaultmat 'userdata' 'meshfile' 'callback' cb_selectmesh 'tag' 'comp' 'enable' enablecomp } ... { 'style' 'pushbutton' 'string' 'Browse other' 'callback' cb_browsemesh 'tag' 'comp' 'enable' enablecomp } ... { } ... { 'style' 'text' 'string' ' Mesh associated channel file' 'tag' 'comp' 'enable' enablecomp } ... { 'style' 'popupmenu' 'string' defaultloc 'userdata' 'meshchanfile' 'callback' cb_selectmesh 'tag' 'comp' 'enable' enablecomp } ... { 'style' 'pushbutton' 'string' 'Browse other' 'callback' cb_browsemeshchan 'tag' 'comp' 'enable' enablecomp } ... { } ... { 'style' 'text' 'string' ' Talairach-model transformation matrix' 'tag' 'comp' 'enable' enablecomp } ... { 'style' 'edit' 'string' num2str(transform) 'userdata' 'coregtext' 'tag' 'comp' 'enable' enablecomp } ... { 'style' 'pushbutton' 'string' 'Manual coreg.' 'callback' cb_selectcoreg 'userdata' userdatatmp 'tag' 'comp' 'enable' enablecomp } ... { } ... { } ... { 'style' 'text' 'string' 'Plot interpolated activity onto 3-D head' 'fontweight' 'bold' } ... { 'style' 'text' 'string' txt } ... { 'style' 'edit' 'string' fastif( typeplot, '', ['1:' int2str(size(EEG.data,1))] ) } { } ... { 'style' 'text' 'string' 'Plot title:' } ... { 'style' 'edit' 'string' [ fastif( typeplot, 'ERP scalp maps of dataset:', 'Components of dataset: ') ... fastif(~isempty(EEG.setname), EEG.setname, '') ] } { } ... { 'style' 'text' 'string' 'Plot geometry (rows,columns): (Default [] = near square)' } ... { 'style' 'edit' 'string' '' } { } ... { 'style' 'text' 'string' 'Other headplot options (See >> help headplot):' } ... { 'style' 'edit' 'string' '' } { } }; % plot GUI and protect parameters % ------------------------------- geom = { [1] [1.3 1.6 0.5 0.5 ] [1.3 1.6 0.5 0.5 ] [1.3 1.6 0.6 0.4 ] [1.3 1.6 0.6 0.4 ] [1.3 1.6 0.6 0.4 ] ... [1] [1] [1.5 1 0.5] [1.5 1 0.5] [1.5 1 0.5] [1.5 1 0.5] }; optiongui = { 'uilist', txt, 'title', fastif( typeplot, 'ERP head plot(s) -- pop_headplot()', ... 'Component head plot(s) -- pop_headplot()'), 'geometry', geom 'userdata' defaulttransform }; [result, userdat2, strhalt, outstruct] = inputgui( 'mode', 'noclose', optiongui{:}); if isempty(result), return; end; if ~isempty(get(0, 'currentfigure')) currentfig = gcf; else return; end; while test_wrong_parameters(currentfig) [result, userdat2, strhalt, outstruct] = inputgui( 'mode', currentfig, optiongui{:}); if isempty(result), return; end; end; close(currentfig); % decode setup parameters % ----------------------- options = {}; if result{1}, options = { options{:} 'load' result{2} }; else if ~isstr(result{5}) result{5} = defaultmat{result{5}}; end; if isempty(result{7}) setupopt = { result{4} 'meshfile' result{5} }; % no coreg else setupopt = { result{4} 'meshfile' result{5} 'transform' str2num(result{7}) }; fprintf('Transformation matrix: %s\n', result{7}); end; options = { options{:} 'setup' setupopt }; if ~strcmpi(result{5}, 'mheadnew.mat'), EEG.headplotmeshfile = result{5}; else EEG.headplotmeshfile = ''; end; end; % decode other parameters % ----------------------- arg2 = eval( [ '[' result{8} ']' ] ); if length(arg2) > EEG.nbchan tmpbut = questdlg2(['This will draw ' int2str(length(arg2)) ' plots. Continue ?'], '', 'Cancel', 'Yes', 'Yes'); if strcmp(tmpbut, 'Cancel'), return; end; end; if length(arg2) == 0, error('please choose a latency(s) to plot'); end topotitle = result{9}; rowcols = eval( [ '[ ' result{10} ' ]' ] ); tmpopts = eval( [ '{ ' result{11} ' }' ] ); if ~isempty(tmpopts) options = { options{:} tmpopts{:} }; end; if size(arg2(:),1) == 1, figure; end; else % Pass along parameters and bypass GUI input options = varargin; end; % Check if pop_headplot input 'colorbar' was called, and don't send it to headplot loc = strmatch('colorbar', options(1:2:end), 'exact'); loc = loc*2-1; if ~isempty(loc) colorbar_switch = strcmp('on',options{ loc+1 }); options(loc:loc+1) = []; else colorbar_switch = 1; end % read or generate file if necessary % ---------------------------------- pop_options = options; loc = strmatch('load', options(1:2:end)); loc = loc*2-1; if ~isempty(loc) if typeplot EEG.splinefile = options{ loc+1 }; else EEG.icasplinefile = options{ loc+1 }; end; options(loc:loc+1) = []; end; loc = strmatch('setup', options(1:2:end)); loc = loc*2-1; if ~isempty(loc) if typeplot headplot('setup', EEG.chanlocs, options{loc+1}{1}, 'chaninfo', EEG.chaninfo, options{ loc+1 }{2:end}); EEG.splinefile = options{loc+1}{1}; else headplot('setup', EEG.chanlocs, options{loc+1}{1}, 'chaninfo', EEG.chaninfo, 'ica', 'on', options{ loc+1 }{2:end}); EEG.icasplinefile = options{loc+1}{1}; end; options(loc:loc+1) = []; compute_file = 1; else compute_file = 0; end; % search for existing file if necessary % ------------------------------------- if typeplot == 1 % ********** data plot fieldname = 'splinefile'; if isempty(EEG.splinefile) if length(EEG.icachansind) == EEG.nbchan & ~isempty(EEG.icasplinefile) EEG.splinefile = EEG.icasplinefile; end; end; else % ************* Component plot fieldname = 'icasplinefile'; if isempty(EEG.icasplinefile) if length(EEG.icachansind) == EEG.nbchan & ~isempty(EEG.splinefile) EEG.icasplinefile = EEG.splinefile; end; end; end; % headplot mesh file % ------------------ if isfield(EEG, 'headplotmeshfile') if ~isempty(EEG.headplotmeshfile) options = { options{:} 'meshfile' EEG.headplotmeshfile }; end; end; % check parameters % ---------------- if ~exist('topotitle') topotitle = ''; end; if typeplot if isempty(EEG.splinefile) error('Pop_headplot: cannot find spline file, aborting...'); end; else if isempty(EEG.icasplinefile) error('Pop_headplot: cannot find spline file, aborting...'); end; end; SIZEBOX = 150; nbgraph = size(arg2(:),1); if ~exist('rowcols') | isempty(rowcols) | rowcols == 0 rowcols(2) = ceil(sqrt(nbgraph)); rowcols(1) = ceil(nbgraph/rowcols(2)); end; fprintf('Plotting...\n'); % determine the scale for plot of different times (same scales) % ------------------------------------------------------------- if typeplot SIGTMP = reshape(EEG.data, EEG.nbchan, EEG.pnts, EEG.trials); pos = round( (arg2/1000-EEG.xmin)/(EEG.xmax-EEG.xmin) * (EEG.pnts-1))+1; indexnan = find(isnan(pos)); nanpos = find(isnan(pos)); pos(nanpos) = 1; SIGTMPAVG = mean(SIGTMP(:,pos,:),3); SIGTMPAVG(:, nanpos) = NaN; maxlim = max(SIGTMPAVG(:)); minlim = min(SIGTMPAVG(:)); maplimits = max(maxlim, -minlim); maplimits = maplimits*1.1; maplimits = [ -maplimits maplimits ]; else maplimits = [-1 1]; end; % plot the graphs % --------------- counter = 1; disp('IMPORTANT NOTICE: electrodes are projected to the head surface so their location'); disp(' might slightly differ from the one they had during coregistration '); for index = 1:size(arg2(:),1) if nbgraph > 1 if mod(index, rowcols(1)*rowcols(2)) == 1 if index> 1, a = textsc(0.5, 0.05, topotitle); set(a, 'fontweight', 'bold'); end; figure; pos = get(gcf,'Position'); posx = max(0, pos(1)+(pos(3)-SIZEBOX*rowcols(2))/2); posy = pos(2)+pos(4)-SIZEBOX*rowcols(1); set(gcf,'Position', [posx posy SIZEBOX*rowcols(2) SIZEBOX*rowcols(1)]); try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; end; subplot( rowcols(1), rowcols(2), mod(index-1, rowcols(1)*rowcols(2))+1); end; if ~isnan(arg2(index)) if typeplot headplot( SIGTMPAVG(:,index), EEG.splinefile, 'maplimits', maplimits, options{:}); if nbgraph == 1, title( topotitle ); else title([int2str(arg2(index)) ' ms']); end; else if arg2(index) < 0 headplot( -EEG.icawinv(:, -arg2(index)), EEG.icasplinefile, options{:}); else headplot( EEG.icawinv(:, arg2(index)), EEG.icasplinefile, options{:}); end; if nbgraph == 1, title( topotitle ); else title(['' int2str(arg2(index))]); end; end; drawnow; axis equal; rotate3d off; else axis off end end % Draw colorbar if colorbar_switch if nbgraph == 1 ColorbarHandle = cbar(0,0,[maplimits(1) maplimits(2)]); pos = get(ColorbarHandle,'position'); % move left & shrink to match head size set(ColorbarHandle,'position',[pos(1)-.05 pos(2)+0.13 pos(3)*0.7 pos(4)-0.26]); else cbar('vert',0,[maplimits(1) maplimits(2)]); end if ~typeplot % Draw '+' and '-' instead of numbers for colorbar tick labels tmp = get(gca, 'ytick'); set(gca, 'ytickmode', 'manual', 'yticklabelmode', 'manual', 'ytick', [tmp(1) tmp(end)], 'yticklabel', { '-' '+' }); end end try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if nbgraph> 1, a = textsc(0.5, 0.05, topotitle); set(a, 'fontweight', 'bold'); axcopy(gcf, [ 'set(gcf, ''''units'''', ''''pixels''''); postmp = get(gcf, ''''position'''');' ... 'set(gcf, ''''position'''', [postmp(1) postmp(2) 560 420]); rotate3d(gcf); clear postmp;' ]); end; % generate output command % ----------------------- com = sprintf('pop_headplot(%s, %d, %s, ''%s'', [%s], %s);', inputname(1), typeplot, vararg2str(arg2), ... topotitle, int2str(rowcols), vararg2str( pop_options ) ); if compute_file, com = [ 'EEG = ' com ]; end; if nbgraph== 1, com = [ 'figure; ' com ]; rotate3d(gcf); end; return; % test for wrong parameters % ------------------------- function bool = test_wrong_parameters(hdl) bool = 0; loadfile = get( findobj( hdl, 'userdata', 'loadfile') , 'value' ); textlines = ''; if ~loadfile coreg1 = get( findobj( hdl, 'userdata', 'coregtext') , 'string' ); coreg3 = get( findobj( hdl, 'userdata', 'coregfile') , 'string' ); if isempty(coreg1) textlines = strvcat('You must co-register your channel locations with the head model.', ... 'This is an easy process: Press the "Manual coreg." button in the', ... 'right center of the pop_headplot() window and follow instructions.',... 'To bypass co-registration (not recommended), enter', ... '"0 0 0 0 0 0 1 1 1" as the "Tailairach transformation matrix.'); bool = 1; end; if isempty(coreg3) textlines = strvcat(textlines, ' ', 'You need to enter an output file name.'); bool = 1; end; if bool warndlg2( textlines, 'Error'); end; end;
github
lcnhappe/happe-master
pop_loadset.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_loadset.m
14,435
utf_8
93a26aeae3a4c3fd4bc70166ff7f5328
% pop_loadset() - load an EEG dataset. If no arguments, pop up an input window. % % Usage: % >> EEGOUT = pop_loadset; % pop up window to input arguments % >> EEGOUT = pop_loadset( 'key1', 'val1', 'key2', 'val2', ...); % >> EEGOUT = pop_loadset( filename, filepath); % old calling format % % Optional inputs: % 'filename' - [string] dataset filename. Default pops up a graphical % interface to browse for a data file. % 'filepath' - [string] dataset filepath. Default is current folder. % 'loadmode' - ['all', 'info', integer] 'all' -> load the data and % the dataset structure. 'info' -> load only the dataset % structure but not the actual data. [integer] -> load only % a specific channel. This is efficient when data is stored % in a separate '.dat' file in which individual channels % may be loaded independently of each other. {default: 'all'} % 'eeg' - [EEG structure] reload current dataset % Note: % Multiple filenames and filepaths may be specified. If more than one, % the output EEG variable will be an array of EEG structures. % Output % EEGOUT - EEG dataset structure or array of structures % % Author: Arnaud Delorme, CNL / Salk Institute, 2001; SCCN/INC/UCSD, 2002- % % See also: eeglab(), pop_saveset() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad function [EEG, command] = pop_loadset( inputname, inputpath, varargin) command = ''; EEG = []; if nargin < 1 % pop up window % ------------- [inputname, inputpath] = uigetfile2('*.SET*;*.set', 'Load dataset(s) -- pop_loadset()', 'multiselect', 'on'); drawnow; if isequal(inputname, 0) return; end; options = { 'filename' inputname 'filepath' inputpath }; else % account for old calling format % ------------------------------ if ~strcmpi(inputname, 'filename') && ~strcmpi(inputname, 'filepath') && ~strcmpi(inputname, 'eeg') options = { 'filename' inputname }; if nargin > 1 options = { options{:} 'filepath' inputpath }; end; if nargin > 2 options = { options{:} 'loadmode' varargin{1} }; end; else options = { inputname inputpath varargin{:} }; end; end; % decode input parameters % ----------------------- g = finputcheck( options, ... { 'filename' { 'string';'cell' } [] ''; 'filepath' 'string' [] ''; 'check' 'string' { 'on';'off' } 'on'; 'loadmode' { 'string';'integer' } { { 'info' 'all' } [] } 'all'; 'eeg' 'struct' [] struct('data',{}) }, 'pop_loadset'); if isstr(g), error(g); end; if isstr(g.filename), g.filename = { g.filename }; end; % reloading EEG structure from disk % --------------------------------- if ~isempty(g.eeg) EEG = pop_loadset( 'filepath', g.eeg.filepath, 'filename', g.eeg.filename); else eeglab_options; ALLEEGLOC = []; for ifile = 1:length(g.filename) if ifile > 1 && option_storedisk g.loadmode = 'last'; % warndlg2(strvcat('You may only load a single dataset','when selecting the "Store at most one', 'dataset in memory" option')); % break; end; % read file % --------- filename = fullfile(g.filepath, g.filename{ifile}); fprintf('pop_loadset(): loading file %s ...\n', filename); %try TMPVAR = load('-mat', filename); %catch, % error([ filename ': file is protected or does not exist' ]); %end; % variable not found % ------------------ if isempty(TMPVAR) error('No dataset info is associated with this file'); end; if isfield(TMPVAR, 'EEG') % load individual dataset % ----------------------- EEG = checkoldformat(TMPVAR.EEG); [ EEG.filepath EEG.filename ext ] = fileparts( filename ); EEG.filename = [ EEG.filename ext ]; % account for name changes etc... % ------------------------------- if isstr(EEG.data) && ~strcmpi(EEG.data, 'EEGDATA') [tmp EEG.data ext] = fileparts( EEG.data ); EEG.data = [ EEG.data ext]; if ~isempty(tmp) && ~strcmpi(tmp, EEG.filepath) disp('Warning: updating folder name for .dat|.fdt file'); end; if ~strcmp(EEG.filename(1:end-3), EEG.data(1:end-3)) disp('Warning: the name of the dataset has changed on disk, updating .dat & .fdt data file to the new name'); EEG.data = [ EEG.filename(1:end-3) EEG.data(end-2:end) ]; EEG.saved = 'no'; end; end; % copy data to output variable if necessary (deprecated) % ----------------------------------------- if ~strcmpi(g.loadmode, 'info') && isfield(TMPVAR, 'EEGDATA') if ~option_storedisk || ifile == length(g.filename) EEG.data = TMPVAR.EEGDATA; end; end; elseif isfield(TMPVAR, 'ALLEEG') % old format eeglab_options; if option_storedisk error('Cannot load multiple dataset file. Change memory option to allow multiple datasets in memory, then try again. Remember that this file type is OBSOLETE.'); end; % this part is deprecated as of EEGLAB 5.00 % since all dataset data have to be saved in separate files % ----------------------------------------------------- disp('pop_loadset(): appending datasets'); EEG = TMPVAR.ALLEEG; for index=1:length(EEG) EEG(index).filename = ''; EEG(index).filepath = ''; if isstr(EEG(index).data), EEG(index).filepath = g.filepath; if length(g.filename{ifile}) > 4 && ~strcmp(g.filename{ifile}(1:end-4), EEG(index).data(1:end-4)) && strcmpi(g.filename{ifile}(end-3:end), 'sets') disp('Warning: the name of the dataset has changed on disk, updating .dat data file to the new name'); EEG(index).data = [ g.filename{ifile}(1:end-4) 'fdt' int2str(index) ]; end; end; end; else EEG = checkoldformat(TMPVAR); if ~isfield( EEG, 'data') error('pop_loadset(): not an EEG dataset file'); end; if isstr(EEG.data), EEG.filepath = g.filepath; end; end; %ALLEEGLOC = pop_newset(ALLEEGLOC, EEG, 1); ALLEEGLOC = eeg_store(ALLEEGLOC, EEG, 0, 'verbose', 'off'); end; EEG = ALLEEGLOC; end; % load all data or specific data channel % -------------------------------------- if strcmpi(g.check, 'on') EEG = eeg_checkset(EEG); end; if isstr(g.loadmode) if strcmpi(g.loadmode, 'all') EEG = eeg_checkset(EEG, 'loaddata'); elseif strcmpi(g.loadmode, 'last') EEG(end) = eeg_checkset(EEG(end), 'loaddata'); end; else % load/select specific channel % ---------------------------- EEG.datachannel = g.loadmode; EEG.data = eeg_getdatact(EEG, 'channel', g.loadmode); EEG.nbchan = length(g.loadmode); if ~isempty(EEG.chanlocs) EEG.chanlocs = EEG.chanlocs(g.loadmode); end; EEG.icachansind = []; EEG.icaact = []; EEG.icaweights = []; EEG.icasphere = []; EEG.icawinv = []; %if isstr(EEG.data) % EEG.datfile = EEG.data; % fid = fopen(fullfile(EEG.filepath, EEG.data), 'r', 'ieee-le'); % fseek(fid, EEG.pnts*EEG.trials*( g.loadmode - 1), 0 ); % EEG.data = fread(fid, EEG.pnts*EEG.trials, 'float32'); % fclose(fid); %else % EEG.data = EEG.data(g.loadmode,:,:); %end; end; % set file name and path % ---------------------- if length(EEG) == 1 tmpfilename = g.filename{1}; if isempty(g.filepath) [g.filepath tmpfilename ext] = fileparts(tmpfilename); tmpfilename = [ tmpfilename ext ]; end; EEG.filename = tmpfilename; EEG.filepath = g.filepath; end; % set field indicating that the data has not been modified % -------------------------------------------------------- if isfield(EEG, 'changes_not_saved') EEG = rmfield(EEG, 'changes_not_saved'); end; for index=1:length(EEG) EEG(index).saved = 'justloaded'; end; command = sprintf('EEG = pop_loadset(%s);', vararg2str(options)); return; function EEG = checkoldformat(EEG) if ~isfield( EEG, 'data') fprintf('pop_loadset(): Incompatible with new format, trying old format and converting...\n'); eegset = EEG.cellArray; off_setname = 1; %= filename off_filename = 2; %= filename off_filepath = 3; %= fielpath off_type = 4; %= type EEG AVG CNT off_chan_names = 5; %= chan_names off_chanlocs = 21; %= filename off_pnts = 6; %= pnts off_sweeps = 7; %= sweeps off_rate = 8; %= rate off_xmin = 9; %= xmin off_xmax = 10; %= xmax off_accept = 11; %= accept off_typeeeg = 12; %= typeeeg off_rt = 13; %= rt off_response = 14; %= response off_signal = 15; %= signal off_variance = 16; %= variance off_winv = 17; %= variance off_weights = 18; %= variance off_sphere = 19; %= variance off_activations = 20; %= variance off_entropytrial = 22; %= variance off_entropycompo = 23; %= variance off_threshold = 24; %= variance off_comporeject = 25; %= variance off_sigreject = 26; off_kurtA = 29; off_kurtR = 30; off_kurtDST = 31; off_nbchan = 32; off_elecreject = 33; off_comptrial = 34; off_kurttrial = 35; %= variance off_kurttrialglob = 36; %= variance off_icareject = 37; %= variance off_gcomporeject = 38; %= variance off_eegentropy = 27; off_eegkurt = 28; off_eegkurtg = 39; off_tmp1 = 40; off_tmp2 = 40; % must convert here into new format EEG.setname = eegset{off_setname }; EEG.filename = eegset{off_filename }; EEG.filepath = eegset{off_filepath }; EEG.namechan = eegset{off_chan_names}; EEG.chanlocs = eegset{off_chanlocs }; EEG.pnts = eegset{off_pnts }; EEG.nbchan = eegset{off_nbchan }; EEG.trials = eegset{off_sweeps }; EEG.srate = eegset{off_rate }; EEG.xmin = eegset{off_xmin }; EEG.xmax = eegset{off_xmax }; EEG.accept = eegset{off_accept }; EEG.eegtype = eegset{off_typeeeg }; EEG.rt = eegset{off_rt }; EEG.eegresp = eegset{off_response }; EEG.data = eegset{off_signal }; EEG.icasphere = eegset{off_sphere }; EEG.icaweights = eegset{off_weights }; EEG.icawinv = eegset{off_winv }; EEG.icaact = eegset{off_activations }; EEG.stats.entropy = eegset{off_entropytrial }; EEG.stats.kurtc = eegset{off_kurttrial }; EEG.stats.kurtg = eegset{off_kurttrialglob}; EEG.stats.entropyc = eegset{off_entropycompo }; EEG.reject.threshold = eegset{off_threshold }; EEG.reject.icareject = eegset{off_icareject }; EEG.reject.compreject = eegset{off_comporeject }; EEG.reject.gcompreject= eegset{off_gcomporeject }; EEG.reject.comptrial = eegset{off_comptrial }; EEG.reject.sigreject = eegset{off_sigreject }; EEG.reject.elecreject = eegset{off_elecreject }; EEG.stats.kurta = eegset{off_kurtA }; EEG.stats.kurtr = eegset{off_kurtR }; EEG.stats.kurtd = eegset{off_kurtDST }; EEG.stats.eegentropy = eegset{off_eegentropy }; EEG.stats.eegkurt = eegset{off_eegkurt }; EEG.stats.eegkurtg = eegset{off_eegkurtg }; %catch % disp('Warning: some variables may not have been assigned'); %end; % modify the eegtype to match the new one try if EEG.trials > 1 EEG.events = [ EEG.rt(:) EEG.eegtype(:) EEG.eegresp(:) ]; end; catch, end; end; % check modified fields % --------------------- if isfield(EEG,'icadata'), EEG.icaact = EEG.icadata; end; if isfield(EEG,'poschan'), EEG.chanlocs = EEG.poschan; end; if ~isfield(EEG, 'icaact'), EEG.icaact = []; end; if ~isfield(EEG, 'chanlocs'), EEG.chanlocs = []; end; if isfield(EEG, 'events') && ~isfield(EEG, 'event') try if EEG.trials > 1 EEG.events = [ EEG.rt(:) ]; EEG = eeg_checkset(EEG); EEG = pop_importepoch(EEG, EEG.events, { 'rt'}, {'rt'}, 1E-3); end; if isfield(EEG, 'trialsval') EEG = pop_importepoch(EEG, EEG.trialsval(:,2:3), { 'eegtype' 'response' }, {},1,0,0); end; EEG = eeg_checkset(EEG, 'eventconsistency'); catch, disp('Warning: could not import events'); end; end; rmfields = {'icadata' 'events' 'accept' 'eegtype' 'eegresp' 'trialsval' 'poschan' 'icadata' 'namechan' }; for index = 1:length(rmfields) if isfield(EEG, rmfields{index}), disp(['Warning: field ' rmfields{index} ' is deprecated']); end; end;
github
lcnhappe/happe-master
pop_selectcomps.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_selectcomps.m
7,725
utf_8
17906d954f5d84a38ea3de8bf871a86d
% pop_selectcomps() - Display components with button to vizualize their % properties and label them for rejection. % Usage: % >> OUTEEG = pop_selectcomps( INEEG, compnum ); % % Inputs: % INEEG - Input dataset % compnum - vector of component numbers % % Output: % OUTEEG - Output dataset with updated rejected components % % Note: % if the function POP_REJCOMP is ran prior to this function, some % fields of the EEG datasets will be present and the current function % will have some more button active to tune up the automatic rejection. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: pop_prop(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad function [EEG, com] = pop_selectcomps( EEG, compnum, fig ); COLREJ = '[1 0.6 0.6]'; COLACC = '[0.75 1 0.75]'; PLOTPERFIG = 35; com = ''; if nargin < 1 help pop_selectcomps; return; end; if nargin < 2 promptstr = { 'Components to plot:' }; initstr = { [ '1:' int2str(size(EEG.icaweights,1)) ] }; result = inputdlg2(promptstr, 'Reject comp. by map -- pop_selectcomps',1, initstr); if isempty(result), return; end; compnum = eval( [ '[' result{1} ']' ]); if length(compnum) > PLOTPERFIG ButtonName=questdlg2(strvcat(['More than ' int2str(PLOTPERFIG) ' components so'],'this function will pop-up several windows'), ... 'Confirmation', 'Cancel', 'OK','OK'); if ~isempty( strmatch(lower(ButtonName), 'cancel')), return; end; end; end; fprintf('Drawing figure...\n'); currentfigtag = ['selcomp' num2str(rand)]; % generate a random figure tag if length(compnum) > PLOTPERFIG for index = 1:PLOTPERFIG:length(compnum) pop_selectcomps(EEG, compnum([index:min(length(compnum),index+PLOTPERFIG-1)])); end; com = [ 'pop_selectcomps(' inputname(1) ', ' vararg2str(compnum) ');' ]; return; end; if isempty(EEG.reject.gcompreject) EEG.reject.gcompreject = zeros( size(EEG.icawinv,2)); end; try, icadefs; catch, BACKCOLOR = [0.8 0.8 0.8]; GUIBUTTONCOLOR = [0.8 0.8 0.8]; end; % set up the figure % ----------------- column =ceil(sqrt( length(compnum) ))+1; rows = ceil(length(compnum)/column); if ~exist('fig','var') figure('name', [ 'Reject components by map - pop_selectcomps() (dataset: ' EEG.setname ')'], 'tag', currentfigtag, ... 'numbertitle', 'off', 'color', BACKCOLOR); set(gcf,'MenuBar', 'none'); pos = get(gcf,'Position'); set(gcf,'Position', [pos(1) 20 800/7*column 600/5*rows]); incx = 120; incy = 110; sizewx = 100/column; if rows > 2 sizewy = 90/rows; else sizewy = 80/rows; end; pos = get(gca,'position'); % plot relative to current axes hh = gca; q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]./100; axis off; end; % figure rows and columns % ----------------------- if EEG.nbchan > 64 disp('More than 64 electrodes: electrode locations not shown'); plotelec = 0; else plotelec = 1; end; count = 1; for ri = compnum if exist('fig','var') button = findobj('parent', fig, 'tag', ['comp' num2str(ri)]); if isempty(button) error( 'pop_selectcomps(): figure does not contain the component button'); end; else button = []; end; if isempty( button ) % compute coordinates % ------------------- X = mod(count-1, column)/column * incx-10; Y = (rows-floor((count-1)/column))/rows * incy - sizewy*1.3; % plot the head % ------------- if ~strcmp(get(gcf, 'tag'), currentfigtag); figure(findobj('tag', currentfigtag)); end; ha = axes('Units','Normalized', 'Position',[X Y sizewx sizewy].*s+q); if plotelec topoplot( EEG.icawinv(:,ri), EEG.chanlocs, 'verbose', ... 'off', 'style' , 'fill', 'chaninfo', EEG.chaninfo, 'numcontour', 8); else topoplot( EEG.icawinv(:,ri), EEG.chanlocs, 'verbose', ... 'off', 'style' , 'fill','electrodes','off', 'chaninfo', EEG.chaninfo, 'numcontour', 8); end; axis square; % plot the button % --------------- if ~strcmp(get(gcf, 'tag'), currentfigtag); figure(findobj('tag', currentfigtag)); end button = uicontrol(gcf, 'Style', 'pushbutton', 'Units','Normalized', 'Position',... [X Y+sizewy sizewx sizewy*0.25].*s+q, 'tag', ['comp' num2str(ri)]); command = sprintf('pop_prop( %s, 0, %d, gcbo, { ''freqrange'', [1 50] });', inputname(1), ri); %RMC command = sprintf('pop_prop( %s, 0, %d, %3.15f, { ''freqrange'', [1 50] });', inputname(1), ri, button); set( button, 'callback', command ); end; set( button, 'backgroundcolor', eval(fastif(EEG.reject.gcompreject(ri), COLREJ,COLACC)), 'string', int2str(ri)); drawnow; count = count +1; end; % draw the bottom button % ---------------------- if ~exist('fig','var') if ~strcmp(get(gcf, 'tag'), currentfigtag); figure(findobj('tag', currentfigtag)); end hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'Cancel', 'Units','Normalized', 'backgroundcolor', GUIBUTTONCOLOR, ... 'Position',[-10 -10 15 sizewy*0.25].*s+q, 'callback', 'close(gcf); fprintf(''Operation cancelled\n'')' ); hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'Set threhsolds', 'Units','Normalized', 'backgroundcolor', GUIBUTTONCOLOR, ... 'Position',[10 -10 15 sizewy*0.25].*s+q, 'callback', 'pop_icathresh(EEG); pop_selectcomps( EEG, gcbf);' ); if isempty( EEG.stats.compenta ), set(hh, 'enable', 'off'); end; hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'See comp. stats', 'Units','Normalized', 'backgroundcolor', GUIBUTTONCOLOR, ... 'Position',[30 -10 15 sizewy*0.25].*s+q, 'callback', ' ' ); if isempty( EEG.stats.compenta ), set(hh, 'enable', 'off'); end; hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'See projection', 'Units','Normalized', 'backgroundcolor', GUIBUTTONCOLOR, ... 'Position',[50 -10 15 sizewy*0.25].*s+q, 'callback', ' ', 'enable', 'off' ); hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'Help', 'Units','Normalized', 'backgroundcolor', GUIBUTTONCOLOR, ... 'Position',[70 -10 15 sizewy*0.25].*s+q, 'callback', 'pophelp(''pop_selectcomps'');' ); command = '[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET); eegh(''[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET);''); close(gcf)'; hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'OK', 'Units','Normalized', 'backgroundcolor', GUIBUTTONCOLOR, ... 'Position',[90 -10 15 sizewy*0.25].*s+q, 'callback', command); % sprintf(['eeg_global; if %d pop_rejepoch(%d, %d, find(EEG.reject.sigreject > 0), EEG.reject.elecreject, 0, 1);' ... % ' end; pop_compproj(%d,%d,1); close(gcf); eeg_retrieve(%d); eeg_updatemenu; '], rejtrials, set_in, set_out, fastif(rejtrials, set_out, set_in), set_out, set_in)); end; com = [ 'pop_selectcomps(' inputname(1) ', ' vararg2str(compnum) ');' ]; return;
github
lcnhappe/happe-master
pop_readsegegi.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_readsegegi.m
3,697
utf_8
c101ff1d191f9634bc1ce0aba263842c
% pop_readsegegi() - load a segmented EGI EEG file. Pop up query % window if no arguments. % Usage: % >> EEG = pop_readsegegi; % a window pops up % >> EEG = pop_readsegegi( filename ); % no pop-up window % % Inputs: % filename - first EGI file name % % Outputs: % EEG - EEGLAB data structure % % Author: Arnaud Delorme, CNL / Salk Institute, 10 April 2003 % % See also: eeglab(), readegi(), readegihdr() % Copyright (C) 12 Nov 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, command] = pop_readegi(filename); EEG = []; command = ''; if nargin < 1 % ask user [filename, filepath] = uigetfile('*.RAW;*.raw', 'Choose first EGI RAW file -- pop_readsegegi()'); drawnow; if filename == 0 return; end; filename = fullfile(filepath, filename); end; % load datas % ---------- EEG = eeg_emptyset; tailname = filename(end-3:end); basename = filename(1:end-7); index = 1; cont = 1; Eventdata = []; disp('Removing trailing character of selected file to find base file name'); fprintf('Base file name is: %s\n', basename); orifilename = [ basename sprintf('%3.3d', index) tailname ]; if ~exist(orifilename) disp ([ 'First file of series ''' orifilename ''' not found' ] ); error([ 'First file of series ''' orifilename ''' not found' ] ); end; while cont tmpfilename = [ basename sprintf('%3.3d', index) tailname ]; try, disp(['Importing ' tmpfilename ]); [Head tmpdata tmpevent] = readegi( tmpfilename ); EEG.data = [ EEG.data tmpdata ]; Eventdata = [ Eventdata tmpevent ]; index = index + 1; catch, cont = 0; end; end; % add one channel with the event data % ----------------------------------- if ~isempty(Eventdata) & size(Eventdata,2) == size(EEG.data,2) EEG.data(end+1:end+size(Eventdata,1),:) = Eventdata; end; EEG.comments = [ 'Original files: ' orifilename ' to ' tmpfilename ]; EEG.filepath = ''; EEG.setname = 'EGI file'; EEG.nbchan = size(EEG.data,1); EEG.srate = Head.samp_rate; EEG.trials = Head.segments; EEG.pnts = Head.segsamps; EEG.xmin = 0; % importing the events % -------------------- if ~isempty(Eventdata) orinbchans = EEG.nbchan; for index = size(Eventdata,1):-1:1 EEG = pop_chanevent( EEG, orinbchans-size(Eventdata,1)+index, 'edge', 'leading', ... 'delevent', 'off', 'typename', Head.eventcode(index,:), ... 'nbtype', 1, 'delchan', 'on'); end; end; % importing channel locations % --------------------------- if all(EEG.data(end,1:10) == 0) disp('Deleting empty data reference channel (reference channel location is retained)'); EEG.data(end,:) = []; EEG.nbchan = size(EEG.data,1); EEG = eeg_checkset(EEG); end; EEG = readegilocs(EEG); EEG = eeg_checkset(EEG); command = sprintf('EEG = pop_readsegegi(''%s'');', filename); return;
github
lcnhappe/happe-master
pop_rmbase.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_rmbase.m
7,453
utf_8
1a9f62f7b588515a06297fd2abc55e74
% pop_rmbase() - remove channel baseline means from an epoched or % continuous EEG dataset. Calls rmbase(). % Usage: % >> OUTEEG = pop_rmbase( EEG ); % pop up an interactive arg entry window % >> OUTEEG = pop_rmbase( EEG, timerange, pointrange); % call rmbase() % % Graphic interface: % "Baseline latency range" - [edit box] Latency range for the baseline in ms. % Collects the 'timerange' command line input. % Empty or [] input ->set_beapp_path; Use whole epoch as baseline % "Baseline points vector" - [edit box] Collects the 'pointrange' command line % option (below). (Overwritten by 'timerange' above). % Empty or [] input -> Use whole epoch as baseline % Inputs: % EEG - Input dataset % timerange - [min_ms max_ms] Baseline latency range in milliseconds. % Empty or [] input -> Use whole epoch as baseline % pointrange - [min:max] Baseline points vector (overwritten by timerange). % Empty or [] input -> Use whole epoch as baseline % Outputs: % OUTEEG - Output dataset % % Note: If dataset is continuous, channel means are removed separately % for each continuous data region, respecting 'boundary' events % marking boundaries of excised or concatenated data portions. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: rmbase(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad function [EEG, com] = pop_rmbase(EEG, timerange, pointrange); com =''; if nargin < 1 help pop_rmbase; return; end; if isempty(EEG(1).data) disp('pop_rmbase(): cannot remove baseline of an empty dataset'); return; end; if nargin < 1 help pop_rmbase; return; end; if nargin < 2 & EEG(1).trials > 1 % popup window parameters % ----------------------- defaultbase = [num2str(EEG(1).xmin*1000) ' 0']; if EEG(1).xmin*1000 >= 0 defaultbase = '[ ]'; end; uilist = { { 'style' 'text' 'string' 'Baseline latency range ([min max] in ms) ([ ] = whole epoch):' } ... { 'style' 'edit' 'string' defaultbase } ... { 'style' 'text' 'string' 'Or remove baseline points vector (ex:1:56):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Note: press Cancel if you do not want to remove the baseline' } ... }; uigeom = { [3 1] [3 1] [1] }; [result usrdat] = inputgui( 'uilist', uilist, 'geometry', uigeom, 'title', 'Baseline removal - pop_rmbase()', 'helpcom', 'pophelp(''pop_rmbase'');'); if isempty(result), return; end; if ~isempty(usrdat) && isnan(usrdat), return; end; % decode parameters % ----------------- if numel(result) < 2 | ((isempty(result{1}) | strcmp(result{1},'[]') ) ... & (isempty(result{2}) | strcmp(result{2},'[]'))) timerange = [num2str(EEG(1).xmin*1000) num2str(EEG(1).xmax*1000)]; % whole epoch latency range fprintf('pop_rmbase(): using whole epoch as baseline.\n'); % fprintf('pop_rmbase(): baseline limits must be specified.\n'); % return; end; else timerange = eval( [ '[' result{1} ']' ] ); pointrange = eval( [ '[' result{2} ']' ] ); end elseif nargin < 2 & EEG(1).trials == 1 % popup window parameters % ----------------------- resp = questdlg2(strvcat('Remove mean of each data channel'), 'pop_rmbase', 'Cancel', 'Ok', 'Ok'); if strcmpi(resp, 'Cancel'), return; end; timerange = []; pointrange = [1:EEG(1).pnts]; end; % process multiple datasets % ------------------------- if length(EEG) > 1 [ EEG com ] = eeg_eval( 'pop_rmbase', EEG, 'warning', 'on', 'params', ... { timerange pointrange } ); return; end; if exist('pointrange') ~= 1 && ~isempty(timerange) if (timerange(1) < EEG.xmin*1000) & (timerange(2) > EEG.xmax*1000) error('pop_rmbase(): Bad time range'); end; pointrange = round((timerange(1)/1000-EEG.xmin)*EEG.srate+1):round((timerange(2)/1000-EEG.xmin)*EEG.srate); end; if isempty(timerange) timerange = [ EEG(1).xmin*1000 EEG(1).xmax*1000]; end; if exist('pointrange') ~= 1 || isempty(pointrange) if ~isempty(timerange) && (timerange(1) < EEG.xmin*1000) & (timerange(2) > EEG.xmax*1000) error('pop_rmbase(): Bad time range'); end; pointrange = round((timerange(1)/1000-EEG.xmin)*EEG.srate+1):ceil((timerange(2)/1000-EEG.xmin)*EEG.srate); if pointrange(end) > EEG.pnts, pointrange(end) = EEG.pnts; end; end; if ~isempty(pointrange) && ((min(pointrange) < 1) || (max( pointrange ) > EEG.pnts)) error('pop_rmbase(): Wrong point range'); end; fprintf('pop_rmbase(): Removing baseline...\n'); % % Respect excised data boundaries if continuous data % --------------------------------------------------- if EEG.trials == 1 && ~isempty(EEG.event) ... && isfield(EEG.event, 'type') ... && isstr(EEG.event(1).type) tmpevent = EEG.event; boundaries = strmatch('boundary', {tmpevent.type}); if ~isempty(boundaries) % this is crashing fprintf('Pop_rmbase(): finding continuous data discontinuities\n'); boundaries = round([ tmpevent(boundaries).latency ] -0.5-pointrange(1)+1); boundaries(boundaries>=pointrange(end)-pointrange(1)) = []; boundaries(boundaries<1) = []; boundaries = [0 boundaries pointrange(end)-pointrange(1)+1]; for index=1:length(boundaries)-1 tmprange = [boundaries(index)+1:boundaries(index+1)]; if length(tmprange) > 1 EEG.data(:,tmprange) = rmbase( EEG.data(:,tmprange), length(tmprange), ... [1:length(tmprange)]); elseif length(tmprange) == 1 EEG.data(:,tmprange) = 0; end; end; else EEG.data = rmbase( EEG.data, EEG.pnts, pointrange ); end; else for indc = 1:EEG.nbchan tmpmean = mean(double(EEG.data(indc,pointrange,:)),2); EEG.data(indc,:,:) = EEG.data(indc,:,:) - repmat(tmpmean, [1 EEG.pnts 1]); end; % EEG.data = rmbase( reshape(EEG.data, EEG.nbchan, EEG.pnts*EEG.trials), EEG.pnts, pointrange ); end; EEG.data = reshape( EEG.data, EEG.nbchan, EEG.pnts, EEG.trials); EEG.icaact = []; if ~isempty(timerange) com = sprintf('%s = pop_rmbase( %s, [%s]);', inputname(1), inputname(1), ... num2str(timerange)); else com = sprintf('%s = pop_rmbase( %s, [], %s);', inputname(1), inputname(1), ... vararg2str({pointrange})); end; return;
github
lcnhappe/happe-master
pop_fileiodir.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_fileiodir.m
2,897
utf_8
0b71b35b5266ba0571298a6974edf189
% pop_fileiodir() - import directory into EEGLAB using FileIO % % Usage: % >> OUTEEG = pop_fileiodir; % pop up window % >> OUTEEG = pop_fileiodir( folder ); % % Inputs: % folder - [string] folder name % % Optional inputs: % 'channels' - [integer array] list of channel indices % 'samples' - [min max] sample point limits for importing data. % 'trials' - [min max] trial's limit for importing data. % % Outputs: % OUTEEG - EEGLAB data structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2012- % % Note: FILEIO toolbox must be installed. % Copyright (C) 2012 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, command] = pop_fileiodir(folder, varargin); EEG = []; command = ''; if nargin < 1 % ask user folder = uigetdir('*.*', 'Choose a directory -- pop_fileiodir()'); if folder == 0 return; end; drawnow; % open file to get infos % ---------------------- disp('Reading data file header...'); dat = ft_read_header(folder); uilist = { { 'style' 'text' 'String' 'Channel list (defaut all):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'String' [ 'Data range (in sample points) (default all [1 ' int2str(dat.nSamples) '])' ] } ... { 'style' 'edit' 'string' '' } }; geom = { [3 1] [3 1] }; if dat.nTrials > 1 uilist{end+1} = { 'style' 'text' 'String' [ 'Trial range (default all [1 ' int2str(dat.nTrials) '])' ] }; uilist{end+1} = { 'style' 'edit' 'string' '' }; geom = { geom{:} [3 1] }; end; result = inputgui( geom, uilist, 'pophelp(''pop_fileiodir'')', 'Load data using FILE-IO -- pop_fileiodir()'); if length(result) == 0 return; end; options = {}; result = { result{:} '' }; if ~isempty(result{1}), options = { options{:} 'channels' eval( [ '[' result{1} ']' ] ) }; end; if ~isempty(result{2}), options = { options{:} 'samples' eval( [ '[' result{2} ']' ] ) }; end; if ~isempty(result{3}), options = { options{:} 'trials' eval( [ '[' result{3} ']' ] ) }; end; else dat = ft_read_header(folder); options = varargin; end; [EEG command] = pop_fileio(folder, options{:});
github
lcnhappe/happe-master
pop_prop.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_prop.m
16,149
utf_8
904238b3dde9c7e83531113172bce7fe
% pop_prop() - plot the properties of a channel or of an independent % component. % Usage: % >> pop_prop( EEG); % pops up a query window % >> pop_prop( EEG, typecomp); % pops up a query window % >> pop_prop( EEG, typecomp, chanorcomp, winhandle,spectopo_options); % % Inputs: % EEG - EEGLAB dataset structure (see EEGGLOBAL) % % Optional inputs: % typecomp - [0|1] 1 -> display channel properties % 0 -> component properties {default: 1 = channel} % chanorcomp - channel or component number[s] to display {default: 1} % % winhandle - if this parameter is present or non-NaN, buttons % allowing the rejection of the component are drawn. % If non-zero, this parameter is used to back-propagate % the color of the rejection button. % spectopo_options - [cell array] optional cell arry of options for % the spectopo() function. % For example { 'freqrange' [2 50] } % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: pop_runica(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % hidden parameter winhandle % 01-25-02 reformated help & license -ad % 02-17-02 removed event index option -ad % 03-17-02 debugging -ad & sm % 03-18-02 text settings -ad & sm % 03-18-02 added title -ad & sm function com = pop_prop(EEG, typecomp, chanorcomp, winhandle, spec_opt) com = ''; if nargin < 1 help pop_prop; return; end; if nargin < 5 spec_opt = {}; end; if nargin == 1 typecomp = 1; % defaults chanorcomp = 1; end; if typecomp == 0 & isempty(EEG.icaweights) error('No ICA weights recorded for this dataset -- first run ICA on it'); end; if nargin == 2 promptstr = { fastif(typecomp,'Channel index(ices) to plot:','Component index(ices) to plot:') ... 'Spectral options (see spectopo() help):' }; inistr = { '1' '''freqrange'', [2 50]' }; result = inputdlg2( promptstr, 'Component properties - pop_prop()', 1, inistr, 'pop_prop'); if size( result, 1 ) == 0 return; end; chanorcomp = eval( [ '[' result{1} ']' ] ); spec_opt = eval( [ '{' result{2} '}' ] ); end; % plotting several component properties % ------------------------------------- if length(chanorcomp) > 1 for index = chanorcomp pop_prop(EEG, typecomp, index, 0, spec_opt); % call recursively for each chanorcomp end; com = sprintf('pop_prop( %s, %d, [%s], NaN, %s);', inputname(1), ... typecomp, int2str(chanorcomp), vararg2str( { spec_opt } )); return; end; if chanorcomp < 1 | chanorcomp > EEG.nbchan % should test for > number of components ??? -sm error('Component index out of range'); end; % assumed input is chanorcomp % ------------------------- try, icadefs; catch, BACKCOLOR = [0.8 0.8 0.8]; GUIBUTTONCOLOR = [0.8 0.8 0.8]; end; basename = [fastif(typecomp,'Channel ', 'Component ') int2str(chanorcomp) ]; fhandle = figure('name', ['pop_prop() - ' basename ' properties'], 'color', BACKCOLOR, 'numbertitle', 'off', 'visible', 'off'); pos = get(fhandle,'Position'); set(fhandle,'Position', [pos(1) pos(2)-500+pos(4) 500 500], 'visible', 'on'); hh = axes('parent',fhandle); pos = get(hh,'position'); % plot relative to current axes q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]./100; axis(hh,'off'); % plotting topoplot % ----------------- h = axes('parent',fhandle,'Units','Normalized', 'Position',[-10 60 40 42].*s+q); %topoplot( EEG.icawinv(:,chanorcomp), EEG.chanlocs); axis square; if isfield(EEG.chanlocs, 'theta') if typecomp == 1 % plot single channel locations topoplot( chanorcomp, EEG.chanlocs, 'chaninfo', EEG.chaninfo, ... 'electrodes','off', 'style', 'blank', 'emarkersize1chan', 12); axis square; else % plot component map topoplot( EEG.icawinv(:,chanorcomp), EEG.chanlocs, 'chaninfo', EEG.chaninfo, ... 'shading', 'interp', 'numcontour', 3); axis square; end; else axis(h,'off'); end; basename = [fastif(typecomp,'Channel ', 'IC') int2str(chanorcomp) ]; % title([ basename fastif(typecomp, ' location', ' map')], 'fontsize', 14); title(basename, 'fontsize', 14); % plotting erpimage % ----------------- hhh = axes('Parent', fhandle,'Units','Normalized', 'Position',[45 62 48 38].*s+q); eeglab_options; if EEG.trials > 1 % put title at top of erpimage axis(hhh,'off'); hh = axes('Parent', fhandle,'Units','Normalized', 'Position',[45 62 48 38].*s+q); EEG.times = linspace(EEG.xmin, EEG.xmax, EEG.pnts); if EEG.trials < 6 ei_smooth = 1; else ei_smooth = 3; end if typecomp == 1 % plot channel offset = nan_mean(EEG.data(chanorcomp,:)); erp=nan_mean(squeeze(EEG.data(chanorcomp,:,:))')-offset; erp_limits=get_era_limits(erp); erpimage( EEG.data(chanorcomp,:)-offset, ones(1,EEG.trials)*10000, EEG.times*1000, ... '', ei_smooth, 1, 'caxis', 2/3, 'cbar','erp','erp_vltg_ticks',erp_limits); else % plot component icaacttmp = eeg_getdatact(EEG, 'component', chanorcomp); offset = nan_mean(icaacttmp(:)); era = nan_mean(squeeze(icaacttmp)')-offset; era_limits = get_era_limits(era); erpimage( icaacttmp-offset, ones(1,EEG.trials)*10000, EEG.times*1000, ... '', ei_smooth, 1, 'caxis', 2/3, 'cbar','erp', 'yerplabel', '','erp_vltg_ticks',era_limits); end; axes(hhh); title(sprintf('%s activity \\fontsize{10}(global offset %3.3f)', basename, offset), 'fontsize', 14); else % put title at top of erpimage EI_TITLE = 'Continous data'; axis(hhh,'off'); hh = axes('Parent', fhandle,'Units','Normalized', 'Position',[45 62 48 38].*s+q); ERPIMAGELINES = 200; % show 200-line erpimage while size(EEG.data,2) < ERPIMAGELINES*EEG.srate ERPIMAGELINES = 0.9 * ERPIMAGELINES; end ERPIMAGELINES = round(ERPIMAGELINES); if ERPIMAGELINES > 2 % give up if data too small if ERPIMAGELINES < 10 ei_smooth = 1; else ei_smooth = 3; end erpimageframes = floor(size(EEG.data,2)/ERPIMAGELINES); erpimageframestot = erpimageframes*ERPIMAGELINES; eegtimes = linspace(0, erpimageframes-1, length(erpimageframes)); % 05/27/2014 Ramon: length(erpimageframes) by EEG.srate/1000 in eegtimes = linspace(0, erpimageframes-1, EEG.srate/1000); if typecomp == 1 % plot channel offset = nan_mean(EEG.data(chanorcomp,:)); % Note: we don't need to worry about ERP limits, since ERPs % aren't visualized for continuous data erpimage( reshape(EEG.data(chanorcomp,1:erpimageframestot),erpimageframes,ERPIMAGELINES)-offset, ones(1,ERPIMAGELINES)*10000, eegtimes , ... EI_TITLE, ei_smooth, 1, 'caxis', 2/3, 'cbar'); else % plot component icaacttmp = eeg_getdatact(EEG, 'component', chanorcomp); offset = nan_mean(icaacttmp(:)); erpimage(reshape(icaacttmp(:,1:erpimageframestot),erpimageframes,ERPIMAGELINES)-offset,ones(1,ERPIMAGELINES)*10000, eegtimes , ... EI_TITLE, ei_smooth, 1, 'caxis', 2/3, 'cbar','yerplabel', ''); end else axis(hh,'off'); text(0.1, 0.3, [ 'No erpimage plotted' 10 'for small continuous data']); end; axes(hhh); end; % plotting spectrum % ----------------- if ~exist('winhandle') winhandle = NaN; end; if ishandle(winhandle) h = axes('Parent', fhandle,'units','normalized', 'position',[5 10 95 35].*s+q); else h = axes('Parent', fhandle,'units','normalized', 'position',[5 0 95 40].*s+q); end; %h = axes('units','normalized', 'position',[45 5 60 40].*s+q); try eeglab_options; if typecomp == 1 [spectra freqs] = spectopo( EEG.data(chanorcomp,:), EEG.pnts, EEG.srate, spec_opt{:} ); else if option_computeica [spectra freqs] = spectopo( EEG.icaact(chanorcomp,:), EEG.pnts, EEG.srate, 'mapnorm', EEG.icawinv(:,chanorcomp), spec_opt{:} ); else icaacttmp = (EEG.icaweights(chanorcomp,:)*EEG.icasphere)*reshape(EEG.data(EEG.icachansind,:,:), length(EEG.icachansind), EEG.trials*EEG.pnts); [spectra freqs] = spectopo( icaacttmp, EEG.pnts, EEG.srate, 'mapnorm', EEG.icawinv(:,chanorcomp), spec_opt{:} ); end; end; % set up new limits % ----------------- %freqslim = 50; %set(gca, 'xlim', [0 min(freqslim, EEG.srate/2)]); %spectra = spectra(find(freqs <= freqslim)); %set(gca, 'ylim', [min(spectra) max(spectra)]); %tmpy = get(gca, 'ylim'); %set(gca, 'ylim', [max(tmpy(1),-1) tmpy(2)]); set( get(h, 'ylabel'), 'string', 'Power 10*log_{10}(\muV^{2}/Hz)', 'fontsize', 14); set( get(h, 'xlabel'), 'string', 'Frequency (Hz)', 'fontsize', 14); title('Activity power spectrum', 'fontsize', 14); catch err axis off; text(0.1, 0.3, [ 'Error: no spectrum plotted' 10 err.message 10]); % lasterror % text(0.1, 0.3, [ 'Error: no spectrum plotted' 10 ' make sure you have the ' 10 'signal processing toolbox']); end; % display buttons % --------------- if ishandle(winhandle) COLREJ = '[1 0.6 0.6]'; COLACC = '[0.75 1 0.75]'; % CANCEL button % ------------- h = uicontrol(fhandle, 'Style', 'pushbutton', 'backgroundcolor', GUIBUTTONCOLOR, 'string', 'Cancel', 'Units','Normalized','Position',[-10 -10 15 6].*s+q, 'callback', 'close(gcf);'); % VALUE button % ------------- hval = uicontrol(fhandle, 'Style', 'pushbutton', 'backgroundcolor', GUIBUTTONCOLOR, 'string', 'Values', 'Units','Normalized', 'Position', [15 -10 15 6].*s+q); % REJECT button % ------------- if ~isempty(EEG.reject.gcompreject) status = EEG.reject.gcompreject(chanorcomp); else status = 0; end; hr = uicontrol(fhandle, 'Style', 'pushbutton', 'backgroundcolor', eval(fastif(status,COLREJ,COLACC)), ... 'string', fastif(status, 'REJECT', 'ACCEPT'), 'Units','Normalized', 'Position', [40 -10 15 6].*s+q, 'userdata', status, 'tag', 'rejstatus'); command = [ 'set(gcbo, ''userdata'', ~get(gcbo, ''userdata''));' ... 'if get(gcbo, ''userdata''),' ... ' set( gcbo, ''backgroundcolor'',' COLREJ ', ''string'', ''REJECT'');' ... 'else ' ... ' set( gcbo, ''backgroundcolor'',' COLACC ', ''string'', ''ACCEPT'');' ... 'end;' ]; set(hr, 'callback', command); % HELP button % ------------- h = uicontrol(fhandle, 'Style', 'pushbutton', 'backgroundcolor', GUIBUTTONCOLOR, 'string', 'HELP', 'Units','Normalized', 'Position', [65 -10 15 6].*s+q, 'callback', 'pophelp(''pop_prop'');'); % OK button % --------- command = [ 'global EEG;' ... 'tmpstatus = get( findobj(''parent'', gcbf, ''tag'', ''rejstatus''), ''userdata'');' ... 'EEG.reject.gcompreject(' num2str(chanorcomp) ') = tmpstatus;' ]; if winhandle ~= 0 if VERS < 8.04 command = [ command ... sprintf('if tmpstatus set(%3.15f, ''backgroundcolor'', %s); else set(%3.15f, ''backgroundcolor'', %s); end;', ... winhandle, COLREJ, winhandle, COLACC)]; elseif VERS >= 8.04 command = [ command ... sprintf('if tmpstatus set(findobj(''Tag'', ''%s''), ''backgroundcolor'', %s); else set(findobj(''Tag'',''%s''), ''backgroundcolor'', %s); end;', ... winhandle.Tag, COLREJ, winhandle.Tag, COLACC)]; end end; command = [ command 'close(gcf); clear tmpstatus' ]; h = uicontrol(fhandle, 'Style', 'pushbutton', 'string', 'OK', 'backgroundcolor', GUIBUTTONCOLOR, 'Units','Normalized', 'Position',[90 -10 15 6].*s+q, 'callback', command); % draw the figure for statistical values % -------------------------------------- index = num2str( chanorcomp ); command = [ ... 'figure(''MenuBar'', ''none'', ''name'', ''Statistics of the component'', ''numbertitle'', ''off'');' ... '' ... 'pos = get(gcf,''Position'');' ... 'set(gcf,''Position'', [pos(1) pos(2) 340 340]);' ... 'pos = get(gca,''position'');' ... 'q = [pos(1) pos(2) 0 0];' ... 's = [pos(3) pos(4) pos(3) pos(4)]./100;' ... 'axis off;' ... '' ... 'txt1 = sprintf(''(\n' ... 'Entropy of component activity\t\t%2.2f\n' ... '> Rejection threshold \t\t%2.2f\n\n' ... ' AND \t\t\t----\n\n' ... 'Kurtosis of component activity\t\t%2.2f\n' ... '> Rejection threshold \t\t%2.2f\n\n' ... ') OR \t\t\t----\n\n' ... 'Kurtosis distibution \t\t\t%2.2f\n' ... '> Rejection threhold\t\t\t%2.2f\n\n' ... '\n' ... 'Current thesholds sujest to %s the component\n\n' ... '(after manually accepting/rejecting the component, you may recalibrate thresholds for future automatic rejection on other datasets)'',' ... 'EEG.stats.compenta(' index '), EEG.reject.threshentropy, EEG.stats.compkurta(' index '), ' ... 'EEG.reject.threshkurtact, EEG.stats.compkurtdist(' index '), EEG.reject.threshkurtdist, fastif(EEG.reject.gcompreject(' index '), ''REJECT'', ''ACCEPT''));' ... '' ... 'uicontrol(gcf, ''Units'',''Normalized'', ''Position'',[-11 4 117 100].*s+q, ''Style'', ''frame'' );' ... 'uicontrol(gcf, ''Units'',''Normalized'', ''Position'',[-5 5 100 95].*s+q, ''String'', txt1, ''Style'',''text'', ''HorizontalAlignment'', ''left'' );' ... 'h = uicontrol(gcf, ''Style'', ''pushbutton'', ''string'', ''Close'', ''Units'',''Normalized'', ''Position'', [35 -10 25 10].*s+q, ''callback'', ''close(gcf);'');' ... 'clear txt1 q s h pos;' ]; set( hval, 'callback', command); if isempty( EEG.stats.compenta ) set(hval, 'enable', 'off'); end; com = sprintf('pop_prop( %s, %d, %d, 0, %s);', inputname(1), typecomp, chanorcomp, vararg2str( { spec_opt } ) ); else com = sprintf('pop_prop( %s, %d, %d, NaN, %s);', inputname(1), typecomp, chanorcomp, vararg2str( { spec_opt } ) ); end; return; function out = nan_mean(in) nans = find(isnan(in)); in(nans) = 0; sums = sum(in); nonnans = ones(size(in)); nonnans(nans) = 0; nonnans = sum(nonnans); nononnans = find(nonnans==0); nonnans(nononnans) = 1; out = sum(in)./nonnans; out(nononnans) = NaN; function era_limits=get_era_limits(era) %function era_limits=get_era_limits(era) % % Returns the minimum and maximum value of an event-related % activation/potential waveform (after rounding according to the order of % magnitude of the ERA/ERP) % % Inputs: % era - [vector] Event related activation or potential % % Output: % era_limits - [min max] minimum and maximum value of an event-related % activation/potential waveform (after rounding according to the order of % magnitude of the ERA/ERP) mn=min(era); mx=max(era); mn=orderofmag(mn)*round(mn/orderofmag(mn)); mx=orderofmag(mx)*round(mx/orderofmag(mx)); era_limits=[mn mx]; function ord=orderofmag(val) %function ord=orderofmag(val) % % Returns the order of magnitude of the value of 'val' in multiples of 10 % (e.g., 10^-1, 10^0, 10^1, 10^2, etc ...) % used for computing erpimage trial axis tick labels as an alternative for % plotting sorting variable val=abs(val); if val>=1 ord=1; val=floor(val/10); while val>=1, ord=ord*10; val=floor(val/10); end return; else ord=1/10; val=val*10; while val<1, ord=ord/10; val=val*10; end return; end
github
lcnhappe/happe-master
eeg_getepochevent.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_getepochevent.m
11,756
utf_8
5ea09aae0a884131df8e8c4e1d238cf3
% eeg_getepochevent() - Return dataset event field values for all events % of one or more specified types % Usage: % >> epochval = eeg_getepochevent( EEG ); % >> epochval = eeg_getepochevent( EEG, 'key', 'val'); % % Inputs: % EEG - Input dataset % % Optional inputs: % 'type' - String containing an event type. Cell array of string % may be used to select several event types; % {} is all types of events. Note: Requires that % a field named 'type' is defined in 'EEG.event'. % 'timewin' - [start end] Event time window in milliseconds % (default []=whole epoch). % 'fieldname' - Name of the field to return the values for. % Default field is 'EEG.event.latency' in milliseconds % (though internally this information is stored in % real frames). % 'trials' - [integer array] return values only for selected trials. % % Outputs: % epochval - A value of the selected field for each epoch. This is % NaN if no selected event occurred during the epoch. If % several values are available for each epoch, only the % first one is taken into consideration. % Latencies are measured in msec relative to epoch onset. % Forced to be numerical, where a string is converted by % double to its ascii number which is normalized to be % between 0 and 1, and the string is summed together. See % the subfunction ascii2num for more details. % allepochval - cell array with same length as the number of epoch % containing all values for all epochs. This output is % usefull when several value are found within each epoch. % Not forced to be numerical. % % Notes: 1) Each epoch structure refers to the events that occurred % during its time window. This function allows the user to return % specified field values for a subset of the defined events. % % 2) If several of the selected events occur during a single epoch, % a warning is issued, and value of ONLY THE FIRST event in the epoch % is returned. % % If NO EVENT is selected in a given epoch, the value returned % is NaN. % % 3) If the user elects to return the latency field, eeg_getepochevent() % recomputes the latency of each event relative to the epoch time % limits. % % Example: % >> latencies = eeg_getepochevent(EEG, 'rt'); % % Return the latencies (by default) in milliseconds of events having % % type 'rt' (reaction time) % % >> latencies = eeg_getepochevent(EEG, {'target','rare'}, [0 300], 'position'); % % Return the position (field 'position') of 'target' or 'rare' type % % events occurring between 0 and 300 milliseconds of each epoch. % % Returns NaN for epochs with no such events. (See Notes above). % % Author: Arnaud Delorme & Scott Makeig, CNL / Salk Institute, 15 Feb 2002 % % See also: eeglab(), epoch() % Copyright (C) 15 Feb 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 02/15/02 modified function according to new event structure -ad function [epochval, allepochval] = eeg_getepochevent(EEG, varargin); if nargin < 2 help eeg_getepochevent; return; end; % process more than one EEG dataset (for STUDY purposes) % ------------------------------------------------------ if length(EEG) > 1 % the trial input may be a cell array; it has to be % extracted before calling the function on each dataset trials = cell(1,length(EEG)); for iArg = length(varargin)-1:-2:1 if strcmpi(varargin{iArg}, 'trials') trials = varargin{iArg+1}; varargin(iArg:iArg+1) = []; end; end; epochval = []; for dat = 1:length(EEG) tmpepochval = eeg_getepochevent(EEG(dat), 'trials', trials{dat}, varargin{:}); epochval = [ epochval tmpepochval ]; end; return; end; % deal with old input format % ------------------------- options = {}; oldformat = 0; if nargin < 3 oldformat = 1; elseif isnumeric(varargin{2}) && length(varargin{2}) == 2 oldformat = 1; elseif length(varargin) == 3 && isfield(EEG.event,varargin(3)) oldformat = 1; end; if oldformat if nargin > 1, options = { options{:} 'type' varargin{1} }; end; if nargin > 2, options = { options{:} 'timewin' varargin{2} }; end; if nargin > 3, options = { options{:} 'fieldname' varargin{3} }; end; else options = varargin; end; opt = finputcheck(options, { 'type' { 'string';'cell' } { [] [] } ''; 'timewin' 'real' [] [-Inf Inf]; 'fieldname' 'string' [] 'latency'; 'trials' { 'real';'cell' } [] [] }, 'eeg_getepochevent'); if isstr(opt), error(opt); end; if iscell(opt.trials) && ~isempty(opt.trials), opt.trials = opt.trials{1}; end; if isempty(opt.timewin) opt.timewin = [-Inf Inf]; end; if isempty(EEG.event) disp('Getepochevent: no event structure, aborting.'); return; end; % check if EEG.epoch contain references to events % ----------------------------------------------- if ~isfield( EEG.event, 'epoch' ) disp('Getepochevent: no epoch indices in events, considering continuous values.'); end; % check if EEG.epoch and EEG.event contains 'latency' field % ------------------------------------------ if ~isfield( EEG.event, opt.fieldname) disp(['Getepochevent: no ''' opt.fieldname ''' field in events, aborting.']); return; end; % deal with empty types % --------------------- if ~isempty(opt.type) & ~iscell(opt.type) opt.type = { opt.type }; end; % convert types % ------------- for indextype=1:length(opt.type) if isstr(opt.type{indextype}) & isnumeric(EEG.event(1).type) if ~isempty(str2num(opt.type{indextype})) opt.type{indextype} = str2num(opt.type{indextype}); else error('eeg_getepochevent: string type cannot be found in numeric event type array'); end; elseif isnumeric(opt.type{indextype}) & isstr(EEG.event(1).type) opt.type{indextype} = num2str(opt.type{indextype}); end; end; % select epochs % ------------- if ~isempty(opt.type) Ieventtmp = []; tmpevent = EEG.event; for indextype=1:length(opt.type) typeval = opt.type{indextype}; if isstr(typeval) Ieventtmp = [Ieventtmp strmatch(typeval, { tmpevent.type }, 'exact')' ]; else Ieventtmp = [Ieventtmp find(typeval == [ tmpevent.type ] ) ]; end; end; else Ieventtmp = [1:length(EEG.event)]; end; % select latencies % ---------------- if isfield(EEG.event, 'latency') & (opt.timewin(1) ~= -Inf | opt.timewin(2) ~= Inf) selected = ones(size(Ieventtmp)); for index=1:length(Ieventtmp) if ~isfield(EEG.event, 'epoch'), epoch = 1; else epoch = EEG.event(Ieventtmp(index)).epoch; end; reallat = eeg_point2lat(EEG.event(Ieventtmp(index)).latency, epoch, ... EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3); if reallat < opt.timewin(1) | reallat > opt.timewin(2) selected(index) = 0; end; end; Ieventtmp = Ieventtmp( find(selected == 1) ); end; % select events % ------------- epochval = cell(1,EEG.trials); epochval(:) = { nan }; allepochval = cell(1, EEG.trials); allepochval(:) = { {} }; if strcmp(opt.fieldname, 'latency') for index = 1:length(Ieventtmp) if ~isfield(EEG.event, 'epoch'), epoch = 1; else epoch = EEG.event(Ieventtmp(index)).epoch; end; allepochval{epoch}{end+1} = eeg_point2lat(EEG.event(Ieventtmp(index)).latency, epoch, ... EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3); if length(allepochval{epoch}) == 1 epochval{epoch} = allepochval{epoch}{end}; else if length(allepochval{epoch}) == 2 & nargout < 2 disp(['Warning: multiple event latencies found in epoch ' int2str(epoch) ]); %, ignoring event ' int2str(Ieventtmp(index)) ' (''' num2str(EEG.event(Ieventtmp(index)).type) ''' type)' ]); end; end; end; elseif strcmp(opt.fieldname, 'duration') for index = 1:length(Ieventtmp) eval( [ 'val = EEG.event(Ieventtmp(index)).' opt.fieldname ';']); if ~isempty(val) if ~isfield(EEG.event, 'epoch'), epoch = 1; else epoch = EEG.event(Ieventtmp(index)).epoch; end; epochval{epoch} = val/EEG.srate*1000; allepochval{epoch}{end+1} = val/EEG.srate*1000; end; end; else for index = 1:length(Ieventtmp) eval( [ 'val = EEG.event(Ieventtmp(index)).' opt.fieldname ';']); if ~isempty(val) if isstr(val) val = ascii2num(val); %val_tmp = double(val); % force epochval output to be numerical % **Turn string into number that will sort in alphebetical order** %val = 0; %for val_count = 1:length(val_tmp) % -48 so that '1' is scaled to ascii number 1, not 49 % /74 to scale double('z')=122 to 1 % 10^((2-... scale to 0 to 100milliseconds % val = val + (val_tmp(val_count)-48)/74*10^(2-(val_count-1)); %end % **End turn string ...** end if ~isfield(EEG.event, 'epoch'), epoch = 1; else epoch = EEG.event(Ieventtmp(index)).epoch; end epochval{epoch} = val(1); allepochval{epoch}{end+1} = val(1); end; end; end; if isnumeric(epochval{1}) try epochval = [ epochval{:} ]; for index = 1:length(allepochval) allepochval{index} = [ allepochval{index}{:} ]; end catch end end % select specific trials if ~isempty(opt.trials) epochval = epochval(opt.trials); allepochval = allepochval(opt.trials); end; %% SUBFUNCTION ASCII2NUM % Maps ascii characters ['0','9'] to [1, 10], ['a','z'] to [11, 36] % This is intended for alphebetically sorting string arrays numerically % ascii_in [string array] % output [double] function out = ascii2num(ascii_in) ascii_vector = double(ascii_in); out = 0; % go through each character in the string and scale and add it to output for val_count = 1:length(ascii_vector) ascii_char = ascii_vector(val_count); if ascii_char>=48 & ascii_char<=57 % ['0','9'] to [1, 10] ascii_adj = ascii_char - 47; elseif ascii_char>=65 & ascii_char<=90 % ['A','Z'] to [11, 36] ascii_adj = ascii_char - 64; elseif ascii_char>=97 & ascii_char<=122 % ['a','z'] to [11, 36] ascii_adj = ascii_char - 96; else ascii_adj = ascii_char; end out = out + ascii_adj/36^val_count; end
github
lcnhappe/happe-master
eeg_timeinterp.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_timeinterp.m
3,370
utf_8
365cfdc876b172e03a77db2833308aee
% eeg_timeinterp() - perform spline interpolation of a portion % of data based on prior and post activity. See % eeg_interp() for interpolation of bad channels. % % Usage: % >> OUTEEG = eeg_timeinterp( INEEG, samples, 'key', 'val'); % % Inputs: % INEEG - input EEG structure % samplerange - [min max] range sample points in continuous % or epoched data. Only one sample point range % may be given at a time. % % Optional inputs: % 'elecinds' - indices of electrodes to interpolate (default all) % 'epochinds' - indices of epochs for epoched data (default all) % 'interpwin' - [integer] number of data points to use before and % after the sample range. Default is 5 times the % interpolated sample range. % 'epochcont' - ['on'|'off'] epochs are contiguous. Only works for % interpolating the end of epochs (default 'off') % % Outputs: % OUTEEG - EEGLAB data structure % % Author: Arnaud Delorme, SCCN/INC/UCSD, 2007 % Copyright (C) Arnaud Delorme, SCCN/INC/UCSD, 2007 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function EEG = eeg_timeinterp( EEG, samples, varargin); if nargin < 2 help eeg_timeinterp; return; end; opt = finputcheck(varargin, { 'epochinds' 'integer' [] [1:EEG.trials]; ... 'interpwin' 'integer' [] 5; ... 'elecinds' 'integer' [] [1:EEG.nbchan]; ... 'epochcont' 'string' { 'on';'off' } 'off' }, 'eeg_timeinterp'); if isstr(opt), error(opt); end; srange = samples(2)-samples(1); data = EEG.data; pnts = EEG.pnts; if strcmpi(opt.epochcont, 'on') data(:,end+1:end+srange*opt.interpwin,1:end-1) = data(:,1:srange*opt.interpwin,2:end); pnts = pnts + srange*opt.interpwin; end; % determine region to interpolate % and region to use for interpolation % ----------------------------------- samplesin = [min(samples(1)-srange*opt.interpwin,1):samples(1)-1 samples(2)+1:min(samples(2)+srange*opt.interpwin, pnts)]; samplesout = [samples(1):samples(2)]; if length(opt.epochinds) > 1, fprintf('Trials:'); end; for index = opt.epochinds for elec = opt.elecinds EEG.data(elec,samplesout,index) = spline( samplesin, data(elec, samplesin, index), samplesout); end; if length(opt.epochinds) > 1, fprintf('.'); if mod(index,40) == 01, fprintf('\n'); end; end; end; if length(opt.epochinds) > 1, fprintf('\n'); end;
github
lcnhappe/happe-master
pop_comments.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_comments.m
5,327
utf_8
e203d4a9ef43004035f13e5afe147831
% pop_comments() - edit comments % % Usage: % >> newcomments = pop_comments( oldcomments); % >> newcomments = pop_comments( oldcomments, title, newcomments, concat); % % Inputs: % oldcomments - old comments (string or cell array of strings) % title - optional window title (string) % newcomments - new comments (string or cell array of strings) % to assign (during commandline calls only) % concat - [0|1] 1 concatenate the newcomments to the old one. % Default is 0. % % Outputs: % newcomments - new comments, string % % Note: if new comments are given as input, there are simply % converted and returned by the function; otherwise a % window pops up. % % Example % EEG.comments = pop_comments( { 'This is the first line.' ' ' ... % 'This is the third line.' }, 'Editing'); % EEG.comments = pop_comments(EEG.comments,'','This is the fourth line.",1); % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-16-02 text interface editing -sm & ad function [newcomments, com] = pop_comments( comments, plottitle, newcomments, concat ); com = ''; if exist('comments') ~=1, comments = ''; elseif iscell(comments), comments = strvcat(comments{:}); end; % remove trailing blanks and make multiline comments = strmultiline( comments, 53); if nargin < 3 newcomments = comments; try, icadefs; catch, BACKCOLOR = [.8 .8 .8]; GUIBUTTONCOLOR = [.8 .8 .8]; end; figure('menubar', 'none', 'tag', 'comment', 'color', BACKCOLOR, 'userdata', 0, ... 'numbertitle', 'off', 'name', 'Read/Enter comments -- pop_comments()'); pos = get(gca,'position'); % plot relative to current axes q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]./100; if exist('plottitle') ~=1, plottitle = ''; end; h = title(plottitle); set(h, 'fontname','Helvetica','fontweight', 'bold', 'interpreter', 'none'); axis off; % create the buttons % ------------------ uicontrol('Parent',gcf, ... 'Units','Normalized', ... 'Position', [0 -5 20 10].*s+q, ... 'backgroundcolor', GUIBUTTONCOLOR, ... 'string','CANCEL', 'callback', 'close(findobj(''tag'', ''comment''));' ); uicontrol('Parent',gcf, ... 'Units','Normalized', ... 'Position', [80 -5 20 10].*s+q, ... 'backgroundcolor', GUIBUTTONCOLOR, ... 'string','SAVE', 'callback', ... [ 'set(gcbf, ''userdata'', ' ... 'get(findobj(''parent'', gcbf, ''tag'', ''edit''), ''string''));' ]); %hh = text( q(1), 100*s(2)+q(2), comments, 'tag', 'edit'); %set( hh, 'editing', 'on', 'verticalalignment', 'top'); %hh = uicontrol('Parent',gcf, ... %'Units','Normalized', ... %'style', 'text', ... %'Position', [0 100 105 5].*s+q, ... %'string', 'Warning: each blank line must contain at least a ''space'' character', ... %'horizontalalignment', 'left', ... %'backgroundcolor', BACKCOLOR ); hh = uicontrol('Parent',gcf, ... 'Units','Normalized', ... 'style', 'edit', ... 'tag', 'edit', ... 'Position', [0 10 105 85].*s+q, ... 'string', comments, ... 'backgroundcolor', [ 1 1 1], ... 'horizontalalignment', 'left', ... 'max', 3, ... 'fontsize', 12); % Try to use 'courier' since it has constant character size lf = listfonts; tmppos = strmatch('Courier', lf); if ~isempty(tmppos) set(hh, 'fontname', lf{tmppos(1)}, 'fontsize', 10); end; waitfor(gcf, 'userdata'); % find return mode if isempty(get(0, 'currentfigure')), return; end; tmp = get(gcf, 'userdata'); if ~isempty(tmp) & isstr(tmp) newcomments = tmp; % ok button else return; end; close(findobj('tag', 'comment')); else if iscell(newcomments) newcomments = strvcat(newcomments{:}); end; if nargin > 3 & concat == 1 newcomments = strvcat(comments, newcomments); end; return; end; I = find( comments(:) == ''''); comments(I) = ' '; if nargout > 1 if ~strcmp( comments, newcomments) allsame = 1; for index = 1:size(comments, 1) if ~strcmp(comments(index,:), newcomments(index,:)), allsame = 0; end; end; else allsame = 0; end; if allsame & ~isempty(comments) com =sprintf('EEG.comments = pop_comments(EEG.comments, '''', %s, 1);', vararg2str(newcomments(index+1:end,:))); else com =sprintf('EEG.comments = pop_comments('''', '''', %s);', vararg2str(newcomments)); end; end; return;
github
lcnhappe/happe-master
eeg_emptyset.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_emptyset.m
2,505
utf_8
a93f07a3989f904c1eade15794aab1f1
% eeg_emptyset() - Initialize an EEG dataset structure with default values. % % Usage: % >> EEG = eeg_emptyset(); % % Outputs: % EEG - empty dataset structure with default values. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad function EEG = eeg_emptyset(); EEG.setname = ''; EEG.filename = ''; EEG.filepath = ''; EEG.subject = ''; EEG.group = ''; EEG.condition = ''; EEG.session = []; EEG.comments = ''; EEG.nbchan = 0; EEG.trials = 0; EEG.pnts = 0; EEG.srate = 1; EEG.xmin = 0; EEG.xmax = 0; EEG.times = []; EEG.data = []; EEG.icaact = []; EEG.icawinv = []; EEG.icasphere = []; EEG.icaweights = []; EEG.icachansind = []; EEG.chanlocs = []; EEG.urchanlocs = []; EEG.chaninfo = []; EEG.ref = []; EEG.event = []; EEG.urevent = []; EEG.eventdescription = {}; EEG.epoch = []; EEG.epochdescription = {}; EEG.reject = []; EEG.stats = []; EEG.specdata = []; EEG.specicaact = []; EEG.splinefile = ''; EEG.icasplinefile = ''; EEG.dipfit = []; EEG.history = ''; EEG.saved = 'no'; EEG.etc = []; %EEG.reject.threshold = [1 0.8 0.85]; %EEG.reject.icareject = []; %EEG.reject.compreject = []; %EEG.reject.gcompreject= []; %EEG.reject.comptrial = []; %EEG.reject.sigreject = []; %EEG.reject.elecreject = []; %EEG.stats.kurta = []; %EEG.stats.kurtr = []; %EEG.stats.kurtd = []; %EEG.stats.eegentropy = []; %EEG.stats.eegkurt = []; %EEG.stats.eegkurtg = []; %EEG.stats.entropy = []; %EEG.stats.kurtc = []; %EEG.stats.kurtt = []; %EEG.stats.entropyc = []; return;
github
lcnhappe/happe-master
pop_eventstat.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_eventstat.m
4,984
utf_8
a4b8019a80d3c517ad7407e9b6906815
% pop_eventstat() - Computes and plots statistical characteristics of an EEG event, % including the data histogram, a fitted normal distribution, % a normal ditribution fitted on trimmed data, a boxplot, and % the QQ-plot. The estimates value are printed in a panel and % can be read as output. NaNs are omitted. See signalstat(). % % Usage: % >> OUTEEG = pop_eventstat( EEG ); % pops up % >> [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh] = pop_eventstat( EEG, eventfield, type ); % >> [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh] = pop_eventstat( EEG, eventfield, type, percent ); % % Inputs: % EEG - input EEG dataset % eventfield - event field to process (i.e. latency) % type - name of the event type(s) to process. Can be a single element or % a cell array. Default is all types. % latrange - [min max] event latency range within data epochs in milliseconds. % Default is whole epoch. % percent - percentage for trimmed data statistics. Default is 5%. (see signalstat()) % % Outputs: % OUTEEG - output dataset % % Author: Arnaud Delorme & Luca Finelli, CNL / Salk Institute - SCCN, 15 August 2002 % % See also: signalstat(), eeg_getepochevent(), eeglab() % Copyright (C) 2002 Arnaud Delorme & Luca Finelli, Salk/SCCN, La Jolla, CA % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function varargout = pop_eventstat( EEG, eventfield, type, latrange, percent ); % the command output is a hidden output that does not have to % be described in the header com = ''; % this initialization ensure that the function will return something % if the user press the cancel button varargout{1} = ''; % display help if not enough arguments % ------------------------------------ if nargin < 1 help pop_eventstat; return; end; popup=0; if nargin < 2 popup = 1; end; if nargin < 3 percent=5; end; % pop up window % ------------- if nargin < 2 promptstr = { 'Event field to process:' ... strvcat('Event type(s) ([]=all):', ... 'Select "Edit > Event values" to see type values') ... strvcat('Event latency range (ms)', ... 'Default is whole epoch or data') ... 'Percent for trimmed statistics:' }; inistr = { 'latency' '' '' '5' }; result = inputdlg2( promptstr, 'Plot event statistics -- pop_eventstat()', 1, inistr, 'signalstat'); if length( result ) == 0 return; end; eventfield = deblank(result{1}); % the brackets allow to process matlab arrays if ~isempty(result{2}) if strcmpi(result{2}(1),'''') type = eval( [ '{' result{2} '}' ] ); else type = parsetxt( result{2}); end; else disp('WARNING: you should select an event type'); type = {}; end; latrange = eval( [ '[' result{3} ']' ] ); percent = eval( [ '[' result{4} ']' ] ); else if nargin < 3 type = []; end; if nargin < 4 latrange = []; end; if nargin < 5 percent = 5; end; end; % call function signalstat() either on raw data or ICA data % --------------------------------------------------------- [ typevals alltypevals ] = eeg_getepochevent(EEG, type, latrange, eventfield); % concatenate alltypevals % ----------------------- typevals = []; for index = 1:length(alltypevals) typevals = [ typevals alltypevals{index} ]; end; if isempty(typevals) error('No such events found. See Edit > Event values to confirm event type.'); end; dlabel='Event values'; if isempty(type) dlabel2=['All event statistics for ''' eventfield ''' info']; else dlabel2=['Event ' vararg2str(type) ' statistics for ''' eventfield ''' info']; end; % outputs % ------- outstr = ''; if ~popup for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end; if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end; end; % return the string command % ------------------------- fprintf('pop_eventstat: extracting events...\n'); varargout{1} = sprintf('pop_eventstat( %s, %s );', inputname(1), vararg2str({eventfield type latrange percent})); com = sprintf('%s signalstat( typevals, 1, dlabel, percent, dlabel2 ); %s', outstr); eval(com) try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; return;
github
lcnhappe/happe-master
getchanlist.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/getchanlist.m
2,052
utf_8
12fe9861407f310f8b008f835753091b
% getchanlist() - Obtain indices of specified channel types. % % Usage: % >> chanlist = getchanlist(chanlocs, type) % % Inputs: % chanlocs - EEGLAB channel location structure % type - [string] select channel of specified type % can enter a cell array to select several channel types % % Output: % chanlist - list of channel indices for the selected type(s) % sorted in increasing order % % Note: this function is not case sensitive % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2004 % % See also: pop_chanedit() % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, 2004 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function chanlist = getchanlist(chanlocs, type) if nargin < 1 help getchanlist; return; end; if nargin < 2 || ~isfield(chanlocs, 'type') chanlist = [1:length(chanlocs)]; return; end; % search channel types % -------------------- if isstr(type), type = { type }; end; type = lower(type); chanlist = []; alltypes = lower({ chanlocs.type }); for index = 1:length(type) tmplist = strmatch(type{index}, alltypes, 'exact'); if isempty(tmplist) fprintf('Warning: no channel of type ''%s'' found\n', type{index}); end; chanlist = [ chanlist tmplist' ]; end; chanlist = sort(chanlist);
github
lcnhappe/happe-master
pop_biosig.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_biosig.m
11,163
utf_8
6ee00ab65985120e56281589f761e898
% pop_biosig() - import data files into EEGLAB using BIOSIG toolbox % % Usage: % >> OUTEEG = pop_biosig; % pop up window % >> OUTEEG = pop_biosig( filename, channels, type); % % Inputs: % filename - [string] file name % % Optional inputs: % 'channels' - [integer array] list of channel indices % 'blockrange' - [min max] integer range of data blocks to import, in seconds. % Entering [0 3] will import the first three blocks of data. % Default is empty -> import all data blocks. % 'importevent' - ['on'|'off'] import events. Default if 'on'. % 'importannot' - ['on'|'off'] import annotations (EDF+ only). Default if 'on' % 'blockepoch' - ['on'|'off'] force importing continuous data. Default is 'on' % 'ref' - [integer] channel index or index(s) for the reference. % Reference channels are not removed from the data, % allowing easy re-referencing. If more than one % channel, data are referenced to the average of the % indexed channels. WARNING! Biosemi Active II data % are recorded reference-free, but LOSE 40 dB of SNR % if no reference is used!. If you do not know which % channel to use, pick one and then re-reference after % the channel locations are read in. {default: none}. % For more information see http://www.biosemi.com/faq/cms&drl.htm % 'refoptions' - [Cell] Option for the pop_reref function. Default is to % remove the reference channel if there is one of them and to % keep it if there are several of them from the graphic % interface. From the command line default option is to % keep the reference channel. % 'rmeventchan' - ['on'|'off'] remove event channel after event % extraction. Default is 'on'. % 'memorymapped' - ['on'|'off'] import memory mapped file (useful if % encountering memory errors). Default is 'off'. % % Outputs: % OUTEEG - EEGLAB data structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, Oct. 29, 2003- % % Note: BIOSIG toolbox must be installed. Download BIOSIG at % http://biosig.sourceforge.net % Contact [email protected] for troubleshooting using BIOSIG. % Copyright (C) 2003 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, command, dat] = pop_biosig(filename, varargin); EEG = []; command = ''; if ~plugin_askinstall('Biosig', 'sopen'), return; end; biosigpathfirst; if nargin < 1 % ask user [filename, filepath] = uigetfile('*.*', 'Choose a data file -- pop_biosig()'); %%% this is incorrect in original version!!!!!!!!!!!!!! drawnow; if filename == 0 return; end; filename = [filepath filename]; % look if MEG % ----------- if length(filepath)>4 if strcmpi(filepath(end-3:end-1), '.ds'), filename = filepath(1:end-1); end; end; % open file to get infos % ---------------------- disp('Reading data file header...'); dat = sopen(filename, 'r', [], 'OVERFLOWDETECTION:OFF'); if ~isfield(dat, 'NRec') error('Unsuported data format'); end; % special BIOSEMI % --------------- eeglab_options; if strcmpi(dat.TYPE, 'BDF') disp(upper('We highly recommend that you choose a reference channel IF these are Biosemi data')); disp(upper('(e.g., a mastoid or other channel). Otherwise the data will lose 40 dB of SNR!')); disp('For more information, see <a href="http://www.biosemi.com/faq/cms&drl.htm">http://www.biosemi.com/faq/cms&drl.htm</a>'); end; uilist = { { 'style' 'text' 'String' 'Channel list (defaut all):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'String' [ 'Data range (in seconds) to read (default all [0 ' int2str(dat.NRec) '])' ] } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'String' 'Extract event' } ... { 'style' 'checkbox' 'string' '' 'value' 1 'enable' 'on' } {} ... { 'style' 'text' 'String' 'Import anotations (EDF+ only)' } ... { 'style' 'checkbox' 'string' '' 'value' 1 'enable' 'on' } {} ... { 'style' 'text' 'String' 'Force importing continuous data' 'value' 1} ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'String' 'Reference chan(s) indices - required for BIOSEMI' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'checkbox' 'String' 'Import as memory mapped file (use if out of memory error)' 'value' option_memmapdata } }; geom = { [3 1] [3 1] [3 0.35 0.5] [3 0.35 0.5] [3 0.35 0.5] [3 1] [1] }; result = inputgui( geom, uilist, 'pophelp(''pop_biosig'')', ... 'Load data using BIOSIG -- pop_biosig()'); if length(result) == 0 return; end; % decode GUI params % ----------------- options = {}; if ~isempty(result{1}), options = { options{:} 'channels' eval( [ '[' result{1} ']' ] ) }; end; if ~isempty(result{2}), options = { options{:} 'blockrange' eval( [ '[' result{2} ']' ] ) }; end; if length(result) > 2 if ~result{3}, options = { options{:} 'importevent' 'off' }; end; if ~result{4}, options = { options{:} 'importannot' 'off' }; end; if result{5}, options = { options{:} 'blockepoch' 'off' }; end; if ~isempty(result{6}), options = { options{:} 'ref' eval( [ '[' result{6} ']' ] ) }; end; if result{7}, options = { options{:} 'memorymapped' 'on' }; end; end; if length(eval( [ '[' result{6} ']' ] )) > 1 options = { options{:} 'refoptions' { 'keepref' 'off' } }; end; else options = varargin; end; % decode imput parameters % ----------------------- g = finputcheck( options, { 'blockrange' 'integer' [0 Inf] []; 'channels' 'integer' [0 Inf] []; 'ref' 'integer' [0 Inf] []; 'refoptions' 'cell' {} { 'keepref' 'on' }; 'rmeventchan' 'string' { 'on';'off' } 'on'; 'importevent' 'string' { 'on';'off' } 'on'; 'importannot' 'string' { 'on';'off' } 'on'; 'memorymapped' 'string' { 'on';'off' } 'off'; 'blockepoch' 'string' { 'on';'off' } 'off' }, 'pop_biosig'); if isstr(g), error(g); end; % import data % ----------- EEG = eeg_emptyset; [dat DAT interval] = readfile(filename, g.channels, g.blockrange, g.memorymapped); if strcmpi(g.blockepoch, 'off') dat.NRec = 1; end; EEG = biosig2eeglab(dat, DAT, interval, g.channels, strcmpi(g.importevent, 'on')); if strcmpi(g.rmeventchan, 'on') & strcmpi(dat.TYPE, 'BDF') & isfield(dat, 'BDF') if size(EEG.data,1) >= dat.BDF.Status.Channel, disp('Removing event channel...'); EEG.data(dat.BDF.Status.Channel,:) = []; if ~isempty(EEG.chanlocs) && length(EEG.chanlocs) >= dat.BDF.Status.Channel EEG.chanlocs(dat.BDF.Status.Channel) = []; end; end; EEG.nbchan = size(EEG.data,1); end; % rerefencing % ----------- if ~isempty(g.ref) disp('Re-referencing...'); EEG = pop_reref(EEG, g.ref, g.refoptions{:}); % EEG.data = EEG.data - repmat(mean(EEG.data(g.ref,:),1), [size(EEG.data,1) 1]); % if length(g.ref) == size(EEG.data,1) % EEG.ref = 'averef'; % end; % if length(g.ref) == 1 % disp([ 'Warning: channel ' int2str(g.ref) ' is now zeroed (but still present in the data)' ]); % else % disp([ 'Warning: data matrix rank has decreased through re-referencing' ]); % end; end; % test if annotation channel is present % ------------------------------------- if isfield(dat, 'EDFplus') && strcmpi(g.importannot, 'on') tmpfields = fieldnames(dat.EDFplus); for ind = 1:length(tmpfields) tmpdat = getfield(dat.EDFplus, tmpfields{ind}); if length(tmpdat) == EEG.pnts EEG.data(end+1,:) = tmpdat; EEG.nbchan = EEG.nbchan+1; if ~isempty(EEG.chanlocs) EEG.chanlocs(end+1).labels = tmpfields{ind}; end; end; end; end; % convert data to single if necessary % ----------------------------------- EEG = eeg_checkset(EEG,'makeur'); % Make EEG.urevent field EEG = eeg_checkset(EEG); % history % ------- if isempty(options) command = sprintf('EEG = pop_biosig(''%s'');', filename); else command = sprintf('EEG = pop_biosig(''%s'', %s);', filename, vararg2str(options)); end; % Checking if str2double is on top of the path biosigpathlast; % --------- % read data % --------- function [dat DAT interval] = readfile(filename, channels, blockrange, memmapdata); if isempty(channels), channels = 0; end; dat = sopen(filename, 'r', channels,'OVERFLOWDETECTION:OFF'); if strcmpi(memmapdata, 'off') fprintf('Reading data in %s format...\n', dat.TYPE); if ~isempty(blockrange) newblockrange = blockrange; % newblockrange = newblockrange*dat.Dur; DAT=sread(dat, newblockrange(2)-newblockrange(1), newblockrange(1)); else DAT=sread(dat, Inf);% this isn't transposed in original!!!!!!!! newblockrange = []; end sclose(dat); else fprintf('Reading data in %s format (file will be mapped to memory so this may take a while)...\n', dat.TYPE); inc = ceil(250000/(dat.NS*dat.SPR)); % 1Mb block if isempty(blockrange), blockrange = [0 dat.NRec]; end; blockrange(2) = min(blockrange(2), dat.NRec); allblocks = [blockrange(1):inc:blockrange(end)]; count = 1; for bind = 1:length(allblocks)-1 TMPDAT=sread(dat, (allblocks(bind+1)-allblocks(bind))*dat.Dur, allblocks(bind)*dat.Dur); if bind == 1 DAT = mmo([], [size(TMPDAT,2) (allblocks(end)-allblocks(1))*dat.SPR]); end; DAT(:,count:count+length(TMPDAT)-1) = TMPDAT'; count = count+length(TMPDAT); end; sclose(dat); end; if ~isempty(blockrange) interval(1) = blockrange(1) * dat.SampleRate(1) + 1; interval(2) = blockrange(2) * dat.SampleRate(1); else interval = []; end
github
lcnhappe/happe-master
pop_export.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_export.m
8,253
utf_8
d7e2bbf82fd68b8df5f65244d810f123
% pop_export() - export EEG dataset % % Usage: % >> com = pop_export(EEG); % a window pops up % >> com = pop_export(EEG, filename, 'key', 'val', ... ); % % Inputs: % EEG - eeglab dataset % filename - file name % % Optional inputs: % 'ica' - ['on'|'off'] export ICA activities (or ERP). Default 'off'. % 'time' - ['on'|'off'] include time values. Default 'on'. % 'timeunit' - [float] time unit rel. to seconds. Default: 1E-3 = msec. % 'elec' - ['on'|'off'] include electrodes names or component numbers. % Default 'on'. % 'transpose' - ['on'|'off'] 'off'-> electrode data = rows; 'on' -> electrode % data = columns. Default 'off'. % 'erp' - ['on'|'off'] export ERP instead of raw data. Default 'off'. % 'expr' - [string] evaluate epxression on data. The expression must % contain a variable 'x' representing the 2-D or 3-D % data. For example "x = 2*x" to multiply the data by 2. % 'precision' - [float] number of significant digits in output. Default 7. % Default of 7 should allow to reach about 23 to 24 bits % of precision and should be enough for EEG. % % Outputs: % com - The expresion that execute this function. i.e. 'pop_export(MyEEG, 'ExpEEG.mat')' % % Note: tabulation are used as a delimiter. % % Author: Arnaud Delorme, CNL / Salk Institute, May 13, 2003 % Copyright (C) May 13, 2003, Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function com = pop_export(EEG, filename, varargin); com = ''; if nargin < 1 help pop_export; return; end; if nargin < 2 commandload = [ '[filename, filepath] = uiputfile(''*'', ''Select a text file'');' ... 'if filename ~=0,' ... ' set(findobj(''parent'', gcbf, ''tag'', ''tagedit''), ''string'', [ filepath filename ]);' ... 'end;' ... 'clear filename filepath tagtest;' ]; uilist = { { 'style' 'text' 'string' 'Output file name' }, ... { 'style' 'edit' 'string' '' 'tag' 'tagedit' }, ... { 'style' 'pushbutton' 'string' 'Browse' 'callback' commandload },... { 'style' 'text' 'string' 'Export ICA activities instead of EEG data:' }, ... { 'style' 'checkbox' 'string' '' }, { },{ }, ... { 'style' 'text' 'string' 'Export ERP average instead of trials:' }, ... { 'style' 'checkbox' 'string' '' }, { }, { }, ... { 'style' 'text' 'string' 'Transpose matrix (elec -> rows):' }, ... { 'style' 'checkbox' 'string' '' }, { }, { }, ... { 'style' 'text' 'string' 'Export channel labels/component numbers:' }, ... { 'style' 'checkbox' 'string' '' 'value' 1 }, { }, { }, ... { 'style' 'text' 'string' 'Export time values:' }, ... { 'style' 'checkbox' 'string' '' 'value' 1 }, ... { 'style' 'text' 'string' 'Unit (re. sec)' }, { 'style' 'edit' 'string' '1E-3' }, ... { 'style' 'text' 'string' 'Number of significant digits to output:' }, ... { 'style' 'edit' 'string' '4' }, { }, { }, ... { 'style' 'text' 'string' 'Apply an expression to the output (see ''expr'' help):'} , ... { 'style' 'edit' 'string' '' } { } { } }; bcheck = [1.7 0.25 0.7 0.6]; uigeom = { [1 2 0.5] bcheck bcheck bcheck bcheck bcheck [3 0.7 0.8 0.6] [3 2 0.05 0.05] }; result = inputgui( uigeom, uilist, 'pophelp(''pop_export'');', 'Export data - pop_export()' ); if length( result ) == 0 return; end; % decode options % -------------- if isempty(result{1}), error('File name required'); end; filename = result{1}; options = {}; if result{2}, options = { options{:} 'ica' 'on' }; end; if result{3}, options = { options{:} 'erp' 'on' }; end; if result{4}, options = { options{:} 'transpose' 'on' }; end; if ~result{5}, options = { options{:} 'elec' 'off' }; end; if ~result{6}, options = { options{:} 'time' 'off' }; end; if ~strcmpi(result{7}, '1E-3'), options = { options{:} 'timeunit' eval(result{7}) }; end; if ~strcmpi(result{8}, '7'), options = { options{:} 'precision' eval(result{8}) }; end; if ~isempty(result{9}), options = { options{:} 'expr' result{9} }; end; else options = varargin; end; % test inputs % ----------- g = finputcheck(options, { ... 'ica' 'string' { 'on';'off' } 'off'; 'time' 'string' { 'on';'off' } 'on'; 'timeunit' 'float' [0 Inf] 1E-3; 'elec' 'string' { 'on';'off' } 'on'; 'transpose' 'string' { 'on';'off' } 'off'; 'erp' 'string' { 'on';'off' } 'off'; 'precision' 'integer' [0 Inf] 7; 'expr' 'string' [] '' }, 'pop_export'); if isstr(g), error(g); end; % select data % ---------- if strcmpi(g.ica, 'on'); eeglab_options; % changed from eeglaboptions 3/30/02 -sm if option_computeica x = EEG.icaact; else x = EEG.icaweights*EEG.icasphere*reshape(EEG.data(EEG.icachansind,:,:), length(EEG.icachansind), EEG.trials*EEG.pnts); x = reshape(x, size(x,1), EEG.pnts, EEG.trials); end; else x = EEG.data; end; % select erp % ---------- if strcmpi(g.erp, 'on'); x = mean(x, 3); else x = reshape(x, size(x,1), size(x,2)*size(x,3)); end; % write data % ---------- if ~isempty(g.expr) eval([ g.expr ';' ]); end; % add time axis % ------------- if strcmpi(g.time, 'on'); timeind = repmat( linspace(EEG.xmin, EEG.xmax, EEG.pnts)/g.timeunit, ... [ 1 fastif(strcmpi(g.erp,'on'), 1, EEG.trials) ]); xx = zeros(size(x,1)+1, size(x,2)); xx(1,:) = timeind; xx(2:end,:) = x; x = xx; clear xx; end % transpose and write to disk % --------------------------- fid = fopen(filename, 'w'); if strcmpi(g.transpose, 'on'); % writing electrodes % ------------------ strprintf = ''; for index = 1:size(x,1) if strcmpi(g.time, 'on'), tmpind = index-1; else tmpind = index; end; if strcmpi(g.elec, 'on') if tmpind > 0 if ~isempty(EEG.chanlocs) & ~strcmpi(g.ica, 'on') fprintf(fid, '%s\t', EEG.chanlocs(tmpind).labels); else fprintf(fid, '%d\t', tmpind); end; else fprintf(fid, ' \t'); end; end; strprintf = [ strprintf '%.' num2str(g.precision) 'f\t' ]; end; strprintf(end) = 'n'; if strcmpi(g.elec, 'on'), fprintf(fid, '\n'); end; fprintf(fid, strprintf, x); else % writing electrodes % ------------------ for index = 1:size(x,1) if strcmpi(g.time, 'on'), tmpind = index-1; else tmpind = index; end; if strcmpi(g.elec, 'on') if tmpind > 0 if ~isempty(EEG.chanlocs) & ~strcmpi(g.ica, 'on') fprintf(fid,'%s\t', EEG.chanlocs(tmpind).labels); else fprintf(fid,'%d\t', tmpind); end; else fprintf(fid, ' \t'); end; end; fprintf(fid,[ '%.' num2str(g.precision) 'f\t' ], x(index, :)); fprintf(fid, '\n'); end; end; fclose(fid); com = sprintf('pop_export(%s,%s);', inputname(1), vararg2str({ filename, options{:} })); return;
github
lcnhappe/happe-master
pop_rejchan.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_rejchan.m
10,320
utf_8
5c5252542d5934e5b83a0dfecc30881e
% pop_rejchan() - reject artifacts channels in an EEG dataset using joint % probability of the recorded electrode. % % Usage: % >> pop_rejchan( INEEG ) % pop-up interative window mode % >> [EEG, indelec, measure, com] = ... % = pop_rejchan( INEEG, 'key', 'val'); % % Inputs: % INEEG - input dataset % % Optional inputs: % 'elec' - [n1 n2 ...] electrode number(s) to take into % consideration for rejection % 'threshold' - [max] absolute thresold or activity probability % limit(s) (in std. dev.) if norm is 'on'. % 'measure' - ['prob'|'kurt'|'spec'] compute probability 'prob', kurtosis 'kurt' % or spectrum 'spec' for each channel. Default is 'kurt'. % 'norm' - ['on'|'off'] normalize measure above (using trimmed % normalization as described in the function jointprob() % and rejkurt(). Default is 'off'. % 'precomp' - [float array] use this array instead of computing the 'prob' % or 'kurt' measures. % 'freqrange' - [min max] frequency range for spectrum computation. % Default is 1 to sampling rate divided by 2. The average % of the log spectral power is computed over the frequency % range of interest. % % Outputs: % OUTEEG - output dataset with updated joint probability array % indelec - indices of rejected electrodes % measure - measure value for each electrode % com - executed command % % Author: Arnaud Delorme, CERCO, UPS/CNRS, 2008- % % See also: jointprob(), rejkurt() % Copyright (C) 2008 Arnaud Delorme, CERCO, UPS/CNRS % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, indelec, measure, com] = pop_rejchan( EEG, varargin); com = ''; indelec = []; measure = []; if nargin < 1 help pop_rejchan; return; end; if nargin < 2 % which set to save % ----------------- cb_select = [ 'if get(gcbo, ''value'') == 3,' ... ' set(findobj(gcbf, ''tag'', ''spec''), ''enable'', ''on'');' ... 'else,' ... ' set(findobj(gcbf, ''tag'', ''spec''), ''enable'', ''off'');' ... 'end;' ]; cb_norm = [ 'if get(gcbo, ''value''),' ... ' set(findobj(gcbf, ''tag'', ''normlab''), ''string'', ''Z-score threshold [max] or [min max]'');' ... 'else,' ... ' set(findobj(gcbf, ''tag'', ''normlab''), ''string'', ''Absolute threshold [max] or [min max]'');' ... 'end;' ]; uilist = { { 'style' 'text' 'string' 'Electrode (number(s); Ex: 2 4 5)' } ... { 'style' 'edit' 'string' ['1:' int2str(EEG.nbchan)] } ... { 'style' 'text' 'string' 'Measure to use' } ... { 'style' 'popupmenu' 'string' 'Probability|Kurtosis|Spectrum' 'value' 2 'callback' cb_select } ... { 'style' 'text' 'string' 'Normalize measure (check=on)' } ... { 'style' 'checkbox' 'string' '' 'value' 1 'callback' cb_norm } { } ... { 'style' 'text' 'string' 'Z-score threshold [max] or [min max]' 'tag' 'normlab' } ... { 'style' 'edit' 'string' '5' } ... { 'style' 'text' 'string' 'Spectrum freq. range' 'enable' 'off' 'tag' 'spec' } ... { 'style' 'edit' 'string' num2str([1 EEG.srate/2]) 'enable' 'off' 'tag' 'spec' } }; % 7/16/2014 Ramon geom = { [2 1.3] [2 1.3] [2 0.4 0.9] [2 1.3] [2 1.3] }; result = inputgui( 'uilist', uilist, 'geometry', geom, 'title', 'Reject channel -- pop_rejchan()', ... 'helpcom', 'pophelp(''pop_rejchan'')'); if isempty(result), return; end; options = { 'elec' eval( [ '[' result{1} ']' ] ) 'threshold' str2num(result{4}) }; if result{3}, options = { options{:} 'norm', 'on' }; else options = { options{:} 'norm', 'off' }; end; if result{2} == 1 options = { options{:} 'measure', 'prob' }; elseif result{2} == 2 options = { options{:} 'measure', 'kurt' }; else options = { options{:} 'measure', 'spec' }; options = { options{:} 'freqrange', str2num(result{5})}; end; else options = varargin; end; opt = finputcheck( options, { 'norm' 'string' { 'on';'off' } 'off'; 'measure' 'string' { 'prob';'kurt';'spec' } 'kurt'; 'precomp' 'real' [] []; 'freqrange' 'real' [] [1 EEG.srate/2]; 'elec' 'integer' [] [1:EEG.nbchan]; 'threshold' 'real' [] 400 }, 'pop_rejchan'); if isstr(opt), error(opt); end; % compute the joint probability % ----------------------------- if strcmpi(opt.norm, 'on') normval = 2; else normval = 0; end; if strcmpi(opt.measure, 'prob') fprintf('Computing probability for channels...\n'); [ measure indelec ] = jointprob( reshape(EEG.data(opt.elec,:,:), length(opt.elec), size(EEG.data,2)*size(EEG.data,3)), opt.threshold, opt.precomp, normval); elseif strcmpi(opt.measure, 'kurt') fprintf('Computing kurtosis for channels...\n'); [ measure indelec ] = rejkurt( reshape(EEG.data(opt.elec,:,:), length(opt.elec), size(EEG.data,2)*size(EEG.data,3)), opt.threshold, opt.precomp, normval); else fprintf('Computing spectrum for channels...\n'); [measure freq] = pop_spectopo(EEG, 1, [], 'EEG' , 'plot','off'); measure = measure(opt.elec,:); % selecting channels % select frequency range if ~isempty(opt.freqrange) [tmp fBeg] = min(abs(freq-opt.freqrange(1))); [tmp fEnd] = min(abs(freq-opt.freqrange(2))); measure = measure(:, fBeg:fEnd); end; % consider that data below 20 db has been filtered and remove it indFiltered = find(mean(measure) < -20); if ~isempty(indFiltered) && indFiltered(1) > 11, measure = measure(:,1:indFiltered(1)-10); disp('Removing spectrum data below -20dB (most likelly filtered out)'); end; meanSpec = mean(measure); stdSpec = std( measure); % for indChan = 1:size(measure,1) % if any(measure(indChan,:) > meanSpec+stdSpec*opt.threshold), indelec(indChan) = 1; end; % end; if strcmpi(opt.norm, 'on') measure1 = max(bsxfun(@rdivide, bsxfun(@minus, measure, meanSpec), stdSpec),[],2); if length(opt.threshold) > 1 measure2 = min(bsxfun(@rdivide, bsxfun(@minus, measure, meanSpec), stdSpec),[],2); indelec = measure2 < opt.threshold(1) | measure1 > opt.threshold(end); disp('Selecting minimum and maximum normalized power over the frequency range'); else indelec = measure1 > opt.threshold(1); disp('Selecting maximum normalized power over the frequency range'); end; else measure1 = max(measure,[],2); if length(opt.threshold) > 1 measure2 = min(measure,[],2); indelec = measure2 < opt.threshold(1) | measure1 > opt.threshold(end); disp('Selecting minimum and maximum power over the frequency range'); else indelec = measure > opt.threshold(1); disp('Selecting maximum power over the frequency range'); end; end; measure = measure1; end; colors = cell(1,length(opt.elec)); colors(:) = { 'k' }; colors(find(indelec)) = { 'r' }; colors = colors(end:-1:1); fprintf('%d electrodes labeled for rejection\n', length(find(indelec))); % output variables indelec = find(indelec)'; tmpchanlocs = EEG.chanlocs; if ~isempty(EEG.chanlocs), tmplocs = EEG.chanlocs(opt.elec); tmpelec = { tmpchanlocs(opt.elec).labels }'; else tmplocs = []; tmpelec = mattocell([opt.elec]'); % tmpelec = mattocell([1:EEG.nbchan]');%Ramon on 8/7/2014 end; if exist('measure2', 'var') fprintf('#\tElec.\t[min]\t[max]\n'); tmpelec(:,3) = mattocell(measure2); tmpelec(:,4) = mattocell(measure); else fprintf('#\tElec.\tMeasure\n'); tmpelec(:,3) = mattocell(measure); end; tmpelec(:,2) = tmpelec(:,1); tmpelec(:,1) = mattocell([1:length(measure)]'); for index = 1:size(tmpelec,1) if exist('measure2', 'var') fprintf('%d\t%s\t%3.2f\t%3.2f', tmpelec{index,1}, tmpelec{index,2}, tmpelec{index,3}, tmpelec{index,4}); elseif ~isempty(EEG.chanlocs) fprintf('%d\t%s\t%3.2f' , tmpelec{index,1}, tmpelec{index,2}, tmpelec{index,3}); else % Ramon on 8/7/2014 fprintf('%d\t%d\t%3.2f' , tmpelec{index,1}, tmpelec{index,2}, tmpelec{index,3}); end; if any(indelec == index), fprintf('\t*Bad*\n'); else fprintf('\n'); end; end; if isempty(indelec), return; end; com = sprintf('EEG = pop_rejchan(EEG, %s);', vararg2str(options)); if nargin < 2 tmpcom = [ 'EEGTMP = pop_select(EEG, ''nochannel'', [' num2str(opt.elec(indelec)) ']);' ]; tmpcom = [ tmpcom ... 'LASTCOM = ' vararg2str(com) ';' ... '[ALLEEG EEG CURRENTSET tmpcom] = pop_newset(ALLEEG, EEGTMP, CURRENTSET);' ... ' if ~isempty(tmpcom),' ... ' EEG = eegh(LASTCOM, EEG);' ... ' eegh(tmpcom);' ... ' eeglab(''redraw'');' ... ' end; clear EEGTMP tmpcom;' ]; eegplot(EEG.data(opt.elec,:,:), 'srate', EEG.srate, 'title', 'Scroll component activities -- eegplot()', ... 'limits', [EEG.xmin EEG.xmax]*1000, 'color', colors(end:-1:1), 'eloc_file', tmplocs, 'command', tmpcom); else EEG = pop_select(EEG, 'nochannel', opt.elec(indelec)); end; return;
github
lcnhappe/happe-master
eeg_countepochs.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_countepochs.m
4,033
utf_8
a9c4c080c3befb23347f12d5c4360d4e
% eeg_countepochs() Count how many epochs there are of each type % % Usage: % >> eeg_countepochs(EEG); % % Inputs: % EEG - input dataset % epochmarker - ['type'|'eventtype'] indicates which part of the % EEG.epoch structure the different trial types are stored in. Depending % on what system the data are from and how they were preprocessed, this % may be either EEG.epoch.type or EEG.epoch.eventtype. Defaults to % 'type'. % Outputs: % sweeps - Scalar structure showing, for each epoch type % (sweeps.types) the number of sweeps in the dataset with that type % (sweeps.counts) % % Example: % eeg_countepochs( EEG, 'type' ) % eeg_countepochs( EEG, 'eventtype' ) % % Author: Stephen Politzer-Ahles, University of Kansas, 2013 % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [sweeps] = eeg_countepochs(EEG, epochmarker); if nargin < 1 help eeg_countepochs; return; end; % Initialize an array which will keep counts clearvars types counts types{1} = ''; counts = [0]; % Iterate through all trials for trial=1:length(EEG.epoch) % Default 'epochmarker' to 'type' if no input was provided. if nargin < 2 epochmarker = 'type'; end; % Look for epochs that have >1 event and find which event is epoched around eventindex = 1; % if only 1 event, eventindex=1 if length(EEG.epoch(trial).eventlatency) > 1 for eventnum = 1:length(EEG.epoch(trial).eventlatency) if EEG.epoch(trial).eventlatency{eventnum}==0 eventindex = eventnum; end % end if end % end for end % end if % Get the trigger number for this trial if strcmp(epochmarker,'eventtype') % change event type from cell/number event to string if iscell(EEG.epoch(trial).eventtype(eventindex)) type = EEG.epoch(trial).eventtype{eventindex}; elseif isnumeric(EEG.epoch(trial).eventtype(eventindex)) type = num2str( EEG.epoch(trial).eventtype(eventindex) ); else % is char type = EEG.epoch(trial).eventtype; end elseif strcmp(epochmarker,'type') % change cell/number event to string if iscell(EEG.epoch(trial).type(eventindex)) type = EEG.epoch(trial).type{eventindex}; elseif isnumeric(EEG.epoch(trial).type(eventindex)) type = num2str( EEG.epoch(trial).type(eventindex) ); else % is char type = EEG.epoch(trial).type; end end; % end if % Find the row of the array that corresponds to this trigger (or if this trigger has not been counted yet) index_of_type = find( cellfun(@(x) strcmp(x,type), types) ); % If this trial has a trigger that has already been counted before, % 'row_of_type' will be a number. If not, it will be an empty % array. if index_of_type % If we already have a count for this trigger, increment that count by 1 counts(index_of_type) = counts(index_of_type) + 1; else % If not, create a new count for this type types = [types type]; counts(end+1) = 1; end; % end if end; % end for % Remove the unnecessary first item types = types(2:end); counts = counts(2:end); % Sorts [Y,I] = sort( types ); % Add types and sweeps to a scalar structure sweeps.types = types(I); sweeps.counts = counts(I); end
github
lcnhappe/happe-master
pop_chanedit.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_chanedit.m
52,066
utf_8
bf28afe0988b5a6a63cd71032753762b
% pop_chanedit() - Edit the channel locations structure of an EEGLAB dataset, % EEG.chanlocs. For structure location and file formats, % see >> help readlocs % % EEG.chanlocs. For structure location and file formats, % see >> help readlocs % % Usage: >> EEG = pop_chanedit( EEG, 'key1', value1, 'key2', value2, ... ); % >> [ chanlocs options ] = pop_chanedit( chanlocs, 'key1', value1); % >> [ chanlocs chaninfo options ] = pop_chanedit( chanlocs, chaninfo, ... % 'key1', value1, 'key2', value2, ... ); % % Graphic interface: % "Channel information ('field name')" - [edit boxes] display channel field % contents for the current channel. Command line equivalent % to modify these fields: 'transform' % "Opt. 3D center" - [button] optimally re-center 3-D channel coordinates. Uses % chancenter(). Command line equivalent: 'convert', { 'chancenter' % [xc yc zc] }, [xc yc zc] being the center of the sphere. Use [] % to find the center of the best fitting sphere. % "Rotate axis" - [button] force one electrode to one position and rotate the other % electrodes accordingly. Command line equivalent: 'forcelocs'. % "Transform axis" - [button] perform any operation on channel fields. Command % line equivalent: 'transform'. % "Xyz->polar & sph." - [button] convert 3-D cartesian coordinates to polar and % 3-D spherical coordinates. This is useful when you edit the % coordinates manually. Command line equivalent: 'convert', 'cart2all'. % "Sph.->polar & xyz" - [button] convert 3-D spherical coordinates to polar and % 3-D cartesian coordinates. Command line equivalent: 'convert', 'sph2all'. % "Polar->sph & xyz" - [button] convert 2-D polar coordinates to 3-D spherical and % 3-D cartesian coordinates. Command line equivalent: 'convert', 'topo2all'. % Note that if spherical radii are absent, they are forced to 1. % "Set head radius" - [button] change head size radius. This is useful % to make channels location compatible with a specified spherical model. % Command line equivalent: 'headrad'. % "Set channel types" - [button] set channel type names for a range of data channels. % "Delete chan" - [button] delete channel. Command line equivalent: 'delete'. % "Insert chan" - [button] insert channel before current channel. % Command line equivalent: 'insert'. % "<<" - [button] scroll channel backward by 10. % "<" - [button] scroll channel backward by 1. % ">" - [button] scroll channel forward by 1. % ">>" - [button] scroll channel forward by 10. % "Append chan" - [button] append channel after the current channel. % Command line equivalent: 'append'. % "Plot 2D" - [button] plot channel locations in 2-D using topoplot() % "Plot radius [value (0.2-1.0), []=auto)" - [edit box] default plotting radius % in 2-D polar views. This does NOT affect channel locations; it % is only used for visualization. This parameter is attached to the % chanlocs structure and is then used in all 2-D scalp topoplots. % Default -> to data limits. Command line equivalent: 'plotrad'. % "Nose along +X" - [list] Indicate the direction of the nose. This information % is used in functions like topoplot(), headplot() and dipplot(). % Command line equivalent: 'nosedir'. % "Plot 3D" - [button] plot channel positions in 3-D using plotchans3d() % "Read locations" - [button] read location file using readlocs() % Command line equivalent: 'load'. % "Read help" - [button] display readlocs() function help. % "Save .ced" - [button] save channel locations in native EEGLAB ".ced" format. % Command line equivalent: 'save'. % "Save others" - [button] save channel locations in other formats using % pop_writelocs() (see readlocs() for available channel formats). % "Cancel" - [button] cancel all editing. % "Help" - [button] display this help message. % "OK" - [button] save edits and propagate to parent. % % Inputs: % EEG - EEG dataset % chanlocs - EEG.chanlocs structure % % Optional inputs: % 'convert' - {conversion_type [args]} Conversion type may be: 'cart2topo' % 'sph2topo', 'topo2sph', 'sph2cart', 'cart2sph', or 'chancenter'. % See help messages for these functions. Args are only relevant % for 'chancenter'. More info is given in the graphic interface % description above. % 'transform' - String command for manipulating arrays. 'chan' is full channel % info. Fields that can be manipulated are 'labels', 'theta' % 'radius' (polar angle and radius), 'X', 'Y', 'Z' (cartesian % 3-D) or 'sph_theta', 'sph_phi', 'sph_radius' for spherical % horizontal angle, azimuth and radius. % Ex: 'chans(3) = chans(14)', 'X = -X' or a multi-step transform % with steps separated by ';': Ex. 'TMP = X; X = Y; Y = TMP' % 'changechan' - {number value1 value2 value3 ...} Change the values of all fields % for the given channel number, mimimally {num label theta radius}. % Ex: 'changechan' {12 'PXz' -90 0.30} % 'changefield' - {number field value} Change field value for channel number number. % Ex: {34 'theta' 320.4}. % 'insert' - {number label theta radius X Y Z sph_theta sph_phi sph_radius } % Insert new channel and specified values before the current channel % number. If the number of values is less than 10, remaining % fields will be 0. (Previously, this parameter was termed 'add'). % 'append' - {num label theta radius X Y Z sph_theta sph_phi sph_radius } % same as 'insert' (above) but insert the the new channel after % the current channel number. % 'delete' - [int_vector] Vector of channel numbers to delete. % 'forcelocs' - [cell] call forcelocs() to force a particular channel to be at a % particular location on the head sphere; rotate other channels % accordingly. % 'skirt' - Topographical polar skirt factor (see >> help topoplot) % 'shrink' - Topographical polar shrink factor (see >> help topoplot) % 'load' - [filename|{filename, 'key', 'val'}] Load channel location file % optional arguments (such as file format) to the function % readlocs() can be specified if the input is a cell array. % 'save' - 'filename' Save text file with channel info. % 'eval' - [string] evaluate string ('chantmp' is the name of the channel % location structure). % 'headrad' - [float] change head radius. % 'lookup' - [string] look-up channel numbers for standard locations in the % channel location file given as input. % % Outputs: % EEG - new EEGLAB dataset with updated channel location structures % EEG.chanlocs, EEG.urchanlocs, EEG.chaninfo % chanlocs - updated channel location structure % chaninfo - updated chaninfo structure % options - structure containing plotting options (equivalent to EEG.chaninfo) % % Ex: EEG = pop_chanedit(EEG,'load', { 'dummy.elp' 'elp' }, 'delete', [3 4], ... % 'convert', { 'xyz->polar' [] -1 1 }, 'save', 'mychans.loc' ) % % Load polhemus file, delete two channels, convert to polar (see % % cart2topo() for arguments) and save into 'mychans.loc'. % % Author: Arnaud Delorme, CNL / Salk Institute, 20 April 2002 % % See also: readlocs() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 15 March 2002, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % hidden parameter % 'gui' - [figure value], allow to process the same dialog box several times function [chansout, chaninfo, urchans, com] = pop_chanedit(chans, orichaninfo, varargin); urchans = []; com =''; if nargin < 1 help pop_chanedit; return; end; chansout = chans; chaninfo = []; fig = []; if nargin < 2 orichaninfo = []; end; if isempty(chans) || all(~ishandle(chans)) % in case an EEG structure was given as input % ------------------------------------------- if isfield(chans, 'chanlocs') dataset_input = 1; EEG = chans; chans = EEG(1).chanlocs; nchansori = EEG.nbchan; if isfield(EEG, 'chaninfo') chaninfo = EEG(1).chaninfo; else chaninfo = []; end; if isfield(EEG, 'urchanlocs') urchans = EEG(1).urchanlocs; end; else nchansori = 0; dataset_input = 0; chaninfo = orichaninfo; end; % dealing with additional parameters % ---------------------------------- if nargin > 1 && ~isstr(orichaninfo), % nothing if nargin > 2 if ~isstr(varargin{1}) urchans = varargin{1}; varargin = varargin(2:end); end; end; elseif nargin > 1 && ~isempty(orichaninfo) && isstr(orichaninfo) varargin = { orichaninfo varargin{:} }; if isequal(orichaninfo, chaninfo) chaninfo = []; end; orichaninfo = []; end; % insert "no data channels" in channel structure % ---------------------------------------------- nbchan = length(chans); [tmp chaninfo chans] = eeg_checkchanlocs(chans, chaninfo); if isfield(chaninfo, 'shrink') && ~isempty(chaninfo.shrink) icadefs; if SHRINKWARNING warndlg2( [ 'You are currently shrinking channel locations for display.' 10 ... 'A new option (more anatomically correct) is to plot channels' 10 ... 'outside head limits so the shrink option has been disabled.' 10 ... '(Edit the icadefs file to disable this message)' ], 'Shrink factor warning'); end; end; oldchaninfo = chaninfo; end; if nargin < 3 totaluserdat = {}; % lookup channel locations if necessary % ------------------------------------- if ~all(cellfun('isempty', {chans.labels})) && all(cellfun('isempty', {chans.theta})) [chans chaninfo urchans com] = pop_chanedit(chans, chaninfo, 'lookupgui', []); for index = 1:length(chans) chans(index).ref = ''; chans(index).datachan = 1; end; if ~isempty(com) totaluserdat = com; %[chans chaninfo urchans com] = pop_chanedit(chans, chaninfo, com{:}); end; end; commentfields = { 'Channel label ("label")', ... 'Polar angle ("theta")', 'Polar radius ("radius")', ... 'Cartesian X ("X")', ... 'Cartesian Y ("Y")', ... 'Cartesian Z ("Z")', ... 'Spherical horiz. angle ("sph_theta")', ... 'Spherical azimuth angle ("sph_phi")', ... 'Spherical radius ("sph_radius")' ... 'Channel type' 'Reference' ... 'Index in backup ''urchanlocs'' structure' ... 'Channel in data array (set=yes)' }; % add field values % ---------------- geometry = { 1 }; tmpstr = sprintf('Channel information ("field_name"):'); uilist = { { 'Style', 'text', 'string', tmpstr, 'fontweight', 'bold' } }; uiconvert = { ... { 'Style', 'pushbutton', 'string', 'Opt. head center', 'callback', 'pop_chanedit(gcbf, [], ''chancenter'', []);' } ... { 'Style', 'pushbutton', 'string', 'Rotate axis' , 'callback', 'pop_chanedit(gcbf, [], ''forcelocs'', []);' } ... { 'Style', 'pushbutton', 'string', 'Transform axes' , 'callback', 'pop_chanedit(gcbf, [], ''transform'', []);' } ... { }, ... { 'Style', 'pushbutton', 'string', 'xyz -> polar & sph.', 'callback', 'pop_chanedit(gcbf, [], ''convert'', {''cart2all''});' }, ... { 'Style', 'pushbutton', 'string', 'sph. -> polar & xyz', 'callback', 'pop_chanedit(gcbf, [], ''convert'', {''sph2all'' });' }, ... { 'Style', 'pushbutton', 'string', 'polar -> sph. & xyz', 'callback', 'pop_chanedit(gcbf, [], ''convert'', {''topo2all''});' }, ... { }, ... { 'Style', 'pushbutton', 'string', 'Set head radius', 'callback', 'pop_chanedit(gcbf, [], ''headrad'', []);' } ... { 'Style', 'pushbutton', 'string', 'Set channel types', 'callback', 'pop_chanedit(gcbf, [], ''settype'', []);' } ... { 'Style', 'pushbutton', 'string', 'Set reference', 'callback', 'pop_chanedit(gcbf, [], ''setref'' , []);' } ... { } { } }; % create text and edit for each field % ----------------------------------- allfields = { 'labels' 'theta' 'radius' 'X' 'Y' 'Z' 'sph_theta' 'sph_phi' 'sph_radius' 'type' 'ref' 'urchan' 'datachan' }; for index = 1:length(allfields)-1 cbfield = [ 'valnumtmp = str2num(get(findobj(gcbf, ''tag'', ''chaneditnumval''), ''string''));' ... 'pop_chanedit(gcbf, [], ''changefield'', { valnumtmp ''' allfields{index} ''' get(gcbo, ''string'') });' ... 'clear valnumtmp;' ]; geometry = { geometry{:} [1.5 1 0.2 1] }; uilist = { uilist{:}, ... { 'Style', 'text', 'string', commentfields{index} }, ... { 'Style', 'edit', 'tag', [ 'chanedit' allfields{index} ], 'string', ... num2str(getfield(chans,{1}, allfields{index})), 'horizontalalignment', 'center', 'callback', cbfield } ... { } uiconvert{index} }; end; % special checkbox for chandata field % ----------------------------------- geometry = { geometry{:} [2 0.35 0.5 1] }; cbfield = [ 'valnumtmp = str2num(get(findobj(gcbf, ''tag'', ''chaneditnumval''), ''string''));' ... 'pop_chanedit(gcbf, [], ''changefield'', { valnumtmp ''' allfields{end} ''' get(gcbo, ''value'') });' ... 'clear valnumtmp;' ]; uilist = { uilist{:}, ... { 'Style', 'text', 'string', commentfields{end} }, ... { 'Style', 'checkbox', 'tag', [ 'chanedit' allfields{end}], 'string', '' 'value', 1 'callback', cbfield } { } uiconvert{end} }; % add buttons % ----------- geometry = { geometry{:} [1] [1.15 0.5 0.6 1.9 0.4 0.4 1.15] [1.15 0.7 0.7 1 0.7 0.7 1.15] }; cb_del = [ 'valnum = str2num(char(get(findobj(gcbf,''tag'', ''chaneditnumval''), ''string'')));' ... 'pop_chanedit(gcbf, [], ''deletegui'', valnum);' ]; cb_insert = [ 'valnum = str2num(char(get(findobj(gcbf,''tag'', ''chaneditnumval''), ''string'')));' ... 'pop_chanedit(gcbf, [], ''insert'', valnum);' ]; cb_append = [ 'valnum = str2num(char(get(findobj(gcbf,''tag'', ''chaneditnumval''), ''string'')));' ... 'pop_chanedit(gcbf, [], ''append'', valnum);' ]; uilist = { uilist{:}, ... { }, ... { 'Style', 'pushbutton', 'string', 'Delete chan', 'callback', cb_del }, ... { },{ }, ... { 'Style', 'text' , 'string', ['Channel number (of ' int2str(length(chans)) ')'], ... 'fontweight', 'bold', 'tag', 'chaneditscantitle' }, { },{ },{ }, ... { 'Style', 'pushbutton', 'string', 'Insert chan', 'callback', cb_insert } ... { 'Style', 'pushbutton', 'string', '<<', 'callback', [ 'pop_chanedit(gcbf, [], ''movecursor'', -10);' ] } ... { 'Style', 'pushbutton', 'string', '<', 'callback', [ 'pop_chanedit(gcbf, [], ''movecursor'', -1);' ] } ... { 'Style', 'edit' , 'string', '1', 'tag', 'chaneditnumval', 'callback', [ 'pop_chanedit(gcbf, []);' ] } ... { 'Style', 'pushbutton', 'string', '>', 'callback', [ 'pop_chanedit(gcbf, [], ''movecursor'', 1);' ] } ... { 'Style', 'pushbutton', 'string', '>>', 'callback', [ 'pop_chanedit(gcbf, [], ''movecursor'', 10);' ] } ... { 'Style', 'pushbutton', 'string', 'Append chan', 'callback', cb_append }, ... }; % add sorting options % ------------------- noseparam = strmatch(upper(chaninfo.nosedir), { '+X' '-X' '+Y' '-Y' }); if isempty(noseparam), error('Wrong value for nose direction'); end; geometry = { geometry{:} [1] [0.9 1.3 0.6 1.1 0.9] [1] [1 1 1 1 1]}; uilist = { uilist{:},... { } ... { 'Style', 'pushbutton', 'string', 'Plot 2-D', 'callback', 'pop_chanedit(gcbf, [], ''plot2d'', []);' },... { 'Style', 'text', 'string', 'Plot radius (0.2-1, []=auto)'} ... { 'Style', 'edit', 'string', chaninfo.plotrad, 'tag', 'plotrad' 'callback' 'pop_chanedit(gcbf, [], ''plotrad'', []);' } ... { 'Style', 'popupmenu', 'string', 'Nose along +X|Nose along -X|Nose along +Y|Nose along -Y', ... 'tag' 'nosedir' 'value',noseparam, 'callback' 'pop_chanedit(gcbf,[],''nosedir'',[]);' 'listboxtop' noseparam } ... { 'Style', 'pushbutton', 'string', 'Plot 3-D (xyz)', 'callback', 'pop_chanedit(gcbf, [], ''plot3d'', []);' } ... {}, ... { 'Style', 'pushbutton', 'string', 'Read locations', 'callback', 'pop_chanedit(gcbf,[],''load'',[]);' }, ... { 'Style', 'pushbutton', 'string', 'Read locs help', 'callback', 'pophelp(''readlocs.m'');' }, ... { 'Style', 'pushbutton', 'string', 'Look up locs', 'callback', 'pop_chanedit(gcbf,[], ''lookupgui'', []);' }, ... { 'Style', 'pushbutton', 'string', 'Save (as .ced)', 'callback', 'pop_chanedit(gcbf,[], ''save'',[]);' } ... { 'Style', 'pushbutton', 'string', 'Save (other types)' 'callback', 'pop_chanedit(gcbf,[], ''saveothers'',[]);' } ... }; % evaluation of command below is required to center text (if % declared a text instead of edit, the uicontrol is not centered) comeval = [ 'set(findobj( ''tag'', ''chanediturchan''), ''style'', ''text'', ''backgroundcolor'', [.66 .76 1] );' ... 'set(findobj( ''tag'', ''chaneditref''), ''style'', ''text'', ''backgroundcolor'', [.66 .76 1] );' ... 'set(findobj( ''tag'', ''ok''), ''callback'', ''pop_chanedit(gcbf, [], ''''return'''', []);'')' ]; userdata.chans = chans; userdata.nchansori = nchansori; userdata.chaninfo = chaninfo; userdata.commands = totaluserdat; [results userdata returnmode] = inputgui( 'geometry', geometry, 'uilist', uilist, 'helpcom', ... 'pophelp(''pop_chanedit'');', 'title', 'Edit channel info -- pop_chanedit()', ... 'userdata', userdata, 'eval' , comeval ); if length(results) == 0, com = ''; if dataset_input, chansout = EEG; end; return; end; % transfer events back from global workspace chans = userdata.chans; chaninfo = userdata.chaninfo; if ~isempty(userdata.commands) com = sprintf('%s=pop_chanedit(%s, %s);', inputname(1), inputname(1), vararg2str(userdata.commands)); end; else % call from command line or from a figure % --------------------------------------- currentpos = 0; if ishandle(chans) fig = chans; userdata = get(fig, 'userdata'); chans = userdata.chans; nchansori = userdata.nchansori; chaninfo = userdata.chaninfo; currentpos = str2num(get(findobj(fig, 'tag', 'chaneditnumval'), 'string')); end; args = varargin; % no interactive inputs % scan all the fields of g % ------------------------ for curfield = 1:2:length(args) switch lower(args{curfield}) case 'return' [tmpchans] = eeg_checkchanlocs(chans); if nchansori ~= 0 & nchansori ~= length(tmpchans) if ~popask(strvcat(['The number of data channels (' int2str(length(tmpchans)) ') not including fiducials does not'], ... ['correspond to the initial number of channels (' int2str(nchansori) '), so for consistency purposes'], ... 'new channel information will be ignored if this function was called from EEGLAB', ... 'If you have added a reference channel manually, check the "Data channel" checkbox is off')) else set(findobj(fig, 'tag', 'ok'), 'userdata', 'stop'); end; else set(findobj(fig, 'tag', 'ok'), 'userdata', 'stop'); end; args = {}; case 'plot3d', % GUI only tmpind = find(~cellfun('isempty', { chans.X })); if ~isempty(tmpind), plotchans3d([ [ chans(tmpind).X ]' [ chans(tmpind).Y ]' [ chans(tmpind).Z ]'], { chans(tmpind).labels }); else disp('cannot plot: no XYZ coordinates'); end; args = {}; case 'plot2d', % GUI only plotrad = str2num(get(findobj(fig, 'tag', 'plotrad'), 'string')); figure; topoplot([],chans, 'style', 'blank', 'drawaxis', 'on', 'electrodes', ... 'labelpoint', 'plotrad', plotrad, 'chaninfo', chaninfo); args = {}; case 'movecursor', % GUI only currentpos = max(1,min(currentpos+args{curfield+1},length(chans))); args = {}; case 'plotrad', if isempty( args{curfield+1} ) args{curfield+1} = str2num(get(findobj(fig, 'tag', 'plotrad'), 'string')); end; chaninfo.plotrad = args{curfield+1}; case 'forcelocs', if ~isempty(fig) % GUI BASED [ comtmp tmpforce ] = forcelocs(chans); if ~isempty(tmpforce), args{curfield+1} = tmpforce{1}; end; end; if ~isempty(args{curfield+1}) chans = forcelocs(chans,args{curfield+1}); disp('Convert XYZ coordinates to spherical and polar'); end; case 'chancenter', if ~isempty(fig) [chans newcenter tmpcom] = pop_chancenter(chans); args{curfield } = 'eval'; args{curfield+1} = tmpcom; end; case 'convert', if iscell(args{curfield+1}) method=args{curfield+1}{1}; extraargs = args{curfield+1}(2:end); else method=args{curfield+1}; extraargs = {''}; end; if ~isempty(fig) & ~strcmp(method, 'chancenter') tmpButtonName=questdlg2( strvcat('This will modify fields in the channel structure', ... 'Are you sure you want to apply this function ?'), 'Confirmation', 'Cancel', 'Yes','Yes'); if ~strcmpi(tmpButtonName, 'Yes'), return; end; end; switch method case 'chancenter', if isempty(extraargs) [X Y Z]=chancenter( [chans.X ]', [ chans.Y ]', [ chans.Z ]',[]); else [X Y Z]=chancenter( [chans.X ]', [ chans.Y ]', [ chans.Z ]', extraargs{:}); end; if isempty(X), return; end; for index = 1:length(chans) chans(index).X = X(index); chans(index).Y = Y(index); chans(index).Z = Z(index); end; disp('Note: automatically convert XYZ coordinates to spherical and polar'); chans = convertlocs(chans, 'cart2all'); otherwise chans = convertlocs(chans, method, 'verbose', 'on'); end; case 'settype' if ~isempty(fig) args{curfield+1} = inputdlg2({'Channel indices' 'Type (e.g. EEG)' }, ... 'Set channel type', 1, { '' '' }, 'pop_chanedit'); end; try, tmpchans = args{curfield+1}{1}; tmptype = args{curfield+1}{2};catch, return; end; if isempty(tmpchans) & isempty(tmptype), return; end; if isstr(tmpchans) tmpchans = eval( [ '[' tmpchans ']' ], 'settype: error in channel indices'); end; if ~isstr(tmptype), tmptype = num2str(tmptype); end; for index = 1:length(tmpchans) if tmpchans(index) > 0 & tmpchans(index) <= length(chans) chans( tmpchans(index) ).type = tmptype; end; end; case 'setref' if ~isempty(fig) disp('Note that setting the reference only changes the reference labels'); disp('Use the re-referencing menu to change the reference'); args{curfield+1} = inputdlg2({'Channel indices' 'Reference (e.g. Cz)' }, ... 'Set channel reference', 1, { '' '' }, 'pop_chanedit'); end; try, tmpchans = args{curfield+1}{1}; tmpref = args{curfield+1}{2};catch, return; end; if isempty(tmpchans) & isempty(tmpref), return; end; if isstr(tmpchans) tmpchans = eval( [ '[' tmpchans ']' ], 'settype: error in channel indices'); end; if ~isstr(tmpref), tmpref = num2str(tmpref); end; for index = 1:length(tmpchans) if tmpchans(index) > 0 & tmpchans(index) <= length(chans) chans( tmpchans(index) ).ref = tmpref; end; end; case 'transform' if ~isempty(fig) args{curfield+1} = inputdlg2({'Enter transform: (Ex: TMP=X; X=-Y; Y=TMP or Y(3) = X(2), etc.' }, ... 'Transform', 1, { '' }, 'pop_chanedit'); end; try, tmpoper = args{curfield+1}; catch, return; end; if isempty(deblank(tmpoper)), return; end; if iscell(tmpoper), tmpoper = tmpoper{1}; end; tmpoper = [ tmpoper ';' ]; [eloc, labels, theta, radius, indices] = readlocs(chans); if isempty(findstr(tmpoper, 'chans')) try, X = [ chans(indices).X ]; Y = [ chans(indices).Y ]; Z = [ chans(indices).Z ]; sph_theta = [ chans(indices).sph_theta ]; sph_phi = [ chans(indices).sph_phi ]; sph_radius = [ chans(indices).sph_radius ]; eval(tmpoper); for ind = 1:length(indices) chans(indices(ind)).X = X(min(length(X),ind)); chans(indices(ind)).Y = Y(min(length(Y),ind)); chans(indices(ind)).Z = Z(min(length(Z),ind)); chans(indices(ind)).theta = theta(min(length(theta),ind)); chans(indices(ind)).radius = radius(min(length(radius),ind)); chans(indices(ind)).sph_theta = sph_theta(min(length(sph_theta),ind)); chans(indices(ind)).sph_phi = sph_phi(min(length(sph_phi),ind)); chans(indices(ind)).sph_radius = sph_radius(min(length(sph_radius),ind)); end; if ~isempty(findstr(tmpoper, 'X')), chans = convertlocs(chans, 'cart2all'); end; if ~isempty(findstr(tmpoper, 'Y')), chans = convertlocs(chans, 'cart2all'); end; if ~isempty(findstr(tmpoper, 'Z')), chans = convertlocs(chans, 'cart2all'); end; if ~isempty(findstr(tmpoper, 'sph_theta')), chans = convertlocs(chans, 'sph2all'); elseif ~isempty(findstr(tmpoper, 'theta')), chans = convertlocs(chans, 'topo2all'); end; if ~isempty(findstr(tmpoper, 'sph_phi')), chans = convertlocs(chans, 'sph2all'); end; if ~isempty(findstr(tmpoper, 'sph_radius')), chans = convertlocs(chans, 'sph2all'); elseif ~isempty(findstr(tmpoper, 'radius')), chans = convertlocs(chans, 'topo2all'); end; catch, disp('Unknown error when applying transform'); end; else eval(tmpoper); end; case 'headrad' if ~isempty(fig) % GUI tmpres = inputdlg2({'Enter new head radius (same unit as DIPFIT head model):' }, ... 'Head radius', 1, { '' }, 'pop_chanedit'); if ~isempty(tmpres), args{ curfield+1 } = str2num(tmpres{1}); else return; end; end; if ~isempty( args{ curfield+1 } ) allrad = [ chans.sph_radius ]; if length(unique(allrad)) == 1 % already spherical chans = pop_chanedit(chans, 'transform', [ 'sph_radius = ' num2str( args{ curfield+1 } ) ';' ]); else % non-spherical, finding best match factor = args{ curfield+1 } / mean(allrad); chans = pop_chanedit(chans, 'transform', [ 'sph_radius = sph_radius*' num2str( factor ) ';' ]); disp('Warning: electrodes do not lie on a sphere. Sphere model fitting for'); disp(' dipole localization will work but generate many warnings'); end; chans = convertlocs(chans, 'sph2all'); end; case 'shrink' chans(1).shrink = args{ curfield+1 }; case 'plotrad' chans(1).plotrad = args{ curfield+1 }; case 'deletegui' chans(args{ curfield+1 })=[]; currentpos = min(length(chans), currentpos); args{ curfield } = 'delete'; case 'delete' chans(args{ curfield+1 })=[]; case 'changefield' tmpargs = args{ curfield+1 }; if length( tmpargs ) < 3 error('pop_chanedit: not enough arguments to change field value'); end; if ~isempty(strmatch( tmpargs{2}, { 'X' 'Y' 'Z' 'theta' 'radius' 'sph_theta' 'sph_phi' 'sph_radius'})) if ~isnumeric(tmpargs{3}), tmpargs{3} = str2num(tmpargs{3}); end; end; eval([ 'chans(' int2str(tmpargs{1}) ').' tmpargs{2} '=' reformat(tmpargs{3} ) ';' ]); case { 'insert' 'add' 'append' } tmpargs = args{ curfield+1 }; allfields = fieldnames(chans); if isnumeric(tmpargs) tmpargs2 = cell(1, length(allfields)+1); tmpargs2{1} = tmpargs; tmpargs = tmpargs2; if strcmpi(allfields{end}, 'datachan'), tmpargs{end} = 0; end; end; if length( tmpargs ) < length(allfields)+1 error('pop_chanedit: not enough arguments to change all field values'); end; num = tmpargs{1}; if strcmpi(lower(args{curfield}), 'append'), num=num+1; currentpos = currentpos+1; end; chans(end+1) = chans(end); chans(num+1:end) = chans(num:end-1); for index = 1:length( allfields ) chans = setfield(chans, {num}, allfields{index}, tmpargs{index+1}); end; if isfield(chans, 'datachan') if isempty(chans(num).datachan) chans(num).datachan = 0; end; end; case 'changechan' tmpargs = args{ curfield+1 }; num = tmpargs{1}; allfields = fieldnames(chans); if length( tmpargs ) < length(allfields)+1 error('pop_chanedit: not enough arguments to change all field values'); end; for index = 1:length( allfields ) eval([ 'chans(' int2str(num) ').' allfields{index} '=' reformat(tmpargs{index+1}) ';' ]); end; case 'load' if ~isempty(fig) % GUI [tmpf tmpp] = uigetfile('*.*', 'Load a channel location file'); drawnow; if ~isequal(tmpf, 0), tmpformats = readlocs('getinfos'); tmpformattype = { 'autodetect' tmpformats(1:end-1).type }; tmpformatstr = { 'autodetect' tmpformats(1:end-1).typestring }; tmpformatdesc = { 'Autodetect file format from file extension' tmpformats(1:end-1).description }; %cb_listbox = 'tmpdesc=get(gcbf, ''userdata''); set(findobj(gcbf, ''tag'', ''strdesc''), ''string'', strmultiline([ ''File format: '' tmpdesc{get(gcbo, ''value'')} ], 30, 10)); clear tmpdesc;'' } }, ''pophelp(''''readlocs'''')'',' ... % 'Read electrode file'', tmpformatdesc, ''normal'', 4); %txtgui = [ strmultiline([ 'File format: Autodetect file format from file extension'], 20, 10) 10 10 ]; %tmpfmt = inputgui( 'geometry', {[1 1]}, ... % 'uilist' , { { 'style', 'text', 'string', txtgui 'tag' 'strdesc' }, ... % { 'style', 'listbox', 'string', strvcat(tmpformatstr) 'callback' '' } }, ... % 'geomvert', [10], ... % 'helpcom' , 'pophelp(''readlocs'');'); tmpfmt = inputgui( 'geometry', {[1 1 1] [1]}, ... 'uilist' , { { 'style', 'text', 'string', 'File format:' 'tag' 'strdesc' } {} {}, ... { 'style', 'listbox', 'string', strvcat(tmpformatstr) 'callback' '' } }, ... 'geomvert', [1 8], ... 'helpcom' , 'pophelp(''readlocs'');'); if isempty(tmpfmt), args{ curfield+1 } = []; else args{ curfield+1 } = { fullfile(tmpp, tmpf) 'filetype' tmpformattype{tmpfmt{1}} }; end; else args{ curfield+1 } = []; end; end; tmpargs = args{ curfield+1 }; if ~isempty(tmpargs), if isstr(tmpargs) [chans] = readlocs(tmpargs); [tmp tmp2 chans] = eeg_checkchanlocs(chans); chaninfo = []; chaninfo.filename = tmpargs; else [chans] = readlocs(tmpargs{:}); [tmp tmp2 chans] = eeg_checkchanlocs(chans); chaninfo = []; chaninfo.filename = tmpargs{1}; end; % backup file content etc... % -------------------------- tmptext = loadtxt( chaninfo.filename, 'delim', [], 'verbose', 'off', 'convert', 'off'); chaninfo.filecontent = strvcat(tmptext{:}); % set urchan structure % -------------------- urchans = chans; for index = 1:length(chans) chans(index).urchan = index; end; end; if ~isfield(chans, 'datachan') chans(1).datachan = []; end; for index = 1:length(chans) if isempty(chans(index).datachan) chans(index).datachan = 1; end; end; case 'eval' tmpargs = args{ curfield+1 }; eval(tmpargs); case 'saveothers' com = pop_writelocs(chans); args{ curfield } = 'eval'; args{ curfield+1 } = com; case 'save' if ~isempty(fig) [tmpf tmpp] = uiputfile('*.ced', 'Save channel locs in EEGLAB .ced format'); drawnow; args{ curfield+1 } = fullfile(tmpp, tmpf); end; tmpargs = args{ curfield+1 }; if isempty(tmpargs), return; end; fid = fopen(tmpargs, 'w'); if fid ==-1, error('Cannot open file'); end; allfields = fieldnames(chans); fields = { 'labels' 'theta' 'radius' 'X' 'Y' 'Z' 'sph_theta' 'sph_phi' 'sph_radius' 'type' }; tmpdiff = setdiff(fields, allfields); if ~isempty(tmpdiff), error(sprintf('Field "%s" missing in channel location structure', tmpdiff{1})); end; [tmp,ia,tmp] = intersect(allfields,fields,'stable'); %Getting the original order from file origfield = allfields(ia); fprintf(fid, 'Number\t'); for field = 1:length(fields) fprintf(fid, '%s\t', origfield{field}); end; fprintf(fid, '\n'); for index=1:length(chans) fprintf(fid, '%d\t', index); for field = 1:length(fields) tmpval = getfield(chans, {index}, origfield{field}); if isstr(tmpval) fprintf(fid, '%s\t', tmpval); else fprintf(fid, '%3.3g\t', tmpval); end; end; fprintf(fid, '\n'); end; if isempty(tmpargs), chantmp = readlocs(tmpargs); end; case 'nosedir' nosevals = { '+X' '-X' '+Y' '-Y' }; if ~isempty(fig) tmpval = get(findobj(gcbf, 'tag', 'nosedir'), 'value'); args{ curfield+1 } = nosevals{tmpval}; warndlg2( [ 'Changing the nose direction will force EEGLAB to physically rotate ' 10 ... 'electrodes, so next time you call this interface, nose direction will' 10 ... 'be +X. If your electrodes are currently aligned with a specific' 10 ... 'head model, you will have to rotate them in the model coregistration' 10 ... 'interface to realign them with the model.'], 'My Warn Dialog'); end; chaninfo.nosedir = args{ curfield+1 }; if isempty(strmatch(chaninfo.nosedir, nosevals)) error('Wrong value for nose direction'); end; case { 'lookup' 'lookupgui' } if strcmpi(lower(args{curfield}), 'lookupgui') standardchans = { 'Fp1' 'Fpz' 'Fp2' 'Nz' 'AF9' 'AF7' 'AF3' 'AFz' 'AF4' 'AF8' 'AF10' 'F9' 'F7' 'F5' ... 'F3' 'F1' 'Fz' 'F2' 'F4' 'F6' 'F8' 'F10' 'FT9' 'FT7' 'FC5' 'FC3' 'FC1' 'FCz' 'FC2' ... 'FC4' 'FC6' 'FT8' 'FT10' 'T9' 'T7' 'C5' 'C3' 'C1' 'Cz' 'C2' 'C4' 'C6' 'T8' 'T10' ... 'TP9' 'TP7' 'CP5' 'CP3' 'CP1' 'CPz' 'CP2' 'CP4' 'CP6' 'TP8' 'TP10' 'P9' 'P7' 'P5' ... 'P3' 'P1' 'Pz' 'P2' 'P4' 'P6' 'P8' 'P10' 'PO9' 'PO7' 'PO3' 'POz' 'PO4' 'PO8' 'PO10' ... 'O1' 'Oz' 'O2' 'O9' 'O10' 'CB1' 'CB2' 'Iz' }; for indexchan = 1:length(chans) if isempty(chans(indexchan).labels), chans(indexchan).labels = ''; end; end; [tmp1 ind1 ind2] = intersect_bc( lower(standardchans), {chans.labels}); if ~isempty(tmp1) | isfield(chans, 'theta') % finding template location files % ------------------------------- setmodel = [ 'tmpdat = get(gcbf, ''userdata'');' ... 'tmpval = get(gcbo, ''value'');' ... 'set(findobj(gcbf, ''tag'', ''elec''), ''string'', tmpdat{tmpval});' ... 'clear tmpval tmpdat;' ]; try EEG = eeg_emptyset; % for dipfitdefs dipfitdefs; tmpp = which('eeglab.m'); tmpp = fullfile(fileparts(tmpp), 'functions', 'resources', 'Standard-10-5-Cap385_witheog.elp'); userdatatmp = { template_models(1).chanfile template_models(2).chanfile tmpp }; clear EEG; catch, userdatatmp = { 'Standard-10-5-Cap385.sfp' 'Standard-10-5-Cap385.sfp' 'Standard-10-5-Cap385_witheog.elp' }; end; % other commands for help/load % ---------------------------- comhelp = [ 'warndlg2(strvcat(''The template file depends on the model'',' ... '''you intend to use for dipole fitting. The default file is fine for'',' ... '''spherical model.'');' ]; commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ... 'if filename ~=0,' ... ' set(findobj(''parent'', gcbf, ''tag'', ''elec''), ''string'', [ filepath filename ]);' ... 'end;' ... 'clear filename filepath tagtest;' ]; if ~isfield(chans, 'theta'), message =1; elseif all(cellfun('isempty', {chans.theta })), message =1; else message =2; end; if message == 1 textcomment = strvcat('Only channel labels are present currently, but some of these labels have known', ... 'positions. Do you want to look up coordinates for these channels using the electrode', ... 'file below? If you have a channel location file for this dataset, press cancel, then', ... 'use button "Read location" in the following gui. If you do not know, just press OK.'); else textcomment = strvcat('Some channel labels may have known locations.', ... 'Do you want to look up coordinates for these channels using the electrode', ... 'file below? If you do not know, press OK.'); end; uilist = { { 'style' 'text' 'string' textcomment } ... { 'style' 'popupmenu' 'string' [ 'use BESA file for 4-shell dipfit spherical model' ... '|use MNI coordinate file for BEM dipfit model|Use spherical file with eye channels' ] ... 'callback' setmodel } ... { } ... { 'style' 'edit' 'string' userdatatmp{1} 'tag' 'elec' } ... { 'style' 'pushbutton' 'string' '...' 'callback' commandload } }; res = inputgui( { 1 [1 0.3] [1 0.3] }, uilist, 'pophelp(''pop_chanedit'')', 'Look up channel locations?', userdatatmp, 'normal', [4 1 1] ); if ~isempty(res) chaninfo.filename = res{2}; args{ curfield } = 'lookup'; args{ curfield+1 } = res{2}; com = args; else return; end; end; else chaninfo.filename = args{ curfield+1 }; end; if strcmpi(chaninfo.filename, 'standard-10-5-cap385.elp') dipfitdefs; chaninfo.filename = template_models(1).chanfile; elseif strcmpi(chaninfo.filename, 'standard_1005.elc') dipfitdefs; chaninfo.filename = template_models(2).chanfile; end; tmplocs = readlocs( chaninfo.filename, 'defaultelp', 'BESA' ); for indexchan = 1:length(chans) if isempty(chans(indexchan).labels), chans(indexchan).labels = ''; end; end; [tmp ind1 ind2] = intersect_bc(lower({ tmplocs.labels }), lower({ chans.labels })); if ~isempty(tmp) chans = struct('labels', { chans.labels }, 'datachan', { chans.datachan }, 'type', { chans.type }); [ind2 ind3] = sort(ind2); ind1 = ind1(ind3); for index = 1:length(ind2) chans(ind2(index)).theta = tmplocs(ind1(index)).theta; chans(ind2(index)).radius = tmplocs(ind1(index)).radius; chans(ind2(index)).X = tmplocs(ind1(index)).X; chans(ind2(index)).Y = tmplocs(ind1(index)).Y; chans(ind2(index)).Z = tmplocs(ind1(index)).Z; chans(ind2(index)).sph_theta = tmplocs(ind1(index)).sph_theta; chans(ind2(index)).sph_phi = tmplocs(ind1(index)).sph_phi; chans(ind2(index)).sph_radius = tmplocs(ind1(index)).sph_radius; end; tmpdiff = setdiff_bc([1:length(chans)], ind2); if ~isempty(tmpdiff) fprintf('Channel lookup: no location for '); for index = 1:(length(tmpdiff)-1) fprintf('%s,', chans(tmpdiff(index)).labels); end; fprintf('%s\nSend us standard location for your channels at [email protected]\n', ... chans(tmpdiff(end)).labels); end; if ~isfield(chans, 'type'), chans(1).type = []; end; end; if ~isempty(findstr(args{ curfield+1 }, 'standard_10')) & ... ~isempty(findstr(args{ curfield+1 }, '.elc')) chaninfo.nosedir = '+Y'; else chaninfo.nosedir = '+X'; end; urchans = chans; for index = 1:length(chans) chans(index).urchan = index; chans(index).ref = ''; end; end; end; end; % call from a figure % ------------------ if ~isempty(fig) userdata.chans = chans; userdata.chaninfo = chaninfo; userdata.commands = { userdata.commands{:} args{:} }; set(fig, 'userdata', userdata); set(findobj(fig, 'tag', 'chaneditnumval'), 'string', num2str(currentpos)); set(findobj(fig, 'tag', 'chaneditscantitle'), 'string', ['Channel number (of ' int2str(length(chans)) ')']); % update GUI with current channel info allfields = fieldnames(chans); if ~isempty(chans) for index = 1:length(allfields) obj = findobj(fig, 'tag', [ 'chanedit' allfields{index}]); if strcmpi(allfields{index}, 'datachan') set(obj, 'value', getfield(chans(currentpos), allfields{index})); else tmpval = getfield(chans(currentpos), allfields{index}); if isstr(tmpval) && strcmpi(tmpval, '[]'), tmpval = ''; end; set(obj, 'string', num2str(tmpval)); end; end; else for index = 1:length(allfields) obj = findobj(fig, 'tag', [ 'chanedit' allfields{index}]); if strcmpi(allfields{index}, 'datachan') set(obj, 'value', 0); else set(obj, 'string', ''); end; end; end; else [chans chaninfo] = eeg_checkchanlocs(chans, chaninfo); if dataset_input, if nchansori == length(chans) for index = 1:length(EEG) EEG(index).chanlocs = chans; EEG(index).chaninfo = chaninfo; end; EEG = eeg_checkset(EEG); % for channel orientation else disp('Channel structure size not consistent with the data so changes will be ignored'); disp('Use the function pop_select(EEG, ''nochannel'', [x]); if you wish the remove data channels'); end; chansout = EEG; else chansout = chans; end; end; return; % format the output field % ----------------------- function strval = reformat( val ) if isnumeric(val) & isempty(val), val = '[]'; end; if isstr(val), strval = [ '''' val '''' ]; else strval = num2str(val); end; % extract text using tokens (not used) % ------------------------------------ function txt = inserttxt( txt, tokins, tokfind); locfind = findstr(txt, tokfind); for index = length(locfind):-1:1 txt = [txt(1:locfind(index)-1) tokins txt(locfind(index):end)]; end; % ask for confirmation % -------------------- function num = popask( text ) ButtonName=questdlg2( text, ... 'Confirmation', 'Cancel', 'Yes','Yes'); switch lower(ButtonName), case 'cancel', num = 0; case 'yes', num = 1; end;
github
lcnhappe/happe-master
pop_newcrossf.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_newcrossf.m
9,208
utf_8
e9ec5bedf577d64df52c8c9838dae4e9
% pop_newcrossf() - Return estimates and plots of event-related spectral coherence % % Usage: % >> pop_newcrossf(EEG, typeproc, num1, num2, tlimits,cycles, % 'key1',value1,'key2',value2, ... ); % Inputs: % INEEG - Input EEG dataset % typeproc - Type of processing: % 1 = process two raw-data channels, % 0 = process two ICA components % num1 - First component or channel number % num2 - Second component or channel number % tlimits - [mintime maxtime] Sub-epoch time limits in ms % cycles - >0 -> Number of cycles in each analysis wavelet % 0 -> Use FFTs (with constant window length) % % Optional inputs: As for newcrossf(). See >> help newcrossf % % Outputs: Same as newcrossf(). No outputs are returned when a % window pops-up to ask for additional arguments % % Author: Arnaud Delorme, CNL / Salk Institute, 11 March 2002 % % See also: timef(), eeglab() % Copyright (C) 11 March 2002 [email protected], Arnaud Delorme, CNL / Salk Institute % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 03-18-02 added title -ad & sm % 04-04-02 added outputs -ad & sm function varargout = pop_newcrossf(EEG, typeproc, num1, num2, tlimits, cycles, varargin ); varargout{1} = ''; % display help if not enough arguments % ------------------------------------ if nargin < 2 help pop_newcrossf; return; end; lastcom = []; if nargin < 3 popup = 1; else popup = isstr(num1) | isempty(num1); if isstr(num1) lastcom = num1; end; end; % pop up window % ------------- if popup [txt vars] = gethelpvar('timef.m'); geometry = { [1 0.5 0.5] [1 0.5 0.5] [1 0.5 0.5] [1 0.5 0.5] [0.92 0.15 0.73] [0.92 0.15 0.73] [1 0.5 0.5] [1 0.8 0.2] [1] [1 1]}; uilist = { { 'Style', 'text', 'string', fastif(typeproc, 'First channel number', 'First component number'), 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,3,[],'1') } {} ... { 'Style', 'text', 'string', fastif(typeproc, 'Second channel number', 'Second component number'), 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,4,[],'2') } {} ... { 'Style', 'text', 'string', 'Epoch time range [min max] (msec)', 'fontweight', 'bold', ... 'tooltipstring', 'Sub epoch time limits' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,5,[],[ int2str(EEG.xmin*1000) ' ' int2str(EEG.xmax*1000) ]) } {} ... { 'Style', 'text', 'string', 'Wavelet cycles (0->FFT, see >> help timef)', 'fontweight', 'bold', ... 'tooltipstring', context('cycles',vars,txt) } ... { 'Style', 'edit', 'string', getkeyval(lastcom,6,[],'3 0.5') } {} ... { 'Style', 'text', 'string', '[set]->log. scale for frequencies (match STUDY)', 'fontweight', 'bold' } ... { 'Style', 'checkbox', 'value', getkeyval(lastcom,'logscale',1,0) } { } ... { 'Style', 'text', 'string', '[set]->Linear coher / [unset]->Phase coher', 'fontweight', 'bold', ... 'tooltipstring', ['Compute linear inter-trial coherence (coher)' 10 ... 'OR Amplitude-normalized inter-trial phase coherence (phasecoher)'] } ... { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'phasecoher','present',1) } { } ... { 'Style', 'text', 'string', 'Bootstrap significance level (Ex: 0.01 -> 1%)', 'fontweight', 'bold', ... 'tooltipstring', context('alpha',vars,txt) } ... { 'Style', 'edit', 'string', getkeyval(lastcom,'alpha') } {} ... { 'Style', 'text', 'string', 'Optional timef() arguments (see Help)', 'fontweight', 'bold', ... 'tooltipstring', 'See newcrossf() help via the Help button on the right...' } ... { 'Style', 'edit', 'string', '''padratio'', 1' } ... { 'Style', 'pushbutton', 'string', 'Help', 'callback', 'pophelp(''newcrossf'');' } ... {} ... { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotersp','present',0), 'string', ... 'Plot coherence amplitude', 'tooltipstring', ... 'Plot coherence ampltitude image in the upper panel' } ... { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotphase','present',0), 'string', ... 'Plot coherence phase', 'tooltipstring', ... 'Plot coherence phase image in the lower panel' } ... }; result = inputgui( geometry, uilist, 'pophelp(''pop_newcrossf'');', ... fastif(typeproc, 'Plot channel cross-coherence -- pop_newcrossf()', ... 'Plot component cross-coherence -- pop_newcrossf()')); if length( result ) == 0 return; end; num1 = eval( [ '[' result{1} ']' ] ); num2 = eval( [ '[' result{2} ']' ] ); tlimits = eval( [ '[' result{3} ']' ] ); cycles = eval( [ '[' result{4} ']' ] ); if result{5}, if isempty(result{8}), result{8} = '''freqscale'', ''log'''; else result{8} = [ result{8} ', ''freqscale'', ''log''' ]; end; end; if result{6} options = [',''type'', ''coher''' ]; else options = [',''type'', ''phasecoher''' ]; end; % add topoplot % ------------ if isfield(EEG.chanlocs, 'theta') && ~isempty(EEG.chanlocs(num1).theta) && ~isempty(EEG.chanlocs(num2).theta) if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end; if typeproc == 1 options = [options ', ''topovec'', [' int2str([num1 num2]) ... '], ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ]; else % typeproc == 0 options = [options ', ''topovec'', EEG.icawinv(:, [' int2str([num1 num2]) ... '])'', ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ]; end; end; % add title % --------- if isempty( findstr( 'title', result{8})) if ~isempty(EEG.chanlocs) & typeproc chanlabel1 = EEG.chanlocs(num1).labels; chanlabel2 = EEG.chanlocs(num2).labels; else chanlabel1 = int2str(num1); chanlabel2 = int2str(num2); end; if result{6} options = [options ', ''title'',' fastif(typeproc, '''Channel ', '''Component ') chanlabel1 '-' chanlabel2 ... ' Coherence''']; else options = [options ', ''title'',' fastif(typeproc, '''Channel ', '''Component ') chanlabel1 '-' chanlabel2 ... ' Phase Coherence''' ]; end; end; if ~isempty( result{7} ) options = [ options ', ''alpha'',' result{7} ]; end; if ~isempty( result{8} ) options = [ options ',' result{8} ]; end; if ~result{9} options = [ options ', ''plotersp'', ''off''' ]; end; if ~result{10} options = [ options ', ''plotphase'', ''off''' ]; end; figure; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; else options = [ ',' vararg2str(varargin) ]; end; % compute epoch limits % -------------------- if isempty(tlimits) tlimits = [EEG.xmin, EEG.xmax]; end; pointrange1 = round(max((tlimits(1)/1000-EEG.xmin)*EEG.srate, 1)); pointrange2 = round(min((tlimits(2)/1000-EEG.xmin)*EEG.srate, EEG.pnts)); pointrange = [pointrange1:pointrange2]; % call function sample either on raw data or ICA data % --------------------------------------------------- if typeproc == 1 tmpsig1 = EEG.data(num1,pointrange,:); tmpsig2 = EEG.data(num2,pointrange,:); else if ~isempty( EEG.icasphere ) eeglab_options; % changed from eeglaboptions 3/30/02 -sm tmpsig1 = eeg_getdatact(EEG, 'component', num1, 'samples',pointrange); tmpsig2 = eeg_getdatact(EEG, 'component', num2, 'samples',pointrange); else error('You must run ICA first'); end; end; tmpsig1 = reshape( tmpsig1, 1, size(tmpsig1,2)*size(tmpsig1,3)); tmpsig2 = reshape( tmpsig2, 1, size(tmpsig2,2)*size(tmpsig2,3)); % outputs % ------- outstr = ''; if ~popup for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end; if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end; end; % plot the datas and generate output command % -------------------------------------------- if length( options ) < 2 options = ''; end; varargout{1} = sprintf('figure; pop_newcrossf( %s, %d, %d, %d, [%s], [%s] %s);', ... inputname(1), typeproc, num1, num2, int2str(tlimits), num2str(cycles), options); com = sprintf( '%s newcrossf( tmpsig1, tmpsig2, length(pointrange), [tlimits(1) tlimits(2)], EEG.srate, cycles %s);', outstr, options); eval(com) return; % get contextual help % ------------------- function txt = context(var, allvars, alltext); loc = strmatch( var, allvars); if ~isempty(loc) txt= alltext{loc(1)}; else disp([ 'warning: variable ''' var ''' not found']); txt = ''; end;
github
lcnhappe/happe-master
pop_spectopo.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_spectopo.m
17,090
utf_8
67c293563d033f27b24aa4f35c39f569
% pop_spectopo() - Plot spectra of specified data channels or components. % Show scalp maps of power at specified frequencies. % Calls spectopo(). % Usage: % >> pop_spectopo( EEG, dataflag); % pops-up interactive window % OR % >> [spectopo_outputs] = pop_spectopo( EEG, dataflag, timerange, ... % process, 'key', 'val',...); % returns spectopo() outputs % % Graphic interface for EEG data (dataflag = 1): % "Epoch time range" - [edit box] [min max] Epoch time range (in ms) to use % in computing the spectra (by default the whole epoch or data). % Command line equivalent: 'timerange' % "Percent data to sample" - [edit box] Percentage of data to use in % computing the spectra (low % speeds up the computation). % spectopo() equivalent: 'percent' % "Frequencies to plot as scalp maps" - [edit box] Vector of 1-7 frequencies to % plot topoplot() scalp maps of power at all channels. % spectopo() equivalent: 'freqs' % "Apply to EEG|ERP|BOTH" - [edit box] Plot spectra of the 'EEG', 'ERP' or of 'BOTH'. % NOTE: This edit box does not appear for continuous data. % Command line equivalent: 'process' % "Plotting frequency range" - [edit box] [min max] Frequency range (in Hz) to plot. % spectopo() equivalent: 'freqrange' % "Spectral and scalp map options (see topoplot)" - [edit box] 'key','val','key',... % sequence of arguments passed to spectopo() for details of the % spectral decomposition or to topoplot() to adjust details of % the scalp maps. For details see >> help topoplot % % Graphic interface for components (dataflag = 0): % "Epoch time range" - [edit box] [min max] Epoch time range (in ms) to use % in computing the spectra (by default the whole epoch or data). % Command line equivalent: 'timerange' % "Frequency (Hz) to analyze" - [edit box] Single frequency (Hz) at which to plot % component contributions. spectopo() equivalent: 'freqs' % "Electrode number to analyze" - [edit box] 1-nchans --> Plot component contributions % at this channel; [] --> Plot contributions at channel with max % power; 0 --> Plot component contributions to global (RMS) power. % spectopo() equivalent: 'plotchan' % "Percent data to sample" - [edit box] Percent of data to use in computing the spectra % (low % speeds up the computation). spectopo() equivalent: 'percent' % "Components to include ..." - [Edit box] Only compute spectrum of a subset of the % components. spectopo() equivalent: 'icacomps' % "Number of largest-contributing ..." - [edit box] Number of component maps % to plot. spectopo() equivalent: 'nicamaps' % "Else, map only these components ..." - [edit box] Use this entry to override % plotting maps of the components that project most strongly (at % the selected frequency) to the the selected channel (or whole scalp % if 'plotchan' (above) == 0). spectopo() equivalent: 'icamaps' % "[Checked] Compute comp spectra ..." - [checkbox] If checked, compute the spectra % of the selected component activations; else, if unchecked % compute the spectra of (the data MINUS each selected component). % spectopo() equivalent: 'icamode' % "Plotting frequency range" - [edit box] [min max] Frequency range (in Hz) to plot. % spectopo() equivalent: 'freqrange' % "Spectral and scalp map options (see topoplot)" - [edit box] 'key','val','key',... % sequence of arguments passed to spectopo() for details of the % spectral decomposition or to topoplot() to adjust details of % the scalp maps. For details see >> help topoplot % Inputs: % EEG - Input EEGLAB dataset % dataflag - If 1, process the input data channels. % If 0, process its component activations. % {Default: 1, process the data channels}. % timerange - [min_ms max_ms] Epoch time range to use in computing the spectra % {Default: whole input epochs} % process - 'EEG'|ERP'|'BOTH' If processing data epochs, work on either the % mean single-trial 'EEG' spectra, the spectrum of the trial-average % 'ERP', or plot 'BOTH' the EEG and ERP spectra. {Default: 'EEG'} % % Optional inputs: % 'key','val' - Optional topoplot() and/or spectopo() plotting arguments % {Default, 'electrodes','off'} % % Outputs: As from spectopo(). When nargin<2, a query window pops-up % to ask for additional arguments and NO outputs are returned. % Note: Only the outputs of the 'ERP' spectral analysis % are returned when plotting 'BOTH' ERP and EEG spectra. % % Author: Arnaud Delorme & Scott Makeig, CNL / Salk Institute, 10 March 2002 % % See also: spectopo(), topoplot() % Copyright (C) 10 March 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 03-15-02 debugging -ad % 03-16-02 add all topoplot options -ad % 04-04-02 added outputs -ad & sm function varargout = pop_spectopo( EEG, dataflag, timerange, processflag, varargin); varargout{1} = ''; if nargin < 1 help pop_spectopo; return; end; if nargin < 2 dataflag = 1; end; if nargin < 3 processflag = 'EEG'; end; chanlocs_present = 0; if ~isempty(EEG.chanlocs) if isfield(EEG.chanlocs, 'theta') tmpchanlocs = EEG.chanlocs; if any(~cellfun(@isempty, { tmpchanlocs.theta })) chanlocs_present = 1; end; end; end; if nargin < 3 if dataflag geometry = { [2 1] [2 1] [2 1] [2 1] [2 1] [2 1]}; scalp_freq = fastif(chanlocs_present, { '6 10 22' }, { '' 'enable' 'off' }); promptstr = { { 'style' 'text' 'string' 'Epoch time range to analyze [min_ms max_ms]:' }, ... { 'style' 'edit' 'string' [num2str( EEG.xmin*1000) ' ' num2str(EEG.xmax*1000)] }, ... { 'style' 'text' 'string' 'Percent data to sample (1 to 100):'}, ... { 'style' 'edit' 'string' '15' }, ... { 'style' 'text' 'string' 'Frequencies to plot as scalp maps (Hz):'}, ... { 'style' 'edit' 'string' scalp_freq{:} }, ... { 'style' 'text' 'string' 'Apply to EEG|ERP|BOTH:'}, ... { 'style' 'edit' 'string' 'EEG' }, ... { 'style' 'text' 'string' 'Plotting frequency range [lo_Hz hi_Hz]:'}, ... { 'style' 'edit' 'string' '2 25' }, ... { 'style' 'text' 'string' 'Spectral and scalp map options (see topoplot):' } ... { 'style' 'edit' 'string' '''electrodes'',''off''' } }; if EEG.trials == 1 geometry(3) = []; promptstr(7:8) = []; end; result = inputgui( geometry, promptstr, 'pophelp(''pop_spectopo'')', 'Channel spectra and maps -- pop_spectopo()'); if size(result,1) == 0 return; end; timerange = eval( [ '[' result{1} ']' ] ); options = []; if isempty(EEG.chanlocs) disp('Topographic plot options ignored. First import a channel location file'); disp('To plot a single channel, use channel property menu or the following call'); disp(' >> figure; chan = 1; spectopo(EEG.data(chan,:,:), EEG.pnts, EEG.srate);'); end; if eval(result{2}) ~= 100, options = [ options ', ''percent'', ' result{2} ]; end; if ~isempty(result{3}) & ~isempty(EEG.chanlocs), options = [ options ', ''freq'', [' result{3} ']' ]; end; if EEG.trials ~= 1 processflag = result{4}; if ~isempty(result{5}), options = [ options ', ''freqrange'',[' result{5} ']' ]; end; if ~isempty(result{6}), options = [ options ',' result{6} ]; end; else if ~isempty(result{4}), options = [ options ', ''freqrange'',[' result{4} ']' ]; end; if ~isempty(result{5}), options = [ options ',' result{5} ]; end; end; else if ~chanlocs_present error('pop_spectopo(): cannot plot component contributions without channel locations'); end; geometry = { [2 1] [2 1] [2 1] [2 1] [2 1] [2 1] [2 1] [2 0.18 0.78] [2 1] [2 1] }; promptstr = { { 'style' 'text' 'string' 'Epoch time range to analyze [min_ms max_ms]:' }, ... { 'style' 'edit' 'string' [num2str( EEG.xmin*1000) ' ' num2str(EEG.xmax*1000)] }, ... { 'style' 'text' 'string' 'Frequency (Hz) to analyze:'}, ... { 'style' 'edit' 'string' '10' }, ... { 'style' 'text' 'string' 'Electrode number to analyze ([]=elec with max power; 0=whole scalp):', 'tooltipstring', ... ['If value is 1 to nchans, plot component contributions at this channel' 10 ... 'If value is [], plot contributions at channel with max. power' 10 ... 'If value is 0, plot component contributions to global (RMS) power'] }, ... { 'style' 'edit' 'string' '0' }, ... { 'style' 'text' 'string' 'Percent data to sample (1 to 100):'}, ... { 'style' 'edit' 'string' '20' }, ... { 'style' 'text' 'string' 'Components to include in the analysis:' }, ... { 'style' 'edit' 'string' ['1:' int2str(size(EEG.icaweights,1))] }, ... { 'style' 'text' 'string' 'Number of largest-contributing components to map:' }, ... { 'style' 'edit' 'string' '5' }, ... { 'style' 'text' 'string' ' Else, map only these component numbers:', 'tooltipstring', ... ['Use this entry to override plotting maps of the components that project' 10 ... 'most strongly to the selected channel (or whole scalp) at the selected frequency.' ] }, ... { 'style' 'edit' 'string' '' }, ... { 'style' 'text' 'string' '[Checked] Compute comp spectra; [Unchecked] (data-comp) spectra:', 'tooltipstring' ... ['If checked, compute the spectra of the selected component activations' 10 ... 'else [if unchecked], compute the spectra of (the data MINUS each slected component)']}, ... { 'style' 'checkbox' 'value' 1 } { }, ... { 'style' 'text' 'string' 'Plotting frequency range ([min max] Hz):'}, ... { 'style' 'edit' 'string' '2 25' }, ... { 'style' 'text' 'string' 'Spectral and scalp map options (see topoplot):' } ... { 'style' 'edit' 'string' '''electrodes'',''off''' } }; result = inputgui( geometry, promptstr, 'pophelp(''spectopo'')', 'Component spectra and maps -- pop_spectopo()'); if size(result,1) == 0 return; end; timerange = eval( [ '[' result{1} ']' ] ); options = ''; if ~isempty(result{2}) , options = [ options ', ''freq'', [' result{2} ']' ]; end; if ~isempty(result{3}) , options = [ options ', ''plotchan'', ' result{3} ]; end; if eval(result{4}) ~= 100, options = [ options ', ''percent'', ' result{4} ]; end; if ~isempty(result{5}) , options = [ options ', ''icacomps'', [' result{5} ']' ]; end; if ~isempty(result{6}) , options = [ options ', ''nicamaps'', ' result{6} ]; end; if ~isempty(result{7}) && ~isempty(result{5}) try list2 = eval(result{7}); catch,list2 = str2double(result{7}); end try list1 = eval(result{5}); catch,list1 = str2double(result{5}); end [memberflag, pos] = ismember(list2,list1); if sum(memberflag) options = [ options ', ''icamaps'', [' num2str(pos(memberflag)) ']' ]; else fprintf(2,'pop_spectopo error: IC(s) selected do not match the ones on the list\n'); return; end end; if ~result{8}, options = [ options ', ''icamode'', ''sub''' ]; end; if ~isempty(result{9}), options = [ options ', ''freqrange'',[' result{9} ']' ]; end; if ~isempty(result{10}), options = [ options ',' result{10} ]; end; end; figure('tag', 'spectopo'); set(gcf,'Name','spectopo()'); else if ~isempty(varargin) options = [',' vararg2str(varargin)]; else options = ''; end; if isempty(timerange) timerange = [ EEG.xmin*1000 EEG.xmax*1000 ]; end; if nargin < 3 percent = 100; end; if nargin < 4 topofreqs = []; end; end; % set the background color of the figure try, tmpopt = struct(varargin{:}); if ~isfield(tmpopt, 'plot') || strcmpi(tmpopt, 'on'), icadefs; set(gcf, 'color', BACKCOLOR); end; catch, end; switch processflag, case {'EEG' 'eeg' 'ERP' 'erp' 'BOTH' 'both'},; otherwise, if nargin <3, close; end; error('Pop_spectopo: processflag must be ''EEG'', ''ERP'' or ''BOTH'''); end; if EEG.trials == 1 & ~strcmp(processflag,'EEG') if nargin <3, close; end; error('pop_spectopo(): must use ''EEG'' mode when processing continuous data'); end; if ~isempty(EEG.chanlocs) if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end; spectopooptions = [ options ', ''verbose'', ''off'', ''chanlocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ]; if dataflag == 0 % i.e. components spectopooptions = [ spectopooptions ', ''weights'', EEG.icaweights*EEG.icasphere' ]; end; else spectopooptions = options; end; if ~dataflag spectopooptions = [ spectopooptions ', ''icawinv'', EEG.icawinv, ''icachansind'', EEG.icachansind' ]; end; % The programming here is a bit redundant but it tries to optimize % memory usage. % ---------------------------------------------------------------- if timerange(1)/1000~=EEG.xmin | timerange(2)/1000~=EEG.xmax posi = round( (timerange(1)/1000-EEG.xmin)*EEG.srate )+1; posf = min(round( (timerange(2)/1000-EEG.xmin)*EEG.srate )+1, EEG.pnts ); pointrange = posi:posf; if posi == posf, error('pop_spectopo(): empty time range'); end; fprintf('pop_spectopo(): selecting time range %6.2f ms to %6.2f ms (points %d to %d)\n', ... timerange(1), timerange(2), posi, posf); end; if isempty(EEG.icachansind) || dataflag == 1, chaninds = 1:EEG.nbchan; else chaninds = EEG.icachansind; end; if exist('pointrange') == 1, SIGTMP = EEG.data(chaninds,pointrange,:); totsiz = length( pointrange); else SIGTMP = EEG.data(chaninds,:,:); totsiz = EEG.pnts; end; % add boundaries if continuous data % ---------------------------------- if EEG.trials == 1 & ~isempty(EEG.event) & isfield(EEG.event, 'type') & isstr(EEG.event(1).type) tmpevent = EEG.event; boundaries = strmatch('boundary', {tmpevent.type}); if ~isempty(boundaries) if exist('pointrange') boundaries = [ tmpevent(boundaries).latency ] - 0.5-pointrange(1)+1; boundaries(find(boundaries>=pointrange(end)-pointrange(1))) = []; boundaries(find(boundaries<1)) = []; boundaries = [0 boundaries pointrange(end)-pointrange(1)]; else boundaries = [0 [ tmpevent(boundaries).latency ]-0.5 EEG.pnts ]; end; spectopooptions = [ spectopooptions ',''boundaries'',[' int2str(round(boundaries)) ']']; end; fprintf('Pop_spectopo: finding data discontinuities\n'); end; % outputs % ------- outstr = ''; if nargin >= 2 for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end; if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end; end; % plot the data and generate output and history commands % ------------------------------------------------------ popcom = sprintf('figure; pop_spectopo(%s, %d, [%s], ''%s'' %s);', inputname(1), dataflag, num2str(timerange), processflag, options); switch processflag case { 'EEG' 'eeg' }, SIGTMP = reshape(SIGTMP, size(SIGTMP,1), size(SIGTMP,2)*size(SIGTMP,3)); com = sprintf('%s spectopo( SIGTMP, totsiz, EEG.srate %s);', outstr, spectopooptions); eval(com) case { 'ERP' 'erp' }, com = sprintf('%s spectopo( mean(SIGTMP,3), totsiz, EEG.srate %s);', outstr, spectopooptions); eval(com) case { 'BOTH' 'both' }, sbplot(2,1,1); com = sprintf('%s spectopo( mean(SIGTMP,3), totsiz, EEG.srate, ''title'', ''ERP'' %s);', outstr, spectopooptions); eval(com) SIGTMP = reshape(SIGTMP, size(SIGTMP,1), size(SIGTMP,2)*size(SIGTMP,3)); sbplot(2,1,2); com = sprintf('%s spectopo( SIGTMP, totsiz, EEG.srate, ''title'', ''EEG'' %s);', outstr, spectopooptions); eval(com) end; if nargout < 2 & nargin < 3 varargout{1} = popcom; end; return;
github
lcnhappe/happe-master
pop_epoch.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_epoch.m
17,066
utf_8
24e8804d26b9485c07243313c9baf197
% pop_epoch() - Convert a continuous EEG dataset to epoched data by extracting % data epochs time locked to specified event types or event indices. % May also sub-epoch an already epoched dataset (if sub-epochs are % same size or smaller). This pop_function calls epoch(). % Usage: % >> OUTEEG = pop_epoch( EEG); % pop-up a data entry window % >> OUTEEG = pop_epoch( EEG, events, timelimits); % >> [OUTEEG, indices] = pop_epoch( EEG, typerange, timelimits,'key1', value1 ...); % % Graphic interface: % "Time-locking event type(s)" - [edit box] Select 'Edit > Event values' % to see a list of event.type values; else use the push button. % To use event types containing spaces, enter in single-quotes. % epoch() function command line equivalent: 'typerange' % "..." - [push button] scroll event types. % "Epoch limits" - [edit box] epoch latency range [start, end] in seconds relative % to the time-locking events. epoch() function equivalent: 'timelim' % "Name for the new dataset" - [edit box] % epoch() function equivalent: 'newname' % "Out-of-bounds EEG ..." - [edit box] Rejection limits ([min max], []=none). % epoch() function equivalent: 'valuelim' % Inputs: % EEG - Input dataset. Data may already be epoched; in this case, % extract (shorter) subepochs time locked to epoch events. % typerange - Cell array of event types to time lock to. 'eventindices' % {default {} --> time lock epochs to any type of event} % (Note: An event field called 'type' must be defined in the % 'EEG.event' structure. The command line argument is % 'eventindices' below). % timelim - Epoch latency limits [start end] in seconds relative to % the time-locking event {default: [-1 2]} % % Optional inputs: % 'eventindices'- [integer vector] Extract data epochs time locked to the % indexed event numbers. % 'valuelim' - [min max] or [max]. Lower and upper bound latencies for % trial data. Else if one positive value is given, use its % negative as the lower bound. The given values are also % considered outliers (min max) {default: none} % 'verbose' - ['yes'|'no'] {default: 'yes'} % 'newname' - [string] New dataset name {default: "[old_dataset] epochs"} % 'epochinfo'- ['yes'|'no'] Propagate event information into the new % epoch structure {default: 'yes'} % % Outputs: % OUTEEG - output dataset % indices - indices of accepted events % % Authors: Arnaud Delorme and Hilit Serby, SCCN, INC, UCSD, 2001 % % See also: eeglab, epoch % deprecated % 'timeunit' - Time unit ['seconds'|'points'] If 'seconds,' consider events % times to be in seconds. If 'points,' consider events as % indices into the data array. {default: 'points'} % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 02-13-02 introduction of 'key', val arguments -ad % 02-13-02 rereferencing of events -ad % 03-18-02 interface and debugging -ad % 03-27-02 interface and debugging -ad & sm function [EEG, indices, com] = pop_epoch( EEG, events, lim, varargin ); if nargin < 1 help pop_epoch; return; end; com = ''; indices = []; if isempty(EEG.event) if EEG.trials > 1 & EEG.xmin <= 0 & EEG.xmax >=0 disp('No EEG.event structure found: creating events of type ''TLE'' (Time-Locking Event) at time 0'); EEG.event(EEG.trials).epoch = EEG.trials; for trial = 1:EEG.trials EEG.event(trial).epoch = trial; EEG.event(trial).type = 'TLE'; EEG.event(trial).latency = -EEG.xmin*EEG.srate+1+(trial-1)*EEG.pnts; end; else disp('Cannot epoch data with no events'); beep; return; end; end; if ~isfield(EEG.event, 'latency'), disp( 'Absent latency field in event array/structure: must name one of the fields ''latency'''); beep; return; end; if size(EEG.data,3) > 1 epochlim = [num2str( round(EEG.xmin*1000,1)) ' ' num2str(round(EEG.xmax*1000,1))]; else epochlim = '-1 2'; end OLDEEG = EEG; if nargin < 3 % popup window parameters % ----------------------- promptstr = { strvcat('Time-locking event type(s) ([]=all):', ... 'Select ''Edit > Event values'' to see type values.'), ... 'Epoch limits [start, end] in seconds:', ... 'Name for the new dataset:', ... 'Out-of-bounds EEG rejection limits ([min max], []=none):' }; cbevent = ['if ~isfield(EEG.event, ''type'')' ... ' errordlg2(''No type field'');' ... 'else' ... ' tmpevent = EEG.event;' ... ' if isnumeric(EEG.event(1).type),' ... ' [tmps,tmpstr] = pop_chansel(unique([ tmpevent.type ]));' ... ' else,' ... ' [tmps,tmpstr] = pop_chansel(unique({ tmpevent.type }));' ... ' end;' ... ' if ~isempty(tmps)' ... ' set(findobj(''parent'', gcbf, ''tag'', ''events''), ''string'', tmpstr);' ... ' end;' ... 'end;' ... 'clear tmps tmpevent tmpv tmpstr tmpfieldnames;' ]; geometry = { [2 1 0.5] [2 1 0.5] [2 1.5] [2 1 0.5] }; uilist = { { 'style' 'text' 'string' 'Time-locking event type(s) ([]=all)' } ... { 'style' 'edit' 'string' '' 'tag' 'events' } ... { 'style' 'pushbutton' 'string' '...' 'callback' cbevent } ... { 'style' 'text' 'string' 'Epoch limits [start, end] in seconds' } ... { 'style' 'edit' 'string' epochlim } ... { } ... { 'style' 'text' 'string' 'Name for the new dataset' } ... { 'style' 'edit' 'string' fastif(isempty(EEG.setname), '', [ EEG.setname ' epochs' ]) } ... { 'style' 'text' 'string' 'Out-of-bounds EEG limits if any [min max]' } ... { 'style' 'edit' 'string' '' } { } }; result = inputgui( geometry, uilist, 'pophelp(''pop_epoch'')', 'Extract data epochs - pop_epoch()'); if length(result) == 0 return; end; if strcmpi(result{1}, '[]'), result{1} = ''; end; if ~isempty(result{1}) if strcmpi(result{1}(1),'''') % If event type appears to be in single-quotes, use comma % and single-quote as delimiter between event types. toby 2.24.2006 % fixed Arnaud May 2006 events = eval( [ '{' result{1} '}' ] ); else events = parsetxt( result{1}); end; else events = {}; end lim = eval( [ '[' result{2} ']' ] ); args = {}; if ~isempty( result{3} ), args = { args{:}, 'newname', result{3} }; end; if ~isempty( result{4} ), args = { args{:}, 'valuelim', eval( [ '[' result{4} ']' ] ) }; end; args = { args{:}, 'epochinfo', 'yes' }; else % no interactive inputs args = varargin; end; % create structure % ---------------- if ~isempty(args) try, g = struct(args{:}); catch, disp('pop_epoch(): wrong syntax in function arguments'); return; end; else g = []; end; % test the presence of variables % ------------------------------ try, g.epochfield; catch, g.epochfield = 'type'; end; % obsolete try, g.timeunit; catch, g.timeunit = 'points'; end; try, g.verbose; catch, g.verbose = 'on'; end; try, g.newname; catch, g.newname = fastif(isempty(EEG.setname), '', [EEG.setname ' epochs' ]); end; try, g.eventindices; catch, g.eventindices = 1:length(EEG.event); end; try, g.epochinfo; catch, g.epochinfo = 'yes'; end; try, if isempty(g.valuelim), g.valuelim = [-Inf Inf]; end; catch, g.valuelim = [-Inf Inf]; end; % transform string events into a int array of column indices % ---------------------------------------------------------- tmpevent = EEG.event; tmpeventlatency = [ tmpevent(:).latency ]; [tmpeventlatency Itmp] = sort(tmpeventlatency); EEG.event = EEG.event(Itmp); % sort by ascending time Ievent = g.eventindices; if ~isempty( events ) % select the events for epoching % ------------------------------ Ieventtmp = []; tmpevent = EEG.event; tmpeventtype = { tmpevent.type }; if iscell(events) if isstr(EEG.event(1).type) for index2 = 1:length( events ) tmpevent = events{index2}; if ~isstr( tmpevent ), tmpevent = num2str( tmpevent ); end; Ieventtmp = [ Ieventtmp ; strmatch(tmpevent, tmpeventtype, 'exact') ]; end; else for index2 = 1:length( events ) tmpevent = events{index2}; if isstr( tmpevent ),tmpevent = str2num( tmpevent ); end; if isempty( tmpevent ), error('pop_epoch(): string entered in a numeric field'); end; Ieventtmp = [ Ieventtmp find(tmpevent == [ tmpeventtype{:} ]) ]; end; end; else error('pop_epoch(): multiple event types must be entered as {''a'', ''cell'', ''array''}'); return; end; Ievent = sort(intersect(Ievent, Ieventtmp)); end; % select event latencies for epoching %------------------------------------ Ievent = sort(Ievent); alllatencies = tmpeventlatency(Ievent); if isempty(alllatencies) error('pop_epoch(): empty epoch range (no epochs were found).'); return; end; fprintf('pop_epoch():%d epochs selected\n', length(alllatencies)); try % ---------------------------------------------------- % For AMICA probabilities...Temporarily add model probabilities as channels %----------------------------------------------------- if isfield(EEG.etc, 'amica') && ~isempty(EEG.etc.amica) && isfield(EEG.etc.amica, 'v_smooth') && ~isempty(EEG.etc.amica.v_smooth) && ~isfield(EEG.etc.amica,'prob_added') if isfield(EEG.etc.amica, 'num_models') && ~isempty(EEG.etc.amica.num_models) if size(EEG.data,2) == size(EEG.etc.amica.v_smooth,2) && size(EEG.data,3) == size(EEG.etc.amica.v_smooth,3) && size(EEG.etc.amica.v_smooth,1) == EEG.etc.amica.num_models EEG = eeg_formatamica(EEG); %-------------------- [EEG indices com] = pop_epoch(EEG,events,lim,args{:}); %--------------------------------- EEG = eeg_reformatamica(EEG); EEG = eeg_checkamica(EEG); return; else disp('AMICA probabilities not compatible with size of data, model probabilities cannot be epoched...') end end end % ---------------------------------------------------- catch warnmsg = strcat('your dataset contains amica information, but the amica plugin is not installed. Continuing and ignoring amica information.'); warning(warnmsg) end % change boundaries in rare cases when limits do not include time-locking events % ------------------------------------------------------------------------------ tmpevents = EEG.event; if lim(1) > 0 && ischar(EEG.event(1).type) % go through all onset latencies for Z1 = length(alllatencies):-1:1 % if there is any event in between trigger and epoch onset which are boundary events selEvt = find([tmpevents.latency] > alllatencies(Z1) & [tmpevents.latency] < alllatencies(Z1) + lim(1) * EEG.srate); selEvt = selEvt(strcmp({tmpevents(selEvt).type}, 'boundary')); if any(selEvt) if sum([tmpevents(selEvt).duration]) > lim(1) * EEG.srate alllatencies(Z1) = []; else % correct the latencies by the duration of the data that were cutout alllatencies(Z1) = alllatencies(Z1) - sum([tmpevents(selEvt).duration]); end; end end end if lim(2) < 0 && ischar(EEG.event(1).type) % go through all onset latencies for Z1 = length(alllatencies):-1:1 % if there is any event in between trigger and epoch onset which are boundary events selEvt = find([tmpevents.latency] < alllatencies(Z1) & [tmpevents.latency] > alllatencies(Z1) + lim(2) * EEG.srate); selEvt = selEvt(strcmp({tmpevents(selEvt).type}, 'boundary')); if any(selEvt) if sum([tmpevents(selEvt).duration]) > -lim(2) * EEG.srate alllatencies(Z1) = []; else % correct the latencies by the duration of the data that were cutout alllatencies(Z1) = alllatencies(Z1) + sum([tmpevents(selEvt).duration]); end; end end end % select event time format and epoch % ---------------------------------- switch lower( g.timeunit ) case 'points', [EEG.data tmptime indices epochevent]= epoch(EEG.data, alllatencies, [lim(1) lim(2)]*EEG.srate, ... 'valuelim', g.valuelim, 'allevents', tmpeventlatency); tmptime = tmptime/EEG.srate; case 'seconds', [EEG.data tmptime indices epochevent]= epoch(EEG.data, alllatencies, lim, 'valuelim', g.valuelim, ... 'srate', EEG.srate, 'allevents', tmpeventlatency); otherwise, disp('pop_epoch(): invalid event time format'); beep; return; end; alllatencies = alllatencies(indices); fprintf('pop_epoch():%d epochs generated\n', length(indices)); % update other fields % ------------------- if lim(1) ~= tmptime(1) & lim(2)-1/EEG.srate ~= tmptime(2) fprintf('pop_epoch(): time limits have been adjusted to [%3.3f %3.3f] to fit data points limits\n', ... tmptime(1), tmptime(2)+1/EEG.srate); end; EEG.xmin = tmptime(1); EEG.xmax = tmptime(2); EEG.pnts = size(EEG.data,2); EEG.trials = size(EEG.data,3); EEG.icaact = []; if ~isempty(EEG.setname) if ~isempty(EEG.comments) EEG.comments = strvcat(['Parent dataset "' EEG.setname '": ----------'], EEG.comments); end; EEG.comments = strvcat(['Parent dataset: ' EEG.setname ], ' ', EEG.comments); end; EEG.setname = g.newname; % count the number of events to duplicate and duplicate them % ---------------------------------------------------------- totlen = 0; for index=1:EEG.trials, totlen = totlen + length(epochevent{index}); end; EEG.event(1).epoch = 0; % create the epoch field (for assignment consistency afterwards) if totlen ~= 0 newevent(totlen) = EEG.event(1); % reserve array else newevent = []; end; % modify the event structure accordingly (latencies and add epoch field) % ---------------------------------------------------------------------- allevents = []; count = 1; for index=1:EEG.trials for indexevent = epochevent{index} newevent(count) = EEG.event(indexevent); newevent(count).epoch = index; newevent(count).latency = newevent(count).latency ... - alllatencies(index) - tmptime(1)*EEG.srate + 1 + EEG.pnts*(index-1); count = count + 1; end; end; EEG.event = newevent; EEG.epoch = []; EEG = eeg_checkset(EEG, 'eventconsistency'); % check for boundary events % ------------------------- disp('pop_epoch(): checking epochs for data discontinuity'); if ~isempty(EEG.event) & isstr(EEG.event(1).type) tmpevent = EEG.event; boundaryindex = strmatch('boundary', { tmpevent.type }); if ~isempty(boundaryindex) indexepoch = []; for tmpindex = boundaryindex if isfield(tmpevent, 'epoch') indexepoch = [indexepoch tmpevent(tmpindex).epoch ]; else indexepoch = 1; % only one epoch end; end; EEG = pop_select(EEG, 'notrial', indexepoch); % update the "indices of accepted events", too indices = indices(setdiff(1:length(indices),indexepoch)); end; end; % generate text command % --------------------- com = sprintf('%s = pop_epoch( %s, { ', inputname(1), inputname(1)); for j=1:length(events); if isstr( events{j} ) com = sprintf('%s ''%s'' ', com, events{j} ); else com = sprintf('%s [%s] ', com, num2str(events{j}) ); end; end; com = sprintf('%s }, [%s]', com, num2str(lim)); for i=1:2:length(args) if ~isempty( args{i+1} ) if isstr( args{i+1} ) com = sprintf('%s, ''%s'', ''%s''', com, args{i}, args{i+1} ); else com = sprintf('%s, ''%s'', [%s]', com, args{i}, num2str(args{i+1}) ); end; end; end; com = [com ');']; return; % text command
github
lcnhappe/happe-master
pop_importerplab.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_importerplab.m
8,744
utf_8
20e873906bf7c84c0da1da82b1e62906
% pop_importerplab() - import ERPLAB event list file and bin file into % EEGLAB event structure for use in STUDY processing % % Usage: % >> OUTEEG = pop_sample( INEEG, file1, file2); % % Inputs: % INEEG - input EEG dataset % file1 - ERPLAB event list text file % file2 - ERPLAB bin file % ncbins - [0|1] import all bins including non-contrast bins. Default is % 0 (no). % % Outputs: % OUTEEG - output dataset % Copyright (C) 2016 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 [EEG, com] = pop_importerplab( EEG, file1, file2, ncbins) % the command output is a hidden output that does not have to % be described in the header com = ''; % this initialization ensure that the function will return something % if the user press the cancel button % display help if not enough arguments % ------------------------------------ if nargin < 1 help pop_importerplab; return; end; if nargin < 3 ncbins = false; end; % pop up window % ------------- if nargin < 3 promptstr = { strvcat('Time-locking event type(s) ([]=all):', ... 'Select ''Edit > Event values'' to see type values.'), ... 'Epoch limits [start, end] in seconds:', ... 'Name for the new dataset:', ... 'Out-of-bounds EEG rejection limits ([min max], []=none):' }; commandload1 = [ '[filename, filepath] = uigetfile(''*'', ''Select an event list text file'');' ... 'if filename ~=0,' ... ' set(findobj(''parent'', gcbf, ''tag'', ''file1''), ''string'', [ filepath filename ]);' ... 'end;' ... 'clear filename filepath;' ]; commandload2 = [ '[filename, filepath] = uigetfile(''*'', ''Select an bin text file'');' ... 'if filename ~=0,' ... ' set(findobj(''parent'', gcbf, ''tag'', ''file2''), ''string'', [ filepath filename ]);' ... 'end;' ... 'clear filename filepath;' ]; geometry = { [2 2 0.5] [2 2 0.5] [1] [1] }; uilist = { { 'style' 'text' 'string' 'Select an event list text file ' } ... { 'style' 'edit' 'string' '' 'tag' 'file1' } ... { 'style' 'pushbutton' 'string' '...' 'callback' commandload1 } ... { 'style' 'text' 'string' 'Select a bin text file ' } ... { 'style' 'edit' 'string' '' 'tag' 'file2' } ... { 'style' 'pushbutton' 'string' '...' 'callback' commandload2 } ... {} ... { 'style' 'checkbox' 'string' 'Import all bins including non-contrast bins' 'tag' 'ncbins' } }; [tmp1, tmp2, tmp3, results] = inputgui( geometry, uilist, 'pophelp(''pop_importerplab'');', 'Import ERPLAB info files -- pop_importerplab()' ); file1 = results.file1; file2 = results.file2; ncbins = results.ncbins; end; if isempty(file1), error(sprintf('Empty file %s', file1)); end; if isempty(file2), error(sprintf('Empty file %s', file2)); end; if ~exist(file1), error(sprintf('Could not find file %s', file1)); end; if ~exist(file2), error(sprintf('Could not find file %s', file2)); end; dataFile1 = loadtxt(file1); dataFile2 = loadtxt(file2, 'delim', 9); % decode bin file % --------------- bininfo = []; metabin = []; bCount = 1; mCount = 1; for iLine = 1:size(dataFile2,1) begPar = find(dataFile2{iLine} == '('); endPar = find(dataFile2{iLine} == ')'); indEq = find(dataFile2{iLine} == '='); labelInd = strfind( dataFile2{iLine}, 'label'); if length(indEq) < 1 error(sprintf('Could not find equal for line %d in file %s', iLine, file2)); end; label = dataFile2{iLine}(labelInd+5:end); bin = recodebin(dataFile2{iLine}(1:indEq(1)-1)); if isempty(labelInd) error(sprintf('Could not find "label" for line %d in file %s', iLine, file2)); end; if length(begPar) < 1 || length(endPar) < 1 || begPar(1) > labelInd binrange = deblank(dataFile2{iLine}(indEq+1:labelInd-1)); indMinus = find(binrange == '-'); if length(indEq) < 1 error(sprintf('Could not find minus in bin range for line %d in file %s', iLine, file2)); end; bin1 = recodebin(binrange(1:indMinus-1)); bin2 = recodebin(binrange(indMinus+1:end)); metabin(mCount).bin = bin; metabin(mCount).binnum = str2num(bin(4:end)); metabin(mCount).label = label; metabin(mCount).binrange = { bin1 bin2 }; mCount = mCount+1; else bininfo(bCount).bin = bin; bininfo(bCount).binnum = str2num(bin(4:end)); bininfo(bCount).label = label; bininfo(bCount).eventrange = str2num(dataFile2{iLine}(begPar(1)+1:endPar(1)-1)); bCount = bCount+1; end; end; % scan events % ----------- oldEvents = [dataFile1{:,1}]; % event type numerical eventInds = [dataFile1{:,3}]; newName = dataFile1(:,2); for iEvent = 1:length(EEG.event) type = EEG.event(iEvent).type; typeInd = find(type == oldEvents); if length(typeInd) ~= 1 error('Could not find type in event list'); end; typeIndForBin = eventInds(typeInd); EEG.event(iEvent).newtype = recodeeventlabel(newName{typeInd}); EEG.event(iEvent).eventind = typeIndForBin; end; if ncbins for iEvent = 1:length(EEG.event) typeIndForBin = EEG.event(iEvent).eventind; for iBin = 1:length(bininfo) if any(typeIndForBin == bininfo(iBin).eventrange) EEG.event(iEvent).(recodelabel(bininfo(iBin).label)) = 1; else EEG.event(iEvent).(recodelabel(bininfo(iBin).label)) = 0; end; end; end; end; % scan metabin and transform to bin % --------------------------------- wb = warning('backtrace'); warning('backtrace', 'off'); for iMeta = 1:length(metabin) allBins = [ bininfo.binnum ]; bin1 = str2num(metabin(iMeta).binrange{1}(4:end)); bin2 = str2num(metabin(iMeta).binrange{2}(4:end)); indBin1 = find(allBins == bin1); indBin2 = find(allBins == bin2); if length(indBin1) ~= 1 || length(indBin2) ~= 1 warning([ 'Cannot calculate contrast for ' metabin(iMeta).bin ' using ' metabin(iMeta).binrange{1} ' which is already a contrast bin' ]); else if length(indBin2) ~= 1, error([ metabin(iMeta).binrange{2} ' not found or found twice' ]); end; if ~isempty(intersect(bininfo(indBin1).eventrange, bininfo(indBin2).eventrange)) warning([ 'cannot calculate contrast for ' metabin(iMeta).bin ' because ' metabin(iMeta).binrange{1} ' and ' metabin(iMeta).binrange{2} ' share some common event codes' ]); else for iEvent = 1:length(EEG.event) type = EEG.event(iEvent).eventind; if any(type == bininfo(indBin1).eventrange) EEG.event(iEvent).(recodelabel(metabin(iMeta).label)) = doubledeblank(bininfo(indBin1).label); elseif any(type == bininfo(indBin2).eventrange) EEG.event(iEvent).(recodelabel(metabin(iMeta).label)) = doubledeblank(bininfo(indBin2).label); else EEG.event(iEvent).(recodelabel(metabin(iMeta).label)) = 'none of these'; end; end; end; end; end; warning(wb); % return the string command % ------------------------- com = sprintf('%s = pop_importerplab( %s, ''%s'',''%s'', %d);', inputname(1), inputname(1), file1, file2, ncbins); function str = recodebin(str) str = lower(str); str = doubledeblank(str); if str(1) ~= 'b' str = [ 'bin' str ]; elseif str(2) ~= 'i' str = [ 'bin' str(2:end) ]; end; function str = recodeeventlabel(str) str(find(str == '"')) = []; function str = recodelabel(str) str = doubledeblank(str); str(find(str == ' ')) = '_'; str(find(str == ')')) = '_'; str(find(str == '(')) = '_'; str(find(str == '/')) = '_'; str(find(str == '-')) = '_'; str(find(str == '&')) = '_'; if ~isempty(str2num(str(1))) str = [ 'f' str ]; end; function str = doubledeblank(str) str = deblank(str(end:-1:1)); str = deblank(str(end:-1:1));
github
lcnhappe/happe-master
eeg_eventhist.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_eventhist.m
4,549
utf_8
075deb48deff9d15410e8cce6a433655
% eeg_eventhist() - return or plot histogram of event or urevent field values. % If NO output args, plots the histogram. If the field values % are not numbers or strings, no histogram is computed. % Usage: % >> figure; eeg_eventhist(EEG.event,'field',bins); % plot histogram % >> [fldvals] = eeg_eventhist(EEG.event,'field'); % return field values % >> [fldvals,binNs,binedges] = eeg_eventhist(EEG.event,'field',bins); % Inputs: % % Event - an EEGLAB EEG.event or EEG.urevent structure % 'field' - string containing the name of a field in the input Event structure % bins - optional number of bins to use, else vector of bin edges {default: 10} % If event field values are strings, this argument is ignored. % Outputs: % % fldvals - numeric, struct, or cell array vector of field values for each event % in the input event order (with [] values, if any, replaced by NaN's or ' 's). % binNs - numbers of events in the histogram bins % binedges - if numeric values, a one-column matrix giving bin edges of the [low,high) bins % Else, if string values, cell array containing the string associated with each bin. % Example: % >> [vals,histNs,bins] = eeg_eventhist(EEG.event,'type'); % % % % Returns cell array of event-type strings, numbers of each event type, % % and event type strings, in alphabetic order. No bar() plot produced. % % See also: pop_eventstat(), signalstat(), pop_signalstat(). % % Author: Scott Makeig, SCCN, Institute for Neural Computation, UCSD, March 26, 2004 % % 8-20-05 replace found numeric field values [] with NaN to avoid bug -sm % replace bin numbers in plot with bin labels if strings; add plot title function [vals,histNs,outbins] = eeg_eventhist(Event,field,bins) if nargin < 2 help eeg_eventhist return end if nargin < 3 bins = 10; end if isempty(Event) error('Event structure is empty'); end if ~isfield(Event,field) error('named field is not an Event field') end idx = 0; fld = []; while isempty(fld) idx = idx+1; if idx > length(Event) error('All named event fields are empty'); end fld = getfield(Event(idx),field); if ischar(fld) IS_CHAR = 1; elseif isstruct(fld) IS_STRUCT = 1; elseif ~isempty(fld) IS_NUM = 1; end end if exist('IS_NUM') vals = zeros(length(Event),1); fprintf('Assuming ''%s'' field values are numeric.\n',field); elseif exist('IS_CHAR') vals = cell(length(Event),1); fprintf('Assuming ''%s'' field values are strings.\n',field); elseif exist('IS_STRUCT') vals = repmat(field1,length(Event),1); fprintf('Assuming ''%s'' field values are structures.\n',field); else error('Cannot determine field value type') end if exist('IS_NUM') for k=1:length(Event) v = getfield(Event(k),field); if isempty(v) v = NaN; end vals(k) = v; end else for k=1:length(Event) vals{k} = getfield(Event(k),field); end end if nargout == 1 | exist('IS_STRUCT') return % return vals only, no histogram end % if exist('IS_NUM') %%%%%%%%%%%%%%%% numeric values histogram %%%%%%%%%%%%%%%%%%%%%% % if numel(bins) == 1 if bins < 3 error('number of bins must be > 2'); end mn = mean(vals); stdev = std(vals); binsout = zeros(bins,1); fl2 = floor(bins/2); for k = -1*fl2:ceil(bins/2) binsout(k+fl2+1) = mn+k*stdev; end binsout(1) = -inf; binsout(end) = inf; histNs = histc(vals,binsout); histNs = histNs(1:end-1); else % accomodate specified bin edges histNs = histc(vals,bins); histNs = histNs(1:end-1); end outbins = binsout; if nargout == 0 h = bar(histNs,'histc'); end % else % exist('IS_CHAR') %%%%%%%%%%%% string values histogram %%%%%%%%%%%%%%%%%%%%%% % for v=1:length(vals) if isempty(cell2mat(vals(v))) vals(v) = {' '}; end end outbins = unique_bc(vals); histNs = zeros(length(outbins)-1,1); for k=1:length(outbins) histNs(k) = sum(ismember(vals,outbins{k})); end if nargout == 0 bar(histNs,1); if IS_CHAR set(gca,'xticklabel',outbins); % ??? NEEDS MORE WORK - CANT TEST FROM HOME yl = get(gca,'ylim'); set(gca,'ylim',[yl(1) yl(2)*1.1]); if strcmp(field,'type') tl=title(['Histogram of event types']); else tl=title(['Histogram of event field ''' field ''' values']); end end end end return
github
lcnhappe/happe-master
eeg_latencyur.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_latencyur.m
2,912
utf_8
d55ca27237bce37a4bf5491ff6639324
% eeg_latencyur() - transform latency of sample point in the continuous % data into latencies in the transformed dataset. % % Usage: % >> lat_out = eeg_latencyur( events, lat_in); % % Inputs: % events - event structure. If this structure contain boundary % events, the length of these events is added to restore % the original latency from the relative latency in 'lat_in' % lat_in - sample latency (in point) in the original urEEG. % % Outputs: % lat_out - output latency % % Note: the function that finds the original (ur) latency in the original % dataset using latencies in the current dataset is called % eeg_urlatency() % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2011- % % See also: eeg_urlatency() % Copyright (C) 2011 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function latout = eeg_latencyur( events, latin ); if nargin < 2 help eeg_latencyur; return; end; boundevents = { events.type }; latout = latin; if ~isempty(boundevents) & isstr(boundevents{1}) indbound = strmatch('boundary', boundevents); if isfield(events, 'duration') & ~isempty(indbound) for index = indbound' lowerVals = find(latout > events(index).latency); latout(lowerVals) = latout(lowerVals)-events(index).duration; end; end; end; return; % build array of 0 and 1 (0 no data) boundevents = { events.type }; latout = latin; if ~isempty(boundevents) & isstr(boundevents{1}) indbound = strmatch('boundary', boundevents); if isfield(events, 'duration') & ~isempty(indbound) currentadd = 0; points = ones(1, events(end).latency+sum([events(indbound').duration])); % arrays of 1 for index = indbound' currentlat = events(index).latency+currentadd; currentdur = events(index).duration; points(round(currentlat):round(currentlat+currentdur)) = 0; currentadd = currentadd + currentdur; end; end; end; 8;
github
lcnhappe/happe-master
pop_importev2.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_importev2.m
2,489
utf_8
741843995eba3b57df4e2670647f78ef
% pop_importev2() - merge a neuroscan EV2 file with input dataset % (pop out window if no arguments). % % Usage: % >> OUTEEG = pop_importev2( INEEG ); % pop-up window mode % >> OUTEEG = pop_importev2( INEEG, filename); % % Inputs: % INEEG - input EEGLAB data structure % filename - file name % % Outputs: % OUTEEG - EEGLAB data structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2007 % Copyright (C) 2007 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, command] = pop_importev2(EEG, filename); command = ''; if nargin < 1 help pop_importev2; return; end; if nargin < 2 % ask user [filename, filepath] = uigetfile('*.*', 'Choose a EV2 file -- pop_importev2'); drawnow; if filename == 0 return; end; filename = fullfile(filepath, filename); end; % find out if there is a line to skip or not % ------------------------------------------ fid = fopen(filename, 'r'); tmpl = fgetl(fid); if isempty(findstr('ype', tmpl)), skipline = 0; else skipline = 1; end; fclose(fid); % load datas % ---------- tmpevent = EEG.event; try, oldeventlats = [ tmpevent.latency ]; catch, end; EEG = pop_importevent(EEG, 'fields', { 'num' 'type' 'response' 'acc' 'RT' 'latency'}, ... 'skipline', skipline, 'timeunit', 1E-3, 'align', NaN, 'append', 'no', 'event', filename ); tmpevent = EEG.event; neweventlats = [ tmpevent.latency ]; if ~exist('oldeventlats'), oldeventlats = neweventlats; end; len = min(min(length(oldeventlats), length(neweventlats)), 10); if mean(oldeventlats(1:len) - neweventlats(1:len)) > 1 error('Wrong alignment of ev2 file with data'); end; command = sprintf('%s = pop_importev2(%s, %s);', inputname(1), inputname(1), filename); return;
github
lcnhappe/happe-master
pop_biosig16ying.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_biosig16ying.m
10,593
utf_8
1831d74dfa6b0ab3c1f6991654a256c8
% pop_biosig() - import data files into EEGLAB using BIOSIG toolbox % % Usage: % >> OUTEEG = pop_biosig; % pop up window % >> OUTEEG = pop_biosig( filename, channels, type); % % Inputs: % filename - [string] file name % % Optional inputs: % 'channels' - [integer array] list of channel indices % 'blockrange' - [min max] integer range of data blocks to import, in seconds. % Entering [0 3] will import the first three blocks of data. % Default is empty -> import all data blocks. % 'ref' - [integer] channel index or index(s) for the reference. % Reference channels are not removed from the data, % allowing easy re-referencing. If more than one % channel, data are referenced to the average of the % indexed channels. WARNING! Biosemi Active II data % are recorded reference-free, but LOSE 40 dB of SNR % if no reference is used!. If you do not know which % channel to use, pick one and then re-reference after % the channel locations are read in. {default: none} % 'rmeventchan' - ['on'|'off'] remove event channel after event % extraction. Default is 'on'. % % Outputs: % OUTEEG - EEGLAB data structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, Oct. 29, 2003- % % Note: BIOSIG toolbox must be installed. Download BIOSIG at % http://biosig.sourceforge.net % Contact [email protected] for troubleshooting using BIOSIG. % Copyright (C) 2003 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, command] = my_pop_biosig(filename, varargin); EEG = []; command = ''; if nargin < 1 % ask user [filename, filepath] = uigetfile('*.*', 'Choose an BDF file -- pop_biosig()'); %%% this is incorrect in original version!!!!!!!!!!!!!! drawnow; if filename == 0 return; end; filename = [filepath filename]; % open file to get infos % ---------------------- disp('Reading data file header...'); dat = sopen(filename); % special BIOSEMI % --------------- if strcmpi(dat.TYPE, 'BDF') disp('We highly recommend that you choose a reference channel IF these are Biosemi data'); disp('(e.g., a mastoid or other channel). Otherwise the data will lose 40 dB of SNR!'); end; uilist = { { 'style' 'text' 'String' 'Channel list (defaut all):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'String' [ 'Data range (in seconds) to read (default all [0 ' int2str(dat.NRec) '])' ] } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'String' 'Extract event - cannot be unset (set=yes)' } ... { 'style' 'checkbox' 'string' '' 'value' 1 'enable' 'on' } {} ... { 'style' 'text' 'String' 'Import continuous data (set=yes)' 'value' 1} ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'String' 'Reference chan(s) indices - required for BIOSEMI' } ... { 'style' 'edit' 'string' '' } }; geom = { [3 1] [3 1] [3 0.35 0.5] [3 0.35 0.5] [3 1] }; result = inputgui( geom, uilist, 'pophelp(''pop_biosig'')', ... 'Load data using BIOSIG -- pop_biosig()'); if length(result) == 0 return; end; % decode GUI params % ----------------- options = {}; if ~isempty(result{1}), options = { options{:} 'channels' eval( [ '[' result{1} ']' ] ) }; end; if ~isempty(result{2}), options = { options{:} 'blockrange' eval( [ '[' result{2} ']' ] ) }; end; if length(result) > 2 if ~isempty(result{4}), options = { options{:} 'ref' eval( [ '[' result{4} ']' ] ) }; end; if ~result{3}, options = { options{:} 'rmeventchan' 'off' }; end; end; else options = varargin; end; % decode imput parameters % ----------------------- g = finputcheck( options, { 'blockrange' 'integer' [0 Inf] []; 'channels' 'integer' [0 Inf] []; 'ref' 'integer' [0 Inf] []; 'rmeventchan' 'string' { 'on';'off' } 'on' }, 'pop_biosig'); if isstr(g), error(g); end; % import data % ----------- EEG = eeg_emptyset; if ~isempty(g.channels) dat = sopen(filename, 'r', g.channels,'OVERFLOWDETECTION:OFF'); else dat = sopen(filename, 'r', 0,'OVERFLOWDETECTION:OFF'); end fprintf('Reading data in %s format...\n', dat.TYPE); if ~isempty(g.blockrange) newblockrange = g.blockrange; newblockrange(2) = min(newblockrange(2), dat.NRec); newblockrange = newblockrange*dat.Dur; DAT=sread(dat, newblockrange(2)-newblockrange(1), newblockrange(1))'; else DAT=sread(dat, Inf)';% this isn't transposed in original!!!!!!!! newblockrange = []; end dat = sclose(dat); % convert to seconds for sread % ---------------------------- EEG.nbchan = size(DAT,1); EEG.srate = dat.SampleRate(1); EEG.data = DAT; clear DAT; % $$$ try % why would you do the following??????? JO % $$$ EEG.data = EEG.data'; % $$$ catch, % $$$ pack; % $$$ EEG.data = EEG.data'; % $$$ end; EEG.setname = sprintf('%s file', dat.TYPE); EEG.comments = [ 'Original file: ' filename ]; EEG.xmin = 0; if strcmpi(dat.TYPE, 'BDF') || strcmpi(dat.TYPE, 'EDF') EEG.trials = 1; EEG.pnts = size(EEG.data,2); else EEG.trials = dat.NRec; EEG.pnts = size(EEG.data,2)/dat.NRec; end if isfield(dat, 'Label') & ~isempty(dat.Label) EEG.chanlocs = struct('labels', cellstr(char(dat.Label))); end EEG = eeg_checkset(EEG); % extract events % this part I totally revamped to work... JO % -------------- disp('Extracting events from last EEG channel...'); EEG.event = []; % $$$ startval = mode(EEG.data(end,:)); % my code % $$$ for p = 2:size(EEG.data,2)-1 % $$$ [codeout] = code(EEG.data(end,p)); % $$$ if EEG.data(end,p) > EEG.data(end,p-1) & EEG.data(end,p) >= EEG.data(end,p+1) % $$$ EEG.event(end+1).latency = p; % $$$ EEG.event(end).type = bitand(double(EEG.data(end,p)-startval),255); % $$$ end; % $$$ end; % lastout = mod(EEG.data(end,1),256);newevs = []; % andrey's code 8 bits % codeout = mod(EEG.data(end,2),256); % for p = 2:size(EEG.data,2)-1 % nextcode = mod(EEG.data(end,p+1),256); % if codeout > lastout & codeout >= nextcode % newevs = [newevs codeout]; % EEG.event(end+1).latency = p; % EEG.event(end).type = codeout; % end; % lastout = codeout; % codeout = nextcode; % end; %lastout = mod(EEG.data(end,1),256*256);newevs = []; % andrey's code 16 bits %codeout = mod(EEG.data(end,2),256*256); %for p = 2:size(EEG.data,2)-1 % nextcode = mod(EEG.data(end,p+1),256*256); % if (codeout > lastout) & (codeout >= nextcode) % newevs = [newevs codeout]; % EEG.event(end+1).latency = p; % EEG.event(end).type = codeout; % end; % lastout = codeout; % codeout = nextcode; %end; % Modifieded by Andrey (Aug.5,2008) to detect all non-zero codes: thiscode = 0;lastcode=0; for p = 1:size(EEG.data,2)-1 prevcode = thiscode; thiscode = mod(EEG.data(end,p),256*256); % andrey's code - 16 bits if (thiscode ~= 0) && (thiscode~=prevcode) && (thiscode~=lastcode) % fix to avoid repeated codes (per Ying's demand) EEG.event(end+1).latency = p; EEG.event(end).type = thiscode; lastcode = thiscode; end; end; if strcmpi(g.rmeventchan, 'on') EEG.data(dat.BDF.Status.Channel,:) = []; EEG.nbchan = size(EEG.data,1); if ~isempty(EEG.chanlocs) EEG.chanlocs(dat.BDF.Status.Channel,:) = []; end; end; EEG = eeg_checkset(EEG, 'eventconsistency'); % $$$ if ~isempty(dat.EVENT) % $$$ if isfield(dat, 'out') % Alois fix for event interval does not work % $$$ if isfield(dat.out, 'EVENT') % $$$ dat.EVENT = dat.out.EVENT; % $$$ end; % $$$ end; % $$$ if ~isempty(newblockrange) % $$$ interval(1) = newblockrange(1) * dat.SampleRate(1) + 1; % $$$ interval(2) = newblockrange(2) * dat.SampleRate(1); % $$$ else interval = []; % $$$ end % $$$ EEG.event = biosig2eeglabevent(dat.EVENT, interval); % Toby's fix % $$$ if strcmpi(g.rmeventchan, 'on') & strcmpi(dat.TYPE, 'BDF') & isfield(dat, 'BDF') % $$$ disp('Removing event channel...'); % $$$ EEG.data(dat.BDF.Status.Channel,:) = []; % $$$ EEG.nbchan = size(EEG.data,1); % $$$ if ~isempty(EEG.chanlocs) % $$$ EEG.chanlocs(dat.BDF.Status.Channel,:) = []; % $$$ end; % $$$ end; % $$$ EEG = eeg_checkset(EEG, 'eventconsistency'); % $$$ else % $$$ disp('Warning: no event found. Events might be embeded in a data channel.'); % $$$ disp(' To extract events, use menu File > Import Event Info > From data channel'); % $$$ end; % rerefencing % ----------- if ~isempty(g.ref) disp('Re-referencing...'); EEG.data = EEG.data - repmat(mean(EEG.data(g.ref,:),1), [size(EEG.data,1) 1]); if length(g.ref) == size(EEG.data,1) EEG.ref = 'averef'; end; if length(g.ref) == 1 disp([ 'Warning: channel ' int2str(g.ref) ' is now zeroed (but still present in the data)' ]); else disp([ 'Warning: data matrix rank has decreased through re-referencing' ]); end; end; % convert data to single if necessary % ----------------------------------- EEG = eeg_checkset(EEG,'makeur'); % Make EEG.urevent field EEG = eeg_checkset(EEG); % history % ------- if isempty(options) command = sprintf('EEG = my_pop_biosig(''%s'');', filename); else command = sprintf('EEG = my_pop_biosig(''%s'', %s);', filename, vararg2str(options)); end;
github
lcnhappe/happe-master
eeg_insertboundold.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_insertboundold.m
7,147
utf_8
cdb944c0e4d9182d26465cca98d458a1
% eeg_insertbound() - insert boundary event in an EEG event structure. % % Usage: % >> [eventout indnew] = eeg_insertbound( eventin, pnts, ... % abslatency, duration); % Required Inputs: % eventin - EEGLAB event structure (EEG.event) % pnts - data points in EEG dataset (EEG.pnts * EEG.trials) % abslatency - absolute latency of regions in original dataset. Can % also be an array of [beg end] latencies with one row % per region removed. Then 'lengths' argument is ignored. % Optional Inputs: % lengths - lengths of removed regions % % Outputs: % eventout - EEGLAB event output structure with added boundaries % indnew - array of indices returning new event index for any old % (input eventin) event index % Notes: % This function performs the following: % 1) add boundary events to the 'event' structure; % remove nested boundaries; % recompute the latencies of all events. % 2) all latencies are given in (float) data points. % e.g., a latency of 2000.3 means 0.3 samples (at EEG.srate) % after the 2001st data frame (since first frame has latency 0). % % Author: Arnaud Delorme and Hilit Serby, SCCN, INC, UCSD, April, 19, 2004 % % See also: eeg_eegrej(), pop_mergeset() % Copyright (C) 2004 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [eventout,indnew] = eeg_insertbound( eventin, pnts, regions, lengths); if nargin < 3 help eeg_insertbound; return; end; if size(regions,2) ~= 1 & exist('lengths') ~= 1 lengths = regions(:,2)-regions(:,1)+1; regions = regions(:,1); end; if exist('lengths') ~= 1 lengths = zeros(size(regions)); end; if length(regions) fprintf('eeg_insertbound(): %d boundary (break) events added.\n', size(regions, 1)); else return; end; % recompute latencies of boundevents (in new dataset) % --------------------------------------------------- [regions tmpsort] = sort(regions); lengths = lengths(tmpsort); boundevents = regions(:,1)-0.5; % sort boundevents by decreasing order (otherwise bug in new event index) % ------------------------------------ boundevents = boundevents(end:-1:1); lengths = lengths (end:-1:1); eventout = eventin; indnew = 1:length(eventin); allnest = []; countrm = 0; for tmpindex = 1:length(boundevents) % sorted in decreasing order if boundevents(tmpindex) >= 0.5 & boundevents(tmpindex) <= pnts % find event succeding boundary to insert event % at the correct location in the event structure % ---------------------------------------------- if ~isempty(eventout) & isfield(eventout, 'latency') alllats = [ eventout.latency ] - boundevents(tmpindex); tmpind = find( alllats >= 0 ); [tmp tmpind2 ] = min(alllats(tmpind)); tmpind2 = tmpind(tmpind2); else tmpind2 = []; end; % insert event at tmpind2 % ----------------------- if ~isempty(tmpind2) eventout(end+1).type = 'boundary'; tmp = eventout(end); eventout(tmpind2+1:end) = eventout(tmpind2:end-1); eventout(tmpind2) = tmp; indnew(tmpind2:end) = indnew(tmpind2:end)+1; else tmpind2 = length(eventout)+1; eventout(tmpind2).type = 'boundary'; end; eventout(tmpind2).latency = boundevents(tmpindex); eventout(tmpind2).duration = lengths(tmpindex); % just to create field [ tmpnest addlength ] = findnested(eventout, tmpind2); % recompute latencies and remove events in the rejected region % ------------------------------------------------------------ eventout(tmpnest) = []; countrm = countrm+length(tmpnest); for latind = tmpind2+1:length(eventout) eventout(latind).latency = eventout(latind).latency-lengths(tmpindex); end; % add lengths of previous events (must be done after above) % --------------------------------------------------------- eventout(tmpind2).duration = lengths(tmpindex)+addlength; if eventout(tmpind2).duration == 0, eventout(tmpind2).duration=NaN; end; end; end; if countrm > 0 fprintf('eeg_insertbound(): event latencies recomputed and %d events removed.\n', countrm); end; % look for nested events % retrun indices of nested events and % their total length % ----------------------------------- function [ indnested, addlen ] = findnested(event, ind); indnested = []; addlen = 0; tmpind = ind+1; while tmpind <= length(event) & ... event(tmpind).latency < event(ind).latency+event(ind).duration if strcmpi(event(tmpind).type, 'boundary') if ~isempty( event(tmpind).duration ) addlen = addlen + event(tmpind).duration; % otherwise old event duration or merge data discontinuity end; end; indnested = [ indnested tmpind ]; tmpind = tmpind+1; end; % remove urevent and recompute indices % THIS FUNCTION IS DEPRECATED % ------------------------------------ function [event, urevent] = removenested(event, urevent, nestind); if length(nestind) > 0 fprintf('eeg_insertbound() debug msg: removing %d nested urevents\n', length(nestind)); nestind = sort(nestind); urind = [ event.urevent ]; % this must not be done in the loop % since the indices are dyanmically updated end; for ind = 1:length(nestind) % find event urindices higher than the urevent to suppress % -------------------------------------------------------- tmpind = find( urind > nestind(ind) ); for indevent = tmpind event(indevent).urevent = event(indevent).urevent-1; end; end; urevent(nestind) = [];
github
lcnhappe/happe-master
eeg_oldica.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_oldica.m
4,381
utf_8
22d0c16288409e669fd273afd79ec6f0
% eeg_oldica() - report, return or add to oldicaweights and oldicasphere % stored in cell arrays in EEG.etc of an EEGLAB dataset % Usage: % >> eeg_oldica(EEG); % report number of stored oldicaweights % >> [EEG,icaweights, icasphere] = eeg_oldica(EEG,N); % return matrices % >> EEG = eeg_oldica(EEG,N,icaweights,icasphere); % add wts and sph % % matrices to EEG.etc.icaweights and EEG.etc.icasphere % Inputs: % EEG - EEGLAB dataset structure % nreturn - index of the oldicaweights and sphere to return {default: 1} % icaweights - ICA weights matrix to store in EEG.etc.oldicaweights % icasphere - ICA sphere matrix to store in EEG.etc.oldicasphere % Outputs: % icaweights - ICA unmixing matrix (e.g., EEG.icaweights) % icasphere - ICA data sphering matrix (e.g., EEG.icasphere) % % See also: pop_runica() % % Author: Scott Makeig, SCCN/INC/UCSD, March 17, 2005 % Copyright (C) 2004 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG,oldicaweights,oldicasphere] = eeg_oldica(EEG, nreturn,icaweights,icasphere) if nargin< 1 help eeg_oldica return end if ~isstruct(EEG) error('EEG argument must be a dataset structure') end if ~isfield(EEG,'etc') error('EEG.etc field not found - no old ICA weights in dataset'); end if ~isfield(EEG.etc,'oldicaweights') & nargin < 3 error('EEG.etc.oldicaweights field not found - no old ICA weights in dataset'); elseif nargout < 2 & nargin < 3 if length(EEG.etc.oldicaweights) > 1 fprintf('EEG.etc.oldicaweights contains %d weight matrices\n',length(EEG.etc.oldicaweights)); EEG.etc.oldicaweights else fprintf('EEG.etc.oldicaweights contains %d weight matrix\n',length(EEG.etc.oldicaweights)); EEG.etc.oldicaweights end end if ~isfield(EEG.etc,'oldicasphere') & nargin < 3 fprintf('EEG.etc.oldicasphere field not found - no old ICA sphere matrix in dataset'); elseif nargout < 2 & nargin < 3 fprintf('\n'); if length(EEG.etc.oldicasphere) > 1 fprintf('EEG.etc.oldicasphere contains %d weight matrices\n',length(EEG.etc.oldicasphere)); EEG.etc.oldicasphere else fprintf('EEG.etc.oldicasphere contains %d weight matrix\n',length(EEG.etc.oldicasphere)); EEG.etc.oldicasphere end fprintf('\n'); end if nargin < 2 nreturn = 1; elseif nargin < 3 if nreturn< 1 error('nreturn must be an oldicaweights index'); elseif length(EEG.etc.oldicaweights) < nreturn fprintf('nreturn (%d) > number of stored oldicaweights (%d) ', nreturn,length(EEG.etc.oldicaweights)); error(' '); end end if nargin > 4 error('too many arguments.\n'); end if nargin > 2 if nargout > 0 fprintf('New EEG.etc.oldicaweights: '); EEG.etc.oldicaweights = [EEG.etc.oldicaweights {icaweights}]; EEG.etc.oldicaweights else error('To update oldicaweights, at least one output required'); end end if nargin > 3 fprintf('New EEG.etc.oldicasphere: '); EEG.etc.oldicasphere = [EEG.etc.oldicasphere {icasphere}]; EEG.etc.oldicasphere end if nargout > 1 % fprintf('\n'); oldicaweights = EEG.etc.oldicaweights{nreturn}; % fprintf('Stored oldicaweights matrix (%d) returned (%d,%d).\n',nreturn,size(oldicaweights,1),size(oldicaweights,2)); if length(EEG.etc.oldicasphere) >= nreturn oldicasphere = EEG.etc.oldicasphere{nreturn}; % fprintf('Stored oldicasphere matrix (%d) returned (%d,%d).\n',nreturn,size(oldicasphere,1),size(oldicasphere,2)); else oldicasphere = []; % fprintf('No corresponding oldicasphere matrix; [] returned.\n'); end % fprintf('\n'); end return
github
lcnhappe/happe-master
pop_plotdata.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_plotdata.m
6,983
utf_8
a050f0fb99538d1e30279c41241ba0b6
% pop_plotdata() - Plot average of EEG channels or independent components in % a rectangular array. Else, (over)plot single trials. % Usage: % >> avg = pop_plotdata(EEG, typeplot, indices, trials, title, singletrials, ydir, ylimits); % % Inputs: % EEG - Input dataset % typeplot - Type data to plot (1=channels, 0=components) {Default:1} % indices - Array of channels (or component) indices to plot % {Default: all} % trials - Array of trial indices. sum specific trials in the average % {Default: all} % title - Plot title. {Default: []}. % singletrials - [0|1], Plot average or overplot single trials % 0 plot average, 1 plot single trials {Default: 0} % ydir - [1|-1] y-axis polarity (pos-up = 1; neg-up = -1) % {def command line-> pos-up; def GUI-> neg-up} % ylimits - [ymin ymax] plotting limits {default [0 0] -> data range} % % Outputs: % avg - [matrix] Data average % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: plotdata(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-08-02 add eeglab options -ad % 03-18-02 added title -ad & sm % 03-30-02 added single trial capacities -ad function [sigtmp, com] = pop_plotdata(EEG, typeplot, indices, trials, plottitle, singletrials, ydir,ylimits); ylimits = [0 0];% default ylimits = data range % warning signal must be in a 3D form before averaging sigtmp = []; com = ''; if nargin < 1 help pop_plotdata; return; end; if nargin < 2 typeplot = 1; % 1=signal; 0=component end; if exist('plottitle') ~= 1 plottitle = ''; end; if nargin <3 if typeplot % plot signal channels result = inputdlg2({ 'Channel number(s):' ... 'Plot title:' ... 'Vertical limits ([0 0]-> data range):' ... }, ... 'Channel ERPs in rect. array -- pop_plotdata()', 1, ... {['1:' int2str(EEG.nbchan)] [fastif(isempty(EEG.setname), '',[EEG.setname ' ERP'])] ['0 0'] }, ... 'pop_plotdata' ); else % plot components result = inputdlg2({ 'Component number(s):' ... 'Plot title:' ... 'Vertical limits ([0 0]-> data range):' ... }, ... 'Component ERPs in rect. array -- pop_plotdata()', 1, ... { ['1:' int2str(size(EEG.icawinv,2))] [fastif(isempty(EEG.setname), '',[EEG.setname ' ERP'])] ['0 0'] }, ... 'pop_plotdata' ); end; if length(result) == 0 return; end; indices = eval( [ '[' result{1} ']' ] ); plottitle = result{2}; singletrials = 0; ylimits = eval( [ '[' result{3} ']' ] ); if length(ylimits) ~= 2 ylimits = [0 0]; % use default if 2 values not given end end; if ~(exist('trials') == 1) trials = 1:EEG.trials; end; if exist('plottitle') ~= 1 plottitle = ''; end; if exist('singletrials') ~= 1 singletrials = 0; end; if EEG.trials > 1 & singletrials == 0 fprintf('Selecting trials and components...\n'); if typeplot == 1 sigtmp = nan_mean(EEG.data(indices,:,trials),3); else if isempty(EEG.icasphere) error('no ICA data for this set, first run ICA'); end; tmpdata = eeg_getdatact(EEG, 'component', indices, 'trialindices', trials); fprintf('Averaging...\n'); sigtmp = nan_mean(tmpdata,3); end; else if typeplot == 1 sigtmp = EEG.data(indices,:,trials); else if isempty(EEG.icasphere) error('no ICA data for this set, first run ICA'); end; sigtmp = eeg_getdatact(EEG, 'component', indices, 'trialindices', trials); end; end; figure; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if exist('YDIR') ~= 1 ydir = 1; else ydir = YDIR; end % %%%%%%%%%%%%%%%%%%%%%%%%%% make the plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % sigtmp = reshape( sigtmp, size(sigtmp,1), size(sigtmp,2)*size(sigtmp,3)); ymin = ylimits(1); ymax = ylimits(2); if ischar(ymin) ymin = str2num(ymin); ymax = str2num(ymax); end % com = sprintf('pop_plotdata(%s, %d, %s, [1:%d], ''%s'', %d, %d, [%f %f]);', ... % inputname(1), typeplot, vararg2str(indices), EEG.trials, plottitle, singletrials,ydir,ymin,ymax); % fprintf([com '\n']); if ~isempty(EEG.chanlocs) && typeplot == 1 tmpchanlocs = EEG.chanlocs; chanlabels = strvcat({ tmpchanlocs(indices).labels }); else chanlabels = num2str(indices(:)); end; plottopo( sigtmp, 'frames', EEG.pnts, 'limits', [EEG.xmin*1000 EEG.xmax*1000 ymin ymax], 'title', plottitle, 'chans', 1:size(sigtmp,1), 'ydir', ydir, 'channames', chanlabels); %plotdata(sigtmp, EEG.pnts, [EEG.xmin*1000 EEG.xmax*1000 ymin ymax], plottitle, indices,0,0,ydir); % %%%%%%%%%%%%%%%%%%%%%%%%%% add figure title %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if typeplot == 1 set(gcf, 'name', 'Plot > Channel ERPs > In rect. array -- plotdata()'); else set(gcf, 'name', 'Plot > Component ERPs > In rect. array -- plotdata()'); end; % %%%%%%%%%%%%%%%%%%%%%%%%%% set y-axis direction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if exist('ydir') ~= 1 if exist('YDIR') ~= 1 ydir = 1; % default positive up else ydir = YDIR; % icadefs.m system-wide default end end if ydir==1 set(gca,'ydir','normal'); else % ydir == -1 set(gca,'ydir','reverse'); end switch nargin case {0, 1, 2, 3}, com = sprintf('pop_plotdata(%s, %d, %s, [1:%d], ''%s'', %d, %d, [%g %g]);', inputname(1), typeplot, vararg2str(indices), EEG.trials, plottitle, singletrials,ydir,ymin,ymax); case 4, com = sprintf('pop_plotdata(%s, %d, %s, %s, ''%s'', %d, %d, [%g %g]);', inputname(1), typeplot, vararg2str(indices), vararg2str(trials), plottitle, singletrials,ydir,ymin,ymax); end; fprintf([com '\n']); return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function out = nan_mean(in, dim) tmpin = in; tmpin(find(isnan(in(:)))) = 0; out = sum(tmpin, dim) ./ sum(~isnan(in),dim);
github
lcnhappe/happe-master
pop_eegfilt.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_eegfilt.m
9,360
utf_8
f64d8d0b36d5e7e5ac64782c3412bb38
% pop_eegfilt() - interactively filter EEG dataset data using eegfilt() % % Usage: % >> EEGOUT = pop_eegfilt( EEG, locutoff, hicutoff, filtorder); % % Graphical interface: % "Lower edge ..." - [edit box] Lower edge of the frequency pass band (Hz) % Same as the 'locutoff' command line input. % "Higher edge ..." - [edit box] Higher edge of the frequency pass band (Hz) % Same as the 'hicutoff' command line input. % "Notch filter" - [edit box] provide the notch range, i.e. [45 55] % for 50 Hz). This option overwrites the low and high edge limits % given above. Set the 'locutoff' and 'hicutoff' values to the % values entered as parameters, and set 'revfilt to 1, to swap % from bandpass to notch filtering. % "Filter length" - [edit box] Filter lenghth in point (default: see % >> help eegfilt). Same as 'filtorder' optional input. % % Inputs: % EEG - input dataset % locutoff - lower edge of the frequency pass band (Hz) {0 -> lowpass} % hicutoff - higher edge of the frequency pass band (Hz) {0 -> highpass} % filtorder - length of the filter in points {default 3*fix(srate/locutoff)} % revfilt - [0|1] Reverse filter polarity (from bandpass to notch filter). % Default is 0 (bandpass). % usefft - [0|1] 1 uses FFT filtering instead of FIR. Default is 0. % plotfreqz - [0|1] plot frequency response of filter. Default is 0. % firtype - ['firls'|'fir1'] filter design method, default is 'firls' % from the command line % causal - [0|1] 1 uses causal filtering. Default is 0. % % Outputs: % EEGOUT - output dataset % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eegfilt(), eegfiltfft(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad function [EEG, com] = pop_eegfilt( EEG, locutoff, hicutoff, filtorder, revfilt, usefft, plotfreqz, firtype, causal) com = ''; if nargin < 1 help pop_eegfilt; return; end; if isempty(EEG(1).data) disp('Pop_eegfilt() error: cannot filter an empty dataset'); return; end; % warning % ------- if exist('filtfilt') ~= 2 disp('Warning: cannot find the signal processing toolbox'); disp(' a simple fft/inverse fft filter will be used'); usefft = 1; end; if nargin < 2 % which set to save % ----------------- uilist = { ... { 'style' 'text' 'string' 'Lower edge of the frequency pass band (Hz)' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Higher edge of the frequency pass band (Hz)' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'FIR Filter order (default is automatic)' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'checkbox' 'string' 'Notch filter the data instead of pass band' } ... { 'style' 'checkbox' 'string' 'Use (sharper) FFT linear filter instead of FIR filtering' 'value' 0 } ... { 'style' 'text' 'string' '(Use the option above if you do not have the Signal Processing Toolbox)' } ... { 'style' 'checkbox' 'string' 'Use causal filter (useful when performing causal analysis)' 'value' 0} ... { 'style' 'checkbox' 'string' 'Plot the filter frequency response' 'value' 0} ... { 'style' 'checkbox' 'string' 'Use fir1 (check, recommended) or firls (uncheck, legacy)' 'value' 1}}; geometry = { [3 1] [3 1] [3 1] 1 1 1 1 1 1 }; result = inputgui( 'geometry', geometry, 'uilist', uilist, 'title', 'Filter the data -- pop_eegfilt()', ... 'helpcom', 'pophelp(''pop_eegfilt'')'); if isempty(result), return; end; if isempty(result{1}), result{1} = '0'; end; if isempty(result{2}), result{2} = '0'; end; locutoff = eval( result{1} ); hicutoff = eval( result{2} ); if isempty( result{3} ) filtorder = []; else filtorder = eval( result{3} ); end; revfilt = 0; if result{4}, revfilt = 1; if locutoff == 0 | hicutoff == 0, error('Need both lower and higher edge for notch filter'); end; end; if result{5} usefft = 1; else usefft = 0; end; if result{6} causal = 1; else causal = 0; end; plotfreqz = result{7}; if locutoff == 0 & hicutoff == 0 return; end; if result{8} firtype = 'fir1'; else firtype = 'firls'; end else if nargin < 3 hicutoff = 0; end; if nargin < 4 filtorder = []; end; if nargin < 5 revfilt = 0; end; if nargin < 6 usefft = 0; end; if nargin < 7 plotfreqz = 0; end if nargin < 8 firtype = 'firls'; end if nargin < 8 causal = 0; end end; if locutoff && hicutoff disp('WARNING: BANDPASS FILTERS SOMETIMES DO NOT WORK (MATLAB BUG)') disp('WARNING: PLOT SPECTRUM AFTER FILTERING TO ASSESS FILTER EFFICIENCY') disp('WARNING: IF FILTER FAILS, LOWPASS DATA THEN HIGHPASS DATA') end; % process multiple datasets % ------------------------- if length(EEG) > 1 [ EEG com ] = eeg_eval( 'pop_eegfilt', EEG, 'warning', 'on', 'params', ... { locutoff, hicutoff, filtorder, revfilt } ); return; end; options = { EEG.srate, locutoff, hicutoff, 0 }; if ~isempty( filtorder ) options = { options{:} filtorder }; else options = { options{:} 0 }; end; options = {options{:} revfilt firtype causal}; if EEG.trials == 1 if ~isempty(EEG.event) & isfield(EEG.event, 'type') & isstr(EEG.event(1).type) tmpevent = EEG.event; boundaries = strmatch('boundary', { tmpevent.type }); if isempty(boundaries) if ~usefft [EEG.data, b] = eegfilt( EEG.data, options{:}); else EEG.data = eegfiltfft( EEG.data, options{1:6}); % 7/30/2014 Ramon: {:} to {1:6}; end; else options{4} = 0; disp('Pop_eegfilt:finding continuous data boundaries'); tmplat = [ tmpevent.latency ]; boundaries = tmplat(boundaries); boundaries = [0 floor(boundaries-0.49) EEG.pnts]; try, warning off MATLAB:divideByZero catch, end; for n=1:length(boundaries)-1 if boundaries(n)+1 < boundaries(n+1) try fprintf('Processing continuous data (%d:%d)\n',boundaries(n),boundaries(n+1)); if ~usefft [EEG.data(:,boundaries(n)+1:boundaries(n+1)), b] = ... eegfilt(EEG.data(:,boundaries(n)+1:boundaries(n+1)), options{:}); else EEG.data(:,boundaries(n)+1:boundaries(n+1)) = ... eegfiltfft(EEG.data(:,boundaries(n)+1:boundaries(n+1)), options{1:6}); % 7/30/2014 Ramon: {:} to {1:6}; end; catch fprintf('\nFilter error: continuous data portion too narrow (DC removed if highpass only)\n'); if locutoff ~= 0 & hicutoff == 0 tmprange = [boundaries(n)+1:boundaries(n+1)]; EEG.data(:,tmprange) = ... EEG.data(:,tmprange) - repmat(mean(EEG.data(:,tmprange),2), [1 length(tmprange)]); end; end; end; end try, warning on MATLAB:divideByZero catch, end; end else if ~usefft [EEG.data, b] = eegfilt( EEG.data, options{:}); else EEG.data = eegfiltfft( EEG.data, options{1:6}); % 7/30/2014 Ramon: {:} to {1:6}; end; end; else EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts*EEG.trials); options{4} = EEG.pnts; if ~usefft [EEG.data, b] = eegfilt( EEG.data, options{:}); else EEG.data = eegfiltfft( EEG.data, options{1:6}); % 7/30/2014 Ramon: {:} to {1:6}; end; % Note: reshape does not reserve new memory while EEG.data(:,:) does end; EEG.icaact = []; if ~usefft & plotfreqz & exist('b') == 1 freqz(b, 1, [], EEG.srate); end com = sprintf( '%s = pop_eegfilt( %s, %s, %s, [%s], [%s], %s, %s, ''%s'', %d);', inputname(1), inputname(1), ... num2str( locutoff), num2str( hicutoff), num2str( filtorder ), num2str( revfilt ), num2str(usefft), num2str(plotfreqz), firtype, causal); return
github
lcnhappe/happe-master
pop_subcomp.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_subcomp.m
7,238
utf_8
4a80ba538d5c8fe431deea54838159bb
% pop_subcomp() - remove specified components from an EEG dataset. % and subtract their activities from the data. Else, % remove components already marked for rejection. When used % with the options 'keepcomp', the function will retain [1] % or reject[0] the components provided as input. % Usage: % >> OUTEEG = pop_subcomp( INEEG ); % pop-up window mode % >> OUTEEG = pop_subcomp( INEEG, components, plotag); % >> OUTEEG = pop_subcomp( INEEG, components, plotag, keepcomp); % % Pop-up window interface: % "Component(s) to remove ..." - [edit box] Array of components to % remove from the data. Sets the 'components' parameter % in the command line call (see below). % "Component(s) to retain ..." - [edit box] Array of components to % to retain in the data. Sets the 'components' parameter in % the command line call. Then, comp_to_remove = ... % setdiff([1:size(EEG.icaweights,1)], comp_to_keep). See % option 'keepcomp' for command line call. % Overwrites "Component(s) to remove" (above). % Command line inputs: % INEEG - Input EEG dataset. % components - Array of components to remove from the data. If empty, % remove components previously marked for rejection (e.g., % EEG.reject.gcompreject). % plotag - [0|1] Display the difference between original and processed % dataset. 1 = Ask for confirmation. 0 = Do not ask. {Default: 0} % keepcomp - [0|1] If [1] will retain the components provided by the % input variable 'components', [0] will reject them. Option % intended to be used only with the components provided in % 'components', and not with components marked for rejection % {Default: 0} % Outputs: % OUTEEG - output dataset. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: compvar() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 02-15-02 propagate ica weight matrix -ad sm jorn function [EEG, com] = pop_subcomp( EEG, components, plotag, keepcomp) com=''; if nargin < 1 help pop_subcomp; return; end; if nargin < 3 plotag = 0; end; if nargin == 4 && ismember(keepcomp,[1 0]); keep_flag = keepcomp; if isempty(plotag) plotag = 0; end; else keep_flag = 0; end; if nargin < 2 % popup window parameters % ----------------------- if ~isempty(EEG.reject.gcompreject) components = find(EEG.reject.gcompreject == 1); components = components(:)'; promptstr = { ['Component(s) to remove from the data ([] = marked comps.)'] }; %promptstr = { ['Components to subtract from data' 10 '(default: pre-labeled components to reject):'] }; else components = []; promptstr = { ['Component(s) to remove from data:'] }; end; uilist = { { 'style' 'text' 'string' ['Component(s) to remove from data:'] } ... { 'style' 'edit' 'string' int2str(components) } ... { 'style' 'text' 'string' 'Component(s) to retain (overwrites "Component(s) to remove")' } ... { 'style' 'edit' 'string' '' } ... }; geom = { [2 0.7] [2 0.7] }; result = inputgui( 'uilist', uilist, 'geometry', geom, 'helpcom', 'pophelp(''pop_subcomp'')', ... 'title', 'Remove components from data -- pop_subcomp()'); if length(result) == 0 return; end; components = eval( [ '[' result{1} ']' ] ); if ~isempty(result{2}), components = eval( [ '[' result{2} ']' ] ); keep_flag = 1; %components = setdiff_bc([1:size(EEG.icaweights,1)], components); end; end; if isempty(components) if ~isempty(EEG.reject.gcompreject) components = find(EEG.reject.gcompreject == 1); else fprintf('Warning: no components specified, no rejection performed\n'); return; end; else if keep_flag == 1; components = setdiff_bc([1:size(EEG.icaweights,1)], components); end if (max(components) > size(EEG.icaweights,1)) || min(components) < 1 error('Component index out of range'); end; end; fprintf('Computing projection ....\n'); component_keep = setdiff_bc(1:size(EEG.icaweights,1), components); compproj = EEG.icawinv(:, component_keep)*eeg_getdatact(EEG, 'component', component_keep, 'reshape', '2d'); compproj = reshape(compproj, size(compproj,1), EEG.pnts, EEG.trials); %fprintf( 'The ICA projection accounts for %2.2f percent of the data\n', 100*varegg); if nargin < 2 | plotag ~= 0 ButtonName = 'continue'; while ~strcmpi(ButtonName, 'Cancel') & ~strcmpi(ButtonName, 'Accept') ButtonName=questdlg2( [ 'Please confirm. Are you sure you want to remove these components?' ], ... 'Confirmation', 'Cancel', 'Plot ERPs', 'Plot single trials', 'Accept', 'Accept'); if strcmpi(ButtonName, 'Plot ERPs') if EEG.trials > 1 tracing = [ squeeze(mean(EEG.data(EEG.icachansind,:,:),3)) squeeze(mean(compproj,3))]; figure; plotdata(tracing, EEG.pnts, [EEG.xmin*1000 EEG.xmax*1000 0 0], ... 'Trial ERPs (red) with and (blue) without these components'); else warndlg2('Cannot plot ERPs for continuous data'); end; elseif strcmpi(ButtonName, 'Plot single trials') eegplot( EEG.data(EEG.icachansind,:,:), 'srate', EEG.srate, 'title', 'Black = channel before rejection; red = after rejection -- eegplot()', ... 'limits', [EEG.xmin EEG.xmax]*1000, 'data2', compproj); end; end; switch ButtonName, case 'Cancel', disp('Operation cancelled'); return; case 'Accept', disp('Components removed'); end % switch end; EEG.data(EEG.icachansind,:,:) = compproj; EEG.setname = [ EEG.setname ' pruned with ICA']; EEG.icaact = []; goodinds = setdiff_bc(1:size(EEG.icaweights,1), components); EEG.icawinv = EEG.icawinv(:,goodinds); EEG.icaweights = EEG.icaweights(goodinds,:); EEG.specicaact = []; EEG.specdata = []; EEG.reject = []; try, EEG.dipfit.model = EEG.dipfit.model(goodinds); catch, end; com = sprintf('%s = pop_subcomp( %s, [%s], %d);', inputname(1), inputname(1), ... int2str(components), plotag); return;
github
lcnhappe/happe-master
eeg_topoplot.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_topoplot.m
13,363
utf_8
f7a6fe417c1429baaee4201b16da5df0
% eeg_topoplot() - plot scalp map % % eeg_topoplot( vals, chanlocs, 'key', 'val'); % % Input: % vals - values, one per channel % chanlocs - channel structure, same size as vals % % Optional inputs: % 'colormap' - colormap. Possible colormaps are 'blueredyellow', ... % 'yellowredblue', 'bluered' or any Matlab colormap ('cool', % 'jet', 'hsv', ...). It can also be a text file 'xxx.txt'. % The text file must contain 3 columns and idealy 64 rows % defining the colors in RGB format. % 'maplimits' - can be [min max]. This help defines the color scale for % maps. % 'electrodes' - can be 'on' to show electrode dots, 'off', or % 'labels' to show electrode labels. Default is 'on' % 'dotsize' - size of electrode dots. Default is 5. % 'shading' - 'flat','interp' {default: 'interp'} % 'exclude' - labels or indices of electrodes not to be plotted. From the % compiled files, these must be entered using underscores % for separators (e.g., "cz_pz"). % 'sphspline' - can be 'on' or 'off'. If 'on' spherical splines are used % for interpolation of the scalp map. If 'off' standard % planar inverse distance interpolation is used. % 'shrink' - shrink electrode positions (default is 0.75 to be able to % plot electrode at the head limit if spherical interpolation % is set and 0.95 for planar 2-D interpolation). % % References for spline interpolation: % [1] Perrin, F., Pernier, J., Bertrand, O., & Echallier, J. F. % (1989). Spherical splines for scalp potential and current % density mapping. Electroencephalography and Clinical % Neurophysiology, 72, 184-187 % [2] Ferree, T. C. (2000). Spline Interpolation of the Scalp EEG. % Retrieved March 26, 2006, from % www.egi.com/Technotes/SplineInterpolation.pdf % % limitation: does not plot anything below the upper part of the head % Copyright (C) Arnaud Delorme, SCCN, INC, 2010 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function eeg_topoplot(values, chanlocs, varargin); g = []; for index = 1:2:length(varargin) g = setfield(g, varargin{index}, varargin{index+1}); end; if ~isfield(g, 'electrodes'), g.electrodes = 'on'; end; if ~isfield(g, 'colormap'), g.colormap = jet; end; if ~isfield(g, 'maplimits'), g.maplimits = []; end; if ~isfield(g, 'headrad'), g.headrad = []; end; if ~isfield(g, 'sphspline'), g.sphspline = 'on'; end; if ~isfield(g, 'shading'), g.shading = 'interp'; end; if ~isfield(g, 'contour'), g.contour = 'on'; end; if ~isfield(g, 'dotsize'), g.dotsize = 5; end; if ~isfield(g, 'mark'), g.mark = []; end; if ~isfield(g, 'exclude'), g.exclude = []; end; if ~isfield(g, 'linewidth'), g.linewidth = 2; end; if ~isfield(g, 'shrink'), g.shrink = 1; end; if isstr(g.dotsize), g.dotsize = str2num(g.dotsize); end; if any(values == 0) inds = find(values == 0); if ~isempty( [ chanlocs(inds).theta ]) g.contour = 'off'; g.sphspline = 'off'; end; end; % exclude electrodes % ------------------ if ~isempty(g.exclude) chanlocs(g.exclude) = []; values(g.exclude) = []; end; % find channel coordinates % ------------------------ emptyvals = cellfun('isempty', { chanlocs.theta }); th = [ chanlocs.theta ]; rd = [ chanlocs.radius ]; [y x] = pol2cart(th/180*pi, rd); x=-x; x = x*g.shrink; y = y*g.shrink; newvalues = values; newvalues(emptyvals) = []; labls = { chanlocs.labels }; labls(emptyvals) = []; if strcmpi(g.sphspline, 'on') % default head radius % ------------------- g.headrad = 0.5; % spherical plotting % ------------------ xelec = [ chanlocs.X ]; yelec = [ chanlocs.Y ]; zelec = [ chanlocs.Z ]; dist = sqrt(xelec.^2+yelec.^2+zelec.^2); xelec = xelec./dist; yelec = yelec./dist; zelec = zelec./dist; if g.shrink ~= 1 [th phi rad] = cart2sph(xelec, yelec, zelec); phi = (phi-pi/2)*g.shrink+pi/2; [xelec, yelec, zelec] = sph2cart(th, phi, rad); end; [xsph, ysph, zsph, valsph] = spheric_spline(xelec,yelec,zelec,newvalues); surf(-ysph/2,xsph/2,zsph/2,double(valsph), 'edgecolor', 'none'); view([0 0 1]);hold on; shading(g.shading); top = max(abs(valsph(:)))*1000; if strcmpi(g.contour, 'on') [c h] = contour3(-ysph/2, xsph/2, valsph+top/10, 5); view([0 0 1]); set(h, 'cdata', [], 'edgecolor', 'k') end; % coordinates for electrodes % -------------------------- xelec(find(zelec < 0)) = []; yelec(find(zelec < 0)) = []; x = yelec/2; y = xelec/2; else % default head radius % ------------------- if isempty(g.headrad); g.headrad = max(sqrt(x.^2+y.^2)); end; % data points for 2-D data plot % ----------------------------- pnts = linspace(0,2*pi,200/0.25*(g.headrad.^2)); xx = sin(pnts)*g.headrad; yy = cos(pnts)*g.headrad; % make grid and add circle % ------------------------ gridres = 30; coords = linspace(-g.headrad, g.headrad, gridres); ay = repmat(coords, [gridres 1]); ax = repmat(coords', [1 gridres]); for ind=1:length(xx) [tmp closex] = min(abs(xx(ind)-coords)); [tmp closey] = min(abs(yy(ind)-coords)); ax(closex,closey) = xx(ind); ay(closex,closey) = yy(ind); end; xx2 = sin(pnts)*(g.headrad-0.01); yy2 = cos(pnts)*(g.headrad-0.01); for ind=1:length(xx) [tmp closex] = min(abs(xx2(ind)-coords)); [tmp closey] = min(abs(yy2(ind)-coords)); ax(closex,closey) = xx(ind); ay(closex,closey) = yy(ind); end; % linear interpolation and removal of values outside circle % --------------------------------------------------------- a = griddata(x, y, newvalues, -ay, ax, 'v4'); aradius = sqrt(ax.^2 + ay.^2); indoutcircle = find(aradius(:) > g.headrad+0.01); a(indoutcircle) = NaN; surf(ay, ax, a, 'edgecolor', 'none'); view([0 0 1]); hold on; shading(g.shading); top = max(values)*1.5; % plot level lines % ---------------- if strcmpi(g.contour, 'on') [c h] = contour3(ay, ax, a, 5); set(h, 'cdata', [], 'edgecolor', 'k') end; end; % plot electrodes as dots % ----------------------- if strcmpi(g.electrodes, 'on') | strcmpi(g.electrodes, 'labels') rad = sqrt(x.^2 + y.^2); x(find(rad > g.headrad)) = []; y(find(rad > g.headrad)) = []; plot3( -x, y, ones(size(x))*top, 'k.', 'markersize', g.dotsize); for i = g.mark, plot3( -x(i), y(i), double(top), 'y.', 'markersize', 4*g.dotsize); plot3( -x(i), y(i), double(top), 'r.', 'markersize', 2*g.dotsize); end; if strcmpi(g.electrodes, 'labels') for index = 1:length(x) text( -x(index)+0.02, y(index), double(top), labls{index}); end; end; else % invisible electrode that avoid plotting problem (no surface, only % contours) plot3( -x, y, -ones(size(x))*top, 'k.', 'markersize', 0.001); end; % plot dipoles if any % ------------------- if ~isempty(g.dipole) hold on; for index = 1:size(g.dipole,1) g.dipole(index,:) = g.dipole(index,:)*0.5; g.dipole(index,3:5) = g.dipole(index,3:5)/norm(g.dipole(index,3:end))*0.2; if ~any(g.dipole(index,:)) fprintf('Note: dipole contains 0 - not plotted\n') elseif sum(g.dipole(index,3:4).^2) <= 0.00001 fprintf('Note: dipole is length 0 - not plotted\n') elseif sum(g.dipole(index,1:2).^2) > g.headrad fprintf('Note: dipole is outside plotting area - not plotted\n') else hh = plot3( -g.dipole(index, 2), g.dipole(index, 1), top, '.'); set(hh, 'color', 'k', 'markersize', 30); hh = line( -[g.dipole(index, 2) g.dipole(index, 2)+g.dipole(index, 4)]', ... [g.dipole(index, 1) g.dipole(index, 1)+g.dipole(index, 3)]',[top top]); set(hh, 'color', 'k', 'linewidth', 30/7); end; end; end; % special colormaps % ----------------- if isstr(g.colormap) if ~isempty(strmatch(g.colormap, { 'hsv' 'jet' 'gray' 'hot' 'cool' 'bone' ... 'copper', 'pink' 'flag' 'prism' }, 'exact')) else % read text file g.colormap = load('-ascii', g.colormap); end; end; colormap(g.colormap); if ~isempty(g.maplimits) if ~isstr(g.maplimits) && ~isempty(g.maplimits) && ~isnan(g.maplimits(1)) caxis(g.maplimits); end; end; % main circle % ----------- radiuscircle = 0.5; pnts = linspace(0,2*pi,200); xc = sin(pnts)*radiuscircle; yc = cos(pnts)*radiuscircle; sf = 1; % scaling factor plot3(xc*sf,yc*sf,ones(size(xc))*top, 'k', 'linewidth', g.linewidth); hold on; % ears & nose % ----------- rmax = 0.5; base = rmax-.0046; basex = 0.18*rmax; % nose width tip = 1.15*rmax; tiphw = .04*rmax; % nose tip half width tipr = .01*rmax; % nose tip rounding q = .04; % ear lengthening EarX = [.497-.005 .510 .518 .5299 .5419 .54 .547 .532 .510 .489-.005]; % rmax = 0.5 EarY = [q+.0555 q+.0775 q+.0783 q+.0746 q+.0555 -.0055 -.0932 -.1313 -.1384 -.1199]; plot3(EarX*sf,EarY*sf,ones(size(EarX))*top,'color','k','LineWidth',g.linewidth) % plot left ear plot3(-EarX*sf,EarY*sf,ones(size(EarY))*top,'color','k','LineWidth',g.linewidth) % plot right ear plot3([basex;tiphw;0;-tiphw;-basex]*sf,[base;tip-tipr;tip;tip-tipr;base]*sf,top*ones(size([basex;tiphw;0;-tiphw;-basex])),'color','k','LineWidth',g.linewidth); % axis limits % ----------- axis off; set(gca, 'ydir', 'normal'); axis equal ylimtmp = max(g.headrad, 0.58); ylim([-ylimtmp ylimtmp]); % ---------------- % spherical spline % ---------------- function [x, y, z, Res] = spheric_spline( xelec, yelec, zelec, values); SPHERERES = 40; [x,y,z] = sphere(SPHERERES); x(1:(length(x)-1)/2,:) = []; y(1:(length(x)-1)/2,:) = []; z(1:(length(x)-1)/2,:) = []; Gelec = computeg(xelec,yelec,zelec,xelec,yelec,zelec); Gsph = computeg(x,y,z,xelec,yelec,zelec); % equations are % Gelec*C + C0 = Potential (C unknow) % Sum(c_i) = 0 % so % [c_1] % * [c_2] % [c_ ] % xelec [c_n] % [x x x x x] [potential_1] % [x x x x x] [potential_ ] % [x x x x x] = [potential_ ] % [x x x x x] [potential_4] % [1 1 1 1 1] [0] % compute solution for parameters C % --------------------------------- meanvalues = mean(values); values = values - meanvalues; % make mean zero C = pinv([Gelec;ones(1,length(Gelec))]) * [values(:);0]; % apply results % ------------- Res = zeros(1,size(Gsph,1)); for j = 1:size(Gsph,1) Res(j) = sum(C .* Gsph(j,:)'); end Res = Res + meanvalues; Res = reshape(Res, size(x)); % compute G function % ------------------ function g = computeg(x,y,z,xelec,yelec,zelec) unitmat = ones(length(x(:)),length(xelec)); EI = unitmat - ((repmat(x(:),1,length(xelec)) - repmat(xelec,length(x(:)),1)).^2 +... (repmat(y(:),1,length(xelec)) - repmat(yelec,length(x(:)),1)).^2 +... (repmat(z(:),1,length(xelec)) - repmat(zelec,length(x(:)),1)).^2)/2; g = zeros(length(x(:)),length(xelec)); m = 4; % 3 is linear, 4 is best according to Perrin's curve for n = 1:7 L = legendre(n,EI); g = g + ((2*n+1)/(n^m*(n+1)^m))*squeeze(L(1,:,:)); end g = g/(4*pi); % find electrode indices % ---------------------- function allinds = elecind( str, chanlocs, values ); findmax = 0; findmin = 0; if ~iscell(str) if strmatch(str, 'max', 'exact'), findmax = 1; end; if strmatch(str, 'min', 'exact'), findmin = 1; end; indunderscore = [ 0 find( str == '_' ) length(str)+1 ]; else indunderscore = [1:length(str)+1]; end; % find maximum or minimum % ----------------------- if findmax, [tmp allinds] = max(values); return; end; if findmin, [tmp allinds] = min(values); return; end; % find indices for labels % ----------------------- labels = lower({ chanlocs.labels }); for i = 1:length(indunderscore)-1 if ~iscell(str) tmpstr = str(indunderscore(i)+1:indunderscore(i+1)-1); else tmpstr = str{i}; end; tmpind = strmatch(lower(tmpstr), labels, 'exact'); if isempty(tmpind) if str2num(tmpstr) > 0 tmpind = str2num(tmpstr); else error(sprintf('Could not find channel "%s"', tmpstr)); end; end; allinds(i) = tmpind; end;
github
lcnhappe/happe-master
eeg_pvaf.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_pvaf.m
9,554
utf_8
0e527313c0a1dda9713e3cc25f465861
% eeg_pvaf() - Compute EEG.data 'percent variance accounted for' (pvaf) by specified components. % Can omit specified components and channels from the computation. Can draw a plot % of the scalp distribution of pvaf, or progressively compute the pvaf for comps % 1:k, where k = 1 -> the total number of components. Note: pvaf's of spatially % non-orthogonal independent components may not add to 100%, and individual component % pvaf could be < 0%. % Usage: % >> [pv] = eeg_pvaf(EEG,comps);s % >> [pvaf,pvafs,vars] = eeg_pvaf(EEG, comps,'key', val); % Inputs: % EEG - EEGLAB dataset. Must have icaweights, icasphere, icawinv, icaact. % comps - vector of component indices to sum {default|[] -> progressive mode} % In progressive mode, comps is first [1], then [1 2], etc. up to % [1:size(EEG.icaweights,2)] (all components); here, the plot shows pvaf. % % Optional inputs: % 'artcomps' - [integer] vector of artifact component indices to remove from data before % computing pvaf {default|[]: none} % 'omitchans' - [integer] channels to omit from the computation (e.g. off-head, etc) % {default|[]: none} % 'chans' - [integer] only compute pvaf at selected channels. Overwrite omitchans above. % 'fraction' - [0<real<=1] fraction of the data to randomly select {default|[]: 1=all} % 'plot' - ['on'|'off'] Plot scalp map of channel pvafs. {default: Plot only if no % output arguments} % % Outputs: % pvaf - (real) percent total variance accounted for by the summed back-projection of % the requested components. If comps is [], a vector of pvafs for the sum of % components 1:k (k=1:ncomps). % pvafs - (real vector) percent variance accounted for by the summed back-projection of % the requested components to each data channel. If comps is [], a matrix of % pvafs (as for pv above). % vars - variances of the requested channels % % Fields: % Assumes existence of the following EEG fiels: EEG.data, EEG.pnts, EEG.nbchan, EEG.trials, % EEG.icaact, EEG.icaweights, EEG.icasphere, EEG.icawinv, and for plot, EEG.chanlocs % % Author: Scott Makeig & Arnaud Delorme, SCCN, INC, UCSD, Fri Feb 13, 2004 % Copyright (C) 2004- Scott Makeig & Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [pvaf,pvafs,pvall] = eeg_pvaf(EEG,comps, varargin) if nargin < 1 help eeg_pvaf return end g = finputcheck(varargin, { 'artcomps' 'integer' [] []; 'omitchans' 'integer' [] []; 'chans' 'integer' [] []; 'fraction' 'real' [] 1; 'plot' 'string' { 'on';'off';'def' } 'def' }, 'eeg_pvaf'); if isstr(g), error(g); end; numcomps = size(EEG.icaact,1); if round(g.fraction*EEG.pnts*EEG.trials)<1 error('g.fraction of data specified too small.') return end if strcmpi(g.plot, 'def') if nargout > 0, g.plot = 'on'; else g.plot = 'off'; end; end numchans = EEG.nbchan; chans = 1:numchans; if ~isempty(g.chans) g.omitchans = setdiff_bc([1:EEG.nbchan], g.chans); end; if ~isempty(g.omitchans) if max(g.omitchans)>numchans help eeg_pvaf error('at least one channel to omit > number of channels in data'); end if min(g.omitchans)<1 help eeg_pvaf error('channel numbers to omit must be > 0'); end chans(g.omitchans) = []; end progressive = 0; % by default, progressive mode is off if nargin < 2 | isempty(comps)|comps==0 comps = []; progressive = 1; % turn progressive mode on end if isempty(EEG.icaweights) help eeg_pvaf return end if isempty(EEG.icasphere) help eeg_pvaf return end if isempty(EEG.icawinv) EEG.icawinv = pinv(EEG.icaweights*EEG.icasphere); end if isempty(EEG.icaact) help eeg_pvaf fprintf('EEG.icaact not present.\n'); % EEG.icaact = EEG.icaweights*EEG.icasphere*EEG.data; % remake it like this end if max(comps) > size(EEG.icawinv,1) help eeg_pvaf fprintf('Only %d components in this dataset. Cannot project component %d.\n',numcomps,max(comps)); error('bad comps input'); end if ~isempty(g.artcomps) & max(g.artcomps) > numcomps help eeg_pvaf fprintf('Only %d components in this dataset. Cannot project artcomp %d.\n',numcomps,max(g.artcomps)); error('bad artcomps input') end npts = EEG.trials*EEG.pnts; allcomps = 1:numcomps; if progressive fprintf('Considering components up to: '); cum_pvaf = zeros(1,numcomps); cum_pvafs = zeros(numcomps,numchans); end for comp = 1:numcomps %%%%%%%%%%%%%%% progressive mode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if progressive comps = allcomps(1:comp); % summing components 1 to current comp fprintf('%d ',comp) end if ~isempty(g.artcomps) [a b c] = intersect_bc(g.artcomps,comps); if ~isempty(a) if ~progressive if length(a)>1 fprintf('eeg_pvaf(): not back-projecting %d comps already in the artcomps.\n',length(c)); else fprintf('eeg_pvaf(): not back-projecting comp %d already in the artcomps.\n',comps(c)); end end comps(c) = []; end end if ~isempty(g.artcomps) & min([comps g.artcomps]) < 1 error('comps and artcomps must contain component indices'); end % %%%%%%%%%%%%%%%%%%%%%%%% compute variance accounted for by specified components %%%%%%%%%%%%% % if ~progressive | comp == 1 % pare out g.omitchans and artcomps from EEG.data if ~isempty(g.artcomps) EEG.data = EEG.data(chans,:) - EEG.icawinv(chans,g.artcomps)*EEG.icaact(g.artcomps,:); else EEG.data = EEG.data(chans,:); end nsel = round(g.fraction*npts); varpts = randperm(npts); varwts = ones(size(varpts)); if nsel<npts varwts(varpts(nsel+1:npts)) = 0; end pvall = var(EEG.data(:,:)',varwts); end pvdiff = var((EEG.data(:,:) - EEG.icawinv(chans,comps)*EEG.icaact(comps,:))', varwts); % %%%%%%%%%%%%%%%%%%%%%%%% compute percent variance accounted for %%%%%%%%%%%%%%% % pvafs = pvdiff ./ pvall; pvafs = 100-100*pvafs; pvaf = sum(pvdiff) ./ sum(pvall); pvaf = 100-100*pvaf; if ~progressive break else cum_pvaf(comp) = pvaf; cum_pvafs(comp,:) = pvafs; end end %%%%%%%%%%%%%% end progressive forloop %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if progressive % output accumulated results fprintf('\n'); pvaf = cum_pvaf; pvafs = cum_pvafs; if strcmpi(g.plot, 'on'); plot(1:numcomps,pvaf); xl = xlabel('Components Included (1:n)'); yl = ylabel('Percent Variance Accounted For (pvaf)'); set(xl,'fontsize',15); set(yl,'fontsize',15); set(gca,'fontsize',14); end elseif strcmpi(g.plot, 'on') % %%%%%%%%%%%%%%%%%%%%%%%% plot the scalp distribtion of pvaf %%%%%%%%%%%%% % if isfield(EEG,'chanlocs') chanlocs = EEG.chanlocs; if ~isempty(g.omitchans) chanlocs(g.omitchans) = []; end if length(chanlocs) > 1 topoplot(pvafs',chanlocs); % plot pvaf here end; if length(comps)>5 % add text legend if length(g.artcomps)>3 tlstr=sprintf('Pvaf by %d comps in data minus %d comps',length(comps),length(g.artcomps)); elseif isempty(g.artcomps) tlstr=sprintf('Pvaf by %d comps in data',length(comps)); elseif length(g.artcomps)==1 % < 4 g.artcomps, list them tlstr=sprintf('Pvaf by %d comps in data (less comp ',length(comps)); tlstr = [tlstr sprintf('%d ',g.artcomps) ')']; else tlstr=sprintf('Pvaf by %d comps in data (less comps ',length(comps)); tlstr = [tlstr sprintf('%d ',g.artcomps) ')']; end else % < 6 comps, list them if length(comps)>1 tlstr=sprintf('Pvaf by comps '); else tlstr=sprintf('Pvaf by comp '); end if length(g.artcomps)>3 tlstr = ... [tlstr sprintf('%d ',comps) sprintf('in data minus %d comps',length(comps),length(g.artcomps))]; else if isempty(g.artcomps) tlstr = [tlstr sprintf('%d ',comps) 'in data']; elseif length(g.artcomps)==1 tlstr = [tlstr sprintf('%d ',comps) 'in data (less comp ']; tlstr = [tlstr int2str(g.artcomps) ')']; else tlstr = [tlstr sprintf('%d ',comps) 'in data (less comps ']; tlstr = [tlstr sprintf('%d ',g.artcomps) ')']; end end end tl=title(tlstr); if max(pvafs)>100, maxc=max(pvafs) else maxc=100; end; pvstr=sprintf('Total pvaf: %3.1f%%',pvaf); tx=text(-0.9,-0.6,pvstr); caxis([-100 100]); cb=cbar('vert',33:64,[0 100]); % color bar showing >0 (green->red) only else fprintf('EEG.chanlocs not found - not plotting scalp pvaf\n'); end end % end plot
github
lcnhappe/happe-master
pop_copyset.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_copyset.m
2,501
utf_8
5ff586e542073596297cfaa0cb6d2da0
% pop_copyset() - Copy the current EEG dataset into another dataset. % % Usage: % >> ALLEEG = pop_copyset(ALLEEG, index1); % pop-up % >> [ ALLEEG EEG CURRENTSET ] = pop_copyset(ALLEEG, index1, index2 ); % % Inputs: % ALLEEG - array of dataset structure % index1 - input dataset number % index2 - index of dataset to copy into % % Inputs: % ALLEEG - array of dataset structures % EEG - new copied structure % CURRENTSET - index of the new dataset % % Note: this function performs ALLEEG(index2) = ALLEEG(index1); % with dataset checks % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeg_store(), pop_delset(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad function [ALLEEG, EEG, CURRENTSET, com] = pop_copyset(ALLEEG, set_in, set_out); com = ''; if nargin < 2 help pop_copyset; return; end; if isempty(ALLEEG) error(['Pop_copyset error: cannot copy' 10 'single dataset mode']); end; if set_in == 0 error('Pop_copyset error: cannot copy dataset'); return; end; if isempty(ALLEEG(set_in).data) error('Pop_copyset error: cannot copy empty dataset'); return; end; if nargin < 3 % which set to save % ----------------- promptstr = { 'Index of the new dataset:'}; inistr = { int2str(set_in+1) }; result = inputdlg2( promptstr, 'Copy dataset -- pop_copyset()', 1, inistr, 'pop_copyset'); if size( result ) == 0, EEG = []; CURRENTSET = 0; return; end; set_out = eval( result{1} ); end; ALLEEG = eeg_store(ALLEEG, eeg_retrieve(ALLEEG, set_in), set_out); EEG = eeg_retrieve(ALLEEG, set_out); CURRENTSET = set_out; com = sprintf('[ALLEEG EEG CURRENTSET] = pop_copyset( %s, %d, %d);', inputname(1), set_in, set_out); return;
github
lcnhappe/happe-master
eeg_chaninds.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_chaninds.m
2,367
utf_8
2def40fab41159484d7bd8502397d5a6
% std_chaninds() - look up channel indices in a EEG structure % % Usage: % >> inds = std_chaninds(EEG, channames); % Inputs: % EEG - EEG structure containing a chanlocs substructure. % the chanlocs structure may also be used as input. % channames - [cell] channel names. May also be a string containing % one or several channel names. % % Outputs: % inds - [integer array] channel indices % % Author: Arnaud Delorme, CERCO, 2009- % Copyright (C) Arnaud Delorme, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function finalinds = eeg_chaninds(EEG, channames, errorifnotfound); if nargin < 2 help eeg_chaninds; return; end; if nargin < 3 errorifnotfound = 1; end; if isfield(EEG, 'chanlocs') chanlocs = EEG.chanlocs; else chanlocs = EEG; end; % decode string if necessary % -------------------------- if isstr(channames) channames = parsetxt( channames ); end; finalinds = []; if isempty(chanlocs) tmpallchans = []; else tmpallchans = lower({ chanlocs.labels }); end; if isempty(channames), finalinds = [1:length(chanlocs)]; return; end; for c = 1:length(channames) chanind = strmatch( lower(channames{c}), tmpallchans, 'exact'); if isempty(chanind), chanind = str2double(channames{c}); if isnan(chanind), chanind = []; end; if errorifnotfound && isempty(chanind) error(sprintf('Channel %s not found', channames{c})); end; end; finalinds = [ finalinds chanind ]; end; finalinds = sort(finalinds);
github
lcnhappe/happe-master
pop_readegi.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_readegi.m
8,591
utf_8
2f7b99d9be1290f1e4f5c78dd01815da
% pop_readegi() - load a EGI EEG file (pop out window if no arguments). % % Usage: % >> EEG = pop_readegi; % a window pops up % >> EEG = pop_readegi( filename ); % >> EEG = pop_readegi( filename, datachunks, forceversion, fileloc); % % Inputs: % filename - EGI file name % datachunks - desired frame numbers (see readegi() help) % option available from the command line only % forceversion - [integer] force reading a specfic file version % fileloc - [string] channel location file name. Default is % 'auto' (autodetection) % % Outputs: % EEG - EEGLAB data structure % % Author: Arnaud Delorme, CNL / Salk Institute, 12 Nov 2002 % % See also: eeglab(), readegi(), readegihdr() % Copyright (C) 12 Nov 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, command] = pop_readegi(filename, datachunks, forceversion, fileloc); EEG = []; command = ''; if nargin < 4, fileloc = 'auto'; end; disp('Warning: This function can only import continuous files or'); disp(' epoch files with only one length for data epochs'); if nargin < 1 % ask user [filename, filepath] = uigetfile('*.RAW;*.raw', ... 'Choose an EGI RAW file -- pop_readegi()'); drawnow; if filename == 0 return; end; filename = [filepath filename]; fid = fopen(filename, 'rb', 'b'); if fid == -1, error('Cannot open file'); end head = readegihdr(fid); % read EGI file header fclose(fid); if head.segments ~= 0 fileloc = ''; floc = { 'GSN-HydroCel-32.sfp' 'GSN65v2_0.sfp' 'GSN129.sfp' 'GSN-HydroCel-257.sfp'}; switch head.nchan case { 32 33 }, fileloc = floc; case { 64 65 }, fileloc = {floc{2} floc{3:4} floc{1}}; case { 128 129 }, fileloc = {floc{3} floc{4} floc{1:2}}; case { 256 257 }, fileloc = {floc{4} floc{1:3}}; end; uilist = { { 'style' 'text' 'string' sprintf('Segment/frame number (default: 1:%d)', head.segments) } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Channel location file (in eeglab/sample_locs)' } ... { 'style' 'popupmenu' 'string' fileloc } ... { } ... { 'style' 'text' 'string' ... [ 'Note: Choosing the correct electrode location file for your data is critical.' 10 ... 'Note that in some cases none of the channel location files listed will correspond' 10 ... 'to your montage as EGI has different versions of caps and is creating new ones' 10 ... 'constantly. Remember to check your montage in the channel editor and import. Channel' 10 ... 'location files are stored in the sample_locs sub-folder of the EEGLAB distribution.' ] } }; uigeometry = { [2 1] [2 1] [1] [1] }; uigeomvert = [1 1 1.5 3]; result = inputgui('uilist', uilist, 'geometry', uigeometry, 'geomvert', uigeomvert); % promptstr = { sprintf('Segment/frame number (default: 1:%d)', head.segments) 'Channel location file (in eeglab/sample_locs)' }; % inistr = { '' fileloc(res{2})}; % result = inputdlg2( promptstr, 'Import EGI file -- pop_readegi()', 1, inistr, 'pop_readegi'); if length(result) == 0 return; end; datachunks = eval( [ '[' result{1} ']' ] ); fileloc = char(fileloc(result{2})); else datachunks = []; disp('Only one segment, cannot read portion of the file'); end; end; % load data % ---------- EEG = eeg_emptyset; if exist('datachunks') && exist('forceversion') && ~isempty(forceversion) [Head EEG.data Eventdata SegCatIndex] = readegi( filename, datachunks,forceversion); elseif exist('forceversion') && ~isempty(forceversion) [Head EEG.data Eventdata SegCatIndex] = readegi( filename,[],forceversion); elseif exist('datachunks') [Head EEG.data Eventdata SegCatIndex] = readegi( filename, datachunks); forceversion = []; else [Head EEG.data Eventdata SegCatIndex] = readegi( filename); forceversion = []; end if ~isempty(Eventdata) & size(Eventdata,2) == size(EEG.data,2) EEG.data(end+1:end+size(Eventdata,1),:) = Eventdata; end; EEG.comments = [ 'Original file: ' filename ]; EEG.setname = 'EGI file'; EEG.nbchan = size(EEG.data,1); EEG.srate = Head.samp_rate; EEG.trials = Head.segments; EEG.pnts = Head.segsamps; EEG.xmin = 0; % importing the events % -------------------- EEG = eeg_checkset(EEG); if ~isempty(Eventdata) orinbchans = EEG.nbchan; for index = size(Eventdata,1):-1:1 EEG = pop_chanevent( EEG, orinbchans-size(Eventdata,1)+index, 'edge', 'leading', ... 'delevent', 'off', 'typename', Head.eventcode(index,:), ... 'nbtype', 1, 'delchan', 'on'); Head.eventcode(end,:) = []; end; % renaming event codes % -------------------- try, tmpevent = EEG.event; alltypes = { tmpevent.type }; if isstr(alltypes{1}) indepoc = strmatch('epoc', lower(alltypes), 'exact'); indtim = strmatch('tim0', lower(alltypes), 'exact'); % if epoc but no tim0 then epoc represent pauses in recording if isempty(indtim) & ~isempty(indepoc) for index = indepoc EEG.event(index).type = 'boundary'; end; end; % other wise if both non-empty data epochs if ~isempty(indtim) & ~isempty(indepoc) if rem(size(EEG.data,2) / (length(indepoc)+1),1) == 0 EEG.event(index) = []; % remove epoch events EEG.trials = length(indepoc)+1; else disp('Warning: data epochs detected but wrong data size'); end; end; end; catch, disp('Warning: event renaming failed'); end; end; % adding segment category indices % ------------------------------- if ~isempty(SegCatIndex) && EEG.trials > 1 try if ~isempty(EEG.event) for index = 1:length(EEG.event) EEG.event(index).category = Head.catname{SegCatIndex(EEG.event(index).epoch)}; end; else % create time-locking events for trial = 1:EEG.trials EEG.event(trial).epoch = trial; EEG.event(trial).type = 'TLE'; EEG.event(trial).latency = -EEG.xmin*EEG.srate+1+(trial-1)*EEG.pnts; EEG.event(trial).category = Head.catname{SegCatIndex(trial)}; end; end; catch, disp('Warning: error while importing trial categories'); EEG.event = rmfield(EEG.event, 'category'); end; end; EEG = eeg_checkset(EEG, 'makeur'); EEG = eeg_checkset(EEG, 'eventconsistency'); % importing channel locations % --------------------------- if nargin < 1 warndlg2( [ 'EEGLAB will now import a default electrode location file' 10 ... 'for your data. Note that this might not correspond' 10 ... 'to your montage as EGI has different versions of caps.' 10 ... 'Check your montage in the channel editor and import' 10 ... 'the correct location file if necessary.' ]); end; if all(EEG.data(end,1:10) == 0) disp('Deleting empty data reference channel (reference channel location is retained)'); EEG.data(end,:) = []; EEG.nbchan = size(EEG.data,1); EEG = eeg_checkset(EEG); end; if ~isempty(fileloc) if strcmpi(fileloc, 'auto') EEG = readegilocs(EEG); else EEG = readegilocs(EEG, fileloc); end; end; if nargin < 1 command = sprintf('EEG = pop_readegi(''%s'', %s);', filename, vararg2str({datachunks forceversion fileloc }) ); end; return;
github
lcnhappe/happe-master
pop_erpimage.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_erpimage.m
34,127
utf_8
7a821956c6e3beaf067346e54d7e5e01
% pop_erpimage() - draw an ERP-image plot of a given EEG channel or independent % component. Uses a pop-up window if less than three (or four % in one condition) input arguments are supplied. Calls erpimage(). % For futher details see >> help erpimage % Usage: % >> pop_erpimage(EEG, typeplot); % pop-up a data entry window % >> pop_erpimage(EEG, typeplot, lastcom); % pop-up a data entry window % >> pop_erpimage(EEG, typeplot, channel); % no pop-up window % >> pop_erpimage(EEG, typeplot, channel, projchan, title, ... % smooth, decimate, sortingtype, sortingwin, ... % sortingeventfield, renorm, options...); % Graphic interface: % "Channel or Component" - [edit box] Enter channel number or component % number to plot. erpimage() equivalent: 'channel' % "Project to channel #" - [edit box] (for plotting independent components). % Allow reprojecting the component activity % to a given channel or group of channels. % erpimage() equivalent: [none] % "Smoothing" - [text box] Smoothing parameter in number of trials. % erpimage() equivalent: 'smooth' % "Downsampling" - [edit box] Decimate parameter. % erpimage() equivalent: 'decimate' % "Time limits" - [edit box] Enter the time limits in milliseconds. % erpimage() equivalent: the 1st and 2nd parameters of the 'limit' array % "Figure title" - [edit box] Enter the figure title here. If empty, a title % is automatically generated. erpimage() equivalent: 'title' % "Plot scalp map" - [checkbox] Setting this option plot a scalp map of the % channel location (or component topography) next to the % erpimage. erpimage() equivalent: 'topo' % "plot ERP" - [checkbox] Setting this option plot the channel or component % ERP below the ERP image. erpimage() equivalent: 'erp' % "Plot colorbar" - [checkbox] Plot the colorbar on the right of the erpimage. % erpimage() equivalent: 'cbar' % "ERP limits" - [edit box] Set the minimum and maximum value for the ERP plot % erpimage() equivalent: 3rd and 4th parameters of the 'limit' array % "Color limits" - [edit box] Set the color limits for the ERP image. % erpimage() equivalent: 'caxis' % "Epoch sorting field" - [button and edit box] Specify the event field which % values will be used to sort the trials. For instance, if you % select the 'latency' fields, trials will be sorted by the % latency of the selected events. % erpimage() equivalent: 'sortingeventfield' % "Event type(s)" - [button and edit box] Specify which event subset to select, % based on the event 'type' field values (to scan for event types, use % menu Edit > Events values and look at the values of the 'type' % field). For instance, entering type 'rt' (if defined) and field % 'latency' in option aboce will sort trials on reaction time latencies. % When several selected events are present in individual trials, % the first event values are used for sorting and a warning is issued. % erpimage() equivalent: 'sortingtype' % "Event time range" - [edit box] Specify which event subset to select based on % event latency values. As the option above, this further restrains % the selection of events. For example, entering [200 300] in this % box, 'rt' for the event type (above), and 'latency' for the % epoch sorting field will select trials with reaction-time latencies % in between 200 and 300 ms. Trials with no such event will not be % included in the ERP-image plot. erpimage() equivalent: 'sortingwin' % "rescale" - [edit box] 'yes', 'no', or a Matlab formula. % erpimage() equivalent: 'renorm' % "align" - [edit box] Set this to 'Inf' to re-align the individual trials % on the median latency of the selected events. Else, enter an epoch time % (in ms) to align the events to (Ex: 0). erpimage() equivalent: 'align' % "Don't sort by value" - [checkbox] Check this box if you do not want to % sort the trials but do want to plot the selected event values. % erpimage() equivalent: 'nosort' % "Don't plot value" - [checkbox] Check this box if you do not want to % plot the selected event values, but still want to sort % the data trials according to these values. % erpimage() eqivalent: 'noplot' % "Sort by phase > Frequency" - [edit box] Specify the frequency or frequency % range for sorting trials by phase. erpimage() equivalent: % 3rd and 4th inputs to 'phasesort' % "Window center (ms)" - [edit box] erpimage() equivalent: 1st 'phasesort' input % "Percent low-amp. trials to ignore" - [edit box] erpimage() equivalent: % 2nd 'phasesort' input % "Wavelet cycles" - [text] Number of wavelet cycles used for spectral decomposition % at the specified latency. To change this, see "More options" {default: 3} % "Inter-trial coherence options > Frequency" - [edit box] Frequency at which % to compute coherence. Constrained to be the same as the % "Sort by phase > Frequency" edit box. erpimage() equivalent: 'coher' % "Signif. level" - [edit box] Coherence significance cutoff, as a proability % (Ex: .05). erpimage() equivalent: 'signif' % "Amplitude limit" - [edit box] Amplitude limits [min max] for the data power % plot at the selected frequency. erpimage() equivalent: % 5th and 6th inputs to 'limit' % "Coher limits" - [edit box] Upper limit (<=1) for the coherence % plot. erpimage() equivalent: 7th and 8th inputs of 'limit' % "Image amps" - [checkbox] Check this box for plotting the spectral amplitude % image at the selected frequency (instead of plotting EEG potential). % erpimage() equivalent: 'plotamp' % "Plot spectrum" - [edit box] Plot the channel or component data spectrum in % the top right corner of the ERP image. erpimage() equivalent: 'spec' % "Baseline ampl." - [edit box] Baseline amplitude for data power plot at the % selected frequency. erpimage() equivalent: 7th inputs of 'limit' % "Mark times" - [edit box] Time(s) in ms to plot vertical lines. % erpimage() equivalent: 'vert' % "More options" - [edit box] Enter 'key', 'value' sequences. Other erpimage() % options not handled by this interface, including: 'erpstd' to % plot the ERP standard deviation; 'auxvar' to plot auxilary % variables; 'ampsort' to sort trials based on amplitude at % the selected frequency, etc. For further information see % >> help erpimage() % Inputs: % EEG - dataset structure % typeplot - 1=channel, 0=component {default: 1} % lastcom - string containing previous pop_erpimage command (from LASTCOM) % or from the previous function call output. The values from this % function call are used as default in the graphic interface. % % Commandline options: % channel - Index of channel or component(s) to plot {default: 1} % projchan - Channel to back-project the selected component(s) to. % If plotting channel activity, this argument is ignored. % If [], the ICA component activation is plotted {default []}. % title - ['string'] Plot title {default: []} % smooth - Smoothing parameter (number of trials). {Default: 5} % erpimage() equivalent: 'avewidth' % decimate - Decimate parameter (i.e. ratio of trials_in/trials_out). % erpaimge() equivalent: 'decimate' {Default: 0} % sortingtype - Sorting event type(s) ([int vector]; []=all). See Notes below. % Either a string or an integer. % sortingwin - Sorting event window [start, end] in seconds ([]=whole epoch) % sortingeventfield - Sorting field name. {default: none}. See Notes below. % options - erpimage() options, separated by commas (Ex: 'erp', 'cbar'). % {Default: none}. For further details see >> erpimage help % % Outputs from pop-up: % String containing the command used to evaluate this plotting function % (saved by eeglab() as LASTCOM). Enter it as the 'lastcom' input to restore % the previous parameters as defaults in a new pop_erpimage() pop-up window % % Outputs from commandline: % Same as erpimage(). Note: No outputs are returned when a window pops-up % to ask for additional arguments % % Notes: % 1) A new figure is created only when the pop-up window is called, % so you may call this command with >3 args to draw in sbplot() axes. % 2) To sort epochs, first define the event field to be used with % the argument 'sortingeventfield' (for instance 'latency'). Then, % because there may be several events with different latencies in a % given epoch, it is possible to consider only a subsets of events % using the 'sortingtype' and 'sortingwin' arguments. The % 'sortingtype' argument selects events with definite types. The % 'sortingwin' argument helps to define a specific time window in the % epoch to select events. For instance the epoch time range may be -1 % to 2 seconds but one may want to select events only in the range 0 % to 1 second. These three parameters are forwarded to the function % eeg_getepochevent(), whose help message contains more details. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab(), erpimage(), eeg_getepochevent() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 02-12-02 added new event format compatibility -ad % 02-15-02 text interface editing -sm & ad % 03-07-02 add the eeglab computeica options -ad % 02-15-02 modified the function accoring to the new event/epoch structure -ad % 03-18-02 added title -ad & sm % 04-04-02 added outputs -ad & sm function varargout = pop_erpimage( EEG, typeplot, channel, projchan, titleplot, smooth, decimate, sortingtype, ... sortingwin, sortingeventfield, varargin) varargout{1} = ''; if nargin < 1 help pop_erpimage; return; end; if typeplot == 0 && isempty(EEG.icasphere) error('no ICA data for this set, first run ICA'); end; if EEG.trials == 1 error('erpimage of one trial cannot be plotted'); end; if nargin < 2 typeplot = 1; %1=signal; 0=component end; lastcom = []; if nargin < 3 popup = 1; else popup = isstr(channel) | isempty(channel); if isstr(channel) lastcom = channel; end; end; if popup % get contextual help % ------------------- clear functions; erpimagefile = which('erpimage.m'); [txt2 vars2] = gethelpvar(erpimagefile); txt = { txt2{:}}; vars = { vars2{:}}; % [txt vars] = gethelpvar('erpimopt.m'); % txt = { txt{:} txt2{:}}; % vars = { vars{:} vars2{:}}; opt.topo = getkeyval(lastcom, 'topo', 'present', 1); opt.fieldname = getkeyval(lastcom, 10); opt.type = getkeyval(lastcom, 8); opt.renorm = getkeyval(lastcom, 'renorm','', 'no'); opt.erp = fastif(getkeyval(lastcom, '''erp''', 'present', 1), 'on', 'off'); opt.cbar = fastif(getkeyval(lastcom, 'cbar', 'present', 1), 'on', 'off'); opt.nosort = fastif(getkeyval(lastcom, 'nosort', 'present', 0), 'on', 'off'); opt.noplot = fastif(getkeyval(lastcom, 'noplot', 'present', 0), 'on', 'off'); opt.plotamps = fastif(getkeyval(lastcom, 'plotamps', 'present', 0), 'on', 'off'); opt.index = str2num(getkeyval(lastcom,3,[],'1')); opt.smoothing = str2num(getkeyval(lastcom, 6, [], int2str(min(max(EEG.trials-5,0), 10)))); opt.downsampling = str2num(getkeyval(lastcom, 7, [], '1')); opt.caxis = str2num(getkeyval(lastcom, 'caxis')); opt.eventrange = str2num(getkeyval(lastcom, 9)); opt.align = str2num(getkeyval(lastcom, 'align')); opt.phasesort = str2num(getkeyval(lastcom, 'phasesort')); opt.coher = str2num(getkeyval(lastcom, 'coher')); opt.spec = str2num(getkeyval(lastcom, 'spec')); opt.vert = str2num(getkeyval(lastcom, 'vert')); opt.limits = str2num(getkeyval(lastcom, 'limits')); opt.limits = [ opt.limits NaN NaN NaN NaN NaN NaN NaN NaN NaN ]; opt.limits = opt.limits(1:9); opt.coher = [ opt.coher NaN NaN NaN NaN NaN NaN NaN NaN NaN ]; opt.coher = opt.coher(1:3); opt.phasesort = [ opt.phasesort NaN NaN NaN NaN NaN NaN NaN NaN NaN ]; opt.phasesort = opt.phasesort(1:4); if isnan(opt.limits(1)), opt.limits(1:2) = 1000*[EEG.xmin EEG.xmax]; end; commandphase = [ 'if ~isempty(get(findobj(''parent'', gcbf, ''tag'', ''phase''),''string'')),' ... ' if ~isempty(get(findobj(''parent'', gcbf, ''tag'', ''coher''),''string'')), ' ... ' set(findobj(''parent'', gcbf, ''tag'', ''coher''), ''string'', get(findobj(''parent'', gcbf, ''tag'', ''phase''),''string''));' ... 'end; end;' ]; commandcoher = [ 'if ~isempty(get(findobj(''parent'', gcbf, ''tag'', ''coher''),''string'')),' ... ' if ~isempty(get(findobj(''parent'', gcbf, ''tag'', ''phase''),''string'')), ' ... ' set(findobj(''parent'', gcbf, ''tag'', ''phase''), ''string'', get(findobj(''parent'', gcbf, ''tag'', ''coher''),''string''));' ... 'end; end;' ]; commandfield = ['if isempty(EEG.event)' ... ' errordlg2(''No events'');' ... 'else' ... ' tmpfieldnames = fieldnames(EEG.event);' ... ' [tmps,tmpv] = listdlg2(''PromptString'', ''Select fields'', ''SelectionMode'',''single'',''ListString'', tmpfieldnames);' ... ' if tmpv' ... ' set(findobj(''parent'', gcbf, ''tag'', ''field''), ''string'', tmpfieldnames{tmps});' ... ' end;' ... 'end;' ... 'if isempty(get(findobj(''parent'', gcbf, ''tag'', ''type''), ''string'')),' ... ' warndlg2(''Do not forget to select an event type in the next edit box'');' ... 'end;' ... 'clear tmps tmpv tmpfieldnames;' ]; commandtype = [ 'if ~isfield(EEG.event, ''type'')' ... ' errordlg2(''No type field'');' ... 'else' ... ' tmpevent = EEG.event;' ... ' if isnumeric(EEG.event(1).type),' ... ' [tmps,tmpstr] = pop_chansel(unique([ tmpevent.type ]));' ... ' else,' ... ' [tmps,tmpstr] = pop_chansel(unique({ tmpevent.type }));' ... ' end;' ... ' if ~isempty(tmps)' ... ' set(findobj(''parent'', gcbf, ''tag'', ''type''), ''string'', tmpstr);' ... ' end;' ... 'end;' ... 'if isempty(get(findobj(''parent'', gcbf, ''tag'', ''field''), ''string'')),' ... ' warndlg2(''Do not forget to select an event type in the previous edit box'');' ... 'end;' ... 'clear tmps tmpv tmpstr tmpevent tmpfieldnames;' ]; geometry = { [1 1 0.1 0.8 2.1] [1 1 1 1 1] [1 1 1 1 1] [1 1 1 1 1] [1] [1] [1 1 1 0.8 0.8 1.2] [1 1 1 0.8 0.8 1.2] [1] [1] ... [1.6 1.7 1.2 1 .5] [1.6 1.7 1.2 1 .5] [1] [1] [1.5 1 1 1 1] [1.5 1 1 1 1] [1] [1] [1.5 1 1 2.2] [1.5 1 1 2.2]}; uilist = { { 'Style', 'text', 'string', fastif(typeplot, 'Channel', 'Component(s)'), 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', num2str(opt.index), 'tag', 'chan' } { } ... { 'Style', 'text', 'string', 'Figure title', 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', '', 'tag', 'title' } ... ... { 'Style', 'text', 'string', 'Smoothing', 'fontweight', 'bold', 'tooltipstring', context('avewidth',vars,txt) } ... { 'Style', 'edit', 'string', num2str(opt.smoothing), 'tag', 'smooth' } ... { 'Style', 'checkbox', 'string', 'Plot scalp map', 'tooltipstring', 'plot a 2-d head map (vector) at upper left', ... 'value', opt.topo, 'tag', 'plotmap' } { } { } ... { 'Style', 'text', 'string', 'Downsampling', 'fontweight', 'bold', 'tooltipstring', context('decimate',vars,txt) } ... { 'Style', 'edit', 'string', num2str(opt.downsampling), 'tag', 'decimate' } ... { 'Style', 'checkbox', 'string', 'Plot ERP', 'tooltipstring', context('erp',vars,txt), 'value', fastif(strcmpi(opt.erp, 'on'), 1,0), 'tag', 'erp' } ... { 'Style', 'text', 'string', fastif(typeplot, 'ERP limits (uV)','ERP limits'), 'tooltipstring', [ 'Plotting limits for ERP trace [min_uV max_uV]' 10 '{Default: ERP data limits}'] } ... { 'Style', 'edit', 'string', fastif(~isnan(opt.limits(3)), num2str(opt.limits(3:4)), ''), 'tag', 'limerp' } ... { 'Style', 'text', 'string', 'Time limits (ms)', 'fontweight', 'bold', 'tooltipstring', 'Select time subset in ms' } ... { 'Style', 'edit', 'string', fastif(~isnan(opt.limits(1)), num2str(opt.limits(1:2)), ''), 'tag', 'limtime' } ... { 'Style', 'checkbox', 'string', 'Plot colorbar','tooltipstring', context('caxis',vars,txt), 'value', fastif(strcmpi(opt.cbar, 'on'), 1,0), 'tag', 'cbar' } ... { 'Style', 'text', 'string', 'Color limits (see Help)','tooltipstring', context('caxis',vars,txt) } ... { 'Style', 'edit', 'string', num2str(opt.caxis), 'tag', 'caxis' } ... {} ... { 'Style', 'text', 'string', 'Sort/align trials by epoch event values', 'fontweight', 'bold'} ... { 'Style', 'pushbutton', 'string', 'Epoch-sorting field', 'callback', commandfield, ... 'tooltipstring', 'Epoch-sorting event field name (Ex: latency; default: no sorting):' } ... { 'Style', 'pushbutton', 'string', 'Event type(s)', 'callback', commandtype, 'tooltipstring', ['Event type(s) subset (default: all):' 10 ... '(See ''/Edit/Edit event values'' for event types)'] } ... { 'Style', 'text', 'string', 'Event time range', 'tooltipstring', [ 'Sorting event window [start, end] in milliseconds (default: whole epoch):' 10 ... 'events are only selected within this time window (can be usefull if several' 10 ... 'events of the same type are in the same epoch, or for selecting trials with given response time)']} ... { 'Style', 'text', 'string', 'Rescale', 'tooltipstring', 'Rescale sorting variable to plot window (yes|no|a*x+b)(Ex:3*x+2):' } ... { 'Style', 'text', 'string', 'Align', 'tooltipstring', context('align',vars,txt) } ... { 'Style', 'checkbox', 'string', 'Don''t sort by value', 'tooltipstring', context('nosort',vars,txt), 'value', fastif(strcmpi(opt.nosort, 'on'), 1,0), 'tag', 'nosort' } ... { 'Style', 'edit', 'string', opt.fieldname, 'tag', 'field' } ... { 'Style', 'edit', 'string', opt.type, 'tag', 'type' } ... { 'Style', 'edit', 'string', num2str(opt.eventrange), 'tag', 'eventrange' } ... { 'Style', 'edit', 'string', opt.renorm, 'tag', 'renorm' } ... { 'Style', 'edit', 'string', num2str(opt.align), 'tag', 'align' } ... { 'Style', 'checkbox', 'string', 'Don''t plot values', 'tooltipstring', context('noplot',vars,txt), 'value', fastif(strcmpi(opt.noplot, 'on'), 1,0), 'tag', 'noplot' } ... {} ... { 'Style', 'text', 'string', 'Sort trials by phase', 'fontweight', 'bold'} ... { 'Style', 'text', 'string', 'Frequency (Hz | minHz maxHz)', 'tooltipstring', ['sort by phase at maximum-power frequency' 10 ... 'in the data within the range [minHz,maxHz]' 10 '(overrides frequency specified in ''coher'' flag)'] } ... { 'Style', 'text', 'string', 'Percent low-amp. trials to ignore', 'tooltipstring', ['percent of trials to reject for low' ... 'amplitude. Else,' 10 'if prct is in the range [-100,0] -> percent to reject for high amplitude'] } ... { 'Style', 'text', 'string', 'Window center (ms)', 'tooltipstring', 'Center time of the n-cycle window' } ... { 'Style', 'text', 'string', 'Wavelet cycles', 'tooltipstring', 'cycles per wavelet window' } {}... { 'Style', 'edit', 'string', fastif(~isnan(opt.phasesort(3)),num2str(opt.phasesort(3:4)),'') 'tag', 'phase', 'callback', commandphase } ... { 'Style', 'edit', 'string', fastif(~isnan(opt.phasesort(2)),num2str(opt.phasesort(2)),''), 'tag', 'phase2' } ... { 'Style', 'edit', 'string', fastif(~isnan(opt.phasesort(1)),num2str(opt.phasesort(1)),''), 'tag', 'phase3' } ... { 'Style', 'text', 'string', ' 3' } {}... {} ... { 'Style', 'text', 'string', 'Inter-trial coherence options', 'fontweight', 'bold'} ... { 'Style', 'text', 'string', 'Frequency (Hz | minHz maxHz)', 'tooltipstring', [ '[freq] -> plot erp plus amp & coher at freq (Hz)' 10 ... '[minHz maxHz] -> find max in frequency range' 10 '(or at phase freq above, if specified)']} ... { 'Style', 'text', 'string', 'Signif. level (<0.20)', 'tooltipstring', 'add coher. signif. level line at alpha (alpha range: (0,0.1])' } ... { 'Style', 'text', 'string', 'Amplitude limits (dB)' } ... { 'Style', 'text', 'string', 'Coher limits (<=1)' } ... { 'Style', 'checkbox', 'string', 'Image amps', 'tooltipstring', context('plotamps',vars,txt), 'value', fastif(strcmpi(opt.plotamps, 'on'), 1,0), 'tag', 'plotamps' } ... { 'Style', 'edit', 'string', fastif(~isnan(opt.coher(1)), num2str(opt.coher(1:2)), ''), 'tag', 'coher', 'callback', commandcoher } ... { 'Style', 'edit', 'string', fastif(~isnan(opt.coher(3)), num2str(opt.coher(3)), ''), 'tag', 'coher2' } ... { 'Style', 'edit', 'string', fastif(~isnan(opt.limits(5)), num2str(opt.limits(5:6)), ''), 'tag', 'limamp' } ... { 'Style', 'edit', 'string', fastif(~isnan(opt.limits(7)), num2str(opt.limits(7:8)), ''), 'tag', 'limcoher' } ... {'style', 'text', 'string', ' (Requires signif.)' } ... {} ... { 'Style', 'text', 'string', 'Other options', 'fontweight', 'bold'} ... { 'Style', 'text', 'string', 'Plot spectrum (minHz maxHz)','tooltipstring', context('spec',vars,txt)} ... { 'Style', 'text', 'string', 'Baseline ampl. (dB)', 'tooltipstring', 'Use it to fix baseline amplitude' } ... { 'Style', 'text', 'string', 'Mark times (ms)','tooltipstring', context('vert',vars,txt)} ... { 'Style', 'text', 'string', 'More options (see >> help erpimage)' } ... { 'Style', 'edit', 'string', num2str(opt.spec), 'tag', 'spec' } ... { 'Style', 'edit', 'string', fastif(~isnan(opt.limits(9)), num2str(opt.limits(9)), ''), 'tag', 'limbaseamp' } ... { 'Style', 'edit', 'string', num2str(opt.vert), 'tag', 'vert' } ... { 'Style', 'edit', 'string', '', 'tag', 'others' } ... }; if typeplot == 0 % add extra param for components geometry = { [1 1 0.1 0.8 2.1] geometry{:} }; uilist = { { } { } { } { } { } uilist{:}}; uilist{1} = uilist{6}; uilist{2} = uilist{7}; uilist{6} = { 'Style', 'text', 'string', 'Project to channel #', 'fontweight', 'bold','tooltipstring', ['Project component(s) to data channel' 10 ... 'This allows plotting projected component activity at one channel in microvolts'] }; uilist{7} = { 'Style', 'edit', 'string', getkeyval(lastcom, 4), 'tag', 'projchan' }; end; [oldres a b res] = inputgui( geometry, uilist, 'pophelp(''pop_erpimage'');', ... fastif( typeplot, 'Channel ERP image -- pop_erpimage()', 'Component ERP image -- pop_erpimage()')); if isempty(oldres), return; end; % first rows % --------- channel = eval( [ '[' res.chan ']' ]); titleplot = res.title; if isfield(res, 'projchan'), if ~isempty(res.projchan) if strcmpi(res.projchan(1),'''') projchan = eval( [ '{' res.projchan '}' ]); else projchan = parsetxt( res.projchan); end; if ~isempty(projchan) && ~isempty(str2num(projchan{1})) projchan = cellfun(@str2num, projchan); end; else projchan = []; end; else, projchan = []; end; opt = []; if ~isempty(res.others) try, tmpcell = eval( [ '{' res.others '}' ] ); opt = struct( tmpcell{:} ); catch, error('Additional options ("More options") requires ''key'', ''val'' arguments'); end; end; if ~typeplot && isempty(projchan) opt.yerplabel = ''; else opt.yerplabel = '\muV' ; end; smooth = eval(res.smooth); if res.plotmap if isfield(EEG.chanlocs, 'theta') if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end; if typeplot == 0 opt.topo = [ ' { mean(EEG.icawinv(:,[' int2str(channel) ']),2) EEG.chanlocs EEG.chaninfo } ']; else opt.topo = [ ' { [' int2str(channel) '] EEG.chanlocs EEG.chaninfo } ']; end; end; end; decimate = eval( res.decimate ); if res.erp opt.erp = 'on'; end; % finding limits % -------------- limits(1:8) = NaN; if ~isempty(res.limerp) limits(3:4) = eval( [ '[' res.limerp ']' ]); end; if ~isempty(res.limtime) % time limits if ~strcmp(res.limtime, num2str(1000*[EEG.xmin EEG.xmax])) limits(1:2) = eval( [ '[' res.limtime ']' ]); end; end; if ~isempty(res.limamp) limits(5:6) = eval( [ '[' res.limamp ']' ]); end; if ~isempty(res.limcoher) limits(7:8) = eval( [ '[' res.limcoher ']' ]); end; if ~isempty(res.limbaseamp) limits(9) = eval( res.limbaseamp ); %bamp end; if ~all(isnan(limits)) opt.limits = limits; end; % color limits % -------------- if res.cbar opt.cbar = 'on'; end; if res.caxis opt.caxis = str2num(res.caxis); end; % event rows % ---------- if res.nosort opt.nosort = 'on'; end; try, sortingeventfield = eval( res.field ); catch, sortingeventfield = res.field; end; if ~isempty(res.type) if strcmpi(res.type(1),'''') sortingtype = eval( [ '{' res.type '}' ] ); else sortingtype = parsetxt( res.type ); end; end sortingwin = eval( [ '[' res.eventrange ']' ] ); if ~isempty(res.field) & ~strcmp(res.renorm, 'no') opt.renorm = res.renorm; end; if ~isempty(res.align) opt.align = str2num(res.align); end; if res.noplot opt.noplot = 'on'; end; % phase rows % ---------- tmpphase = []; if ~isempty(res.phase) tmpphase = eval( [ '[ 0 0 ' res.phase ']' ]); end; if ~isempty(res.phase2) tmpphase(2) = eval( res.phase2 ); end; if ~isempty(res.phase3) tmpphase(1) = eval( res.phase3 ); end; if ~isempty(tmpphase) opt.phasesort = tmpphase; end; % coher row % ---------- tmpcoher = []; if res.plotamps opt.plotamps = 'on'; end; if ~isempty(res.coher) tmpcoher = eval( [ '[' res.coher ']' ]); end; if ~isempty(res.coher2) if length(tmpcoher) == 1 tmpcoher(2) = tmpcoher(1); end; tmpcoher(3) = eval( res.coher2 ); end; if ~isempty(tmpcoher) opt.coher = tmpcoher; end; % options row % ------------ if ~isempty(res.spec) opt.spec = eval( [ '[' res.spec ']' ]); end; if ~isempty(res.vert) opt.vert = eval( [ '[' res.vert ']' ]); end; figure; options = ''; else options = ''; if nargin < 4 projchan = []; end; if nargin < 5 titleplot = ' '; end; if nargin < 6 smooth = 5; end; if nargin < 7 decimate = 0; end; if nargin < 8 sortingtype = []; end; if nargin < 9 sortingwin = []; end; if nargin < 10 sortingeventfield = []; end; %options = vararg2str(varargin); % NO BECAUSE OF THE CHANNEL LOCATION % PROBLEM BELOW for i=1:length( varargin ) if isstr( varargin{ i } ) options = [ options ', ''' varargin{i} '''' ]; else if ~iscell( varargin{ i } ) options = [ options ',' vararg2str({varargin{i}}) ]; else %options = [ options ', { [' num2str(varargin{ i }{1}') ']'' EEG.chanlocs EEG.chaninfo }' ]; % JRI -- why does this ignore value passed as topo option? if length(varargin{i})>1 optchanlocs = varargin{i}{2}; % JRI -- fix else optchanlocs = EEG.chanlocs; end; if length(varargin{i})>2, optchaninfo = varargin{i}{3}; else optchaninfo = EEG.chaninfo; end options = [ options ', { [' num2str(varargin{ i }{1}') ']'' optchanlocs optchaninfo }' ]; end; end; end; end; try, icadefs; set(gcf, 'color', BACKCOLOR,'Name',' erpimage()'); catch, end; % testing inputs % -------------- if typeplot == 0 && length(channel) > 1 && isempty(projchan) error('A channel must be selected to plot (the sum of) several component projections'); end; % find sorting latencies % --------------------- typetxt = ''; if ~isempty(sortingeventfield) %events = eeg_getepochevent( EEG, sortingtype, sortingwin, sortingeventfield); events = sprintf('eeg_getepochevent( EEG, %s)', vararg2str({sortingtype, sortingwin, sortingeventfield})); % generate text for the command % ----------------------------- for index = 1:length(sortingtype) if isstr(sortingtype{index}) typetxt = [typetxt ' ''' sortingtype{index} '''' ]; else typetxt = [typetxt ' ' num2str(sortingtype{index}) ]; end; end; % $$$ % renormalize latencies if necessary % $$$ % ---------------------------------- % $$$ switch lower(renorm) % $$$ case 'yes', % $$$ disp('Pop_erpimage warning: *** sorting variable renormalized ***'); % $$$ events = (events-min(events)) / (max(events) - min(events)) * ... % $$$ 0.5 * (EEG.xmax*1000 - EEG.xmin*1000) + EEG.xmin*1000 + 0.4*(EEG.xmax*1000 - EEG.xmin*1000); % $$$ case 'no',; % $$$ otherwise, % $$$ locx = findstr('x', lower(renorm)) % $$$ if length(locx) ~= 1, error('Pop_erpimage error: unrecognize renormalazing formula'); end; % $$$ eval( [ 'events =' renorm(1:locx-1) 'events' renorm(locx+1:end) ';'] ); % $$$ end; else events = 'ones(1, EEG.trials)*EEG.xmax*1000'; %events = ones(1, EEG.trials)*EEG.xmax*1000; sortingeventfield = ''; end; if isstr(projchan) projchan = { projchan }; end; if iscell(projchan) projchannum = std_chaninds(EEG, projchan); else projchannum = projchan; end; if typeplot == 1 tmpsig = ['mean(EEG.data([' int2str(channel) '], :),1)']; else % test if ICA was computed or if one has to compute on line % --------------------------------------------------------- tmpsig = [ 'eeg_getdatact(EEG, ''component'', [' int2str(channel) '], ''projchan'', [' int2str(projchannum) '])' ]; end; % outputs % ------- outstr = ''; if ~popup for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end; if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end; end; % plot title % ---------- if isempty(titleplot) if typeplot==1 % if channel plot if ~isempty(EEG.chanlocs) % if channel information exist titleplot = [ EEG.chanlocs(channel).labels ]; else, titleplot = [ int2str(channel) ]; end else titleplot = [ 'Comp. ' int2str(channel) ]; if ~isempty(projchan), tmpstr = vararg2str({projchan}); tmpstr(find(tmpstr == '''')) = '"'; titleplot = [ titleplot ' -> Chan. ' tmpstr ]; end; end end; % plot the data and generate output command % -------------------------------------------- if isempty( options ) if isfield(opt, 'topo') tmptopo = opt.topo; opt = rmfield(opt, 'topo'); else tmptopo = ''; end; fields = fieldnames(opt); values = struct2cell(opt); params = { fields{:}; values{:} }; options = [ ',' vararg2str( { params{:} } ) ]; tmpind = find( options == '\' ); options(tmpind(1:2:end)) = []; if ~isempty(tmptopo), options = [ options ',''topo'',' tmptopo ]; end; end; % varargout{1} = sprintf('figure; pop_erpimage(%s,%d,%d,''%s'',%d,%d,{%s},[%s],''%s'',''%s''%s);', inputname(1), typeplot, channel, titleplot, smooth, decimate, typetxt, int2str(sortingwin), sortingeventfield, renorm, options); popcom = sprintf('figure; pop_erpimage(%s,%d, [%s],[%s],''%s'',%d,%d,{%s},[%s],''%s'' %s);', inputname(1), typeplot, int2str(channel), vararg2str({projchan}), titleplot, smooth, decimate, typetxt, int2str(sortingwin), sortingeventfield, options); com = sprintf('%s erpimage( %s, %s, linspace(EEG.xmin*1000, EEG.xmax*1000, EEG.pnts), ''%s'', %d, %d %s);', outstr, tmpsig, events, titleplot, smooth, decimate, options); disp('Command executed by pop_erpimage:'); disp(' '); disp(com); disp(' '); eval(com) if popup varargout{1} = popcom; % [10 '% Call: ' com]; end; return; % get contextual help % ------------------- function txt = context(var, allvars, alltext); loc = strmatch( var, allvars); if ~isempty(loc) txt= alltext{loc(1)}; else disp([ 'warning: variable ''' var ''' not found']); txt = ''; end;
github
lcnhappe/happe-master
eeg_epochformat.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_epochformat.m
7,674
utf_8
b6227100d8d67253534322618e4b81fa
% eeg_epochformat() - Convert the epoch information of a dataset from struct % to array or vice versa. % % Usage: >> [epochsout fields] = eeg_epochformat( epochs, 'format', fields, events ); % % Input: % epochs - epoch numerical or cell array or epoch structure % format - ['struct'|'array'] convert epoch array to structure and epoch % structure to array. % fields - [optional] cell array of strings containing the names of % the epoch struct fields. If this field is empty, it uses the % following list for the names of the fields { 'var1' 'var2' ... }. % For structure conversion, this field helps export a given % event type. If this field is left empty, the time locking % event for each epoch is exported. % events - numerical array of event indices associated with each epoch. % For array conversion, this field is ignored. % % Outputs: % epochsout - output epoch array or structure % fields - output cell array with the name of the fields % % Epoch format: % struct - Epoch information is organised as an array of structs % array - Epoch information is organised as an 2-d array of numbers, % each column representing a user-defined variable (the % order of the variable is a function of its order in the % struct format). % % Note: 1) The epoch structure is defined only for epoched data. % 2) The epoch 'struct' format is more comprehensible. % For instance, to see all the properties of epoch i, % type >> EEG.epoch(i) % Unfortunately, structures are awkward for expert users to deal % with from the command line (Ex: To get an array of 'var1' values, % >> celltomat({EEG.epoch(:).var1})') % In array format, asuming 'var1' is the first variable % declared, the same information is obtained by % >> EEG.epoch(:,1) % 3) This function automatically updates the 'epochfields' % cell array depending on the format. % % Author: Arnaud Delorme, CNL / Salk Institute, 12 Feb 2002 % % See also: eeglab() %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) from eeg_eventformat.m, % Arnaud Delorme, CNL / Salk Institute, 12 Feb 2002, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % $Log: eeg_epochformat.m,v $ % Revision 1.4 2005/05/24 16:57:09 arno % cell2mat % % Revision 1.3 2003/07/20 19:32:20 scott % typos % % Revision 1.2 2002/04/21 01:10:35 scott % *** empty log message *** % % Revision 1.1 2002/04/05 17:32:13 jorn % Initial revision % % 03/13/02 added field arrays options -ad function [ epoch, fields, epocheventout] = eeg_epochformat( epoch, format, fields, epochevent); if nargin < 2 help eeg_epochformat; return; end; if nargin < 3 fields = {}; end; epocheventout = []; switch format case 'struct' if ~isempty(epoch) & ~isstruct(epoch) fields = getnewfields( fields, size(epoch,2) - length(fields)); % generate the structure % ---------------------- command = 'epoch = struct('; for index = 1:length(fields) if iscell(epoch) command = [ command '''' fields{index} ''', epoch(:,' num2str(index) ')'',' ]; else command = [ command '''' fields{index} ''', mattocell( epoch(:,' num2str(index) ')'',' ... '[1], ones(1,size(epoch,1))),' ]; end; end; eval( [command(1:end-1) ');' ] ); if exist('epochevent') == 1 for index = 1:size(epoch,2) if iscell(epochevent) epoch(index).event = epochevent{index}; else epoch(index).event = epochevent(index); end; end; end; end case 'array' if isstruct(epoch) % note that the STUDY std_maketrialinfo also gets the epoch info for the % time locking event selectedType = fields; if iscell(fields) && ~isempty(fields), selectedType = fields{1}; end; fields = fieldnames( epoch ); eval( [ 'values = { epoch.' fields{1} ' };' ]); if any(cellfun(@length, values) > 1) if ~isfield(epoch, 'eventlatency') error('eventlatency field not present in data epochs'); end; if isempty(selectedType) % find indices of time locking events for index = 1:length(epoch) epochlat = [ epoch(index).eventlatency{:} ]; tmpevent = find( abs(epochlat) < 0.02 ); if isempty(tmpevent) error('time locking event missing, cannot convert to array'); end; epochSubIndex(index) = tmpevent; end; else % find indices of specific event type (if several take the % first one for index = 1:length(epoch) epochtype = epoch(index).eventtype; tmpeventind = strmatch( selectedType, epochtype ); if length(tmpeventind) > 1 fprintf('Warning: epoch %d has several events of "type" %s, taking the fist one\n', index, selectedType); end; if isempty(tmpeventind) epochSubIndex(index) = NaN; else epochSubIndex(index) = tmpeventind(1); end; end; end; else epochSubIndex = ones(1, length(epoch)); end; % copy values to array tmp = cell( length(epoch), length( fields )); for index = 1:length( fields ) for trial = 1:length(epoch) tmpval = getfield(epoch, {trial}, fields{index}); if isnan(epochSubIndex(trial)) tmp(trial, index) = { NaN }; elseif iscell(tmpval) tmp(trial, index) = tmpval(epochSubIndex(trial)); elseif ~ischar(tmpval) tmp(trial, index) = { tmpval(epochSubIndex(trial)) }; else tmp(trial, index) = { tmpval }; end; end; end; epoch = tmp; end; otherwise, error('unrecognised format'); end; return; % create new field names % ---------------------- function epochfield = getnewfields( epochfield, nbfields ) count = 1; if nbfields > 0 while nbfields > 0 if isempty( strmatch([ 'var' int2str(count) ], epochfield ) ) epochfield = { epochfield{:} [ 'var' int2str(count) ] }; nbfields = nbfields-1; else count = count+1; end; end; else epochfield = epochfield(1:end+nbfields); end; return;
github
lcnhappe/happe-master
eeg_urlatency.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_urlatency.m
2,237
utf_8
7a9b9b21f8b247ddcea52752ae05bc26
% eeg_urlatency() - find the original (ur) latency of a time point in % the original continuous data. % % Usage: % >> lat_out = eeg_urlatency( event, lat_in ); % % Inputs: % event - event structure. If this structure contain boundary % events, the length of these events is added to restore % the original latency from the relative latency in 'lat_in' % lat_in - relative latency in sample point % % Outputs: % lat_out - output latency % % Note: the function that finds the latency in the current dataset using (ur) % original latencies as input is eeg_latencyur() % % Author: Arnaud Delorme, SCCN, INC, UCSD, April, 15, 2004 % % See also: eeg_latencyur() % Copyright (C) 2004 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function latout = eeg_urlatency( events, latin ); if nargin < 2 help eeg_urlatency; return; end; boundevents = { events.type }; latout = latin; if ~isempty(boundevents) & isstr(boundevents{1}) indbound = strmatch('boundary', boundevents); if isfield(events, 'duration') & ~isempty(indbound) for index = indbound' tmpInds = find(events(index).latency < latin); % the find handles several input latencies latout(tmpInds) = latout(tmpInds) + events(index).duration; end; elseif ~isempty(indbound) % boundaries but with no associated duration latout = NaN; end; end;
github
lcnhappe/happe-master
eeg_context.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_context.m
27,634
utf_8
8abec48acc7f051c46340c6cbf7f45f4
% eeg_context() - returns (in output 'delays') a matrix giving, for each event of specified % ("target") type(s), the latency (in ms) to the Nth preceding and/or following % urevents (if any) of specified ("neighbor") type(s). Return the target event % and urevent numbers, the neighbor urevent numbers, and the values of specified % urevent field(s) for each of the neighbor urevents. Uses the EEG.urevent % structure, plus EEG.event().urevent pointers to it. If epoched data, also % uses the EEG.epoch structure. For use in event-handling scripts and functions. % Usage: % >> [targs,urnbrs,urnbrtypes,delays,tfields,urnfields] = ... % eeg_context(EEG,{targets},{neighbors},[positions],{fields},alltargs); % Required input: % EEG - EEGLAB dataset structure containing EEG.event and EEG.urevent sub-structures % % Optional inputs: % targets - string or cell array of strings naming event type(s) of the specified target % events {default | []: all events} % neighbors - string or cell array of strings naming event type(s) of the specified % neighboring urevents {default | []: any neighboring events}. % [positions] - int vector giving the relative positions of 'neighbor' type urevents to return. % Ex: [-3 -2 -1 0 1 2 3] -> return the previous 3, current, and succeeding 3 % urevents of the specified {neighbor} types. [positions] values are arranged % in ascending order before processing. {default | []: 1 = first succeeding} % fields - string or cell array of strings naming one or more (ur)event field(s) to return % values for neighbor urevents. {default: no field info returned} % alltargs - string ('all'|[]) if 'all', return information about all target urevents, % even those on which no epoch in the current dataset is centered. % {default: [] -> only return information on epoch-centered target events} % Outputs: % targs - size(ntargets,4) matrix giving the indices of target events in the event % structure in column 1 and in the urevent structure in column 2. Column 3 gives % the epoch number in which the target has latency 0 (else NaN if no such epoch). % The fourth column gives the index of the target type in the {targets} cell array. % urnbrs - matrix of indices of "neighbor" events in the URevent structure (NaN if none). % urnbrtypes - int array giving the urnbrs event type indices in the {neighbor} cell array, % else NaN if no such neighbor. Ex: If nbr = {'square','rt'} (see below), % then urnbrtypes outputs are [1|2]; if nbr = {'rt'}, returns [1]s. % delays - matrix giving, for each {targets} type event, the latency of the delay (in ms) % from each target event to its neighbor urevents. Else, returns NaN when no % neighbor event. Output matrix size: (ntargets,length(positions)). % tfields - real or cell array of values of the requested (ur)event field(s) for the target % events. Values are the same type as the field values, else NaN if no such event. % urnfields - real or cell array of values of the requested (ur)event field(s) for the neighbor % urevents. Values are the same type as the field values, else NaN if no such event. % If > 1 field specified, a 3-D array or cell array (nevents,nnbrpos,nfields). % Example: % % >> target = 'square'; % target events are type 'square' % >> nbr = {'square','rt'}; % neighbor events are either 'square' or 'rt' % % >> [trgs,urnbrs,urnbrtypes,delays,tflds,urnflds] = ... % eeg_context(EEG,target,nbr,[-4 1],'position'); % % % % Output 'delays' now contains latencies (in ms) from each 'square' target event to the % % 4th preceding and 1st succeeding 'rt' OR 'square' urevent (else NaN when none such). % % Outputs 'tfields' and 'urnflds' give the 'position' field values of target events and % % neighbor urevents. Output 'urnbrtypes', the index of the type (1='square' or 2='rt') % % of the ('urnbrs') neighbor urevents. % % % >> trts = find(trgs(:,4)==2); % targets followed by an 'rt' (before any 'square') % >> pos3 = find(trgfld = 3); % targets with 'position'=3 (numeric field value). % >> selevents = intersect_bc(trts,pos3); % target events by both criteria % >> selepochs = trgs(selevents,3); % epoch numbers centered on the selected target events % % Author: Scott Makeig, SCCN, Institute for Neural Computation, UCSD, March 27, 2004 % Edit History: % 1/10/05 added 4th (type) field to output trgs; added to Example; % 5/25/04 test for isnan(urevent.duration) to detect real break events -sm % 3/27/04 made no-such-event return NaNs; added {target} and {neighbor} defaults -sm % 3/28/04 added test for boundary urevents; renamed relidx as positions, lats as delays -sm % 3/29/04 reorganized output order, adding urnbrtypes -sm % 3/29/04 changed urnbrtypes to int array -sm % 3/31/04 ruled out searching 'boundary' events -sm % 5/06/04 completed the function -sm % function [targs,ur_nbrs,ur_nbrtypes,delays,tfields,nfields] = eeg_context(EEG,targets,neighbors,positions,field,alltargs) verbose = 0; % flag useful info printout (1=on|0=off) debug_print = 0; % flag overly verbose printout breakwarning = 0; % flag no pre-4.4 warning given if nargin < 1 help eeg_context return end if nargin< 6 | isempty(alltargs) alltargs = 0; elseif strcmpi(alltargs,'all') alltargs = 1; else error('alltargs argument must be ''all'' or [].') end if ~isstruct(EEG) error('first argument must be an EEG dataset structure'); end if ~isfield(EEG,'event') error('No EEG.event structure found'); end if ~isfield(EEG,'urevent') error('No EEG.urevent structure found'); end if ~isfield(EEG.event,'urevent') error('No EEG.event().urevent field found'); end if EEG.trials == 1 | ~isfield(EEG.event(1),'epoch') fprintf('Data are continuous: Returning info on all targets; no epoch info returned.\n') alltargs = 1; epochinfo = 0; else epochinfo = 1; end if epochinfo & ~isfield(EEG,'epoch') error('No EEG.epoch information in this epoched dataset - run eeg_checkset()'); end if epochinfo & ~isfield(EEG.epoch,'eventlatency') error('No EEG.epoch.eventlatency information in this epoched dataset'); end if epochinfo & ~isfield(EEG.epoch,'event') error('No EEG.epoch.event information in this epoched dataset'); end nevents = length(EEG.event); nurevents = length(EEG.urevent); if length(EEG.urevent) < nevents fprintf('In this dataset there are more events than urevents. Check consistency.\n'); end % %%%%%%%%%%%%%%%%%% Substitute input defaults %%%%%%%%%%%%%%%%%%%% % if nargin < 5 | isempty(field) NO_FIELD = 1; % flag no field variable output end if nargin < 4 | isempty(positions) positions = 1; % default: find next end if nargin < 3 | isempty(neighbors) neighbors = {'_ALL'}; % flag neighbors are all neighboring events end if nargin < 2 | isempty(targets) targets = {'_ALL'}; % flag targets are all events end % %%%%%%%%%%%%% Test and adjust input arguments %%%%%%%%%%%%%%%%%%%% % if ischar(targets) targets = {targets}; end if ~iscell(targets) error('2nd argument "targets" must be a {cell array} of event types.'); end if ischar(neighbors) neighbors = {neighbors}; end if ~iscell(neighbors) error('3rd argument "neighbors" must be a {cell array} of event types.'); end for k=1:length(targets) % make all target types strings if ~ischar(targets{k}) targets{k} = num2str(targets{k}); end end for k=1:length(neighbors) % make all neighbor types strings if ~ischar(neighbors{k}) neighbors{k} = num2str(neighbors{k}); end end tmp = sort(positions); % reorder positions in ascending order if sum(tmp==positions) ~= length(positions) fprintf('eeg_context(): returning neighbors in ascending order: '); for k=1:length(tmp) fprintf('%d ',tmp(k)); end fprintf('\n'); end positions = tmp; % %%%%%%%%%%%%%% Prepare to find "neighbor" events %%%%%%%%%%%%%%%%%% % zeroidx = find(positions == 0); % find 0's in positions vector negidx = find(positions < 0); negpos = positions(negidx); if ~isempty(negpos) negpos = abs(negpos(end:-1:1)); % work backwards, make negpos positive negidx = negidx(end:-1:1); % index into output ur_nbrs end nnegpos = length(negpos); % number of negative positions to search for posidx = find(positions>0); % work forwards pospos = positions(posidx); npospos = length(pospos); % number of positive positions to search for % %%%%%%%%%%%%%%%%%%%% Initialize output arrays %%%%%%%%%%%%%%%%%%%%%% % npos = length(positions); delays = NaN*zeros(nevents,npos); % holds inter-event intervals in ms % else NaN when no neighboring event targs = NaN*zeros(nevents,1); % holds indices of targets targepochs= NaN*zeros(nevents,1); % holds numbers of the epoch centered % on each target (or NaN if none such) ur_trgs = NaN*zeros(nevents,1); % holds indices of targets ur_nbrs = NaN*zeros(nevents,npos); % holds indices of neighbors ur_nbrtypes = NaN*zeros(nevents,npos); % holds {neighbors} type indices cellfld = -1; % flag no field output specified if ~exist('NO_FIELD','var') % if field values asked for if ischar(field) if ~isfield(EEG.urevent,field) error('Specified field not found in urevent struct'); end if ischar(EEG.urevent(1).(field)) ... | iscell(EEG.urevent(1).(field)) ... | isstruct(EEG.urevent(1).(field)), tfields = cell(nevents,1); nfields = cell(nevents,npos); cellfld = 1; % flag that field outputs are cell arrays else % is number tfields = NaN*zeros(nevents,1); nfields = NaN*zeros(nevents,npos); cellfld = 0; % flag that field outputs are numeric arrays end field = {field}; % make string field a cell array for uniformity nfieldnames = 1; elseif iscell(field) nfieldnames = length(field); for f = 1:nfieldnames if ~isfield(EEG.urevent,field{f}) error('Specified field not found in urevent struct'); end if ischar(EEG.urevent(1).(field{f})) ... | iscell(EEG.urevent(1).(field{f})) ... | isstruct(EEG.urevent(1).(field{f})), if f==1, tfields = cell(nevents,nfieldnames); nfields = cell(nevents,npos,nfieldnames); end cellfld = 1; % flag that field outputs are cell arrays else % is number if f==1 tfields = NaN*zeros(nevents,nfieldnames); nfields = NaN*zeros(nevents,npos,nfieldnames); end end end if cellfld == -1, cellfld = 0; % field value(s) must be numeric end else error('''field'' value must be string or cell array'); end end targetcount = 0; % index of current target % Below: % evidx = current event index % uridx = current urevent index % uidx = neighbor urevent index % tidx = target type index % nidx = neighbor type index % pidx = position index % %%%%%%%%%%%for each event in the dataset %%%%%%%%%%%%%%%%%%%% % wb=waitbar(0,'Computing event contexts...','createcancelbtn','delete(gcf)'); noepochs = 0; % counter of targets that are not epoch-centered targidx = zeros(nevents,1); for evidx = 1:nevents %%%%%% for each event in the dataset %%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% waitbar(evidx/nevents); % update the waitbar fraction if ~strcmp(EEG.event(evidx).type,'boundary') % ignore boundary events (no urevents!) % %%%%%%%%%%%%%%%%%%%%%%%% find target events %%%%%%%%%%%%%%%%% % uridx = EEG.event(evidx).urevent; % find its urevent index if isempty(uridx) fprintf('eeg_context(): Data event %d does not point to an urevent.\n',evidx); delete(wb); return end istarget = 0; % initialize target flag tidx = 1; % initialize target type index % %%%%%%%%%%%%%%% cycle through target types %%%%%%%%%%%%%%%%%% % while ~istarget & tidx<=length(targets) % for each potential target type uridxtype = EEG.urevent(uridx).type; if ~ischar(uridxtype), uridxtype = num2str(uridxtype); end if strcmpi(uridxtype,targets(tidx)) | strcmp(targets{1},'_ALL') % if is a target type istarget=1; % flag event as target targetcount = targetcount+1; % increment target count % %%%%%%%%%%%%% find 0th neighbors (=targets themselves) % if ~isempty(zeroidx) % if the target event is asked for in the nbrs array delays(targetcount,zeroidx) = 0; if ~exist('NO_FIELD','var') for f=1:nfieldnames if cellfld == 0 nfields(targetcount,zeroidx,f) = EEG.urevent(uridx).(field{f}); else % cellfld == 1 nfields{targetcount,zeroidx,f} = EEG.urevent(uridx).(field{f}); end end end end if epochinfo % if the data are epoched is0epoch = 0; for z = 1:length(EEG.event(evidx).epoch) % for each epoch the event is in ep = EEG.event(evidx).epoch(z); for e = 1:length(EEG.epoch(ep).event) % for each event in the epoch if EEG.epoch(ep).event(e) == evidx % if current event % js : added the if ~iscell loop if ~iscell(EEG.epoch(ep).eventlatency) % i.e. not more than 1 eventtype in the epoch if length(EEG.epoch(ep).eventlatency(e)) == 1 trglt = EEG.epoch(ep).eventlatency(e); % get its epoch latency else trglt = EEG.epoch(ep).eventlatency(1); % this shouldn't happen fprintf('EEG.epoch(%d).eventlatency(%d) length > 1 ??\n',ep,e); end else if length(EEG.epoch(ep).eventlatency{e}) == 1 trglt = EEG.epoch(ep).eventlatency{e}; % get its epoch latency else trglt = EEG.epoch(ep).eventlatency{e}(1); % this shouldn't happen fprintf('EEG.epoch(%d).eventlatency{%d} length > 1 ??\n',ep,e); end; end if trglt == 0 targepochs(targetcount) = ep; is0epoch = 1; break; end end end if is0epoch break; end end % for if ~is0epoch, noepochs = noepochs+1; end end targs(targetcount) = evidx; % save event index ur_trgs(targetcount) = uridx; % save urevent index if ~exist('NO_FIELD','var') for f=1:nfieldnames if cellfld ==0 tfields(targetcount,f) = EEG.urevent(uridx).(field{f}); elseif cellfld == 1 tfields{targetcount,f} = EEG.urevent(uridx).(field{f}); end end break % stop target type checking end else % next target type tidx = tidx+1; % else try next target type end % if is target end % while ~istarget if istarget % if current event is a target type targidx(targetcount) = tidx; % save index of its type within targets if ~isempty(negpos) % %%%%%%%%%%%%%%%%%% find previous neighbor urevents %%%%%%%%%%%% % uidx = uridx-1; % begin with the previous urevent npidx = 1; % index into negpos curpos = 1; % current (negative) position seekpos = negpos(npidx); % begin with first negpos position while uidx > 0 & npidx <= nnegpos % search through previous urevents uidxtype = EEG.urevent(uidx).type; if ~ischar(uidxtype), uidxtype = num2str(uidxtype); end if strcmpi(uidxtype,'boundary') % flag boundary urevents if ~isfield(EEG.urevent,'duration') ... | ( isnan(EEG.urevent(uidx).duration) ... | isempty(EEG.urevent(uidx).duration)) % pre-v4.4 or real break urevent % (NaN duration) if ~isfield(EEG.urevent,'duration') ... % pre version-4.4 dataset & breakwarning == 0 fprintf('Pre-v4.4 boundary urevent found - duration field not defined.'); breakwarning = 1; end end break % don't search for neighbors across a boundary urevent end isneighbor = 0; % initialize neighbor flag nidx = 1; % initialize neighbor type index % %%%%%%%%%% cycle through neighbor types %%%%%%%%%%%%% % while ~isneighbor & nidx<=length(neighbors) % for each neighbor event type if strcmpi(uidxtype,neighbors(nidx)) | strcmp(neighbors,'_ALL') isneighbor=1; % flag 'neighbors' event curpos = curpos+1; % %%%%%%%%%%%%%%% if an event in one of the specified positions %%%%% % if curpos-1 == seekpos delays(targetcount,negidx(npidx)) = 1000/EEG.srate * ... (EEG.urevent(uidx).latency - EEG.urevent(uridx).latency); % return negative latencies for negpos events ur_nbrs(targetcount,negidx(npidx))=uidx; % mark urevent as neighbor ur_nbrtypes(targetcount,negidx(npidx)) = nidx; if ~exist('NO_FIELD','var') for f=1:nfieldnames if cellfld ==0 if nfieldnames > 1 if ~isempty(EEG.urevent(uidx).(field{f})) nfields(targetcount,negidx(npidx),f) = EEG.urevent(uidx).(field{f}); else nfields(targetcount,negidx(npidx),f) = NaN; end elseif ~isempty(EEG.urevent(uidx).(field{f})) nfields(targetcount,negidx(npidx)) = EEG.urevent(uidx).(field{f}); else nfields(targetcount,negidx(npidx)) = NaN; end elseif cellfld == 1 if nfieldnames > 1 nfields{targetcount,negidx(npidx),f} = EEG.urevent(uidx).(field{f}); else nfields{targetcount,negidx(npidx)} = EEG.urevent(uidx).(field{f}); end end end end npidx = npidx+1; % look for next negpos position if npidx<=nnegpos seekpos = negpos(npidx); % new seek position end end % if seekpos break % stop neighbors type checking else nidx = nidx+1; % try next 'neighbors' event type end end % nidx - neighbor-type testing loop % %%%%%%%%%%%%%%% find preceding neighbor event %%%%%%%%%%%%%% % uidx = uidx-1; % keep checking for a 'neighbors' type event end % while uidx - urevent type checking end % if negpos if ~isempty(pospos) % %%%%%%%%%%%%%%% find succeeding position urevents %%%%%%%%%%%% % uidx = uridx+1; % begin with the succeeding urevent ppidx = 1; % index into pospos curpos = 1; % current (positive) position seekpos = pospos(ppidx); % begin with first pospos position while uidx <= nurevents & ppidx <= npospos % search through succeeding urevents isneighbor = 0; % initialize neighbor flag uidxtype = EEG.urevent(uidx).type; if ~ischar(uidxtype), uidxtype = num2str(uidxtype); end if strcmpi(uidxtype,'boundary') % flag boundary events if ~isfield(EEG.urevent,'duration') ... | ( isnan(EEG.urevent(uidx).duration) ... | isempty(EEG.urevent(uidx).duration)) % pre-v4.4 or real break urevent % (NaN duration) if ~isfield(EEG.urevent,'duration') ... % pre version-4.4 dataset & breakwarning == 0 fprintf('Pre-v4.4 boundary urevent found - duration field not defined.'); breakwarning = 1; end end break % don't search for neighbors across a boundary urevent end pidx = 1; % initialize neighbor type index % %%%%%%%%%% cycle through neighbor types %%%%%%%%%%%%% % while ~isneighbor & pidx<=length(neighbors) % for each neighbor event type if strcmpi(uidxtype,neighbors(pidx)) ... | strcmp(neighbors,'_ALL') isneighbor=1; % flag 'neighbors' event curpos = curpos+1; % %%%% if an event in one of the specified positions %%%%% % if curpos-1 == seekpos ur_nbrs(targetcount,posidx(ppidx))=uidx; % mark urevent as neighbor % ur_nbrtypes{targetcount,posidx(ppidx)} = EEG.urevent(uidx).type; % note its type ur_nbrtypes(targetcount,posidx(ppidx)) = pidx; % note its type delays(targetcount,posidx(ppidx)) = 1000/EEG.srate * ... (EEG.urevent(uidx).latency - EEG.urevent(uridx).latency); % return positive latencies for pospos events if ~exist('NO_FIELD','var') for f=1:nfieldnames if cellfld ==0 if nfieldnames > 1 if ~isempty(EEG.urevent(uidx).(field{f})) nfields(targetcount,posidx(ppidx),f) = EEG.urevent(uidx).(field{f}); else nfields(targetcount,posidx(ppidx),f) = NaN; end elseif ~isempty(EEG.urevent(uidx).(field{f})) nfields(targetcount,posidx(ppidx)) = EEG.urevent(uidx).(field{f}); else nfields(targetcount,posidx(ppidx)) = NaN; end else % if cellfld == 1 if nfieldnames > 1 nfields{targetcount,posidx(ppidx),f} = EEG.urevent(uidx).(field{f}); else nfields{targetcount,posidx(ppidx)} = EEG.urevent(uidx).(field{f}); end end end end ppidx = ppidx+1; if ppidx<=npospos seekpos = pospos(ppidx); % new seek position end break % stop neighbors type checking end % if seekpos break else % %%%%%%%%%%%% find succeeding neighbor event %%%%%%%%%%%% % pidx = pidx+1; % try next 'neighbors' event-type end end % pidx - neighbor-type testing loop uidx = uidx+1; % keep checking for 'neighbors' type urevents end % uidx - urevent type checking end % if pospos % %%%%%%%%%%%%%%% debug mode info printout %%%%%%%%%%%%%%%%%%%%%% % if debug_print fprintf('%d. ',targetcount) if targetcount<1000, fprintf(' '); end if targetcount<100, fprintf(' '); end if targetcount<10, fprintf(' '); end; if uidx > 1 %fprintf('event %-4d ttype %s - delays: ',evidx,num2str(EEG.urevent(evidx).type)); for k=1:npos fprintf('(%d) ',ur_nbrs(targetcount,k)); if ur_nbrs(targetcount,k)<1000, fprintf(' '); end if ur_nbrs(targetcount,k)<100, fprintf(' '); end if ur_nbrs(targetcount,k)<10, fprintf(' '); end; fprintf('%2.0f ',delays(targetcount,k)); end if ~exist('NO_FIELD','var') if cellfld == 0 % numeric field values fprintf('fields: ') for f=1:nfieldnames fprintf('%-5g - ',tfields(targetcount,f)) for k=1:npos fprintf('%-5g ',nfields(targetcount,k,f)); end end elseif cellfld == 1 % cell array field values fprintf('fields: ') for f=1:nfieldnames if ischar(EEG.urevent(1).(field{f})) fprintf('%-5g -',tfields{targetcount,f}) for k=1:npos fprintf('%-5g ',nfields{targetcount,k,f}); end % k end % ischar end % f end % cellfield end % ~NO_FIELD end % uidx > 1 fprintf('\n'); end % debug_print end % istarget % %%%%%%%%%%%%%%%%% find next target event %%%%%%%%%%%%%%%%%%%%%% % end % if not 'boundary' event evidx = evidx+1; % continue event checking end % event loop % %%%%%%%%% delete watibar %%%%%%%% % if ishandle(wb), delete(wb); end; if ~alltargs fprintf('Returning info on the %d of %d target events that have epochs centered on them.\n',... targetcount-noepochs,targetcount); else fprintf('Returning info on all %d target events (%d have epochs centered on them).\n',... targetcount,targetcount-noepochs); end if debug_print fprintf('---------------------------------------------------\n'); fprintf('ur# event # ttype targtype - delays (urnbr) ms\n'); end % %%%%%%%%%%%%%% Truncate the output arrays %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if targetcount > 0 targs = [targs(1:targetcount) ur_trgs(1:targetcount) ... targepochs(1:targetcount) targidx(1:targetcount)]; % 4-column output ur_nbrs = ur_nbrs(1:targetcount,:); delays = delays(1:targetcount,:); epcenttargs = find(~isnan(targs(:,3))); % find targets that have an epoch centered on them if ~alltargs targs = targs(epcenttargs,:); ur_nbrs = ur_nbrs(epcenttargs,:); delays = delays(epcenttargs,:); end if ~exist('NO_FIELD','var') if cellfld == 0 tfields = tfields(1:targetcount,:); nfields = nfields(1:targetcount,:,:); elseif cellfld == 1 tfields = tfields(1:targetcount,:); nfields = nfields(1:targetcount,:,:); end if ~alltargs tfields = tfields(epcenttargs,:); nfields = nfields(epcenttargs,:,:); end else % NO_FIELD tfields = []; nfields = []; end ur_nbrtypes = ur_nbrtypes(1:targetcount,:); if ~alltargs ur_nbrtypes = ur_nbrtypes(epcenttargs,:); end else % return nulls if no targets found if verbose fprintf('eeg_context(): No target type events found.\n') end delays = []; targs = []; ur_nbrs = []; tfields = []; nfields = []; end
github
lcnhappe/happe-master
pop_biosig16.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_biosig16.m
10,480
utf_8
0740b905165b210b6e1c587304d14801
% pop_biosig() - import data files into EEGLAB using BIOSIG toolbox % % Usage: % >> OUTEEG = pop_biosig; % pop up window % >> OUTEEG = pop_biosig( filename, channels, type); % % Inputs: % filename - [string] file name % % Optional inputs: % 'channels' - [integer array] list of channel indices % 'blockrange' - [min max] integer range of data blocks to import, in seconds. % Entering [0 3] will import the first three blocks of data. % Default is empty -> import all data blocks. % 'ref' - [integer] channel index or index(s) for the reference. % Reference channels are not removed from the data, % allowing easy re-referencing. If more than one % channel, data are referenced to the average of the % indexed channels. WARNING! Biosemi Active II data % are recorded reference-free, but LOSE 40 dB of SNR % if no reference is used!. If you do not know which % channel to use, pick one and then re-reference after % the channel locations are read in. {default: none} % 'rmeventchan' - ['on'|'off'] remove event channel after event % extraction. Default is 'on'. % % Outputs: % OUTEEG - EEGLAB data structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, Oct. 29, 2003- % % Note: BIOSIG toolbox must be installed. Download BIOSIG at % http://biosig.sourceforge.net % Contact [email protected] for troubleshooting using BIOSIG. % Copyright (C) 2003 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, command] = my_pop_biosig(filename, varargin); EEG = []; command = ''; if nargin < 1 % ask user [filename, filepath] = uigetfile('*.*', 'Choose an BDF file -- pop_biosig()'); %%% this is incorrect in original version!!!!!!!!!!!!!! drawnow; if filename == 0 return; end; filename = [filepath filename]; % open file to get infos % ---------------------- disp('Reading data file header...'); dat = sopen(filename); % special BIOSEMI % --------------- if strcmpi(dat.TYPE, 'BDF') disp('We highly recommend that you choose a reference channel IF these are Biosemi data'); disp('(e.g., a mastoid or other channel). Otherwise the data will lose 40 dB of SNR!'); end; uilist = { { 'style' 'text' 'String' 'Channel list (defaut all):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'String' [ 'Data range (in seconds) to read (default all [0 ' int2str(dat.NRec) '])' ] } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'String' 'Extract event - cannot be unset (set=yes)' } ... { 'style' 'checkbox' 'string' '' 'value' 1 'enable' 'on' } {} ... { 'style' 'text' 'String' 'Import continuous data (set=yes)' 'value' 1} ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'String' 'Reference chan(s) indices - required for BIOSEMI' } ... { 'style' 'edit' 'string' '' } }; geom = { [3 1] [3 1] [3 0.35 0.5] [3 0.35 0.5] [3 1] }; result = inputgui( geom, uilist, 'pophelp(''pop_biosig'')', ... 'Load data using BIOSIG -- pop_biosig()'); if length(result) == 0 return; end; % decode GUI params % ----------------- options = {}; if ~isempty(result{1}), options = { options{:} 'channels' eval( [ '[' result{1} ']' ] ) }; end; if ~isempty(result{2}), options = { options{:} 'blockrange' eval( [ '[' result{2} ']' ] ) }; end; if length(result) > 2 if ~isempty(result{4}), options = { options{:} 'ref' eval( [ '[' result{4} ']' ] ) }; end; if ~result{3}, options = { options{:} 'rmeventchan' 'off' }; end; end; else options = varargin; end; % decode imput parameters % ----------------------- g = finputcheck( options, { 'blockrange' 'integer' [0 Inf] []; 'channels' 'integer' [0 Inf] []; 'ref' 'integer' [0 Inf] []; 'rmeventchan' 'string' { 'on';'off' } 'on' }, 'pop_biosig'); if isstr(g), error(g); end; % import data % ----------- EEG = eeg_emptyset; if ~isempty(g.channels) dat = sopen(filename, 'r', g.channels,'OVERFLOWDETECTION:OFF'); else dat = sopen(filename, 'r', 0,'OVERFLOWDETECTION:OFF'); end fprintf('Reading data in %s format...\n', dat.TYPE); if ~isempty(g.blockrange) newblockrange = g.blockrange; newblockrange(2) = min(newblockrange(2), dat.NRec); newblockrange = newblockrange*dat.Dur; DAT=sread(dat, newblockrange(2)-newblockrange(1), newblockrange(1))'; else DAT=sread(dat, Inf)';% this isn't transposed in original!!!!!!!! newblockrange = []; end dat = sclose(dat); % convert to seconds for sread % ---------------------------- EEG.nbchan = size(DAT,1); EEG.srate = dat.SampleRate(1); EEG.data = DAT; clear DAT; % $$$ try % why would you do the following??????? JO % $$$ EEG.data = EEG.data'; % $$$ catch, % $$$ pack; % $$$ EEG.data = EEG.data'; % $$$ end; EEG.setname = sprintf('%s file', dat.TYPE); EEG.comments = [ 'Original file: ' filename ]; EEG.xmin = 0; if strcmpi(dat.TYPE, 'BDF') || strcmpi(dat.TYPE, 'EDF') EEG.trials = 1; EEG.pnts = size(EEG.data,2); else EEG.trials = dat.NRec; EEG.pnts = size(EEG.data,2)/dat.NRec; end if isfield(dat, 'Label') & ~isempty(dat.Label) EEG.chanlocs = struct('labels', cellstr(char(dat.Label))); end EEG = eeg_checkset(EEG); % extract events % this part I totally revamped to work... JO % -------------- disp('Extracting events from last EEG channel...'); EEG.event = []; % $$$ startval = mode(EEG.data(end,:)); % my code % $$$ for p = 2:size(EEG.data,2)-1 % $$$ [codeout] = code(EEG.data(end,p)); % $$$ if EEG.data(end,p) > EEG.data(end,p-1) & EEG.data(end,p) >= EEG.data(end,p+1) % $$$ EEG.event(end+1).latency = p; % $$$ EEG.event(end).type = bitand(double(EEG.data(end,p)-startval),255); % $$$ end; % $$$ end; % lastout = mod(EEG.data(end,1),256);newevs = []; % andrey's code 8 bits % codeout = mod(EEG.data(end,2),256); % for p = 2:size(EEG.data,2)-1 % nextcode = mod(EEG.data(end,p+1),256); % if codeout > lastout & codeout >= nextcode % newevs = [newevs codeout]; % EEG.event(end+1).latency = p; % EEG.event(end).type = codeout; % end; % lastout = codeout; % codeout = nextcode; % end; %lastout = mod(EEG.data(end,1),256*256);newevs = []; % andrey's code 16 bits %codeout = mod(EEG.data(end,2),256*256); %for p = 2:size(EEG.data,2)-1 % nextcode = mod(EEG.data(end,p+1),256*256); % if (codeout > lastout) & (codeout >= nextcode) % newevs = [newevs codeout]; % EEG.event(end+1).latency = p; % EEG.event(end).type = codeout; % end; % lastout = codeout; % codeout = nextcode; %end; % Modifieded by Andrey (Aug.5,2008) to detect all non-zero codes: thiscode = 0; for p = 1:size(EEG.data,2)-1 prevcode = thiscode; thiscode = mod(EEG.data(end,p),256*256); % andrey's code - 16 bits if (thiscode ~= 0) && (thiscode~=prevcode) EEG.event(end+1).latency = p; EEG.event(end).type = thiscode; end; end; if strcmpi(g.rmeventchan, 'on') EEG.data(dat.BDF.Status.Channel,:) = []; EEG.nbchan = size(EEG.data,1); if ~isempty(EEG.chanlocs) EEG.chanlocs(dat.BDF.Status.Channel,:) = []; end; end; EEG = eeg_checkset(EEG, 'eventconsistency'); % $$$ if ~isempty(dat.EVENT) % $$$ if isfield(dat, 'out') % Alois fix for event interval does not work % $$$ if isfield(dat.out, 'EVENT') % $$$ dat.EVENT = dat.out.EVENT; % $$$ end; % $$$ end; % $$$ if ~isempty(newblockrange) % $$$ interval(1) = newblockrange(1) * dat.SampleRate(1) + 1; % $$$ interval(2) = newblockrange(2) * dat.SampleRate(1); % $$$ else interval = []; % $$$ end % $$$ EEG.event = biosig2eeglabevent(dat.EVENT, interval); % Toby's fix % $$$ if strcmpi(g.rmeventchan, 'on') & strcmpi(dat.TYPE, 'BDF') & isfield(dat, 'BDF') % $$$ disp('Removing event channel...'); % $$$ EEG.data(dat.BDF.Status.Channel,:) = []; % $$$ EEG.nbchan = size(EEG.data,1); % $$$ if ~isempty(EEG.chanlocs) % $$$ EEG.chanlocs(dat.BDF.Status.Channel,:) = []; % $$$ end; % $$$ end; % $$$ EEG = eeg_checkset(EEG, 'eventconsistency'); % $$$ else % $$$ disp('Warning: no event found. Events might be embeded in a data channel.'); % $$$ disp(' To extract events, use menu File > Import Event Info > From data channel'); % $$$ end; % rerefencing % ----------- if ~isempty(g.ref) disp('Re-referencing...'); EEG.data = EEG.data - repmat(mean(EEG.data(g.ref,:),1), [size(EEG.data,1) 1]); if length(g.ref) == size(EEG.data,1) EEG.ref = 'averef'; end; if length(g.ref) == 1 disp([ 'Warning: channel ' int2str(g.ref) ' is now zeroed (but still present in the data)' ]); else disp([ 'Warning: data matrix rank has decreased through re-referencing' ]); end; end; % convert data to single if necessary % ----------------------------------- EEG = eeg_checkset(EEG,'makeur'); % Make EEG.urevent field EEG = eeg_checkset(EEG); % history % ------- if isempty(options) command = sprintf('EEG = my_pop_biosig(''%s'');', filename); else command = sprintf('EEG = my_pop_biosig(''%s'', %s);', filename, vararg2str(options)); end;
github
lcnhappe/happe-master
pop_chanevent.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_chanevent.m
14,346
utf_8
6dd2b5a53ddab6deffe78bae70f589b9
% pop_chanevent() - import event latencies from the rising and/or falling 'edge' % latencies of a specified event-marker channel in EEG.data % Usage: % >> OUTEEG = pop_chanevent( INEEG ); % select parameters via a pop-up window % >> OUTEEG = pop_chanevent( INEEG, chanindices, 'key', 'val' ... ); % no pop-up % % Graphic interface: % "Event channel(s)" - [edit box] indices of event channel(s) to import. % Command line equivalent: chanindices. % "Preprocessing transform" - [edit box] apply this preprocessing % formula or function to the selected data channel(s) X, % transforming X into the command output before edge % extraction. Command line equivalent 'oper'. % "Transition to extract" - [list box] extract events when the event % channel values go up ('leading'), down ('trailing') % or both ('both'). Command line equivalent: 'edge'. % "Transition length" - [edit box] Increase this number to avoid having % events very close to each other due to a not perfectly % straight edge. Command line equivalent: 'edgelen'. % "Assign duration to events?" - [checkbox] . Assign duration to each % extracted event. This option can only be used when % extracting events on leading edges. Event will last % until next trailing edge (down) event. Command line % equivalent: 'duration'. % "Delete event channel(s)" - [checkbox] check to delete the event channel % after events have been extracted from it. % Command line equivalent: 'delchan'. % "Delete old events if any" - [checkbox] check this checkbox to % remove any prior events in the dataset. Otherwise % imported events are appended to old events. Command % line equivalent: 'delevent'. % "Only one event type" - [checkbox] check this checkbox to assign % all transitions in the event channel to one event % type. Else, one type is assigned for each non-zero % channel value. Command line equivalent: 'nbtype'. % Inputs: % INEEG - input dataset structure % chanindices - index|(indices) of the event channel(s) % % Optional inputs: % 'edge' - ['leading'|'trailing'|'both'] extract events when values % in the event channel go up ('leading'), down ('trailing') % or both ('both'). {Default is 'both'}. % 'edgelen' - [integer] maximum edge length (for some data edge do not % take whole value and it takes a few sample points for % signal to rise. Default is 1 (perfect edges). % 'oper' - [string] prior to extracting edges, preprocess data % channel(s) using the string command argument. % In this command, the data channel(s) are designated by % (capital) X. For example, 'X>3' will test the value of X % at each time point (returning 1 if the data channel value % is larger than 3, and 0 otherwise). You may also use % any function (Ex: 'myfunction(X)'). % 'duration' - ['on'|'off'] extract event duration. This option can only be % used when extracting events on leading edges. Event will last % until next trailing-edge (down) event { 'off' }. % 'delchan' - ['on'|'off'] delete channel from data { 'on' }. % 'delevent' - ['on'|'off'] delete old events if any { 'on' }. % 'nbtype' - [1|NaN] setting this to 1 will force the program to % consider all events to have the same type. {Default is NaN}. % If set (1), all transitions are considered the same event type % If unset (NaN), each (transformed) event channel value following a % transition determines an event type (Ex: Detecting leading-edge % transitions of 0 0 1 0 2 0 ... produces event types 1 and 2). % 'typename' - [string] event type name. Only relevant if 'nbtype' is 1 % or if there is only one event type in the event channel. % {Default is 'chanX', X being the index of % the selected event channel}. % Outputs: % OUTEEG - EEGLAB output data structure % % Author: Arnaud Delorme, CNL / Salk Institute, 29 July 2002 % % See also: eeglab() % Copyright (C) 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, command] = pop_chanevent(EEG, chan, varargin); command = ''; if nargin < 1 help pop_chanevent; return; end; if nargin < 2 geometry = { [1.5 1 1] [1] [1.5 1 1] [1.5 1 1] [1.5 1 1] [1.5 0.2 0.36 0.84] ... [1] [1.5 0.21 1] [1.5 0.21 1] [1.5 0.21 1] }; % callback from listbox to disable duration checkbox (if leading event is not selected) % -------------------------------------------------- cb_list = [ 'if get(gcbo, ''value'') == 1,' ... ' set(findobj(gcbf, ''tag'', ''dur''), ''enable'', ''on'');' ... 'else,' ... ' set(findobj(gcbf, ''tag'', ''dur''), ''enable'', ''off'', ''value'', 0);' ... 'end;' ]; strgui = { { 'style' 'text' 'string' 'Event channel(s)' 'tooltipstring' 'indexes of event channels' } ... { 'style' 'edit' 'string' '' } { } ... {} ... { 'style' 'text' 'string' 'Preprocessing transform (data=''X'')' 'tooltipstring' ... [ 'For example, ''X>3'' will test the value of X' 10 ... 'at each time point (returning 1 if the data channel value' 10 ... 'is larger than 3, and 0 otherwise).' ] } ... { 'style' 'edit' 'string' '' } { 'style' 'text' 'string' 'Optional. Ex: X>3' } ... { 'style' 'text' 'string' 'Transitions to extract? (up|down)' 'tooltipstring' ... [ 'Extract events whenever values in the (transformed) event channel(s) shift up' 10 ... '(''leading''), down (''trailing'') or either (''both'').' 10 ... 'AFTER SCROLLING CLICK TO SELECT' ] } ... { 'style' 'listbox' 'string' 'up (leading)|both|down (trailing)' 'value' 1 'callback' cb_list } ... { 'style' 'text' 'string' '(click to select)'} ... { 'style' 'text' 'string' 'Transition length (1=perfect edges)' 'tooltipstring' ... [ 'Increase this number to avoid having events very close to each other due.' 10 ... 'to a not perfectly straight edge' ] } ... { 'style' 'edit' 'string' '0' } { } ... { 'style' 'text' 'string' 'Assign duration to each events?' 'tag' 'dur' 'tooltipstring' ... [ 'You may assign an event duration to each event if you select to detect' 10 ... 'event on the leading edge above. Event will last as long as the signal is non-0.' ] } ... { 'style' 'checkbox' 'string' '' 'value' 0 'tag' 'dur'} { } ... { 'style' 'text' 'string' '(set=yes)' } ... {} ... { 'style' 'text' 'string' 'Delete event channel(s)? ' } ... { 'style' 'checkbox' 'value' 1 } { 'style' 'text' 'string' ' (set = yes)'} ... { 'style' 'text' 'string' 'Delete old events if any? ' } ... { 'style' 'checkbox' 'value' 1 } { } ... { 'style' 'text' 'string' 'All events of same type? ' 'tooltipstring' ... ['If set, all transitions are considered the same event type,' 10 ... 'If unset, each (transformed) event channel value following a transition' 10 ... 'determines an event type (Ex: Detecting leading-edge transitions of' 10 ... '0 0 1 0 2 0 ... produces event types 1 and 2).' ] } ... { 'style' 'checkbox' 'value' 0 } { } }; result = inputgui( geometry, strgui, 'pophelp(''pop_chanevent'');', 'Extract event from channel(s) - pop_chanevent()'); if length(result) == 0 return; end; chan = eval( [ '[' result{1} ']' ] ); options = {}; if ~isempty(result{2}), options = { options{:} 'oper' result{2} }; end; switch result{3}, case 1, options = { options{:} 'edge' 'leading' }; case 2, options = { options{:} 'edge' 'both' }; case 3, options = { options{:} 'edge' 'trailing' }; end; options = { options{:} 'edgelen' eval( [ '[' result{4} ']' ] ) }; if result{5}, options = { options{:} 'duration' 'on' }; end; if ~result{6}, options = { options{:} 'delchan' 'off'}; end; if ~result{7}, options = { options{:} 'delevent' 'off'}; end; if result{8}, options = { options{:} 'nbtype' 1}; end; else options = varargin; end; listcheck = { 'edge' 'string' { 'both';'leading';'trailing'} 'both'; 'edgelen' 'integer' [1 Inf] 1; 'delchan' 'string' { 'on';'off' } 'on'; 'oper' 'string' [] ''; 'delevent' 'string' { 'on';'off' } 'on'; 'duration' 'string' { 'on';'off' } 'off'; 'typename' 'string' [] [ 'chan' int2str(chan) ]; 'nbtype' 'integer' [1 NaN] NaN }; g = finputcheck( options, listcheck, 'pop_chanedit'); if isstr(g), error(g); end; % check inut consistency % ---------------------- if strcmpi(g.duration, 'on') & ~strcmpi(g.edge, 'leading') error('Must detect leading edge to extract event duration'); end; % process events % -------------- fprintf('pop_chanevent: importing events from data channel %d ...\n', chan); counte = 1; % event counter events(10000).latency = 0; if isnan(g.nbtype) if length(unique(EEG.data(chan, :))) == 2, g.nbtype = 1; end; end; for ci = chan X = EEG.data(ci, :); % apply preprocessing % ------------------- if ~isempty(g.oper) try, eval( [ 'X = ' g.oper ';' ]); catch, error('pop_chanevent: error executing preprocessing string'); end; end; % extract edges % ------------- tmpdiff = diff(abs([ X X(end) ])); switch g.edge case 'both' , tmpevent1 = find( tmpdiff > 0)-1; tmpevent2 = find( tmpdiff < 0); case 'trailing', tmpevent2 = find( tmpdiff < 0); case 'leading' , tmpevent1 = find( tmpdiff > 0)-1; tmpdur = find( tmpdiff < 0); end; % fuse close events if necessary % ------------------------------ if exist('tmpevent1') tmpclose = find( tmpevent1(2:end)-tmpevent1(1:end-1) < g.edgelen)+1; tmpevent1(tmpclose) = []; tmpevent = tmpevent1+1; tmpeventval = tmpevent1+2; end; if exist('tmpevent2') tmpclose = find( tmpevent2(2:end)-tmpevent2(1:end-1) < g.edgelen); % not +1 tmpevent2(tmpclose) = []; tmpevent = tmpevent2+1; tmpeventval = tmpevent2; end; if exist('tmpevent1') & exist('tmpevent2') tmpevent = sort([ tmpevent1+1 tmpevent2+1]); tmpeventval = sort([ tmpevent1+2 tmpevent2]); end; % adjust edges for duration if necessary % --------------------------------------- if strcmpi(g.duration, 'on') tmpclose = find( tmpdur(2:end)-tmpdur(1:end-1) < g.edgelen); % not +1 (take out the first) tmpdur(tmpclose) = []; if tmpdur(1) < tmpevent(1), tmpdur(1) = []; end; if length(tmpevent) > length(tmpdur), tmpdur(end+1) = EEG.pnts; end; if length(tmpevent) ~= length(tmpdur) error([ 'Error while attempting to extract event durations' 10 ... 'Maybe edges are not perfectly defined, try increasing edge length' ]); end; end; if isempty(tmpevent), fprintf('No event found for channel %d\n', ci); else for tmpi = 1:length(tmpevent) if ~isnan(g.nbtype) events(counte).type = g.typename; else events(counte).type = X(tmpeventval(tmpi)); end; events(counte).latency = tmpevent(tmpi); if strcmpi(g.duration, 'on') events(counte).duration = tmpdur(tmpi) - tmpevent(tmpi); end; counte = counte+1; end; end; events = events(1:counte-1); end; % resort events % -------------- if strcmp(g.delevent, 'on') EEG.event = events; if EEG.trials > 1 for index = 1:length(events) EEG.event(index).epoch = 1+floor((EEG.event(index).latency-1) / EEG.pnts); end; end; else for index = 1:length(events) EEG.event(end+1).type = events(index).type; EEG.event(end).latency = events(index).latency; if EEG.trials > 1 | isfield(EEG.event, 'epoch'); EEG.event(end).epoch = 1+floor((EEG.event(end).latency-1) / EEG.pnts); end; end; if EEG.trials > 1 EEG = pop_editeventvals( EEG, 'sort', { 'epoch' 0 'latency', [0] } ); else EEG = pop_editeventvals( EEG, 'sort', { 'latency', [0] } ); end; end; if isfield(EEG.event, 'urevent'), EEG.event = rmfield(EEG.event, 'urevent'); end; EEG = eeg_checkset(EEG, 'eventconsistency'); EEG = eeg_checkset(EEG, 'makeur'); % delete channels % --------------- if strcmp(g.delchan, 'on') EEG = pop_select(EEG, 'nochannel', chan); end; if nargin < 2 command = sprintf('%s = pop_chanevent(%s, %s);', inputname(1), inputname(1), ... vararg2str({ chan options{:} })); end; return;
github
lcnhappe/happe-master
pop_rejspec.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_rejspec.m
14,657
utf_8
bb4bfd5ea24f96a7f9ac51a55585a1df
% pop_rejspec() - rejection of artifact in a dataset using % thresholding of frequencies in the data. % Usage: % >> pop_rejspec(INEEG, typerej); % pop-up interactive window mode % >> [OUTEEG, Indices] = pop_rejspec( INEEG, typerej, 'key', val, ...); % % Pop-up window options: % "Electrode|Component" - [edit box] electrode or component indices to % take into consideration for rejection. Sets the 'elecrange' % parameter in the command line call (see below). % "Spectrum computation method" -[popupmenu] with values {'fft','multitaper'} % Select method to compute spectrum. % "Minimum power rejection threshold(s) (dB)" - [edit box] minimum rejection % threshold(s) in (in dB). Sets the command line parameter % 'threshold'. If more than one, apply to each electrode| % component individually. If fewer than number of % electrodes|components, apply the last value to all remaining % electrodes|components. % "Maximun power rejection threshold(s) (dB)" - Maximum rejection threshold(s) % Sets the command line parameter 'threshold'. % "Low frequency limit(s)" - [edit box] Low-frequency limit(s) in Hz of % range to perform rejection. Sets the command line parameter % 'freqlimits'. % "High frequency limit(s)" - [edit box] High-frequency limit(s) in Hz of % range to perform rejection. Sets the command line parameter % 'freqlimits'. % "Display previous rejection marks: " - [Checkbox]. Sets the command line % input option 'eegplotplotallrej'. % "Reject marked trials: " - [Checkbox] Sets the command line % input option 'eegplotreject'. % % Command line inputs: % INEEG - input dataset % typerej - [1|0] data to reject on (0 = component activations; 1 = % electrode data). {Default is 1}. % % Optional arguments. % 'elecrange' - [e1 e2 ...] array of indices of electrode|component % number(s) to take into consideration during rejection. % 'threshold' - [lower upper] threshold limit(s) in dB. % 'freqlimits' - [lower upper] frequency limit(s) in Hz. % 'method' - ['fft'|'multitaper'] method to compute spectrum. % 'specdata' - [array] precomputed spectral data. % 'eegplotcom' - [string] EEGPLOT command to execute when pressing the % reject button (see 'command' input of EEGPLOT). % 'eegplotreject' - [0|1] 0 = Do not reject marked trials (but store the % marks. 1 = Reject marked trials. {Default: 1}. % 'eegplotplotallrej' - [0|1] 0 = Do not superpose rejection marks on previous % marks stored in the dataset. 1 = Show both previous and % current marks using different colors. {Default: 0}. % % Outputs: % OUTEEG - output dataset with updated spectrograms % Indices - index of rejected trials % Note: When eegplot() is called, modifications are applied to the current % dataset at the end of the call to eegplot() (e.g., when the user presses % the 'Reject' button). % % Author: Arnaud Delorme, CNL / Salk Institute, 2001- % % See also: eegthresh(), eeglab(), eegplot(), pop_rejepoch() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-07-02 added srate argument to eegplot call -ad % 03-08-02 reworked spectrum to save space & add eeglab options -ad function [EEG, Irej, com] = pop_rejspec( EEG, icacomp, varargin); %elecrange, negthresh, posthresh, ... %startfreq, endfreq, superpose, reject); Irej = []; com = ''; if nargin < 1 help pop_rejspec; return; end; if nargin < 2 icacomp = 1; end; if icacomp == 0 if isempty( EEG.icasphere ) ButtonName=questdlg( 'Do you want to run ICA now ?', ... 'Confirmation', 'NO', 'YES', 'YES'); switch ButtonName, case 'NO', disp('Operation cancelled'); return; case 'YES', [ EEG com ] = pop_runica(EEG); end % switch end; end; if nargin < 3 % which set to save % ----------------- promptstr = { fastif(icacomp==0, 'Component indices (Ex: 2 4 6:8 10)', ... 'Electrode indices (Ex: 2 4 6:8 10)'), ... 'Spectrum computation method',... 'Minimum power rejection threshold(s) (dB)',... %'Low power rejection threshold (s) (dB)', ... 'Maximum power rejection threshold(s) (dB)',... %'High power rejection threshold (s) (dB)', ... 'Low frequency limit(s) (Hz)', ... 'High frequency limit(s) (Hz)', ... 'Display previous rejection marks', ... 'Reject marked trial(s)' }; inistr = { ['1:' int2str(EEG.nbchan)], ... '',... '-30', ... '30', ... '15', ... '30', ... '0', ... '0' }; methodlist = {'FFT', 'Multitaper'}; g = [1 0.1 0.75]; g2 = [1 0.26 0.9]; g3 = [1 0.22 0.85]; geometry = {g g2 g g g g 1 g3 g3}; uilist = {... { 'Style', 'text', 'string', promptstr{1}} {} { 'Style','edit' ,'string' ,inistr{1} 'tag' 'cpnum'}... { 'Style', 'text', 'string', promptstr{2}} {} { 'Style','popupmenu' ,'string' ,methodlist 'tag' 'specmethod' }... { 'Style', 'text', 'string', promptstr{3}} {} { 'Style','edit' ,'string' ,inistr{3} 'tag' 'lowlim'}... { 'Style', 'text', 'string', promptstr{4}} {} { 'Style','edit' ,'string' ,inistr{4} 'tag' 'higlim'}... { 'Style', 'text', 'string', promptstr{5}} {} { 'Style','edit' ,'string' ,inistr{5} 'tag' 'lowfreq'}... { 'Style', 'text', 'string', promptstr{6}} {} { 'Style','edit' ,'string' ,inistr{6} 'tag' 'higfreq'}... {}... { 'Style', 'text', 'string', promptstr{7}} {} { 'Style','checkbox' ,'string' ,' ' 'value' str2double(inistr{7}) 'tag','rejmarks' }... { 'Style', 'text', 'string', promptstr{8}} {} { 'Style','checkbox' ,'string' ,' ' 'value' str2double(inistr{8}) 'tag' 'rejtrials'} ... }; result = inputgui( geometry,uilist,'pophelp(''pop_rejspec'');', 'Reject by data spectra -- pop_rejspec()'); size_result = size( result ); if size_result(1) == 0 return; end; options = {}; options = { options{:} 'elecrange' eval( [ '[' result{1} ']' ] ) }; options = { options{:} 'method' lower(methodlist{result{2}})}; thresholdsLow = eval( [ '[' result{3} ']' ] ); thresholdsHigh = eval( [ '[' result{4} ']' ] ); options = { options{:} 'threshold' [thresholdsLow(:) thresholdsHigh(:) ] }; freqLimitsLow = eval( [ '[' result{5} ']' ] ); freqLimitsHigh = eval( [ '[' result{6} ']' ] ); options = { options{:} 'freqlimits' [freqLimitsLow(:) freqLimitsHigh(:) ] }; if result{7}, superpose=1; else superpose=0; end; if result{8}, reject=1; else reject=0; end; options = { options{:} 'eegplotplotallrej' superpose }; options = { options{:} 'eegplotreject' reject }; else if isnumeric(varargin{3}) || ~isempty(str2num(varargin{3})) options = {}; if isstr(varargin{1}), varargin{1} = str2num(varargin{1}); end; if isstr(varargin{2}), varargin{2} = str2num(varargin{2}); end; if isstr(varargin{3}), varargin{3} = str2num(varargin{3}); end; if isstr(varargin{4}), varargin{4} = str2num(varargin{4}); end; if isstr(varargin{5}), varargin{5} = str2num(varargin{5}); end; if nargin > 2, options = { options{:} 'elecrange' varargin{1} }; end; if nargin > 3, options = { options{:} 'threshold' [ varargin{2}; varargin{3}]' }; end; if nargin > 5, options = { options{:} 'freqlimits' [ varargin{4}; varargin{5}]' }; end; if nargin > 7, options = { options{:} 'eegplotplotallrej' varargin{6} }; end; if nargin > 8, options = { options{:} 'eegplotreject' varargin{7} }; end; if nargin > 9, options = { options{:} 'eegplotcom' varargin{8} }; end; else options = varargin; end; end; opt = finputcheck( options, { 'elecrange' 'integer' [] [1:EEG.nbchan]; 'threshold' 'real' [] [-30 30]; 'freqlimits' 'real' [] [15 30]; 'specdata' 'real' [] EEG.specdata; 'eegplotcom' 'string' [] ''; 'method' 'string' { 'fft';'multitaper' } 'multitaper'; 'eegplotreject' 'integer' [] 0; 'eegplotplotallrej' 'integer' [] 0 }, 'pop_rejspec'); if isstr(opt), error(opt); end; sizewin = 2^nextpow2(EEG.pnts); if icacomp == 1 [allspec, Irej, tmprejE, freqs ] = spectrumthresh( EEG.data, opt.specdata, ... opt.elecrange, EEG.srate, opt.threshold(:,1)', opt.threshold(:,2)', opt.freqlimits(:,1)', opt.freqlimits(:,2)', opt.method); rejE = zeros(EEG.nbchan, EEG.trials); rejE(opt.elecrange,Irej) = tmprejE; else % test if ICA was computed % ------------------------ icaacttmp = eeg_getdatact(EEG, 'component', [1:size(EEG.icaweights,1)]); [allspec, Irej, tmprejE, freqs ] = spectrumthresh( icaacttmp, EEG.specicaact, ... opt.elecrange, EEG.srate, opt.threshold(:,1)', opt.threshold(:,2)', opt.freqlimits(:,1)', opt.freqlimits(:,2)', opt.method); rejE = zeros(size(EEG.icaweights,1), size(icaacttmp,1)); rejE(opt.elecrange,Irej) = tmprejE; end; fprintf('%d channel selected\n', size(opt.elecrange(:), 1)); fprintf('%d/%d trials marked for rejection\n', length(Irej), EEG.trials); rej = zeros( 1, EEG.trials); rej(Irej) = 1; if nargin < 3 || opt.eegplotplotallrej == 2 nbpnts = size(allspec,2); if icacomp == 1 macrorej = 'EEG.reject.rejfreq'; macrorejE = 'EEG.reject.rejfreqE'; else macrorej = 'EEG.reject.icarejfreq'; macrorejE = 'EEG.reject.icarejfreqE'; end; colrej = EEG.reject.rejfreqcol; elecrange = opt.elecrange; superpose = opt.eegplotplotallrej; reject = opt.eegplotreject; topcommand = opt.eegplotcom; eeg_rejmacro; % script macro for generating command and old rejection arrays if icacomp == 1 eegplot(EEG.data(opt.elecrange,:,:), 'winlength', 5, 'position', [100 550 800 500], ... 'limits', [EEG.xmin EEG.xmax]*1000, 'xgrid', 'off', 'tag', 'childEEG' ); else eegplot(icaacttmp(opt.elecrange,:,:), 'winlength', 5, 'position', [100 550 800 500], 'limits', ... [EEG.xmin EEG.xmax]*1000 , 'xgrid', 'off', 'tag', 'childEEG' ); end; eegplot( allspec(elecrange,:,:), 'srate', EEG.srate, 'freqlimits', [1 EEG.srate/2],'freqs', freqs,... 'command',command, 'children', findobj('tag', 'childEEG'), 'position', [100 50 800 500], eegplotoptions{3:end}); % excluding events end; if ~isempty(rej) if icacomp == 1 EEG.reject.rejfreq = rej; EEG.reject.rejfreqE = rejE; else EEG.reject.icarejfreq = rej; EEG.reject.icarejfreqE = rejE; end; if opt.eegplotreject EEG = pop_rejepoch(EEG, rej, 0); end; Irej = find(rej); end; % store variables % --------------- if icacomp == 1, EEG.specdata = allspec; else, EEG.specicaact = allspec; end; com = [com sprintf('%s = pop_rejspec( %s, %s);', inputname(1), ... inputname(1), vararg2str({icacomp, 'elecrange', opt.elecrange,'method', opt.method, 'threshold', opt.threshold, 'freqlimits', opt.freqlimits, ... 'eegplotcom', opt.eegplotcom, 'eegplotplotallrej' opt.eegplotplotallrej 'eegplotreject' opt.eegplotreject })) ]; return; % compute spectrum and reject artifacts % ------------------------------------- function [specdata, Irej, Erej, freqs ] = spectrumthresh( data, specdata, elecrange, srate, negthresh, posthresh, startfreq, endfreq, method); % compute the fft if necessary - old version if isempty(specdata) if strcmpi(method, 'fft') sizewin = size(data,2); freqs = srate*[1, sizewin]/sizewin/2; specdata = fft( data-repmat(mean(data,2), [1 size(data,2) 1]), sizewin, 2); specdata = specdata( :, 2:sizewin/2+1, :); specdata = 10*log10(abs( specdata ).^2); specdata = specdata - repmat( mean(specdata,3), [1 1 size(data,3)]); else if ~exist('pmtm') error('The signal processing toolbox needs to be installed'); end; [tmp freqs] = pmtm( data(1,:,1), [],[],srate); % just to get the frequencies fprintf('Computing spectrum (using slepian tapers; done only once):\n'); for index = 1:size(data,1) fprintf('%d ', index); for indextrials = 1:size(data,3) [ tmpspec(index,:,indextrials) freqs] = pmtm( data(index,:,indextrials) , [],[],srate); end; end; tmpspec = 10*log(tmpspec); tmpspec = tmpspec - repmat( mean(tmpspec,3), [1 1 size(data,3)]); specdata = tmpspec; end; else if strcmpi(method, 'fft') sizewin = size(data,2); freqs = srate*[1, sizewin]/sizewin/2; else [tmp freqs] = pmtm( data(1,:,1), [],[],srate); % just to get the frequencies end; end; % perform the rejection % --------------------- [I1 Irej NS Erej] = eegthresh( specdata(elecrange, :, :), size(specdata,2), 1:length(elecrange), negthresh, posthresh, ... [freqs(1) freqs(end)], startfreq, min(freqs(end), endfreq)); fprintf('\n');
github
lcnhappe/happe-master
pop_topoplot.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_topoplot.m
15,355
utf_8
19c72493ffe31f579682a0e2b754a95f
% pop_topoplot() - Plot scalp map(s) in a figure window. If number of input % arguments is less than 3, pop up an interactive query window. % Makes (possibly repeated) calls to topoplot(). % Usage: % >> pop_topoplot( EEG); % pops up a parameter query window % >> pop_topoplot( EEG, typeplot, items, title, plotdip, options...); % no pop-up % % Inputs: % EEG - Input EEG dataset structure (see >> help eeglab) % typeplot - 1-> Plot channel ERP maps; 0-> Plot component maps {default:1}. % % Commandline inputs also set in pop-up window: % items - [array] If typeplot==1 (ERP maps), within-epoch latencies % (ms) at which to plot the maps. If typeplot==0 (component % maps), component indices to plot. In this case, % negative map indices -> invert map polarity, or % NaN -> leave a blank subplot. (Ex: [1 -3 NaN 4]) % title - Plot title. % rowscols - Vector of the form [m,n] giving [rows, cols] per page. % If the number of maps exceeds m*n, multiple figures % are produced {default|0 -> one near-square page}. % plotdip - [0|1] plot associated dipole(s) for scalp map if present % in dataset. % % Optional Key-Value Pair Inputs % 'colorbar' - ['on' or 'off'] Switch to turn colorbar on or off. {Default: 'on'} % options - optional topoplot() arguments. Separate using commas. % Example 'style', 'straight'. See >> help topoplot % for further details. {default: none} % % Note: % A new figure is created automatically only when the pop_up window is % called or when more than one page of maps are plotted. Thus, this % command may be used to draw topographic maps in a figure sub-axis. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: topoplot(), 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 % 02-15-02 text interface editing -sm & ad % 02-16-02 added axcopy -ad & sm % 03-18-02 added title -ad & sm function com = pop_topoplot( EEG, typeplot, arg2, topotitle, rowcols, varargin); com = ''; if nargin < 1 help pop_topoplot; return; end; if nargin < 2 typeplot = 1; end; if typeplot == 0 & isempty(EEG.icasphere) disp('Error: no ICA data for this set, first run ICA'); return; end; if isempty(EEG.chanlocs) disp('Error: cannot plot topography without channel location file'); return; end; if nargin < 3 % which set to save % ----------------- if typeplot txtwhat2plot1 = 'Plotting ERP scalp maps at these latencies'; txtwhat2plot2 = sprintf('(range: %d to %d ms, NaN -> empty):', ... round(EEG.xmin*1000), round(EEG.xmax*1000)); editwhat2plot = ['']; else txtwhat2plot1 = 'Component numbers'; txtwhat2plot2 = '(negate index to invert component polarity; NaN -> empty subplot; Ex: -1 NaN 3)'; editwhat2plot = ['1:' int2str(size(EEG.icaweights,1))]; end; if EEG.nbchan > 64, elecdef = ['''electrodes'', ''off''']; else, elecdef = ['''electrodes'', ''on''']; end; uilist = { { 'style' 'text' 'string' txtwhat2plot1 } ... { 'style' 'edit' 'string' editwhat2plot } ... { 'style' 'text' 'string' txtwhat2plot2 } ... { } ... { 'style' 'text' 'string' 'Plot title' } ... { 'style' 'edit' 'string' fastif(~isempty(EEG.setname), [EEG.setname], '') } ... { 'style' 'text' 'string' 'Plot geometry (rows,col.); [] -> near square' } ... { 'style' 'edit' 'string' '[]' } ... { 'style' 'text' 'string' 'Plot associated dipole(s) (if present)' } ... { 'style' 'checkbox' 'string' '' } { } ... { } ... { 'style' 'text' 'string' [ '-> Additional topoplot()' fastif(typeplot,'',' (and dipole)') ... ' options (see Help)' ] } ... { 'style' 'edit' 'string' elecdef } }; uigeom = { [1.5 1] [1] [1] [1.5 1] [1.5 1] [1.55 0.2 0.8] [1] [1] [1] }; if typeplot uilist(9:11) = []; uigeom(6) = []; end; guititle = fastif( typeplot, 'Plot ERP scalp maps in 2-D -- pop_topoplot()', ... 'Plot component scalp maps in 2-D -- pop_topoplot()'); result = inputgui( uigeom, uilist, 'pophelp(''pop_topoplot'')', guititle, [], 'normal'); if length(result) == 0 return; end; % reading first param % ------------------- arg2 = eval( [ '[' result{1} ']' ] ); if length(arg2) > EEG.nbchan tmpbut = questdlg2(... ['This involves drawing ' int2str(length(arg2)) ' plots. Continue ?'], ... '', 'Cancel', 'Yes', 'Yes'); if strcmp(tmpbut, 'Cancel'), return; end; end; if isempty(arg2), error('Nothing to plot; enter parameter in first edit box'); end; % reading other params % -------------------- topotitle = result{2}; rowcols = eval( [ '[' result{3} ']' ] ); if typeplot plotdip = 0; try, options = eval( [ '{ ' result{4} ' }' ]); catch, error('Invalid scalp map options'); end; else plotdip = result{4}; try, options = eval( [ '{ ' result{5} ' }' ]); catch, error('Invalid scalp map options'); end; end; if length(arg2) == 1, figure('paperpositionmode', 'auto'); curfig=gcf; try, icadefs; set(curfig, 'color', BACKCOLOR); catch, end; end; else if ~isempty(varargin) & isnumeric(varargin{1}) plotdip = varargin{1}; varargin = varargin(2:end); else plotdip = 0; end; options = varargin; end; % additional options % ------------------ outoptions = { options{:} }; % for command options = { options{:} 'masksurf' 'on' }; % find maplimits % -------------- maplimits = []; for i=1:2:length(options) if isstr(options{i}) if strcmpi(options{i}, 'maplimits') maplimits = options{i+1}; options(i:i+1) = []; break; end; end; end; nbgraph = size(arg2(:),1); if ~exist('topotitle') topotitle = ''; end; if ~exist('rowcols') | isempty(rowcols) | rowcols == 0 rowcols(2) = ceil(sqrt(nbgraph)); rowcols(1) = ceil(nbgraph/rowcols(2)); end; SIZEBOX = 150; fprintf('Plotting...\n'); if isempty(EEG.chanlocs) fprintf('Error: set has no channel location file\n'); return; end; % Check if pop_topoplot input 'colorbar' was called, and don't send it to topoplot loc = strmatch('colorbar', options(1:2:end), 'exact'); loc = loc*2-1; if ~isempty(loc) colorbar_switch = strcmp('on',options{ loc+1 }); options(loc:loc+1) = []; else colorbar_switch = 1; end % determine the scale for plot of different times (same scales) % ------------------------------------------------------------- if typeplot SIGTMP = reshape(EEG.data, EEG.nbchan, EEG.pnts, EEG.trials); pos = round( (arg2/1000-EEG.xmin)/(EEG.xmax-EEG.xmin) * (EEG.pnts-1))+1; nanpos = find(isnan(pos)); pos(nanpos) = 1; SIGTMPAVG = mean(SIGTMP(:,pos,:),3); SIGTMPAVG(:, nanpos) = NaN; if isempty(maplimits) maxlim = max(SIGTMPAVG(:)); minlim = min(SIGTMPAVG(:)); maplimits = [ -max(maxlim, -minlim) max(maxlim, -minlim)]; end; else if isempty(maplimits) maplimits = 'absmax'; end; end; if plotdip if strcmpi(EEG.dipfit.coordformat, 'CTF') disp('Cannot plot dipole on scalp map for CTF MEG data'); end; end; % plot the graphs % --------------- counter = 1; countobj = 1; allobj = zeros(1,1000); curfig = get(0, 'currentfigure'); if isfield(EEG, 'chaninfo'), options = { options{:} 'chaninfo' EEG.chaninfo }; end for index = 1:size(arg2(:),1) if nbgraph > 1 if mod(index, rowcols(1)*rowcols(2)) == 1 if index> 1, figure(curfig); a = textsc(0.5, 0.05, topotitle); set(a, 'fontweight', 'bold'); end; curfig = figure('paperpositionmode', 'auto'); pos = get(curfig,'Position'); posx = max(0, pos(1)+(pos(3)-SIZEBOX*rowcols(2))/2); posy = pos(2)+pos(4)-SIZEBOX*rowcols(1); set(curfig,'Position', [posx posy SIZEBOX*rowcols(2) SIZEBOX*rowcols(1)]); try, icadefs; set(curfig, 'color', BACKCOLOR); catch, end; end; curax = subplot( rowcols(1), rowcols(2), mod(index-1, rowcols(1)*rowcols(2))+1,'Parent',curfig); set(curax, 'visible', 'off') end; % add dipole location if present % ------------------------------ dipoleplotted = 0; if plotdip && typeplot == 0 if isfield(EEG, 'dipfit') & isfield(EEG.dipfit, 'model') if length(EEG.dipfit.model) >= index & ~strcmpi(EEG.dipfit.coordformat, 'CTF') %curpos = EEG.dipfit.model(arg2(index)).posxyz/EEG.dipfit.vol.r(end); curpos = EEG.dipfit.model(arg2(index)).posxyz; curmom = EEG.dipfit.model(arg2(index)).momxyz; try, select = EEG.dipfit.model(arg2(index)).select; catch select = 0; end; if ~isempty(curpos) if strcmpi(EEG.dipfit.coordformat, 'MNI') % from MNI to sperical coordinates transform = pinv( sph2spm ); tmpres = transform * [ curpos(1,:) 1 ]'; curpos(1,:) = tmpres(1:3); tmpres = transform * [ curmom(1,:) 1 ]'; curmom(1,:) = tmpres(1:3); try, tmpres = transform * [ curpos(2,:) 1 ]'; curpos(2,:) = tmpres(1:3); catch, end; try, tmpres = transform * [ curmom(2,:) 1 ]'; curmom(2,:) = tmpres(1:3); catch, end; end; curpos = curpos / 85; if size(curpos,1) > 1 && length(select) == 2 dipole_index = find(strcmpi('dipole',options),1); if ~isempty(dipole_index) % if 'dipoles' is already defined in options{:} options{dipole_index+1} = [ curpos(:,1:2) curmom(:,1:3) ]; else options = { options{:} 'dipole' [ curpos(:,1:2) curmom(:,1:3) ] }; end dipoleplotted = 1; else if any(curpos(1,:) ~= 0) dipole_index = find(strcmpi('dipole',options),1); if ~isempty(dipole_index) % if 'dipoles' is already defined in options{:} options{dipole_index+1} = [ curpos(1,1:2) curmom(1,1:3) ]; else options = { options{:} 'dipole' [ curpos(1,1:2) curmom(1,1:3) ] }; end dipoleplotted = 1; end end end if nbgraph ~= 1 dipscale_index = find(strcmpi('dipscale',options),1); if ~isempty(dipscale_index) % if 'dipscale' is already defined in options{:} options{dipscale_index+1} = 0.6; else options = { options{:} 'dipscale' 0.6 }; end end %options = { options{:} 'dipsphere' max(EEG.dipfit.vol.r) }; end end end % plot scalp map % -------------- if index == 1 addopt = { 'verbose', 'on' }; else addopt = { 'verbose', 'off' }; end; %fprintf('Printing to figure %d.\n',curfig); options = { 'maplimits' maplimits options{:} addopt{:} }; if ~isnan(arg2(index)) if typeplot if nbgraph > 1, axes(curax); end; tmpobj = topoplot( SIGTMPAVG(:,index), EEG.chanlocs, options{:}); if nbgraph == 1, figure(curfig); if nbgraph > 1, axes(curax); end; title( [ 'Latency ' int2str(arg2(index)) ' ms from ' topotitle]); else figure(curfig); if nbgraph > 1, axes(curax); end; title([int2str(arg2(index)) ' ms'] ); end; else if arg2(index) < 0 figure(curfig); if nbgraph > 1, axes(curax); end; tmpobj = topoplot( -EEG.icawinv(:, -arg2(index)), EEG.chanlocs, options{:} ); else figure(curfig); if nbgraph > 1, axes(curax); end; tmpobj = topoplot( EEG.icawinv(:, arg2(index)), EEG.chanlocs, options{:} ); end; if nbgraph == 1, texttitle = [ 'IC ' int2str(arg2(index)) ' from ' topotitle]; else texttitle = ['' int2str(arg2(index))]; end; if dipoleplotted, texttitle = [ texttitle ' (' num2str(EEG.dipfit.model(arg2(index)).rv*100,2) '%)']; end; figure(curfig); if nbgraph > 1, axes(curax); end; title(texttitle); end; allobj(countobj:countobj+length(tmpobj)-1) = tmpobj; countobj = countobj+length(tmpobj); drawnow; axis square; else axis off end; end % Draw colorbar if colorbar_switch if nbgraph == 1 if ~isstr(maplimits) ColorbarHandle = cbar(0,0,[maplimits(1) maplimits(2)]); else ColorbarHandle = cbar(0,0,get(gca, 'clim')); end; pos = get(ColorbarHandle,'position'); % move left & shrink to match head size set(ColorbarHandle,'position',[pos(1)-.05 pos(2)+0.13 pos(3)*0.7 pos(4)-0.26]); elseif ~isstr(maplimits) cbar('vert',0,[maplimits(1) maplimits(2)]); else cbar('vert',0,get(gca, 'clim')); end if ~typeplot % Draw '+' and '-' instead of numbers for colorbar tick labels tmp = get(gca, 'ytick'); set(gca, 'ytickmode', 'manual', 'yticklabelmode', 'manual', 'ytick', [tmp(1) tmp(end)], 'yticklabel', { '-' '+' }); end end if nbgraph> 1, figure(curfig); a = textsc(0.5, 0.05, topotitle); set(a, 'fontweight', 'bold'); end; if nbgraph== 1, com = 'figure;'; end; set(allobj(1:countobj-1), 'visible', 'on'); figure(curfig); axcopy(curfig, 'set(gcf, ''''units'''', ''''pixels''''); postmp = get(gcf, ''''position''''); set(gcf, ''''position'''', [postmp(1) postmp(2) 560 420]); clear postmp;'); com = [com sprintf('pop_topoplot(%s,%d, %s);', ... inputname(1), typeplot, vararg2str({arg2 topotitle rowcols plotdip outoptions{:} }))]; return;
github
lcnhappe/happe-master
eeg_mergechan.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_mergechan.m
2,300
utf_8
48938c717d76faeab216bacf2ac08eaa
% eeg_mergechan() - merge channel structure while preserving channel % order % % >> mergelocs = eeg_mergechan(locs1, locs2); % % Inputs: % locs1 - EEGLAB channel location structure % locs2 - second EEGLAB channel location structure % % Output: % mergelocs - merged channel location structure % % Author: Arnaud Delorme, August 2006 % Copyright (C) Arnaud Delorme, CERCO, 2006, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % union of two channel location structure % without loosing the order information % --------------------------------------- function alllocs = myunion(locs1, locs2) labs1 = { locs1.labels }; labs2 = { locs2.labels }; count1 = 1; count2 = 1; count3 = 1; alllocs = locs1; alllocs(:) = []; while count1 <= length(locs1) | count2 <= length(locs2) if count1 > length(locs1) alllocs(count3) = locs2(count2); count2 = count2 + 1; count3 = count3 + 1; elseif count2 > length(locs2) alllocs(count3) = locs1(count1); count1 = count1 + 1; count3 = count3 + 1; elseif strcmpi(labs1{count1}, labs2{count2}) alllocs(count3) = locs1(count1); count1 = count1 + 1; count2 = count2 + 1; count3 = count3 + 1; elseif isempty(strmatch(labs1{count1}, labs2)) alllocs(count3) = locs1(count1); count1 = count1 + 1; count3 = count3 + 1; else alllocs(count3) = locs2(count2); count2 = count2 + 1; count3 = count3 + 1; end; end;
github
lcnhappe/happe-master
pop_interp.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_interp.m
7,599
utf_8
eeaf74ad67176964b6a8cb937a11371b
% pop_interp() - interpolate data channels % % Usage: EEGOUT = pop_interp(EEG, badchans, method); % % Inputs: % EEG - EEGLAB dataset % badchans - [integer array] indices of channels to interpolate. % For instance, these channels might be bad. % [chanlocs structure] channel location structure containing % either locations of channels to interpolate or a full % channel structure (missing channels in the current % dataset are interpolated). % method - [string] method used for interpolation (default is 'spherical'). % 'invdist'/'v4' uses inverse distance on the scalp % 'spherical' uses superfast spherical interpolation. % 'spacetime' uses griddata3 to interpolate both in space % and time (very slow and cannot be interupted). % Output: % EEGOUT - data set with bad electrode data replaced by % interpolated data % % Author: Arnaud Delorme, CERCO, CNRS, 2009- % Copyright (C) Arnaud Delorme, CERCO, 2009, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG com] = pop_interp(EEG, bad_elec, method) com = ''; if nargin < 1 help pop_interp; return; end; if nargin < 2 disp('Warning: interpolation can be done on the fly in studies'); disp(' this function will actually create channels in the dataset'); disp('Warning: do not interpolate channels before running ICA'); disp('You may define channel location to interpolate in the channel'); disp('editor and declare such channels as non-data channels'); enablenondat = 'off'; if isfield(EEG.chaninfo, 'nodatchans') if ~isempty(EEG.chaninfo.nodatchans) enablenondat = 'on'; end; end; uilist = { { 'Style' 'text' 'string' 'What channel(s) do you want to interpolate' 'fontweight' 'bold' } ... { 'style' 'text' 'string' 'none selected' 'tag' 'chanlist' } ... { 'style' 'pushbutton' 'string' 'Select from removed channels' 'callback' 'pop_interp(''nondatchan'',gcbf);' 'enable' enablenondat } ... { 'style' 'pushbutton' 'string' 'Select from data channels' 'callback' 'pop_interp(''datchan'',gcbf);' } ... { 'style' 'pushbutton' 'string' 'Use specific channels of other dataset' 'callback' 'pop_interp(''selectchan'',gcbf);'} ... { 'style' 'pushbutton' 'string' 'Use all channels from other dataset' 'callback' 'pop_interp(''uselist'',gcbf);'} ... { } ... { 'style' 'text' 'string' 'Interpolation method'} ... { 'style' 'popupmenu' 'string' 'Spherical|Planar (slow)' 'tag' 'method' } ... }; geom = { 1 1 1 1 1 1 1 [1.1 1] }; [res userdata tmp restag ] = inputgui( 'uilist', uilist, 'title', 'Interpolate channel(s) -- pop_interp()', 'geometry', geom, 'helpcom', 'pophelp(''pop_interp'')'); if isempty(res) | isempty(userdata), return; end; if restag.method == 1 method = 'spherical'; else method = 'invdist'; end; bad_elec = userdata.chans; com = sprintf('EEG = pop_interp(EEG, %s, ''%s'');', userdata.chanstr, method); if ~isempty(findstr('nodatchans', userdata.chanstr)) eval( [ userdata.chanstr '=[];' ] ); end; elseif isstr(EEG) command = EEG; clear EEG; fig = bad_elec; userdata = get(fig, 'userdata'); if strcmpi(command, 'nondatchan') global EEG; tmpchaninfo = EEG.chaninfo; [chanlisttmp chanliststr] = pop_chansel( { tmpchaninfo.nodatchans.labels } ); if ~isempty(chanlisttmp), userdata.chans = EEG.chaninfo.nodatchans(chanlisttmp); userdata.chanstr = [ 'EEG.chaninfo.nodatchans([' num2str(chanlisttmp) '])' ]; set(fig, 'userdata', userdata); set(findobj(fig, 'tag', 'chanlist'), 'string', chanliststr); end; elseif strcmpi(command, 'datchan') global EEG; tmpchaninfo = EEG.chanlocs; [chanlisttmp chanliststr] = pop_chansel( { tmpchaninfo.labels } ); if ~isempty(chanlisttmp), userdata.chans = chanlisttmp; userdata.chanstr = [ '[' num2str(chanlisttmp) ']' ]; set(fig, 'userdata', userdata); set(findobj(fig, 'tag', 'chanlist'), 'string', chanliststr); end; else global ALLEEG EEG; tmpanswer = inputdlg2({ 'Dataset index' }, 'Choose dataset', 1, { '' }); if ~isempty(tmpanswer), tmpanswernum = round(str2num(tmpanswer{1})); if ~isempty(tmpanswernum), if tmpanswernum > 0 & tmpanswernum <= length(ALLEEG), TMPEEG = ALLEEG(tmpanswernum); tmpchans1 = TMPEEG.chanlocs; if strcmpi(command, 'selectchan') chanlist = pop_chansel( { tmpchans1.labels } ); else chanlist = 1:length(TMPEEG.chanlocs); % use all channels end % look at what new channels are selected tmpchans2 = EEG.chanlocs; [tmpchanlist chaninds] = setdiff_bc( { tmpchans1(chanlist).labels }, { tmpchans2.labels } ); if ~isempty(tmpchanlist), if length(chanlist) == length(TMPEEG.chanlocs) userdata.chans = TMPEEG.chanlocs; userdata.chanstr = [ 'ALLEEG(' tmpanswer{1} ').chanlocs' ]; else userdata.chans = TMPEEG.chanlocs(chanlist(sort(chaninds))); userdata.chanstr = [ 'ALLEEG(' tmpanswer{1} ').chanlocs([' num2str(chanlist(sort(chaninds))) '])' ]; end; set(fig, 'userdata', userdata); tmpchanlist(2,:) = { ' ' }; set(findobj(gcbf, 'tag', 'chanlist'), 'string', [ tmpchanlist{:} ]); else warndlg2('No new channels selected'); end; else warndlg2('Wrong index'); end; end; end; end; return; end; EEG = eeg_interp(EEG, bad_elec, method);
github
lcnhappe/happe-master
pop_importepoch.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_importepoch.m
20,310
utf_8
9bb19bf2478e05dd8fa4a86f6e7ffc51
% pop_importepoch() - Export epoch and/or epoch event information to the event % structure array of an EEG dataset. If the dataset is % the only input, a window pops up to ask for the relevant % parameter values. % Usage: % >> EEGOUT = pop_importepoch( EEG ); % pop-up window mode % >> EEGOUT = pop_importepoch( EEG, filename, fieldlist, 'key', 'val', ...); % % Graphic interface: % "Epoch file or array" - [edit box] enter epoch text file name. Use "Browse" % button to browse for a file. If a file with the given name % can not be found, the function search for a variable with % this name in the global workspace. Command line % equivalent: filename. % "File input field ..." - [edit box] enter a name for each of the column in the % text file. If columns names are defined in the text file, % they cannnot be used and you must copy their names % in this edit box (and skip the rows). One column name % for each column must be provided. The keywords "type" and % "latency" should not be used. Columns names can be % separated by comas, quoted or not. Command line % equivalent: fieldlist. % "Field name(s) containing event latencies" - [edit box] enter columns name(s) % containing latency information. It is not necessary to % define a latency field for epoch information. All fields % that contain latencies will be imported as different event % types. For instance, if field 'RT' contains latencies, % events of type 'RT' will be created with latencies given % in the RT field. See notes. Command line % equivalent: 'latencyfields'. % "Field name(s) containing event durations" - [edit box] enter columns name(s) % containing duration information. It is not necessary to % define a latency field for epoch information, but if you % do, a duration field (or 0) must be entered for each % latency field you define. For instance if the latency fields % are "'rt1' 'rt2'", then you must have duration fields % such as "'dr1' 'dr2'". If duration is not defined for event % latency 'tr1', you may enter "0 'rt2'". Command line % equivalent: 'durationfields'. % "Field name containing time locking event type(s)" - [edit box] if one column % contain the epoch type, its name must be defined in the % previous edit box and copied here. It is not necessary to % define a type field for the time-locking event (TLE). By % default it is defined as type ''TLE'' at time 0 for all % epochs. Command line equivalent: 'typefield'. % "Latency time unit rel. to seconds" - [edit box] specify the time unit for % latency columns defined above. Command line % equivalent: 'timeunit'. % "Number of header lines to ignore" - [edit box] for some text files, the first % rows do not contain epoch information and have to be % skipped. Command line equivalent: 'headerlines'. % "Remove old epoch and event info" - [checkbox] check this checkbox % to remove any prior event or epoch information. Command % line equivalent: 'clearevents'. % % Inputs: % EEG - Input EEG dataset % filename - Name of an ascii file with epoch and/or epoch event % information organised in columns. ELSE, name of a Matlab % variable with the same information (either a Matlab array % or cell array). % fieldlist - {cell array} Label of each column (data field) in the file. % % Optional inputs: % 'typefield' - ['string'] Name of the field containing the type(s) % of the epoch time-locking events (at time 0). % By default, all the time-locking events are assigned % type 'TLE' (for "time-locking event"). % 'latencyfields' - {cell array} Field names that contain the latency % of an event. These fields are transferred into % events whose type will be the same as the name of % the latency field. (Ex: field RT -> type 'RT' events). % 'durationfields' - {cell array} Field names that contain the duration % of an event. % 'timeunit' - [float] Optional unit for latencies relative to seconds. % Ex: sec -> 1, msec -> 1e-3. Default: Assume latencies % are in time points (relative to the time-zero time point % in the epoch). % 'headerlines' - [int] Number of header lines in the input file to ignore. % {Default 0}. % 'clearevents' - ['on'|'off'], 'on'-> clear the old event array. % {Default 'on'} % % Output: % EEGOUT - EEG dataset with modified event structure % % FAQ: % 1) Why is this function so complex? This function can handle as many events % per epochs as needed, and the information is stored in terms of events % rather than epoch information, which requires some conversion. % 2) Can I access epoch information later? The epoch information is stored in % "EEG.event" and the information is stored in terms of events only. For % user convenience the "EEG.epoch" structure is generated automatically % from the event structure. See EEGLAB manual for more information. % % Authors: Arnaud Delorme & Scott Makeig, CNL/Salk Institute, 11 March 2002 % % See also: eeglab() % 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 % graphic interface INFOS % 03/18/02 debugging variable passing - ad & lf % 03/18/02 adding event updates and incremental calls -ad % 03/25/02 adding default event description -ad % 03/28/02 fixed latency calculation -ad function [EEG, com] = pop_importepoch( EEG, filename, fieldlist, varargin); com =''; if nargin < 1 help pop_importepoch return; end; if nargin < 2 geometry = { [ 1 1 1.86] [1] [1 0.66] [2.5 1 0.6] [2.5 1 0.6] [2.5 1 0.6] [1] [2 0.5 0.5] [2 0.5 0.5] [2 0.17 0.86]}; commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ... 'if filename ~=0,' ... ' set(findobj(''parent'', gcbf, ''tag'', tagtest), ''string'', [ filepath filename ]);' ... 'end;' ... 'clear filename filepath tagtest;' ]; helpstrtype = ['It is not necessary to define a type field for the time-locking event.' 10 ... 'By default it is defined as type ''TLE'' at time 0 for all epochs']; helpstrlat = ['It is not necessary to define a latency field for epoch information.' 10 ... 'All fields that contain latencies will be imported as different event types.' 10 ... 'For instance, if field ''RT'' contains latencies, events of type ''RT''' 10 ... 'will be created with latencies given in the RT field']; helpstrdur = ['It is not necessary to define a duration for each event (default is 0).' 10 ... 'However if a duration is defined, a corresponding latency must be defined too' 10 ... '(in the edit box above). For each latency field, you have define a duration field.' 10 ... 'if no duration field is defined for a specific event latency, enter ''0'' in place of the duration field' ]; uilist = { ... { 'Style', 'text', 'string', 'Epoch file or array', 'horizontalalignment', 'right', 'fontweight', 'bold' }, ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''globfile'';' commandload ] }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'globfile' }, ... { }... { 'Style', 'text', 'string', 'File input field (col.) names', 'fontweight', 'bold' }, { 'Style', 'edit', 'string', '' }, ... { 'Style', 'text', 'string', ' Field name(s) containing event latencies', 'horizontalalignment', 'right', ... 'fontweight', 'bold', 'tooltipstring', helpstrlat }, ... { 'Style', 'edit', 'string', '' }, ... { 'Style', 'text', 'string', '(Ex: RT)', 'tooltipstring', helpstrlat }, ... { 'Style', 'text', 'string', ' Field name(s) containing event durations', 'horizontalalignment', 'right', ... 'fontweight', 'bold', 'tooltipstring', helpstrdur }, ... { 'Style', 'edit', 'string', '' }, ... { 'Style', 'text', 'string', 'NOTE', 'tooltipstring', helpstrdur }, ... { 'Style', 'text', 'string', ' Field name containing time-locking event type(s)', 'horizontalalignment', 'right', ... 'tooltipstring', helpstrtype }, ... { 'Style', 'edit', 'string', '' }, ... { 'Style', 'text', 'string', 'NOTE', 'tooltipstring', helpstrtype }, ... { } ... { 'Style', 'text', 'string', 'Latency time unit rel. to seconds. Ex: ms -> 1E-3 (NaN -> samples)', 'horizontalalignment', 'left' }, { 'Style', 'edit', 'string', '1' }, { } ... { 'Style', 'text', 'string', 'Number of file header lines to ignore', 'horizontalalignment', 'left' }, { 'Style', 'edit', 'string', '0' }, { },... { 'Style', 'text', 'string', 'Remove old epoch and event info (set = yes)', 'horizontalalignment', 'left' }, { 'Style', 'checkbox', 'value', isempty(EEG.event) }, { } }; result = inputgui( geometry, uilist, 'pophelp(''pop_importepoch'');', 'Import epoch info (data epochs only) -- pop_importepoch()'); if length(result) == 0, return; end; filename = result{1}; fieldlist = parsetxt( result{2} ); options = {}; if ~isempty( result{3}), options = { options{:} 'latencyfields' parsetxt( result{3} ) }; end; if ~isempty( result{4}), options = { options{:} 'durationfields' parsetxt( result{4} ) }; end; if ~isempty( result{5}), options = { options{:} 'typefield' result{5} }; end; if ~isempty( result{6}), options = { options{:} 'timeunit' eval(result{6}) }; end; if ~isempty( result{7}), options = { options{:} 'headerlines' eval(result{7}) }; end; if ~result{8}, options = { options{:} 'clearevents' 'off'}; end; else if ~isempty(varargin) & ~isstr(varargin{1}) % old call compatibility options = { 'latencyfields' varargin{1} }; if nargin > 4 options = { options{:} 'timeunit' varargin{2} }; end; if nargin > 5 options = { options{:} 'headerlines' varargin{3} }; end; if nargin > 6 options = { options{:} 'clearevents' fastif(varargin{4}, 'on', 'off') }; end; else options = varargin; end; end; g = finputcheck( options, { 'typefield' 'string' [] ''; ... 'latencyfields' 'cell' [] {}; ... 'durationfields' 'cell' [] {}; ... 'timeunit' 'real' [0 Inf] 1/EEG.srate; ... 'headerlines' 'integer' [0 Inf] 0; ... 'clearevents' 'string' {'on';'off'} 'on'}, 'pop_importepoch'); if isstr(g), error(g); end; % check duration field % -------------------- if ~isempty(g.durationfields) if length(g.durationfields) ~= length(g.latencyfields) error( [ 'If duration field(s) are defined, their must be as many duration' 10 ... 'fields as there are latency fields (or enter 0 instead of a field for no duration' ]); end; else for index = 1:length(g.latencyfields) g.durationfields{index} = 0; end; end; % convert filename % ---------------- fprintf('Pop_importepoch: Loading file or array...\n'); if isstr(filename) % check filename % -------------- if exist(filename) == 2 & evalin('base', ['exist(''' filename ''')']) == 1 disp('Pop_importepoch WARNING: FILE AND ARRAY WITH THE SAME NAME, LOADING FILE'); end; values = load_file_or_array( filename, g.headerlines ); else values = filename; filename = inputname(2); end; % check parameters % ---------------- if size(values,1) < size(values,2), values = values'; end; if length(fieldlist) ~= size(values,2) values = values'; if length(fieldlist) ~= size(values,2) error('There must be as many field names as there are columsn in the file/array'); end; end; if ~iscell(fieldlist) otherfieldlist = { fieldlist }; fieldlist = { fieldlist }; end; otherfieldlist = setdiff_bc( fieldlist, g.latencyfields); otherfieldlist = setdiff_bc( otherfieldlist, g.typefield); for index = 1:length(g.durationfields) if isstr(g.durationfields{index}) otherfieldlist = setdiff_bc( otherfieldlist, g.durationfields{index}); end; end; if size(values,1) ~= EEG.trials error( [ 'Pop_importepoch() error: the number of rows in the input file/array does' 10 ... 'not match the number of trials. Maybe you forgot to specify the file header length?' ]); end; % create epoch array info % ----------------------- if iscell( values ) for indexfield = 1:length(fieldlist) for index=1:EEG.trials eval( ['EEG.epoch(index).' fieldlist{ indexfield } '=values{ index, indexfield };'] ); end; end; else for indexfield = 1:length(fieldlist) for index=1:EEG.trials eval( ['EEG.epoch(index).' fieldlist{ indexfield } '=values( index, indexfield);'] ); end; end; end; if isempty( EEG.epoch ) error('Pop_importepoch: cannot process empty epoch structure'); end; epochfield = fieldnames( EEG.epoch ); % determine the name of the non latency fields % -------------------------------------------- tmpfieldname = {}; for index = 1:length(otherfieldlist) if isempty(strmatch( otherfieldlist{index}, epochfield )) error(['Pop_importepoch: field ''' otherfieldlist{index} ''' not found']); end; switch otherfieldlist{index} case {'type' 'latency'}, tmpfieldname{index} = [ 'epoch' otherfieldlist{index} ]; otherwise, tmpfieldname{index} = otherfieldlist{index}; end; end; if ~isempty(EEG.event) if ~isfield(EEG.event, 'epoch') g.clearevents = 'on'; disp('Pop_importepoch: cannot add events to a non-epoch event structure, erasing old epoch structure'); end; end; if strcmpi(g.clearevents, 'on') if ~isempty(EEG.event) fprintf('Pop_importepoch: deleting old events if any\n'); end; EEG.event = []; else fprintf('Pop_importepoch: appending new events to the existing event array\n'); end; % add time locking event fields % ----------------------------- if EEG.xmin <= 0 fprintf('Pop_importepoch: adding automatically Time Locking Event (TLE) events\n'); if ~isempty(g.typefield) if isempty(strmatch( g.typefield, epochfield )) error(['Pop_importepoch: type field ''' g.typefield ''' not found']); end; end; for trial = 1:EEG.trials EEG.event(end+1).epoch = trial; if ~isempty(g.typefield) eval( ['EEG.event(end).type = EEG.epoch(trial).' g.typefield ';'] ); else EEG.event(end).type = 'TLE'; end; EEG.event(end).latency = -EEG.xmin*EEG.srate+1+(trial-1)*EEG.pnts; EEG.event(end).duration = 0; end; end; % add latency fields % ------------------ for index = 1:length(g.latencyfields) if isempty(strmatch( g.latencyfields{index}, epochfield )) error(['Pop_importepoch: latency field ''' g.latencyfields{index} ''' not found']); end; for trials = 1:EEG.trials EEG.event(end+1).epoch = trials; EEG.event(end).type = g.latencyfields{index}; EEG.event(end).latency = (getfield(EEG.epoch(trials), g.latencyfields{index})*g.timeunit-EEG.xmin)*EEG.srate+1+(trials-1)*EEG.pnts; if g.durationfields{index} ~= 0 & g.durationfields{index} ~= '0' EEG.event(end).duration = getfield(EEG.epoch(trials), g.durationfields{index})*g.timeunit*EEG.srate; else EEG.event(end).duration = 0; end; end; end; % add non latency fields % ---------------------- if ~isfield(EEG.event, 'epoch') % no events added yet for trial = 1:EEG.trials EEG.event(end+1).epoch = trial; end; end; for indexevent = 1:length(EEG.event) if ~isempty( EEG.event(indexevent).epoch ) for index2 = 1:length(tmpfieldname) eval( ['EEG.event(indexevent).' tmpfieldname{index2} ' = EEG.epoch(EEG.event(indexevent).epoch).' otherfieldlist{index2} ';' ] ); end; end; end; % adding desciption to the fields % ------------------------------- if ~isfield(EEG, 'eventdescription' ) | isempty( EEG.eventdescription ) allfields = fieldnames(EEG.event); EEG.eventdescription{strmatch('epoch', allfields, 'exact')} = 'Epoch number'; if ~isempty(strmatch('type', allfields)), EEG.eventdescription{strmatch('type', allfields)} = 'Event type'; end; if ~isempty(strmatch('latency', allfields)), EEG.eventdescription{strmatch('latency', allfields)} = 'Event latency'; end; if ~isempty(strmatch('duration', allfields)), EEG.eventdescription{strmatch('duration', allfields)} = 'Event duration'; end; end; % checking and updating events % ---------------------------- EEG = pop_editeventvals( EEG, 'sort', { 'epoch', 0 } ); % resort fields EEG = eeg_checkset(EEG, 'eventconsistency'); EEG = eeg_checkset(EEG, 'makeur'); % generate the output command % --------------------------- if isempty(filename) & nargout == 2 disp('Pop_importepoch: cannot generate command string'); return; else com = sprintf('%s = pop_importepoch( %s, ''%s'', %s);', inputname(1), inputname(1), ... filename, vararg2str( { fieldlist options{:} })); end; % interpret the variable name % --------------------------- function array = load_file_or_array( varname, skipline ); if exist( varname ) == 2 if exist(varname) ~= 2, error( [ 'Set error: no filename ' varname ] ); end; fid=fopen(varname,'r','ieee-le'); if fid<0, error( ['Set error: file ''' varname ''' found but error while opening file'] ); end; for index=1:skipline fgetl(fid); end; % skip lines --------- inputline = fgetl(fid); linenb = 1; while inputline~=-1 colnb = 1; while ~isempty(deblank(inputline)) [tmp inputline] = strtok(inputline); tmp2 = str2num( tmp ); if isempty( tmp2 ), array{linenb, colnb} = tmp; else array{linenb, colnb} = tmp2; end; colnb = colnb+1; end; inputline = fgetl(fid); linenb = linenb +1; end; fclose(fid); else % variable in the global workspace % -------------------------- array = evalin('base', varname); end; return;
github
lcnhappe/happe-master
pop_writeeeg.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_writeeeg.m
3,347
utf_8
86d8d16a225a800acc5fca43d4c6c1cb
% pop_writeeeg - write EEGLAB dataset to disk in EDF/GDF or BDF format % % pop_writeeeg( EEG ) % pops up a window % pop_writeeeg( EEG, filename, 'key', 'val' ) % % Inputs: % EEG - EEGLAB dataset % filename - [string] filename % % Optional keys (same as writeeeg): % 'TYPE' - ['GDF'|'EDF'|'BDF'|'CFWB'|'CNT'] file format for writing % default is 'EDF'. % See writeeeg for more information % % 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 [command] = pop_writeeeg(EEG, filename, varargin) command = ''; % enforce use the str2double of Biosig biosigpathfirst % Check for BIOSIG Toolbox global PLUGINLIST if ~isempty(PLUGINLIST) && ~any(strcmpi({PLUGINLIST.plugin}','biosig')) fprintf(2,'pop_writeeeg error: This function requires you to install <a href="http://biosig.sourceforge.net/index.html">BIOSIG Toolbox</a> plug-in. \n'); return; elseif isempty(PLUGINLIST) warning('pop_writeeeg check for <a href="http://biosig.sourceforge.net/index.html">BIOSIG Toolbox</a> could not be performed.'); end if nargin < 2 if EEG.trials > 1 res = questdlg2( [ 'This dataset contains data epochs.' 10 'Do you want to export the concatenated' 10 'data epochs?' ], '', 'No', 'Yes', 'Yes'); if strcmpi(res, 'No') return; end; end; % ask user [filename, filepath] = uiputfile('*.*', 'Enter a file name -- pop_writeeeg()'); if filename == 0 return; end; filename = fullfile(filepath,filename); % file format % ----------- fileformats = { 'EDF' 'GDF' 'BDF' }; uilist = { { 'style' 'text' 'String' 'File format' } ... { 'style' 'listbox' 'string' strvcat(fileformats) 'value' 1 } }; geom = [1 1]; result = inputgui( 'geometry', geom, 'uilist', uilist, 'helpcom', 'pophelp(''pop_writeeeg'')', ... 'title', 'Write data using BIOSIG -- pop_writeeeg()', 'geomvert', [1 2.5]); if length(result) == 0 return; end; options = { 'TYPE' fileformats{result{1}} }; else options = varargin; end; warning('off', 'MATLAB:intConvertNonIntVal'); if ~isempty(EEG.chanlocs) tmpchanlocs = EEG.chanlocs; writeeeg(filename, EEG.data(:,:), EEG.srate, 'label', { tmpchanlocs.labels }, 'EVENT', EEG.event, options{:}); else writeeeg(filename, EEG.data(:,:), EEG.srate, 'EVENT', EEG.event, options{:}); end; warning('on', 'MATLAB:intConvertNonIntVal'); command = sprintf('pop_writeeeg(EEG, ''%s'', %s);', filename, vararg2str(options)); biosigpathlast
github
lcnhappe/happe-master
pop_chancenter.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_chancenter.m
4,180
utf_8
83264735d5a2740c1458fc2b72f215f5
% pop_chancenter() - recenter cartesian X,Y,Z channel coordinates % % Usage: % >> chanlocs = pop_chancenter(chanlocs); % pop up interactive window % >> [chanlocs centerloc] = pop_chancenter(chanlocs, center, omitchan); % % Inputs: % chanlocs = eeglab channel location structure (see readlocs()) % 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]. % omitchan = indices of channel to omit when computing center % % Outputs: % chanlocs = updated channel location structure % centerloc = 3-D location of the new center (in the old coordinate % frame). % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, Feb 2004 % % See also: chancenter(), spherror(), cart2topo() % Copyright (C) 2004, Arnaud Delorme, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [ chanlocs, newcenter, com] = pop_chancenter( chanlocs, center, omitchans) optim = 0; if nargin<1 help pop_chancenter return; end; com = ''; newcenter = []; if nargin < 3 omitchans = []; end; if nargin < 2 cb_browse = [ 'tmpchans = get(gcbf, ''userdata'');' ... 'set(findobj(gcbf, ''tag'', ''chans''), ''string'', ' ... 'int2str(pop_chansel( { tmpchans.labels } )));' ]; cb_opt = [ 'if get(gcbo, ''value''), ' ... ' set(findobj(gcbf, ''tag'', ''center''), ''enable'', ''off'');' ... 'else,' ... ' set(findobj(gcbf, ''tag'', ''center''), ''enable'', ''on'');' ... 'end;' ]; geometry = { [1.3 0.28 1 1] [1] [1] [2 1] }; uilist = { { 'Style', 'text', 'string', 'Optimize center location', 'fontweight', 'bold' } ... { 'Style', 'checkbox', 'value', 1 'callback' cb_opt } ... { 'Style', 'text', 'string', 'or specify center', 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', '0 0 0', 'tag' 'center' 'enable' 'off' } ... { } ... { 'Style', 'text', 'string', 'Channel indices to ignore for best-sphere matching' } ... { 'Style', 'edit', 'string', '', 'tag', 'chans' } ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', cb_browse } }; results = inputgui( geometry, uilist, 'pophelp(''pop_chancenter'');', ... 'Convert channel locations -- pop_chancenter()', chanlocs ); if isempty(results), return; end; if results{1} center = []; else center = eval( [ '[' results{2} ']' ] ); end; if ~isempty(results{3}) omitchans = eval( [ '[' results{3} ']' ] ); end; end; % remove channels % --------------- c = setdiff_bc([1:length(chanlocs)], union(omitchans, find(cellfun('isempty', { chanlocs.theta })))); % optimize center % --------------- [X Y Z newcenter]= chancenter( [ chanlocs(c).X ]', [ chanlocs(c).Y ]', [ chanlocs(c).Z ]', center); for index = 1:length(c) chanlocs(c(index)).X = X(index); chanlocs(c(index)).Y = Y(index); chanlocs(c(index)).Z = Z(index); end; disp('Note: automatically convert XYZ coordinates to spherical and polar'); chanlocs = convertlocs(chanlocs, 'cart2all'); if ~isempty(omitchans) disp('Important warning: the location of omitted channels has not been modified'); end; com = sprintf('%s = pop_chancenter( %s, %s);', inputname(1), inputname(1), vararg2str({ center omitchans }));
github
lcnhappe/happe-master
eeg_rejsuperpose.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_rejsuperpose.m
4,163
utf_8
31ddb44aab055e8f1ae1b9307ade5b9b
% eeg_rejsuperpose() - superpose rejections of a EEG dataset. % % Usage: % >> EEGOUT = eeg_rejsuperpose( EEGIN, typerej, Rmanual, Rthres, ... % Rconst, Rent, Rkurt, Rfreq, Rothertype); % % Inputs: % EEGIN - input dataset % typerej - type of rejection (1=raw data; 0=ica). % Rmanual - include manual rejection (0|1). % Rthres - include threshold rejection (0|1). % Rconst - include rejection of constant activity (0|1). % Rent - include entropy rejection (0|1). % Rkurt - include kurtosis rejection (0|1). % Rfreq - include frequcy based rejection (0|1). % Rothertype - include manual rejection (0|1). % % Outputs: % EEGOUT - with rejglobal and rejglobalE fields updated % % See also: eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, com] = eeg_rejsuperpose( EEG, typerej, Rmanual, Rthres, Rconst, ... Rent, Rkurt, Rfreq, Rothertype); if nargin < 9 help eeg_rejsuperpose; return; end; typerej = ~typerej; rejglobal = zeros( 1, EEG.trials); if typerej == 0 rejglobalE = zeros( EEG.nbchan, EEG.trials); else rejglobalE = zeros( size(EEG.icaweights,1), EEG.trials); end if typerej == 0 | Rothertype if Rmanual rejglobal = rejarray( rejglobal, EEG.reject.rejmanual); % see bottom for the rejglobalE = rejarray( rejglobalE, EEG.reject.rejmanualE); % function rejarray end; if Rthres rejglobal = rejarray( rejglobal, EEG.reject.rejthresh); rejglobalE = rejarray( rejglobalE, EEG.reject.rejthreshE); end; if Rfreq rejglobal = rejarray( rejglobal, EEG.reject.rejfreq); rejglobalE = rejarray( rejglobalE, EEG.reject.rejfreqE); end; if Rconst rejglobal = rejarray( rejglobal, EEG.reject.rejconst); rejglobalE = rejarray( rejglobalE, EEG.reject.rejconstE); end; if Rent rejglobal = rejarray( rejglobal, EEG.reject.rejjp); rejglobalE = rejarray( rejglobalE, EEG.reject.rejjpE); end; if Rkurt rejglobal = rejarray( rejglobal, EEG.reject.rejkurt); rejglobalE = rejarray( rejglobalE, EEG.reject.rejkurtE); end; end; % --------------- if typerej == 1 | Rothertype if Rmanual rejglobal = rejarray( rejglobal, EEG.reject.icarejmanual); rejglobalE = rejarray( rejglobalE, EEG.reject.icarejmanualE); end; if Rthres rejglobal = rejarray( rejglobal, EEG.reject.icarejthresh); rejglobalE = rejarray( rejglobalE, EEG.reject.icarejthreshE); end; if Rfreq rejglobal = rejarray( rejglobal, EEG.reject.icarejfreq); rejglobalE = rejarray( rejglobalE, EEG.reject.icarejfreqE); end; if Rconst rejglobal = rejarray( rejglobal, EEG.reject.icarejconst); rejglobalE = rejarray( rejglobalE, EEG.reject.icarejconstE); end; if Rent rejglobal = rejarray( rejglobal, EEG.reject.icarejjp); rejglobalE = rejarray( rejglobalE, EEG.reject.icarejjpE); end; if Rkurt rejglobal = rejarray( rejglobal, EEG.reject.icarejkurt); rejglobalE = rejarray( rejglobalE, EEG.reject.icarejkurtE); end; end; EEG.reject.rejglobal = rejglobal; EEG.reject.rejglobalE = rejglobalE; com =sprintf('%s = eeg_rejsuperpose( %s, %d, %d, %d, %d, %d, %d, %d, %d);', ... inputname(1), inputname(1), ~typerej, Rmanual, Rthres, Rconst, Rent, Rkurt, Rfreq, Rothertype); return; % subfunction rejecting an array ------ function dest = rejarray( dest, ori) if isempty(dest) dest = ori; elseif ~isempty(ori) dest = dest | ori; end; return;
github
lcnhappe/happe-master
pop_rejcont.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_rejcont.m
14,137
utf_8
1bcb135e0cc0f260852867027268020b
% pop_rejcont() - reject continuous portions of data based on spectrum % thresholding. First, contiguous data epochs are extracted % and a standard spectrum thresholding algorithm is % applied. Regions of contiguous epochs larger than a % specified size are then labeled as artifactual. % % Usage: % >> pop_rejcont( INEEG ) % pop-up interative window mode % >> [OUTEEG, selectedregions] = pop_rejcont( INEEG, 'key', 'val'); % % Inputs: % INEEG - input dataset % % Optional inputs: % 'elecrange' - [integer array] electrode indices {Default: all electrodes} % 'epochlength' - [float] epoch length in seconds {Default: 0.5 s} % 'overlap' - [float] epoch overlap in seconds {Default: 0.25 s} % 'freqlimit' - [min max] frequency range too consider for thresholding % Default is [35 128] Hz. % 'threshold' - [float] frequency upper threshold in dB {Default: 10} % 'contiguous' - [integer] number of contiguous epochs necessary to % label a region as artifactual {Default: 4 } % 'addlength' - [float] once a region of contiguous epochs has been labeled % as artifact, additional trailing neighboring regions on % each side may also be added {Default: 0.25 s} % 'eegplot' - ['on'|'off'] plot rejected portions of data in a eegplot % window. Default is 'off'. % 'onlyreturnselection' - ['on'|'off'] this option when set to 'on' only % return the selected regions and does not remove them % from the datasets. This allow to perform quick % optimization of the rejected portions of data. % 'precompstruct' - [struct] structure containing precomputed spectrum (see % Outputs) to be used instead of computing the spectrum. % 'verbose' - ['on'|'off'] display information. Default is 'off'. % 'taper' - ['none'|'hamming'] taper to use before FFT. Default is % 'none' for backward compatibility but 'hamming' is % recommended. % % Outputs: % OUTEEG - output dataset with updated joint probability array % selectedregions - frames indices of rejected electrodes. Array of n x 2 % n being the number of regions and 2 for the beginning % and end of each region. % precompstruct - structure containing precomputed data. This structure % contains the spectrum, the frequencies and the EEGLAB % dataset used as input with epochs extracted. % % Author: Arnaud Delorme, CERCO, UPS/CNRS, 2009- % % Example: % EEG = pop_rejcont(EEG, 'elecrange',[1:32] ,'freqlimit',[20 40] ,'threshold',... % 10,'epochlength',0.5,'contiguous',4,'addlength',0.25, 'taper', 'hamming'); % % See also: eegthresh() % Copyright (C) 2009 Arnaud Delorme, CERCO, UPS/CNRS % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG selectedregions precompstruct com ] = pop_rejcont(EEG, varargin); com = ''; if nargin < 1 help pop_rejcont; return; end; if nargin < 2 firstelec = 'EXG1'; % first non EEG channel % take all scalp electrodes % ------------------------- if ~isempty(EEG.chanlocs) tmpchanlocs = EEG.chanlocs; indelec = strmatch( firstelec, { tmpchanlocs.labels }); if isempty(indelec), elecrange = 1:EEG.nbchan; else elecrange = 1:(indelec-1); end; else elecrange = 1:EEG.nbchan; end; elecrange = deblank(vararg2str(elecrange)); %elecrange = elecrange(2:end-1); % promptstr = { 'Channel range' ... % 'Frequency range (Hz)' ... % 'Frequency threshold in dB' ... % 'Epoch segment length (s)' ... % 'Minimum number of contiguous epochs' ... % 'Add trails before and after regions (s)' ... % }; % initstr = { elecrange '20 40' '10' '0.5' '4' '0.25' }; % result = inputdlg2(promptstr, 'Reject portions of continuous data - pop_rejcont', 1, initstr); uilist = { { 'style' 'text' 'string' 'Channel range' } ... { 'style' 'edit' 'string' elecrange } ... { 'style' 'text' 'string' 'Frequency range (Hz)' } ... { 'style' 'edit' 'string' '20 40' } ... { 'style' 'text' 'string' 'Frequency threshold in dB' } ... { 'style' 'edit' 'string' '10' } ... { 'style' 'text' 'string' 'Epoch segment length (s)' } ... { 'style' 'edit' 'string' '0.5' } ... { 'style' 'text' 'string' 'Minimum number of contiguous epochs' } ... { 'style' 'edit' 'string' '4' } ... { 'style' 'text' 'string' 'Add trails before and after regions (s)' } ... { 'style' 'edit' 'string' '0.25' } ... { 'style' 'text' 'string' 'Use hanning window before computing FFT' } ... { 'style' 'checkbox' 'string' '' 'value' 1 } ... }; geom = { [2 1] [2 1] [2 1] [2 1] [2 1] [2 1] [2 1] }; result = inputgui('uilist', uilist, 'geometry', geom); if length( result ) == 0 return; end; options = { 'elecrange' str2num(result{1}) ... 'freqlimit' str2num(result{2}) ... 'threshold' str2double(result{3}) ... 'epochlength' str2double(result{4}) ... 'contiguous' str2double(result{5}) ... 'addlength' str2double(result{6}) ... 'taper' fastif(result{7}, 'hamming', 'none') }; else options = varargin; end; opt = finputcheck(options, { 'threshold' { 'real';'cell' } [] 10; 'freqlimit' { 'real';'cell' } [] [35 128]; 'elecrange' 'real' [] [1:EEG.nbchan]; 'rejectori' 'real' [] []; 'contiguous' 'real' [] 4; 'addlength' 'real' [] 0.25; 'precompstruct' 'struct' [] struct([]); 'eegplot' 'string' { 'on';'off' } 'off'; 'onlyreturnselection' 'string' { 'on';'off' } 'off'; 'verbose' 'string' { 'on';'off' } 'on'; 'taper' 'string' { 'none' 'hamming' } 'none'; 'overlap' 'real' [] 0.25; 'epochlength' 'real' [] 0.5 }, 'pop_rejcont'); if isstr(opt), error(opt); end; if ~iscell(opt.threshold) && length(opt.threshold) == 2 && ... iscell(opt.freqlimit) && length(opt.freqlimit) == 2 opt.threshold = { opt.threshold(1) opt.threshold(2) }; end; if ~iscell(opt.threshold), opt.threshold = { opt.threshold }; end; if ~iscell(opt.freqlimit), opt.freqlimit = { opt.freqlimit }; end; %EEG.event = []; grouplen = opt.contiguous/2*opt.epochlength*EEG.srate+1; % maximum number of points for grouping regions color = [ 0 0.9 0]; % color of rejection window NEWEEG = EEG; if isempty(opt.precompstruct) % compute power spectrum % ---------------------- % average reference % NEWEEG.data(opt.elecrange,:) = NEWEEG.data(opt.elecrange,:)-repmat(mean(NEWEEG.data(opt.elecrange,:),1), [length(opt.elecrange) 1]); % only keep boundary events % ------------------------- tmpevent = NEWEEG.event; if ~isempty(tmpevent) if isnumeric( tmpevent(1).type ) NEWEEG.event = []; else boundEvent = strmatch('boundary', { tmpevent.type }, 'exact'); NEWEEG.event = NEWEEG.event(boundEvent); end; end; [TMPNEWEEG] = eeg_regepochs(NEWEEG, opt.overlap, [0 opt.epochlength], NaN); %[TMPNEWEEG indices] = pop_rejspec(TMPNEWEEG, 1, [1:64], -100, 15, 30, 45, 0, 0); %rejepoch = find(indices); tmpdata = TMPNEWEEG.data; if strcmpi(opt.taper, 'hamming'), tmpdata = bsxfun(@times, tmpdata, hamming(size(TMPNEWEEG.data,2))'); end; tmp = fft(tmpdata, [], 2); freqs = linspace(0, TMPNEWEEG.srate/2, size(tmp,2)/2); freqspectrum = freqs(2:end); % remove DC (match the output of PSD) tmp = tmp(:,2:size(tmp,2)/2,:); warning('off', 'MATLAB:log:logOfZero'); tmpspec = 10*log10(abs(tmp).^2); warning('on', 'MATLAB:log:logOfZero'); tmpspec = tmpspec - repmat( mean(tmpspec,3), [1 1 TMPNEWEEG.trials]); specdata = tmpspec; % compute mean spectrum % --------------------- meanspectrum = nan_mean(specdata(opt.elecrange, :, :), 1); precompstruct.spec = meanspectrum; precompstruct.freqs = freqspectrum; precompstruct.EEG = TMPNEWEEG; else meanspectrum = opt.precompstruct.spec; freqspectrum = opt.precompstruct.freqs; TMPNEWEEG = opt.precompstruct.EEG; precompstruct = opt.precompstruct; end; % apply threshold to average of all electrodes % -------------------------------------------- rejepoch = []; for iReject = 1:length(opt.threshold) threshold = opt.threshold{iReject}; freqLim = opt.freqlimit{iReject}; if length(threshold) == 1, threshold = [ -100 threshold ]; end; [I1 tmpRejEpoch NS Erej] = eegthresh( meanspectrum, size(meanspectrum,2), 1, threshold(1), threshold(2), [freqspectrum(1) freqspectrum(end)], freqLim(1), freqLim(2)); rejepoch = union_bc(rejepoch, tmpRejEpoch); if strcmpi(opt.verbose, 'on') fprintf('%d regions selected for rejection, threshold %3.2f-%3.2f dB, frequency limits %3.1f-%3.1f\n', length(tmpRejEpoch), threshold(1), threshold(2), freqLim(1), freqLim(2)); end; end; % build the winrej array for eegplot % ---------------------------------- winrej = []; if ~isempty(find(cellfun(@isempty, { TMPNEWEEG.event.epoch }) == 1)) error('Some events are not associated with any epoch'); end; tmpevent = TMPNEWEEG.event; allepoch = [ tmpevent.epoch ]; if ~isempty(rejepoch) for index = 1:length(rejepoch) eventepoch = find( rejepoch(index) == allepoch ); if strcmpi(TMPNEWEEG.event(eventepoch(1)).type, 'X') urevent = TMPNEWEEG.event(eventepoch(1)).urevent; lat = TMPNEWEEG.urevent(urevent).latency; winrej = [ winrej; lat lat+opt.epochlength*TMPNEWEEG.srate-1 color ]; %Erej(:,index)']; else error('Wrong type for epoch'); end; end; winrej(:,6:6+length(opt.elecrange)-1) = 0; end; % remove isolated regions and merge others % ---------------------------------------- merged = 0; isolated = 0; for index = size(winrej,1):-1:1 if size(winrej,1) >= index && winrej(index,2) - winrej(index,1) > grouplen, winrej(index,:) = []; isolated = isolated + 1; elseif index == 1 && size(winrej,1) > 1 && winrej(index+1,1) - winrej(index,2) > grouplen, winrej(index,:) = []; isolated = isolated + 1; elseif index == size(winrej,1) && size(winrej,1) > 1 && winrej(index,1) - winrej(index-1,2) > grouplen, winrej(index,:) = []; isolated = isolated + 1; elseif index > 1 && size(winrej,1) > 1 && index < size(winrej,1) && winrej(index+1,1) - winrej(index,2) > grouplen && ... winrej(index,1) - winrej(index-1,2) > grouplen winrej(index,:) = []; isolated = isolated + 1; elseif index < size(winrej,1) && size(winrej,1) > 1 && winrej(index+1,1) - winrej(index,2) <= grouplen winrej(index,2) = winrej(index+1,2); winrej(index+1,:) = []; merged = merged + 1; end; end; if strcmpi(opt.verbose, 'on') fprintf('%d regions merged\n', merged); fprintf('%d regions removed\n', isolated); end; % add time before and after each region % ------------------------------------- for index = 1:size(winrej,1) winrej(index,1) = max(1, winrej(index,1)-opt.addlength*EEG.srate); winrej(index,2) = min(EEG.pnts, winrej(index,2)+opt.addlength*EEG.srate); end; % plot result % ----------- if ~isempty(winrej) selectedregions = winrej(:,1:2); if strcmpi(opt.onlyreturnselection, 'off') % merge with initial regions if ~isempty(opt.rejectori) winrej(:,3) = 1; % color for iRow = 1:size(opt.rejectori,1) winrej(end+1,1:2) = opt.rejectori(iRow,:); winrej(end ,4) = 1; % color winrej(end ,5) = 1; % color end; end; command = '[EEG LASTCOM] = pop_select(EEG, ''nopoint'', TMPREJ(:,1:2)); eegh(LASTCOM); [ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET, ''study'', ~isempty(STUDY)+0); eegh(LASTCOM); eeglab redraw'; if nargin < 2 || strcmpi(opt.eegplot, 'on') eegplot(NEWEEG.data(opt.elecrange,:), 'srate', NEWEEG.srate, 'winrej', winrej, 'command', command, 'events', EEG.event, 'winlength', 50); disp('Green is overlap'); disp('Light blue is ORIGINAL rejection'); disp('Yellow is AUTOMATIC rejection'); else NEWEEG = pop_select(EEG, 'nopoint', round(selectedregions)); end; EEG = NEWEEG; else EEG = []; end; else selectedregions = []; if strcmpi(opt.verbose, 'on') disp('No region removed'); end; end; if nargout > 3 com = sprintf('EEG = pop_rejcont(EEG, %s);', vararg2str(options)); end;
github
lcnhappe/happe-master
pop_chansel.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_chansel.m
5,372
utf_8
4773a5a96563eba18577995430d93045
% pop_chansel() - pop up a graphic interface to select channels % % Usage: % >> [chanlist] = pop_chansel(chanstruct); % a window pops up % >> [chanlist strchannames cellchannames] = ... % pop_chansel(chanstruct, 'key', 'val', ...); % % Inputs: % chanstruct - channel structure. See readlocs() % % Optional input: % 'withindex' - ['on'|'off'] add index to each entry. May also a be % an array of indices % 'select' - selection of channel. Can take as input all the % outputs of this function. % 'selectionmode' - selection mode 'multiple' or 'single'. See listdlg2(). % % Output: % chanlist - indices of selected channels % strchannames - names of selected channel names in a concatenated string % (channel names are separated by space characters) % cellchannames - names of selected channel names in a cell array % % Author: Arnaud Delorme, CNL / Salk Institute, 3 March 2003 % Copyright (C) 3 March 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 [chanlist,chanliststr, allchanstr] = pop_chansel(chans, varargin); if nargin < 1 help pop_chansel; return; end; if isempty(chans), disp('Empty input'); return; end; if isnumeric(chans), for c = 1:length(chans) newchans{c} = num2str(chans(c)); end; chans = newchans; end; chanlist = []; chanliststr = {}; allchanstr = ''; g = finputcheck(varargin, { 'withindex' { 'integer';'string' } { [] {'on' 'off'} } 'off'; 'select' { 'cell';'string';'integer' } [] []; 'selectionmode' 'string' { 'single';'multiple' } 'multiple'}); if isstr(g), error(g); end; if ~isstr(g.withindex), chan_indices = g.withindex; g.withindex = 'on'; else chan_indices = 1:length(chans); end; % convert selection to integer % ---------------------------- if isstr(g.select) & ~isempty(g.select) g.select = parsetxt(g.select); end; if iscell(g.select) & ~isempty(g.select) if isstr(g.select{1}) tmplower = lower( chans ); for index = 1:length(g.select) matchind = strmatch(lower(g.select{index}), tmplower, 'exact'); if ~isempty(matchind), g.select{index} = matchind; else error( [ 'Cannot find ''' g.select{index} '''' ] ); end; end; end; g.select = [ g.select{:} ]; end; if ~isnumeric( g.select ), g.select = []; end; % add index to channel name % ------------------------- tmpstr = {chans}; if isnumeric(chans{1}) tmpstr = [ chans{:} ]; tmpfieldnames = cell(1, length(tmpstr)); for index=1:length(tmpstr), if strcmpi(g.withindex, 'on') tmpfieldnames{index} = [ num2str(chan_indices(index)) ' - ' num2str(tmpstr(index)) ]; else tmpfieldnames{index} = num2str(tmpstr(index)); end; end; else tmpfieldnames = chans; if strcmpi(g.withindex, 'on') for index=1:length(tmpfieldnames), tmpfieldnames{index} = [ num2str(chan_indices(index)) ' - ' tmpfieldnames{index} ]; end; end; end; [chanlist,tmp,chanliststr] = listdlg2('PromptString',strvcat('(use shift|Ctrl to', 'select several)'), ... 'ListString', tmpfieldnames, 'initialvalue', g.select, 'selectionmode', g.selectionmode); if tmp == 0 chanlist = []; chanliststr = ''; return; else allchanstr = chans(chanlist); end; % test for spaces % --------------- spacepresent = 0; if ~isnumeric(chans{1}) tmpstrs = [ allchanstr{:} ]; if ~isempty( find(tmpstrs == ' ')) | ~isempty( find(tmpstrs == 9)) spacepresent = 1; end; end; % get concatenated string (if index) % ----------------------- if strcmpi(g.withindex, 'on') | spacepresent if isnumeric(chans{1}) chanliststr = num2str(celltomat(allchanstr)); else chanliststr = ''; for index = 1:length(allchanstr) if spacepresent chanliststr = [ chanliststr '''' allchanstr{index} ''' ' ]; else chanliststr = [ chanliststr allchanstr{index} ' ' ]; end; end; chanliststr = chanliststr(1:end-1); end; end; return;
github
lcnhappe/happe-master
pop_importpres.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_importpres.m
7,397
utf_8
7bdcf2f321f530fa80e188b145a4807a
% pop_importpres() - append Presentation event file information into an EEGLAB dataset % The Presentation stimulus presentation program outputs an ascii % log file. This function merges existing EEG dataset events with % additional field information (fields) about those events contained % in the logfile. % Usage: % >> EEGOUT = pop_importpres( EEGIN, filename ); % >> EEGOUT = pop_importpres( EEGIN, filename, typefield, ... % latfield, durfield, align, 'key', 'val', ... ); % Inputs: % EEGIN - input dataset % logfilename - Presentation logfile name % % typefield - [string] type fieldname {default: 'code'} % latfield - [string] latency fieldname {default: 'time'} % durfield - [string] duration fieldname {default: 'none'} % align - [integer] alignment with pre-existing events % See >> help pop_importevent % 'key','val' - This function calls pop_importevent(). These are % optional arguments for this function (for event % alignment for instance). % Outputs: % EEGOUT - data structure with added Presentation logfile information % % Note: If there are pre-existing events in the input dataset, % this function will recalculate the latencies of the events % in the Presentation file, so that they match those % of the pre-existing events. % % Author: Arnaud Delorme, CNL / Salk Institute, 15 March 2002 % % Note: This function is backward compatible with its early versions % (before the input argument 'durfield' was introduced). % It can read the 'align' value as its 5th (not 6th) paramater. % % See also: eeglab(), pop_importevent() % Copyright (C) 13 March 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, command] = pop_importpres(EEG, filename, typefield, latfield, durfield, align, varargin); command = ''; if nargin < 1 help pop_importpres; return end; % decode input (and backward compatibility) % ----------------------------------------- if nargin < 5 durfield = ''; end; if nargin >= 5 & ~isstr(durfield) if nargin >= 6 varargin = { align varargin{:} }; end; align = durfield; durfield = ''; else if nargin < 6 align = 0; end; end; if nargin < 2 % ask user [filename, filepath] = uigetfile('*.log;*.LOG', 'Choose a Presentation file -- pop_importpres()'); drawnow; if filename == 0 return; end; filename = [filepath filename]; end; fields = loadtxt(filename, 'delim', 9, 'skipline', -2, 'nlines', 1, 'verbose', 'off'); % finding fields % -------------- if nargin > 1 if nargin < 3 typefield = 'code'; % backward compatibility latfield = 'time'; end; indtype = strmatch(lower(typefield), lower(fields)); indlat = strmatch(lower(latfield) , lower(fields)); if ~isempty(durfield) inddur = strmatch(lower(durfield) , lower(fields)); else inddur = 0; end; else indtype1 = strmatch('event type', lower(fields)); indtype2 = strmatch('code', lower(fields)); indtype = [ indtype1 indtype2 1]; indlatency = strmatch('time', lower(fields), 'exact'); indlatency = [ indlatency 1 ]; uilist = { { 'style' 'text' 'string' [ 'File field containing event types' 10 '' ] } ... { 'style' 'list' 'string' strvcat(fields) 'value' indtype(1) 'listboxtop' indtype(1)} ... { 'style' 'text' 'string' [ 'File field containing event latencies' 10 '' ] } ... { 'style' 'list' 'string' strvcat(fields) 'value' indlatency(1) 'listboxtop' indlatency(1) } ... { 'style' 'text' 'string' [ 'File field containing event durations' 10 '' ] } ... { 'style' 'list' 'string' strvcat({ 'None' fields{:} }) 'value' 1 'listboxtop' 1 } ... { } { 'style' 'text' 'string' 'Note: scroll lists then click to select field' } }; uigeom = { [2 1] [2 1] [2 1] 1 1 }; result = inputgui(uigeom, uilist, 'pophelp(''pop_importpres'')', 'Import presentation file - pop_importpres()', ... [], 'normal', [2 2 2 1 1]); if isempty(result), return; end; indtype = result{1}; indlat = result{2}; inddur = result{3}-1; typefield = fields{indtype}; latfield = fields{indlat}; if inddur ~= 0 durfield = fields{inddur}; else durfield = ''; end; end; if isempty(indtype) error(['Could not detect field ''' typefield ''', try importing the file as ASCII (use delimiter=9 (tab))']); end; if isempty(indlat) error(['Could not detect field ''' latfield ''', try importing the file as ASCII (use delimiter=9 (tab))']); end; disp(['Replacing field ''' typefield ''' by ''type'' for EEGLAB compatibility']); disp(['Replacing field ''' latfield ''' by ''latency'' for EEGLAB compatibility']); fields{indtype} = 'type'; fields{indlat} = 'latency'; if inddur ~= 0 fields{inddur} = 'duration'; end % check inputs % regularizing field names % ------------------------ for index = 1:length(fields) indspace = find(fields{index} == ' '); fields{index}(indspace) = '_'; indparen = find(fields{index} == ')'); if ~isempty(indparen) & indparen == length(fields{index}) % remove text for parenthesis indparen = find(fields{index} == '('); if indparen ~= 1 disp([ 'Renaming ''' fields{index} ''' to ''' fields{index}(1:indparen-1) ''' for Matlab compatibility' ]); fields{index} = fields{index}(1:indparen-1); else fields{index}(indspace) = '_'; end; else fields{index}(indspace) = '_'; indparen = find(fields{index} == '('); fields{index}(indspace) = '_'; end; end; % find if uncertainty is duplicated % --------------------------------- induncert = strmatch('uncertainty', lower(fields), 'exact'); if length(induncert) > 1 fields{induncert(2)}= 'Uncertainty2'; disp('Renaming second ''Uncertainty'' field'); end; % import file % ----------- if isempty(EEG.event), align = NaN; end; %EEG = pop_importevent(EEG, 'append', 'no', 'event', filename, 'timeunit', 1E-4, 'skipline', -3, ... % 'delim', 9, 'align', align, 'fields', fields, varargin{:}); EEG = pop_importevent(EEG, 'event', filename, 'timeunit', 1E-4, 'skipline', -3, ... 'delim', 9, 'align', align, 'fields', fields, varargin{:}); command = sprintf('EEG = pop_importpres(%s, %s);', inputname(1), vararg2str({ filename typefield latfield durfield align })); return;
github
lcnhappe/happe-master
pop_rejkurt.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_rejkurt.m
11,390
utf_8
869a31b3c44d2c5f44d64a48a4d0b935
% pop_rejkurt() - rejection of artifact in a dataset using kurtosis % of activity (i.e. to detect peaky distribution of % activity). % % Usage: % >> pop_rejkurt( INEEG, typerej) % pop-up interative window mode % >> [OUTEEG, locthresh, globthresh, nrej] = ... % = pop_rejkurt( INEEG, typerej, elec_comp, ... % locthresh, globthresh, superpose, reject, vistype); % % Graphical interface: % "Electrode|Component" - [edit box] electrodes or components indices to take % into consideration for rejection. Same as the 'elec_comp' % parameter from the command line. % "Single-channel limit|Single-component limit" - [edit box] kurtosis limit % in terms of standard-dev. Same as 'locthresh' command line % parameter. % "All-channel limit|All-component limit" - [edit box] kurtosis limit % in terms of standard-dev (all channel regrouped). Same as % 'globthresh' command line parameter. % "visualization type" - [popup menu] can be either 'REJECTRIALS'|'EEGPLOT'. % This correspond to the command line input option 'vistype'. % "Display with previous rejection(s)" - [checkbox] This checkbox set the % command line input option 'superpose'. % "Reject marked trial(s)" - [checkbox] This checkbox set the command % line input option 'reject'. % % Inputs: % INEEG - Input dataset % typerej - Type of rejection (0 = independent components; 1 = eeg % data). Default is 1. For independent components, before % thresholding, the activity is normalized for each % component. % elec_comp - [e1 e2 ...] electrodes (number) to take into % consideration for rejection. % locthresh - Activity kurtosis limit in terms of standard-dev. % globthresh - Global limit (for all channel). Same unit as above. % superpose - [0] do not superpose pre-labelling with previous % pre-labelling (stored in the dataset). [1] consider % both pre-labelling (using different colors). Default is [0]. % reject - [0] do not reject labelled trials (but still % store the labels. [1] reject labelled trials. % Default is [1]. % vistype - Visualization type. [0] calls rejstatepoch() and [1] calls % eegplot() default is [0].When added to the command line % call it will not display the plots if the option 'plotflag' % is not set. % topcommand - [] Deprecated argument , keep to ensure backward compatibility % plotflag - [1,0] [1]Turns plots 'on' from command line, [0] off. % (Note for developers: When called from command line % it will make 'calldisp = plotflag') {Default: 0} % % Outputs: % OUTEEG - output dataset with updated kurtosis array % locthresh - electrodes probability of activity thresholds in terms % of standard-dev. % globthresh - global threshold (where all electrode activity are % regrouped). % nrej - number of rejected sweeps % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: rejkurt(), rejstatepoch(), pop_rejepoch(), eegplot(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-07-02 added srate argument to eegplot call -ad % 03-08-02 add eeglab options -ad function [EEG, locthresh, globthresh, nrej, com] = pop_rejkurt( EEG, icacomp, elecrange, ... locthresh, globthresh, superpose, reject, vistype, topcommand, plotflag); nrej = []; com = ''; if nargin < 1 help pop_rejkurt; return; end; if nargin < 2 icacomp = 1; end; if exist('reject') ~= 1 reject = 1; end; if icacomp == 0 if isempty( EEG.icasphere ) ButtonName=questdlg( 'Do you want to run ICA now ?', ... 'Confirmation', 'NO', 'YES', 'YES'); switch ButtonName, case 'NO', disp('Operation cancelled'); return; case 'YES', [ EEG com ] = pop_runica(EEG); end % switch end; end; if nargin < 3 % which set to save % ----------------- promptstr = { [ fastif(icacomp, 'Electrode', 'Component') ' (indices; Ex: 2 6:8 10):' ], ... [ fastif(icacomp, 'Single-channel', 'Single-component') ' limit(s) (std. dev(s): Ex: 2 2 2 2.5):'], ... [ fastif(icacomp, 'All-channel', 'All-component') ' limit(s) (std. dev(s): Ex: 2.1 2 2 2):'], ... 'Visualization mode',... 'Display previous rejection marks', ... 'Reject marked trial(s)'}; inistr = { fastif(icacomp, ['1:' int2str(EEG.nbchan)], ['1:' int2str(size(EEG.icaweights,1))])... fastif(icacomp, '3', '5'), ... fastif(icacomp, '3', '5'), ... ''... '1', ... '0',}; vismodelist= {'REJECTTRIALS','EEGPLOT'}; g1 = [1 0.1 0.75]; g2 = [1 0.26 0.9]; g3 = [1 0.22 0.85]; geometry = {g1 g1 g1 g2 [1] g3 g3}; uilist = {... { 'Style', 'text', 'string', promptstr{1}} {} { 'Style','edit' , 'string' ,inistr{1} 'tag' 'cpnum'}... { 'Style', 'text', 'string', promptstr{2}} {} { 'Style','edit' , 'string' ,inistr{2} 'tag' 'singlelimit'}... { 'Style', 'text', 'string', promptstr{3}} {} { 'Style','edit' , 'string' ,inistr{3} 'tag' 'alllimit'}... { 'Style', 'text', 'string', promptstr{4}} {} { 'Style','popupmenu' , 'string' , vismodelist 'tag' 'specmethod' }... {}... { 'Style', 'text', 'string', promptstr{5}} {} { 'Style','checkbox' ,'string' ,' ' 'value' str2double(inistr{5}) 'tag' 'rejmarks' }... { 'Style', 'text', 'string', promptstr{6}} {} { 'Style','checkbox' ,'string' ,' ' 'value' str2double(inistr{6}) 'tag' 'rejtrials'} ... }; figname = fastif(~icacomp, 'Trial rejection using comp. kurtosis -- pop_rejkurt()', 'Trial rejection using data kurtosis -- pop_rejkurt()'); result = inputgui( geometry,uilist,'pophelp(''pop_rejkurt'');', figname); size_result = size( result ); if size_result(1) == 0, locthresh = []; globthresh = []; return; end; elecrange = result{1}; locthresh = result{2}; globthresh = result{3}; switch result{4}, case 1, vistype=0; otherwise, vistype=1; end; superpose = result{5}; reject = result{6}; end; if ~exist('vistype','var'), vistype = 0; end; if ~exist('reject','var'), reject = 0; end; if ~exist('superpose','var'), superpose = 1; end; if isstr(elecrange) % convert arguments if they are in text format calldisp = 1; elecrange = eval( [ '[' elecrange ']' ] ); locthresh = eval( [ '[' locthresh ']' ] ); globthresh = eval( [ '[' globthresh ']' ] ); else calldisp = 0; end; if exist('plotflag','var') && ismember(plotflag,[1,0]) calldisp = plotflag; else plotflag = 0; end if isempty(elecrange) error('No electrode selectionned'); end; % compute the joint probability % ----------------------------- if icacomp == 1 fprintf('Computing kurtosis for channels...\n'); tmpdata = eeg_getdatact(EEG); if isempty(EEG.stats.kurtE ) [ EEG.stats.kurtE rejE ] = rejkurt( tmpdata, locthresh, EEG.stats.kurtE, 1); end; [ tmp rejEtmp ] = rejkurt( tmpdata(elecrange, :,:), locthresh, EEG.stats.kurtE(elecrange, :), 1); rejE = zeros(EEG.nbchan, size(rejEtmp,2)); rejE(elecrange,:) = rejEtmp; fprintf('Computing all-channel kurtosis...\n'); tmpdata2 = permute(tmpdata, [3 1 2]); tmpdata2 = reshape(tmpdata2, size(tmpdata2,1), size(tmpdata2,2)*size(tmpdata2,3)); [ EEG.stats.kurt rej ] = rejkurt( tmpdata2, globthresh, EEG.stats.kurt, 1); else fprintf('Computing joint probability for components...\n'); % test if ICA was computed % ------------------------ icaacttmp = eeg_getica(EEG); if isempty(EEG.stats.icakurtE ) [ EEG.stats.icakurtE rejE ] = rejkurt( icaacttmp, locthresh, EEG.stats.icakurtE, 1); end; [ tmp rejEtmp ] = rejkurt( icaacttmp(elecrange, :,:), locthresh, EEG.stats.icakurtE(elecrange, :), 1); rejE = zeros(size(icaacttmp,1), size(rejEtmp,2)); rejE(elecrange,:) = rejEtmp; fprintf('Computing global joint probability...\n'); tmpdata = permute(icaacttmp, [3 1 2]); tmpdata = reshape(tmpdata, size(tmpdata,1), size(tmpdata,2)*size(tmpdata,3)); [ EEG.stats.icakurt rej] = rejkurt( tmpdata, globthresh, EEG.stats.icakurt, 1); end; rej = rej' | max(rejE, [], 1); fprintf('%d/%d trials marked for rejection\n', sum(rej), EEG.trials); if calldisp if vistype == 1 % EEGPLOT ------------------------- if icacomp == 1 macrorej = 'EEG.reject.rejkurt'; macrorejE = 'EEG.reject.rejkurtE'; else macrorej = 'EEG.reject.icarejkurt'; macrorejE = 'EEG.reject.icarejkurtE'; end; colrej = EEG.reject.rejkurtcol; eeg_rejmacro; % script macro for generating command and old rejection arrays if icacomp == 1 eegplot( tmpdata(elecrange,:,:), 'srate', ... EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}); else eegplot( icaacttmp(elecrange,:,:), 'srate', ... EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}); end; else % REJECTRIALS ------------------------- if icacomp == 1 [ rej, rejE, n, locthresh, globthresh] = ... rejstatepoch( tmpdata, EEG.stats.kurtE(elecrange,:), 'global', 'on', 'rejglob', EEG.stats.kurt, ... 'threshold', locthresh, 'thresholdg', globthresh, 'normalize', 'off' ); else [ rej, rejE, n, locthresh, globthresh] = ... rejstatepoch( icaacttmp, EEG.stats.icakurtE(elecrange,:), 'global', 'on', 'rejglob', EEG.stats.icakurt, ... 'threshold', locthresh, 'thresholdg', globthresh, 'normalize', 'off' ); end; nrej = n; end; else % compute rejection locally rejtmp = max(rejE(elecrange,:),[],1); rej = rejtmp | rej; nrej = sum(rej); fprintf('%d trials marked for rejection\n', nrej); end; if ~isempty(rej) if icacomp == 1 EEG.reject.rejkurt = rej; EEG.reject.rejkurtE = rejE; else EEG.reject.icarejkurt = rej; EEG.reject.icarejkurtE = rejE; end; if reject EEG = pop_rejepoch(EEG, rej, 0); end; end; nrej = sum(rej); com = [ com sprintf('%s = pop_rejkurt(%s,%s);', inputname(1), ... inputname(1), vararg2str({icacomp,elecrange,locthresh,globthresh,superpose,reject,vistype, [], plotflag})) ]; if nargin < 3 & nargout == 2 locthresh = com; end; return;
github
lcnhappe/happe-master
pop_writelocs.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_writelocs.m
8,336
utf_8
fe5e26b45aeae126898af6bfd87633bd
% pop_writelocs() - load a EGI EEG file (pop out window if no arguments). % % Usage: % >> EEG = pop_writelocs(chanstruct); % a window pops up % >> EEG = pop_writelocs(chanstruct, filename, 'key', val, ...); % % Inputs: % chanstruct - channel structure. See readlocs() % filename - Electrode location file name % 'key',val - same as writelocs() % % Author: Arnaud Delorme, CNL / Salk Institute, 17 Dec 2002 % % See also: writelocs() % Copyright (C) Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function com = pop_writelocs(chans, filename, varargin); com = ''; if nargin < 1 help pop_writelocs; return; end; if isfield(chans, 'shrink') chans = rmfield(chans, 'shrink'); disp('Warning: shrink factor ignored'); end; disp('WARNING: ELECTRODE COORDINATES MUST BE WITH NOSE ALONG THE +X DIMENSION TO BE EXPORTED') disp(' IF NOT, THE EXPORTED FILE COORDINATES MAY BE INNACURATE') % get infos from readlocs % ----------------------- [chanformat listcolformat] = readlocs('getinfos'); chanformat(end) = []; listcolformat(end) = []; % remove chanedit chanformat(end) = []; listcolformat(end) = []; % remove chanedit indformat = []; for index = 1:length(chanformat), if ~isstr(chanformat(index).importformat) indformat = [ indformat index ]; end; if isempty(chanformat(index).skipline), chanformat(index).skipline = 0; end; end; listtype = { chanformat(indformat).type }; formatinfo = { chanformat(indformat).importformat }; formatskip = [ chanformat(indformat).skipline ]; %[listtype formatinfo listcolformat formatskip] = readlocs('getinfoswrite'); listtype{end+1} = 'custom'; formatinfo{end+1} = {}; formatskip = [ formatskip 0]; if nargin < 2 updatefields = [ 'tmpdata = get(gcf, ''userdata'');' ... 'tmpobj = findobj(gcf, ''tag'', ''list2'');' ... 'set(tmpobj, ''string'', strvcat(tmpdata{2}));' ... 'clear tmpobj tmpdata;' ]; addfieldcom = [ 'tmpdata = get(gcbf, ''userdata'');' ... 'tmpobj = findobj(gcf, ''tag'', ''list1'');' ... 'tmpdata{2}{end+1} = tmpdata{1}{get(tmpobj, ''value'')};' ... 'set(gcbf, ''userdata'', tmpdata);' ... updatefields ]; rmfieldcom = [ 'tmpdata = get(gcbf, ''userdata'');' ... 'tmpobj = findobj(gcbf, ''tag'', ''list2'');' ... 'try, tmpdata{2}(get(tmpobj, ''value'')) = [];' ... ' set(tmpobj, ''value'', 1);' ... 'catch, end;' ... 'set(gcbf, ''userdata'', tmpdata);' ... updatefields ]; filetypecom = [ 'tmpdata = get(gcf, ''userdata'');' ... 'tmpobj = findobj(gcf, ''tag'', ''formatlist'');' ... 'tmpval = get(tmpobj, ''value'');' ... 'try, tmpdata{2} = tmpdata{3}{tmpval}; catch, end;' ... %try and catch for custom 'set(gcf, ''userdata'', tmpdata);' ... updatefields ... 'tmpdata = get(gcf, ''userdata'');' ... 'tmpobj1 = findobj(gcf, ''tag'', ''insertcol'');' ... % the lines below 'tmpobj2 = findobj(gcf, ''tag'', ''inserttext'');' ... % update the checkbox 'try, ' ... % and the edit text box ' if tmpdata{4}(tmpval) == 2,' ... ' set(tmpobj1, ''value'', 1);' ... ' else,' ... ' set(tmpobj1, ''value'', 0);' ... ' end;' ... ' if tmpval == 1,' ... % besa only ' set(tmpobj2, ''string'', ''' int2str(length(chans)) ''');' ... ' else,' ... ' set(tmpobj2, ''string'', '''');' ... ' end;' ... 'catch, end;' ... % catch for custom case 'tmpobj = findobj(gcf, ''userdata'', ''setfield'');' ... 'if tmpval == ' int2str(length(listtype)) ',' ... % disable if non-custom type ' set(tmpobj, ''enable'', ''on'');' ... 'else,' ... ' set(tmpobj, ''enable'', ''off'');' ... 'end; clear tmpobj tmpobj2 tmpdata tmpval;' ]; geometry = { [1 1 1] [1 1] [1] [1 1 1] [1 1] [1 1 1] [1 0.3 0.7] [1] [1] }; listui = { ... { 'style' 'text' 'string' 'Filename' } ... { 'style' 'edit' 'string' '' 'tag' 'filename' 'horizontalalignment' 'left' } ... { 'style' 'pushbutton' 'string' 'Browse' 'callback' ... [ '[tmpfile tmppath] = uiputfile(''*'', ''Exporting electrode location file -- pop_writelocs()'');' ... 'set(findobj(gcbf, ''tag'', ''filename''), ''string'', char([tmppath tmpfile ]));' ... 'clear tmpfile tmppath;' ] } ... { 'style' 'text' 'string' strvcat('Select output file type', ' ', ' ') } ... { 'style' 'listbox' 'tag' 'formatlist' 'string' strvcat(listtype) ... 'value' length(listtype) 'callback' filetypecom } ... { 'style' 'text' 'string' 'Select fields to export below' } ... { } { 'style' 'pushbutton' 'string' '-> ADD' 'callback' addfieldcom 'userdata' 'setfield' } { } ... { 'style' 'listbox' 'tag' 'list1' 'string' strvcat(fieldnames(chans)) 'userdata' 'setfield' } ... { 'style' 'listbox' 'tag' 'list2' 'string' '' 'userdata' 'setfield2' } ... { } { 'style' 'pushbutton' 'string' 'REMOVE <-' 'callback' rmfieldcom 'userdata' 'setfield' } { } ... { 'style' 'text' 'string' 'Insert column names' } ... { 'style' 'checkbox' 'tag' 'insertcol' 'value' 1 'userdata' 'setfield' } { } ... { 'style' 'text' 'string' 'Enter custom header below' } ... { 'style' 'edit' 'userdata' 'setfield' 'tag' 'inserttext' 'horizontalalignment' 'left' 'max' 2 } ... }; inputgui(geometry, listui, 'pophelp(''writelocs'');', ... 'Exporting electrode location file -- pop_writelocs()', { fieldnames(chans) {} formatinfo formatskip }, 'plot', [1 3 1 1 3 1 1 1 3 ]); fig = gcf; % set default format tmpobj = findobj(fig, 'tag', 'formatlist'); set(tmpobj, 'value', 6); eval(get(tmpobj, 'callback')); res = inputgui(geometry, listui, 'pophelp(''writelocs'');', ... 'Exporting electrode location file -- pop_writelocs()', { listcolformat {} formatinfo formatskip }, fig, [1 3 1 1 3 1 1 1 3 ]); if gcf ~= fig, return; end; exportfields = get(fig, 'userdata'); exportfields = exportfields{2}; close(fig); % decode the inputs filename = res{1}; if isempty(filename), errordlg2('Error: Empty file name', 'Error'); return; end; options = { 'filetype' listtype{res{2}} 'format' exportfields ... 'header' fastif(res{5}, 'on', 'off') 'customheader' res{6} }; else options = varargin; end; % generate history % ---------------- if isempty(inputname(1)) % not a variable name -> probably the structure from pop_chanedit writelocs(chans, filename, options{:}); com = sprintf('pop_writelocs( EEG.chanlocs, ''%s'', %s);', filename, vararg2str(options)); else if strcmpi(inputname(1), 'chantmp') % do not write file (yet) com = sprintf('pop_writelocs( chans, ''%s'', %s);', filename, vararg2str(options)); else writelocs(chans, filename, options{:}); com = sprintf('pop_writelocs( %s, ''%s'', %s);', inputname(1), filename, vararg2str(options)); end; end;
github
lcnhappe/happe-master
eeg_mergelocs.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_mergelocs.m
4,253
utf_8
9aea0945e66cf1f13747a871668c7963
% eeg_mergelocs() - merge channel structure while preserving channel % order % % >> mergedlocs = eeg_mergelocs(loc1, loc2, loc3, ...); % % Inputs: % loc1 - EEGLAB channel location structure % loc2 - second EEGLAB channel location structure % % Output: % mergedlocs - merged channel location structure % warning - [0|1] dissimilar structures found (0=false, 1=true) % % Author: Arnaud Delorme, August 2006 % Copyright (C) Arnaud Delorme, CERCO, 2006, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [alllocs warn] = eeg_mergelocs(varargin) persistent warning_shown; warn = 0; try % sort by length % -------------- len = cellfun(@length, varargin); [tmp so] = sort(len, 2, 'descend'); varargin = varargin(so); alllocs = varargin{1}; for index = 2:length(varargin) % fuse while preserving order (assumes the same channel order) % ------------------------------------------------------------ tmplocs = varargin{index}; newlocs = myunion(alllocs, tmplocs); if length(newlocs) > length(union({ alllocs.labels }, { tmplocs.labels })) warn = 1; if isempty(warning_shown) disp('Warning: different channel montage or electrode order for the different datasets'); warning_shown = 1; end; % trying to preserve order of the longest array %---------------------------------------------- if length(alllocs) < length(tmplocs) tmp = alllocs; alllocs = tmplocs; tmplocs = tmp; end; allchans = { alllocs.labels tmplocs.labels }; [uniquechan ord1 ord2 ] = unique_bc( allchans ); [tmp rminds] = intersect_bc( uniquechan, { alllocs.labels }); ord1(rminds) = []; tmplocsind = ord1-length(alllocs); newlocs = [ alllocs tmplocs(tmplocsind) ]; end; alllocs = newlocs; end; catch, % temporary fix for dissimilar structures % should check channel structure consistency instead % using checkchan function disp('Channel merging warning: dissimilar fields in the two structures'); [alllocs warn ] = eeg_mergelocs_diffstruct(varargin{:}); end; % Checking consistency of chanlocs alllocs = eeg_checkchanlocs(alllocs); % union of two channel location structure % without loosing the order information % --------------------------------------- function alllocs = myunion(locs1, locs2) labs1 = { locs1.labels }; labs2 = { locs2.labels }; count1 = 1; count2 = 1; count3 = 1; alllocs = locs1; alllocs(:) = []; while count1 <= length(locs1) || count2 <= length(locs2) if count1 > length(locs1) alllocs(count3) = locs2(count2); count2 = count2 + 1; count3 = count3 + 1; elseif count2 > length(locs2) alllocs(count3) = locs1(count1); count1 = count1 + 1; count3 = count3 + 1; elseif strcmpi(labs1{count1}, labs2{count2}) alllocs(count3) = locs1(count1); count1 = count1 + 1; count2 = count2 + 1; count3 = count3 + 1; elseif isempty(strmatch(labs1{count1}, labs2, 'exact')) alllocs(count3) = locs1(count1); count1 = count1 + 1; count3 = count3 + 1; else alllocs(count3) = locs2(count2); count2 = count2 + 1; count3 = count3 + 1; end; end;
github
lcnhappe/happe-master
pop_plottopo.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_plottopo.m
4,700
utf_8
dc19c8e12f6b42f992ddfe25d0489039
% pop_plottopo() - plot one or more concatenated multichannel data epochs % in a topographic array format using plottopo() % Usage: % >> pop_plottopo( EEG ); % pop-up % >> pop_plottopo( EEG, channels ); % >> pop_plottopo( EEG, channels, title, singletrials); % >> pop_plottopo( EEG, channels, title, singletrials, axsize, ... % 'color', ydir, vert); % % Inputs: % EEG - input dataset % channels - indices of channels to plot % title - plot title. Default is none. % singletrials - [0|1], 0 plot average, 1 plot individual % single trials. Default is 0. % others... - additional plottopo arguments {'axsize', 'color', 'ydir' % 'vert'} (see >> help plottopo) % % Author: Arnaud Delorme, CNL / Salk Institute, 10 March 2002 % % See also: plottopo() % Copyright (C) 10 March 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 02-16-02 text interface editing -sm & ad % 03-18-02 added title -ad & sm % 03-30-02 added single trial capacities -ad function com = pop_plottopo( EEG, channels, plottitle, singletrials, varargin); com = ''; if nargin < 1 help pop_plottopo; return; end; if isempty(EEG.chanlocs) fprintf('Cannot plot without knowing channel locations. Use Edit/Dataset info\n'); return; end; if nargin < 2 uilist = { { 'style' 'text' 'string' 'Channels to plot' } ... { 'style' 'edit' 'string' [ '1:' num2str( EEG.nbchan ) ] 'tag' 'chan' } ... { 'style' 'text' 'string' 'Plot title' } ... { 'style' 'edit' 'string' fastif(isempty(EEG.setname), '',EEG.setname) 'tag' 'title' } ... { 'style' 'text' 'string' 'Plot single trials' } ... { 'style' 'checkbox' 'string' '(set=yes)' 'tag' 'cbst' } ... { 'style' 'text' 'string' 'Plot in rect. array' } ... { 'style' 'checkbox' 'string' '(set=yes)' 'tag' 'cbra' } ... { 'style' 'text' 'string' 'Other plot options (see help)' } ... { 'style' 'edit' 'string' '''ydir'', 1' 'tag' 'opt' } }; geometry = { [1 1] [1 1] [1 1] [1 1] [1 1] }; [result userdata tmphalt restag ] = inputgui( 'uilist', uilist, 'geometry', geometry, 'helpcom', 'pophelp(''pop_plottopo'')', 'title', 'Topographic ERP plot - pop_plottopo()'); if length(result) == 0 return; end; channels = eval( [ '[' restag.chan ']' ] ); plottitle = restag.title; singletrials = restag.cbst; addoptions = eval( [ '{' restag.opt '}' ] ); rect = restag.cbra; figure('name', ' plottopo()'); options ={ 'frames' EEG.pnts 'limits' [EEG.xmin EEG.xmax 0 0]*1000 ... 'title' plottitle 'chans' channels addoptions{:} }; if ~rect options = { options{:} 'chanlocs' EEG.chanlocs }; end; else options ={ 'chanlocs' EEG.chanlocs 'frames' EEG.pnts 'limits' [EEG.xmin EEG.xmax 0 0]*1000 ... 'title' plottitle 'chans' channels varargin{:}}; addoptions = {}; end; % adapt frames to time limit. if any(strcmp(addoptions,'limits')) addoptions{end+1} = 'frames'; ilimits = find(strcmp(addoptions,'limits'))+1; timelims = addoptions{ilimits}(1:2); addoptions{end+1} = round(diff(timelims/1000)*EEG.srate); end try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if exist('plottitle') ~= 1 plottitle = ''; end; if exist('singletrials') ~= 1 singletrials = 0; end; if singletrials plottopo( EEG.data, options{:} ); else plottopo( mean(EEG.data,3), options{:} ); end; if ~isempty(addoptions) com = sprintf('figure; pop_plottopo(%s, %s, ''%s'', %d, %s);', ... inputname(1), vararg2str(channels), plottitle, singletrials, vararg2str(addoptions)); else com = sprintf('figure; pop_plottopo(%s, %s, ''%s'', %d);', ... inputname(1), vararg2str(channels), plottitle, singletrials); end; return;
github
lcnhappe/happe-master
pop_loaddat.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_loaddat.m
3,543
utf_8
fe210f46e8ff2314b39fb77ae8b3945b
% pop_loaddat() - merge a neuroscan DAT file with input dataset % (pop out window if no arguments). % % Usage: % >> OUTEEG = pop_loaddat( INEEG ); % pop-up window mode % >> OUTEEG = pop_loaddat( INEEG, filename, no_rt); % % Graphic interfance: % "Code signifying no event ..." - [edit box] reaction time % no event code. See 'no_rt' command line equivalent % help. % Inputs: % filename - file name % INEEG - input EEGLAB data structure % no_rt - no reaction time integer code (ex: 1000). Since % a number has to be defined for each reaction % time, epochs with no reaction time usually have % a stereotyped reaction time value (such as 1000). % Default none. % Outputs: % OUTEEG - EEGLAB data structure % % Author: Arnaud Delorme, CNL/Salk Institute, 2001 % % See also: loaddat(), 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 % 13/02/02 removed the no latency option -ad function [EEG, command] = pop_loaddat(EEG, filename, no_rt); command = ''; if nargin < 1 help pop_loaddat; return; end; if nargin < 2 % ask user [filename, filepath] = uigetfile('*.DAT', 'Choose a DAT file -- pop_loaddat'); drawnow; if filename == 0 return; end; result = inputdlg2( { strvcat('Code signifying no event in a trial ([]=none)', ... '(none=all latencies are imported)')}, ... 'Load Neuroscan DATA file -- pop_loaddat()', 1, {'1000'}, 'pop_loaddat'); if length(result) == 0 return; end; no_rt = eval( result{1} ); end; if exist('no_rt') ~= 1 | isempty(no_rt) no_rt = NaN; end; % load datas % ---------- if exist('filepath') fullFileName = sprintf('%s%s', filepath, filename); else fullFileName = filename; end; disp('Loading dat file...'); [typeeeg, rt, response, n] = loaddat( fullFileName ); if n ~= EEG.trials error('pop_loaddat, number of trials in input dataset and DAT file different, aborting'); end; for index = 1:length(EEG.event) EEG.event(index).eegtype = typeeeg (EEG.event(index).epoch); EEG.event(index).response = response(EEG.event(index).epoch); end; for index = 1:n if rt(index) ~= no_rt EEG.event(end+1).type = 'rt'; EEG.event(end).latency = eeg_lat2point(rt(index)/1000, index, EEG.srate, [EEG.xmin EEG.xmax]); EEG.event(end).epoch = index; EEG.event(end).eegtype = typeeeg(index); EEG.event(end).response = response(index); end end; tmpevent = EEG.event; tmp = [ tmpevent.latency ]; [tmp indexsort] = sort(tmp); EEG.event = EEG.event(indexsort); EEG = eeg_checkset(EEG, 'eventconsistency'); command = sprintf('%s = pop_loaddat(%s, %s, %d);', inputname(1), inputname(1), fullFileName, no_rt); return;
github
lcnhappe/happe-master
pop_crossf.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_crossf.m
8,682
utf_8
12df1d32f46458d3c4a9ed985725dd22
% pop_crossf() - Return estimates and plots of event-related spectral coherence % % Usage: % >> pop_crossf(EEG, typeproc, num1, num2, tlimits,cycles, % 'key1',value1,'key2',value2, ... ); % Inputs: % INEEG - Input EEG dataset % typeproc - Type of processing: % 1 = process two raw-data channels, % 0 = process two ICA components % num1 - First component or channel number % num2 - Second component or channel number % tlimits - [mintime maxtime] Sub-epoch time limits in ms % cycles - >0 -> Number of cycles in each analysis wavelet % 0 -> Use FFTs (with constant window length) % % Optional inputs: As for crossf(). See >> help crossf % % Outputs: Same as crossf(). No outputs are returned when a % window pops-up to ask for additional arguments % % Author: Arnaud Delorme, CNL / Salk Institute, 11 March 2002 % % See also: timef(), eeglab() % Copyright (C) 11 March 2002 [email protected], Arnaud Delorme, CNL / Salk Institute % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 03-18-02 added title -ad & sm % 04-04-02 added outputs -ad & sm function varargout = pop_crossf(EEG, typeproc, num1, num2, tlimits, cycles, varargin ); varargout{1} = ''; % display help if not enough arguments % ------------------------------------ if nargin < 2 help pop_crossf; return; end; lastcom = []; if nargin < 3 popup = 1; else popup = isstr(num1) | isempty(num1); if isstr(num1) lastcom = num1; end; end; % pop up window % ------------- if popup [txt vars] = gethelpvar('timef.m'); geometry = { [1 0.5 0.5] [1 0.5 0.5] [1 0.5 0.5] [1 0.5 0.5] [0.92 0.1 0.78] [1 0.5 0.5] [1 0.8 0.2] [1] [1 1]}; uilist = { { 'Style', 'text', 'string', fastif(typeproc, 'First channel number', 'First component number'), 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,3,[],'1') } {} ... { 'Style', 'text', 'string', fastif(typeproc, 'Second channel number', 'Second component number'), 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,4,[],'2') } {} ... { 'Style', 'text', 'string', 'Epoch time range [min max] (msec)', 'fontweight', 'bold', ... 'tooltipstring', 'Sub epoch time limits' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,5,[],[ int2str(EEG.xmin*1000) ' ' int2str(EEG.xmax*1000) ]) } {} ... { 'Style', 'text', 'string', 'Wavelet cycles (0->FFT, see >> help timef)', 'fontweight', 'bold', ... 'tooltipstring', context('cycles',vars,txt) } ... { 'Style', 'edit', 'string', getkeyval(lastcom,6,[],'3 0.5') } {} ... { 'Style', 'text', 'string', '[set]->Linear coher / [unset]->Phase coher', 'fontweight', 'bold', ... 'tooltipstring', ['Compute linear inter-trial coherence (coher)' 10 ... 'OR Amplitude-normalized inter-trial phase coherence (phasecoher)'] } ... { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'phasecoher','present',1) } { } ... { 'Style', 'text', 'string', 'Bootstrap significance level (Ex: 0.01 -> 1%)', 'fontweight', 'bold', ... 'tooltipstring', context('alpha',vars,txt) } ... { 'Style', 'edit', 'string', getkeyval(lastcom,'alpha') } {} ... { 'Style', 'text', 'string', 'Optional timef() arguments (see Help)', 'fontweight', 'bold', ... 'tooltipstring', 'See crossf() help via the Help button on the right...' } ... { 'Style', 'edit', 'string', '''padratio'', 4' } ... { 'Style', 'pushbutton', 'string', 'Help', 'callback', 'pophelp(''crossf'');' } ... {} ... { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotersp','present',0), 'string', ... 'Plot coherence amplitude', 'tooltipstring', ... 'Plot coherence ampltitude image in the upper panel' } ... { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotphase','present',0), 'string', ... 'Plot coherence phase', 'tooltipstring', ... 'Plot coherence phase image in the lower panel' } ... }; result = inputgui( geometry, uilist, 'pophelp(''pop_crossf'');', ... fastif(typeproc, 'Plot channel cross-coherence -- pop_crossf()', ... 'Plot component cross-coherence -- pop_crossf()')); if length( result ) == 0 return; end; num1 = eval( [ '[' result{1} ']' ] ); num2 = eval( [ '[' result{2} ']' ] ); tlimits = eval( [ '[' result{3} ']' ] ); cycles = eval( [ '[' result{4} ']' ] ); if result{5} options = [',''type'', ''coher''' ]; else options = [',''type'', ''phasecoher''' ]; end; % add topoplot % ------------ if isfield(EEG.chanlocs, 'theta') if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end; if typeproc == 1 options = [options ', ''topovec'', [' int2str([num1 num2]) ... '], ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ]; else % typeproc == 0 options = [options ', ''topovec'', EEG.icawinv(:, [' int2str([num1 num2]) ... '])'', ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ]; end; end; % add title % --------- if isempty( findstr( 'title', result{7})) if ~isempty(EEG.chanlocs) & typeproc chanlabel1 = EEG.chanlocs(num1).labels; chanlabel2 = EEG.chanlocs(num2).labels; else chanlabel1 = int2str(num1); chanlabel2 = int2str(num2); end; if result{5} options = [options ', ''title'',' fastif(typeproc, '''Channel ', '''Component ') chanlabel1 '-' chanlabel2 ... ' Coherence''']; else options = [options ', ''title'',' fastif(typeproc, '''Channel ', '''Component ') chanlabel1 '-' chanlabel2 ... ' Phase Coherence''' ]; end; end; if ~isempty( result{6} ) options = [ options ', ''alpha'',' result{6} ]; end; if ~isempty( result{7} ) options = [ options ',' result{7} ]; end; if ~result{8} options = [ options ', ''plotersp'', ''off''' ]; end; if ~result{9} options = [ options ', ''plotphase'', ''off''' ]; end; figure; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; else options = [ ',' vararg2str(varargin) ]; end; % compute epoch limits % -------------------- if isempty(tlimits) tlimits = [EEG.xmin, EEG.xmax]*1000; end; pointrange1 = round(max((tlimits(1)/1000-EEG.xmin)*EEG.srate, 1)); pointrange2 = round(min((tlimits(2)/1000-EEG.xmin)*EEG.srate, EEG.pnts)); pointrange = [pointrange1:pointrange2]; % call function sample either on raw data or ICA data % --------------------------------------------------- if typeproc == 1 tmpsig1 = EEG.data(num1,pointrange,:); tmpsig2 = EEG.data(num2,pointrange,:); else if ~isempty( EEG.icasphere ) tmpsig1 = eeg_getdatact(EEG, 'component', num1, 'samples', pointrange); tmpsig2 = eeg_getdatact(EEG, 'component', num2, 'samples', pointrange); else error('You must run ICA first'); end; end; tmpsig1 = reshape( tmpsig1, 1, size(tmpsig1,2)*size(tmpsig1,3)); tmpsig2 = reshape( tmpsig2, 1, size(tmpsig2,2)*size(tmpsig2,3)); % outputs % ------- outstr = ''; if ~popup for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end; if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end; end; % plot the datas and generate output command % -------------------------------------------- if length( options ) < 2 options = ''; end; varargout{1} = sprintf('figure; pop_crossf( %s, %d, %d, %d, [%s], [%s] %s);', ... inputname(1), typeproc, num1, num2, int2str(tlimits), num2str(cycles), options); %options = [ options ', ''ydir'', ''norm''' ]; com = sprintf( '%s crossf( tmpsig1, tmpsig2, length(pointrange), [tlimits(1) tlimits(2)], EEG.srate, cycles %s);', outstr, options); eval(com) return; % get contextual help % ------------------- function txt = context(var, allvars, alltext); loc = strmatch( var, allvars); if ~isempty(loc) txt= alltext{loc(1)}; else disp([ 'warning: variable ''' var ''' not found']); txt = ''; end;
github
lcnhappe/happe-master
pop_timtopo.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_timtopo.m
4,061
utf_8
83935198482b3bf9e34948c08e8aef23
% pop_timtopo() - call the timtopo() function for epoched EEG datasets. % Plots the epoch mean for each channel on a single axis, % plus scalp maps of the data at specified latencies. % Usage: % >> pop_timtopo( EEG, timerange, topotimes, title, 'key', 'val', ...); % % Inputs: % EEG - input dataset % timerange - [min max] epoch time range (in ms) to plot % topotimes - array of times to plot scalp maps {Default: NaN % = display scalp map at frame of max var()} % % Optional inputs: % title - optional plot title % 'key','val' - optional topoplot() arguments (see >> help topoplot) % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: timtopo() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 02-16-02 text interface editing -sm & ad % 03-15-02 add all topoplot options -ad % 03-18-02 added title -ad & sm function com = pop_timtopo( EEG, timerange, topotime, plottitle, varargin); com = ''; if nargin < 1 help pop_timtopo; return; end; if nargin < 3 promptstr = { 'Plotting time range (ms):', ... ['Scalp map latencies (ms, NaN -> max-RMS)'], ... 'Plot title:' ... 'Scalp map options (see >> help topoplot):' }; inistr = { [num2str( EEG.xmin*1000) ' ' num2str(EEG.xmax*1000)], ... 'NaN', ... ['ERP data and scalp maps' fastif(~isempty(EEG.setname), [' of ' EEG.setname ], '') ], ... '' }; result = inputdlg2( promptstr, 'ERP data and scalp maps -- pop_timtopo()', 1, inistr, 'pop_timtopo'); if size(result,1) == 0 return; end; timerange = eval( [ '[' result{1} ']' ] ); topotime = eval( [ '[' result{2} ']' ] ); plottitle = result{3}; options = [ ',' result{4} ]; figure; else options = []; for i=1:length( varargin ) if isstr( varargin{ i } ) options = [ options ', ''' varargin{i} '''' ]; else options = [ options ', [' num2str(varargin{i}) ']' ]; end; end; end; try, icadefs; set(gcf, 'color', BACKCOLOR, 'Name', ' timtopo()'); catch, end; if exist('plottitle') ~= 1 plottitle = ['ERP data and scalp maps' fastif(~isempty(EEG.setname), [' of ' EEG.setname ], '') ]; end; if ~isempty(EEG.chanlocs) if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end; SIGTMP = reshape(EEG.data, size(EEG.data,1), EEG.pnts, EEG.trials); posi = round( (timerange(1)/1000-EEG.xmin)/(EEG.xmax-EEG.xmin) * (EEG.pnts-1))+1; posf = round( (timerange(2)/1000-EEG.xmin)/(EEG.xmax-EEG.xmin) * (EEG.pnts-1))+1; if length( options ) < 2 timtopo( mean(SIGTMP(:,posi:posf,:),3), EEG.chanlocs, 'limits', [timerange(1) timerange(2) 0 0], 'plottimes', topotime, 'chaninfo', EEG.chaninfo); com = sprintf('figure; pop_timtopo(%s, [%s], [%s], ''%s'');', inputname(1), num2str(timerange), num2str(topotime), plottitle); else com = sprintf('timtopo( mean(SIGTMP(:,posi:posf,:),3), EEG.chanlocs, ''limits'', [timerange(1) timerange(2) 0 0], ''plottimes'', topotime, ''chaninfo'', EEG.chaninfo %s);', options); eval(com) com = sprintf('figure; pop_timtopo(%s, [%s], [%s], ''%s'' %s);', inputname(1), num2str(timerange), num2str(topotime), plottitle, options); end; else fprintf('Cannot make plot without channel locations\n'); return; end; return;
github
lcnhappe/happe-master
eeg_multieegplot.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_multieegplot.m
4,358
utf_8
16fe8e9b9e5bff89de4ed0ebe4dd8ec5
% eeg_multieegplot() - Produce an eegplot() of a the average of an epoched dataset % (with optional pre-labelling of specific trials). % Usage: % >> eeg_multieegplot( data,trialrej, elecrej, ... % 'key1', value, 'key2', value ... ); % Inputs: % data - input data (channels x points or channels x points x trials). % trialrej - array of 0s and 1s (depicting rejected trials) (size sweeps) % elecrej - array of 0s and 1s (depicting electrodes rejected in % all trials) (size nbelectrodes x sweeps ) % oldtrialrej - array of 0s and 1s (depicting rejected trials) (size sweeps) % oldelecrej - array of 0s and 1s (depicting electrodes rejected in % all trials) (size nbelectrodes x sweeps ) % % Note: 1) {'Key', value } Arguments are passed on to eegplot() % 2) To ignore previous rejections simply set 'oldtrialrej' and % 'oldelecrej' arguments to empty ([]). % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eegplot(), eegplot2event(), 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 % 01-25-02 reformated help & license -ad % 03-07-02 corrected help -ad function eeg_multieegplot( data, rej, rejE, oldrej, oldrejE, varargin); if nargin < 1 help eeg_multieegplot; return; end; if nargin < 4 oldrej = []; end; if nargin < 5 oldrejE = []; end; if ~exist('command') command = ''; end; chans = size(data,1); pnts = size(data,2); colnew = [0.8 0.8 1]; colold = [0.8 1 0.8]; if ndims(data) > 2 % --------------- considering epoched EEG data rejeegplot = []; % concatenate old rejection if not empty % -------------------------------------- if ~isempty( oldrej ) oldrej = find( oldrej > 0); oldrejE = oldrejE(:, oldrej)'; rejeegplot = trial2eegplot( oldrej, oldrejE, pnts, colold); end; % convert for eegplot % ------------------- if ~isempty( rej ) rej = find( rej > 0); rejE = rejE(:,rej)'; secondrejeegplot = trial2eegplot( rej, rejE, pnts, colnew); % see bottom of code for this function rejeegplot = [ rejeegplot' secondrejeegplot' ]'; % remove duplicates % ----------------- %[tmp I] = unique_bc( rejeegplot(:,1) ); %rejeegplot = rejeegplot(I,:); end; else % ---------------------------------------- considering continuous EEG % for continuous EEG, electrodes (rejE and oldrejE) are not considered yet % because there would be a format problem (these rejection are stored in % the event array). rejeegplot = []; if ~isempty(rej) %assuming nrejection x 2 (2 = begin end) s = size(rej, 1); rejeegplot = [ rej(3:4) colnew*ones(s,1) zeros(s, chans) ]; end; % pooling previous rejections if ~isempty(oldrej) tmp = [ oldrej(:, 3:4) colold*ones(s,1) zeros(size(oldrej,1), chans) ]; rejeegplot = [rejeegplot; tmp]; end; end; if isempty(varargin) eegplot(data, 'winlength', 5, 'position', [100 300 800 500], 'winrej', rejeegplot, 'xgrid', 'off'); else eegplot(data, 'winlength', 5, 'position', [100 300 800 500], 'winrej', rejeegplot, 'xgrid', 'off', varargin{:} ); end; return; % convert eeglab format to eeplot format of rejection window % ---------------------------------------------------------- function rejeegplot = trial2eegplot( rej, rejE, pnts, color) 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
lcnhappe/happe-master
pop_chancoresp.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_chancoresp.m
17,056
utf_8
fd71daf5fecf686e892f204c0f95cf38
% pop_chancoresp() - define correspondances between two channel locations structures % (EEG.chanlocs) automatically (by matching channel labels) % else using a user input gui. % Usage: % >> [chanlist1 chanlist2] = pop_chancoresp(chanstruct1, chanstruc2, 'key', 'val', ...); % % Inputs: % chanstruct1 - first (new) channel locations structure (EEG.chanlocs). % For details, >> help readlocs % chanstruct2 - second (reference) chanlocs structure. % % Optional parameters: % 'gui' - ['on'|'off'] display gui or not ('on' -> yes) % 'autoselect' - ['none'|'fiducials'|'all'] automatically pair channels % 'chaninfo1' - EEG.chaninfo structure for first (new) EEG.chanlocs % 'chaninfo2' - EEG.chaninfo structure for second (reference) EEG.chanlocs % 'chanlist1' - [integer] selected channel to pair in the graphic interface % for the first channel structure. This requires the input % 'chanlist2' below. % 'chanlist2' - [integer] selected channel to pair in the graphic interface % for the first channel structure. This requires the input % requires the input 'chanlist1' that must be of the same length. % Output: % chanlist1 - [int vector] indices of selected channels from first (new) EEG.chanlocs % chanlist2 - [int vector] selected channels from second (reference) EEG.chanlocs % % Author: Arnaud Delorme, CNL / Salk Institute, 2005 % 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 [chanlistout1, chanlistout2, thirdout, outfourth] = pop_chancoresp(chans1, chans2, varargin); if nargin < 2 help pop_chancoresp; return; end; chanlistout1 = []; chanlistout2 = []; % process sub command % ------------------- if isstr(chans1) if strcmpi(chans1, 'pair') [chanlistout1, chanlistout2, thirdout, outfourth] = pair(chans2, varargin{:}); elseif strcmpi(chans1, 'unpair') [chanlistout1, chanlistout2, thirdout, outfourth] = unpair(chans2, varargin{:}); elseif strcmpi(chans1, 'clear') [chanlistout1, chanlistout2, thirdout, outfourth] = clearchans(chans2, varargin{:}); elseif strcmpi(chans1, 'auto') [chanlistout1, chanlistout2, thirdout, outfourth] = autoselect(chans2, varargin{:}); end; return; end; g = finputcheck(varargin, { 'autoselect' 'string' {'none';'fiducials';'all'} 'all'; 'chanlist1' 'integer' [1 Inf] []; 'chanlist2' 'integer' [1 Inf] []; 'chaninfo1' '' [] []; 'chaninfo2' '' [] []; 'gui' 'string' { 'on';'off' } 'on' } ); if isstr(g), error(g); end; g.chanstruct1 = chans1; g.chanstruct2 = chans2; if length(g.chanlist1) ~= length(g.chanlist2) error('input arguments ''chanlist1'' and ''chanlist2'' must have the same length'); end; % decode different input formats % ------------------------------ if isstruct(chans1) if isfield(chans1, 'label') % fieldtrip chanstr1 = chans1.label; chanstr2 = chans2.label; else % EEGLAB chanstr1 = { chans1.labels }; chanstr2 = { chans2.labels }; end; else % only channel labels chanstr1 = chans1; chanstr2 = chans2; end; % convert selection to integer % ---------------------------- if isempty(g.chanlist1) if strcmpi(g.autoselect, 'fiducials') % find fiducials in both channel location strustures % -------------------------------------------------- naz1 = strmatch('nz', lower( chanstr1 ), 'exact'); if isempty(naz1), naz1 = strmatch('nasion', lower( chanstr1 ), 'exact'); end; if isempty(naz1), naz1 = strmatch('fidnz', lower( chanstr1 ), 'exact'); end; naz2 = strmatch('nz', lower( chanstr2 ), 'exact'); if isempty(naz2), naz2 = strmatch('nasion', lower( chanstr2 ), 'exact'); end; if isempty(naz2), naz2 = strmatch('fidnz', lower( chanstr2 ), 'exact'); end; lpa1 = strmatch('lpa', lower( chanstr1 ), 'exact'); if isempty(lpa1), lpa1 = strmatch('left', lower( chanstr1 ), 'exact'); end; if isempty(lpa1), lpa1 = strmatch('fidt10', lower( chanstr1 ), 'exact'); end; lpa2 = strmatch('lpa', lower( chanstr2 ), 'exact'); if isempty(lpa2), lpa2 = strmatch('left', lower( chanstr2 ), 'exact'); end; if isempty(lpa2), lpa2 = strmatch('fidt10', lower( chanstr2 ), 'exact'); end; rpa1 = strmatch('rpa', lower( chanstr1 ), 'exact'); if isempty(rpa1), rpa1 = strmatch('right', lower( chanstr1 ), 'exact'); end; if isempty(rpa1), rpa1 = strmatch('fidt9', lower( chanstr1 ), 'exact'); end; rpa2 = strmatch('rpa', lower( chanstr2 ), 'exact'); if isempty(rpa2), rpa2 = strmatch('right', lower( chanstr2 ), 'exact'); end; if isempty(rpa2), rpa2 = strmatch('fidt9', lower( chanstr2 ), 'exact'); end; g.chanlist1 = [ naz1 lpa1 rpa1 ]; g.chanlist2 = [ naz2 lpa2 rpa2 ]; if length(g.chanlist1) ~= length(g.chanlist2) | length(g.chanlist1) == 0 disp('Warning: could not find fiducials in at least one of the channel location structure'); g.chanlist1 = []; g.chanlist2 = []; end; elseif strcmpi(g.autoselect, 'all') % find common channels in both channel location strustures % -------------------------------------------------------- chanstr2low = lower( chanstr2 ); chanstr1low = lower( chanstr1 ); for index = 1:length( chanstr1 ) ind = strmatch(chanstr1low{index}, chanstr2low, 'exact' ); if ~isempty(ind) g.chanlist1(end+1) = index; g.chanlist2(end+1) = ind; end; end; end; end; % plot % ---- if strcmpi(g.gui, 'off') chanlistout1 = g.chanlist1; chanlistout2 = g.chanlist2; return; end; try, g.promptstring; catch, g.promptstring = ''; end; try, g.selectionmode; catch, g.selectionmode = 'multiple'; end; try, g.listsize; catch, g.listsize = []; end; try, g.initialvalue; catch, g.initialvalue = []; end; try, g.name; catch, g.name = ''; end; g.chanstr1 = chanstr1; g.chanstr2 = chanstr2; fig = figure('visible', 'off'); set(fig, 'name', 'Select corresponding channels to pair'); % make text for list % ------------------ [ g.newchanstr1 g.newchanstr2 ] = makelisttext( chanstr1, chanstr2, g.chanlist1, g.chanlist2); % callback for paring and unpairing % --------------------------------- cb_pair = [ 'tmpdat = get(gcbf, ''userdata'');' ... 'tmpval1 = get(findobj(gcbf, ''tag'', ''list1''), ''value'');' ... 'tmpval2 = get(findobj(gcbf, ''tag'', ''list2''), ''value'');' ... '[tmpdat.newchanstr1{tmpval1}, tmpdat.newchanstr2{tmpval2}, tmpdat.chanlist1, tmpdat.chanlist2] = pop_chancoresp(''pair'', tmpval1, tmpval2, tmpdat.chanstr1, tmpdat.chanstr2, tmpdat.chanlist1, tmpdat.chanlist2, tmpdat.newchanstr1{tmpval1}, tmpdat.newchanstr2{tmpval2});' ... 'set(findobj(gcbf, ''tag'', ''list1''), ''string'', tmpdat.newchanstr1);' ... 'set(findobj(gcbf, ''tag'', ''list2''), ''string'', tmpdat.newchanstr2);' ... 'set(gcbf, ''userdata'', tmpdat);' ... 'clear tmpdat tmpval1 tmpval2;' ]; cb_unpair = [ 'tmpdat = get(gcbf, ''userdata'');' ... 'tmpval1 = get(findobj(gcbf, ''tag'', ''list1''), ''value'');' ... 'tmpval2 = get(findobj(gcbf, ''tag'', ''list2''), ''value'');' ... '[tmpdat.newchanstr1{tmpval1}, tmpdat.newchanstr2{tmpval2}, tmpdat.chanlist1, tmpdat.chanlist2] = pop_chancoresp(''unpair'', tmpval1, tmpval2, tmpdat.chanstr1, tmpdat.chanstr2, tmpdat.chanlist1, tmpdat.chanlist2, tmpdat.newchanstr1{tmpval1}, tmpdat.newchanstr2{tmpval2});' ... 'set(findobj(gcbf, ''tag'', ''list1''), ''string'', tmpdat.newchanstr1);' ... 'set(findobj(gcbf, ''tag'', ''list2''), ''string'', tmpdat.newchanstr2);' ... 'set(gcbf, ''userdata'', tmpdat);' ... 'clear tmpdat tmpval1 tmpval2;' ]; cb_plot1 = [ 'tmpdat = get(gcbf, ''userdata'');' ... 'figure; topoplot([], tmpdat.chanstruct1, ''style'', ''blank'', ''drawaxis'', ''on'', ' ... '''electrodes'', ''labelpoint'', ''chaninfo'', tmpdat.chaninfo1);' ]; cb_plot2 = [ 'tmpdat = get(gcbf, ''userdata'');' ... 'figure; topoplot([], tmpdat.chanstruct2, ''style'', ''blank'', ''drawaxis'', ''on'', ' ... '''electrodes'', ''labelpoint'', ''chaninfo'', tmpdat.chaninfo2);' ]; cb_list1 = [ 'tmpdat = get(gcbf, ''userdata'');' ... 'tmpval = get(findobj(gcbf, ''tag'', ''list1''), ''value'');' ... 'tmppos = find(tmpdat.chanlist1 == tmpval);' ... 'if ~isempty(tmppos), set(findobj(gcbf, ''tag'', ''list2''), ''value'', tmpdat.chanlist2(tmppos)); end;' ... 'clear tmpdat tmpval tmppos;' ]; cb_list2 = [ 'tmpdat = get(gcbf, ''userdata'');' ... 'tmpval = get(findobj(gcbf, ''tag'', ''list2''), ''value'');' ... 'tmppos = find(tmpdat.chanlist2 == tmpval);' ... 'if ~isempty(tmppos), set(findobj(gcbf, ''tag'', ''list1''), ''value'', tmpdat.chanlist1(tmppos)); end;' ... 'clear tmpdat tmpval tmppos;' ]; cb_clear = [ 'tmpdat = get(gcbf, ''userdata'');' ... '[tmpdat.newchanstr1, tmpdat.newchanstr2, tmpdat.chanlist1, tmpdat.chanlist2] = pop_chancoresp(''clear'', tmpdat.chanstr1, tmpdat.chanstr2);' ... 'set(gcbf, ''userdata'', tmpdat);' ... 'set(findobj(gcbf, ''tag'', ''list1''), ''string'', tmpdat.newchanstr1);' ... 'set(findobj(gcbf, ''tag'', ''list2''), ''string'', tmpdat.newchanstr2);' ... 'set(gcbf, ''userdata'', tmpdat);' ... 'clear tmpdat;' ]; cb_auto = [ 'tmpdat = get(gcbf, ''userdata'');' ... '[tmpdat.newchanstr1, tmpdat.newchanstr2, tmpdat.chanlist1, tmpdat.chanlist2] = pop_chancoresp(''auto'', tmpdat.chanstr1, tmpdat.chanstr2, tmpdat.newchanstr1, tmpdat.newchanstr2, tmpdat.chanlist1, tmpdat.chanlist2);' ... 'set(gcbf, ''userdata'', tmpdat);' ... 'set(findobj(gcbf, ''tag'', ''list1''), ''string'', tmpdat.newchanstr1);' ... 'set(findobj(gcbf, ''tag'', ''list2''), ''string'', tmpdat.newchanstr2);' ... 'set(gcbf, ''userdata'', tmpdat);' ... 'clear tmpdat;' ]; geometry = {[1 1] [1 1] [1 1] [1 1] [1 1]}; geomvert = [ 1 min(max(length(chanstr1),length(chanstr2)), 10) 1 1 1]; listui = { ... { 'Style', 'pushbutton', 'string', 'Plot new montage', 'callback', cb_plot1 } ... { 'Style', 'pushbutton', 'string', 'Plot ref montage', 'callback', cb_plot2 } ... { 'Style', 'listbox', 'tag', 'list1', 'string', g.newchanstr1, 'value', 1, 'min', 1, 'max', 2, 'callback', cb_list1 } ... { 'Style', 'listbox', 'tag', 'list2', 'string', g.newchanstr2, 'value', 1, 'min', 1, 'max', 2, 'callback', cb_list2 } ... { 'Style', 'pushbutton', 'string', 'Pair channels' , 'callback', cb_pair } ... { 'Style', 'pushbutton', 'string', 'Clear this pair', 'callback', cb_unpair } ... { 'Style', 'pushbutton', 'string', 'Clear all pairs' , 'callback', cb_clear } ... { 'Style', 'pushbutton', 'string', 'Auto select', 'callback', cb_auto } ... { 'Style', 'pushbutton', 'string', 'Cancel', 'callback', 'close(gcbf);' } ... { 'Style', 'pushbutton', 'string', 'Ok' , 'tag', 'ok', 'callback', ['set(gcbo, ''userdata'', ''ok'');'] } }; [tmp tmp2 allobj] = supergui( fig, geometry, geomvert, listui{:} ); set(fig, 'userdata', g); % decode output % ------------- okbut = findobj( 'parent', fig, 'tag', 'ok'); figure(fig); drawnow; waitfor( okbut, 'userdata'); try, tmpdat = get(fig, 'userdata'); chanlistout1 = tmpdat.chanlist1; chanlistout2 = tmpdat.chanlist2; close(fig); drawnow; end; % unpair channels % --------------- function [ str1, str2, chanlist1, chanlist2 ] = unpair(ind1, ind2, chanstr1, chanstr2, chanlist1, chanlist2, str1, str2); if nargin > 4 if isempty(find(chanlist2 == ind2)), disp('Channels not associated'); return; end; if isempty(find(chanlist1 == ind1)), disp('Channels not associated'); return; end; end; str1 = sprintf('%2d - %3s', ind1, chanstr1{ind1}); str2 = sprintf('%2d - %3s', ind2, chanstr2{ind2}); if nargout > 2 tmppos = find( chanlist1 == ind1); chanlist1(tmppos) = []; chanlist2(tmppos) = []; end; % pair channels % ------------- function [ str1, str2, chanlist1, chanlist2 ] = pair(ind1, ind2, chanstr1, chanstr2, chanlist1, chanlist2, str1, str2); if nargin > 4 if ~isempty(find(chanlist2 == ind2)), disp('Channel in second structure already associated'); return; end; if ~isempty(find(chanlist1 == ind1)), disp('Channel in first structure already associated'); return; end; end; str1 = sprintf('%2d - %3s -> %2d - %3s', ind1, chanstr1{ind1}, ind2, chanstr2{ind2}); str2 = sprintf('%2d - %3s -> %2d - %3s', ind2, chanstr2{ind2}, ind1, chanstr1{ind1}); if nargout > 2 chanlist1 = [ chanlist1 ind1 ]; chanlist2 = [ chanlist2 ind2 ]; end; % make full channel list % ---------------------- function [ newchanstr1, newchanstr2 ] = makelisttext( chanstr1, chanstr2, chanlist1, chanlist2); for index = 1:length(chanstr1) if ismember(index, chanlist1) pos = find(chanlist1 == index); newchanstr1{index} = pair( chanlist1(pos), chanlist2(pos), chanstr1, chanstr2 ); else newchanstr1{index} = sprintf('%2d - %3s', index, chanstr1{index}); end; end; for index = 1:length(chanstr2) if ismember(index, chanlist2) pos = find(chanlist2 == index); [tmp newchanstr2{index}] = pair( chanlist1(pos), chanlist2(pos), chanstr1, chanstr2 ); else newchanstr2{index} = sprintf('%2d - %3s', index, chanstr2{index}); end; end; % clear channel pairs % ------------------- function [ newchanstr1, newchanstr2, chanlist1, chanlist2 ] = clearchans(chanstr1, chanstr2); chanlist1 = []; chanlist2 = []; [ newchanstr1, newchanstr2 ] = makelisttext( chanstr1, chanstr2, chanlist1, chanlist2); % autoselect channel pairs % ------------------------ function [ newchanstr1, newchanstr2, chanlist1, chanlist2 ] = autoselect(chanstr1, chanstr2, newchanstr1, newchanstr2, chanlist1, chanlist2); % GUI for selecting pairs % ----------------------- listoptions = { 'All channels (same labels)' 'Fiducials (same labels)' 'BIOSEMI -> 10-20' ... 'EGI -> 10-20' }; listui = { { 'style' 'text' 'string' [ 'How to pair channels (click to select)' 10 ] } ... { 'style' 'listbox' 'string' listoptions 'value' 1 } }; results = inputgui({ [1 1] }, listui, '', 'Auto select channel pairs', [], 'normal', 2); % decode results % -------------- if isempty(results), return; end; if results{1} == 1 % select all pairs [chanlist1 chanlist2] = pop_chancoresp(chanstr1, chanstr2, 'autoselect', 'all', 'gui', 'off'); elseif results{1} == 2 [chanlist1 chanlist2] = pop_chancoresp(chanstr1, chanstr2, 'autoselect', 'fiducials', 'gui', 'off'); else disp('Not implemented yet'); return; end; [ newchanstr1, newchanstr2 ] = makelisttext( chanstr1, chanstr2, chanlist1, chanlist2);
github
lcnhappe/happe-master
pop_select.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_select.m
28,999
utf_8
9bbb1b2f12bb0c9d06e8ba416efab1c5
% pop_select() - given an input EEG dataset structure, output a new EEG data structure % retaining and/or excluding specified time/latency, data point, channel, % and/or epoch range(s). % Usage: % >> OUTEEG = pop_select(INEEG, 'key1', value1, 'key2', value2 ...); % % Graphic interface: % "Time range" - [edit box] RETAIN only the indicated epoch latency or continuous data % time range: [low high] in ms, inclusive. For continuous data, several % time ranges may be specified, separated by semicolons. % Example: "5 10; 12 EEG.xmax" will retain the indicated % stretches of continuous data, and remove data portions outside % the indicated ranges, e.g. from 0 s to 5 s and from 10 s to 12 s. % Command line equivalent: 'time' (or 'notime' - see below) % "Time range" - [checkbox] EXCLUDE the indicated latency range(s) from the data. % For epoched data, it is not possible to remove a range of latencies % from the middle of the epoch, so either the low and/or the high values % in the specified latency range (see above) must be at an epoch boundary % (EEG.xmin, EEGxmax). Command line equivalent: [if checked] 'notime' % "Point range" - [edit box] RETAIN the indicated data point range(s). % Same options as for the "Time range" features (above). % Command line equivalent: 'point' (or 'nopoint' - see below). % "Point range" - [checkbox] EXCLUDE the indicated point range(s). % Command line equivalent: [if checked] 'nopoint' % "Epoch range" - [edit box] RETAIN the indicated data epoch indices in the dataset. % This checkbox is only visible for epoched datasets. % Command line equivalent: 'trial' (or 'notrial' - see below) % "Epoch range" - [checkbox] EXCLUDE the specified data epochs. % Command line equivalent: [if checked] 'notrial' % "Channel range" - [edit box] RETAIN the indicated vector of data channels % Command line equivalent: 'channel' (or 'nochannel' - see below) % "Channel range" - [checkbox] EXCLUDE the indicated channels. % Command line equivalent: [if checked] 'nochannel' % "..." - [button] select channels by name. % "Scroll dataset" - [button] call the eegplot() function to scroll the % channel activities in a new window for visual inspection. % Commandline equivalent: eegplot() - see its help for details. % Inputs: % INEEG - input EEG dataset structure % % Optional inputs % 'time' - [min max] in seconds. Epoch latency or continuous data time range % to retain in the new dataset, (Note: not ms, as in the GUI text entry % above). For continuous data (only), several time ranges can be specified, % separated by semicolons. Example: "5 10; 12 EEG.xmax" will retain % the indicated times ranges, removing data outside the indicated ranges % e.g. here from 0 to 5 s and from 10 s to 12 s. (See also, 'notime') % 'notime' - [min max] in seconds. Epoch latency or continuous dataset time range % to exclude from the new dataset. For continuous data, may be % [min1 max1; min2 max2; ...] to exclude several time ranges. For epoched % data, the latency range must include an epoch boundary, as latency % ranges in the middle of epochs cannot be removed from epoched data. % 'point' - [min max] epoch or continuous data point range to retain in the new % dataset. For continuous datasets, this may be [min1 max1; min2 max2; ...] % to retain several point ranges. (Notes: If both 'point'/'nopoint' and % 'time' | 'notime' are specified, the 'point' limit values take precedence. % The 'point' argument was originally a point vector, now deprecated). % 'nopoint' - [min max] epoch or continuous data point range to exclude in the new dataset. % For epoched data, the point range must include either the first (0) % or the last point (EEG.pnts), as a central point range cannot be removed. % 'trial' - array of trial indices to retain in the new dataset % 'notrial' - array of trial indices to exclude from the new dataset % 'sorttrial' - ['on'|'off'] sort trial indices before extracting them (default: 'on'). % 'channel' - vector of channel indices to retain in the new % dataset. Can also be a cell array of channel names. % 'nochannel' - vector of channel indices to exclude from the new % dataset. Can also be a cell array of channel names. % % Outputs: % OUTEEG - new EEG dataset structure % % Note: This function performs a conjunction (AND) of all its optional inputs. % Using negative counterparts of all options, any logical combination is % possible. % % Author: Arnaud Delorme, CNL/Salk Institute, 2001; SCCN/INC/UCSD, 2002- % % 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 changed the format for events and trial conditions -ad % 02-04-02 changed display format and allow for negation of inputs -ad % 02-17-02 removed the event removal -ad % 03-17-02 added channel info subsets selection -ad % 03-21-02 added event latency recalculation -ad function [EEG, com] = pop_select( EEG, varargin); com = ''; if nargin < 1 help pop_select; return; end; if isempty(EEG(1).data) disp('Pop_select error: cannot process empty dataset'); return; end; if nargin < 2 geometry = { [1 1 1] [1 1 0.25 0.23 0.51] [1 1 0.25 0.23 0.51] [1 1 0.25 0.23 0.51] ... [1 1 0.25 0.23 0.51] [1] [1 1 1]}; uilist = { ... { 'Style', 'text', 'string', 'Select data in:', 'fontweight', 'bold' }, ... { 'Style', 'text', 'string', 'Input desired range', 'fontweight', 'bold' }, ... { 'Style', 'text', 'string', 'on->remove these', 'fontweight', 'bold' }, ... { 'Style', 'text', 'string', 'Time range [min max] (s)', 'fontangle', fastif(length(EEG)>1, 'italic', 'normal') }, ... { 'Style', 'edit', 'string', '', 'enable', fastif(length(EEG)>1, 'off', 'on') }, ... { }, { 'Style', 'checkbox', 'string', ' ', 'enable', fastif(length(EEG)>1, 'off', 'on') },{ }, ... ... { 'Style', 'text', 'string', 'Point range (ex: [1 10])', 'fontangle', fastif(length(EEG)>1, 'italic', 'normal') }, ... { 'Style', 'edit', 'string', '', 'enable', fastif(length(EEG)>1, 'off', 'on') }, ... { }, { 'Style', 'checkbox', 'string', ' ', 'enable', fastif(length(EEG)>1, 'off', 'on') },{ }, ... ... { 'Style', 'text', 'string', 'Epoch range (ex: 3:2:10)', 'fontangle', fastif(length(EEG)>1, 'italic', 'normal') }, ... { 'Style', 'edit', 'string', '', 'enable', fastif(length(EEG)>1, 'off', 'on') }, ... { }, { 'Style', 'checkbox', 'string', ' ', 'enable', fastif(length(EEG)>1, 'off', 'on') },{ }, ... ... { 'Style', 'text', 'string', 'Channel range' }, ... { 'Style', 'edit', 'string', '', 'tag', 'chans' }, ... { }, { 'Style', 'checkbox', 'string', ' ' }, ... { 'style' 'pushbutton' 'string' '...', 'enable' fastif(isempty(EEG.chanlocs), 'off', 'on') ... 'callback' 'tmpchanlocs = EEG(1).chanlocs; [tmp tmpval] = pop_chansel({tmpchanlocs.labels}, ''withindex'', ''on''); set(findobj(gcbf, ''tag'', ''chans''), ''string'',tmpval); clear tmp tmpchanlocs tmpval' }, ... { }, { }, { 'Style', 'pushbutton', 'string', 'Scroll dataset', 'enable', fastif(length(EEG)>1, 'off', 'on'), 'callback', ... 'eegplot(EEG.data, ''srate'', EEG.srate, ''winlength'', 5, ''limits'', [EEG.xmin EEG.xmax]*1000, ''position'', [100 300 800 500], ''xgrid'', ''off'', ''eloc_file'', EEG.chanlocs);' } {}}; results = inputgui( geometry, uilist, 'pophelp(''pop_select'');', 'Select data -- pop_select()' ); if length(results) == 0, return; end; % decode inputs % ------------- args = {}; if ~isempty( results{1} ) if ~results{2}, args = { args{:}, 'time', eval( [ '[' results{1} ']' ] ) }; else args = { args{:}, 'notime', eval( [ '[' results{1} ']' ] ) }; end; end; if ~isempty( results{3} ) if ~results{4}, args = { args{:}, 'point', eval( [ '[' results{3} ']' ] ) }; else args = { args{:}, 'nopoint', eval( [ '[' results{3} ']' ] ) }; end; end; if ~isempty( results{5} ) if ~results{6}, args = { args{:}, 'trial', eval( [ '[' results{5} ']' ] ) }; else args = { args{:}, 'notrial', eval( [ '[' results{5} ']' ] ) }; end; end; if ~isempty( results{7} ) [ chaninds chanlist ] = eeg_decodechan(EEG.chanlocs, results{7}); if isempty(chanlist), chanlist = chaninds; end; if ~results{8}, args = { args{:}, 'channel' , chanlist }; else args = { args{:}, 'nochannel', chanlist }; end; end; else args = varargin; end; %----------------------------AMICA--------------------------------- if isfield(EEG.etc,'amica') && isfield(EEG.etc.amica,'prob_added') for index = 1:2:length(args) if strcmpi(args{index}, 'channel') args{index+1} = [ args{index+1} EEG.nbchan-(0:2*EEG.etc.amica.num_models-1)]; end; end; end; %-------------------------------------------------------------------- % process multiple datasets % ------------------------- if length(EEG) > 1 [ EEG com ] = eeg_eval( 'pop_select', EEG, 'warning', 'on', 'params', args); return; end; if isempty(EEG.chanlocs), chanlist = [1:EEG.nbchan]; else chanlocs = EEG.chanlocs; chanlist = { chanlocs.labels }; end; g = finputcheck(args, { 'time' 'real' [] []; ... 'notime' 'real' [] []; ... 'trial' 'integer' [] [1:EEG.trials]; ... 'notrial' 'integer' [] []; ... 'point' 'integer' [] []; ... 'nopoint' 'integer' [] []; ... 'channel' { 'integer','cell' } [] chanlist; 'nochannel' { 'integer','cell' } [] []; 'trialcond' 'integer' [] []; ... 'notrialcond' 'integer' [] []; ... 'sort' 'integer' [] []; ... 'sorttrial' 'string' { 'on','off' } 'on' }, 'pop_select'); if isstr(g), error(g); end; if ~isempty(g.sort) if g.sort, g.sorttrial = 'on'; else g.sorttrial = 'off'; end; end; if strcmpi(g.sorttrial, 'on') g.trial = sort(setdiff( g.trial, g.notrial )); if isempty(g.trial), error('Error: dataset is empty'); end; else g.trial(ismember(g.trial,g.notrial)) = []; % still warn about & remove duplicate trials (may be removed in the future) [p,q] = unique_bc(g.trial); if length(p) ~= length(g.trial) disp('Warning: trial selection contained duplicated elements, which were removed.'); end g.trial = g.trial(sort(q)); end if isempty(g.channel) && ~iscell(g.nochannel) && ~iscell(chanlist) g.channel = [1:EEG.nbchan]; end; if iscell(g.channel) && ~iscell(g.nochannel) && ~isempty(EEG.chanlocs) noChannelAsCell = {}; for nochanId = 1:length(g.nochannel) noChannelAsCell{nochanId} = EEG.chanlocs(g.nochannel(nochanId)).labels; end; g.nochannel = noChannelAsCell; end; if strcmpi(g.sorttrial, 'on') if iscell(g.channel) g.channel = sort(setdiff( lower(g.channel), lower(g.nochannel) )); else g.channel = sort(setdiff( g.channel, g.nochannel )); end; else g.channel(ismember(lower(g.channel),lower(g.nochannel))) = []; % still warn about & remove duplicate channels (may be removed in the future) [p,q] = unique_bc(g.channel); if length(p) ~= length(g.channel) disp('Warning: channel selection contained duplicated elements, which were removed.'); end g.channel = g.channel(sort(q)); end if ~isempty(EEG.chanlocs) if strcmpi(g.sorttrial, 'on') g.channel = eeg_decodechan(EEG.chanlocs, g.channel); else % we have to protect the channel order against changes by eeg_decodechan if iscell(g.channel) % translate channel names into indices [inds,names] = eeg_decodechan(EEG.chanlocs, g.channel); % and sort the indices back into the original order of channel names [tmp,I] = ismember_bc(lower(g.channel),lower(names)); g.channel = inds(I); end end end; if ~isempty(g.time) && (g.time(1) < EEG.xmin*1000) && (g.time(2) > EEG.xmax*1000) error('Wrong time range'); end; if min(g.trial) < 1 || max( g.trial ) > EEG.trials error('Wrong trial range'); end; if ~isempty(g.channel) if min(double(g.channel)) < 1 || max(double(g.channel)) > EEG.nbchan error('Wrong channel range'); end; end; if size(g.point,2) > 2, g.point = [g.point(1) g.point(end)]; disp('Warning: vector format for point range is deprecated'); end; if size(g.nopoint,2) > 2, g.nopoint = [g.nopoint(1) g.nopoint(end)]; disp('Warning: vector format for point range is deprecated'); end; if ~isempty( g.point ) g.time = zeros(size(g.point)); for index = 1:length(g.point(:)) g.time(index) = eeg_point2lat(g.point(index), 1, EEG.srate, [EEG.xmin EEG.xmax]); end; g.notime = []; end; if ~isempty( g.nopoint ) g.notime = zeros(size(g.nopoint)); for index = 1:length(g.nopoint(:)) g.notime(index) = eeg_point2lat(g.nopoint(index), 1, EEG.srate, [EEG.xmin EEG.xmax]); end; g.time = []; end; if ~isempty( g.notime ) if size(g.notime,2) ~= 2 error('Time/point range must contain 2 columns exactly'); end; if g.notime(2) == EEG.xmax g.time = [EEG.xmin g.notime(1)]; else if g.notime(1) == EEG.xmin g.time = [g.notime(2) EEG.xmax]; elseif EEG.trials > 1 error('Wrong notime range. Remember that it is not possible to remove a slice of time for data epochs.'); end; end; if floor(max(g.notime(:))) > EEG.xmax || min(g.notime(:)) < EEG.xmin error('Time/point range out of data limits'); end; end; if ~isempty(g.time) if size(g.time,2) ~= 2 error('Time/point range must contain 2 columns exactly'); end; for index = 1:length(g.time) if g.time(index) > EEG.xmax g.time(index) = EEG.xmax; disp('Upper time limits exceed data, corrected'); elseif g.time(index) < EEG.xmin g.time(index) = EEG.xmin; disp('Lower time limits exceed data, corrected'); end; end; end; % select trial values %-------------------- if ~isempty(g.trialcond) try, tt = struct( g.trialcond{:} ); catch error('Trial conditions format error'); end; ttfields = fieldnames (tt); for index = 1:length(ttfields) if ~isfield( EEG.epoch, ttfields{index} ) error([ ttfields{index} 'is not a field of EEG.epoch' ]); end; tmpepoch = EEG.epoch; eval( [ 'Itriallow = find( [ tmpepoch(:).' ttfields{index} ' ] >= tt.' ttfields{index} '(1) );' ] ); eval( [ 'Itrialhigh = find( [ tmpepoch(:).' ttfields{index} ' ] <= tt.' ttfields{index} '(end) );' ] ); Itrialtmp = intersect_bc(Itriallow, Itrialhigh); g.trial = intersect_bc( g.trial(:)', Itrialtmp(:)'); end; end; if isempty(g.trial) error('Empty dataset, no trial'); end; if length(g.trial) ~= EEG.trials fprintf('Removing %d trial(s)...\n', EEG.trials - length(g.trial)); end; if length(g.channel) ~= EEG.nbchan fprintf('Removing %d channel(s)...\n', EEG.nbchan - length(g.channel)); end; try % For AMICA probabilities... %----------------------------------------------------- if isfield(EEG.etc, 'amica') && ~isempty(EEG.etc.amica) && isfield(EEG.etc.amica, 'v_smooth') && ~isempty(EEG.etc.amica.v_smooth) && ~isfield(EEG.etc.amica,'prob_added') if isfield(EEG.etc.amica, 'num_models') && ~isempty(EEG.etc.amica.num_models) if size(EEG.data,2) == size(EEG.etc.amica.v_smooth,2) && size(EEG.data,3) == size(EEG.etc.amica.v_smooth,3) && size(EEG.etc.amica.v_smooth,1) == EEG.etc.amica.num_models EEG = eeg_formatamica(EEG); %------------------------------------------- [EEG com] = pop_select(EEG,args{:}); %------------------------------------------- EEG = eeg_reformatamica(EEG); EEG = eeg_checkamica(EEG); return; else disp('AMICA probabilities not compatible with size of data, probabilities cannot be rejected') disp('Resuming rejection...') end end end % ------------------------------------------------------ catch warnmsg = strcat('your dataset contains amica information, but the amica plugin is not installed. Continuing and ignoring amica information.'); warning(warnmsg) end % recompute latency and epoch number for events % --------------------------------------------- if length(g.trial) ~= EEG.trials & ~isempty(EEG.event) if ~isfield(EEG.event, 'epoch') disp('Pop_epoch warning: bad event format with epoch dataset, removing events'); EEG.event = []; else if isfield(EEG.event, 'epoch') keepevent = []; for indexevent = 1:length(EEG.event) newindex = find( EEG.event(indexevent).epoch == g.trial );% For AMICA probabilities... %----------------------------------------------------- try if isfield(EEG.etc, 'amica') && ~isempty(EEG.etc.amica) && isfield(EEG.etc.amica, 'v_smooth') && ~isempty(EEG.etc.amica.v_smooth) && ~isfield(EEG.etc.amica,'prob_added') if isfield(EEG.etc.amica, 'num_models') && ~isempty(EEG.etc.amica.num_models) if size(EEG.data,2) == size(EEG.etc.amica.v_smooth,2) && size(EEG.data,3) == size(EEG.etc.amica.v_smooth,3) && size(EEG.etc.amica.v_smooth,1) == EEG.etc.amica.num_models EEG = eeg_formatamica(EEG); %------------------------------------------- [EEG com] = pop_select(EEG,args{:}); %------------------------------------------- EEG = eeg_reformatamica(EEG); EEG = eeg_checkamica(EEG); return; else disp('AMICA probabilities not compatible with size of data, probabilities cannot be rejected') disp('Resuming rejection...') end end end catch warnmsg = strcat('your dataset contains amica information, but the amica plugin is not installed. Continuing and ignoring amica information.'); warning(warnmsg) end; % ------------------------------------------------------ if ~isempty(newindex) keepevent = [keepevent indexevent]; if isfield(EEG.event, 'latency') EEG.event(indexevent).latency = EEG.event(indexevent).latency - (EEG.event(indexevent).epoch-1)*EEG.pnts + (newindex-1)*EEG.pnts; end; EEG.event(indexevent).epoch = newindex; end; end; diffevent = setdiff_bc([1:length(EEG.event)], keepevent); if ~isempty(diffevent) disp(['Pop_select: removing ' int2str(length(diffevent)) ' unreferenced events']); EEG.event(diffevent) = []; end; end; end; end; % performing removal % ------------------ if ~isempty(g.time) | ~isempty(g.notime) if EEG.trials > 1 % select new time window % ---------------------- try, tmpevent = EEG.event; tmpeventlatency = [ tmpevent.latency ]; catch, tmpeventlatency = []; end; alllatencies = 1-(EEG.xmin*EEG.srate); % time 0 point alllatencies = linspace( alllatencies, EEG.pnts*(EEG.trials-1)+alllatencies, EEG.trials); [EEG.data tmptime indices epochevent]= epoch(EEG.data, alllatencies, ... [g.time(1) g.time(2)]*EEG.srate, 'allevents', tmpeventlatency); tmptime = tmptime/EEG.srate; if g.time(1) ~= tmptime(1) & g.time(2)-1/EEG.srate ~= tmptime(2) fprintf('pop_select(): time limits have been adjusted to [%3.3f %3.3f] to fit data points limits\n', tmptime(1), tmptime(2)+1/EEG.srate); end; EEG.xmin = tmptime(1); EEG.xmax = tmptime(2); EEG.pnts = size(EEG.data,2); alllatencies = alllatencies(indices); % modify the event structure accordingly (latencies and add epoch field) % ---------------------------------------------------------------------- allevents = []; newevent = []; count = 1; if ~isempty(epochevent) newevent = EEG.event(1); for index=1:EEG.trials for indexevent = epochevent{index} newevent(count) = EEG.event(indexevent); newevent(count).epoch = index; newevent(count).latency = newevent(count).latency - alllatencies(index) - tmptime(1)*EEG.srate + 1 + EEG.pnts*(index-1); count = count + 1; end; end; end; EEG.event = newevent; % erase event-related fields from the epochs % ------------------------------------------ if ~isempty(EEG.epoch) fn = fieldnames(EEG.epoch); EEG.epoch = rmfield(EEG.epoch,{fn{strmatch('event',fn)}}); end; else if isempty(g.notime) if length(g.time) == 2 && EEG.xmin < 0 disp('Warning: negative minimum time; unchanged to ensure correct latency of initial boundary event'); end; g.notime = g.time'; g.notime = g.notime(:); if g.notime(1) ~= 0, g.notime = [EEG.xmin g.notime(:)']; else g.notime = [g.notime(2:end)']; end; if g.time(end) == EEG.xmax, g.notime(end) = []; else g.notime(end+1) = EEG.xmax; end; for index = 1:length(g.notime) if g.notime(index) ~= 0 & g.notime(index) ~= EEG.xmax if mod(index,2), g.notime(index) = g.notime(index) + 1/EEG.srate; else g.notime(index) = g.notime(index) - 1/EEG.srate; end; end; end; g.notime = reshape(g.notime, 2, length(g.notime)/2)'; end; nbtimes = length(g.notime(:)); [points,flag] = eeg_lat2point(g.notime(:)', ones(1,nbtimes), EEG.srate, [EEG.xmin EEG.xmax]); points = reshape(points, size(g.notime)); % fixing if last region is the same if flag if ~isempty(find((points(end,1)-points(end,2))== 0)), points(end,:) = []; end; end EEG = eeg_eegrej(EEG, points); end end; % performing removal % ------------------ if ~isequal(g.channel,1:size(EEG.data,1)) || ~isequal(g.trial,1:size(EEG.data,3)) %EEG.data = EEG.data(g.channel, :, g.trial); % this code belows is prefered for memory mapped files diff1 = setdiff_bc([1:size(EEG.data,1)], g.channel); diff2 = setdiff_bc([1:size(EEG.data,3)], g.trial); if ~isempty(diff1) EEG.data(diff1, :, :) = []; end; if ~isempty(diff2) EEG.data(:, :, diff2) = []; end; end if ~isempty(EEG.icaact), EEG.icaact = EEG.icaact(:,:,g.trial); end; EEG.trials = length(g.trial); EEG.pnts = size(EEG.data,2); EEG.nbchan = length(g.channel); if ~isempty(EEG.chanlocs) EEG.chanlocs = EEG.chanlocs(g.channel); end; if ~isempty(EEG.epoch) EEG.epoch = EEG.epoch( g.trial ); end; if ~isempty(EEG.specdata) if length(g.point) == EEG.pnts EEG.specdata = EEG.specdata(g.channel, :, g.trial); else EEG.specdata = []; fprintf('Warning: spectral data were removed because of the change in the numner of points\n'); end; end; % ica specific % ------------ if ~isempty(EEG.icachansind) rmchans = setdiff_bc( EEG.icachansind, g.channel ); % channels to remove % channel sub-indices % ------------------- icachans = 1:length(EEG.icachansind); for index = length(rmchans):-1:1 chanind = find(EEG.icachansind == rmchans(index)); icachans(chanind) = []; end; % new channels indices % -------------------- count = 1; newinds = []; for index = 1:length(g.channel) if any(EEG.icachansind == g.channel(index)) newinds(count) = index; count = count+1; end; end; EEG.icachansind = newinds; else icachans = 1:size(EEG.icasphere,2); end; if ~isempty(EEG.icawinv) flag_rmchan = (length(icachans) ~= size(EEG.icawinv,1)); if isempty(EEG.icaweights) || flag_rmchan EEG.icawinv = EEG.icawinv(icachans,:); EEG.icaweights = pinv(EEG.icawinv); EEG.icasphere = eye(size(EEG.icaweights,2)); end end; if ~isempty(EEG.specicaact) if length(g.point) == EEG.pnts EEG.specicaact = EEG.specicaact(icachans, :, g.trial); else EEG.specicaact = []; fprintf('Warning: spectral ICA data were removed because of the change in the numner of points\n'); end; end; % check if only one epoch % ----------------------- if EEG.trials == 1 if isfield(EEG.event, 'epoch') EEG.event = rmfield(EEG.event, 'epoch'); end; EEG.epoch = []; end; EEG.reject = []; EEG.stats = []; EEG.reject.rejmanual = []; % for stats, can adapt remove the selected trials and electrodes % in the future to gain time ----------------------------------- EEG.stats.jp = []; EEG = eeg_checkset(EEG, 'eventconsistency'); % generate command % ---------------- if nargout > 1 com = sprintf('EEG = pop_select( %s,%s);', inputname(1), vararg2str(args)); end return; % ********* OLD, do not remove any event any more % ********* in the future maybe do a pack event to remove events not in the time range of any epoch if ~isempty(EEG.event) % go to array format if necessary if isstruct(EEG.event), format = 'struct'; else format = 'array'; end; switch format, case 'struct', EEG = eventsformat(EEG, 'array'); end; % keep only events related to the selected trials Indexes = []; Ievent = []; for index = 1:length( g.trial ) currentevents = find( EEG.event(:,2) == g.trial(index)); Indexes = [ Indexes ones(1, length(currentevents))*index ]; Ievent = union_bc( Ievent, currentevents ); end; EEG.event = EEG.event( Ievent,: ); EEG.event(:,2) = Indexes(:); switch format, case 'struct', EEG = eventsformat(EEG, 'struct'); end; end;
github
lcnhappe/happe-master
pop_rmdat.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_rmdat.m
7,061
utf_8
a5678449e4d7392ff5975e3c4546c3e9
% pop_rmdat() - Remove continuous data around specific events % % Usage: % >> OUTEEG = pop_rmdat( EEG); % pop-up a data entry window % >> OUTEEG = pop_rmdat( EEG, typerange, timelimits, invertselection); % % Graphic interface: % "Time-locking event type(s)" - [edit box] Select 'Edit > Event values' % to see a list of event.type values; else use the push button. % To use event types containing spaces, enter in single-quotes. % "..." - [push button] scroll event types. % "Time limits" - [edit box] epoch latency range [start, end] in seconds relative % to the event type latency. % % Inputs: % EEG - Input dataset. Data may already be epoched; in this case, % extract (shorter) subepochs time locked to epoch events. % typerange - Cell array of event types to time lock to. % (Note: An event field called 'type' must be defined in % the 'EEG.event' structure). % timelimits - Epoch latency limits [start end] in seconds relative to the time-locking event % {default: [-1 2]}% % invertselection - [0|1] Invert selection {default:0 is no} % % Outputs: % OUTEEG - output dataset % % Authors: Arnaud Delorme, SCCN, INC, UCSD, 2009- % 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, com] = pop_rmdat( EEG, events, timelims, invertsel ); if nargin < 1 help pop_rmdat; return; end; com = ''; if isempty(EEG.event) error( [ 'No event. This function removes data' 10 'based on event latencies' ]); end; if isempty(EEG.trials) error( [ 'This function only works with continuous data' ]); end; if ~isfield(EEG.event, 'latency'), error( 'Absent latency field in event array/structure: must name one of the fields ''latency'''); end; if nargin < 3 % popup window parameters % ----------------------- promptstr = { strvcat('Time-locking event type(s) ([]=all):', ... 'Select ''Edit > Event values'' to see type values.'), ... 'Epoch limits [start, end] in seconds:', ... 'Name for the new dataset:', ... 'Out-of-bounds EEG rejection limits ([min max], []=none):' }; cbevent = ['if ~isfield(EEG.event, ''type'')' ... ' errordlg2(''No type field'');' ... 'else' ... ' tmpevent = EEG.event;' ... ' if isnumeric(EEG.event(1).type),' ... ' [tmps,tmpstr] = pop_chansel(unique([ tmpevent.type ]));' ... ' else,' ... ' [tmps,tmpstr] = pop_chansel(unique({ tmpevent.type }));' ... ' end;' ... ' if ~isempty(tmps)' ... ' set(findobj(''parent'', gcbf, ''tag'', ''events''), ''string'', tmpstr);' ... ' end;' ... 'end;' ... 'clear tmps tmpv tmpstr tmpevent tmpfieldnames;' ]; geometry = { [2 1 1.2] [2 1 1.2] }; uilist = { { 'style' 'text' 'string' 'Event type(s) ([]=all)' } ... { 'style' 'edit' 'string' '' 'tag' 'events' } ... { 'style' 'pushbutton' 'string' '...' 'callback' cbevent } ... { 'style' 'text' 'string' 'Time limits [start, end] in sec.' } ... { 'style' 'edit' 'string' '-1 1' } ... { 'style' 'popupmenu' 'string' 'Keep selected|Remove selected' } }; result = inputgui( geometry, uilist, 'pophelp(''pop_rmdat'')', 'Remove data portions around events - pop_rmdat()'); if length(result) == 0 return; end; if strcmpi(result{1}, '[]'), result{1} = ''; end; if ~isempty(result{1}) if strcmpi(result{1}(1),'''') % If event type appears to be in single-quotes, use comma % and single-quote as delimiter between event types. toby 2.24.2006 % fixed Arnaud May 2006 events = eval( [ '{' result{1} '}' ] ); else events = parsetxt( result{1}); end; else events = {}; end timelims = eval( [ '[' result{2} ']' ] ); invertsel = result{3}-1; end; tmpevent = EEG.event; % Checking for numeric values in fieldnames and changing them to string for i = 1: length(tmpevent) checknum(i) = isnumeric(tmpevent(i).type); end if sum(checknum)~=0 tmpindx = find(checknum == 1); for i = 1: length(tmpindx) tmpevent(tmpindx(i)).type = num2str(tmpevent(tmpindx(i)).type); end end % compute event indices % --------------------- allinds = []; for index = 1:length(events) inds = strmatch(events{index},{ tmpevent.type }, 'exact'); allinds = [allinds(:); inds(:) ]'; end; allinds = sort(allinds); if isempty(allinds) disp('No event found'); return; end; % compute time limits % ------------------- array = []; bnd = strmatch('boundary', lower({tmpevent.type })); bndlat = [ tmpevent(bnd).latency ]; for bind = 1:length(allinds) evtlat = EEG.event(allinds(bind)).latency; evtbeg = evtlat+EEG.srate*timelims(1); evtend = evtlat+EEG.srate*timelims(2); if any(bndlat > evtbeg & bndlat < evtend) % find the closer upper and lower boundaries bndlattmp = bndlat(bndlat > evtbeg & bndlat < evtend); diffbound = bndlattmp-evtlat; allneginds = find(diffbound < 0); allposinds = find(diffbound > 0); if ~isempty(allneginds), evtbeg = bndlattmp(allneginds(1)); end; if ~isempty(allposinds), evtend = bndlattmp(allposinds(1)); end; fprintf('Boundary found: time limits for event %d reduced from %3.2f to %3.2f\n', allinds(bind), ... (evtbeg-evtlat)/EEG.srate, (evtend-evtlat)/EEG.srate); end if ~isempty(array) && evtbeg < array(end) array(end) = evtend; else array = [ array; evtbeg evtend]; end; end; array if ~isempty(array) && array(1) < 1, array(1) = 1; end; if ~isempty(array) && array(end) > EEG.pnts, array(end) = EEG.pnts; end; if isempty(array) disp('No event found'); return; end; if invertsel EEG = pop_select(EEG, 'notime', (array-1)/EEG.srate); else EEG = pop_select(EEG, 'time', (array-1)/EEG.srate); end; % generate output command % ----------------------- com = sprintf('EEG = pop_rmdat( EEG, %s);', vararg2str( { events timelims invertsel } ));
github
lcnhappe/happe-master
pop_editeventfield.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_editeventfield.m
21,851
utf_8
71f72e83e89bf49e4935579619263775
% pop_editeventfield() - Add/remove/rename/modify a field in the event structure % of an EEG dataset. Can also be used to append new events to the end of the % event structure or to delete all current events. If the dataset is % the only input, a window pops up to ask for relevant parameter values. % % Usage: >> [EEG] = pop_editeventfield( EEG, 'key1', 'value1', ...); % % Input: % EEG - input dataset % % Optional inputs: % 'FIELDNAME_X' - [ 'filename'|vector ]. Name of a current or new % user-defined event field. The ascii file, vector variable, % or explicit numeric vector should contain values for this field % for all events specified in 'indices' (below) or in new events % appended to the dataset (if 'indices' not specified). If one arg % value is given, it will be used for all the specified events. % If the arg is [], the named field is *removed* from all the % specified (or new) events. Use this option to add a new field to % all events in the dataset, or to modify the field values of specified % events, to specify field information for new events appended to % the event structure, or to remove an event field. For example, % 'FIELDNAME_X' may be 'latency', 'type', 'duration'. % 'latency' - [ 'filename'|vector ] example of field name (see description above). % 'type' - [ 'filename'|vector ] example of field name (see description above). % 'duration' - [ 'filename'|vector ] example of field name (see description above). % 'FIELDNAME_X_info' - new comment string for field FIELDNAME_X. % 'latency_info' - description string for the latency field. % 'type_info' - description string for the type field. % 'duration_info' - description string for the duration field. % 'indices' - [vector of event indices] The indices of the events to modify. % If adding a new event field, events not listed here % will have an empty field value IF they are not in an epoch % containing events whose field value is specified. However, % if adding a new (FIELDNAME) field to an epoched dataset, % and the field value for only one event in some data epoch is % specified, then the other events in the same epoch will be given % the specified value. If field values of more than one, but not all % the events in an epoch are specified, then unspecified events at % the beginning of the epoch will be given the value of the first % specified event, unspecified epoch events after this event will % be given the field value of the second specified epoch event, etc. % {default|[]: modify all events in the dataset} % 'rename' - ['FIELDNAME1->FIELDNAME2'] rename field 'FIELDNAME1' to % field 'FIELDNAME2'. Ex: { 'rename', 'blocktype->condition' }. % 'delold' - ['yes'|'no'] 'yes' = delete ALL previous events. {default: 'no'} % 'timeunit' - [latency field time unit in fraction of seconds]. Ex: 1e-3 -> % read specified latencies as msec {default: 1 (-->seconds)} % 'skipline' - number of leading text file lines to skip in named text files. % {default: 0}. % 'delim' - delimiting characters in named text files {default: tabs and spaces} % % Outputs: % EEG - dataset with updated event field % % Example: EEG = pop_editeventfield(EEG, 'type', 1, ... % 'sleepstage', 'sleepstage_values.txt', ... % 'latency', [100 130 123 400],'timeunit',1e-3); % % Append 4 events to the EEG struct, all of type 1, at the latencies % % given (in msec) with user-defined field ('sleepstage') values read % % from a one-column ascii file ('sleepstage_values.txt'). % % Example: EEG = pop_editeventfield(EEG, 'indices', 1:2:3277, ... % 'sleepstage', 'sleepstage_values.txt'); % % Add a new 'sleepstage' field to all events in the EEG struct. % % Read 'sleepstage' field values for odd-numbered events from a one-column % % ascii file ('sleepstage_values.txt') -- even-numbered % events will have % % an empty 'sleepstage' value (unless the data are epoched, see 'indices' above). % % Note: To save events into a readable table, first convert them to 'array' format, % then save the array. % >> events = eeg_eventformat(EEG.event, 'array'); % >> save -ascii myevents.txt events % % Author: Arnaud Delorme & Scott Makeig, CNL / Salk Institute, 9 Feb 2002- % % See also: pop_importevent(), eeg_eventformat(), pop_selectevent() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 9 Feb 2002, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %02/13/2001 fix bug if EEG.event is empty -ad %03/12/2001 add timeunit option -ad %03/18/2001 debug rename option -ad & sm %03/18/2001 correct allignment problem -ad & ja function [EEG, com] = pop_editeventfield(EEG, varargin); com =''; if nargin < 1 help pop_editeventfield; return; end; if isempty(EEG.data) error('Setevent error: cannot process empty dataset'); end; I = []; % remove the event field % ---------------------- if ~isempty(EEG.event), allfields = fieldnames(EEG.event); ind1 = strmatch('urevent', allfields, 'exact'); ind2 = strmatch('epoch', allfields, 'exact'); allfields([ind1 ind2]) = []; try, EEG.eventdescription([ind1 ind2]) = []; catch, end; else allfields = { 'type' 'latency' }; end; if nargin<2 commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ... 'if filename ~=0,' ... ' set(findobj(''parent'', gcbf, ''tag'', tagtest), ''string'', [ filepath filename ]);' ... 'end;' ... 'clear filename filepath tagtest;' ]; uilist = { ... { 'Style', 'text', 'string', 'Edit fields:', 'fontweight', 'bold' }, ... { 'Style', 'text', 'string', 'Edit description', 'fontweight', 'bold' }, ... { 'Style', 'text', 'string', sprintf('New values (file or array containing %d values)', length(EEG.event)), 'fontweight', 'bold' }, ... { 'Style', 'text', 'string', 'Delete field', 'fontweight', 'bold' } ... }; geometry = { [1.05 1.05 2 0.8] }; listboxtext = { 'No field selected' }; txt_warn = 'warndlg2(strvcat(''Warning: deleting/renaming this field might cause EEGLAB'', ''to be unstable. Some functionalities will also be lost.''));'; cb_warn2 = [ 'strtmp = get(gcbo, ''string''); if ~isempty(strmatch(strtmp(get(gcbo, ''value'')), { ''latency'' ''type''}, ''exact'')),' txt_warn 'end;' ]; for index = 1:length(allfields) geometry = { geometry{:} [1 1 1 0.7 0.2 0.32 0.2] }; description = ''; try, description = fastif(isempty(EEG.eventdescription{index}), '', EEG.eventdescription{index}); description = description(1,:); tmplines = find(description == 10); if ~isempty(tmplines), description = description(1:tmplines(1)-1); end; catch, end; if strcmp(allfields{index}, 'latency') || strcmp(allfields{index}, 'type') cb_warn = { 'callback' [ 'if get(gcbo, ''value''),' txt_warn 'end;' ] }; else cb_warn = { }; end; if strcmp(allfields{index}, 'latency') tmpfield = [ allfields{index} '(s)' ]; elseif strcmp(allfields{index}, 'duration') tmpfield = [ allfields{index} '(s)' ]; else tmpfield = allfields{index}; end; uilist = { uilist{:}, ... { 'Style', 'text', 'string', tmpfield }, ... { 'Style', 'pushbutton', 'string', description, 'callback', ... [ 'tmpuserdata = get(gcf, ''userdata'');' ... 'tmpuserdata{' int2str(index) '} = pop_comments(tmpuserdata{' int2str(index) ... '}, ''Comments on event field: ' allfields{index} ''');' ... 'set(gcbo, ''string'', tmpuserdata{' int2str(index) '});' ... 'set(gcf, ''userdata'', tmpuserdata); clear tmpuserdata;' ] }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', allfields{index} }, ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', ['tagtest = ''' allfields{index} ''';' commandload ] }, ... { }, { 'Style', 'checkbox', 'string', ' ', cb_warn{:} }, { } }; listboxtext = { listboxtext{:} allfields{index} }; end; index = length(allfields) + 1; uilist = { uilist{:}, ... { 'Style', 'edit', 'string', ''}, ... { 'Style', 'pushbutton', 'string', '', 'callback', ... [ 'tmpuserdata = get(gcf, ''userdata'');' ... 'tmpuserdata{' int2str(index) '} = pop_comments(tmpuserdata{' int2str(index) ... '}, ''Comments on new event field:'');' ... 'set(gcbo, ''string'', tmpuserdata{' int2str(index) '});' ... 'set(gcf, ''userdata'', tmpuserdata); clear tmpuserdata;' ] }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'newfield' }, ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', ['tagtest = ''newfield'';' commandload ] }, ... { 'Style', 'text', 'string', '-> add field'} ... { } ... { 'Style', 'text', 'string', 'Rename field', 'fontweight', 'bold' }, ... { 'Style', 'popupmenu', 'string', listboxtext 'callback' cb_warn2 }, ... { 'Style', 'text', 'string', 'as', 'fontweight', 'bold' }, ... { 'Style', 'edit', 'string', '' } ... fastif(isunix,{ 'Style', 'text', 'string', '(Click on field name to select it!)' },{ })}; geometry = { geometry{:} [1 1 1 0.7 0.72] [1] [1 1.2 0.6 1 2] }; descriptions = EEG.eventdescription; if isempty(descriptions), descriptions = { '' '' }; end; [results userdat ]= inputgui( geometry, uilist, 'pophelp(''pop_editeventfield'');', ... 'Edit event field(s) -- pop_editeventfield()', { descriptions{:} '' } ); if length(results) == 0, return; end; % decode top inputs % ----------------- args = { }; % dealing with existing fields %----------------------------- for index = 1:length(allfields) if results{index*2} == 1, args = { args{:}, allfields{index}, [] }; else if ~isempty( results{index*2-1} ) if exist(results{index*2-1}) == 2, args = { args{:}, allfields{index}, [ results{index*2-1} ] }; % file else args = { args{:}, allfields{index}, results{index*2-1} }; end; end; try, if ~strcmp( userdat{index}, EEG.eventdescription{index}) args = { args{:}, [ allfields{index} 'info' ], userdat{index} }; end; catch, end; end; end; % dealing with the new field %--------------------------- sub = 3; if ~isempty( results{end-sub} ) args = { args{:}, results{end-sub}, results{end-sub+1} }; % file end; % handle rename % ------------- if results{end-1} ~= 1, args = { args{:}, 'rename', [ allfields{results{end-1}-1} '->' results{end} ] }; end; else % no interactive inputs args = varargin; % scan args to modify array/file format % array are transformed into string % files are transformed into string of string % (this is usefull to build the string command for the function) % -------------------------------------------------------------- for index=1:2:length(args) if iscell(args{index+1}), args{index+1} = { args{index+1} }; end; % double nested if isstr(args{index+1}) args{index+1} = args{index+1}; % string end; end; end; % create structure % ---------------- try, g = struct(args{:}); catch, disp('pop_editeventfield(): wrong syntax in function arguments'); return; end; % test the presence of variables % ------------------------------ try, g.skipline; catch, g.skipline = 0; end; try, g.indices; catch, g.indices = [1:length(EEG.event)]; end; try, g.delold; catch, g.delold = 'no'; end; try, g.timeunit; catch, g.timeunit = 1; end; try, g.delim; catch, g.delim = char([9 32]); end; if isstr(g.indices), g.indices = eval([ '[' g.indices ']' ]); end; tmpfields = fieldnames(g); % scan all the fields of g % ------------------------ for curfield = tmpfields' if ~isempty(EEG.event), allfields = fieldnames(EEG.event); else allfields = {}; end; switch lower(curfield{1}) case { 'append' 'delold', 'fields', 'skipline', 'indices', 'timeunit', 'delim' }, ; % do nothing now case 'rename', if isempty( findstr('->',g.rename) ), disp('warning pop_editeventfield() bad syntax for ''rename'', ignoring input'); else oldname = g.rename(1:findstr('->',g.rename)-1); newname = g.rename(findstr('->',g.rename)+2:end); indexmatch = strmatch(oldname, allfields); if isempty(indexmatch), disp('pop_editeventfield() warning: name not found for rename'); else for index = 1:length(EEG.event) eval([ 'EEG.event(index).' newname '=EEG.event(index).' oldname ';']); end; EEG.event = rmfield(EEG.event, oldname); end; if isfield(EEG, 'urevent') disp('pop_editeventfield() warning: field name not renamed in urevent structure'); end; end; otherwise, % user defined field command % -------------------------- infofield = findstr(curfield{1}, 'info'); if ~isempty(infofield) & infofield == length( curfield{1} )-3 % description of a field % ---------------------- fieldname = curfield{1}(1:infofield-1); indexmatch = strmatch( fieldname, allfields); if isempty( indexmatch ) disp(['pop_editeventfield() warning: Field ' fieldname ' not found to add description, ignoring']); else EEG.eventdescription{indexmatch} = getfield(g, curfield{1}); end; else % not an field for description % ---------------------------- if isempty( getfield(g, curfield{1}) ) % delete indexmatch = strmatch( curfield{1}, allfields); if isempty( indexmatch ) disp(['pop_editeventfield() warning: Field ''' curfield{1} ''' not found for deletion, ignoring']); else EEG.event = rmfield(EEG.event, curfield{1}); allfields(indexmatch) = []; if isfield(EEG, 'urevent') fprintf('pop_editeventfield() warning: field ''%s'' not deleted from urevent structure\n', curfield{1} ); end; try, EEG.eventdescription(indexmatch) = []; catch, end; end; else % interpret switch g.delold % delete old events case 'yes' EEG.event = load_file_or_array( getfield(g, curfield{1}), g.skipline, g.delim ); allfields = { curfield{1} }; EEG.event = eeg_eventformat(EEG.event, 'struct', allfields); EEG.event = recomputelatency( EEG.event, 1:length(EEG.event), EEG.srate, g.timeunit); EEG = eeg_checkset(EEG, 'makeur'); case 'no' % match existing fields % --------------------- tmparray = load_file_or_array( getfield(g, curfield{1}), g.skipline, g.delim ); if isempty(g.indices) g.indices = [1:size(tmparray(:),1)] + length(EEG.event); end; indexmatch = strmatch(curfield{1}, allfields); if isempty(indexmatch) % no match disp(['pop_editeventfield(): creating new field ''' curfield{1} '''' ]); end; try EEG.event = setstruct(EEG.event, curfield{1}, g.indices, [ tmparray{:} ]); catch, error('Wrong size for input array'); end; if strcmp(curfield{1}, 'latency') EEG.event = recomputelatency( EEG.event, g.indices, EEG.srate, g.timeunit); end; if strcmp(curfield{1}, 'duration') for indtmp = 1:length(EEG.event) EEG.event(indtmp).duration = EEG.event(indtmp).duration/EEG.srate; end; end; if isfield(EEG, 'urevent') disp('pop-editeventfield(): updating urevent structure'); try tmpevent = EEG.event; for indtmp = g.indices(:)' if ~isempty(EEG.event(indtmp).urevent) tmpval = getfield (EEG.event, {indtmp}, curfield{1}); EEG.urevent = setfield (EEG.urevent, { tmpevent(indtmp).urevent }, ... curfield{1}, tmpval); end; end; catch, disp('pop_editeventfield(): problem while updating urevent structure'); end; end; end; end; end; end; end; if isempty(EEG.event) % usefull 0xNB empty structure EEG.event = []; end; EEG = eeg_checkset(EEG, 'eventconsistency'); % generate the output command % --------------------------- com = sprintf('%s = pop_editeventfield( %s, %s);', inputname(1), inputname(1), vararg2str(args)); % interpret the variable name % --------------------------- function str = str2str( array ) str = ''; for index = 1:size(array,1) str = [ str ', ''' array(index,:) '''' ]; end; if size(array,1) > 1 str = [ 'strvcat(' str(2:end) ')']; else str = str(2:end); end; return; % interpret the variable name % --------------------------- function array = load_file_or_array( varname, skipline, delim ); if isstr(varname) if exist(varname) == 2 % mean that it is a filename % -------------------------- array = loadtxt( varname, 'skipline', skipline, 'delim', delim); else % variable in the global workspace % -------------------------- array = evalin('base', varname); if ~iscell(array) array = mattocell(array, ones(1, size(array,1)), ones(1, size(array,2))); end; end; else array = mattocell(varname); end; return; % update latency values % --------------------- function event = recomputelatency( event, indices, srate, timeunit); if ~isfield(event, 'latency'), return; end; for index = indices event(index).latency = event(index).latency*srate*timeunit+1; end; % create new field names % ---------------------- function epochfield = getnewfields( epochfield, nbfields ) count = 1; while nbfields > 0 if isempty( strmatch([ 'var' int2str(count) ], epochfield ) ) epochfield = { epochfield{:} [ 'var' int2str(count) ] }; nbfields = nbfields-1; else count = count+1; end; end; return; function var = setstruct( var, fieldname, indices, values ) if exist('indices') ~= 1, indices = 1:length(var); end; if length(values) > 1 for index = 1:length(indices) var = setfield(var, {indices(index)}, fieldname, values(index)); end; else for index = 1:length(indices) var = setfield(var, {indices(index)}, fieldname, values); end; end; return;
github
lcnhappe/happe-master
eeg_mergelocs_diffstruct.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_mergelocs_diffstruct.m
5,083
utf_8
91e039a2591913d015acd76805b6b6ff
% eeg_mergelocs() - merge channel structure while preserving channel % order % % >> mergedlocs = eeg_mergelocs(loc1, loc2, loc3, ...); % % Inputs: % loc1 - EEGLAB channel location structure % loc2 - second EEGLAB channel location structure % % Output: % mergedlocs - merged channel location structure % % Author: Arnaud Delorme, August 2006 % Copyright (C) Arnaud Delorme, CERCO, 2006, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [alllocs warn] = eeg_mergelocs(varargin) persistent warning_shown; warn = 0; % sort by length % -------------- len = cellfun(@length, varargin); [tmp so] = sort(len, 2, 'descend'); varargin = varargin(so); alllocs = varargin{1}; for index = 2:length(varargin) % fuse while preserving order (assumes the same channel order) % ------------------------------------------------------------ tmplocs = varargin{index}; newlocs = myunion(alllocs, tmplocs); if length(newlocs) > length(union({ alllocs.labels }, { tmplocs.labels })) warn = 1; if isempty(warning_shown) disp('Warning: different channel montage order for the different datasets'); warning_shown = 1; end; % trying to preserve order of the longest array %---------------------------------------------- if length(alllocs) < length(tmplocs) tmp = alllocs; alllocs = tmplocs; tmplocs = tmp; end; allchans = { alllocs.labels tmplocs.labels }; [uniquechan ord1 ord2 ] = unique_bc( allchans ); [tmp rminds] = intersect_bc( uniquechan, { alllocs.labels }); ord1(rminds) = []; tmplocsind = ord1-length(alllocs); newlocs = concatlocs(alllocs, tmplocs(tmplocsind)); end; alllocs = newlocs; end; % union of two channel location structure % without loosing the order information % --------------------------------------- function alllocs = myunion(locs1, locs2) labs1 = { locs1.labels }; labs2 = { locs2.labels }; count1 = 1; count2 = 1; count3 = 1; alllocs = locs1; alllocs(:) = []; while count1 <= length(locs1) | count2 <= length(locs2) if count1 > length(locs1) alllocs = copyfields(alllocs, count3, locs2(count2)); %alllocs(count3) = locs2(count2); count2 = count2 + 1; count3 = count3 + 1; elseif count2 > length(locs2) alllocs = copyfields(alllocs, count3, locs1(count1)); %alllocs(count3) = locs1(count1); count1 = count1 + 1; count3 = count3 + 1; elseif strcmpi(labs1{count1}, labs2{count2}) alllocs = copyfields(alllocs, count3, locs1(count1)); %alllocs(count3) = locs1(count1); count1 = count1 + 1; count2 = count2 + 1; count3 = count3 + 1; elseif isempty(strmatch(labs1{count1}, labs2, 'exact')) alllocs = copyfields(alllocs, count3, locs1(count1)); %alllocs(count3) = locs1(count1); count1 = count1 + 1; count3 = count3 + 1; else alllocs = copyfields(alllocs, count3, locs2(count2)); %alllocs(count3) = locs2(count2); count2 = count2 + 1; count3 = count3 + 1; end; end; % concatenate channel structures with different fields function loc3 = concatlocs(loc1, loc2); fields1 = fieldnames(loc1); fields2 = fieldnames(loc2); if isequal(fields1, fields2) % the try, catch clause is necessary % below seems to be a Matlab bug try, loc3 = [ loc1; loc2 ]; catch try loc3 = [ loc1 loc2 ]; catch, loc3 = [ loc1(:)' loc2(:)' ]; end; end; else loc3 = loc1; for index = 1:length(loc2) loc3 = copyfields(loc3, length(loc1)+index, loc2(index)); end; end; % copy fields of a structure to another one function [struct1] = copyfields(struct1, index1, struct2) fields1 = fieldnames(struct1); fields2 = fieldnames(struct2); if isequal(fields1, fields2) struct1(index1) = struct2; else for index = 1:length(fields2) struct1 = setfield(struct1, {index1}, fields2{index}, getfield(struct2, fields2{index})); end; end;
github
lcnhappe/happe-master
pop_envtopo.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_envtopo.m
8,687
utf_8
89ae576831e60b8de872e2a39e41d892
% pop_envtopo() - Plot envelope of an averaged EEG epoch, plus scalp maps % of specified or largest contributing components referenced % to their time point of maximum variance in the epoch or specified % sub-epoch. Calls envtopo(). When nargin < 3, a query window % pops-up to allow additional arguments. % Usage: % >> pop_envtopo( EEG ); % pop-up window mode % >> pop_envtopo( EEG, timerange, 'key', 'val', ...); % % Inputs: % EEG - input dataset. Can also be an array of two epoched datasets. % In this case, the epoch mean (ERP) of the second is subtracted % from the epoch mean (ERP) of the first. Note: The ICA weights % must be the same for the two datasets. % timerange - [min max] time range (in ms) in epoch to plot, or if [], from EEG % % Optional inputs: % 'key','val' - optional envtopo() and topoplot() arguments % (see >> help topoplot()) % % Outputs: Same as envtopo(). When nargin < 3, a query window pops-up % to ask for additional arguments and no outputs are returned. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: envtopo(), 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 reformatted help & license -ad % 03-16-02 added all topoplot() options -ad % 03-18-02 added title -ad & sm function varargout = pop_envtopo( EEG, timerange, varargin); varargout{1} = ''; if nargin < 1 help pop_envtopo; return; end; if length(EEG) == 1 & isempty( EEG.icasphere ) disp('Error: cannot make plot without ICA weights. See "Tools > Run ICA".'); return; end; if length(EEG) == 1 & isempty(EEG.chanlocs) fprintf('Cannot make plot without channel locations. See "Edit > Dataset info".\n'); return; end; if exist('envtitle') ~= 1 envtitle = 'Largest ERP components'; end; options = ','; if nargin < 3 % which set to save % ----------------- promptstr = { 'Enter time range (in ms) to plot:', ... 'Enter time range (in ms) to rank component contributions:', ... 'Number of largest contributing components to plot (7):', ... 'Else plot these component numbers only (Ex: 2:4,7):', ... 'Component numbers to remove from data before plotting:' ... 'Plot title:' ... 'Optional topoplot() and envtopo() arguments:' }; inistr = { [num2str( EEG(end).xmin*1000) ' ' num2str(EEG(end).xmax*1000)], ... [num2str( EEG(end).xmin*1000) ' ' num2str(EEG(end).xmax*1000)], ... '7', ... '', ... '', ... ['Largest ERP components' fastif(isempty(EEG(end).setname), '',[' of ' EEG(end).setname])] ... '''electrodes'',''off''' }; if length(EEG) > 1 promptstr = { 'Dataset indices to subtract (Ex: ''1 2''-> 1-2)' promptstr{:} }; inistr = { '2 1' inistr{:} }; end; result = inputdlg2( promptstr, 'Plot component and ERP envelopes -- pop_envtopo()', 1, inistr, 'pop_envtopo'); if length(result) == 0 return; end; if length(EEG) > 1 subindices = eval( [ '[' result{1} ']' ] ); result(1) = []; EEG = EEG(subindices(1:2)); fprintf('pop_envtopo(): Subtracting the epoch mean of dataset %d from that of dataset %d\n', ... subindices(2), subindices(1)); end; timerange = eval( [ '[' result{1} ']' ] ); if ~isempty( result{2} ), options = [ options '''limcontrib'',[' result{2} '],' ]; end; if ~isempty( result{3} ), options = [ options '''compsplot'',[' result{3} '],' ]; end; if ~isempty( result{4} ), options = [ options '''compnums'',[' result{4} '],' ]; end; if ~isempty(result{5}), options = [ options '''subcomps'',[' result{5} '],' ]; end; if ~isempty(result{6}), options = [ options '''title'', ''' result{6} ''',' ]; end; options = [ options result{7} ]; fig = figure; if ~isnumeric(fig), fig = fig.Number; end; optionsplot = [ options ', ''figure'',' int2str(fig) ]; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; else if isempty(timerange) timerange = [EEG.xmin*1000 EEG.xmax*1000]; end options = [options vararg2str( varargin ) ]; optionsplot = options; end; if length(EEG) > 2 error('Cannot process more than two datasets'); end; if timerange(1) < max([EEG.xmin])*1000, timerange(1) = max([EEG.xmin])*1000; end; if timerange(2) > min([EEG.xmax])*1000, timerange(2) = min([EEG.xmax])*1000; end; EEG1 = eeg_checkset(EEG(1),'loaddata'); sigtmp = reshape(EEG1.data, EEG1.nbchan, EEG1.pnts, EEG1.trials); if ~isempty(EEG1.icachansind), sigtmp = sigtmp(EEG1.icachansind,:,:); end; if length(EEG) == 2 EEG2 = eeg_checkset(EEG(2),'loaddata'); if ~all(EEG1.icaweights(:) == EEG2.icaweights(:)) error('The ICA decomposition must be the same for the two datasets'); end; sigtmp2 = reshape(EEG2.data, EEG2.nbchan, EEG2.pnts, EEG2.trials); if ~isempty(EEG2.icachansind), sigtmp2 = sigtmp2(EEG2.icachansind,:,:); end; end; posi = round( (timerange(1)/1000-EEG1.xmin) * EEG1.srate) + 1; posf = min(round( (timerange(2)/1000-EEG1.xmin) * EEG1.srate) + 1, EEG1.pnts); % outputs % ------- outstr = ''; if nargin >= 4 for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end; if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end; end; % generate output command % ------------------------ if length( options ) < 2, options = ''; end; if length(EEG) == 1 varargout{1} = sprintf('figure; pop_envtopo(%s, [%s] %s);', ... inputname(1), num2str(timerange), options); else if exist('subindices') varargout{1} = sprintf('figure; pop_envtopo(%s([%s]), [%s] %s);', ... inputname(1), int2str(subindices), num2str(timerange), options); end; end; options = optionsplot; % plot the data % -------------- options = [ options ', ''verbose'', ''off''' ]; if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end; if any(isnan(sigtmp(:))) disp('NaN detected: using nan_mean'); if length(EEG) == 2 com = sprintf(['%s envtopo(nan_mean(sigtmp(:,posi:posf,:),3)-nan_mean(sigtmp2(:,posi:posf,:),3),' ... 'EEG(1).icaweights*EEG(1).icasphere, ' ... '''chanlocs'', EEG(1).chanlocs(EEG(1).chaninfo.icachansind), ''chaninfo'', EEG(1).chaninfo, ''icawinv'', EEG(1).icawinv,' ... '''timerange'', [timerange(1) timerange(2)] %s);' ] , outstr, options); else % length(EEG) == 1 com = sprintf(['%s envtopo(nan_mean(sigtmp(:,posi:posf,:),3), EEG.icaweights*EEG.icasphere, ' ... '''chanlocs'', EEG.chanlocs(EEG.chaninfo.icachansind), ''chaninfo'', EEG.chaninfo, ''icawinv'', EEG.icawinv,' ... '''timerange'', [timerange(1) timerange(2)] %s);' ] , outstr, options); end; else if length(EEG) == 2 com = sprintf(['%s envtopo(mean(sigtmp(:,posi:posf,:),3)-mean(sigtmp2(:,posi:posf,:),3),' ... ' EEG(1).icaweights*EEG(1).icasphere, ' ... '''chanlocs'', EEG(1).chanlocs(EEG(1).chaninfo.icachansind), ''chaninfo'', EEG(1).chaninfo, ''icawinv'', EEG(1).icawinv,' ... '''timerange'', [timerange(1) timerange(2)] %s);' ] , outstr, options); else % length(EEG) == 1 com = sprintf(['%s envtopo(mean(sigtmp(:,posi:posf,:),3), EEG.icaweights*EEG.icasphere, ' ... '''chanlocs'', EEG.chanlocs(EEG.chaninfo.icachansind), ''chaninfo'', EEG.chaninfo, ''icawinv'', EEG.icawinv,' ... '''timerange'', [timerange(1) timerange(2)] %s);' ] , outstr, options); end; end; % fprintf(['\npop_envtopo(): Issuing command: ' com '\n\n']); % type the evntopo() call eval(com); % make the plot using envtopo() return;
github
lcnhappe/happe-master
pop_readlocs.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_readlocs.m
8,752
utf_8
ddf2ebd69a1b663a17650baa003d5b41
% pop_readlocs() - load a EGI-format EEG file (pop up an interactive window if no arguments). % % Usage: % >> EEG = pop_readlocs; % a window pops up % >> EEG = pop_readlocs( filename, 'key', val, ...); % no window % % Inputs: % filename - Electrode location file name % 'key',val - Same options as readlocs() (see >> help readlocs) % % Outputs: same as readlocs() % % Author: Arnaud Delorme, CNL / Salk Institute, 17 Dec 2002 % % See also: readlocs() % Copyright (C) 17 Dec 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 [tmplocs, command] = pop_readlocs(filename, varargin); tmplocs = []; command = ''; % get infos from readlocs % ----------------------- [chanformat listcolformat] = readlocs('getinfos'); listtype = { chanformat.type }; if nargin < 1 [filename, filepath] = uigetfile('*.*', 'Importing electrode location file -- pop_readlocs()'); %filename = 'chan32.locs'; %filepath = 'c:\eeglab\eeglab4.0\'; drawnow; if filename == 0 return; end; filename = [filepath filename]; tmpfile = loadtxt(filename); nbcols = cellfun('isempty', tmpfile(end,:)); nbcols = ones(1,length(find(~nbcols))); % decoding file type % ------------------ periods = find(filename == '.'); fileextension = filename(periods(end)+1:end); switch lower(fileextension), case {'loc' 'locs' }, filetype = 'loc'; case 'xyz', filetype = 'xyz'; case 'sph', filetype = 'sph'; case 'txt', filetype = 'chanedit'; case 'elp', filetype = 'polhemus'; case 'eps', filetype = 'besa'; otherwise, filetype = ''; end; indexfiletype = strmatch(filetype, listtype, 'exact'); % convert format info % ------------------- formatinfo = { chanformat.importformat }; formatskipcell = { chanformat.skipline }; rmindex = []; count = 1; for index = 1:length(formatinfo) if ~isstr(formatinfo{index}) for index2 = 1:length(formatinfo{index}) indexformat = strmatch(formatinfo{index}{index2}, listcolformat, 'exact'); indexlist(count, index2) = indexformat; end; if isempty(formatskipcell{index}), formatskip(count) = 0; else formatskip(count) = formatskipcell{index}; end; count = count+1; else rmindex = [ rmindex index ]; end; end; listtype(rmindex) = []; listtype (end+1) = { 'custom' }; formatskip(end+1) = 0; indexlist(end+1,:) = -1; % ask user formatcom = [ ... 'indexformat = get(findobj(gcf, ''tag'', ''format''), ''value'');' ... 'tmpformat = get(findobj(gcf, ''tag'', ''format''), ''userdata'');' ... 'for tmpindex=1:' int2str(length(nbcols)) ... ' tmpobj = findobj(gcf, ''tag'', [ ''col'' int2str(tmpindex) ]);' ... ' if tmpformat{1}(indexformat,tmpindex) == -1,' ... ' set(tmpobj, ''enable'', ''on'');' ... ' else ' ... ' set(tmpobj, ''enable'', ''off'');' ... ' set(tmpobj, ''value'', tmpformat{1}(indexformat,tmpindex));' ... ' end;' ... 'end;' ... 'strheaderline = fastif(tmpformat{2}(indexformat)<0, ''auto'', int2str(tmpformat{2}(indexformat)));' ... 'set(findobj(gcf, ''tag'', ''headlines''), ''string'', strheaderline);' ... 'eval(get(findobj(gcf, ''tag'', ''headlines''), ''callback''));' ... 'clear tmpindex indexformat tmpformat tmpobj strheaderline;' ]; headercom = [ ... 'tmpheader = str2num(get(findobj(gcf, ''tag'', ''headlines''), ''string''));' ... 'if ~isempty(tmpheader), ' ... ' for tmpindex=1:' int2str(length(nbcols)) ... ' tmpobj = findobj(gcf, ''tag'', [ ''text'' int2str(tmpindex) ]);' ... ' tmpstr = get(tmpobj, ''userdata'');' ... ' set(tmpobj, ''string'', tmpstr(tmpheader+1:min(tmpheader+10, size(tmpstr,1)),:));' ... ' end;' ... 'end;' ... 'clear tmpobj tmpstr tmpheader tmpindex;' ]; geometry = { [1 1 1] [1 2] [nbcols] [nbcols] [nbcols] [1] [1 1 1]}; listui = { ... { 'style' 'text' 'string' 'Predefined format' } ... { 'style' 'text' 'string' 'Header lines' } ... { 'style' 'edit' 'tag' 'headlines' 'string' '0' 'callback' headercom } ... { 'style' 'listbox' 'tag' 'format' 'string' strvcat(listtype{:}) ... 'callback' formatcom 'userdata' { indexlist;formatskip } } ... { 'style' 'pushbutton' 'string' 'preview' ... 'callback' 'set(findobj(gcbf, ''tag'', ''Import''), ''userdata'', ''preview'')'} }; % custom columns % -------------- for index = 1:length(nbcols) listui{end+1} = { 'style' 'text' 'string' [ 'column ' int2str(index) ] }; end; for index = 1:length(nbcols) listui{end+1} = { 'style' 'listbox' 'tag' [ 'col' int2str(index) ] 'string' ... strvcat(listcolformat{:}) }; end; for index = 1:length(nbcols) listui{end+1} = { 'style' 'text' 'string' formatstr(tmpfile(1:min(10, size(tmpfile,1)),index)) ... 'tag' ['text' int2str(index) ] 'userdata' formatstr(tmpfile(:,index)) }; end; listui = { listui{:} ... {} ... { 'style' 'pushbutton' 'string' 'Cancel', 'callback', 'close gcbf;' } ... { 'style' 'pushbutton' 'string' 'Help', 'callback', 'pophelp(''pop_readlocs'');' } ... { 'style' 'pushbutton' 'string' 'Import' 'tag' 'Import' ... 'callback', 'set(findobj(gcbf, ''tag'', ''Import''), ''userdata'', ''import'')'} }; fig = figure('name', 'Importing electrode location file -- pop_readlocs()', 'visible', 'off'); supergui( fig, geometry, [1 2 1 3 7 1 1], listui{:}); % update figure set(findobj(gcf, 'tag', 'format'), 'value', indexfiletype); eval(formatcom); % this loop is necessary for decoding Preview cont = 1; while cont waitfor( findobj('parent', fig, 'tag', 'Import'), 'userdata'); if isempty( findobj('parent', fig, 'tag', 'Import') ), return; end; % decode inputs % ------------- tmpheader = str2num(get(findobj(fig, 'tag', 'headlines'), 'string')); tmpobj = findobj(fig, 'tag', 'format'); tmpformatstr = get(tmpobj, 'string'); tmpformatstr = tmpformatstr(get(tmpobj, 'value'),:); for tmpindex=1:length(nbcols) tmpobj = findobj(fig, 'tag', [ 'col' int2str(tmpindex) ]); tmpcolstr{tmpindex} = get(tmpobj, 'string'); tmpcolstr{tmpindex} = deblank(tmpcolstr{tmpindex}(get(tmpobj,'value'),:)); end; % take appropriate measures % ------------------------- res = get(findobj('parent', fig, 'tag', 'Import'), 'userdata'); set(findobj('parent', fig, 'tag', 'Import'), 'userdata', ''); if strcmp(res, 'preview') try, tmplocs = readlocs( filename, 'filetype', tmpformatstr, ... 'skiplines', tmpheader, 'format', tmpcolstr); figure; topoplot([],tmplocs, 'style', 'blank', 'electrodes', 'labelpoint'); catch, errordlg2(strvcat('Error while importing locations:', lasterr), 'Error'); end; else cont = 0; end; end; close(fig); % importing files % --------------- tmplocs = readlocs( filename, 'filetype', tmpformatstr, ... 'skiplines', tmpheader, 'format', tmpcolstr); else tmplocs = readlocs( filename, varargin{:}); end; command = sprintf('EEG.chanlocs = pop_readlocs(''%s'', %s);', filename, vararg2str(varargin)); return; % format string for text file % --------------------------- function alltxt = formatstr( celltxt ) for index1 = 1:size(celltxt,1) alltxt{index1} = ''; for index2 = 1:size(celltxt,2) alltxt{index1} = sprintf('%s\t%s', alltxt{index1}, num2str(celltxt{index1,index2})); end; alltxt{index1} = sprintf(alltxt{index1}, '%s\n', alltxt{index1}); end; alltxt = strvcat( alltxt{:});
github
lcnhappe/happe-master
pop_runica.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_runica.m
25,380
utf_8
8bde9961b840c40e8b2743eec81903f2
% pop_runica() - Run an ICA decomposition of an EEG dataset using runica(), % binica(), or another ICA or other linear decomposition. % Usage: % >> OUT_EEG = pop_runica( EEG ); % pops-up a data entry window % >> OUT_EEG = pop_runica( EEG, 'key', 'val' ); % no pop_up % % Graphic interface: % "ICA algorithm to use" - [edit box] The ICA algorithm to use for % ICA decomposition. Command line equivalent: 'icatype' % "Commandline options" - [edit box] Command line options to forward % to the ICA algorithm. Command line equivalent: 'options' % Inputs: % EEG - input EEG dataset or array of datasets % % Optional inputs: % 'icatype' - ['runica'|'binica'|'jader'|'fastica'] ICA algorithm % to use for the ICA decomposition. The nature of any % differences in the results of these algorithms have % not been well characterized. {default: binica(), if % found, else runica()} % 'dataset' - [integer array] dataset index or indices. % 'chanind' - [integer array or cell array] subset of channel indices % for running the ICA decomposition. Alternatively, you may % also enter channel types here in a cell array. % 'concatenate' - ['on'|'off'] 'on' concatenate all input datasets % (assuming there are several). 'off' run ICA independently % on each dataset. Default is 'off'. % 'concatcond' - ['on'|'off'] 'on' concatenate conditions for input datasets % of the same sessions and the same subject. Default is 'off'. % 'key','val' - ICA algorithm options (see ICA routine help messages). % % Adding a new algorithm: % Add the algorithm to the list of algorithms line 366 to 466, for example % % case 'myalgo', [EEG.icaweights] = myalgo( tmpdata, g.options{:} ); % % where "myalgo" is the name of your algorithm (and Matlab function). % tmpdata is the 2-D array containing the EEG data (channels x points) and % g.options{} contains custom options for your algorithm (there is no % predetermined format for these options). The output EEG.icaweights is the % mixing matrix (or inverse of the unmixing matrix). % % Note: % 1) Infomax (runica, binica) is the ICA algorithm we use most. It is based % on Tony Bell's infomax algorithm as implemented for automated use by % Scott Makeig et al. using the natural gradient of Amari et al. It can % also extract sub-Gaussian sources using the (recommended) 'extended' option % of Lee and Girolami. Function runica() is the all-Matlab version; function % binica() calls the (1.5x faster) binary version (a separate download) % translated into C from runica() by Sigurd Enghoff. % 2) jader() calls the JADE algorithm of Jean-Francois Cardoso. This is % included in the EEGLAB toolbox by his permission. See >> help jader % 3) To run fastica(), download the fastICA toolbox from its website, % http://www.cis.hut.fi/projects/ica/fastica/, and make it available % in your Matlab path. According to its authors, default parameters % are not optimal: Try args 'approach', 'sym' to estimate components % in parallel. % 4) By default the function resaves the datasets when multiple datasets % are processed. % % Outputs: % OUT_EEG = The input EEGLAB dataset with new fields icaweights, icasphere % and icachansind (channel indices). % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: runica(), binica(), jader(), fastica() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-07-02 add the eeglab options -ad % 03-18-02 add other decomposition options -ad % 03-19-02 text edition -sm function [ALLEEG, com] = pop_runica( ALLEEG, varargin ) com = ''; if nargin < 1 help pop_runica; return; end; % find available algorithms % ------------------------- allalgs = { 'runica' 'binica' 'jader' 'jadeop' 'jade_td_p' 'MatlabshibbsR' 'fastica' ... 'tica' 'erica' 'simbec' 'unica' 'amuse' 'fobi' 'evd' 'evd24' 'sons' 'sobi' 'ng_ol' ... 'acsobiro' 'acrsobibpf' 'pearson_ica' 'egld_ica' 'eeA' 'tfbss' 'icaML' 'icaMS' }; % do not use egld_ica => too slow selectalg = {}; linenb = 1; count = 1; for index = length(allalgs):-1:1 if exist(allalgs{index}) ~= 2 & exist(allalgs{index}) ~= 6 allalgs(index) = []; end; end; % special AMICA % ------------- selectamica = 0; defaultopts = [ '''extended'', 1' ] ; if nargin > 1 if isstr(varargin{1}) if strcmpi(varargin{1}, 'selectamica') selectamica = 1; allalgs = { 'amica' allalgs{:} }; defaultopts = sprintf('''outdir'', ''%s''', fullfile(pwd, 'amicaout')); elseif strcmpi(varargin{1}, 'selectamicaloc') selectamica = 1; allalgs = { 'amica' allalgs{:} }; defaultopts = sprintf('''outdir'', ''%s'', ''qsub'', ''off''', fullfile(pwd, 'amicaout')); end; end; end; % popup window parameters % ----------------------- fig = []; if nargin < 2 | selectamica commandchans = [ 'tmpchans = get(gcbf, ''userdata'');' ... 'tmpchans = tmpchans{1};' ... 'set(findobj(gcbf, ''tag'', ''chantype''), ''string'', ' ... ' int2str(pop_chansel( tmpchans )));' ... 'clear tmpchans;' ]; commandtype = ['tmptype = get(gcbf, ''userdata'');' ... 'tmptype = tmptype{2};' ... 'if ~isempty(tmptype),' ... ' [tmps,tmpv, tmpstr] = listdlg2(''PromptString'',''Select type(s)'', ''ListString'', tmptype);' ... ' if tmpv' ... ' set(findobj(''parent'', gcbf, ''tag'', ''chantype''), ''string'', tmpstr);' ... ' end;' ... 'else,' ... ' warndlg2(''No channel type'', ''No channel type'');' ... 'end;' ... 'clear tmps tmpv tmpstr tmptype tmpchans;' ]; cb_ica = [ 'if get(gcbo, ''value'') < 3, ' ... ' set(findobj(gcbf, ''tag'', ''params''), ''string'', ''''''extended'''', 1'');' ... 'else set(findobj(gcbf, ''tag'', ''params''), ''string'', '''');' ... 'end;' ]; promptstr = { { 'style' 'text' 'string' 'ICA algorithm to use (click to select)' } ... { 'style' 'listbox' 'string' strvcat(allalgs{:}) 'callback', cb_ica } ... { 'style' 'text' 'string' 'Commandline options (See help messages)' } ... { 'style' 'edit' 'string' defaultopts 'tag' 'params' } ... { 'style' 'text' 'string' 'Channel type(s) or channel indices' } ... { 'style' 'edit' 'string' '' 'tag' 'chantype' } ... { 'style' 'pushbutton' 'string' '... types' 'callback' commandtype } ... { 'style' 'pushbutton' 'string' '... channels' 'callback' commandchans } }; geometry = { [2 1.5] [2 1.5] [2 1 1 1] }; if length(ALLEEG) > 1 cb1 = 'set(findobj(''parent'', gcbf, ''tag'', ''concat2''), ''value'', 0);'; cb2 = 'set(findobj(''parent'', gcbf, ''tag'', ''concat1''), ''value'', 0);'; promptstr = { promptstr{:}, ... { 'style' 'text' 'string' 'Concatenate all datasets (check=yes; uncheck=run ICA on each dataset)?' }, ... { 'style' 'checkbox' 'string' '' 'value' 0 'tag' 'concat1' 'callback' cb1 }, ... { 'style' 'text' 'string' 'Concatenate datasets for the same subject and session (check=yes)?' }, ... { 'style' 'checkbox' 'string' '' 'value' 1 'tag' 'concat2' 'callback' cb2 } }; geometry = { geometry{:} [ 2 0.2 ] [ 2 0.2 ]}; end; % channel types % ------------- if isfield(ALLEEG(1).chanlocs, 'type'), tmpchanlocs = ALLEEG(1).chanlocs; alltypes = { tmpchanlocs.type }; indempty = cellfun('isempty', alltypes); alltypes(indempty) = ''; try, alltypes = unique_bc(alltypes); catch, alltypes = ''; end; else alltypes = ''; end; % channel labels % -------------- if ~isempty(ALLEEG(1).chanlocs) tmpchanlocs = ALLEEG(1).chanlocs; alllabels = { tmpchanlocs.labels }; else for index = 1:ALLEEG(1).nbchan alllabels{index} = int2str(index); end; end; % gui % --- result = inputgui( 'geometry', geometry, 'uilist', promptstr, ... 'helpcom', 'pophelp(''pop_runica'')', ... 'title', 'Run ICA decomposition -- pop_runica()', 'userdata', { alllabels alltypes } ); if length(result) == 0 return; end; options = { 'icatype' allalgs{result{1}} 'dataset' [1:length(ALLEEG)] 'options' eval( [ '{' result{2} '}' ]) }; if ~isempty(result{3}) if ~isempty(str2num(result{3})), options = { options{:} 'chanind' str2num(result{3}) }; else options = { options{:} 'chanind' parsetxt(result{3}) }; end; end; if length(result) > 3 options = { options{:} 'concatenate' fastif(result{4}, 'on', 'off') }; options = { options{:} 'concatcond' fastif(result{5}, 'on', 'off') }; end; else if mod(length(varargin),2) == 1 options = { 'icatype' varargin{1:end} }; else options = varargin; end; end; % decode input arguments % ---------------------- [ g addoptions ] = finputcheck( options, { 'icatype' 'string' allalgs 'runica'; ... 'dataset' 'integer' [] [1:length(ALLEEG)]; 'options' 'cell' [] {}; 'concatenate' 'string' { 'on','off' } 'off'; 'resave' 'string' { 'on','off' } 'on'; % hidden option (only valid when multiple datasets and concat mode) 'concatcond' 'string' { 'on','off' } 'off'; 'chanind' { 'cell','integer' } { [] [] } [];}, ... 'pop_runica', 'ignore'); if isstr(g), error(g); end; if ~isempty(addoptions), g.options = { g.options{:} addoptions{:}}; end; % select datasets, create new big dataset if necessary % ---------------------------------------------------- if length(g.dataset) == 1 EEG = ALLEEG(g.dataset); EEG = eeg_checkset(EEG, 'loaddata'); % continue after test elseif length(ALLEEG) > 1 & ~strcmpi(g.concatenate, 'on') & ~strcmpi(g.concatcond, 'on') [ ALLEEG com ] = eeg_eval( 'pop_runica', ALLEEG, 'warning', 'off', 'params', ... { 'icatype' g.icatype 'options' g.options 'chanind' g.chanind } ); return; elseif length(ALLEEG) > 1 & strcmpi(g.concatcond, 'on') allsubjects = { ALLEEG.subject }; allsessions = { ALLEEG.session }; allgroups = { ALLEEG.group }; alltags = zeros(1,length(allsubjects)); if any(cellfun('isempty', allsubjects)) errordlg2( [ 'Aborting: Subject names missing from at least one dataset.' 10 ... 'Use the STUDY > Edit STUDY Info menu and check the box' 10 ... '"Dataset info (condition, group, ...) differs from study info..."' ]); end; dats = {}; for index = 1:length(allsubjects) if ~alltags(index) allinds = strmatch(allsubjects{index}, allsubjects, 'exact'); rmind = []; % if we have different sessions they will not be concatenated for tmpi = setdiff_bc(allinds,index)' if ~isequal(allsessions(index), allsessions(tmpi)), rmind = [rmind tmpi]; %elseif ~isequal(allgroups(index), allgroups(tmpi)), rmind = [rmind tmpi]; end; end; allinds = setdiff_bc(allinds, rmind); fprintf('Found %d datasets for subject ''%s''\n', length(allinds), allsubjects{index}); dats = { dats{:} allinds }; alltags(allinds) = 1; end; end; fprintf('**************************\nNOW RUNNING ALL DECOMPOSITIONS\n****************************\n'); for index = 1:length(dats) ALLEEG(dats{index}) = pop_runica(ALLEEG(dats{index}), 'icatype', g.icatype, ... 'options', g.options, 'chanind', g.chanind, 'concatenate', 'on', 'resave', 'off'); for idat = 1:length(dats{index}) ALLEEG(dats{index}(idat)).saved = 'no'; pop_saveset(ALLEEG(dats{index}(idat)), 'savemode', 'resave'); ALLEEG(dats{index}(idat)).saved = 'yes'; end; end; com = sprintf('%s = pop_runica(%s, %s);', inputname(1),inputname(1), ... vararg2str({ 'icatype' g.icatype 'concatcond' 'on' 'options' g.options }) ); return; else disp('Concatenating datasets...'); EEG = ALLEEG(g.dataset(1)); % compute total data size % ----------------------- totalpnts = 0; for i = g.dataset totalpnts = totalpnts+ALLEEG(g.dataset(i)).pnts*ALLEEG(g.dataset(i)).trials; end; EEG.data = zeros(EEG.nbchan, totalpnts); % copy data % --------- cpnts = 1; for i = g.dataset tmplen = ALLEEG(g.dataset(i)).pnts*ALLEEG(g.dataset(i)).trials; TMP = eeg_checkset(ALLEEG(g.dataset(i)), 'loaddata'); EEG.data(:,cpnts:cpnts+tmplen-1) = reshape(TMP.data, size(TMP.data,1), size(TMP.data,2)*size(TMP.data,3)); cpnts = cpnts+tmplen; end; EEG.icaweights = []; EEG.trials = 1; EEG.pnts = size(EEG.data,2); EEG.saved = 'no'; EEG = pop_runica(EEG, 'icatype', g.icatype, 'options', g.options, 'chanind', g.chanind); for idat = 1:length(ALLEEG) ALLEEG(idat).saved = 'no'; ALLEEG(idat).icaweights = EEG.icaweights; ALLEEG(idat).icasphere = EEG.icasphere; if strcmpi(g.resave, 'on') pop_saveset(ALLEEG(idat), 'savemode', 'resave'); ALLEEG(idat).saved = 'yes'; end; end; return; end; % below processing at most one dataset % Store and then remove current EEG ICA weights and sphere % --------------------------------------------------- fprintf('\n'); if ~isempty(EEG.icaweights) fprintf('Saving current ICA decomposition in "EEG.etc.oldicaweights" (etc.).\n'); if ~isfield(EEG,'etc'), EEG.etc = []; end; if ~isfield(EEG.etc,'oldicaweights') EEG.etc.oldicaweights = {}; EEG.etc.oldicasphere = {}; EEG.etc.oldicachansind = {}; end; tmpoldicaweights = EEG.etc.oldicaweights; tmpoldicasphere = EEG.etc.oldicasphere; tmpoldicachansind = EEG.etc.oldicachansind; EEG.etc.oldicaweights = { EEG.icaweights tmpoldicaweights{:} }; EEG.etc.oldicasphere = { EEG.icasphere tmpoldicasphere{:} }; EEG.etc.oldicachansind = { EEG.icachansind tmpoldicachansind{:} }; fprintf(' Decomposition saved as entry %d.\n',length(EEG.etc.oldicaweights)); end EEG.icaweights = []; EEG.icasphere = []; EEG.icawinv = []; EEG.icaact = []; % select sub_channels % ------------------- if isempty(g.chanind) g.chanind = 1:EEG.nbchan; end; if iscell(g.chanind) g.chanind = eeg_chantype(EEG.chanlocs, g.chanind); end; EEG.icachansind = g.chanind; % is pca already an option? % ------------------------- pca_opt = 0; for i = 1:length(g.options) if isstr(g.options{i}) if strcmpi(g.options{i}, 'pca') pca_opt = 1; end; end; end; %------------------------------ % compute ICA on a definite set % ----------------------------- tmpdata = reshape( EEG.data(g.chanind,:,:), length(g.chanind), EEG.pnts*EEG.trials); tmprank = getrank(double(tmpdata(:,1:min(3000, size(tmpdata,2))))); tmpdata = tmpdata - repmat(mean(tmpdata,2), [1 size(tmpdata,2)]); % zero mean if ~strcmpi(lower(g.icatype), 'binica') try disp('Attempting to convert data matrix to double precision for more accurate ICA results.') tmpdata = double(tmpdata); tmpdata = tmpdata - repmat(mean(tmpdata,2), [1 size(tmpdata,2)]); % zero mean (more precise than single precision) catch disp('*************************************************************') disp('Not enough memory to convert data matrix to double precision.') disp('All computations will be done in single precision. Matlab 7.x') disp('under 64-bit Linux and others is imprecise in this mode.') disp('We advise use of "binica" instead of "runica."') disp('*************************************************************') end; end; switch lower(g.icatype) case 'runica' try, if ismatlab, g.options = { g.options{:}, 'interupt', 'on' }; end; catch, end; if tmprank == size(tmpdata,1) | pca_opt [EEG.icaweights,EEG.icasphere] = runica( tmpdata, 'lrate', 0.001, g.options{:} ); else if nargin < 2 uilist = { { 'style' 'text' 'string' [ 'EEGLAB has detected that the rank of your data matrix' 10 ... 'is lower the number of input data channels. This might' 10 ... 'be because you are including a reference channel or' 10 ... 'because you are running a second ICA decomposition.' 10 ... sprintf('The proposed dimension for ICA is %d (out of %d channels).', tmprank, size(tmpdata,1)) 10 ... 'Rank computation may be innacurate so you may edit this' 10 ... 'number below. If you do not understand, simply press OK.' ] } { } ... { 'style' 'text' 'string' 'Proposed rank:' } ... { 'style' 'edit' 'string' num2str(tmprank) } }; res = inputgui('uilist', uilist, 'geometry', { [1] [1] [1 1] }, 'geomvert', [6 1 1]); if isempty(res), return; end; tmprank = str2num(res{1}); g.options = [g.options { 'pca' tmprank }]; else g.options = [g.options {'pca' tmprank }]; % automatic for STUDY (batch processing) end; disp(['Data rank (' int2str(tmprank) ') is smaller than the number of channels (' int2str(size(tmpdata,1)) ').']); [EEG.icaweights,EEG.icasphere] = runica( tmpdata, 'lrate', 0.001, g.options{:} ); end; case 'binica' icadefs; fprintf(['Warning: If the binary ICA function does not work, check that you have added the\n' ... 'binary file location (in the EEGLAB directory) to your Unix /bin directory (.cshrc file)\n']); if exist(ICABINARY) ~= 2 error('Pop_runica(): binary ICA executable not found. Edit icadefs.m file to specify the ICABINARY location'); end; tmprank = getrank(tmpdata(:,1:min(3000, size(tmpdata,2)))); if tmprank == size(tmpdata,1) | pca_opt [EEG.icaweights,EEG.icasphere] = binica( tmpdata, 'lrate', 0.001, g.options{:} ); else disp(['Data rank (' int2str(tmprank) ') is smaller than the number of channels (' int2str(size(tmpdata,1)) ').']); [EEG.icaweights,EEG.icasphere] = binica( tmpdata, 'lrate', 0.001, 'pca', tmprank, g.options{:} ); end; case 'amica' tmprank = getrank(tmpdata(:,1:min(3000, size(tmpdata,2)))); fprintf('Now Running AMICA\n'); if length(g.options) > 1 if isstr(g.options{2}) fprintf('See folder %s for outputs\n', g.options{2}); end; end; fprintf('To import results, use menu item "Tools > Run AMICA > Load AMICA components\n'); modres = runamica( tmpdata, [], size(tmpdata,1), size(tmpdata,2), g.options{:} ); if ~isempty(modres) EEG.icaweights = modres.W; EEG.icasphere = modres.S; else return; end; case 'pearson_ica' if isempty(g.options) disp('Warning: EEGLAB default for pearson ICA is 1000 iterations and epsilon=0.0005'); [tmp EEG.icaweights] = pearson_ica( tmpdata, 'maxNumIterations', 1000,'epsilon',0.0005); else [tmp EEG.icaweights] = pearson_ica( tmpdata, g.options{:}); end; case 'egld_ica', disp('Warning: This algorithm is very slow!!!'); [tmp EEG.icaweights] = egld_ica( tmpdata, g.options{:} ); case 'tfbss' if isempty(g.options) [tmp EEG.icaweights] = tfbss( tmpdata, size(tmpdata,1), 8, 512 ); else [tmp EEG.icaweights] = tfbss( tmpdata, g.options{:} ); end; case 'jader', [EEG.icaweights] = jader( tmpdata, g.options{:} ); case 'matlabshibbsr', [EEG.icaweights] = MatlabshibbsR( tmpdata, g.options{:} ); case 'eea', [EEG.icaweights] = eeA( tmpdata, g.options{:} ); case 'icaml', [tmp EEG.icawinv] = icaML( tmpdata, g.options{:} ); case 'icams', [tmp EEG.icawinv] = icaMS( tmpdata, g.options{:} ); case 'fastica', [ ICAcomp, EEG.icawinv, EEG.icaweights] = fastica( tmpdata, 'displayMode', 'off', g.options{:} ); case { 'tica' 'erica' 'simbec' 'unica' 'amuse' 'fobi' 'evd' 'sons' ... 'jadeop' 'jade_td_p' 'evd24' 'sobi' 'ng_ol' 'acsobiro' 'acrsobibpf' } fig = figure('tag', 'alg_is_run', 'visible', 'off'); if isempty(g.options), g.options = { size(tmpdata,1) }; end; switch lower(g.icatype) case 'tica', EEG.icaweights = tica( tmpdata, g.options{:} ); case 'erica', EEG.icaweights = erica( tmpdata, g.options{:} ); case 'simbec', EEG.icaweights = simbec( tmpdata, g.options{:} ); case 'unica', EEG.icaweights = unica( tmpdata, g.options{:} ); case 'amuse', EEG.icaweights = amuse( tmpdata ); case 'fobi', [tmp EEG.icaweights] = fobi( tmpdata, g.options{:} ); case 'evd', EEG.icaweights = evd( tmpdata, g.options{:} ); case 'sons', EEG.icaweights = sons( tmpdata, g.options{:} ); case 'jadeop', EEG.icaweights = jadeop( tmpdata, g.options{:} ); case 'jade_td_p',EEG.icaweights = jade_td_p( tmpdata, g.options{:} ); case 'evd24', EEG.icaweights = evd24( tmpdata, g.options{:} ); case 'sobi', EEG.icawinv = sobi( tmpdata, g.options{:} ); case 'ng_ol', [tmp EEG.icaweights] = ng_ol( tmpdata, g.options{:} ); case 'acsobiro', EEG.icawinv = acsobiro( tmpdata, g.options{:} ); case 'acrsobibpf', EEG.icawinv = acrsobibpf( tmpdata, g.options{:} ); end; clear tmp; close(fig); otherwise, error('Pop_runica: unrecognized algorithm'); end; % update weight and inverse matrices etc... % ----------------------------------------- if ~isempty(fig), try, close(fig); catch, end; end; if isempty(EEG.icaweights) EEG.icaweights = pinv(EEG.icawinv); end; if isempty(EEG.icasphere) EEG.icasphere = eye(size(EEG.icaweights,2)); end; if isempty(EEG.icawinv) EEG.icawinv = pinv(EEG.icaweights*EEG.icasphere); % a priori same result as inv end; % copy back data to ALLEEG if necessary % ------------------------------------- EEG = eeg_checkset(EEG); ALLEEG = eeg_store(ALLEEG, EEG, g.dataset); if nargin < 2 || selectamica com = sprintf('%s = pop_runica(%s, %s);', inputname(1), inputname(1), vararg2str(g.options) ); %vararg2str({ 'icatype' g.icatype 'dataset' g.dataset 'options' g.options }) ); end; return; function tmprank2 = getrank(tmpdata); tmprank = rank(tmpdata); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Here: alternate computation of the rank by Sven Hoffman %tmprank = rank(tmpdata(:,1:min(3000, size(tmpdata,2)))); old code covarianceMatrix = cov(tmpdata', 1); [E, D] = eig (covarianceMatrix); rankTolerance = 1e-7; tmprank2=sum (diag (D) > rankTolerance); if tmprank ~= tmprank2 fprintf('Warning: fixing rank computation inconsistency (%d vs %d) most likely because running under Linux 64-bit Matlab\n', tmprank, tmprank2); tmprank2 = max(tmprank, tmprank2); end;
github
lcnhappe/happe-master
pop_importegimat.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_importegimat.m
6,094
utf_8
dba75d9338bed4f93159796aecef4717
% pop_importegimat() - import EGI Matlab segmented file % % Usage: % >> EEG = pop_importegimat(filename, srate, latpoint0); % % Inputs: % filename - Matlab file name % srate - sampling rate % latpoint0 - latency in sample ms of stimulus presentation. % When data files are exported using Netstation, the user specify % a time range (-100 ms to 500 ms for instance). In this % case, the latency of the stimulus is 100 (ms). Default is 0 (ms) % % Output: % EEG - EEGLAB dataset structure % % Authors: Arnaud Delorme, CERCO/UCSD, Jan 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 [EEG com] = pop_importegimat(filename, srate, latpoint0, dataField); EEG = []; com = ''; if nargin < 3, latpoint0 = 0; end; if nargin < 4, dataField = 'Session'; end; if nargin < 1 % ask user [filename, filepath] = uigetfile('*.mat', 'Choose a Matlab file from Netstation -- pop_importegimat()'); if filename == 0 return; end; filename = fullfile(filepath, filename); tmpdata = load('-mat', filename); fieldValues = fieldnames(tmpdata); sessionPos = strmatch('Session', fieldValues); posFieldData = 1; if ~isempty(sessionPos), posFieldData = sessionPos; end; if ~isfield(tmpdata, 'samplingRate'), srate = 250; else srate = tmpdata.samplingRate; end; % epoch data files only promptstr = { { 'style' 'text' 'string' 'Sampling rate (Hz)' } ... { 'style' 'edit' 'string' int2str(srate) } ... { 'style' 'text' 'string' 'Sample latency for stimulus (ms)' } ... { 'style' 'edit' 'string' '0' } ... { 'style' 'text' 'string' 'Field containing data' } ... { 'style' 'popupmenu' 'string' fieldValues 'value' posFieldData } ... }; geometry = { [1 1] [1 1] [1 1] }; result = inputgui( 'geometry', geometry, 'uilist', promptstr, ... 'helpcom', 'pophelp(''pop_importegimat'')', ... 'title', 'Import a Matlab file from Netstation -- pop_importegimat()'); if length(result) == 0 return; end; srate = str2num(result{1}); latpoint0 = str2num(result{2}); dataField = fieldValues{result{3}}; if isempty(latpoint0), latpoint0 = 0; end; end; EEG = eeg_emptyset; fprintf('Reading EGI Matlab file %s\n', filename); tmpdata = load('-mat', filename); if isfield(tmpdata, 'samplingRate') % continuous file srate = tmpdata.samplingRate; end; fieldValues = fieldnames(tmpdata); if all(cellfun(@(x)isempty(findstr(x, 'Segment')), fieldValues)) EEG.srate = srate; indData = strmatch(dataField, fieldValues); EEG.data = tmpdata.(fieldValues{indData(1)}); EEG = eeg_checkset(EEG); EEG = readegilocs(EEG); com = sprintf('EEG = pop_importegimat(''%s'');', filename); else % get data types % -------------- allfields = fieldnames(tmpdata); for index = 1:length(allfields) allfields{index} = allfields{index}(1:findstr(allfields{index}, 'Segment')-2); end; datatypes = unique_bc(allfields); datatypes(cellfun(@isempty, datatypes)) = []; % read all data % ------------- counttrial = 1; EEG.srate = srate; latency = (latpoint0/1000)*EEG.srate+1; for index = 1:length(datatypes) tindex = 1; for tindex = 1:length(allfields) if isfield(tmpdata, sprintf('%s_Segment%d', datatypes{index}, tindex)) datatrial = getfield(tmpdata, sprintf('%s_Segment%d', datatypes{index}, tindex)); if counttrial == 1 EEG.pnts = size(datatrial,2); EEG.data = repmat(single(0), [size(datatrial,1), size(datatrial,2), 1000]); end; EEG.data(:,:,counttrial) = datatrial; EEG.event(counttrial).type = datatypes{index}; EEG.event(counttrial).latency = latency; EEG.event(counttrial).epoch = counttrial; counttrial = counttrial+1; latency = latency + EEG.pnts; end; end; end; fprintf('%d trials read\n', counttrial-1); EEG.data(:,:,counttrial:end) = []; EEG.setname = filename(1:end-4); EEG.nbchan = size(EEG.data,1); EEG.trials = counttrial-1; if latpoint0 ~= 1 EEG.xmin = -latpoint0/1000; end; EEG = eeg_checkset(EEG); % channel location % ---------------- if all(EEG.data(end,1:10) == 0) disp('Deleting empty data reference channel (reference channel location is retained)'); EEG.data(end,:) = []; EEG.nbchan = size(EEG.data,1); EEG = eeg_checkset(EEG); end; EEG = readegilocs(EEG); com = sprintf('EEG = pop_importegimat(''%s'', %3.2f, %3.2f, %d);', filename, srate, latpoint0, dataField); end;
github
lcnhappe/happe-master
pop_rejepoch.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_rejepoch.m
2,957
utf_8
a252e31365db94282bc48a802d83b48b
% pop_rejepoch() - Reject pre-labeled trials in a EEG dataset. % Ask for confirmation and accept the rejection % % Usage: % >> OUTEEG = pop_rejepoch( INEEG, trialrej, confirm) % % Inputs: % INEEG - Input dataset % trialrej - Array of 0s and 1s (depicting rejected trials) (size is % number of trials) % confirm - Display rejections and ask for confirmation. (0=no. 1=yes; % default is 1). % Outputs: % OUTEEG - output dataset % % Example: % >> data2 = pop_rejepoch( EEG, [1 1 1 0 0 0] ); % % reject the 3 first trials of a six-trial dataset % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab(), eegplot() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad function [EEG, com] = pop_rejepoch( EEG, tmprej, confirm); com = ''; if nargin < 1 help pop_rejepoch; return; end; if nargin < 2 tmprej = find(EEG.reject.rejglobal); end; if nargin < 3 confirm = 1; end; if islogical(tmprej), tmprej = tmprej+0; end; uniquerej = double(sort(unique(tmprej))); if length(tmprej) > 0 && length(uniquerej) <= 2 && ... ismember(uniquerej(1), [0 1]) && ismember(uniquerej(end), [0 1]) && any(~tmprej) format0_1 = 1; fprintf('%d/%d trials rejected\n', sum(tmprej), EEG.trials); else format0_1 = 0; fprintf('%d/%d trials rejected\n', length(tmprej), EEG.trials); end; if confirm ~= 0 ButtonName=questdlg2('Are you sure, you want to reject the labeled trials ?', ... 'Reject pre-labelled epochs -- pop_rejepoch()', 'NO', 'YES', 'YES'); switch ButtonName, case 'NO', disp('Operation cancelled'); return; case 'YES', disp('Compute new dataset'); end % switch end; % create a new set if set_out is non nul % -------------------------------------- if format0_1 tmprej = find(tmprej > 0); end; EEG = pop_select( EEG, 'notrial', tmprej); %com = sprintf( '%s = pop_rejepoch( %s, find(%s.reject.rejglobal), 0);', inputname(1), ... % inputname(1), inputname(1)); com = sprintf( '%s = pop_rejepoch( %s, %s);', inputname(1), inputname(1), vararg2str({ tmprej 0 })); return;
github
lcnhappe/happe-master
pop_loadeeg.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_loadeeg.m
5,829
utf_8
1009f8be42d7b9ae13a7b487334378c9
% pop_loadeeg() - load a Neuroscan .EEG file (via a pop-up window if no % arguments). Calls loadeeg(). % % Usage: % >> EEG = pop_loadeeg; % pop-up data entry window % >> EEG = pop_loadeeg( filename, filepath, range_chan, range_trials, ... % range_typeeeg, range_response, format); % no pop-up window % % Graphic interface: % "Data precision in bits..." - [edit box] data binary format length % in bits. Command line equivalent: 'format' % "Trial range subset" - [edit box] integer array. % Command line equivalent: 'range_trials' % "Type range subset" - [edit box] integer array. % Command line equivalent: 'range_typeeeg' % "Electrode subset" - [edit box] integer array. % Command line equivalent: 'range_chan' % "Response range subset" - [edit box] integer array. % Command line equivalent: 'range_response' % % Inputs: % filename - ['string'] file name % filepath - ['string'] file path % range_chan - [integer array] Import only selected electrodes % Ex: 3,4:10; {Default: [] -> import all} % range_trials - [integer array] Import only selected trials % { Default: [] -> import all} % range_typeeeg - [integer array] Import only trials of selected type % {Default: [] -> import all} % range_response - [integer array] Import only trials with selected % response values {Default: [] -> import all} % format - ['short'|'int32'] data binary format (Neuroscan 4.3 % saves data as 'int32'; earlier versions save data as % 'short'. Default is 'short'. % Outputs: % EEG - eeglab() data structure % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: loadeeg(), 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 % uses calls to eeg_emptyset and loadeeg % popup loadeeg file % ------------------ function [EEG, command] = pop_loadeeg(filename, filepath, range_chan, range_sweeps, range_typeeeg, range_response, datformat); EEG = []; command = ''; if nargin < 1 % ask user [filename, filepath] = uigetfile('*.eeg;*.EEG', 'Choose an EEG file -- pop_loadeeg()'); if filename == 0 return; end; % popup window parameters % ----------------------- promptstr = { 'Data precision in bits (16 / 32 bit or Auto for NS v4.3):', ... 'Trial range subset:', ... 'Type range subset:', ... 'Electrodes subset:', ... 'Response range subset:'}; inistr = { 'Auto' '' '' '' '' }; pop_title = sprintf('Load an EEG dataset'); result = inputdlg2( promptstr, pop_title, 1, inistr, 'pop_loadeeg'); if size( result,1 ) == 0 return; end; % decode parameters % ----------------- precision = lower(strtrim(result{1})); if strcmpi(precision, '16') datformat = 'short'; elseif strcmpi(precision, '32') datformat = 'int32'; elseif (strcmpi(precision, '0') || strcmpi(precision, 'auto')) datformat = 'auto' end; range_sweeps = eval( [ '[' result{2} ']' ] ); range_typeeeg = eval( [ '[' result{3} ']' ] ); range_chan = eval( [ '[' result{4} ']' ] ); range_response = eval( [ '[' result{5} ']' ] ); else if exist('filepath') ~= 1 filepath = ''; end; end; if exist('datformat') ~= 1, datformat = 'auto'; end; if exist('range_chan') ~= 1 | isempty(range_chan) , range_chan = 'all'; end; if exist('range_sweeps') ~= 1 | isempty(range_sweeps) , range_sweeps = 'all'; end; if exist('range_typeeeg') ~= 1 | isempty(range_typeeeg) , range_typeeeg = 'all'; end; if exist('range_response') ~= 1 | isempty(range_response), range_response = 'all'; end; % load datas % ---------- EEG = eeg_emptyset; if ~isempty(filepath) if filepath(end) ~= '/' & filepath(end) ~= '\' & filepath(end) ~= ':' error('The file path last character must be a delimiter'); end; fullFileName = sprintf('%s%s', filepath, filename); else fullFileName = filename; end; [EEG.data, accept, eegtype, rt, eegresp, namechan, EEG.pnts, EEG.trials, EEG.srate, EEG.xmin, EEG.xmax] = ... loadeeg( fullFileName, range_chan, range_sweeps, range_typeeeg, 'all', 'all', range_response, datformat); EEG.comments = [ 'Original file: ' fullFileName ]; EEG.setname = 'Neuroscan EEG data'; EEG.nbchan = size(EEG.data,1); for index = 1:size(namechan,1) EEG.chanlocs(index).labels = deblank(char(namechan(index,:))); end; EEG = eeg_checkset(EEG); if any(rt) EEG = pop_importepoch( EEG, [rt(:)*1000 eegtype(:) accept(:) eegresp(:)], { 'RT' 'type' 'accept' 'response'}, {'RT'}, 1E-3, 0, 1); else EEG = pop_importepoch( EEG, [eegtype(:) accept(:) eegresp(:)], { 'type' 'accept' 'response'}, { }, 1E-3, 0, 1); end; command = sprintf('EEG = pop_loadeeg(''%s'', ''%s'', %s);', filename, filepath, ... vararg2str({range_chan range_sweeps range_typeeeg range_response datformat })); return;
github
lcnhappe/happe-master
pop_importdata.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_importdata.m
18,140
utf_8
55023f12445bd132394251c54b2b62e5
% pop_importdata() - import data from a Matlab variable or disk file by calling % importdata(). % Usage: % >> EEGOUT = pop_importdata(); % pop-up a data entry window % >> EEGOUT = pop_importdata( 'key', val,...); % no pop-up window % % Graphic interface (refer to a previous version of the GUI): % "Data file/array" - [Edit box] Data file or Matlab variable name to import % to EEGLAB. Command line equivalent: 'data' % "Data file/array" - [list box] select data format from listbox. If you % browse for a data file, the graphical interface might be % able to detect the file format from the file extension and % his list box accordingly. Note that you have to click on % the option to make it active. Command line equivalent is % 'dataformat' % "Dataset name" - [Edit box] Name for the new dataset. % In the last column of the graphic interface, the "EEG.setname" % text indicates which field of the EEG structure this parameter % is corresponding to (in this case 'setname'). % Command line equivalent: 'setname'. % "Data sampling rate" - [Edit box] In Hz. Command line equivalent: 'srate' % "Time points per epoch" - [Edit box] Number of data frames (points) per epoch. % Changing this value will change the number of data epochs. % Command line equivalent: 'pnts'. % "Start time" - [Edit box] This edit box is only present for % data epoch and specify the epochs start time in ms. Epoch upper % time limit is automatically calculated. % Command line equivalent: 'xmin' % "Number of channels" - [Edit box] Number of data channels. Command line % equivalent: 'nbchan'. This edit box cannot be edited. % "Ref. channel indices or mode" - [edit box] current reference. This edit box % cannot be edited. To change data reference, use menu % Tools > Re-reference calling function pop_reref(). The reference % can be a string, 'common' indicating an unknow common reference, % 'averef' indicating average reference, or an array of integer % containing the indices of the reference channels. % "Subject code" - [Edit box] subject code. For example, 'S01'. The command % line equivalent is 'subject'. % "Task Condition" - [Edit box] task condition. For example, 'Targets'. The % command line equivalent is 'condition'. % "Session number" - [Edit box] session number (from the same subject). All datasets % from the same subject and session will be assumed to use the % same ICA decomposition. The command line equivalent is 'session'. % "Subject group" - [Edit box] subject group. For example 'Patients' or 'Control'. % Command line equivalent is 'group'. % "About this dataset" - [Edit box] Comments about the dataset. Command line % equivalent is 'comments'. % "Channel locations file or array" - [Edit box] For channel data formats, see % >> readlocs help Command line equivalent: 'chanlocs' % "ICA weights array or text/binary file" - [edit box] Import ICA weights from other % decompositions (e.g., same data, different conditions). % To use the ICA weights from another loaded dataset (n), enter % ALLEEG(n).icaweights. Command line equivalent: 'icaweights' % "ICA sphere array or text/binary file" - [edit box] Import ICA sphere matrix. % In EEGLAB, ICA decompositions require a sphere matrix % and an unmixing weight matrix (see above). To use the sphere % matrix from another loaded dataset (n), enter ALLEEG(n).icasphere % Command line equivalent: 'icasphere'. % "From other dataset" - [push button] Press this button and enter the index % of another dataset. This will update the channel location or the % ICA edit box. % % Optional inputs: % 'setname' - Name of the EEG dataset % 'data' - ['varname'|'filename'] Import data from a Matlab variable or file % into an EEG data structure % 'dataformat' - ['array|matlab|ascii|float32le|float32be'] Input data format. % 'array' is a Matlab array in the global workspace. % 'matlab' is a Matlab file (which must contain a single variable). % 'ascii' is an ascii file. 'float32le' and 'float32be' are 32-bit % float data files with little-endian and big-endian byte order. % Data must be organised as (channels, timepoints) i.e. % channels = rows, timepoints = columns; else, as 3-D (channels, % timepoints, epochs). For convenience, the data file is transposed % if the number of rows is larger than the number of columns as the % program assumes that there is more channel than data points. % 'subject' - [string] subject code. For example, 'S01'. % {default: none -> each dataset from a different subject} % 'condition' - [string] task condition. For example, 'Targets' % {default: none -> all datasets from one condition} % 'group' - [string] subject group. For example 'Patients' or 'Control'. % {default: none -> all subjects in one group} % 'session' - [integer] session number (from the same subject). All datasets % from the same subject and session will be assumed to use the % same ICA decomposition {default: none -> each dataset from % a different session} % 'chanlocs' - ['varname'|'filename'] Import a channel location file. % For file formats, see >> help readlocs % 'nbchan' - [int] Number of data channels. % 'xmin' - [real] Data epoch start time (in seconds). % {default: 0} % 'pnts' - [int] Number of data points per data epoch. The number of trial % is automatically calculated. % {default: length of the data -> continuous data assumed} % 'srate' - [real] Data sampling rate in Hz {default: 1Hz} % 'ref' - [string or integer] reference channel indices. 'averef' indicates % average reference. Note that this does not perform referencing % but only sets the initial reference when the data is imported. % 'icaweight' - [matrix] ICA weight matrix. % 'icasphere' - [matrix] ICA sphere matrix. By default, the sphere matrix % is initialized to the identity matrix if it is left empty. % 'comments' - [string] Comments on the dataset, accessible through the EEGLAB % main menu using (Edit > About This Dataset). Use this to attach % background information about the experiment or data to the dataset. % Outputs: % EEGOUT - modified EEG dataset structure % % Note: This function calls pop_editset() to modify parameter values. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: pop_editset(), pop_select(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-16-02 text interface editing -sm & ad % 03-16-02 remove EEG.xmax et EEG.xmin (for continuous) -ad & sm % 04-02-02 debugging command line calls -ad & lf function [EEGOUT, com] = pop_importdata( varargin); com = ''; EEGOUT = eeg_emptyset; if nargin < 1 % if several arguments, assign values % popup window parameters % ----------------------- geometry = { [1.4 0.7 .8 0.5] [2 3.02] [1] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] ... [1] [1.4 0.7 .8 0.5] [1] [1.4 0.7 .8 0.5] [1.4 0.7 .8 0.5] }; editcomments = [ 'tmp = pop_comments(get(gcbf, ''userdata''), ''Edit comments of current dataset'');' ... 'if ~isempty(tmp), set(gcf, ''userdata'', tmp); end; clear tmp;' ]; commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ... 'if filename(1) ~=0,' ... ' set(findobj(''parent'', gcbf, ''tag'', tagtest), ''string'', [ filepath filename ]);' ... 'end;' ... 'clear filename filepath tagtest;' ]; commandsetfiletype = [ 'filename = get( findobj(''parent'', gcbf, ''tag'', ''globfile''), ''string'');' ... 'tmpext = findstr(filename,''.'');' ... 'if ~isempty(tmpext),' ... ' tmpext = lower(filename(tmpext(end)+1:end));' ... ' switch tmpext, ' ... ' case ''mat'', set(findobj(gcbf,''tag'', ''loclist''), ''value'',5);' ... ' case ''fdt'', set(findobj(gcbf,''tag'', ''loclist''), ''value'',3);' ... ' case ''txt'', set(findobj(gcbf,''tag'', ''loclist''), ''value'',2);' ... ' end;' ... 'end; clear tmpext filename;' ]; commandselica = [ 'res = inputdlg2({ ''Enter dataset number'' }, ''Select ICA weights and sphere from other dataset'', 1, { ''1'' });' ... 'if ~isempty(res),' ... ' set(findobj( ''parent'', gcbf, ''tag'', ''weightfile''), ''string'', sprintf(''ALLEEG(%s).icaweights'', res{1}));' ... ' set(findobj( ''parent'', gcbf, ''tag'', ''sphfile'') , ''string'', sprintf(''ALLEEG(%s).icasphere'' , res{1}));' ... 'end;' ]; commandselchan = [ 'res = inputdlg2({ ''Enter dataset number'' }, ''Select channel information from other dataset'', 1, { ''1'' });' ... 'if ~isempty(res),' ... ' set(findobj( ''parent'', gcbf, ''tag'', ''chanfile''), ' ... ' ''string'', sprintf(''{ ALLEEG(%s).chanlocs ALLEEG(%s).chaninfo ALLEEG(%s).urchanlocs }'', res{1}, res{1}, res{1}));' ... 'end;' ]; if isstr(EEGOUT.ref) curref = EEGOUT.ref; else if length(EEGOUT.ref) > 1 curref = [ int2str(abs(EEGOUT.ref)) ]; else curref = [ int2str(abs(EEGOUT.ref)) ]; end; end; uilist = { ... { 'Style', 'text', 'string', 'Data file/array (click on the selected option)', 'horizontalalignment', 'right', 'fontweight', 'bold' }, ... { 'Style', 'popupmenu', 'string', 'Matlab variable|ASCII text file|float32 le file|float32 be file|Matlab .mat file', ... 'fontweight', 'bold', 'tag','loclist' } ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'globfile' }, ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', ... [ 'tagtest = ''globfile'';' commandload commandsetfiletype ] }, ... ... { 'Style', 'text', 'string', 'Dataset name', 'horizontalalignment', 'right', ... 'fontweight', 'bold' }, { 'Style', 'edit', 'string', '' }, { } ... ... { 'Style', 'text', 'string', 'Data sampling rate (Hz)', 'horizontalalignment', 'right', 'fontweight', ... 'bold' }, { 'Style', 'edit', 'string', num2str(EEGOUT.srate) }, ... { 'Style', 'text', 'string', 'Subject code', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', '' }, ... { 'Style', 'text', 'string', 'Time points per epoch (0->continuous)', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', num2str(EEGOUT.pnts) }, ... { 'Style', 'text', 'string', 'Task condition', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', '' }, ... { 'Style', 'text', 'string', 'Start time (sec) (only for data epochs)', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', num2str(EEGOUT.xmin) }, ... { 'Style', 'text', 'string', 'Session number', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', '' }, ... { 'Style', 'text', 'string', 'Number of channels (0->set from data)', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', '0' }, ... { 'Style', 'text', 'string', 'Subject group', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', '' }, ... { 'Style', 'text', 'string', 'Ref. channel indices or mode (see help)', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', curref }, ... { 'Style', 'text', 'string', 'About this dataset', 'horizontalalignment', 'right', ... }, { 'Style', 'pushbutton', 'string', 'Enter comments' 'callback' editcomments }, ... { } ... { 'Style', 'text', 'string', 'Channel location file or info', 'horizontalalignment', 'right', 'fontweight', ... 'bold' }, {'Style', 'pushbutton', 'string', 'From other dataset', 'callback', commandselchan }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'chanfile' }, ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''chanfile'';' commandload ] }, ... ... { 'Style', 'text', 'string', ... ' (note: autodetect file format using file extension; use menu "Edit > Channel locations" for more importing options)', ... 'horizontalalignment', 'right' }, ... ... { 'Style', 'text', 'string', 'ICA weights array or text/binary file (if any):', 'horizontalalignment', 'right' }, ... { 'Style', 'pushbutton' 'string' 'from other dataset' 'callback' commandselica }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'weightfile' }, ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''weightfile'';' commandload ] }, ... ... { 'Style', 'text', 'string', 'ICA sphere array or text/binary file (if any):', 'horizontalalignment', 'right' }, ... { 'Style', 'pushbutton' 'string' 'from other dataset' 'callback' commandselica }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'sphfile' } ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''sphfile'';' commandload ] } }; [ results newcomments ] = inputgui( geometry, uilist, 'pophelp(''pop_importdata'');', 'Import dataset info -- pop_importdata()'); if length(results) == 0, return; end; args = {}; % specific to importdata (not identical to pop_editset % ---------------------------------------------------- switch results{1} case 1, args = { args{:}, 'dataformat', 'array' }; case 2, args = { args{:}, 'dataformat', 'ascii' }; case 3, args = { args{:}, 'dataformat', 'float32le' }; case 4, args = { args{:}, 'dataformat', 'float32be' }; case 5, args = { args{:}, 'dataformat', 'matlab' }; end; i = 3; if ~isempty( results{i+7} ) , args = { args{:}, 'nbchan', str2num(results{i+7}) }; end; if ~isempty( results{2} ) , args = { args{:}, 'data', results{2} }; end; if ~isempty( results{i } ) , args = { args{:}, 'setname', results{i } }; end; if ~isempty( results{i+1} ) , args = { args{:}, 'srate', str2num(results{i+1}) }; end; if ~isempty( results{i+2} ) , args = { args{:}, 'subject', results{i+2} }; end; if ~isempty( results{i+3} ) , args = { args{:}, 'pnts', str2num(results{i+3}) }; end; if ~isempty( results{i+4} ) , args = { args{:}, 'condition', results{i+4} }; end; if ~isempty( results{i+5} ) , args = { args{:}, 'xmin', str2num(results{i+5}) }; end; if ~isempty( results{i+6} ) , args = { args{:}, 'session', str2num(results{i+6}) }; end; if ~isempty( results{i+8} ) , args = { args{:}, 'group', results{i+8} }; end; if ~isempty( results{i+9} ) , args = { args{:}, 'ref', str2num(results{i+9}) }; end; if ~isempty( newcomments ) , args = { args{:}, 'comments', newcomments }; end; if abs(str2num(results{i+5})) > 10, fprintf('WARNING: are you sure the epoch start time (%3.2f) is in seconds\n'); end; if ~isempty( results{i+10} ) , args = { args{:}, 'chanlocs' , results{i+10} }; end; if ~isempty( results{i+11} ), args = { args{:}, 'icaweights', results{i+11} }; end; if ~isempty( results{i+12} ) , args = { args{:}, 'icasphere', results{i+12} }; end; % generate the output command % --------------------------- EEGOUT = pop_editset(EEGOUT, args{:}); com = sprintf( 'EEG = pop_importdata(%s);', vararg2str(args) ); %com = ''; %for i=1:2:length(args) % if ~isempty( args{i+1} ) % if isstr( args{i+1} ) com = sprintf('%s, ''%s'', ''%s''', com, args{i}, char(args{i+1}) ); % else com = sprintf('%s, ''%s'', [%s]', com, args{i}, num2str(args{i+1}) ); % end; % else % com = sprintf('%s, ''%s'', []', com, args{i} ); % end; %end; %com = [ 'EEG = pop_importdata(' com(2:end) ');']; else % no interactive inputs EEGOUT = pop_editset(EEGOUT, varargin{:}); end; return;
github
lcnhappe/happe-master
pop_newtimef.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_newtimef.m
17,862
utf_8
5299a688b12982118ec8c0a8b74b7567
% pop_newtimef() - Returns estimates and plots of event-related (log) spectral % perturbation (ERSP) and inter-trial coherence (ITC) phenomena % timelocked to a set of single-channel input epochs % % Usage: % >> pop_newtimef(EEG, typeplot); % pop_up window % >> pop_newtimef(EEG, typeplot, lastcom); % pop_up window % >> pop_newtimef(EEG, typeplot, channel); % do not pop-up window % >> pop_newtimef(EEG, typeproc, num, tlimits,cycles, % 'key1',value1,'key2',value2, ... ); % % Graphical interface: % "Channel/component number" - [edit box] this is the index of the data % channel or the index of the component for which to plot the % time-frequency decomposition. % "Sub-epoch time limits" - [edit box] sub epochs may be extracted (note that % this function aims at plotting data epochs not continuous data). % You may select the new epoch limits in this edit box. % "Use n time points" - [muliple choice list] this is the number of time % points to use for the time-frequency decomposition. The more % time points, the longer the time-frequency decomposition % takes to compute. % "Frequency limits" - [edit box] these are the lower and upper % frequency limit of the time-frequency decomposition. Instead % of limits, you may also enter a sequence of frequencies. For % example to compute the time-frequency decomposition at all % frequency between 5 and 50 hertz with 1 Hz increment, enter "1:50" % "Use limits, padding n" - [muliple choice list] "using limits" means % to use the upper and lower limits in "Frequency limits" with % a specific padding ratio (padratio argument of newtimef). % The last option "use actual frequencies" forces newtimef to % ignore the padratio argument and use the vector of frequencies % given as input in the "Frequency limits" edit box. % "Log spaced" - [checkbox] you may check this box to compute log-spaced % frequencies. Note that this is only relevant if you specify % frequency limits (in case you specify actual frequencies, % this parameter is ignored). % "Use divisive baseline" - [muliple choice list] there are two types of % baseline correction, additive (the baseline is subtracted) % or divisive (the data is divided by the baseline values). % The choice is yours. There is also the option to perform % baseline correction in single trials. See the 'trialbase' "full" % option in the newtimef.m documentation for more information. % "No baseline" - [checkbox] check this box to compute the raw time-frequency % decomposition with no baseline removal. % "Wavelet cycles" - [edit box] specify the number of cycle at the lowest % and highest frequency. Instead of specifying the number of cycle % at the highest frequency, you may also specify a wavelet % "factor" (see newtimef help message). In addition, it is % possible to specify actual wavelet cycles for each frequency % by entering a sequence of numbers. % "Use FFT" - [checkbox] check this checkbox to use FFT instead of % wavelet decomposition. % "ERSP color limits" - [edit box] set the upper and lower limit for the % ERSP image. % "see log power" - [checkbox] the log power values (in dB) are plotted. % Uncheck this box to plot the absolute power values. % "ITC color limits" - [edit box] set the upper and lower limit for the % ITC image. % "plot ITC phase" - [checkbox] check this box plot plot (overlayed on % the ITC amplitude) the polarity of the ITC complex value. % "Bootstrap significance level" - [edit box] use this edit box to enter % the p-value threshold for masking both the ERSP and the ITC % image for significance (masked values appear as light green) % "FDR correct" - [checkbox] this correct the p-value for multiple comparisons % (accross all time and frequencies) using the False Discovery % Rate method. See the fdr.m function for more details. % "Optional newtimef arguments" - [edit box] addition argument for the % newtimef function may be entered here in the 'key', value % format. % "Plot Event Related Spectral Power" - [checkbox] plot the ERSP image % showing event related spectral stimulus induced changes % "Plot Inter Trial Coherence" - [checkbox] plot the ITC image. % "Plot Curve at each frequency" - [checkbox] instead of plotting images, % it is also possible to display curves at each frequency. % This functionality is beta and might not work in all cases. % % Inputs: % INEEG - input EEG dataset % typeproc - type of processing: 1 process the raw channel data % 0 process the ICA component data % num - component or channel number % tlimits - [mintime maxtime] (ms) sub-epoch time limits to plot % cycles - > 0 --> Number of cycles in each analysis wavelet % = 0 --> Use FFTs (with constant window length % at all frequencies) % % Optional inputs: % See the newtimef() function. % % Outputs: Same as newtimef(); no outputs are returned when a % window pops-up to ask for additional arguments % % Saving the ERSP and ITC output values: % Simply look up the history using the eegh function (type eegh). % Then copy and paste the pop_newtimef() command and add output args. % See the newtimef() function for a list of outputs. For instance, % >> [ersp itc powbase times frequencies] = pop_newtimef( EEG, ....); % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: newtimef(), eeglab() % Copyright (C) 2002 University of California San Diego % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-08-02 add eeglab option & optimize variable sizes -ad % 03-10-02 change newtimef call -ad % 03-18-02 added title -ad & sm % 04-04-02 added outputs -ad & sm function varargout = pop_newtimef(EEG, typeproc, num, tlimits, cycles, varargin ); varargout{1} = ''; % display help if not enough arguments % ------------------------------------ if nargin < 2 help pop_newtimef; return; end; lastcom = []; if nargin < 3 popup = 1; else popup = isstr(num) | isempty(num); if isstr(num) lastcom = num; end; end; % pop up window % ------------- if popup [txt vars] = gethelpvar('newtimef.m'); g = [1 0.3 0.6 0.4]; geometry = { g g g g g g g g [0.975 1.27] [1] [1.2 1 1.2]}; uilist = { ... { 'Style', 'text', 'string', fastif(typeproc, 'Channel number', 'Component number'), 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,3,[],'1') 'tag' 'chan'} {} {} ... ... { 'Style', 'text', 'string', 'Sub epoch time limits [min max] (msec)', 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,4,[],[ int2str(EEG.xmin*1000) ' ' int2str(EEG.xmax*1000) ]) 'tag' 'tlimits' } ... { 'Style', 'popupmenu', 'string', 'Use 50 time points|Use 100 time points|Use 150 time points|Use 200 time points|Use 300 time points|Use 400 time points' 'tag' 'ntimesout' 'value' 4} { } ... ... { 'Style', 'text', 'string', 'Frequency limits [min max] (Hz) or sequence', 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', '' 'tag' 'freqs' } ... { 'Style', 'popupmenu', 'string', 'Use limits, padding 1|Use limits, padding 2|Use limits, padding 4|Use actual freqs.' 'tag' 'nfreqs' } ... { 'Style', 'checkbox', 'string' 'Log spaced' 'value' 0 'tag' 'freqscale' } ... ... { 'Style', 'text', 'string', 'Baseline limits [min max] (msec) (0->pre-stim.)', 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', '0' 'tag' 'baseline' } ... { 'Style', 'popupmenu', 'string', 'Use divisive baseline (DIV)|Use standard deviation (STD)|Use single trial DIV baseline|Use single trial STD baseline' 'tag' 'basenorm' } ... { 'Style', 'checkbox', 'string' 'No baseline' 'tag' 'nobase' } ... ... { 'Style', 'text', 'string', 'Wavelet cycles [min max/fact] or sequence', 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,5,[],'3 0.5') 'tag' 'cycle' } ... { 'Style', 'checkbox', 'string' 'Use FFT' 'value' 0 'tag' 'fft' } ... { } ... ... { 'Style', 'text', 'string', 'ERSP color limits [max] (min=-max)', 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', '' 'tag' 'erspmax'} ... { 'Style', 'checkbox', 'string' 'see log power (set)' 'tag' 'scale' 'value' 1} {} ... ... { 'Style', 'text', 'string', 'ITC color limits [max]', 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', '' 'tag' 'itcmax'} ... { 'Style', 'checkbox', 'string' 'plot ITC phase (set)' 'tag' 'plotphase' } {} ... ... { 'Style', 'text', 'string', 'Bootstrap significance level (Ex: 0.01 -> 1%)', 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,'alpha') 'tag' 'alpha'} ... { 'Style', 'checkbox', 'string' 'FDR correct (set)' 'tag' 'fdr' } {} ... ... { 'Style', 'text', 'string', 'Optional newtimef() arguments (see Help)', 'fontweight', 'bold', ... 'tooltipstring', 'See newtimef() help via the Help button on the right...' } ... { 'Style', 'edit', 'string', '' 'tag' 'options' } ... {} ... { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotersp','present',0), 'string', ... 'Plot Event Related Spectral Power', 'tooltipstring', ... 'Plot log spectral perturbation image in the upper panel' 'tag' 'plotersp' } ... { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotitc','present',0), 'string', ... 'Plot Inter Trial Coherence', 'tooltipstring', ... 'Plot the inter-trial coherence image in the lower panel' 'tag' 'plotitc' } ... { 'Style', 'checkbox', 'value', 0, 'string', ... 'Plot curve at each frequency' 'tag' 'plotcurve' } ... }; % { 'Style', 'edit', 'string', '''padratio'', 4, ''plotphase'', ''off''' } ... %{ 'Style', 'text', 'string', '[set] -> Plot ITC phase sign', 'fontweight', 'bold', ... % 'tooltipstring', ['Plot the sign (+/-) of inter-trial coherence phase' 10 ... % 'as red (+) or blue (-)'] } ... % { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotphase','present',1) } { } ... [ tmp1 tmp2 strhalt result ] = inputgui( geometry, uilist, 'pophelp(''pop_newtimef'');', ... fastif(typeproc, 'Plot channel time frequency -- pop_newtimef()', ... 'Plot component time frequency -- pop_newtimef()')); if length( tmp1 ) == 0 return; end; if result.fft, result.cycle = '0'; end; if result.nobase, result.baseline = 'NaN'; end; num = eval( [ '[' result.chan ']' ] ); tlimits = eval( [ '[' result.tlimits ']' ] ); cycles = eval( [ '[' result.cycle ']' ] ); freqs = eval( [ '[' result.freqs ']' ] ); %result.ncycles == 2 is ignored % add topoplot % ------------ options = []; if isfield(EEG.chanlocs, 'theta') && ~isempty(EEG.chanlocs(num).theta) if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end; if typeproc == 1 if isempty(EEG.chanlocs), caption = [ 'Channel ' int2str(num) ]; else caption = EEG.chanlocs(num).labels; end; options = [options ', ''topovec'', ' int2str(num) ... ', ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo, ''caption'', ''' caption '''' ]; else options = [options ', ''topovec'', EEG.icawinv(:,' int2str(num) ... '), ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo, ''caption'', [''IC ' num2str(num) ''']' ]; end; end; if ~isempty( result.baseline ), options = [ options ', ''baseline'',[' result.baseline ']' ]; end; if ~isempty( result.alpha ), options = [ options ', ''alpha'',' result.alpha ]; end; if ~isempty( result.options ), options = [ options ',' result.options ]; end; if ~isempty( result.freqs ), options = [ options ', ''freqs'', [' result.freqs ']' ]; end; if ~isempty( result.erspmax ), options = [ options ', ''erspmax'', [' result.erspmax ']' ]; end; if ~isempty( result.itcmax ), options = [ options ', ''itcmax'',' result.itcmax ]; end; if ~result.plotersp, options = [ options ', ''plotersp'', ''off''' ]; end; if ~result.plotitc, options = [ options ', ''plotitc'' , ''off''' ]; end; if result.plotcurve, options = [ options ', ''plottype'', ''curve''' ]; end; if result.fdr, options = [ options ', ''mcorrect'', ''fdr''' ]; end; if result.freqscale, options = [ options ', ''freqscale'', ''log''' ]; end; if ~result.plotphase, options = [ options ', ''plotphase'', ''off''' ]; end; if ~result.scale, options = [ options ', ''scale'', ''abs''' ]; end; if result.ntimesout == 1, options = [ options ', ''ntimesout'', 50' ]; end; if result.ntimesout == 2, options = [ options ', ''ntimesout'', 100' ]; end; if result.ntimesout == 3, options = [ options ', ''ntimesout'', 150' ]; end; if result.ntimesout == 5, options = [ options ', ''ntimesout'', 300' ]; end; if result.ntimesout == 6, options = [ options ', ''ntimesout'', 400' ]; end; if result.nfreqs == 1, options = [ options ', ''padratio'', 1' ]; end; if result.nfreqs == 2, options = [ options ', ''padratio'', 2' ]; end; if result.nfreqs == 3, options = [ options ', ''padratio'', 4' ]; end; if result.nfreqs == 4, options = [ options ', ''nfreqs'', ' int2str(length(freqs)) ]; end; if result.basenorm == 2, options = [ options ', ''basenorm'', ''on''' ]; end; if result.basenorm == 4, options = [ options ', ''basenorm'', ''on''' ]; end; if result.basenorm >= 3, options = [ options ', ''trialbase'', ''full''' ]; end; % add title % --------- if isempty( findstr( '''title''', result.options)) if ~isempty(EEG.chanlocs) & typeproc chanlabel = EEG.chanlocs(num).labels; else chanlabel = int2str(num); end; end; % compute default winsize % ----------------------- if EEG.xmin < 0 && isempty(findstr( '''winsize''', result.options)) && isempty( result.freqs ) fprintf('Computing window size in pop_newtimef based on half of the length of the baseline period'); options = [ options ', ''winsize'', ' int2str(-EEG.xmin*EEG.srate) ]; end; figure; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; else options = [ ',' vararg2str(varargin) ]; end; % compute epoch limits % -------------------- if isempty(tlimits) tlimits = [EEG.xmin, EEG.xmax]*1000; end; pointrange1 = round(max((tlimits(1)/1000-EEG.xmin)*EEG.srate, 1)); pointrange2 = round(min((tlimits(2)/1000-EEG.xmin)*EEG.srate, EEG.pnts)); pointrange = [pointrange1:pointrange2]; % call function sample either on raw data or ICA data % --------------------------------------------------- if typeproc == 1 tmpsig = EEG.data(num,pointrange,:); else if ~isempty( EEG.icasphere ) if ~isempty(EEG.icaact) tmpsig = EEG.icaact(num,pointrange,:); else tmpsig = (EEG.icaweights(num,:)*EEG.icasphere)*reshape(EEG.data(:,pointrange,:), EEG.nbchan, EEG.trials*length(pointrange)); end; else error('You must run ICA first'); end; end; tmpsig = reshape( tmpsig, length(num), size(tmpsig,2)*size(tmpsig,3)); % outputs % ------- outstr = ''; if ~popup for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end; if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end; end; % plot the datas and generate output command % -------------------------------------------- if length( options ) < 2 options = ''; end; if nargin < 4 varargout{1} = sprintf('figure; pop_newtimef( %s, %d, %d, [%s], [%s] %s);', inputname(1), typeproc, num, ... int2str(tlimits), num2str(cycles), options); end; com = sprintf('%s newtimef( tmpsig(:, :), length(pointrange), [tlimits(1) tlimits(2)], EEG.srate, cycles %s);', outstr, options); eval(com) return; % get contextual help % ------------------- function txt = context(var, allvars, alltext); loc = strmatch( var, allvars); if ~isempty(loc) txt= alltext{loc(1)}; else disp([ 'warning: variable ''' var ''' not found']); txt = ''; end;
github
lcnhappe/happe-master
pop_comperp.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_comperp.m
24,065
utf_8
0e8f83142764654afb0ecb8f592a7953
% pop_comperp() - Compute the grand average ERP waveforms of multiple datasets % currently loaded into EEGLAB, with optional ERP difference-wave % plotting and t-tests. Creates a plotting figure. % Usage: % >> pop_comperp( ALLEEG, flag ); % pop-up window, interactive mode % >> [erp1 erp2 erpsub time sig] = pop_comperp( ALLEEG, flag, ... % datadd, datsub, 'key', 'val', ...); % Inputs: % ALLEEG - Array of loaded EEGLAB EEG structure datasets % flag - [0|1] 0 -> Use ICA components; 1 -> use data channels {default: 1} % datadd - [integer array] List of ALLEEG dataset indices to average to make % an ERP grand average and optionally to compare with 'datsub' datasets. % % Optional inputs: % datsub - [integer array] List of ALLEEG dataset indices to average and then % subtract from the 'datadd' result to make an ERP grand mean difference. % Together, 'datadd' and 'datsub' may be used to plot and compare grand mean % responses across subjects or conditions. Both arrays must contain the same % number of dataset indices and entries must be matched pairwise (Ex: % 'datadd' indexes condition A datasets from subjects 1:n, and 'datsub', % condition B datasets from the same subjects 1:n). {default: []} % 'alpha' - [0 < float < 1] Apply two-tailed t-tests for p < alpha. If 'datsub' is % not empty, perform t-tests at each latency. If 'datasub' is empty, % perform two-tailed t-tests against a 0 mean dataset with same variance. % Significant time regions are highlighted in the plotted data. % 'chans' - [integer array] Vector of chans. or comps. to use {default: all} % 'geom' - ['scalp'|'array'] Plot erps in a scalp array (plottopo()) % or as a rectangular array (plotdata()). Note: Only channels % (see 'chans' above) can be plotted in a 'scalp' array. % 'tlim' - [min max] Time window (ms) to plot data {default: whole time range} % 'title' - [string] Plot title {default: none} % 'ylim' - [min max] y-axis limits {default: auto from data limits} % 'mode' - ['ave'|'rms'] Plotting mode. Plot either grand average or RMS % (root mean square) time course(s) {default: 'ave' -> grand average}. % 'std' - ['on'|'off'|'none'] 'on' -> plot std. devs.; 'none' -> do not % interact with other options {default:'none'} % % Vizualisation options: % 'addavg' - ['on'|'off'] Plot grand average (or RMS) of 'datadd' datasets % {default: 'on' if 'datsub' empty, otherwise 'off'} % 'subavg' - ['on'|'off'] Plot grand average (or RMS) of 'datsub' datasets % {default:'off'} % 'diffavg' - ['on'|'off'] Plot grand average (or RMS) difference % 'addall' - ['on'|'off'] Plot the ERPs for all 'dataadd' datasets only {default:'off'} % 'suball' - ['on'|'off'] Plot the ERPs for all 'datasub datasets only {default:'off'} % 'diffall' - ['on'|'off'] Plot all the 'datadd'-'datsub' ERP differences {default:'off'} % 'addstd' - ['on'|'off'] Plot std. dev. for 'datadd' datasets only % {default: 'on' if 'datsub' empty, otherwise 'off'} % 'substd' - ['on'|'off'] Plot std. dev. of 'datsub' datasets only {default:'off'} % 'diffstd' - ['on'|'off'] Plot std. dev. of 'datadd'-'datsub' differences {default:'on'} % 'diffonly' - ['on'|'off'|'none'] 'on' -> plot difference only; 'none' -> do not affect % other options {default:'none'} % 'allerps' - ['on'|'off'|'none'] 'on' -> show ERPs for all conditions; % 'none' -> do not affect other options {default:'none'} % 'tplotopt' - [cell array] Pass 'key', val' plotting options to plottopo() % % Output: % erp1 - Grand average (or rms) of the 'datadd' datasets % erp2 - Grand average (or rms) of the 'datsub' datasets % erpsub - Grand average (or rms) 'datadd' minus 'datsub' difference % times - Vector of epoch time indices % sig - T-test significance values (chans,times). % % Author: Arnaud Delorme, CNL / Salk Institute, 15 March 2003 % % Note: t-test functions were adapted for matrix preprocessing from C functions % by Press et al. See the description in the pttest() code below % for more information. % % See also: eeglab(), plottopo() % Copyright (C) 15 March 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 [erp1, erp2, erpsub, times, pvalues] = pop_comperp( ALLEEG, flag, datadd, datsub, varargin); erp1 = ''; if nargin < 1 help pop_comperp; return; end; if isempty(ALLEEG) error('pop_comperp: cannot process empty sets of data'); end; if nargin < 2 flag = 1; end; allcolors = { 'b' 'r' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' ... 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm'}; erp1 = ''; if nargin < 3 gtmp = [1.1 0.8 .21 .21 .21 0.1]; gtmp2 = [1.48 1.03 1]; uigeom = { [2.6 0.95] gtmp gtmp gtmp [1] gtmp2 gtmp2 [1.48 0.25 1.75] gtmp2 gtmp2 }; commulcomp= ['if get(gcbo, ''value''),' ... ' set(findobj(gcbf, ''tag'', ''multcomp''), ''enable'', ''on'');' ... 'else,' ... ' set(findobj(gcbf, ''tag'', ''multcomp''), ''enable'', ''off'');' ... 'end;']; uilist = { { } ... { 'style' 'text' 'string' 'avg. std. all ERPs' } ... { 'style' 'text' 'string' 'Datasets to average (ex: 1 3 4):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'checkbox' 'string' '' 'value' 1 } ... { 'style' 'checkbox' 'string' '' } ... { 'style' 'checkbox' 'string' '' } { } ... { 'style' 'text' 'string' 'Datasets to average and subtract (ex: 5 6 7):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'checkbox' 'string' '' 'value' 1 } ... { 'style' 'checkbox' 'string' '' } ... { 'style' 'checkbox' 'string' '' } { } ... { 'style' 'text' 'string' 'Plot difference' } { } ... { 'style' 'checkbox' 'string' '' 'value' 1 } ... { 'style' 'checkbox' 'string' '' } ... { 'style' 'checkbox' 'string' '' } { } ... { } ... { 'style' 'text' 'string' fastif(flag, 'Channels subset ([]=all):', ... 'Components subset ([]=all):') } ... { 'style' 'edit' 'string' '' } { } ... { 'style' 'text' 'string' 'Highlight significant regions (.01 -> p=.01)' } ... { 'style' 'edit' 'string' '' } { } ... { 'style' 'text' 'string' 'Use RMS instead of average (check):' } { 'style' 'checkbox' 'string' '' } { } ... { 'style' 'text' 'string' 'Low pass (Hz) (for display only)' } ... { 'style' 'edit' 'string' '' } { } ... { 'style' 'text' 'string' 'Plottopo options (''key'', ''val''):' } ... { 'style' 'edit' 'string' '''ydir'', -1' } ... { 'style' 'pushbutton' 'string' 'Help' 'callback', 'pophelp(''plottopo'')' } ... }; % remove geometry textbox for ICA components result = inputgui( uigeom, uilist, 'pophelp(''pop_comperp'')', 'ERP grand average/RMS - pop_comperp()'); if length(result) == 0, return; end; %decode parameters list options = {}; datadd = eval( [ '[' result{1} ']' ]); if result{2}, options = { options{:} 'addavg' 'on' }; else, options = { options{:} 'addavg' 'off' }; end; if result{3}, options = { options{:} 'addstd' 'on' }; else, options = { options{:} 'addstd' 'off' }; end; if result{4}, options = { options{:} 'addall' 'on' }; end; datsub = eval( [ '[' result{5} ']' ]); if result{6}, options = { options{:} 'subavg' 'on' }; end; if result{7}, options = { options{:} 'substd' 'on' }; end; if result{8}, options = { options{:} 'suball' 'on' }; end; if result{9}, options = { options{:} 'diffavg' 'on' }; else, options = { options{:} 'diffavg' 'off' }; end; if result{10}, options = { options{:} 'diffstd' 'on' }; else, options = { options{:} 'diffstd' 'off' }; end; if result{11}, options = { options{:} 'diffall' 'on' }; end; if result{12}, options = { options{:} 'chans' eval( [ '[' result{12} ']' ]) }; end; if ~isempty(result{13}), options = { options{:} 'alpha' str2num(result{13}) }; end; if result{14}, options = { options{:} 'mode' 'rms' }; end; if ~isempty(result{15}), options = { options{:} 'lowpass' str2num(result{15}) }; end; if ~isempty(result{16}), options = { options{:} 'tplotopt' eval([ '{ ' result{16} ' }' ]) }; end; else options = varargin; end; if nargin == 3 datsub = []; % default end % decode inputs % ------------- if isempty(datadd), error('First edit box (datasets to add) can not be empty'); end; g = finputcheck( options, ... { 'chans' 'integer' [] [1:ALLEEG(datadd(1)).nbchan]; 'title' 'string' [] ''; 'alpha' 'float' [] []; 'geom' 'string' {'scalp';'array'} fastif(flag, 'scalp', 'array'); 'addstd' 'string' {'on';'off'} fastif(isempty(datsub), 'on', 'off'); 'substd' 'string' {'on';'off'} 'off'; 'diffstd' 'string' {'on';'off'} 'on'; 'addavg' 'string' {'on';'off'} fastif(isempty(datsub), 'on', 'off'); 'subavg' 'string' {'on';'off'} 'off'; 'diffavg' 'string' {'on';'off'} 'on'; 'addall' 'string' {'on';'off'} 'off'; 'suball' 'string' {'on';'off'} 'off'; 'diffall' 'string' {'on';'off'} 'off'; 'std' 'string' {'on';'off';'none'} 'none'; 'diffonly' 'string' {'on';'off';'none'} 'none'; 'allerps' 'string' {'on';'off';'none'} 'none'; 'lowpass' 'float' [0 Inf] []; 'tlim' 'float' [] []; 'ylim' 'float' [] []; 'tplotopt' 'cell' [] {}; 'mode' 'string' {'ave';'rms'} 'ave'; 'multcmp' 'integer' [0 Inf] [] }); if isstr(g), error(g); end; if length(datadd) == 1 disp('Cannot perform statistics using only 1 dataset'); g.alpha = []; end; h = figure; axcopy try, icadefs; set(h, 'color', BACKCOLOR); axis off; catch, end; % backward compatibility of param % ------------------------------- if ~strcmpi(g.diffonly, 'none') if strcmpi(g.diffonly, 'off'), g.addavg = 'on'; g.subavg = 'on'; end; end; if ~strcmpi(g.allerps, 'none') if isempty(datsub) g.addall = g.allerps; else g.diffall = g.allerps; end; end; if ~strcmpi(g.std, 'none') if isempty(datsub) g.addstd = g.std; else g.diffstd = g.std; end; end; % check consistency % ----------------- if length(datsub) > 0 & length(datadd) ~= length(datsub) error('The number of component to subtract must be the same as the number of components to add'); end; % if only 2 dataset entered, toggle average to single trial % --------------------------------------------------------- if length(datadd) == 1 &strcmpi(g.addavg, 'on') g.addavg = 'off'; g.addall = 'on'; end; if length(datsub) == 1 &strcmpi(g.subavg, 'on') g.subavg = 'off'; g.suball = 'on'; end; if length(datsub) == 1 & length(datadd) == 1 &strcmpi(g.diffavg, 'on') g.diffavg = 'off'; g.diffall = 'on'; end; regions = {}; pnts = ALLEEG(datadd(1)).pnts; srate = ALLEEG(datadd(1)).srate; xmin = ALLEEG(datadd(1)).xmin; xmax = ALLEEG(datadd(1)).xmax; nbchan = ALLEEG(datadd(1)).nbchan; chanlocs = ALLEEG(datadd(1)).chanlocs; unionIndices = union_bc(datadd, datsub); for index = unionIndices(:)' if ALLEEG(index).pnts ~= pnts, error(['Dataset ' int2str(index) ' does not have the same number of points as others']); end; if ALLEEG(index).xmin ~= xmin, error(['Dataset ' int2str(index) ' does not have the same xmin as others']); end; if ALLEEG(index).xmax ~= xmax, error(['Dataset ' int2str(index) ' does not have the same xmax as others']); end; if ALLEEG(index).nbchan ~= nbchan, error(['Dataset ' int2str(index) ' does not have the same number of channels as others']); end; end; if ~isempty(g.alpha) & length(datadd) == 1 error([ 'T-tests require more than one ''' datadd ''' dataset' ]); end % compute ERPs for add % -------------------- for index = 1:length(datadd) TMPEEG = eeg_checkset(ALLEEG(datadd(index)),'loaddata'); if flag == 1, erp1ind(:,:,index) = mean(TMPEEG.data,3); else erp1ind(:,:,index) = mean(eeg_getdatact(TMPEEG, 'component', [1:size(TMPEEG.icaweights,1)]),3); end; addnames{index} = [ '#' int2str(datadd(index)) ' ' TMPEEG.setname ' (n=' int2str(TMPEEG.trials) ')' ]; clear TMPEEG; end; % optional: subtract % ------------------ colors = {}; % color aspect for curves allcolors = { 'b' 'r' 'g' 'c' 'm' 'y' [0 0.5 0] [0.5 0 0] [0 0 0.5] [0.5 0.5 0] [0 0.5 0.5] [0.5 0 0.5] [0.5 0.5 0.5] }; allcolors = { allcolors{:} allcolors{:} allcolors{:} allcolors{:} allcolors{:} allcolors{:} }; allcolors = { allcolors{:} allcolors{:} allcolors{:} allcolors{:} allcolors{:} allcolors{:} }; if length(datsub) > 0 % dataset to subtract % compute ERPs for sub % -------------------- for index = 1:length(datsub) TMPEEG = eeg_checkset(ALLEEG(datsub(index)),'loaddata'); if flag == 1, erp2ind(:,:,index) = mean(TMPEEG.data,3); else erp2ind(:,:,index) = mean(eeg_getdatact(TMPEEG, 'component', [1:size(TMPEEG.icaweights,1)]),3); end; subnames{index} = [ '#' int2str(datsub(index)) ' ' TMPEEG.setname '(n=' int2str(TMPEEG.trials) ')' ]; clear TMPEEG end; l1 = size(erp1ind,3); l2 = size(erp2ind,3); allcolors1 = allcolors(3:l1+2); allcolors2 = allcolors(l1+3:l1+l2+3); allcolors3 = allcolors(l1+l2+3:end); [erps1, erpstd1, colors1, colstd1, legend1] = preparedata( erp1ind , g.addavg , g.addstd , g.addall , g.mode, 'Add ' , addnames, 'b', allcolors1 ); [erps2, erpstd2, colors2, colstd2, legend2] = preparedata( erp2ind , g.subavg , g.substd , g.suball , g.mode, 'Sub ' , subnames, 'r', allcolors2 ); [erps3, erpstd3, colors3, colstd3, legend3] = preparedata( erp1ind-erp2ind, g.diffavg, g.diffstd, g.diffall, g.mode, 'Diff ', ... { addnames subnames }, 'k', allcolors3 ); % handle special case of std % -------------------------- erptoplot = [ erps1 erps2 erps3 erpstd1 erpstd2 erpstd3 ]; colors = { colors1{:} colors2{:} colors3{:} colstd1{:} colstd2{:} colstd3{:}}; legend = { legend1{:} legend2{:} legend3{:} }; % highlight significant regions % ----------------------------- if ~isempty(g.alpha) pvalues = pttest(erp1ind(g.chans,:,:), erp2ind(g.chans,:,:), 3); regions = p2regions(pvalues, g.alpha, [xmin xmax]*1000); else pvalues= []; end; else [erptoplot, erpstd, colors, colstd, legend] = preparedata( erp1ind, g.addavg, g.addstd, g.addall, g.mode, '', addnames, 'k', allcolors); erptoplot = [ erptoplot erpstd ]; colors = { colors{:} colstd{:} }; % highlight significant regions % ----------------------------- if ~isempty(g.alpha) pvalues = ttest(erp1ind, 0, 3); regions = p2regions(pvalues, g.alpha, [xmin xmax]*1000); else pvalues= []; end; end; % lowpass data % ------------ if ~isempty(g.lowpass) if exist('filtfilt') == 2 erptoplot = eegfilt(erptoplot, srate, 0, g.lowpass); else erptoplot = eegfiltfft(erptoplot, srate, 0, g.lowpass); end; end; if strcmpi(g.geom, 'array') | flag == 0, chanlocs = []; end; if ~isfield(chanlocs, 'theta'), chanlocs = []; end; % select time range % ----------------- if ~isempty(g.tlim) pointrange = round(eeg_lat2point(g.tlim/1000, [1 1], srate, [xmin xmax])); g.tlim = eeg_point2lat(pointrange, [1 1], srate, [xmin xmax]); erptoplot = reshape(erptoplot, size(erptoplot,1), pnts, size(erptoplot,2)/pnts); erptoplot = erptoplot(:,[pointrange(1):pointrange(2)],:); pnts = size(erptoplot,2); erptoplot = reshape(erptoplot, size(erptoplot,1), pnts*size(erptoplot,3)); xmin = g.tlim(1); xmax = g.tlim(2); end; % plot data % --------- set(0, 'CurrentFigure', h); plottopo( erptoplot, 'chanlocs', chanlocs, 'frames', pnts, ... 'limits', [xmin xmax 0 0]*1000, 'title', g.title, 'colors', colors, ... 'chans', g.chans, 'legend', legend, 'regions', regions, 'ylim', g.ylim, g.tplotopt{:}); % outputs % ------- times = linspace(xmin, xmax, pnts); erp1 = mean(erp1ind,3); if length(datsub) > 0 % dataset to subtract erp2 = mean(erp2ind,3); erpsub = erp1-erp2; else erp2 = []; erpsub = []; end; if nargin < 3 & nargout == 1 erp1 = sprintf('pop_comperp( %s, %d, %s);', inputname(1), ... flag, vararg2str({ datadd datsub options{:} }) ); end; return; % convert significance values to alpha % ------------------------------------ function regions = p2regions( pvalues, alpha, limits); for index = 1:size(pvalues,1) signif = diff([1 pvalues(index,:) 1] < alpha); pos = find([signif] > 0); pos = pos/length(pvalues)*(limits(2) - limits(1))+limits(1); neg = find([signif(2:end)] < 0); neg = neg/length(pvalues)*(limits(2) - limits(1))+limits(1); if length(pos) ~= length(neg), signif, pos, neg, error('Region error'); end; regions{index} = [neg;pos]; end; % process data % ------------ function [erptoplot, erpstd, colors, colstd, legend] = preparedata( erpind, plotavg, plotstd, plotall, mode, tag, dataset, coloravg, allcolors); colors = {}; legend = {}; erptoplot = []; erpstd = []; colstd = {}; % plot individual differences % --------------------------- if strcmpi(plotall, 'on') erptoplot = [ erptoplot erpind(:,:) ]; for index=1:size(erpind,3) if iscell(dataset) if strcmpi(tag, 'Diff ') legend = { legend{:} [ dataset{1}{index} ' - ' dataset{2}{index} ] }; else legend = { legend{:} dataset{index} }; end; else legend = { legend{:} [ 'Dataset ' int2str(dataset(index)) ] }; end; colors = { colors{:} allcolors{index} }; end; end; % plot average % ------------ if strcmpi( plotavg, 'on') if strcmpi(mode, 'ave') granderp = mean(erpind,3); legend = { legend{:} [ tag 'Average' ] }; else granderp = sqrt(mean(erpind.^2,3)); legend = { legend{:} [ tag 'RMS' ] }; end; colors = { colors{:} {coloravg;'linewidth';2 }}; erptoplot = [ erptoplot granderp]; end; % plot standard deviation % ----------------------- if strcmpi(plotstd, 'on') if strcmpi(plotavg, 'on') std1 = std(erpind, [], 3); erptoplot = [ erptoplot granderp+std1 ]; erpstd = granderp-std1; legend = { legend{:} [ tag 'Standard dev.' ] }; colors = { colors{:} { coloravg;'linestyle';':' } }; colstd = { { coloravg 'linestyle' ':' } }; else disp('Warning: cannot show standard deviation without showing average'); end; end; % ------------------------------------------------------------------ function [p, t, df] = pttest(d1, d2, dim) %PTTEST Student's paired t-test. % PTTEST(X1, X2) gives the probability that Student's t % calculated on paired data X1 and X2 is higher than % observed, i.e. the "significance" level. This is used % to test whether two paired samples have significantly % different means. % [P, T] = PTTEST(X1, X2) gives this probability P and the % value of Student's t in T. The smaller P is, the more % significant the difference between the means. % E.g. if P = 0.05 or 0.01, it is very likely that the % two sets are sampled from distributions with different % means. % % This works for PAIRED SAMPLES, i.e. when elements of X1 % and X2 correspond one-on-one somehow. % E.g. residuals of two models on the same data. % Ref: Press et al. 1992. Numerical recipes in C. 14.2, Cambridge. if size(d1,dim) ~= size(d2, dim) error('PTTEST: paired samples must have the same number of elements !') end if size(d1,dim) == 1 close; error('Cannot compute paired t-test for a single ERP difference') end; a1 = mean(d1, dim); a2 = mean(d2, dim); v1 = std(d1, [], dim).^2; v2 = std(d2, [], dim).^2; n1 = size(d1,dim); df = n1 - 1; disp(['Computing t-values, df:' int2str(df) ]); d1 = d1-repmat(a1, [ones(1,dim-1) size(d1,3)]); d2 = d2-repmat(a2, [ones(1,dim-1) size(d2,3)]); %cab = (x1 - a1)' * (x2 - a2) / (n1 - 1); cab = sum(d1.*d2,3)/(n1-1); % use abs to avoid numerical errors for very similar data % for which v1+v2-2cab may be close to 0. t = (a1 - a2) ./ sqrt(abs(v1 + v2 - 2 * cab) / n1) ; p = betainc( df ./ (df + t.*t), df/2, 0.5) ; % ------------------------------------------------------------------ function [p, t] = ttest(d1, d2, dim) %TTEST Student's t-test for equal variances. % TTEST(X1, X2) gives the probability that Student's t % calculated on data X1 and X2, sampled from distributions % with the same variance, is higher than observed, i.e. % the "significance" level. This is used to test whether % two sample have significantly different means. % [P, T] = TTEST(X1, X2) gives this probability P and the % value of Student's t in T. The smaller P is, the more % significant the difference between the means. % E.g. if P = 0.05 or 0.01, it is very likely that the % two sets are sampled from distributions with different % means. % % This works if the samples are drawn from distributions with % the SAME VARIANCE. Otherwise, use UTTEST. % %See also: UTTEST, PTTEST. if size(d1,dim) == 1 close; error('Cannot compute t-test for a single ERP') end; a1 = mean(d1, dim); v1 = std(d1, [], dim).^2; n1 = size(d1,dim); if length(d2) == 1 & d2 == 0 a2 = 0; n2 = n1; df = n1 + n2 - 2; pvar = (2*(n1 - 1) * v1) / df ; else a2 = mean(d2, dim); v2 = std(d2, [], dim).^2; n2 = size(d2,dim); df = n1 + n2 - 2; pvar = ((n1 - 1) * v1 + (n2 - 1) * v2) / df ; end; disp(['Computing t-values, df:' int2str(df) ]); t = (a1 - a2) ./ sqrt( pvar * (1/n1 + 1/n2)) ; p = betainc( df ./ (df + t.*t), df/2, 0.5) ;
github
lcnhappe/happe-master
pop_jointprob.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/pop_jointprob.m
11,856
utf_8
2e52771f3ef70d7a913563e5c3d2a0d9
% pop_jointprob() - reject artifacts in an EEG dataset using joint % probability of the recorded electrode or component % activities observed at each time point. e.g., Observing % large absoluate values at most electrodes or components % is improbable and may well mark the presence of artifact. % Usage: % >> pop_jointprob( INEEG, typerej) % pop-up interative window mode % >> [OUTEEG, locthresh, globthresh, nrej] = ... % = pop_jointprob( INEEG, typerej, elec_comp, ... % locthresh, globthresh, superpose, reject, vistype); % % Graphic interface: % "Electrode|Component" - [edit box] electrodes or components indices to take % into consideration for rejection. Same as the 'elec_comp' % parameter in the command line call (see below). % "Single-channel limit|Single-component limit" - [edit box] activity % probability limit(s) (in std. dev.) Sets the 'locthresh' % command line parameter. If more than one, defined individual % electrode|channel limits. If fewer values than the number % of electrodes|components specified above, the last input % value is used for all remaining electrodes|components. % "All-channel limit|All-component limit" - [edit box] activity probability % limit(s) (in std. dev.) for all channels (grouped). % Sets the 'globthresh' command line parameter. % "visualization type" - [popup menu] can be either 'REJECTRIALS'|'EEGPLOT'. % This correspond to the command line input option 'vistype' % "Display with previous rejection(s)" - [checkbox] This checkbox set the % command line input option 'superpose'. % "Reject marked trial(s)" - [checkbox] This checkbox set the command % line input option 'reject'. % Inputs: % INEEG - input dataset % typerej - [1|0] data to reject on (0 = component activations; % 1 = electrode data). {Default: 1 = electrode data}. % elec_comp - [n1 n2 ...] electrode|component number(s) to take into % consideration for rejection % locthresh - activity probability limit(s) (in std. dev.) See "Single- % channel limit(s)" above. % globthresh - global limit(s) (all activities grouped) (in std. dev.) % superpose - [0|1] 0 = Do not superpose rejection marks on previously % marks stored in the dataset: 1 = Show both current and % previous marks using different colors. {Default: 0}. % reject - 0 = do not reject marked trials (but store the marks: % 1 = reject marked trials {Default: 1}. % vistype - Visualization type. [0] calls rejstatepoch() and [1] calls % eegplot() default is [0].When added to the command line % call it will not display the plots if the option 'plotflag' % is not set. % topcommand - [] Deprecated argument , keep to ensure backward compatibility % plotflag - [1,0] [1]Turns plots 'on' from command line, [0] off. % (Note for developers: When called from command line % it will make 'calldisp = plotflag') {Default: 0} % % Outputs: % OUTEEG - output dataset with updated joint probability array % locthresh - electrodes probability of activity thresholds in terms % of standard-dev. % globthresh - global threshold (where all electrode activity are % regrouped). % nrej - number of rejected sweeps % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: jointprob(), rejstatepoch(), eegplot(), eeglab(), pop_rejepoch() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-07-02 added srate argument to eegplot call -ad % 03-08-02 add eeglab options -ad function [EEG, locthresh, globthresh, nrej, com] = pop_jointprob( EEG, icacomp, elecrange, ... locthresh, globthresh, superpose, reject, vistype, topcommand,plotflag); nrej = []; com = ''; if nargin < 1 help pop_jointprob; return; end; if nargin < 2 icacomp = 1; end; if icacomp == 0 if isempty( EEG.icasphere ) ButtonName=questdlg( 'Do you want to run ICA now ?', ... 'Confirmation', 'NO', 'YES', 'YES'); switch ButtonName, case 'NO', disp('Operation cancelled'); return; case 'YES', [ EEG com ] = pop_runica(EEG); end % switch end; end; if exist('reject') ~= 1 reject = 1; end; if nargin < 3 % which set to save % ----------------- promptstr = { [ fastif(icacomp, 'Electrode', 'Component') ' (indices; Ex: 2 6:8 10):' ], ... [ fastif(icacomp, 'Single-channel', 'Single-component') ' limit(s) (std. dev(s).: Ex: 2 2 2.5):'], ... [ fastif(icacomp, 'All-channel', 'All-component') ' limit(s) (std. dev(s).: Ex: 2 2.1 2):'], ... 'Visualization type',... 'Display previous rejection marks', ... 'Reject marked trial(s)'}; inistr = { fastif(icacomp, ['1:' int2str(EEG.nbchan)], ['1:' int2str(size(EEG.icaweights,1))])... fastif(icacomp, '3', '5'), ... fastif(icacomp, '3', '5'), ... '',... '1', ... '0'}; vismodelist= {'REJECTTRIALS','EEGPLOT'}; g1 = [1 0.1 0.75]; g2 = [1 0.26 0.9]; g3 = [1 0.22 0.85]; geometry = {g1 g1 g1 g2 [1] g3 g3}; uilist = {... { 'Style', 'text', 'string', promptstr{1}} {} { 'Style','edit' , 'string' ,inistr{1} 'tag' 'cpnum'}... { 'Style', 'text', 'string', promptstr{2}} {} { 'Style','edit' , 'string' ,inistr{2} 'tag' 'singlelimit'}... { 'Style', 'text', 'string', promptstr{3}} {} { 'Style','edit' , 'string' ,inistr{3} 'tag' 'alllimit'}... { 'Style', 'text', 'string', promptstr{4}} {} { 'Style','popupmenu' , 'string' , vismodelist 'tag' 'specmethod' }... {}... { 'Style', 'text', 'string', promptstr{5}} {} { 'Style','checkbox' ,'string' , ' ' 'value' str2double(inistr{5}) 'tag','rejmarks' }... { 'Style', 'text', 'string', promptstr{6}} {} { 'Style','checkbox' ,'string' ,' ' 'value' str2double(inistr{6}) 'tag' 'rejtrials'} ... }; figname = fastif( ~icacomp, 'Reject. improbable comp. -- pop_jointprob()', 'Reject improbable data -- pop_jointprob()'); result = inputgui( geometry,uilist,'pophelp(''pop_jointprob'');', figname); size_result = size( result ); if size_result(1) == 0, locthresh = []; globthresh = []; return; end; elecrange = result{1}; locthresh = result{2}; globthresh = result{3}; switch result{4}, case 1, vistype=0; otherwise, vistype=1; end; superpose = result{5}; reject = result{6}; end; if ~exist('vistype' ,'var'), vistype = 0; end; if ~exist('reject' ,'var'), reject = 0; end; if ~exist('superpose','var'), superpose = 1; end; if isstr(elecrange) % convert arguments if they are in text format calldisp = 1; elecrange = eval( [ '[' elecrange ']' ] ); locthresh = eval( [ '[' locthresh ']' ] ); globthresh = eval( [ '[' globthresh ']' ] ); else calldisp = 0; end; if exist('plotflag','var') && ismember(plotflag,[1,0]) calldisp = plotflag; else plotflag = 0; end if isempty(elecrange) error('No electrode selectionned'); end; % compute the joint probability % ----------------------------- if icacomp == 1 fprintf('Computing joint probability for channels...\n'); tmpdata = eeg_getdatact(EEG); if isempty(EEG.stats.jpE) [ EEG.stats.jpE rejE ] = jointprob( tmpdata, locthresh, EEG.stats.jpE, 1); end; [ tmp rejEtmp ] = jointprob( tmpdata(elecrange,:,:), locthresh, EEG.stats.jpE(elecrange,:), 1); rejE = zeros(EEG.nbchan, size(rejEtmp,2)); rejE(elecrange,:) = rejEtmp; fprintf('Computing all-channel probability...\n'); tmpdata2 = permute(tmpdata, [3 1 2]); tmpdata2 = reshape(tmpdata2, size(tmpdata2,1), size(tmpdata2,2)*size(tmpdata2,3)); [ EEG.stats.jp rej ] = jointprob( tmpdata2, globthresh, EEG.stats.jp, 1); clear tmpdata2; else tmpdata = eeg_getica(EEG); fprintf('Computing joint probability for components...\n'); if isempty(EEG.stats.icajpE) [ EEG.stats.icajpE rejE ] = jointprob( tmpdata, locthresh, EEG.stats.icajpE, 1); end; [ tmp rejEtmp ] = jointprob( tmpdata(elecrange,:), locthresh, EEG.stats.icajpE(elecrange,:), 1); rejE = zeros(size(tmpdata,1), size(rejEtmp,2)); rejE(elecrange,:) = rejEtmp; fprintf('Computing global joint probability...\n'); tmpdata2 = permute(tmpdata, [3 1 2]); tmpdata2 = reshape(tmpdata2, size(tmpdata2,1), size(tmpdata2,2)*size(tmpdata2,3)); [ EEG.stats.icajp rej] = jointprob( tmpdata2, globthresh, EEG.stats.icajp, 1); clear tmpdata2; end; rej = rej' | max(rejE, [], 1); fprintf('%d/%d trials marked for rejection\n', sum(rej), EEG.trials); if calldisp if vistype == 1 % EEGPLOT ------------------------- if icacomp == 1 macrorej = 'EEG.reject.rejjp'; macrorejE = 'EEG.reject.rejjpE'; else macrorej = 'EEG.reject.icarejjp'; macrorejE = 'EEG.reject.icarejjpE'; end; colrej = EEG.reject.rejjpcol; eeg_rejmacro; % script macro for generating command and old rejection arrays if icacomp == 1 eegplot( tmpdata(elecrange,:,:), 'srate', ... EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}); else eegplot( tmpdata(elecrange,:,:), 'srate', ... EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}); end; else % REJECTRIALS ------------------------- if icacomp == 1 [ rej, rejE, n, locthresh, globthresh] = ... rejstatepoch( tmpdata(elecrange,:,:), EEG.stats.jpE(elecrange,:), 'global', 'on', 'rejglob', EEG.stats.jp, ... 'threshold', locthresh, 'thresholdg', globthresh, 'normalize', 'off' ); else [ rej, rejE, n, locthresh, globthresh] = ... rejstatepoch( tmpdata(elecrange,:,:), EEG.stats.icajpE(elecrange,:), 'global', 'on', 'rejglob', EEG.stats.icajp, ... 'threshold', locthresh, 'thresholdg', globthresh, 'normalize', 'off' ); end; nrej = n; end; else % compute rejection locally rejtmp = max(rejE(elecrange,:),[],1); rej = rejtmp | rej; nrej = sum(rej); fprintf('%d trials marked for rejection\n', nrej); end; if ~isempty(rej) if icacomp == 1 EEG.reject.rejjp = rej; EEG.reject.rejjpE = rejE; else EEG.reject.icarejjp = rej; EEG.reject.icarejjpE = rejE; end; if reject EEG = pop_rejepoch(EEG, rej, 0); end; end; nrej = sum(rej); com = [ com sprintf('%s = pop_jointprob(%s,%s);', inputname(1), ... inputname(1), vararg2str({icacomp,elecrange,locthresh,globthresh,superpose,reject, vistype, [],plotflag})) ]; if nargin < 3 & nargout == 2 locthresh = com; end; return;
github
lcnhappe/happe-master
eeg_lat2point.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_lat2point.m
4,019
utf_8
fc612a716877495d005080fab259effb
% eeg_lat2point() - convert latencies in time units relative to the % time locking event of an eeglab() data epoch to % latencies in data points (assuming concatenated epochs). % Usage: % >> [newlat] = eeg_lat2point( lat_array, epoch_array,... % srate, timelimits, timeunit); % >> [newlat] = eeg_lat2point( lat_array, epoch_array,... % srate, timelimits, '','outrange',1); % Inputs: % lat_array - latency array in 'timeunit' units (see below) % epoch_array - epoch number for each latency % srate - data sampling rate in Hz % timelimits - [min max] epoch timelimits in 'timeunit' units (see below) % timeunit - time unit relative to seconds. Default is 1 = seconds. % % Optional inputs: % outrange - [1/0] Replace the points out of the range with the value of % the maximun point in the valid range or raise an error. % Default [1] : Replace point. % % Outputs: % newlat - converted latency values in points assuming concatenated % data epochs (see eeglab() event structure) % flag - 1 if any point out of range was replaced. % % Author: Arnaud Delorme, CNL / Salk Institute, 2 Mai 2002 % % See also: eeg_point2lat(), eeglab() % Copyright (C) 2 Mai 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [newlat,flag] = eeg_lat2point( lat_array, epoch_array, srate, timewin, timeunit, varargin); % ------------------------------------------------------------------------- try options = varargin; if ~isempty( varargin ), for i = 1:2:numel(options) g.(options{i}) = options{i+1}; end else g= []; end; catch error('std_checkdatasession() error: calling convention {''key'', value, ... } error'); end; try, g.outrange; catch, g.outrange = 1; end; % flag = 0; % ------------------------------------------------------------------------- if nargin <4 help eeg_lat2point; return; end; if nargin <5 | isempty(timeunit) timeunit = 1; end; if length(lat_array) ~= length(epoch_array) if length(epoch_array)~= 1 disp('eeg_lat2point: latency and epochs must have the same length'); return; else epoch_array = ones(1,length(lat_array))*epoch_array; end; end; if length(timewin) ~= 2 disp('eeg_lat2point: timelimits must have length 2'); return; end; if iscell(epoch_array) epoch_array = [ epoch_array{:} ]; end; if iscell(lat_array) lat_array = [ lat_array{:} ]; end timewin = timewin*timeunit; pnts = (timewin(2)-timewin(1))*srate+1; newlat = (lat_array*timeunit-timewin(1))*srate+1 + (epoch_array-1)*pnts; % Detecting points out of range (RMC) % Note: This is neccesary since the double precision multiplication could lead to the % shifting in one sample out of the valid range if and(~isempty(newlat),~isempty(epoch_array)) && max(newlat(:)) > max((epoch_array)*pnts) if g.outrange == 1 IndxOut = find(newlat(:) > max((epoch_array)*pnts)); newlat(IndxOut) = max((epoch_array)*pnts); flag = 1; warning('eeg_lat2point(): Points out of range detected. Points replaced with maximum value'); elseif g.outrange == 0 error('Error in eeg_lat2point(): Points out of range detected'); end end
github
lcnhappe/happe-master
eeg_addnewevents.m
.m
happe-master/Packages/eeglab14_0_0b/functions/popfunc/eeg_addnewevents.m
7,648
utf_8
ffc9194217c3e26d7b32be5361c7163b
% eeg_addnewevents() Add new events to EEG structure. Both EEG.event and % EEG.urevent are updated. % % Usage: % >> EEG = eeg_addnewevents(EEG, latencies, types, fieldNames, fieldValues); % % Inputs: % EEG - input dataset % latencies - cell containing numerical arrays for latencies of new % events, each array corresponds to a different event type. % type - cell array containing name of event types. % % Optional Inputs % fieldNames - cell array containing names of fields to be added to event structure. % fieldValues - A cell containing arrays for field values corresponding to fieldNames. % Number of values for each field should be equal to the total number of % latencies (new events) added to dataset. % Outputs: % EEG - EEG dataset with updated event and urevent fields % % Example: % EEG = eeg_addnewevents(EEG, {[100 200] [300 400 500]}, {'type1' 'type2'}, {'field1' 'field2'}, {[1 2 3 4 5] [6 7 8 9]}); % % Author: Nima Bigdely Shamlo, SCCN/INC/UCSD, 2008 function EEG = eeg_addnewevents(EEG, eventLatencyArrays, types, fieldNames, fieldValues); if ~isfield(EEG, 'event') EEG.event = []; EEG.urevent = []; EEG.event(1).type = 'dummy'; EEG.event(1).latency = 1; EEG.event(1).duration = 0; EEG.event(1).urevent = 1; EEG.urevent(1).type = 'dummy'; EEG.urevent(1).latency = 1; EEG.urevent(1).duration = 0; end; % add duration field if it does not exist if length(EEG.event)>0 && ~isfield(EEG.event(1),'duration') EEG.event(1).duration = 0; EEG.urevent(1).duration = 0; end; if nargin<4 fieldNames = []; fieldValues = []; end; newEventLatency = []; for i=1:length(eventLatencyArrays) newEventLatency = [newEventLatency eventLatencyArrays{i}]; end; newEventType = []; for i=1:length(eventLatencyArrays{1}) newEventType{i} = types{1}; end; for j=2:length(eventLatencyArrays) startIndex = length(newEventType); for i=1:length(eventLatencyArrays{j}) newEventType{startIndex+i} = types{j}; end; end; % mix new and old events, sort them by latency and put them back in EEG originalEventLatency = []; originalEventType = []; originalFieldNames = []; for i=1:length(EEG.event) originalEventLatency(i) = EEG.event(i).latency; originalEventType{i} = EEG.event(i).type; originalEventFields(i) = EEG.event(i); end; % make sure that originalEventFields has all the new field names if ~isempty(EEG.event) originalFieldNames = fields(originalEventFields); for f= 1:length(fieldNames) if ~isfield(originalEventFields, fieldNames{f}) originalEventFields(length(originalEventFields)).(fieldNames{f}) = NaN; end; end; end; % make sure that newEventFields has all the original field names for i=1:length(originalFieldNames) newEventFields(length(newEventLatency)).(originalFieldNames{i}) = NaN; end; for i=1:length(newEventLatency) newEventFields(i).latency = newEventLatency(i); newEventFields(i).type = newEventType{i}; newEventFields(i).duration = 0; for f= 1:length(fieldNames) newEventFields(i).(fieldNames{f}) = fieldValues{f}(i); end; end; if ~isempty(EEG.event) %newEventFields = struct('latency', num2cell(newEventLatency), 'type', newEventType); combinedFields = [originalEventFields newEventFields]; combinedLatencies = [originalEventLatency newEventLatency]; combinedType = [originalEventType newEventType]; else combinedFields = newEventFields; combinedLatencies = newEventLatency; combinedType = newEventType; end [sortedEventLatency order] = sort(combinedLatencies,'ascend'); sortedEventType = combinedType(order); combinedFields = combinedFields(order); % put events in eeg %EEG.urevent = []; %EEG.event = []; EEG = rmfield(EEG,'event'); for i=1:length(sortedEventLatency) % EEG.urevent(i).latency = sortedEventLatency(i); % EEG.urevent(i).type = sortedEventType{i}; % combinedFields(order(i)).urevent = i; EEG.event(i) = combinedFields(i); % EEG.event(i).urevent = i; end; %% adding new urevents originalUreventNumber = 1:length(EEG.urevent); originalUreventLatency = zeros(1, length(EEG.urevent)); originalUreventFields= cell(1, length(EEG.urevent)); for i=1:length(EEG.urevent) originalUreventLatency(i) = EEG.urevent(i).latency; originalUreventFields{i} = EEG.urevent(i); end; newUreventLatency = []; newUreventType = []; for i=1:length(EEG.event) if ~isfield(EEG.event,'urevent') || length(EEG.event(i).urevent) == 0 || isnan(EEG.event(i).urevent) % newUreventLatency = [newUreventLatency newEventUrEventLatency(EEG, combinedFields, i)]; % use eeg_urlatency to calculate the original latency based on % EEG.event duartions newUreventLatency = [newUreventLatency eeg_urlatency(EEG.event, EEG.event(i).latency)]; else newUreventLatency = [newUreventLatency EEG.urevent(EEG.event(i).urevent).latency]; end; newUreventFields{i} = EEG.event(i); newUreventEventNumber(i) = i; end; combinedEventNumber = newUreventEventNumber;%[NaN(1,length(EEG.urevent)) newUreventEventNumber]; combinedUrEventLatencies = newUreventLatency;%[originalUreventLatency newUreventLatency]; [sortedUrEventLatency order] = sort(combinedUrEventLatencies,'ascend'); % make urvent stucture ready EEG.urevent = []; EEG.urevent= newUreventFields{order(1)}; for i=1:length(order) %if ~isnan(newUreventEventNumber(i)) EEG.urevent(i) = newUreventFields{order(i)}; EEG.urevent(i).latency = combinedUrEventLatencies(order(i)); EEG.event(newUreventEventNumber(i)).urevent = i; %end; end; if isfield(EEG.urevent,'urevent') EEG.urevent = rmfield(EEG.urevent,'urevent'); % remove urevent field end; % turn empty event durations into 0 for i=1:length(EEG.event) if isempty(EEG.event(i).duration) EEG.event(i).duration = 0; end; end; for i=1:length(EEG.urevent) if isempty(EEG.urevent(i).duration) EEG.urevent(i).duration = 0; end; end; % % function latency = newEventUrEventLatency(EEG, combinedFields, i) % % %% looks for an event with urvent before the new event % urlatencyBefore = []; % currentEventNumber = i; % % while isempty(urlatencyBefore) && currentEventNumber > 1 % currentEventNumber = currentEventNumber - 1; % if ~(~isfield(combinedFields(currentEventNumber),'urevent') || isempty(combinedFields(currentEventNumber).urevent) || isnan(combinedFields(currentEventNumber).urevent)) % urlatencyBefore = EEG.urevent(combinedFields(currentEventNumber).urevent).latency; % end; % end % % %% if no event with urevent is found before, look for an event with urvent after the new event % if isempty(urlatencyBefore) % urlatencyAfter = []; % currentEventNumber = i; % % while isempty(urlatencyAfter) && currentEventNumber < length(combinedFields) % currentEventNumber = currentEventNumber + 1; % if ~(~isfield(combinedFields(currentEventNumber),'urevent') || isempty(combinedFields(currentEventNumber).urevent) || isnan(combinedFields(currentEventNumber).urevent)) % urlatencyAfter = EEG.urevent(combinedFields(currentEventNumber).urevent).latency; % end; % end % end; % %% % if ~isempty(urlatencyBefore) % latency = urlatencyBefore + combinedFields(i).latency - combinedFields(currentEventNumber).latency; % elseif ~isempty(urlatencyAfter) % latency = urlatencyAfter + combinedFields(currentEventNumber).latency - combinedFields(i).latency; % else % latency = []; % end;
github
lcnhappe/happe-master
fmins.m
.m
happe-master/Packages/eeglab14_0_0b/functions/octavefunc/optim/fmins.m
3,181
utf_8
775abc7aa3b9020a0c2080db64070155
% Copyright (C) 2003 Andy Adler % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % -*- texinfo -*- % @deftypefn {Function File} {[@var{x}] =} fmins(@var{f},@var{X0},@var{options},@var{grad},@var{P1},@var{P2}, ...) % % Find the minimum of a funtion of several variables. % By default the method used is the Nelder&Mead Simplex algorithm % % Example usage: % fmins(inline('(x(1)-5).^2+(x(2)-8).^4'),[0;0]) % % @strong{Inputs} % @table @var % @item f % A string containing the name of the function to minimize % @item X0 % A vector of initial parameters fo the function @var{f}. % @item options % Vector with control parameters (not all parameters are used) % @verbatim % options(1) - Show progress (if 1, default is 0, no progress) % options(2) - Relative size of simplex (default 1e-3) % options(6) - Optimization algorithm % if options(6)==0 - Nelder & Mead simplex (default) % if options(6)==1 - Multidirectional search Method % if options(6)==2 - Alternating Directions search % options(5) % if options(6)==0 && options(5)==0 - regular simplex % if options(6)==0 && options(5)==1 - right-angled simplex % Comment: the default is set to "right-angled simplex". % this works better for me on a broad range of problems, % although the default in nmsmax is "regular simplex" % options(10) - Maximum number of function evaluations % @end verbatim % @item grad % Unused (For compatibility with Matlab) % @item P1,P2, ... % Optional parameters for function @var{f} % % @end table % @end deftypefn function ret=fmins(funfun, X0, options, grad, varargin) if ismatlab if license('test','optim_toolbox') p = fileparts(which('fmins')); error( [ 'Octave functions should not run on Matlab' 10 'remove path to ' p ]); end; end; stopit = [1e-3, inf, inf, 1, 0, -1]; minfun = 'nmsmax'; if nargin < 3; options=[]; end if length(options)>=1; stopit(5)= options(1); end if length(options)>=2; stopit(1)= options(2); end if length(options)>=5; if options(6)==0; minfun= 'nmsmax'; if options(5)==0; stopit(4)= 0; elseif options(5)==1; stopit(4)= 1; else error('options(5): no associated simple strategy'); end elseif options(6)==1; minfun= 'mdsmax'; elseif options(6)==2; minfun= 'adsmax'; else error('options(6) does not correspond to known algorithm'); end end if length(options)>=10; stopit(2)= options(10); end ret = feval(minfun, funfun, X0, stopit, [], varargin{:});
github
lcnhappe/happe-master
fminsearch.m
.m
happe-master/Packages/eeglab14_0_0b/functions/octavefunc/optim/fminsearch.m
2,386
utf_8
24a86640354f4abf5e4d1e15a97b9a27
% Copyright (C) 2006 Sylvain Pelissier <[email protected]> % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % -*- texinfo -*- % @deftypefn {Function File} {[@var{x}] =} fminsearch(@var{f},@var{X0},@var{options},@var{grad},@var{P1},@var{P2}, ...) % % Find the minimum of a funtion of several variables. % By default the method used is the Nelder&Mead Simplex algorithm % @seealso{fmin,fmins,nmsmax} % @end deftypefn function varargout = fminsearch(funfun, X0, varargin) if ismatlab p1 = fileparts(which('fminsearch')); rmpath(p1); p2 = fileparts(which('fminsearch')); if ~isequal(p1, p2) disp( [ 'Some Octave functions should not run on Matlab' 10 'removing path to Octave fminsearch and using Matlab fminsearch' ]); switch nargout case 1, varargout{1} = fminsearch(funfun, X0, varargin{:}); case 2, [varargout{1} varargout{2}] = fminsearch(funfun, X0, varargin{:}); case 3, [varargout{1} varargout{2} varargout{3}] = fminsearch(funfun, X0, varargin{:}); case 4, [varargout{1} varargout{2} varargout{3} varargout{4}]= fminsearch(funfun, X0, varargin{:}); end; else disp( [ 'Octave functions should not run on Matlab' 10 'remove path ' p1 ]); end; return; end; if (nargin == 0); usage('[x fval] = fminsearch(funfun, X0, options, grad, varargin)'); end if length(varargin) > 0, options = varargin{1}; varargin(1) = []; end; if length(varargin) > 0, grad = varargin{1}; varargin(1) = []; end; if (nargin < 3); options=[]; end if (nargin < 4); grad=[]; end if (nargin < 5); varargin={}; end varargout{1} = fmins(funfun, X0, options, grad, varargin{:}); varargout{2} = feval(funfun, x, varargin{:});
github
lcnhappe/happe-master
pwelch.m
.m
happe-master/Packages/eeglab14_0_0b/functions/octavefunc/signal/pwelch.m
37,809
utf_8
360a005a779e4d7ad6b92dc49ec8c04c
% Copyright (C) 2006 Peter V. Lanspeary % % This program is free software; you can redistribute it and/or % modify it under the terms of the GNU General Public License % as published by the Free Software Foundation; either version 2, % or (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % % USAGE: % [spectra,freq] = pwelch(x,window,overlap,Nfft,Fs, % range,plot_type,detrend,sloppy) % Estimate power spectral density of data "x" by the Welch (1967) % periodogram/FFT method. All arguments except "x" are optional. % The data is divided into segments. If "window" is a vector, each % segment has the same length as "window" and is multiplied by "window" % before (optional) zero-padding and calculation of its periodogram. If % "window" is a scalar, each segment has a length of "window" and a % Hamming window is used. % The spectral density is the mean of the periodograms, scaled so that % area under the spectrum is the same as the mean square of the % data. This equivalence is supposed to be exact, but in practice there % is a mismatch of up to 0.5% when comparing area under a periodogram % with the mean square of the data. % % [spectra,freq] = pwelch(x,y,window,overlap,Nfft,Fs, % range,plot_type,detrend,sloppy,results) % Two-channel spectrum analyser. Estimate power spectral density, cross- % spectral density, transfer function and/or coherence functions of time- % series input data "x" and output data "y" by the Welch (1967) % periodogram/FFT method. % pwelch treats the second argument as "y" if there is a control-string % argument "cross", "trans", "coher" or "ypower"; "power" does not force % the 2nd argument to be treated as "y". All other arguments are % optional. All spectra are returned in matrix "spectra". % % [spectra,Pxx_ci,freq] = pwelch(x,window,overlap,Nfft,Fs,conf, % range,plot_type,detrend,sloppy) % [spectra,Pxx_ci,freq] = pwelch(x,y,window,overlap,Nfft,Fs,conf, % range,plot_type,detrend,sloppy,results) % Estimates confidence intervals for the spectral density. % See Hint (7) below for compatibility options. Confidence level "conf" % is the 6th or 7th numeric argument. If "results" control-string % arguments are used, one of them must be "power" when the "conf" % argument is present; pwelch can estimate confidence intervals only for % the power spectrum of the "x" data. It does not know how to estimate % confidence intervals of the cross-power spectrum, transfer function or % coherence; if you can suggest a good method, please send a bug report. % % ARGUMENTS % All but the first argument are optional and may be empty, except that % the "results" argument may require the second argument to be "y". % % x % [non-empty vector] system-input time-series data % y % [non-empty vector] system-output time-series data % % window % [real vector] of window-function values between 0 and 1; the % % data segment has the same length as the window. % % Default window shape is Hamming. % % [integer scalar] length of each data segment. The default % % value is window=sqrt(length(x)) rounded up to the % % nearest integer power of 2; see 'sloppy' argument. % % overlap % [real scalar] segment overlap expressed as a multiple of % % window or segment length. 0 <= overlap < 1, % % The default is overlap=0.5 . % % Nfft % [integer scalar] Length of FFT. The default is the length % % of the "window" vector or has the same value as the % % scalar "window" argument. If Nfft is larger than the % % segment length, "seg_len", the data segment is padded % % with "Nfft-seg_len" zeros. The default is no padding. % % Nfft values smaller than the length of the data % % segment (or window) are ignored silently. % % Fs % [real scalar] sampling frequency (Hertz); default=1.0 % % conf % [real scalar] confidence level between 0 and 1. Confidence % % intervals of the spectral density are estimated from % % scatter in the periodograms and are returned as Pxx_ci. % % Pxx_ci(:,1) is the lower bound of the confidence % % interval and Pxx_ci(:,2) is the upper bound. If there % % are three return values, or conf is an empty matrix, % % confidence intervals are calculated for conf=0.95 . % % If conf is zero or is not given, confidence intervals % % are not calculated. Confidence intervals can be % % obtained only for the power spectral density of x; % % nothing else. % % CONTROL-STRING ARGUMENTS -- each of these arguments is a character string. % Control-string arguments must be after the other arguments but can be in % any order. % % range % 'half', 'onesided' : frequency range of the spectrum is % % zero up to but not including Fs/2. Power from % % negative frequencies is added to the positive side of % % the spectrum, but not at zero or Nyquist (Fs/2) % % frequencies. This keeps power equal in time and % % spectral domains. See reference [2]. % % 'whole', 'twosided' : frequency range of the spectrum is % % -Fs/2 to Fs/2, with negative frequencies % % stored in "wrap around" order after the positive % % frequencies; e.g. frequencies for a 10-point 'twosided' % % spectrum are 0 0.1 0.2 0.3 0.4 0.5 -0.4 -0.3 -0.2 -0.1 % % 'shift', 'centerdc' : same as 'whole' but with the first half % % of the spectrum swapped with second half to put the % % zero-frequency value in the middle. (See "help % % fftshift". % % If data (x and y) are real, the default range is 'half', % % otherwise default range is 'whole'. % % plot_type % 'plot', 'semilogx', 'semilogy', 'loglog', 'squared' or 'db': % % specifies the type of plot. The default is 'plot', which % % means linear-linear axes. 'squared' is the same as 'plot'. % % 'dB' plots "10*log10(psd)". This argument is ignored and a % % spectrum is not plotted if the caller requires a returned % % value. % % detrend % 'no-strip', 'none' -- do NOT remove mean value from the data % % 'short', 'mean' -- remove the mean value of each segment from % % each segment of the data. % % 'linear', -- remove linear trend from each segment of % % the data. % % 'long-mean' -- remove the mean value from the data before % % splitting it into segments. This is the default. % % sloppy % 'sloppy': FFT length is rounded up to the nearest integer % % power of 2 by zero padding. FFT length is adjusted % % after addition of padding by explicit Nfft argument. % % The default is to use exactly the FFT and window/ % % segment lengths specified in argument list. % % results % specifies what results to return (in the order specified % % and as many as desired). % % 'power' calculate power spectral density of "x" % % 'cross' calculate cross spectral density of "x" and "y" % % 'trans' calculate transfer function of a system with % % input "x" and output "y" % % 'coher' calculate coherence function of "x" and "y" % % 'ypower' calculate power spectral density of "y" % % The default is 'power', with argument "y" omitted. % % RETURNED VALUES: % If return values are not required by the caller, the results are % plotted and nothing is returned. % % spectra % [real-or-complex matrix] columns of the matrix contain results % % in the same order as specified by "results" arguments. % % Each column contains one of the result vectors. % % Pxx_ci % [real matrix] estimate of confidence interval for power % % spectral density of x. First column is the lower % % bound. Second column is the upper bound. % % freq % [real column vector] frequency values % % HINTS % 1) EMPTY ARGS: % if you don't want to use an optional argument you can leave it empty % by writing its value as []. % 2) FOR BEGINNERS: % The profusion of arguments may make pwelch difficult to use, and an % unskilled user can easily produce a meaningless result or can easily % mis-interpret the result. With real data "x" and sampling frequency % "Fs", the easiest and best way for a beginner to use pwelch is % probably "pwelch(x,[],[],[],Fs)". Use the "window" argument to % control the length of the spectrum vector. For real data and integer % scalar M, "pwelch(x,2*M,[],[],Fs)" gives an M+1 point spectrum. % Run "demo pwelch" (octave only). % 3) WINDOWING FUNCTIONS: % Without a window function, sharp spectral peaks can have strong % sidelobes because the FFT of a data in a segment is in effect convolved % with a rectangular window. A window function which tapers off % (gradually) at the ends produces much weaker sidelobes in the FFT. % Hann (hanning), hamming, bartlett, blackman, flattopwin etc are % available as separate Matlab/sigproc or Octave functions. The sidelobes % of the Hann window have a roll-off rate of 60dB/decade of frequency. % The first sidelobe of the Hamming window is suppressed and is about 12dB % lower than the first Hann sidelobe, but the roll-off rate is only % 20dB/decade. You can inspect the FFT of a Hann window by plotting % "abs(fft(postpad(hanning(256),4096,0)))". % The default window is Hamming. % 4) ZERO PADDING: % Zero-padding reduces the frequency step in the % spectrum, and produces an artificially smoothed spectrum. For example, % "Nfft=2*length(window)" gives twice as many frequency values, but % adjacent PSD (power spectral density) values are not independent; % adjacent PSD values are independent if "Nfft=length(window)", which is % the default value of Nfft. % 5) REMOVING MEAN FROM SIGNAL: % If the mean is not removed from the signal there is a large spectral % peak at zero frequency and the sidelobes of this peak are likely to % swamp the rest of the spectrum. For this reason, the default behaviour % is to remove the mean. However, the matlab pwelch does not do this. % 6) WARNING ON CONFIDENCE INTERVALS % Confidence intervals are obtained by measuring the sample variance of % the periodograms and assuming that the periodograms have a Gaussian % probability distribution. This assumption is not accurate. If, for % example, the data (x) is Gaussian, the periodogram has a Rayleigh % distribution. However, the confidence intervals may still be useful. % % 7) COMPATIBILITY WITH Matlab R11, R12, etc % When used without the second data (y) argument, arguments are compatible % with the pwelch of Matlab R12, R13, R14, 2006a and 2006b except that % 1) overlap is expressed as a multiple of window length --- % effect of overlap scales with window length % 2) default values of length(window), Nfft and Fs are more sensible, and % 3) Goertzel algorithm is not available so Nfft cannot be an array of % frequencies as in Matlab 2006b. % Pwelch has four persistent Matlab-compatibility levels. Calling pwelch % with an empty first argument sets the order of arguments and defaults % specified above in the USAGE and ARGUMENTS section of this documentation. % prev_compat=pwelch([]); % [Pxx,f]=pwelch(x,window,overlap,Nfft,Fs,conf,...); % Calling pwelch with a single string argument (as described below) gives % compatibility with Matlab R11 or R12, or the R14 spectrum.welch % defaults. The returned value is the PREVIOUS compatibility string. % % Matlab R11: For compatibility with the Matlab R11 pwelch: % prev_compat=pwelch('R11-'); % [Pxx,f]=pwelch(x,Nfft,Fs,window,overlap,conf,range,units); % % units of overlap are "number of samples" % % defaults: Nfft=min(length(x),256), Fs=2*pi, length(window)=Nfft, % % window=Hanning, do not detrend, % % N.B. "Sloppy" is not available. % % Matlab R12: For compatibility with Matlab R12 to 2006a pwelch: % prev_compat=pwelch('R12+'); % [Pxx,f]=pwelch(x,window,overlap,nfft,Fs,...); % % units of overlap are "number of samples" % % defaults: length(window)==length(x)/8, window=Hamming, % % Nfft=max(256,NextPow2), Fs=2*pi, do not detrend % % NextPow2 is the next power of 2 greater than or equal to the % % window length. "Sloppy", "conf" are not available. Default % % window length gives very poor amplitude resolution. % % To adopt defaults of the Matlab R14 "spectrum.welch" spectrum object % associated "psd" method. % prev_compat=pwelch('psd'); % [Pxx,f] = pwelch(x,window,overlap,Nfft,Fs,conf,...); % % overlap is expressed as a percentage of window length, % % defaults: length(window)==64, Nfft=max(256,NextPow2), Fs=2*pi % % do not detrend % % NextPow2 is the next power of 2 greater than or equal to the % % window length. "Sloppy" is not available. % % Default window length gives coarse frequency resolution. % % % REFERENCES % [1] Peter D. Welch (June 1967): % "The use of fast Fourier transform for the estimation of power spectra: % a method based on time averaging over short, modified periodograms." % IEEE Transactions on Audio Electroacoustics, Vol AU-15(6), pp 70-73 % % [2] William H. Press and Saul A. Teukolsky and William T. Vetterling and % Brian P. Flannery", % "Numerical recipes in C, The art of scientific computing", 2nd edition, % Cambridge University Press, 2002 --- Section 13.7. % [3] Paul Kienzle (1999-2001): "pwelch", http://octave.sourceforge.net/ function [varargout] = pwelch(x,varargin) checkfunctionmatlab('pwelch', 'signal_toolbox') % % COMPATIBILITY LEVEL % Argument positions and defaults depend on compatibility level selected % by calling pwelch without arguments or with a single string argument. % native: compatib=1; prev_compat=pwelch(); prev_compat=pwelch([]); % matlab R11: compatib=2; prev_compat=pwelch('R11-'); % matlab R12: compatib=3; prev_compat=pwelch('R12+'); % spectrum.welch defaults: compatib=4; prev_compat=pwelch('psd'); % In each case, the returned value is the PREVIOUS compatibility string. % compat_str = {[]; 'R11-'; 'R12+'; 'psd'}; persistent compatib; if ( isempty(compatib) || compatib<=0 || compatib>4 ) % legal values are 1, 2, 3, 4 compatib = 1; end if ( nargin <= 0 ) error( 'pwelch: Need at least 1 arg. Use "help pwelch".' ); elseif ( nargin==1 && (ischar(x) || isempty(x)) ) varargout{1} = compat_str{compatib}; if ( isempty(x) ) % native compatib = 1; elseif ( strcmp(x,'R11-') ) compatib = 2; elseif ( strcmp(x,'R12+') ) compatib = 3; elseif ( strcmp(x,'psd') ) compatib = 4; else error( 'pwelch: compatibility arg must be empty, R11-, R12+ or psd' ); end % return % % Check fixed argument elseif ( isempty(x) || ~isvector(x) ) error( 'pwelch: arg 1 (x) must be vector.' ); else % force x to be COLUMN vector if ( size(x,1)==1 ) x=x(:); end % % Look through all args to check if cross PSD, transfer function or % coherence is required. If yes, the second arg is data vector "y". arg2_is_y = 0; x_len = length(x); nvarargin = length(varargin); for iarg=1:nvarargin arg = varargin{iarg}; if ( ~isempty(arg) && ischar(arg) && ... ( strcmp(arg,'cross') || strcmp(arg,'trans') || ... strcmp(arg,'coher') || strcmp(arg,'ypower') )) % OK. Need "y". Grab it from 2nd arg. arg = varargin{1}; if ( nargin<2 || isempty(arg) || ~isvector(arg) || length(arg)~=x_len ) error( 'pwelch: arg 2 (y) must be vector, same length as x.' ); end % force COLUMN vector y = varargin{1}(:); arg2_is_y = 1; break; end end % % COMPATIBILITY % To select default argument values, "compatib" is used as an array index. % Index values are 1=native, 2=R11, 3=R12, 4=spectrum.welch % % argument positions: % arg_posn = varargin index of window, overlap, Nfft, Fs and conf % args respectively, a value of zero ==>> arg does not exist arg_posn = [1 2 3 4 5; % native 3 4 1 2 5; % Matlab R11- pwelch 1 2 3 4 0; % Matlab R12+ pwelch 1 2 3 4 5]; % spectrum.welch defaults arg_posn = arg_posn(compatib,:) + arg2_is_y; % % SPECIFY SOME DEFAULT VALUES for (not all) optional arguments % Use compatib as array index. % Fs = sampling frequency Fs = [ 1.0 2*pi 2*pi 2*pi ]; Fs = Fs(compatib); % plot_type: 1='plot'|'squared'; 5='db'|'dB' plot_type = [ 1 5 5 5 ]; plot_type = plot_type(compatib); % rm_mean: 3='long-mean'; 0='no-strip'|'none' rm_mean = [ 3 0 0 0 ]; rm_mean = rm_mean(compatib); % use max_overlap=x_len-1 because seg_len is not available yet % units of overlap are different for each version: % fraction, samples, or percent max_overlap = [ 0.95 x_len-1 x_len-1 95]; max_overlap = max_overlap(compatib); % default confidence interval % if there are more than 2 return values and if there is a "conf" arg conf = 0.95 * (nargout>2) * (arg_posn(5)>0); % is_win = 0; % =0 means valid window arg is not provided yet Nfft = []; % default depends on segment length overlap = []; % WARNING: units can be #samples, fraction or percentage range = ~isreal(x) || ( arg2_is_y && ~isreal(y) ); is_sloppy = 0; n_results = 0; do_power = 0; do_cross = 0; do_trans = 0; do_coher = 0; do_ypower = 0; % % DECODE AND CHECK OPTIONAL ARGUMENTS end_numeric_args = 0; for iarg = 1+arg2_is_y:nvarargin arg = varargin{iarg}; if ( ischar(arg) ) % first string arg ==> no more numeric args % non-string args cannot follow a string arg end_numeric_args = 1; % % decode control-string arguments if ( strcmp(arg,'sloppy') ) is_sloppy = ~is_win || is_win==1; elseif ( strcmp(arg,'plot') || strcmp(arg,'squared') ) plot_type = 1; elseif ( strcmp(arg,'semilogx') ) plot_type = 2; elseif ( strcmp(arg,'semilogy') ) plot_type = 3; elseif ( strcmp(arg,'loglog') ) plot_type = 4; elseif ( strcmp(arg,'db') || strcmp(arg,'dB') ) plot_type = 5; elseif ( strcmp(arg,'half') || strcmp(arg,'onesided') ) range = 0; elseif ( strcmp(arg,'whole') || strcmp(arg,'twosided') ) range = 1; elseif ( strcmp(arg,'shift') || strcmp(arg,'centerdc') ) range = 2; elseif ( strcmp(arg,'long-mean') ) rm_mean = 3; elseif ( strcmp(arg,'linear') ) rm_mean = 2; elseif ( strcmp(arg,'short') || strcmp(arg,'mean') ) rm_mean = 1; elseif ( strcmp(arg,'no-strip') || strcmp(arg,'none') ) rm_mean = 0; elseif ( strcmp(arg, 'power' ) ) if ( ~do_power ) n_results = n_results+1; do_power = n_results; end elseif ( strcmp(arg, 'cross' ) ) if ( ~do_cross ) n_results = n_results+1; do_cross = n_results; end elseif ( strcmp(arg, 'trans' ) ) if ( ~do_trans ) n_results = n_results+1; do_trans = n_results; end elseif ( strcmp(arg, 'coher' ) ) if ( ~do_coher ) n_results = n_results+1; do_coher = n_results; end elseif ( strcmp(arg, 'ypower' ) ) if ( ~do_ypower ) n_results = n_results+1; do_ypower = n_results; end else error( 'pwelch: string arg %d illegal value: %s', iarg+1, arg ); end % end of processing string args % elseif ( end_numeric_args ) if ( ~isempty(arg) ) % found non-string arg after a string arg ... oops error( 'pwelch: control arg must be string' ); end % % first 4 optional arguments are numeric -- in fixed order % % deal with "Fs" and "conf" first because empty arg is a special default % -- "Fs" arg -- sampling frequency elseif ( iarg == arg_posn(4) ) if ( isempty(arg) ) Fs = 1; elseif ( ~isscalar(arg) || ~isreal(arg) || arg<0 ) error( 'pwelch: arg %d (Fs) must be real scalar >0', iarg+1 ); else Fs = arg; end % % -- "conf" arg -- confidence level % guard against the "it cannot happen" iarg==0 elseif ( arg_posn(5) && iarg == arg_posn(5) ) if ( isempty(arg) ) conf = 0.95; elseif ( ~isscalar(arg) || ~isreal(arg) || arg < 0.0 || arg >= 1.0 ) error( 'pwelch: arg %d (conf) must be real scalar, >=0, <1',iarg+1 ); else conf = arg; end % % skip all empty args from this point onward elseif ( isempty(arg) ) 1; % % -- "window" arg -- window function elseif ( iarg == arg_posn(1) ) if ( isscalar(arg) ) is_win = 1; elseif ( isvector(arg) ) is_win = length(arg); if ( size(arg,2)>1 ) % vector must be COLUMN vector arg = arg(:); end else is_win = 0; end if ( ~is_win ) error( 'pwelch: arg %d (window) must be scalar or vector', iarg+1 ); elseif ( is_win==1 && ( ~isreal(arg) || fix(arg)~=arg || arg<=3 ) ) error( 'pwelch: arg %d (window) must be integer >3', iarg+1 ); elseif ( is_win>1 && ( ~isreal(arg) || any(arg<0) ) ) error( 'pwelch: arg %d (window) vector must be real and >=0',iarg+1); end window = arg; is_sloppy = 0; % % -- "overlap" arg -- segment overlap elseif ( iarg == arg_posn(2) ) if (~isscalar(arg) || ~isreal(arg) || arg<0 || arg>max_overlap ) error( 'pwelch: arg %d (overlap) must be real from 0 to %f', ... iarg+1, max_overlap ); end overlap = arg; % % -- "Nfft" arg -- FFT length elseif ( iarg == arg_posn(3) ) if ( ~isscalar(arg) || ~isreal(arg) || fix(arg)~=arg || arg<0 ) error( 'pwelch: arg %d (Nfft) must be integer >=0', iarg+1 ); end Nfft = arg; % else error( 'pwelch: arg %d must be string', iarg+1 ); end end if ( conf>0 && (n_results && ~do_power ) ) error('pwelch: can give confidence interval for x power spectrum only' ); end % % end DECODE AND CHECK OPTIONAL ARGUMENTS. % % SETUP REMAINING PARAMETERS % default action is to calculate power spectrum only if ( ~n_results ) n_results = 1; do_power = 1; end need_Pxx = do_power || do_trans || do_coher; need_Pxy = do_cross || do_trans || do_coher; need_Pyy = do_coher || do_ypower; log_two = log(2); nearly_one = 0.99999999999; % % compatibility-options % provides exact compatibility with Matlab R11 or R12 % % Matlab R11 compatibility if ( compatib==2 ) if ( isempty(Nfft) ) Nfft = min( 256, x_len ); end if ( is_win > 1 ) seg_len = min( length(window), Nfft ); window = window(1:seg_len); else if ( is_win ) % window arg is scalar seg_len = window; else seg_len = Nfft; end % make Hann window (don't depend on sigproc) xx = seg_len - 1; window = 0.5 - 0.5 * cos( (2*pi/xx)*[0:xx].' ); end % % Matlab R12 compatibility elseif ( compatib==3 ) if ( is_win > 1 ) % window arg provides window function seg_len = length(window); else % window arg does not provide window function; use Hamming if ( is_win ) % window arg is scalar seg_len = window; else % window arg not available; use R12 default, 8 windows % ignore overlap arg; use overlap=50% -- only choice that makes sense % this is the magic formula for 8 segments with 50% overlap seg_len = fix( (x_len-3)*2/9 ); end % make Hamming window (don't depend on sigproc) xx = seg_len - 1; window = 0.54 - 0.46 * cos( (2*pi/xx)*[0:xx].' ); end if ( isempty(Nfft) ) Nfft = max( 256, 2^ceil(log(seg_len)*nearly_one/log_two) ); end % % Matlab R14 psd(spectrum.welch) defaults elseif ( compatib==4 ) if ( is_win > 1 ) % window arg provides window function seg_len = length(window); else % window arg does not provide window function; use Hamming if ( is_win ) % window arg is scalar seg_len = window; else % window arg not available; use default seg_len = 64 seg_len = 64; end % make Hamming window (don't depend on sigproc) xx = seg_len - 1; window = 0.54 - 0.46 * cos( (2*pi/xx)*[0:xx].' ); end % Now we know segment length, % so we can set default overlap as number of samples if ( ~isempty(overlap) ) overlap = fix(seg_len * overlap / 100 ); end if ( isempty(Nfft) ) Nfft = max( 256, 2^ceil(log(seg_len)*nearly_one/log_two) ); end % % default compatibility level else %if ( compatib==1 ) % calculate/adjust segment length, window function if ( is_win > 1 ) % window arg provides window function seg_len = length(window); else % window arg does not provide window function; use Hamming if ( is_win ) % window arg is scalar seg_len = window; else % window arg not available; use default length: % = sqrt(length(x)) rounded up to nearest integer power of 2 if ( isempty(overlap) ) overlap=0.5; end seg_len = 2 ^ ceil( log(sqrt(x_len/(1-overlap)))*nearly_one/log_two ); end % make Hamming window (don't depend on sigproc) xx = seg_len - 1; window = 0.54 - 0.46 * cos( (2*pi/xx)*[0:xx].' ); end % Now we know segment length, % so we can set default overlap as number of samples if ( ~isempty(overlap) ) overlap = fix(seg_len * overlap); end % % calculate FFT length if ( isempty(Nfft) ) Nfft = seg_len; end if ( is_sloppy ) Nfft = 2 ^ ceil( log(Nfft) * nearly_one / log_two ); end end % end of compatibility options % % minimum FFT length is seg_len Nfft = max( Nfft, seg_len ); % Mean square of window is required for normalising PSD amplitude. win_meansq = (window.' * window) / seg_len; % % Set default or check overlap. if ( isempty(overlap) ) overlap = fix(seg_len /2); elseif ( overlap >= seg_len ) error( 'pwelch: arg (overlap=%d) too big. Must be <length(window)=%d',... overlap, seg_len ); end % % Pad data with zeros if shorter than segment. This should not happen. if ( x_len < seg_len ) x = [x; zeros(seg_len-x_len,1)]; if ( arg2_is_y ) y = [y; zeros(seg_len-x_len,1)]; end x_len = seg_len; end % end SETUP REMAINING PARAMETERS % % % MAIN CALCULATIONS % Remove mean from the data if ( rm_mean == 3 ) n_ffts = max( 0, fix( (x_len-seg_len)/(seg_len-overlap) ) ) + 1; x_len = min( x_len, (seg_len-overlap)*(n_ffts-1)+seg_len ); if ( need_Pxx || need_Pxy ) x = x - sum( x(1:x_len) ) / x_len; end if ( arg2_is_y || need_Pxy) y = y - sum( y(1:x_len) ) / x_len; end end % % Calculate and accumulate periodograms % xx and yy are padded data segments % Pxx, Pyy, Pyy are periodogram sums, Vxx is for confidence interval xx = zeros(Nfft,1); yy = xx; Pxx = xx; Pxy = xx; Pyy = xx; if ( conf>0 ) Vxx = xx; else Vxx = []; end n_ffts = 0; for start_seg = [1:seg_len-overlap:x_len-seg_len+1] end_seg = start_seg+seg_len-1; % Don't truncate/remove the zero padding in xx and yy if ( need_Pxx || need_Pxy ) if ( rm_mean==1 ) % remove mean from segment xx(1:seg_len) = window .* ( ... x(start_seg:end_seg) - sum(x(start_seg:end_seg)) / seg_len); elseif ( rm_mean == 2 ) % remove linear trend from segment xx(1:seg_len) = window .* detrend( x(start_seg:end_seg) ); else % rm_mean==0 or 3 xx(1:seg_len) = window .* x(start_seg:end_seg); end fft_x = fft(xx); end if ( need_Pxy || need_Pyy ) if ( rm_mean==1 ) % remove mean from segment yy(1:seg_len) = window .* ( ... y(start_seg:end_seg) - sum(y(start_seg:end_seg)) / seg_len); elseif ( rm_mean == 2 ) % remove linear trend from segment yy(1:seg_len) = window .* detrend( y(start_seg:end_seg) ); else % rm_mean==0 or 3 yy(1:seg_len) = window .* y(start_seg:end_seg); end fft_y = fft(yy); end if ( need_Pxx ) % force Pxx to be real; pgram = periodogram pgram = real(fft_x .* conj(fft_x)); Pxx = Pxx + pgram; % sum of squared periodograms is required for confidence interval if ( conf>0 ) Vxx = Vxx + pgram .^2; end end if ( need_Pxy ) % Pxy (cross power spectrum) is complex. Do not force to be real. Pxy = Pxy + fft_y .* conj(fft_x); end if ( need_Pyy ) % force Pyy to be real Pyy = Pyy + real(fft_y .* conj(fft_y)); end n_ffts = n_ffts +1; end % % Calculate confidence interval % -- incorrectly assumes that the periodogram has Gaussian probability % distribution (actually, it has a single-sided (e.g. exponential) % distribution. % Sample variance of periodograms is (Vxx-Pxx.^2/n_ffts)/(n_ffts-1). % This method of calculating variance is more susceptible to round-off % error, but is quicker, and for double-precision arithmetic and the % inherently noisy periodogram (variance==mean^2), it should be OK. if ( conf>0 && need_Pxx ) if ( n_ffts<2 ) Vxx = zeros(Nfft,1); else % Should use student distribution here (for unknown variance), but tinv % is not a core Matlab function (is in statistics toolbox. Grrr) Vxx = (erfinv(conf)*sqrt(2*n_ffts/(n_ffts-1))) * sqrt(Vxx-Pxx.^2/n_ffts); end end % % Convert two-sided spectra to one-sided spectra (if range == 0). % For one-sided spectra, contributions from negative frequencies are added % to the positive side of the spectrum -- but not at zero or Nyquist % (half sampling) frequencies. This keeps power equal in time and spectral % domains, as required by Parseval theorem. % if ( range == 0 ) if ( ~ rem(Nfft,2) ) % one-sided, Nfft is even psd_len = Nfft/2+1; if ( need_Pxx ) Pxx = Pxx(1:psd_len) + [0; Pxx(Nfft:-1:psd_len+1); 0]; if ( conf>0 ) Vxx = Vxx(1:psd_len) + [0; Vxx(Nfft:-1:psd_len+1); 0]; end end if ( need_Pxy ) Pxy = Pxy(1:psd_len) + conj([0; Pxy(Nfft:-1:psd_len+1); 0]); end if ( need_Pyy ) Pyy = Pyy(1:psd_len) + [0; Pyy(Nfft:-1:psd_len+1); 0]; end else % one-sided, Nfft is odd psd_len = (Nfft+1)/2; if ( need_Pxx ) Pxx = Pxx(1:psd_len) + [0; Pxx(Nfft:-1:psd_len+1)]; if ( conf>0 ) Vxx = Vxx(1:psd_len) + [0; Vxx(Nfft:-1:psd_len+1)]; end end if ( need_Pxy ) Pxy = Pxy(1:psd_len) + conj([0; Pxy(Nfft:-1:psd_len+1)]); end if ( need_Pyy ) Pyy = Pyy(1:psd_len) + [0; Pyy(Nfft:-1:psd_len+1)]; end end else % two-sided (and shifted) psd_len = Nfft; end % end MAIN CALCULATIONS % % SCALING AND OUTPUT % Put all results in matrix, one row per spectrum % Pxx, Pxy, Pyy are sums of periodograms, so "n_ffts" % in the scale factor converts them into averages spectra = zeros(psd_len,n_results); spect_type = zeros(n_results,1); scale = n_ffts * seg_len * Fs * win_meansq; if ( do_power ) spectra(:,do_power) = Pxx / scale; spect_type(do_power) = 1; if ( conf>0 ) Vxx = [Pxx-Vxx Pxx+Vxx]/scale; end end if ( do_cross ) spectra(:,do_cross) = Pxy / scale; spect_type(do_cross) = 2; end if ( do_trans ) spectra(:,do_trans) = Pxy ./ Pxx; spect_type(do_trans) = 3; end if ( do_coher ) % force coherence to be real spectra(:,do_coher) = real(Pxy .* conj(Pxy)) ./ Pxx ./ Pyy; spect_type(do_coher) = 4; end if ( do_ypower ) spectra(:,do_ypower) = Pyy / scale; spect_type(do_ypower) = 5; end freq = [0:psd_len-1].' * ( Fs / Nfft ); % % range='shift': Shift zero-frequency to the middle if ( range == 2 ) len2 = fix((Nfft+1)/2); spectra = [ spectra(len2+1:Nfft,:); spectra(1:len2,:)]; freq = [ freq(len2+1:Nfft)-Fs; freq(1:len2)]; if ( conf>0 ) Vxx = [ Vxx(len2+1:Nfft,:); Vxx(1:len2,:)]; end end % % RETURN RESULTS or PLOT if ( nargout>=2 && conf>0 ) varargout{2} = Vxx; end if ( nargout>=(2+(conf>0)) ) % frequency is 2nd or 3rd return value, % depends on if 2nd is confidence interval varargout{2+(conf>0)} = freq; end if ( nargout>=1 ) varargout{1} = spectra; else % % Plot the spectra if there are no return variables. plot_title=['power spectrum x '; 'cross spectrum '; 'transfer function'; 'coherence '; 'power spectrum y ' ]; for ii = 1: n_results if ( conf>0 && spect_type(ii)==1 ) Vxxxx = Vxx; else Vxxxx = []; end if ( n_results > 1 ) figure(); end if ( plot_type == 1 ) plot(freq,[abs(spectra(:,ii)) Vxxxx]); elseif ( plot_type == 2 ) semilogx(freq,[abs(spectra(:,ii)) Vxxxx]); elseif ( plot_type == 3 ) semilogy(freq,[abs(spectra(:,ii)) Vxxxx]); elseif ( plot_type == 4 ) loglog(freq,[abs(spectra(:,ii)) Vxxxx]); elseif ( plot_type == 5 ) % db ylabel( 'amplitude (dB)' ); plot(freq,[10*log10(abs(spectra(:,ii))) 10*log10(abs(Vxxxx))]); end title( char(plot_title(spect_type(ii),:)) ); ylabel( 'amplitude' ); % Plot phase of cross spectrum and transfer function if ( spect_type(ii)==2 || spect_type(ii)==3 ) figure(); if ( plot_type==2 || plot_type==4 ) semilogx(freq,180/pi*angle(spectra(:,ii))); else plot(freq,180/pi*angle(spectra(:,ii))); end title( char(plot_title(spect_type(ii),:)) ); ylabel( 'phase' ); end end %for end end end %!demo %! fflush(stdout); %! rand('seed',2038014164); %! a = [ 1.0 -1.6216505 1.1102795 -0.4621741 0.2075552 -0.018756746 ]; %! white = rand(1,16384); %! signal = detrend(filter(0.70181,a,white)); %! % frequency shift by modulating with exp(j.omega.t) %! skewed = signal.*exp(2*pi*i*2/25*[1:16384]); %! Fs = 25; % sampling frequency %! hold off %! pwelch([]); %! pwelch(signal); %! disp('Default settings: Fs=1Hz, overlap=0.5, no padding' ) %! input('Onesided power spectral density (real data). Press ENTER', 's' ); %! hold on %! pwelch(skewed); %! disp('Frequency-shifted complex data. Twosided wrap-around spectrum.' ); %! input('Area is same as one-sided spectrum. Press ENTER', 's' ); %! pwelch(signal,'shift','semilogy'); %! input('Twosided, centred zero-frequency, lin-log plot. Press ENTER', 's' ); %! hold off %! figure(); %! pwelch(skewed,[],[],[],Fs,'shift','semilogy'); %! input('Actual Fs=25 Hz. Note change of scales. Press ENTER', 's' ); %! pwelch(skewed,[],[],[],Fs,0.95,'shift','semilogy'); %! input('Spectral density with 95% confidence interval. Press ENTER', 's' ); %! pwelch('R12+'); %! pwelch(signal,'squared'); %! input('Spectral density with Matlab R12 defaults. Press ENTER', 's' ); %! figure(); %! pwelch([]); %! pwelch(signal,3640,[],4096,2*pi,[],'no-strip'); %! input('Same spectrum with 95% confidence interval. Press ENTER', 's' ); %! figure(); %! pwelch(signal,[],[],[],2*pi,0.95,'no-strip'); %! input('95% confidence interval with native defaults. Press ENTER', 's' ); %! pwelch(signal,64,[],[],2*pi,'no-strip'); %! input('Only 32 frequency values in this spectrum. Press ENTER', 's' ); %! hold on %! pwelch(signal,64,[],256,2*pi,'no-strip'); %! input('4:1 zero padding gives artificial smoothing. Press ENTER', 's' ); %! figure(); %! pwelch('psd'); %! pwelch(signal,'squared'); %! input('Just like Matlab spectrum.welch(...) defaults. Press ENTER', 's' ); %! hold off %! pwelch({}); %! pwelch(white,signal,'trans','coher','short') %! input('Transfer and coherence functions. Press ENTER', 's' ); %! disp('Use "close all" to remove plotting windows.' );
github
lcnhappe/happe-master
filtfilt.m
.m
happe-master/Packages/eeglab14_0_0b/functions/octavefunc/signal/filtfilt.m
4,430
iso_8859_1
011f993ef23add46147387112d313898
% Copyright (C) 1999 Paul Kienzle % Copyright (C) 2007 Francesco Potortì % Copyright (C) 2008 Luca Citi % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % usage: y = filtfilt(b, a, x) % % Forward and reverse filter the signal. This corrects for phase % distortion introduced by a one-pass filter, though it does square the % magnitude response in the process. That's the theory at least. In % practice the phase correction is not perfect, and magnitude response % is distorted, particularly in the stop band. %% % Example % [b, a]=butter(3, 0.1); % 10 Hz low-pass filter % t = 0:0.01:1.0; % 1 second sample % x=sin(2*pi*t*2.3)+0.25*randn(size(t)); % 2.3 Hz sinusoid+noise % y = filtfilt(b,a,x); z = filter(b,a,x); % apply filter % plot(t,x,';data;',t,y,';filtfilt;',t,z,';filter;') % Changelog: % 2000 02 [email protected] % - pad with zeros to load up the state vector on filter reverse. % - add example % 2007 12 [email protected] % - use filtic to compute initial and final states % - work for multiple columns as well % 2008 12 [email protected] % - fixed instability issues with IIR filters and noisy inputs % - initial states computed according to Likhterov & Kopeika, 2003 % - use of a 'reflection method' to reduce end effects % - added some basic tests % TODO: (pkienzle) My version seems to have similar quality to matlab, % but both are pretty bad. They do remove gross lag errors, though. function y = filtfilt(b, a, x) checkfunctionmatlab('filtfilt', 'signal_toolbox') if (nargin ~= 3) usage('y=filtfilt(b,a,x)'); end rotflag = 0; if size(x,1) == 1 rotflag == 1; x = x'; % make it a column vector end; lx = size(x,1); a = a(:).'; b = b(:).'; lb = length(b); la = length(a); n = max(lb, la); lrefl = 3 * (n - 1); if la < n, a(n) = 0; end if lb < n, b(n) = 0; end % Compute a the initial state taking inspiration from % Likhterov & Kopeika, 2003. 'Hardware-efficient technique for % minimizing startup transients in Direct Form II digital filters' kdc = sum(b) / sum(a); if (abs(kdc) < inf) % neither NaN nor +/- Inf si = fliplr(cumsum(fliplr(b - kdc * a))); else si = zeros(size(a)); % fall back to zero initialization end si(1) = []; for (c = 1:size(x,2)) % filter all columns, one by one v = [2*x(1,c)-x((lrefl+1):-1:2,c); x(:,c); 2*x(end,c)-x((end-1):-1:end-lrefl,c)]; % a column vector % Do forward and reverse filtering v = filter(b,a,v,si*v(1)); % forward filter v = flipud(filter(b,a,flipud(v),si*v(end))); % reverse filter y(:,c) = v((lrefl+1):(lx+lrefl)); end if (rotflag) % x was a row vector y = y'; % rotate it back end %!error filtfilt (); %!error filtfilt (1, 2, 3, 4); %!test %! randn('state',0); %! r = randn(1,200); %! [b,a] = butter(10, [.2, .25]); %! yfb = filtfilt(b, a, r); %! assert (size(r), size(yfb)); %! assert (mean(abs(yfb)) < 1e3); %! assert (mean(abs(yfb)) < mean(abs(r))); %! ybf = fliplr(filtfilt(b, a, fliplr(r))); %! assert (mean(abs(ybf)) < 1e3); %! assert (mean(abs(ybf)) < mean(abs(r))); %!test %! randn('state',0); %! r = randn(1,1000); %! s = 10 * sin(pi * 4e-2 * (1:length(r))); %! [b,a] = cheby1(2, .5, [4e-4 8e-2]); %! y = filtfilt(b, a, r+s); %! assert (size(r), size(y)); %! assert (mean(abs(y)) < 1e3); %! assert (corrcoef(s(250:750), y(250:750)) > .95) %! [b,a] = butter(2, [4e-4 8e-2]); %! yb = filtfilt(b, a, r+s); %! assert (mean(abs(yb)) < 1e3); %! assert (corrcoef(y, yb) > .99) %!test %! randn('state',0); %! r = randn(1,1000); %! s = 10 * sin(pi * 4e-2 * (1:length(r))); %! [b,a] = butter(2, [4e-4 8e-2]); %! y = filtfilt(b, a, [r.' s.']); %! yr = filtfilt(b, a, r); %! ys = filtfilt(b, a, s); %! assert (y, [yr.' ys.']); %! y2 = filtfilt(b.', a.', [r.' s.']); %! assert (y, y2);
github
lcnhappe/happe-master
firls.m
.m
happe-master/Packages/eeglab14_0_0b/functions/octavefunc/signal/firls.m
4,078
utf_8
2ce6c9bc19a003aceeafdb9fae59f52e
% Copyright (C) 2006 Quentin Spencer % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % b = firls(N, F, A); % b = firls(N, F, A, W); % % FIR filter design using least squares method. Returns a length N+1 % linear phase filter such that the integral of the weighted mean % squared error in the specified bands is minimized. % % F specifies the frequencies of the band edges, normalized so that % half the sample frequency is equal to 1. Each band is specified by % two frequencies, to the vector must have an even length. % % A specifies the amplitude of the desired response at each band edge. % % W is an optional weighting function that contains one value for each % band that weights the mean squared error in that band. A must be the % same length as F, and W must be half the length of F. % The least squares optimization algorithm for computing FIR filter % coefficients is derived in detail in: % % I. Selesnick, 'Linear-Phase FIR Filter Design by Least Squares,' % http://cnx.org/content/m10577 function coef = firls(N, frequencies, pass, weight, str); checkfunctionmatlab('firls', 'signal_toolbox') if nargin<3 | nargin>6 usage(''); end if nargin==3 weight = ones(1, length(pass)/2); str = []; end if nargin==4 if ischar(weight) str = weight; weight = ones(size(pass)); else str = []; end end if length(frequencies) ~= length(pass) error('F and A must have equal lengths.'); end if 2 * length(weight) ~= length(pass) error('W must contain one weight per band.'); end if ischar(str) error('This feature is implemented yet'); else M = N/2; w = kron(weight(:), [-1; 1]); omega = frequencies * pi; i1 = 1:2:length(omega); i2 = 2:2:length(omega); % Generate the matrix Q % As illustrated in the above-cited reference, the matrix can be % expressed as the sum of a Hankel and Toeplitz matrix. A factor of % 1/2 has been dropped and the final filter coefficients multiplied % by 2 to compensate. warning off MATLAB:colon:nonIntegerIndex cos_ints = [omega; sin((1:N)' * omega)]; q = [1, 1./(1:N)]' .* (cos_ints * w); Q = toeplitz(q(1:M+1)) + hankel(q(1:M+1), q(M+1:end)); % The vector b is derived from solving the integral: % % _ w % / 2 % b = / W(w) D(w) cos(kw) dw % k / w % - 1 % % Since we assume that W(w) is constant over each band (if not, the % computation of Q above would be considerably more complex), but % D(w) is allowed to be a linear function, in general the function % W(w) D(w) is linear. The computations below are derived from the % fact that: % _ % / a ax + b % / (ax + b) cos(nx) dx = --- cos (nx) + ------ sin(nx) % / 2 n % - n % cos_ints2 = [omega(i1).^2 - omega(i2).^2; ... cos((1:M)' * omega(i2)) - cos((1:M)' * omega(i1))] ./ ... ([2, 1:M]' * (omega(i2) - omega(i1))); d = [-weight .* pass(i1); weight .* pass(i2)]; d = d(:); b = [1, 1./(1:M)]' .* ((kron(cos_ints2, [1, 1]) + cos_ints(1:M+1,:)) * d); % Having computed the components Q and b of the matrix equation, % solve for the filter coefficients. a = Q \ b; coef = [ a(end:-1:2); 2 * a(1); a(2:end) ]; warning on MATLAB:colon:nonIntegerIndex end
github
lcnhappe/happe-master
supergui.m
.m
happe-master/Packages/eeglab14_0_0b/functions/guifunc/supergui.m
21,074
utf_8
05da62a5889eab777551326464481bdf
% supergui() - a comprehensive gui automatic builder. This function help % to create GUI very fast without bothering about the % positions of the elements. After creating a geometry, % elements just place themselves into the predefined % locations. It is especially usefull for figure where you % intend to put text button and descriptions. % % Usage: % >> [handles, height, allhandles ] = ... % supergui( 'key1', 'val1', 'key2', 'val2', ... ); % % Inputs: % 'fig' - figure handler, if not given, create a new figure. % 'geom' - cell array of cell array of integer vector. Each cell % array defines the coordinate of a given input in the following % manner: { nb_row nb_col [x_topcorner y_topcorner] % [x_bottomcorner y_bottomcorner] }; % 'geomhoriz' - integer vector or cell array of numerical vectors describing the % geometry of the elements in the figure. % - if integer vector, vector length is the number of rows and vector % values are the number of 'uilist' elements in each row. % For example, [2 3 2] means that the % figures will have 3 rows, with 2 elements in the first % and last row and 3 elements in the second row. % - if cell array, each vector describes the relative widths % of items in each row. For example, { [2 8] [1 2 3] } which means % that figures will have 2 rows, the first one with 2 % elements of relative width 2 and 8 (20% and 80%). The % second row will have 3 elements of relative size 1, 2 % and 3 (1/6 2/6 and 3/6). % 'geomvert' - describting geometry for the rows. For instance % [1 2 1] means that the second row will be twice the height % of the other ones. If [], all the lines have the same height. % 'uilist' - list of uicontrol lists describing elements properties % { { ui1 }, { ui2 }... }, { 'uiX' } being GUI matlab % uicontrol arguments such as { 'style', 'radiobutton', % 'String', 'hello' }. See Matlab function uicontrol() for details. % 'borders' - [left right top bottom] GUI internal borders in normalized % units (0 to 1). Default values are % 'title' - optional figure title % 'userdata' - optional userdata input for the figure % 'inseth' - horizontal space between elements. Default is 2% % of window size. % 'insetv' - vertical space between elements. Default is 2% % of window height. % 'spacing' - [horiz vert] spacing in normalized units. Default % 'spacingtype' - ['absolute'|'proportional'] abolute means that the % spacing values are fixed. Proportional means that they % depend on the number of element in a line. % 'minwidth' - [integer] minimal width in pixels. Default is none. % 'screenpos' - [x y] position of the right top corner of the graphic % interface. 'center' may also be used to center the GUI on % the screen. % 'adjustbuttonwidth' - ['on'|'off'] adjust button width in the GUI. % Default is 'off'. % % Hint: % use 'print -mfile filemane' to save a matlab file of the figure. % % Output: % handles - all the handles of the elements (in the same order as the % uilist input). % height - adviced height for the figure (so the text look nice). % allhandles - all the handles in object format % % Example: % figure; % supergui( 'geomhoriz', { 1 1 }, 'uilist', { ... % { 'style', 'radiobutton', 'string', 'radio' }, ... % { 'style', 'pushbutton' , 'string', 'push' } } ); % % Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 2001- % % See also: eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [handlers, outheight, allhandlers] = supergui( varargin); % handlers cell format % allhandlers linear format handlers = {}; outheight = 0; if nargin < 2 help supergui; return; end; % get version and % set additional parameters % ------------------------- v = version; indDot = find(v == '.'); versnum = str2num(v(1:indDot(2)-1)); if versnum >= 7.14 addParamFont = { 'fontsize' 12 }; else addParamFont = { }; end; warning off MATLAB:hg:uicontrol:ParameterValuesMustBeValid % decoding input and backward compatibility % ----------------------------------------- if isstr(varargin{1}) options = varargin; else options = { 'fig' varargin{1} 'geomhoriz' varargin{2} ... 'geomvert' varargin{3} 'uilist' varargin(4:end) }; end g = finputcheck(options, { 'geomhoriz' 'cell' [] {}; 'fig' '' [] 0; 'geom' 'cell' [] {}; 'uilist' 'cell' [] {}; 'title' 'string' [] ''; 'userdata' '' [] []; 'adjustbuttonwidth' 'string' { 'on' 'off' } 'off'; 'geomvert' 'real' [] []; 'screenpos' { 'real' 'string' } [] []; 'horizontalalignment' 'string' { 'left','right','center' } 'left'; 'minwidth' 'real' [] 10; 'borders' 'real' [] [0.05 0.04 0.07 0.06]; 'spacing' 'real' [] [0.02 0.01]; 'inseth' 'real' [] 0.02; % x border absolute (5% of width) 'insetv' 'real' [] 0.02 }, 'supergui'); if isstr(g), error(g); end if ~isempty(g.geomhoriz) maxcount = sum(cellfun('length', g.geomhoriz)); if maxcount ~= length(g.uilist) warning('Wrong size for ''geomhoriz'' input'); end; if ~isempty(g.geomvert) if length(g.geomvert) ~= length(g.geomhoriz) warning('Wrong size for ''geomvert'' input'); end; end; g.insetv = g.insetv/length(g.geomhoriz); end; if ~isempty(g.geom) if length(g.geom) ~= length(g.uilist) warning('Wrong size for ''geom'' input'); end; maxcount = length(g.geom); end; % create new figure % ----------------- if g.fig == 0 g.fig = figure('visible','off'); end % converting the geometry formats % ------------------------------- if ~isempty(g.geomhoriz) & ~iscell( g.geomhoriz ) oldgeom = g.geomhoriz; g.geomhoriz = {}; for row = 1:length(oldgeom) g.geomhoriz = { g.geomhoriz{:} ones(1, oldgeom(row)) }; end; end if isempty(g.geomvert) g.geomvert = ones(1, length(g.geomhoriz)); end % converting to the new format % ---------------------------- if isempty(g.geom) count = 1; incy = 0; sumvert = sum(g.geomvert); maxhoriz = 1; for row = 1:length(g.geomhoriz) incx = 0; maxhoriz = max(maxhoriz, length(g.geomhoriz{row})); ratio = length(g.geomhoriz{row})/sum(g.geomhoriz{row}); for column = 1:length(g.geomhoriz{row}) g.geom{count} = { length(g.geomhoriz{row}) sumvert [incx incy] [g.geomhoriz{row}(column)*ratio g.geomvert(row)] }; incx = incx+g.geomhoriz{row}(column)*ratio; count = count+1; end; incy = incy+g.geomvert(row); end; g.borders(1:2) = g.borders(1:2)/maxhoriz*5; g.borders(3:4) = g.borders(3:4)/sumvert*10; g.spacing(1) = g.spacing(1)/maxhoriz*5; g.spacing(2) = g.spacing(2)/sumvert*10; end; % disp new geometry % ----------------- if 0 fprintf('{ ...\n'); for index = 1:length(g.geom) fprintf('{ %g %g [%g %g] [%g %g] } ...\n', g.geom{index}{1}, g.geom{index}{2}, ... g.geom{index}{3}(1), g.geom{index}{3}(2), g.geom{index}{4}(1), g.geom{index}{3}(2)); end; fprintf('};\n'); end; % get axis coordinates % -------------------- try set(g.fig, 'menubar', 'none', 'numbertitle', 'off'); catch end pos = [0 0 1 1]; % plot relative to current axes q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]; % allow to use normalized position [0 100] for x and y axis('off'); % creating guis % ------------- row = 1; % count the elements column = 1; % count the elements factmultx = 0; factmulty = 0; %zeros(length(g.geomhoriz)); for counter = 1:maxcount % init clear rowhandle; gm = g.geom{counter}; [posx posy width height] = getcoord(gm{1}, gm{2}, gm{3}, gm{4}, g.borders, g.spacing); try currentelem = g.uilist{ counter }; catch fprintf('Warning: not all boxes were filled\n'); return; end; if ~isempty(currentelem) % decode metadata % --------------- if strcmpi(currentelem{1}, 'link2lines'), currentelem(1) = []; hf1 = 3.6/2-0.3; hf2 = 0.7/2-0.3; allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ... [posx-width/2 posy+hf1*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', ''); allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ... [posx-width/2 posy+hf2*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', ''); allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ... [posx posy+hf2*height 0.005 (hf1-hf2+0.1)*height].*s+q, 'style', 'pushbutton', 'string', ''); allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ... [posx posy+(hf1+hf2)/2*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', ''); allhandlers{counter} = 0; else if strcmpi(currentelem{1}, 'width'), curwidth = currentelem{2}; currentelem(1:2) = []; else curwidth = 0; end; if strcmpi(currentelem{1}, 'align'), align = currentelem{2}; currentelem(1:2) = []; else align = 'right'; end; if strcmpi(currentelem{1}, 'stickto'), stickto = currentelem{2}; currentelem(1:2) = []; else stickto = 'none'; end; if strcmpi(currentelem{1}, 'vertshift'), currentelem(1) = []; addvert = -height/2; else addvert = 0; end; if strcmpi(currentelem{1}, 'vertexpand'), heightfactor = currentelem{2}; addvert = -(heightfactor-1)*height; currentelem(1:2) = []; else heightfactor = 1; end; % position adjustment depending on GUI type if isstr(currentelem{2}) && strcmpi(currentelem{2}, 'popupmenu') posy = posy-height/10; end; if isstr(currentelem{2}) && strcmpi(currentelem{2}, 'text') posy = posy+height/5; end; if strcmpi(currentelem{1}, 'function'), % property grid argument panel = uipanel('Title','','FontSize',12,'BackgroundColor','white','Position',[posx posy+addvert width height*heightfactor].*s+q); allhandlers{counter} = arg_guipanel(panel, currentelem{:}); else allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ... [posx posy+addvert width height*heightfactor].*s+q, currentelem{:}, addParamFont{:}); % this simply compute a factor so that all uicontrol will be visible % ------------------------------------------------------------------ style = get( allhandlers{counter}, 'style'); set( allhandlers{counter}, 'units', 'pixels'); curpos = get(allhandlers{counter}, 'position'); curext = get(allhandlers{counter}, 'extent'); if curwidth ~= 0 curwidth = curwidth/((factmultx-1)/1.85+1); if strcmpi(align, 'right') curpos(1) = curpos(1)+curpos(3)-curwidth; elseif strcmpi(align, 'center') curpos(1) = curpos(1)+curpos(3)/2-curwidth/2; end; set(allhandlers{counter}, 'position', [ curpos(1) curpos(2) curwidth curpos(4) ]); if strcmpi(stickto, 'on') set( allhandlers{counter-1}, 'units', 'pixels'); curpos2 = get(allhandlers{counter-1}, 'position'); set(allhandlers{counter-1}, 'position', [ curpos(1)-curpos2(3)-10 curpos2(2) curpos2(3) curpos2(4) ]); set( allhandlers{counter-1}, 'units', 'normalized'); end; curext(3) = curwidth; end; set( allhandlers{counter}, 'units', 'normalized'); end; if ~strcmp(style, 'edit') && (~strcmp(style, 'pushbutton') || strcmpi(g.adjustbuttonwidth, 'on')) %tmp = curext(3)/curpos(3); %if tmp > 3*factmultx && factmultx > 0, adsfasd; end; factmultx = max(factmultx, curext(3)/curpos(3)); if strcmp(style, 'pushbutton'), factmultx = factmultx*1.1; end; end; if ~strcmp(style, 'listbox') factmulty = max(factmulty, curext(4)/curpos(4)); end; % Uniformize button text aspect (first letter must be upercase) % ----------------------------- if strcmp(style, 'pushbutton') tmptext = get(allhandlers{counter}, 'string'); if length(tmptext) > 1 if upper(tmptext(1)) ~= tmptext(1) || lower(tmptext(2)) ~= tmptext(2) && ~strcmpi(tmptext, 'STATS') tmptext = lower(tmptext); try, tmptext(1) = upper(tmptext(1)); catch, end; end; end; set(allhandlers{counter}, 'string', tmptext); end; end; else allhandlers{counter} = 0; end; end; % adjustments % ----------- factmultx = factmultx*1.02;% because some text was still hidden %factmultx = factmultx*1.2; if factmultx < 0.1 factmultx = 0.1; end; % for MAC (magnify figures that have edit fields) % ------- warning off; try, comp = computer; if length(comp) > 2 && strcmpi(comp(1:3), 'MAC') factmulty = factmulty*1.5; elseif ~isunix % windows factmulty = factmulty*1.08; end; catch, end; factmulty = factmulty*0.9; % global shinking warning on; % scale and replace the figure in the screen % ----------------------------------------- pos = get(g.fig, 'position'); if factmulty > 1 pos(2) = max(0,pos(2)+pos(4)-pos(4)*factmulty); end; pos(1) = pos(1)+pos(3)*(1-factmultx)/2; pos(3) = max(pos(3)*factmultx, g.minwidth); pos(4) = pos(4)*factmulty; set(g.fig, 'position', pos); % vertical alignment to bottom for text (isnumeric by ishanlde was changed here) % --------------------------------------- for index = 1:length(allhandlers) if allhandlers{index} ~= 0 && ishandle(allhandlers{index}) if strcmp(get(allhandlers{index}, 'style'), 'text') set(allhandlers{index}, 'unit', 'pixel'); curpos = get(allhandlers{index}, 'position'); curext = get(allhandlers{index}, 'extent'); set(allhandlers{index}, 'position', [curpos(1) curpos(2)-4 curpos(3) curext(4)]); set(allhandlers{index}, 'unit', 'normalized'); end; end; end; % setting defaults colors %------------------------ try, icadefs; catch, GUIBACKCOLOR = [.8 .8 .8]; GUIPOPBUTTONCOLOR = [.8 .8 .8]; GUITEXTCOLOR = [0 0 0]; end; numobjects = cellfun(@ishandle, allhandlers); % (isnumeric by ishanlde was changed here) allhandlersnum = [ allhandlers{numobjects} ]; hh = findobj(allhandlersnum, 'parent', g.fig, 'style', 'text'); %set(hh, 'BackgroundColor', get(g.fig, 'color'), 'horizontalalignment', 'left'); set(hh, 'Backgroundcolor', GUIBACKCOLOR); set(hh, 'foregroundcolor', GUITEXTCOLOR); try set(g.fig, 'color',GUIBACKCOLOR ); catch end set(hh, 'horizontalalignment', g.horizontalalignment); hh = findobj(allhandlersnum, 'style', 'edit'); set(hh, 'BackgroundColor', [1 1 1]); %, 'horizontalalignment', 'right'); hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'pushbutton'); comp = computer; if length(comp) < 3 || ~strcmpi(comp(1:3), 'MAC') % this puts the wrong background on macs set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR); set(hh, 'foregroundcolor', GUITEXTCOLOR); end; hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'popupmenu'); set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR); set(hh, 'foregroundcolor', GUITEXTCOLOR); hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'checkbox'); set(hh, 'backgroundcolor', GUIBACKCOLOR); set(hh, 'foregroundcolor', GUITEXTCOLOR); hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'listbox'); set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR); set(hh, 'foregroundcolor', GUITEXTCOLOR); hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'radio'); set(hh, 'foregroundcolor', GUITEXTCOLOR); set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR); set(g.fig, 'visible', 'on'); % screen position % --------------- if ~isempty(g.screenpos) pos = get(g.fig, 'position'); if isnumeric(g.screenpos) set(g.fig, 'position', [ g.screenpos pos(3) pos(4)]); else screenSize = get(0, 'screensize'); pos(1) = (screenSize(3)-pos(3))/2; pos(2) = (screenSize(4)-pos(4))/2+pos(4); set(g.fig, 'position', pos); end; end; % set userdata and title % ---------------------- if ~isempty(g.userdata), set(g.fig, 'userdata', g.userdata); end; if ~isempty(g.title ), set(g.fig, 'name', g.title ); end; return; function [posx posy width height] = getcoord(geom1, geom2, coord1, sz, borders, spacing); coord2 = coord1+sz; borders(1:2) = borders(1:2)-spacing(1); borders(3:4) = borders(3:4)-spacing(2); % absolute positions posx = coord1(1)/geom1; posy = coord1(2)/geom2; posx2 = coord2(1)/geom1; posy2 = coord2(2)/geom2; width = posx2-posx; height = posy2-posy; % add spacing posx = posx+spacing(1)/2; width = max(posx2-posx-spacing(1), 0.001); height = max(posy2-posy-spacing(2), 0.001); posy = max(0, 1-posy2)+spacing(2)/2; % add border posx = posx*(1-borders(1)-borders(2))+borders(1); posy = posy*(1-borders(3)-borders(4))+borders(4); width = width*( 1-borders(1)-borders(2)); height = height*(1-borders(3)-borders(4)); function [posx posy width height] = getcoordold(geom1, geom2, coord1, sz); coord2 = coord1+sz; horiz_space = 0.05/geom1; vert_space = 0.05/geom2; horiz_border = min(0.1, 1/geom1)-horiz_space; vert_border = min(0.2, 1.5/geom2)-vert_space; % absolute positions posx = coord1(1)/geom1; posy = coord1(2)/geom2; posx2 = coord2(1)/geom1; posy2 = coord2(2)/geom2; width = posx2-posx; height = posy2-posy; % add spacing posx = posx+horiz_space/2; width = max(posx2-posx-horiz_space, 0.001); height = max(posy2-posy- vert_space, 0.001); posy = max(0, 1-posy2)+vert_space/2; % add border posx = posx*(1-horiz_border)+horiz_border/2; posy = posy*(1- vert_border)+vert_border/2; width = width*(1-horiz_border); height = height*(1-vert_border); % posx = coord1(1)/geom1+horiz_border*1/geom1/2; % posy = 1-(coord1(2)/geom2+vert_border*1/geom2/2)-1/geom2; % % posx2 = coord2(1)/geom1+horiz_border*1/geom1/2; % posy2 = 1-(coord2(2)/geom2+vert_border*1/geom2/2)-1/geom2; % % width = posx2-posx; % height = posy-posy2; %h = axes('unit', 'normalized', 'position', [ posx posy width height ]); %h = axes('unit', 'normalized', 'position', [ coordx/geom1 1-coordy/geom2-1/geom2 1/geom1 1/geom2 ]);
github
lcnhappe/happe-master
warndlg2.m
.m
happe-master/Packages/eeglab14_0_0b/functions/guifunc/warndlg2.m
1,031
utf_8
4d58c147c6515911a93ba2375203951d
% warndlg2() - same as warndlg for eeglab() % % Author: Arnaud Delorme, CNL / Salk Institute, 12 August 2002 % % See also: inputdlg2(), questdlg2() % Copyright (C) Arnaud Delorme, CNL / 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 warndlg2(Prompt, Title); if nargin <2 Title = 'Warning'; end; questdlg2(Prompt, Title, 'OK', 'OK');
github
lcnhappe/happe-master
pophelp.m
.m
happe-master/Packages/eeglab14_0_0b/functions/guifunc/pophelp.m
4,248
utf_8
bde4cd43c45ca121c2aa18c04083fe00
% pophelp() - Same as matlab HTHELP but does not crash under windows. % % Usage: >> pophelp( function ); % >> pophelp( function, nonmatlab ); % % Inputs: % function - string for a Matlab function name % (with or without the '.m' extension). % nonmatlab - [0|1], 1 the file is not a Matlab file % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function pophelp( funct, nonmatlab ); if nargin <1 help pophelp; return; end; if nargin <2 nonmatlab = 0; end; if exist('help2html') if length(funct) > 3 && strcmpi(funct(end-3:end), '.txt') web(funct); else pathHelpHTML = fileparts(which('help2html')); if ~isempty(findstr('NFT', pathHelpHTML)), rmpath(pathHelpHTML); end; text1 = help2html(funct); if length(funct) > 4 & strcmpi(funct(1:4), 'pop_') try, text2 = help2html(funct(5:end)); text1 = [text1 '<br><pre>___________________________________________________________________' 10 ... ' ' 10 ... ' The ''pop'' function above calls the eponymous Matlab function below' 10 ... ' and could use some of its optional parameters' 10 ... '___________________________________________________________________</pre><br><br>' text2 ]; catch, end; end; web([ 'text://' text1 ]); end; else if isempty(funct), return; end; doc1 = readfunc(funct, nonmatlab); if length(funct) > 4 & strcmpi(funct(1:4), 'pop_') try, doc2 = readfunc(funct(5:end), nonmatlab); doc1 = { doc1{:} ' _________________________________________________________________ ' ... ' ' ... ' The ''pop'' function above calls the eponymous Matlab function below, ' ... ' which may contain more information for some parameters. '... ' ' ... ' _________________________________________________________________ ' ... ' ' ... doc2{:} }; catch, end; end; textgui(doc1);1000 h = findobj('parent', gcf, 'style', 'slider'); try, icadefs; catch, GUIBUTTONCOLOR = [0.8 0.8 0.8]; GUITEXTCOLOR = 'k'; end; set(h, 'backgroundcolor', GUIBUTTONCOLOR); h = findobj('parent', gcf, 'style', 'pushbutton'); set(h, 'backgroundcolor', GUIBUTTONCOLOR); h = findobj('parent', gca); set(h, 'color', GUITEXTCOLOR); set(gcf, 'color', BACKCOLOR); end; return; function [doc] = readfunc(funct, nonmatlab) doc = {}; if iseeglabdeployed if isempty(find(funct == '.')), funct = [ funct '.m' ]; end; funct = fullfile(eeglabexefolder, 'help', funct); end; if nonmatlab fid = fopen( funct, 'r'); else if findstr( funct, '.m') fid = fopen( funct, 'r'); else fid = fopen( [funct '.m'], 'r'); end; end; if fid == -1 error('File not found'); end; sub = 1; try, if ~isunix, sub = 0; end; catch, end; if nonmatlab str = fgets( fid ); while ~feof(fid) str = deblank(str(1:end-sub)); doc = { doc{:} str(1:end) }; str = fgets( fid ); end; else str = fgets( fid ); while (str(1) == '%') str = deblank(str(1:end-sub)); doc = { doc{:} str(2:end) }; str = fgets( fid ); end; end; fclose(fid);
github
lcnhappe/happe-master
errordlg2.m
.m
happe-master/Packages/eeglab14_0_0b/functions/guifunc/errordlg2.m
1,467
utf_8
710e811cd40d8f506b5264089f50c95c
% errordlg2() - Makes a popup dialog box with the specified message and (optional) % title. % % Usage: % errordlg2(Prompt, Title); % % Example: % errordlg2('Explanation of error','title of error'); % % Input: % Prompt - A text string explaning why the user is seeing this error message. % Title _ A text string that appears in the title bar of the error message. % % Author: Arnaud Delorme, CNL / Salk Institute, 12 August 2002 % % See also: inputdlg2(), questdlg2() % Copyright (C) Arnaud Delorme, CNL / 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 errordlg2(Prompt, Title); if exist('beep') == 5 beep; else disp(char(7)); end; if nargin <2 Title = 'Error'; end; if ~ismatlab, error(Prompt); end; questdlg2(Prompt, Title, 'OK', 'OK');
github
lcnhappe/happe-master
questdlg2.m
.m
happe-master/Packages/eeglab14_0_0b/functions/guifunc/questdlg2.m
3,133
utf_8
d94e219e87da50c5af28fe1007906abc
% questdlg2() - questdlg function clone with coloring and help for % eeglab(). % % Usage: same as questdlg() % % Warning: % Case of button text and result might be changed by the function % % Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 11 August 2002 % % See also: inputdlg2(), errordlg2(), supergui(), inputgui() % Copyright (C) Arnaud Delorme, CNL / 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 [result] = questdlg2(Prompt,Title,varargin); result = ''; if nargin < 2 help questdlg2; return; end; if isempty(varargin) varargin = { 'Yes' 'No' 'Cancel' 'Yes' }; end; result = varargin{end}; if Prompt(end) == 10, Prompt(end) = []; end; if Prompt(end) == 10, Prompt(end) = []; end; if Prompt(end) == 10, Prompt(end) = []; end; if Prompt(end) == 10, Prompt(end) = []; end; fig = figure('visible', 'off'); set(gcf, 'name', Title); listui = {}; geometry = {}; if ~isempty(find(Prompt == 10)) indlines = find(Prompt == 10); if indlines(1) ~= 1, indlines = [ 0 indlines ]; end; if indlines(end) ~= length(Prompt), indlines = [ indlines length(Prompt)+1 ]; end; for index = 1:length(indlines)-1 geometry{index} = [1]; listui{index} = { 'Style', 'text', 'string' Prompt(indlines(index)+1:indlines(index+1)-1) }; end; else for index = 1:size(Prompt,1) geometry{index} = [1]; listui{index} = { 'Style', 'text', 'string' Prompt(index,:) }; end; end; listui{end+1} = {}; geometry = { geometry{:} 1 ones(1,length(varargin)-1) }; for index = 1:length(varargin)-1 % ignoring default val listui = {listui{:} { 'width',80,'align','center','Style', 'pushbutton', 'string', varargin{index}, 'callback', ['set(gcbf, ''userdata'', ''' varargin{index} ''');'] } }; if strcmp(varargin{index}, varargin{end}) listui{end}{end+1} = 'fontweight'; listui{end}{end+1} = 'bold'; end; end; %cr = length(find(Prompt == char(10)))+1; %if cr == 1 % cr = size(Prompt,1); %end; %cr = cr^(7/); %if cr >= 8, cr = cr-1; end; %if cr >= 4, cr = cr-1; end; %[tmp tmp2 allobj] = supergui( 'fig', fig, 'geomhoriz', geometry, 'geomvert', [cr 1 1], 'uilist', listui, ... [tmp tmp2 allobj] = supergui( 'fig', fig, 'geomhoriz', geometry, 'uilist', listui, ... 'borders', [0.02 0.015 0.08 0.06], 'spacing', [0 0], 'horizontalalignment', 'left', 'adjustbuttonwidth', 'on' ); waitfor( fig, 'userdata'); try, result = get(fig, 'userdata'); close(fig); drawnow; end;
github
lcnhappe/happe-master
listdlg2.m
.m
happe-master/Packages/eeglab14_0_0b/functions/guifunc/listdlg2.m
3,771
utf_8
a0820fcb823bcb9968afa377c5582498
% listdlg2() - listdlg function clone with coloring and help for % eeglab(). % % Usage: same as listdlg() % % Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 16 August 2002 % % See also: inputdlg2(), errordlg2(), supergui(), inputgui() % Copyright (C) Arnaud Delorme, CNL / 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 [vals, okornot, strval] = listdlg2(varargin); if nargin < 2 help listdlg2; return; end; for index = 1:length(varargin) if iscell(varargin{index}), varargin{index} = { varargin{index} }; end; if isstr(varargin{index}), varargin{index} = lower(varargin{index}); end; end; g = struct(varargin{:}); try, g.promptstring; catch, g.promptstring = ''; end; try, g.liststring; catch, error('''liststring'' must be defined'); end; try, g.selectionmode; catch, g.selectionmode = 'multiple'; end; try, g.listsize; catch, g.listsize = []; end; try, g.initialvalue; catch, g.initialvalue = []; end; try, g.name; catch, g.name = ''; end; fig = figure('visible', 'off'); set(gcf, 'name', g.name); if isstr(g.liststring) allstr = g.liststring; else allstr = ''; for index = 1:length(g.liststring) allstr = [ allstr '|' g.liststring{index} ]; end; allstr = allstr(2:end); end; geometry = {[1] [1 1]}; geomvert = [min(length(g.liststring), 10) 1]; if ~strcmpi(g.selectionmode, 'multiple') | ... (iscell(g.liststring) & length(g.liststring) == 1) | ... (isstr (g.liststring) & size (g.liststring,1) == 1 & isempty(find(g.liststring == '|'))) if isempty(g.initialvalue), g.initialvalue = 1; end; minval = 1; maxval = 1; else minval = 0; maxval = 2; end; listui = {{ 'Style', 'listbox', 'tag', 'listboxvals', 'string', allstr, 'max', maxval, 'min', minval } ... { 'Style', 'pushbutton', 'string', 'Cancel', 'callback', ['set(gcbf, ''userdata'', ''cancel'');'] } ... { 'Style', 'pushbutton', 'string', 'Ok' , 'callback', ['set(gcbf, ''userdata'', ''ok'');'] } }; if ~isempty(g.promptstring) geometry = {[1] geometry{:}}; geomvert = [1 geomvert]; listui = { { 'Style', 'text', 'string', g.promptstring } listui{:}}; end; [tmp tmp2 allobj] = supergui( fig, geometry, geomvert, listui{:} ); % assign value to listbox % must be done after creating it % ------------------------------ lstbox = findobj(fig, 'tag', 'listboxvals'); set(lstbox, 'value', g.initialvalue); if ~isempty(g.listsize) pos = get(gcf, 'position'); set(gcf, 'position', [ pos(1:2) g.listsize]); end; h = findobj( 'parent', fig, 'tag', 'listboxvals'); okornot = 0; strval = ''; vals = []; figure(fig); drawnow; waitfor( fig, 'userdata'); try, vals = get(h, 'value'); strval = ''; if iscell(g.liststring) for index = vals strval = [ strval ' ' g.liststring{index} ]; end; else for index = vals strval = [ strval ' ' g.liststring(index,:) ]; end; end; strval = strval(2:end); if strcmp(get(fig, 'userdata'), 'cancel') okornot = 0; else okornot = 1; end; close(fig); drawnow; end;
github
lcnhappe/happe-master
finputcheck.m
.m
happe-master/Packages/eeglab14_0_0b/functions/guifunc/finputcheck.m
9,133
utf_8
fe838fecdd60e76a4006a13c7c1b20e4
% finputcheck() - check Matlab function {'key','value'} input argument pairs % % Usage: >> result = finputcheck( varargin, fieldlist ); % >> [result varargin] = finputcheck( varargin, fieldlist, ... % callingfunc, mode, verbose ); % Input: % varargin - Cell array 'varargin' argument from a function call using 'key', % 'value' argument pairs. See Matlab function 'varargin'. % May also be a structure such as struct(varargin{:}) % fieldlist - A 4-column cell array, one row per 'key'. The first % column contains the key string, the second its type(s), % the third the accepted value range, and the fourth the % default value. Allowed types are 'boolean', 'integer', % 'real', 'string', 'cell' or 'struct'. For example, % {'key1' 'string' { 'string1' 'string2' } 'defaultval_key1'} % {'key2' {'real' 'integer'} { minint maxint } 'defaultval_key2'} % callingfunc - Calling function name for error messages. {default: none}. % mode - ['ignore'|'error'] ignore keywords that are either not specified % in the fieldlist cell array or generate an error. % {default: 'error'}. % verbose - ['verbose', 'quiet'] print information. Default: 'verbose'. % % Outputs: % result - If no error, structure with 'key' as fields and 'value' as % content. If error this output contain the string error. % varargin - residual varagin containing unrecognized input arguments. % Requires mode 'ignore' above. % % Note: In case of error, a string is returned containing the error message % instead of a structure. % % Example (insert the following at the beginning of your function): % result = finputcheck(varargin, ... % { 'title' 'string' [] ''; ... % 'percent' 'real' [0 1] 1 ; ... % 'elecamp' 'integer' [1:10] [] }); % if isstr(result) % error(result); % end % % Note: % The 'title' argument should be a string. {no default value} % The 'percent' argument should be a real number between 0 and 1. {default: 1} % The 'elecamp' argument should be an integer between 1 and 10 (inclusive). % % Now 'g.title' will contain the title arg (if any, else the default ''), etc. % % Author: Arnaud Delorme, CNL / Salk Institute, 10 July 2002 % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 10 July 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 [g, varargnew] = finputcheck( vararg, fieldlist, callfunc, mode, verbose ) if nargin < 2 help finputcheck; return; end; if nargin < 3 callfunc = ''; else callfunc = [callfunc ' ' ]; end; if nargin < 4 mode = 'do not ignore'; end; if nargin < 5 verbose = 'verbose'; end; NAME = 1; TYPE = 2; VALS = 3; DEF = 4; SIZE = 5; varargnew = {}; % create structure % ---------------- if ~isempty(vararg) if isstruct(vararg) g = vararg; else for index=1:length(vararg) if iscell(vararg{index}) vararg{index} = {vararg{index}}; end; end; try g = struct(vararg{:}); catch vararg = removedup(vararg, verbose); try g = struct(vararg{:}); catch g = [ callfunc 'error: bad ''key'', ''val'' sequence' ]; return; end; end; end; else g = []; end; for index = 1:size(fieldlist,NAME) % check if present % ---------------- if ~isfield(g, fieldlist{index, NAME}) g = setfield( g, fieldlist{index, NAME}, fieldlist{index, DEF}); end; tmpval = getfield( g, {1}, fieldlist{index, NAME}); % check type % ---------- if ~iscell( fieldlist{index, TYPE} ) res = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}, ... fieldlist{index, VALS}, tmpval, callfunc ); if isstr(res), g = res; return; end; else testres = 0; tmplist = fieldlist; for it = 1:length( fieldlist{index, TYPE} ) if ~iscell(fieldlist{index, VALS}) res{it} = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}{it}, ... fieldlist{index, VALS}, tmpval, callfunc ); else res{it} = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}{it}, ... fieldlist{index, VALS}{it}, tmpval, callfunc ); end; if ~isstr(res{it}), testres = 1; end; end; if testres == 0, g = res{1}; for tmpi = 2:length(res) g = [ g 10 'or ' res{tmpi} ]; end; return; end; end; end; % check if fields are defined % --------------------------- allfields = fieldnames(g); for index=1:length(allfields) if isempty(strmatch(allfields{index}, fieldlist(:, 1)', 'exact')) if ~strcmpi(mode, 'ignore') g = [ callfunc 'error: undefined argument ''' allfields{index} '''']; return; end; varargnew{end+1} = allfields{index}; varargnew{end+1} = getfield(g, {1}, allfields{index}); end; end; function g = fieldtest( fieldname, fieldtype, fieldval, tmpval, callfunc ); NAME = 1; TYPE = 2; VALS = 3; DEF = 4; SIZE = 5; g = []; switch fieldtype case { 'integer' 'real' 'boolean' 'float' }, if ~isnumeric(tmpval) && ~islogical(tmpval) g = [ callfunc 'error: argument ''' fieldname ''' must be numeric' ]; return; end; if strcmpi(fieldtype, 'boolean') if tmpval ~=0 && tmpval ~= 1 g = [ callfunc 'error: argument ''' fieldname ''' must be 0 or 1' ]; return; end; else if strcmpi(fieldtype, 'integer') if ~isempty(fieldval) if (any(isnan(tmpval(:))) && ~any(isnan(fieldval))) ... && (~ismember(tmpval, fieldval)) g = [ callfunc 'error: wrong value for argument ''' fieldname '''' ]; return; end; end; else % real or float if ~isempty(fieldval) && ~isempty(tmpval) if any(tmpval < fieldval(1)) || any(tmpval > fieldval(2)) g = [ callfunc 'error: value out of range for argument ''' fieldname '''' ]; return; end; end; end; end; case 'string' if ~isstr(tmpval) g = [ callfunc 'error: argument ''' fieldname ''' must be a string' ]; return; end; if ~isempty(fieldval) if isempty(strmatch(lower(tmpval), lower(fieldval), 'exact')) g = [ callfunc 'error: wrong value for argument ''' fieldname '''' ]; return; end; end; case 'cell' if ~iscell(tmpval) g = [ callfunc 'error: argument ''' fieldname ''' must be a cell array' ]; return; end; case 'struct' if ~isstruct(tmpval) g = [ callfunc 'error: argument ''' fieldname ''' must be a structure' ]; return; end; case 'function_handle' if ~isa(tmpval, 'function_handle') g = [ callfunc 'error: argument ''' fieldname ''' must be a function handle' ]; return; end; case ''; otherwise, error([ 'finputcheck error: unrecognized type ''' fieldname '''' ]); end; % remove duplicates in the list of parameters % ------------------------------------------- function cella = removedup(cella, verbose) % make sure if all the values passed to unique() are strings, if not, exist %try [tmp indices] = unique_bc(cella(1:2:end)); if length(tmp) ~= length(cella)/2 myfprintf(verbose,'Note: duplicate ''key'', ''val'' parameter(s), keeping the last one(s)\n'); end; cella = cella(sort(union(indices*2-1, indices*2))); %catch % some elements of cella were not string % error('some ''key'' values are not string.'); %end; function myfprintf(verbose, varargin) if strcmpi(verbose, 'verbose') fprintf(varargin{:}); end;
github
lcnhappe/happe-master
inputdlg2.m
.m
happe-master/Packages/eeglab14_0_0b/functions/guifunc/inputdlg2.m
2,497
utf_8
f37d94d5821140270d3242f0d5d06659
% inputdlg2() - inputdlg function clone with coloring and help for % eeglab(). % % Usage: % >> Answer = inputdlg2(Prompt,Title,LineNo,DefAns,funcname); % % Inputs: % Same as inputdlg. Using the optional additionnal funcname parameter % the function will create a help button. The help message will be % displayed using the pophelp() function. % % Output: % Same as inputdlg % % Note: The advantage of this function is that the color of the window % can be changed and that it displays an help button. Edit % supergui to change window options. Also the parameter LineNo % can only be one. % % Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 11 August 2002 % % See also: supergui(), inputgui() % Copyright (C) Arnaud Delorme, CNL / 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 [result] = inputdlg2(Prompt,Title,LineNo,DefAns,funcname); if nargin < 4 help inputdlg2; return; end; if nargin < 5 funcname = ''; end; if length(Prompt) ~= length(DefAns) error('inputdlg2: prompt and default answer cell array must have the smae size'); end; geometry = {}; listgui = {}; % determine if vertical or horizontal % ----------------------------------- geomvert = []; for index = 1:length(Prompt) geomvert = [geomvert size(Prompt{index},1) 1]; % default is vertical geometry end; if all(geomvert == 1) & length(Prompt) > 1 geomvert = []; % horizontal end; for index = 1:length(Prompt) if ~isempty(geomvert) % vertical geometry = { geometry{:} [ 1] [1 ]}; else geometry = { geometry{:} [ 1 0.6 ]}; end; listgui = { listgui{:} { 'Style', 'text', 'string', Prompt{index}} ... { 'Style', 'edit', 'string', DefAns{index} } }; end; result = inputgui(geometry, listgui, ['pophelp(''' funcname ''');'], Title, [], 'normal', geomvert);
github
lcnhappe/happe-master
inputgui.m
.m
happe-master/Packages/eeglab14_0_0b/functions/guifunc/inputgui.m
13,049
utf_8
4d1fcb532034d20d2ab20e9c28f5da11
% inputgui() - A comprehensive gui automatic builder. This function helps % to create GUI very quickly without bothering about the % positions of the elements. After creating a geometry, % elements just place themselves in the predefined % locations. It is especially useful for figures in which % you intend to put text buttons and descriptions. % % Usage: % >> [ outparam ] = inputgui( 'key1', 'val1', 'key2', 'val2', ... ); % >> [ outparam userdat strhalt outstruct] = ... % inputgui( 'key1', 'val1', 'key2', 'val2', ... ); % % Inputs: % 'geom' - cell array of cell array of integer vector. Each cell % array defines the coordinate of a given input in the % following manner: { nb_row nb_col [x_topcorner y_topcorner] % [x_bottomcorner y_bottomcorner] }; % 'geometry' - cell array describing horizontal geometry. This corresponds % to the supergui function input 'geomhoriz' % 'geomvert' - vertical geometry argument, this argument is passed on to % the supergui function % 'uilist' - list of uicontrol lists describing elements properties % { { ui1 }, { ui2 }... }, { 'uiX' } being GUI matlab % uicontrol arguments such as { 'style', 'radiobutton', % 'String', 'hello' }. See Matlab function uicontrol() for details. % 'helpcom' - optional help command % 'helpbut' - text for help button % 'title' - optional figure title % 'userdata' - optional userdata input for the figure % 'mode' - ['normal'|'noclose'|'plot' fignumber]. Either wait for % user to press OK or CANCEL ('normal'), return without % closing window input ('noclose'), only draw the gui ('plot') % or process an existing window which number is given as % input (fignumber). Default is 'normal'. % 'eval' - [string] command to evaluate at the end of the creation % of the GUI but before waiting for user input. % 'screenpos' - see supergui.m help message. % 'skipline' - ['on'|'off'] skip a row before the "OK" and "Cancel" % button. Default is 'on'. % % Output: % outparam - list of outputs. The function scans all lines and % add up an output for each interactive uicontrol, i.e % edit box, radio button, checkbox and listbox. % userdat - 'userdata' value of the figure. % strhalt - the function returns when the 'userdata' field of the % button with the tag 'ok' is modified. This returns the % new value of this field. % outstruct - returns outputs as a structure (only tagged ui controls % are considered). The field name of the structure is % the tag of the ui and contain the ui value or string. % instruct - resturn inputs provided in the same format as 'outstruct' % This allow to compare in/outputs more easy. % % Note: the function also adds three buttons at the bottom of each % interactive windows: 'CANCEL', 'HELP' (if callback command % is provided) and 'OK'. % % Example: % res = inputgui('geometry', { 1 1 }, 'uilist', ... % { { 'style' 'text' 'string' 'Enter a value' } ... % { 'style' 'edit' 'string' '' } }); % % res = inputgui('geom', { {2 1 [0 0] [1 1]} {2 1 [1 0] [1 1]} }, 'uilist', ... % { { 'style' 'text' 'string' 'Enter a value' } ... % { 'style' 'edit' 'string' '' } }); % % Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 1 Feb 2002 % % See also: supergui(), eeglab() % Copyright (C) Arnaud Delorme, CNL/Salk Institute, 27 Jan 2002, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [result, userdat, strhalt, resstruct, instruct] = inputgui( varargin); if nargin < 2 help inputgui; return; end; % decoding input and backward compatibility % ----------------------------------------- if isstr(varargin{1}) options = varargin; else options = { 'geometry' 'uilist' 'helpcom' 'title' 'userdata' 'mode' 'geomvert' }; options = { options{1:length(varargin)}; varargin{:} }; options = options(:)'; end; % checking inputs % --------------- g = finputcheck(options, { 'geom' 'cell' [] {}; ... 'geometry' {'cell','integer'} [] []; ... 'uilist' 'cell' [] {}; ... 'helpcom' { 'string','cell' } { [] [] } ''; ... 'title' 'string' [] ''; ... 'eval' 'string' [] ''; ... 'helpbut' 'string' [] 'Help'; ... 'skipline' 'string' { 'on' 'off' } 'on'; ... 'addbuttons' 'string' { 'on' 'off' } 'on'; ... 'userdata' '' [] []; ... 'getresult' 'real' [] []; ... 'minwidth' 'real' [] 200; ... 'screenpos' '' [] []; ... 'mode' '' [] 'normal'; ... 'geomvert' 'real' [] [] ... }, 'inputgui'); if isstr(g), error(g); end; if isempty(g.getresult) if isstr(g.mode) fig = figure('visible', 'off'); set(fig, 'name', g.title); set(fig, 'userdata', g.userdata); if ~iscell( g.geometry ) oldgeom = g.geometry; g.geometry = {}; for row = 1:length(oldgeom) g.geometry = { g.geometry{:} ones(1, oldgeom(row)) }; end; end % skip a line if strcmpi(g.skipline, 'on'), g.geometry = { g.geometry{:} [1] }; if ~isempty(g.geom) for ind = 1:length(g.geom) g.geom{ind}{2} = g.geom{ind}{2}+1; % add one row end; g.geom = { g.geom{:} {1 g.geom{1}{2} [0 g.geom{1}{2}-2] [1 1] } }; end; g.uilist = { g.uilist{:}, {} }; end; % add buttons if strcmpi(g.addbuttons, 'on'), g.geometry = { g.geometry{:} [1 1 1 1] }; if ~isempty(g.geom) for ind = 1:length(g.geom) g.geom{ind}{2} = g.geom{ind}{2}+1; % add one row end; g.geom = { g.geom{:} ... {4 g.geom{1}{2} [0 g.geom{1}{2}-1] [1 1] }, ... {4 g.geom{1}{2} [1 g.geom{1}{2}-1] [1 1] }, ... {4 g.geom{1}{2} [2 g.geom{1}{2}-1] [1 1] }, ... {4 g.geom{1}{2} [3 g.geom{1}{2}-1] [1 1] } }; end; if ~isempty(g.helpcom) if ~iscell(g.helpcom) g.uilist = { g.uilist{:}, { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', g.helpbut, 'tag', 'help', 'callback', g.helpcom } {} }; else g.uilist = { g.uilist{:}, { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', 'Help gui', 'callback', g.helpcom{1} } }; g.uilist = { g.uilist{:}, { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', 'More help', 'callback', g.helpcom{2} } }; end; else g.uilist = { g.uilist{:}, {} {} }; end; g.uilist = { g.uilist{:}, { 'width' 80 'align' 'right' 'Style', 'pushbutton', 'string', 'Cancel', 'tag' 'cancel' 'callback', 'close gcbf' } }; g.uilist = { g.uilist{:}, { 'width' 80 'align' 'right' 'stickto' 'on' 'Style', 'pushbutton', 'tag', 'ok', 'string', 'OK', 'callback', 'set(gcbo, ''userdata'', ''retuninginputui'');' } }; end; % add the three buttons (CANCEL HELP OK) at the bottom of the GUI % --------------------------------------------------------------- if ~isempty(g.geom) [tmp tmp2 allobj] = supergui( 'fig', fig, 'minwidth', g.minwidth, 'geom', g.geom, 'uilist', g.uilist, 'screenpos', g.screenpos ); elseif isempty(g.geomvert) [tmp tmp2 allobj] = supergui( 'fig', fig, 'minwidth', g.minwidth, 'geomhoriz', g.geometry, 'uilist', g.uilist, 'screenpos', g.screenpos ); else if strcmpi(g.skipline, 'on'), g.geomvert = [g.geomvert(:)' 1]; end; if strcmpi(g.addbuttons, 'on'),g.geomvert = [g.geomvert(:)' 1]; end; [tmp tmp2 allobj] = supergui( 'fig', fig, 'minwidth', g.minwidth, 'geomhoriz', g.geometry, 'uilist', g.uilist, 'screenpos', g.screenpos, 'geomvert', g.geomvert(:)' ); end; else fig = g.mode; set(findobj('parent', fig, 'tag', 'ok'), 'userdata', []); allobj = findobj('parent',fig); allobj = allobj(end:-1:1); end; % evaluate command before waiting? % -------------------------------- if ~isempty(g.eval), eval(g.eval); end; instruct = outstruct(allobj); % Getting default values in the GUI. % create figure and wait for return % --------------------------------- if isstr(g.mode) & (strcmpi(g.mode, 'plot') | strcmpi(g.mode, 'return') ) if strcmpi(g.mode, 'plot') return; % only plot and returns end; else waitfor( findobj('parent', fig, 'tag', 'ok'), 'userdata'); end; else fig = g.getresult; allobj = findobj('parent',fig); allobj = allobj(end:-1:1); end; result = {}; userdat = []; strhalt = ''; resstruct = []; if ~(ishandle(fig)), return; end % Check if figure still exist % output parameters % ----------------- strhalt = get(findobj('parent', fig, 'tag', 'ok'), 'userdata'); [resstruct,result] = outstruct(allobj); % Output parameters userdat = get(fig, 'userdata'); % if nargout >= 4 % resstruct = myguihandles(fig, g); % end; if isempty(g.getresult) && isstr(g.mode) && ( strcmp(g.mode, 'normal') || strcmp(g.mode, 'return') ) close(fig); end; drawnow; % for windows % function for gui res (deprecated) % -------------------- % function g = myguihandles(fig, g) % h = findobj('parent', fig); % if ~isempty(get(h(index), 'tag')) % try, % switch get(h(index), 'style') % case 'edit', g = setfield(g, get(h(index), 'tag'), get(h(index), 'string')); % case { 'value' 'radio' 'checkbox' 'listbox' 'popupmenu' 'radiobutton' }, ... % g = setfield(g, get(h(index), 'tag'), get(h(index), 'value')); % end; % catch, end; % end; function [resstructout, resultout] = outstruct(allobj) counter = 1; resultout = {}; resstructout = []; for index=1:length(allobj) if isnumeric(allobj), currentobj = allobj(index); else currentobj = allobj{index}; end; if isnumeric(currentobj) | ~isprop(currentobj,'GetPropertySpecification') % To allow new object handles try, objstyle = get(currentobj, 'style'); switch lower( objstyle ) case { 'listbox', 'checkbox', 'radiobutton' 'popupmenu' 'radio' } resultout{counter} = get( currentobj, 'value'); if ~isempty(get(currentobj, 'tag')), resstructout = setfield(resstructout, get(currentobj, 'tag'), resultout{counter}); end; counter = counter+1; case 'edit' resultout{counter} = get( currentobj, 'string'); if ~isempty(get(currentobj, 'tag')), resstructout = setfield(resstructout, get(currentobj, 'tag'), resultout{counter}); end; counter = counter+1; end; catch, end; else ps = currentobj.GetPropertySpecification; resultout{counter} = arg_tovals(ps,false); count = 1; while isfield(resstructout, ['propgrid' int2str(count)]) count = count + 1; end; resstructout = setfield(resstructout, ['propgrid' int2str(count)], arg_tovals(ps,false)); end; end;
github
lcnhappe/happe-master
ft_channelselection.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/ft_channelselection.m
21,836
utf_8
28496cbe0aca921c174ce4c277f55e6a
function [channel] = ft_channelselection(desired, datachannel, senstype) % FT_CHANNELSELECTION makes a selection of EEG and/or MEG channel labels. % This function translates the user-specified list of channels into channel % labels as they occur in the data. This channel selection procedure can be % used throughout FieldTrip. % % Use as: % channel = ft_channelselection(desired, datachannel) % % You can specify a mixture of real channel labels and of special strings, % or index numbers that will be replaced by the corresponding channel % labels. Channels that are not present in the raw datafile are % automatically removed from the channel list. % % E.g. the input 'channel' can be: % 'all' is replaced by all channels in the datafile % 'gui' a graphical user interface will pop up to select the channels % 'C*' is replaced by all channels that match the wildcard, e.g. C1, C2, C3, ... % '*1' is replaced by all channels that match the wildcard, e.g. C1, P1, F1, ... % 'M*1' is replaced by all channels that match the wildcard, e.g. MEG0111, MEG0131, MEG0131, ... % 'meg' is replaced by all MEG channels (works for CTF, 4D, Neuromag and Yokogawa) % 'megref' is replaced by all MEG reference channels (works for CTF and 4D) % 'meggrad' is replaced by all MEG gradiometer channels (works for Yokogawa and Neuromag-306) % 'megmag' is replaced by all MEG magnetometer channels (works for Yokogawa and Neuromag-306) % 'eeg' is replaced by all recognized EEG channels (this is system dependent) % 'eeg1020' is replaced by 'Fp1', 'Fpz', 'Fp2', 'F7', 'F3', ... % 'eog' is replaced by all recognized EOG channels % 'ecg' is replaced by all recognized ECG channels % 'nirs' is replaced by all channels recognized as NIRS channels % 'emg' is replaced by all channels in the datafile starting with 'EMG' % 'lfp' is replaced by all channels in the datafile starting with 'lfp' % 'mua' is replaced by all channels in the datafile starting with 'mua' % 'spike' is replaced by all channels in the datafile starting with 'spike' % 10 is replaced by the 10th channel in the datafile % % Other channel groups are % 'EEG1010' with approximately 90 electrodes % 'EEG1005' with approximately 350 electrodes % 'EEGCHWILLA' for Dorothee Chwilla's electrode caps (used at the DCC) % 'EEGBHAM' for the 128 channel EEG system used in Birmingham % 'EEGREF' for mastoid and ear electrodes (M1, M2, LM, RM, A1, A2) % 'MZ' for MEG zenith % 'ML' for MEG left % 'MR' for MEG right % 'MLx', 'MRx' and 'MZx' with x=C,F,O,P,T for left/right central, frontal, occipital, parietal and temporal % % You can also exclude channels or channel groups using the following syntax % {'all', '-POz', '-Fp1', -EOG'} % % See also FT_PREPROCESSING, FT_SENSLABEL, FT_MULTIPLOTER, FT_MULTIPLOTTFR, % FT_SINGLEPLOTER, FT_SINGLEPLOTTFR % Note that the order of channels that is returned should correspond with % the order of the channels in the data. % Copyright (C) 2003-2014, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % this is to avoid a recursion loop persistent recursion if isempty(recursion) recursion = false; end if nargin<3 senstype = ft_senstype(datachannel); end if ~iscell(datachannel) if ischar(datachannel) datachannel = {datachannel}; else error('please specify the data channels as a cell-array'); end end if ~ischar(desired) && ~isnumeric(desired) && ~iscell(desired) error('please specify the desired channels as a cell-array or a string'); end % start with the list of desired channels, this will be pruned/expanded channel = desired; if length(datachannel)~=length(unique(datachannel)) warning('discarding non-unique channel names'); sel = false(size(datachannel)); for i=1:length(datachannel) sel(i) = sum(strcmp(datachannel, datachannel{i}))==1; end datachannel = datachannel(sel); end if any(size(channel) == 0) % there is nothing to do if it is empty return end if ~iscell(datachannel) % ensure that a single input argument like 'all' also works datachannel = {datachannel}; end if isnumeric(channel) % remove channels tha fall outside the range channel = channel(channel>=1 & channel<=numel(datachannel)); % change index into channelname channel = datachannel(channel); return end if ~iscell(channel) % ensure that a single input argument like 'all' also works % the case of a vector with channel indices has already been dealt with channel = {channel}; end % ensure that both inputs are column vectors channel = channel(:); datachannel = datachannel(:); % remove channels that occur more than once, this sorts the channels alphabetically [channel, indx] = unique(channel); % undo the sorting, make the order identical to that of the data channels [dum, indx] = sort(indx); channel = channel(indx); [dataindx, chanindx] = match_str(datachannel, channel); if length(chanindx)==length(channel) % there is a perfect match between the channels and the datachannels, only some reordering is needed channel = channel(chanindx); % no need to look at channel groups return end % define the known groups with channel labels labelall = datachannel; label1020 = ft_senslabel('eeg1020'); % use external helper function label1010 = ft_senslabel('eeg1010'); % use external helper function label1005 = ft_senslabel('eeg1005'); % use external helper function labelchwilla = {'Fz', 'Cz', 'Pz', 'F7', 'F8', 'LAT', 'RAT', 'LT', 'RT', 'LTP', 'RTP', 'OL', 'OR', 'FzA', 'Oz', 'F7A', 'F8A', 'F3A', 'F4A', 'F3', 'F4', 'P3', 'P4', 'T5', 'T6', 'P3P', 'P4P'}'; labelbham = {'P9', 'PPO9h', 'PO7', 'PPO5h', 'PPO3h', 'PO5h', 'POO9h', 'PO9', 'I1', 'OI1h', 'O1', 'POO1', 'PO3h', 'PPO1h', 'PPO2h', 'POz', 'Oz', 'Iz', 'I2', 'OI2h', 'O2', 'POO2', 'PO4h', 'PPO4h', 'PO6h', 'POO10h', 'PO10', 'PO8', 'PPO6h', 'PPO10h', 'P10', 'P8', 'TPP9h', 'TP7', 'TTP7h', 'CP5', 'TPP7h', 'P7', 'P5', 'CPP5h', 'CCP5h', 'CP3', 'P3', 'CPP3h', 'CCP3h', 'CP1', 'P1', 'Pz', 'CPP1h', 'CPz', 'CPP2h', 'P2', 'CPP4h', 'CP2', 'CCP4h', 'CP4', 'P4', 'P6', 'CPP6h', 'CCP6h', 'CP6', 'TPP8h', 'TP8', 'TPP10h', 'T7', 'FTT7h', 'FT7', 'FC5', 'FCC5h', 'C5', 'C3', 'FCC3h', 'FC3', 'FC1', 'C1', 'CCP1h', 'Cz', 'FCC1h', 'FCz', 'FFC1h', 'Fz', 'FFC2h', 'FC2', 'FCC2h', 'CCP2h', 'C2', 'C4', 'FCC4h', 'FC4', 'FC6', 'FCC6h', 'C6', 'TTP8h', 'T8', 'FTT8h', 'FT8', 'FT9', 'FFT9h', 'F7', 'FFT7h', 'FFC5h', 'F5', 'AFF7h', 'AF7', 'AF5h', 'AFF5h', 'F3', 'FFC3h', 'F1', 'AF3h', 'Fp1', 'Fpz', 'Fp2', 'AFz', 'AF4h', 'F2', 'FFC4h', 'F4', 'AFF6h', 'AF6h', 'AF8', 'AFF8h', 'F6', 'FFC6h', 'FFT8h', 'F8', 'FFT10h', 'FT10'}; labelref = {'M1', 'M2', 'LM', 'RM', 'A1', 'A2'}'; labeleog = datachannel(strncmp('EOG', datachannel, length('EOG'))); % anything that starts with EOG labeleog = [labeleog(:); {'HEOG', 'VEOG', 'VEOG-L', 'VEOG-R', 'hEOG', 'vEOG', 'Eye_Ver', 'Eye_Hor'}']; % or any of these labelecg = datachannel(strncmp('ECG', datachannel, length('ECG'))); labelemg = datachannel(strncmp('EMG', datachannel, length('EMG'))); labellfp = datachannel(strncmp('lfp', datachannel, length('lfp'))); labelmua = datachannel(strncmp('mua', datachannel, length('mua'))); labelspike = datachannel(strncmp('spike', datachannel, length('spike'))); labelnirs = datachannel(~cellfun(@isempty, regexp(datachannel, sprintf('%s%s', regexptranslate('wildcard','Rx*-Tx*[*]'), '$')))); % use regular expressions to deal with the wildcards labelreg = false(size(datachannel)); findreg = []; for i=1:length(channel) if length(channel{i}) < 1 continue; end if strcmp((channel{i}(1)), '-') % skip channels to be excluded continue; end rexp = sprintf('%s%s%s', '^', regexptranslate('wildcard',channel{i}), '$'); lreg = ~cellfun(@isempty, regexp(datachannel, rexp)); if any(lreg) labelreg = labelreg | lreg; findreg = [findreg; i]; end end if ~isempty(findreg) findreg = unique(findreg); % remove multiple occurances due to multiple wildcards labelreg = datachannel(labelreg); end % initialize all the system-specific variables to empty labelmeg = []; labelmeggrad = []; labelmegref = []; labelmegmag = []; labeleeg = []; switch senstype case {'yokogawa', 'yokogawa160', 'yokogawa160_planar', 'yokogawa64', 'yokogawa64_planar', 'yokogawa440', 'yokogawa440_planar'} % Yokogawa axial gradiometers channels start with AG, hardware planar gradiometer % channels start with PG, magnetometers start with M megax = strncmp('AG', datachannel, length('AG')); megpl = strncmp('PG', datachannel, length('PG')); megmag = strncmp('M', datachannel, length('M' )); megind = logical( megax + megpl + megmag); labelmeg = datachannel(megind); labelmegmag = datachannel(megmag); labelmeggrad = datachannel(megax | megpl); case {'ctf64'} labelml = datachannel(~cellfun(@isempty, regexp(datachannel, '^SL'))); % left MEG channels labelmr = datachannel(~cellfun(@isempty, regexp(datachannel, '^SR'))); % right MEG channels labelmeg = cat(1, labelml, labelmr); labelmegref = [datachannel(strncmp('B' , datachannel, 1)); datachannel(strncmp('G' , datachannel, 1)); datachannel(strncmp('P' , datachannel, 1)); datachannel(strncmp('Q' , datachannel, 1)); datachannel(strncmp('R' , datachannel, length('G' )))]; case {'ctf', 'ctf275', 'ctf151', 'ctf275_planar', 'ctf151_planar'} % all CTF MEG channels start with "M" % all CTF reference channels start with B, G, P, Q or R % all CTF EEG channels start with "EEG" labelmeg = datachannel(strncmp('M' , datachannel, length('M' ))); labelmegref = [datachannel(strncmp('B' , datachannel, 1)); datachannel(strncmp('G' , datachannel, 1)); datachannel(strncmp('P' , datachannel, 1)); datachannel(strncmp('Q' , datachannel, 1)); datachannel(strncmp('R' , datachannel, length('G' )))]; labeleeg = datachannel(strncmp('EEG', datachannel, length('EEG'))); % Not sure whether this should be here or outside the switch or % whether these specifications should be supported for systems % other than CTF. labelmz = datachannel(strncmp('MZ' , datachannel, length('MZ' ))); % central MEG channels labelml = datachannel(strncmp('ML' , datachannel, length('ML' ))); % left MEG channels labelmr = datachannel(strncmp('MR' , datachannel, length('MR' ))); % right MEG channels labelmlc = datachannel(strncmp('MLC', datachannel, length('MLC'))); labelmlf = datachannel(strncmp('MLF', datachannel, length('MLF'))); labelmlo = datachannel(strncmp('MLO', datachannel, length('MLO'))); labelmlp = datachannel(strncmp('MLP', datachannel, length('MLP'))); labelmlt = datachannel(strncmp('MLT', datachannel, length('MLT'))); labelmrc = datachannel(strncmp('MRC', datachannel, length('MRC'))); labelmrf = datachannel(strncmp('MRF', datachannel, length('MRF'))); labelmro = datachannel(strncmp('MRO', datachannel, length('MRO'))); labelmrp = datachannel(strncmp('MRP', datachannel, length('MRP'))); labelmrt = datachannel(strncmp('MRT', datachannel, length('MRT'))); labelmzc = datachannel(strncmp('MZC', datachannel, length('MZC'))); labelmzf = datachannel(strncmp('MZF', datachannel, length('MZF'))); labelmzo = datachannel(strncmp('MZO', datachannel, length('MZO'))); labelmzp = datachannel(strncmp('MZP', datachannel, length('MZP'))); case {'bti', 'bti248', 'bti248grad', 'bti148', 'bti248_planar', 'bti148_planar'} % all 4D-BTi MEG channels start with "A" % all 4D-BTi reference channels start with M or G labelmeg = datachannel(myregexp('^A[0-9]+$', datachannel)); labelmegref = [datachannel(myregexp('^M[CLR][xyz][aA]*$', datachannel)); datachannel(myregexp('^G[xyz][xyz]A$', datachannel)); datachannel(myregexp('^M[xyz][aA]*$', datachannel))]; labelmegrefa = datachannel(~cellfun(@isempty,strfind(datachannel, 'a'))); labelmegrefc = datachannel(strncmp('MC', datachannel, 2)); labelmegrefg = datachannel(myregexp('^G[xyz][xyz]A$', datachannel)); labelmegrefl = datachannel(strncmp('ML', datachannel, 2)); labelmegrefr = datachannel(strncmp('MR', datachannel, 2)); labelmegrefm = datachannel(myregexp('^M[xyz][aA]*$', datachannel)); case {'neuromag122' 'neuromag122alt'} % all neuromag MEG channels start with MEG % all neuromag EEG channels start with EEG labelmeg = datachannel(strncmp('MEG', datachannel, length('MEG'))); labeleeg = datachannel(strncmp('EEG', datachannel, length('EEG'))); case {'neuromag306' 'neuromag306alt'} % all neuromag MEG channels start with MEG % all neuromag EEG channels start with EEG % all neuromag-306 gradiometers follow pattern MEG*2,MEG*3 % all neuromag-306 magnetometers follow pattern MEG*1 labelmeg = datachannel(strncmp('MEG', datachannel, length('MEG'))); labeleeg = datachannel(strncmp('EEG', datachannel, length('EEG'))); labelmeggrad = labelmeg(~cellfun(@isempty, regexp(labelmeg, '^MEG.*[23]$'))); labelmegmag = labelmeg(~cellfun(@isempty, regexp(labelmeg, '^MEG.*1$'))); case {'ant128', 'biosemi64', 'biosemi128', 'biosemi256', 'egi32', 'egi64', 'egi128', 'egi256', 'eeg1020', 'eeg1010', 'eeg1005', 'ext1020'} % use an external helper function to define the list with EEG channel names labeleeg = ft_senslabel(ft_senstype(datachannel)); case {'itab153' 'itab28' 'itab28_old'} % all itab MEG channels start with MAG labelmeg = datachannel(strncmp('MAG', datachannel, length('MAG'))); end % switch ft_senstype % figure out if there are bad channels or channel groups that should be excluded findbadchannel = strncmp('-', channel, length('-')); % bad channels start with '-' badchannel = channel(findbadchannel); if ~isempty(badchannel) for i=1:length(badchannel) badchannel{i} = badchannel{i}(2:end); % remove the '-' from the channel label end badchannel = ft_channelselection(badchannel, datachannel); % support exclusion of channel groups end % determine if any of the known groups is mentioned in the channel list findall = find(strcmp(channel, 'all')); % findreg (for the wildcards) is dealt with in the channel group specification above findmeg = find(strcmpi(channel, 'MEG')); findemg = find(strcmpi(channel, 'EMG')); findecg = find(strcmpi(channel, 'ECG')); findeeg = find(strcmpi(channel, 'EEG')); findeeg1020 = find(strcmpi(channel, 'EEG1020')); findeeg1010 = find(strcmpi(channel, 'EEG1010')); findeeg1005 = find(strcmpi(channel, 'EEG1005')); findeegchwilla = find(strcmpi(channel, 'EEGCHWILLA')); findeegbham = find(strcmpi(channel, 'EEGBHAM')); findeegref = find(strcmpi(channel, 'EEGREF')); findmegref = find(strcmpi(channel, 'MEGREF')); findmeggrad = find(strcmpi(channel, 'MEGGRAD')); findmegmag = find(strcmpi(channel, 'MEGMAG')); findmegrefa = find(strcmpi(channel, 'MEGREFA')); findmegrefc = find(strcmpi(channel, 'MEGREFC')); findmegrefg = find(strcmpi(channel, 'MEGREFG')); findmegrefl = find(strcmpi(channel, 'MEGREFL')); findmegrefr = find(strcmpi(channel, 'MEGREFR')); findmegrefm = find(strcmpi(channel, 'MEGREFM')); findeog = find(strcmpi(channel, 'EOG')); findmz = find(strcmp(channel, 'MZ' )); findml = find(strcmp(channel, 'ML' )); findmr = find(strcmp(channel, 'MR' )); findmlc = find(strcmp(channel, 'MLC')); findmlf = find(strcmp(channel, 'MLF')); findmlo = find(strcmp(channel, 'MLO')); findmlp = find(strcmp(channel, 'MLP')); findmlt = find(strcmp(channel, 'MLT')); findmrc = find(strcmp(channel, 'MRC')); findmrf = find(strcmp(channel, 'MRF')); findmro = find(strcmp(channel, 'MRO')); findmrp = find(strcmp(channel, 'MRP')); findmrt = find(strcmp(channel, 'MRT')); findmzc = find(strcmp(channel, 'MZC')); findmzf = find(strcmp(channel, 'MZF')); findmzo = find(strcmp(channel, 'MZO')); findmzp = find(strcmp(channel, 'MZP')); findnirs = find(strcmpi(channel, 'NIRS')); findlfp = find(strcmpi(channel, 'lfp')); findmua = find(strcmpi(channel, 'mua')); findspike = find(strcmpi(channel, 'spike')); findgui = find(strcmpi(channel, 'gui')); % remove any occurences of groups in the channel list channel([ findall findreg findmeg findemg findecg findeeg findeeg1020 findeeg1010 findeeg1005 findeegchwilla findeegbham findeegref findmegref findmeggrad findmegmag findeog findmz findml findmr findmlc findmlf findmlo findmlp findmlt findmrc findmrf findmro findmrp findmrt findmzc findmzf findmzo findmzp findlfp findmua findspike findnirs findgui ]) = []; % add the full channel labels to the channel list if findall, channel = [channel; labelall]; end if findreg, channel = [channel; labelreg]; end if findmeg, channel = [channel; labelmeg]; end if findecg, channel = [channel; labelecg]; end if findemg, channel = [channel; labelemg]; end if findeeg, channel = [channel; labeleeg]; end if findeeg1020, channel = [channel; label1020]; end if findeeg1010, channel = [channel; label1010]; end if findeeg1005, channel = [channel; label1005]; end if findeegchwilla, channel = [channel; labelchwilla]; end if findeegbham, channel = [channel; labelbham]; end if findeegref, channel = [channel; labelref]; end if findmegref, channel = [channel; labelmegref]; end if findmeggrad, channel = [channel; labelmeggrad]; end if findmegmag, channel = [channel; labelmegmag]; end if findmegrefa, channel = [channel; labelmegrefa]; end if findmegrefc, channel = [channel; labelmegrefc]; end if findmegrefg, channel = [channel; labelmegrefg]; end if findmegrefl, channel = [channel; labelmegrefl]; end if findmegrefr, channel = [channel; labelmegrefr]; end if findmegrefm, channel = [channel; labelmegrefm]; end if findeog, channel = [channel; labeleog]; end if findmz , channel = [channel; labelmz ]; end if findml , channel = [channel; labelml ]; end if findmr , channel = [channel; labelmr ]; end if findmlc, channel = [channel; labelmlc]; end if findmlf, channel = [channel; labelmlf]; end if findmlo, channel = [channel; labelmlo]; end if findmlp, channel = [channel; labelmlp]; end if findmlt, channel = [channel; labelmlt]; end if findmrc, channel = [channel; labelmrc]; end if findmrf, channel = [channel; labelmrf]; end if findmro, channel = [channel; labelmro]; end if findmrp, channel = [channel; labelmrp]; end if findmrt, channel = [channel; labelmrt]; end if findmzc, channel = [channel; labelmzc]; end if findmzf, channel = [channel; labelmzf]; end if findmzo, channel = [channel; labelmzo]; end if findmzp, channel = [channel; labelmzp]; end if findlfp, channel = [channel; labellfp]; end if findmua, channel = [channel; labelmua]; end if findspike, channel = [channel; labelspike]; end if findnirs, channel = [channel; labelnirs]; end % remove channel labels that have been excluded by the user badindx = match_str(channel, badchannel); channel(badindx) = []; % remove channel labels that are not present in the data chanindx = match_str(channel, datachannel); channel = channel(chanindx); if findgui indx = select_channel_list(datachannel, match_str(datachannel, channel), 'Select channels'); channel = datachannel(indx); end % remove channels that occur more than once, this sorts the channels alphabetically channel = unique(channel); if isempty(channel) && ~recursion % try whether only lowercase channel labels makes a difference recursion = true; channel = ft_channelselection(desired, lower(datachannel)); recursion = false; % undo the conversion to lowercase, this sorts the channels alphabetically [c, ia, ib] = intersect(channel, lower(datachannel)); channel = datachannel(ib); end if isempty(channel) && ~recursion % try whether only uppercase channel labels makes a difference recursion = true; channel = ft_channelselection(desired, upper(datachannel)); recursion = false; % undo the conversion to uppercase, this sorts the channels alphabetically [c, ia, ib] = intersect(channel, lower(datachannel)); channel = datachannel(ib); end % undo the sorting, make the order identical to that of the data channels [tmp, indx] = match_str(datachannel, channel); channel = channel(indx); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function match = myregexp(pat, list) match = false(size(list)); for i=1:numel(list) match(i) = ~isempty(regexp(list{i}, pat, 'once')); end
github
lcnhappe/happe-master
ft_prepare_layout.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/ft_prepare_layout.m
41,723
utf_8
f9b5585b829110b574694613d0a47fab
function [layout, cfg] = ft_prepare_layout(cfg, data) % FT_PREPARE_LAYOUT loads or creates a 2-D layout of the channel locations. % This layout is required for plotting the topographical distribution of % the potential or field distribution, or for plotting timecourses in a % topographical arrangement. % % Use as % layout = ft_prepare_layout(cfg, data) % % There are several ways in which a 2-D layout can be made: it can be read % directly from a *.mat file containing a variable 'lay', it can be created % based on 3-D electrode or gradiometer positions in the configuration or % in the data, or it can be created based on the specification of an % electrode or gradiometer file. Layouts can also come from an ASCII *.lay % file, but this type of layout is no longer recommended. % % You can specify any one of the following configuration options % cfg.layout filename containg the layout (.mat or .lay file) % can also be a layout structure, which is simply % returned as-is (see below for details) % cfg.rotate number, rotation around the z-axis in degrees (default = [], which means automatic) % cfg.projection string, 2D projection method can be 'stereographic', 'orthographic', % 'polar', 'gnomic' or 'inverse' (default = 'polar') % cfg.elec structure with electrode definition, or % cfg.elecfile filename containing electrode definition % cfg.grad structure with gradiometer definition, or % cfg.gradfile filename containing gradiometer definition % cfg.opto structure with optode structure definition, or % cfg.optofile filename containing optode structure definition % cfg.output filename (ending in .mat or .lay) to which the layout % will be written (default = []) % cfg.montage 'no' or a montage structure (default = 'no') % cfg.image filename, use an image to construct a layout (e.g. useful for ECoG grids) % cfg.bw if an image is used and bw = 1 transforms the image in % black and white (default = 0, do not transform) % cfg.overlap string, how to deal with overlapping channels when % layout is constructed from a sensor configuration % structure (can be 'shift' (shift the positions in 2D % space to remove the overlap (default)), 'keep' (don't % shift, retain the overlap), 'no' (throw error when % overlap is present)) % cfg.skipscale 'yes' or 'no', whether the scale should be included in the layout or not (default = 'no') % cfg.skipcomnt 'yes' or 'no', whether the comment should be included in the layout or not (default = 'no') % % Alternatively the layout can be constructed from either % data.elec structure with electrode positions % data.grad structure with gradiometer definition % data.opto structure with optode structure definition % % Alternatively you can specify the following layouts which will be % generated for all channels present in the data. Note that these layouts % are suitable for multiplotting, but not for topoplotting. % cfg.layout = 'ordered' will give you a NxN ordered layout % cfg.layout = 'vertical' will give you a Nx1 ordered layout % cfg.layout = 'butterfly' will give you a layout with all channels on top of each other % cfg.layout = 'circular' will distribute the channels on a circle % % The output layout structure will contain the following fields % layout.label = Nx1 cell-array with channel labels % layout.pos = Nx2 matrix with channel positions % layout.width = Nx1 vector with the width of each box for multiplotting % layout.height = Nx1 matrix with the height of each box for multiplotting % layout.mask = optional cell-array with line segments that determine the area for topographic interpolation % layout.outline = optional cell-array with line segments that represent % the head, nose, ears, sulci or other anatomical features % % See also FT_TOPOPLOTER, FT_TOPOPLOTTFR, FT_MULTIPLOTER, FT_MULTIPLOTTFR, FT_PLOT_LAY % undocumented and non-recommended option (for SPM only) % cfg.style string, '2d' or '3d' (default = '2d') % Copyright (C) 2007-2013, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble loadvar data ft_preamble provenance data % the ft_abort variable is set to true or false in ft_preamble_init if ft_abort return end % the data can be passed as input argument or can be read from disk hasdata = exist('data', 'var'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % basic check/initialization of input arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~hasdata data = struct([]); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % set default configuration options %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% cfg.rotate = ft_getopt(cfg, 'rotate', []); % [] => rotation is determined based on the type of sensors cfg.style = ft_getopt(cfg, 'style', '2d'); cfg.projection = ft_getopt(cfg, 'projection', 'polar'); cfg.layout = ft_getopt(cfg, 'layout', []); cfg.grad = ft_getopt(cfg, 'grad', []); cfg.elec = ft_getopt(cfg, 'elec', []); cfg.opto = ft_getopt(cfg, 'opto', []); cfg.gradfile = ft_getopt(cfg, 'gradfile', []); cfg.elecfile = ft_getopt(cfg, 'elecfile', []); cfg.optofile = ft_getopt(cfg, 'optofile', []); cfg.output = ft_getopt(cfg, 'output', []); cfg.feedback = ft_getopt(cfg, 'feedback', 'no'); cfg.montage = ft_getopt(cfg, 'montage', 'no'); cfg.image = ft_getopt(cfg, 'image', []); cfg.mesh = ft_getopt(cfg, 'mesh', []); % experimental, should only work with meshes defined in 2D cfg.bw = ft_getopt(cfg, 'bw', 0); cfg.channel = ft_getopt(cfg, 'channel', 'all'); cfg.skipscale = ft_getopt(cfg, 'skipscale', 'no'); cfg.skipcomnt = ft_getopt(cfg, 'skipcomnt', 'no'); cfg.overlap = ft_getopt(cfg, 'overlap', 'shift'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % try to generate the layout structure %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% skipscale = strcmp(cfg.skipscale, 'yes'); % in general a scale is desired skipcomnt = strcmp(cfg.skipcomnt, 'yes'); % in general a comment desired if isa(cfg.layout, 'config') % convert the nested config-object back into a normal structure cfg.layout = struct(cfg.layout); end % ensure that there is a label field in the data, which is needed for % ordered/vertical/butterfly modes if hasdata && ~isfield(data, 'label') && isfield(data, 'labelcmb') data.label = unique(data.labelcmb(:)); end % check whether cfg.layout already contains a valid layout structure (this can % happen when higher level plotting functions are called with cfg.layout set to % a layout structure) if isstruct(cfg.layout) && isfield(cfg.layout, 'pos') && isfield(cfg.layout, 'label') && isfield(cfg.layout, 'width') && isfield(cfg.layout, 'height') layout = cfg.layout; elseif isstruct(cfg.layout) && isfield(cfg.layout, 'pos') && isfield(cfg.layout, 'label') && (~isfield(cfg.layout, 'width') || ~isfield(cfg.layout, 'height')) layout = cfg.layout; % add width and height for multiplotting d = dist(layout.pos'); nchans = length(layout.label); for i=1:nchans d(i,i) = inf; % exclude the diagonal end mindist = min(d(:)); layout.width = ones(nchans,1) * mindist * 0.8; layout.height = ones(nchans,1) * mindist * 0.6; elseif isequal(cfg.layout, 'circular') rho = ft_getopt(cfg, 'rho', []); if hasdata && ~isempty(data) % look at the data to determine the overlapping channels cfg.channel = ft_channelselection(cfg.channel, data.label); chanindx = match_str(data.label, cfg.channel); nchan = length(data.label(chanindx)); layout.label = data.label(chanindx); else assert(iscell(cfg.channel), 'cfg.channel should be a valid set of channels'); nchan = length(cfg.channel); layout.label = cfg.channel; end if isempty(rho) % do an equally spaced layout, starting at 12 o'clock, going clockwise rho = linspace(0,1,nchan+1); rho = 2.*pi.*rho(1:end-1); else if numel(rho) ~= nchan error('the number of elements in the polar angle vector should be equal to the number of channels'); end % convert to radians rho = 2.*pi.*rho./360; end x = sin(rho); y = cos(rho); layout.pos = [x(:) y(:)]; layout.width = ones(nchan,1) * 0.01; layout.height = ones(nchan,1) * 0.01; layout.mask = {}; layout.outline = {}; skipscale = true; % a scale is not desired skipcomnt = true; % a comment is initially not desired, or at least requires more thought elseif isequal(cfg.layout, 'butterfly') if hasdata && ~isempty(data) % look at the data to determine the overlapping channels cfg.channel = ft_channelselection(cfg.channel, data.label); chanindx = match_str(data.label, cfg.channel); nchan = length(data.label(chanindx)); layout.label = data.label(chanindx); else assert(iscell(cfg.channel), 'cfg.channel should be a valid set of channels'); nchan = length(cfg.channel); layout.label = cfg.channel; end layout.pos = zeros(nchan,2); % centered at (0,0) layout.width = ones(nchan,1) * 1.0; layout.height = ones(nchan,1) * 1.0; layout.mask = {}; layout.outline = {}; skipscale = true; % a scale is not desired skipcomnt = true; % a comment is initially not desired, or at least requires more thought elseif isequal(cfg.layout, 'vertical') if hasdata && ~isempty(data) % look at the data to determine the overlapping channels data = ft_checkdata(data); originalorder = cfg.channel; cfg.channel = ft_channelselection(cfg.channel, data.label); if iscell(originalorder) && length(originalorder)==length(cfg.channel) % try to keep the order identical to that specified in the configuration [sel1, sel2] = match_str(originalorder, cfg.channel); % re-order them according to the cfg specified by the user cfg.channel = cfg.channel(sel2); end assert(iscell(cfg.channel), 'cfg.channel should be a valid set of channels'); nchan = length(cfg.channel); layout.label = cfg.channel; else assert(iscell(cfg.channel), 'cfg.channel should be a valid set of channels'); nchan = length(cfg.channel); layout.label = cfg.channel; end for i=1:(nchan+2) x = 0.5; y = 1-i/(nchan+1+2); layout.pos (i,:) = [x y]; layout.width (i,1) = 0.9; layout.height(i,1) = 0.9 * 1/(nchan+1+2); if i==(nchan+1) layout.label{i} = 'SCALE'; elseif i==(nchan+2) layout.label{i} = 'COMNT'; end end layout.mask = {}; layout.outline = {}; elseif any(strcmp(cfg.layout, {'1column', '2column', '3column', '4column', '5column', '6column', '7column', '8column', '9column'})) % it can be 2column, 3column, etcetera % note that this code (in combination with the code further down) fails for 1column if hasdata && ~isempty(data) % look at the data to determine the overlapping channels data = ft_checkdata(data); originalorder = cfg.channel; cfg.channel = ft_channelselection(cfg.channel, data.label); if iscell(originalorder) && length(originalorder)==length(cfg.channel) % try to keep the order identical to that specified in the configuration [sel1, sel2] = match_str(originalorder, cfg.channel); % re-order them according to the cfg specified by the user cfg.channel = cfg.channel(sel2); end assert(iscell(cfg.channel), 'cfg.channel should be a valid set of channels'); nchan = length(cfg.channel); layout.label = cfg.channel; else assert(iscell(cfg.channel), 'cfg.channel should be a valid set of channels'); nchan = length(cfg.channel); layout.label = cfg.channel; end ncol = find(strcmp(cfg.layout, {'1column', '2column', '3column', '4column', '5column', '6column', '7column', '8column', '9column'})); nrow = ceil(nchan/ncol); k = 0; for i=1:ncol for j=1:nrow k = k+1; if k>nchan continue end x = i/ncol - 1/(ncol*2); y = 1-j/(nrow+1); layout.pos (k,:) = [x y]; layout.width (k,1) = 0.85/ncol; layout.height(k,1) = 0.9 * 1/(nrow+1); end end layout.mask = {}; layout.outline = {}; skipscale = true; % a scale is not desired skipcomnt = true; % a comment is initially not desired, or at least requires more thought elseif isequal(cfg.layout, 'ordered') if hasdata && ~isempty(data) % look at the data to determine the overlapping channels data = ft_checkdata(data); cfg.channel = ft_channelselection(cfg.channel, data.label); chanindx = match_str(data.label, cfg.channel); nchan = length(data.label(chanindx)); layout.label = data.label(chanindx); else assert(iscell(cfg.channel), 'cfg.channel should be a valid set of channels'); nchan = length(cfg.channel); layout.label = cfg.channel; end ncol = ceil(sqrt(nchan))+1; nrow = ceil(sqrt(nchan))+1; k = 0; for i=1:nrow for j=1:ncol k = k+1; if k<=nchan x = (j-1)/ncol; y = (nrow-i-1)/nrow; layout.pos(k,:) = [x y]; layout.width(k,1) = 0.8 * 1/ncol; layout.height(k,1) = 0.8 * 1/nrow; end end end layout.label{end+1} = 'SCALE'; layout.width(end+1) = 0.8 * 1/ncol; layout.height(end+1) = 0.8 * 1/nrow; x = (ncol-2)/ncol; y = 0/nrow; layout.pos(end+1,:) = [x y]; layout.label{end+1} = 'COMNT'; layout.width(end+1) = 0.8 * 1/ncol; layout.height(end+1) = 0.8 * 1/nrow; x = (ncol-1)/ncol; y = 0/nrow; layout.pos(end+1,:) = [x y]; % try to generate layout from other configuration options elseif ischar(cfg.layout) % layout file name specified if isempty(strfind(cfg.layout, '.')) cfg.layout = [cfg.layout '.mat']; if exist(cfg.layout, 'file') fprintf('layout file without .mat (or .lay) extension specified, appending .mat\n'); layout = ft_prepare_layout(cfg); return; else cfg.layout = [cfg.layout(1:end-3) 'lay']; layout = ft_prepare_layout(cfg); return; end elseif ft_filetype(cfg.layout, 'matlab') fprintf('reading layout from file %s\n', cfg.layout); if ~exist(cfg.layout, 'file') error('the specified layout file %s was not found', cfg.layout); end tmp = load(cfg.layout, 'lay*'); if isfield(tmp, 'layout') layout = tmp.layout; elseif isfield(tmp, 'lay') layout = tmp.lay; else error('mat file does not contain a layout'); end elseif ft_filetype(cfg.layout, 'layout') if exist(cfg.layout, 'file') fprintf('reading layout from file %s\n', cfg.layout); layout = readlay(cfg.layout); else ft_warning(sprintf('layout file %s was not found on your path, attempting to use a similarly named .mat file instead',cfg.layout)); cfg.layout = [cfg.layout(1:end-3) 'mat']; layout = ft_prepare_layout(cfg); return; end elseif ~ft_filetype(cfg.layout, 'layout') % assume that cfg.layout is an electrode file fprintf('creating layout from electrode file %s\n', cfg.layout); layout = sens2lay(ft_read_sens(cfg.layout), cfg.rotate, cfg.projection, cfg.style, cfg.overlap); end elseif ischar(cfg.elecfile) fprintf('creating layout from electrode file %s\n', cfg.elecfile); layout = sens2lay(ft_read_sens(cfg.elecfile), cfg.rotate, cfg.projection, cfg.style, cfg.overlap); elseif ~isempty(cfg.elec) && isstruct(cfg.elec) fprintf('creating layout from cfg.elec\n'); layout = sens2lay(cfg.elec, cfg.rotate, cfg.projection, cfg.style, cfg.overlap); elseif isfield(data, 'elec') && isstruct(data.elec) fprintf('creating layout from data.elec\n'); data = ft_checkdata(data); layout = sens2lay(data.elec, cfg.rotate, cfg.projection, cfg.style, cfg.overlap); elseif ischar(cfg.gradfile) fprintf('creating layout from gradiometer file %s\n', cfg.gradfile); layout = sens2lay(ft_read_sens(cfg.gradfile), cfg.rotate, cfg.projection, cfg.style, cfg.overlap); elseif ~isempty(cfg.grad) && isstruct(cfg.grad) fprintf('creating layout from cfg.grad\n'); layout = sens2lay(cfg.grad, cfg.rotate, cfg.projection, cfg.style, cfg.overlap); elseif isfield(data, 'grad') && isstruct(data.grad) fprintf('creating layout from data.grad\n'); data = ft_checkdata(data); layout = sens2lay(data.grad, cfg.rotate, cfg.projection, cfg.style, cfg.overlap); elseif ischar(cfg.optofile) fprintf('creating layout from optode file %s\n', cfg.optofile); opto = ft_read_sens(cfg.optofile); if (hasdata) layout = opto2lay(opto, data.label); else layout = opto2lay(opto, opto.label); end elseif ~isempty(cfg.opto) && isstruct(cfg.opto) fprintf('creating layout from cfg.opto\n'); opto = cfg.opto; if (hasdata) layout = opto2lay(opto, data.label); else layout = opto2lay(opto, opto.label); end; elseif isfield(data, 'opto') && isstruct(data.opto) fprintf('creating layout from data.opto\n'); opto = data.opto; if (hasdata) layout = opto2lay(opto, data.label); else layout = opto2lay(opto, opto.label); end; elseif (~isempty(cfg.image) || ~isempty(cfg.mesh)) && isempty(cfg.layout) % deal with image file if ~isempty(cfg.image) fprintf('reading background image from %s\n', cfg.image); [p,f,e] = fileparts(cfg.image); switch e case '.mat' tmp = load(cfg.image); fnames = fieldnames(tmp); if numel(fnames)~=1 error('there is not just a single variable in %s', cfg.image); else img = tmp.(fname{1}); end otherwise img = imread(cfg.image); end img = flipdim(img, 1); % in combination with "axis xy" figure bw = cfg.bw; if bw % convert to greyscale image img = mean(img, 3); imagesc(img); colormap gray else % plot as RGB image image(img); end elseif ~isempty(cfg.mesh) if isfield(cfg.mesh, 'sulc') ft_plot_mesh(cfg.mesh, 'edgecolor','none','vertexcolor',cfg.mesh.sulc);colormap gray; else ft_plot_mesh(cfg.mesh, 'edgecolor','none'); end end hold on axis equal axis off axis xy % get the electrode positions pos = zeros(0,2); electrodehelp = [ ... '-----------------------------------------------------\n' ... 'specify electrode locations\n' ... 'press the right mouse button to add another electrode\n' ... 'press backspace on the keyboard to remove the last electrode\n' ... 'press "q" on the keyboard to continue\n' ... ]; again = 1; while again fprintf(electrodehelp) disp(round(pos)); % values are integers/pixels try [x, y, k] = ginput(1); catch % this happens if the figure is closed return; end switch k case 1 pos = cat(1, pos, [x y]); % add it to the figure plot(x, y, 'b.'); plot(x, y, 'yo'); case 8 if size(pos,1)>0 % remove the last point pos = pos(1:end-1,:); % completely redraw the figure cla if ~isempty(cfg.image) h = image(img); else h = ft_plot_mesh(cfg.mesh,'edgecolor','none','vertexcolor',cfg.mesh.sulc); end hold on axis equal axis off plot(pos(:,1), pos(:,2), 'b.'); plot(pos(:,1), pos(:,2), 'yo'); end case 'q' again = 0; otherwise warning('invalid button (%d)', k); end end % get the mask outline polygon = {}; thispolygon = 1; polygon{thispolygon} = zeros(0,2); maskhelp = [ ... '------------------------------------------------------------------------\n' ... 'specify polygons for masking the topgraphic interpolation\n' ... 'press the right mouse button to add another point to the current polygon\n' ... 'press backspace on the keyboard to remove the last point\n' ... 'press "c" on the keyboard to close this polygon and start with another\n' ... 'press "q" on the keyboard to continue\n' ... ]; again = 1; while again fprintf(maskhelp); fprintf('\n'); for i=1:length(polygon) fprintf('polygon %d has %d points\n', i, size(polygon{i},1)); end try [x, y, k] = ginput(1); catch % this happens if the figure is closed return; end switch k case 1 polygon{thispolygon} = cat(1, polygon{thispolygon}, [x y]); % add the last line segment to the figure if size(polygon{thispolygon},1)>1 x = polygon{i}([end-1 end],1); y = polygon{i}([end-1 end],2); end plot(x, y, 'g.-'); case 8 % backspace if size(polygon{thispolygon},1)>0 % remove the last point polygon{thispolygon} = polygon{thispolygon}(1:end-1,:); % completely redraw the figure cla if ~isempty(cfg.image) h = image(img); else h = ft_plot_mesh(cfg.mesh,'edgecolor','none','vertexcolor',cfg.mesh.sulc); end hold on axis equal axis off % plot the electrode positions plot(pos(:,1), pos(:,2), 'b.'); plot(pos(:,1), pos(:,2), 'yo'); for i=1:length(polygon) x = polygon{i}(:,1); y = polygon{i}(:,2); if i~=thispolygon % close the polygon in the figure x(end) = x(1); y(end) = y(1); end plot(x, y, 'g.-'); end end case 'c' if size(polygon{thispolygon},1)>0 % close the polygon polygon{thispolygon}(end+1,:) = polygon{thispolygon}(1,:); % close the polygon in the figure x = polygon{i}([end-1 end],1); y = polygon{i}([end-1 end],2); plot(x, y, 'g.-'); % switch to the next polygon thispolygon = thispolygon + 1; polygon{thispolygon} = zeros(0,2); end case 'q' if size(polygon{thispolygon},1)>0 % close the polygon polygon{thispolygon}(end+1,:) = polygon{thispolygon}(1,:); % close the polygon in the figure x = polygon{i}([end-1 end],1); y = polygon{i}([end-1 end],2); plot(x, y, 'g.-'); end again = 0; otherwise warning('invalid button (%d)', k); end end % remember this set of polygons as the mask mask = polygon; % get the outline, e.g. head shape and sulci polygon = {}; thispolygon = 1; polygon{thispolygon} = zeros(0,2); maskhelp = [ ... '-----------------------------------------------------------------------------------\n' ... 'specify polygons for adding outlines (e.g. head shape and sulci) to the layout\n' ... 'press the right mouse button to add another point to the current polygon\n' ... 'press backspace on the keyboard to remove the last point\n' ... 'press "c" on the keyboard to close this polygon and start with another\n' ... 'press "n" on the keyboard to start with another without closing the current polygon\n' ... 'press "q" on the keyboard to continue\n' ... ]; again = 1; while again fprintf(maskhelp); fprintf('\n'); for i=1:length(polygon) fprintf('polygon %d has %d points\n', i, size(polygon{i},1)); end try [x, y, k] = ginput(1); catch % this happens if the figure is closed return; end switch k case 1 polygon{thispolygon} = cat(1, polygon{thispolygon}, [x y]); % add the last line segment to the figure if size(polygon{thispolygon},1)>1 x = polygon{i}([end-1 end],1); y = polygon{i}([end-1 end],2); end plot(x, y, 'm.-'); case 8 % backspace if size(polygon{thispolygon},1)>0 % remove the last point polygon{thispolygon} = polygon{thispolygon}(1:end-1,:); % completely redraw the figure cla if ~isempty(cfg.image) h = image(img); else h = ft_plot_mesh(cfg.mesh,'edgecolor','none','vertexcolor',cfg.mesh.sulc); end hold on axis equal axis off % plot the electrode positions plot(pos(:,1), pos(:,2), 'b.'); plot(pos(:,1), pos(:,2), 'yo'); for i=1:length(polygon) x = polygon{i}(:,1); y = polygon{i}(:,2); if i~=thispolygon % close the polygon in the figure x(end) = x(1); y(end) = y(1); end plot(x, y, 'm.-'); end end case 'c' if size(polygon{thispolygon},1)>0 x = polygon{thispolygon}(1,1); y = polygon{thispolygon}(1,2); polygon{thispolygon} = cat(1, polygon{thispolygon}, [x y]); % add the last line segment to the figure x = polygon{i}([end-1 end],1); y = polygon{i}([end-1 end],2); plot(x, y, 'm.-'); % switch to the next polygon thispolygon = thispolygon + 1; polygon{thispolygon} = zeros(0,2); end case 'n' if size(polygon{thispolygon},1)>0 % switch to the next polygon thispolygon = thispolygon + 1; polygon{thispolygon} = zeros(0,2); end case 'q' again = 0; otherwise warning('invalid button (%d)', k); end end % remember this set of polygons as the outline outline = polygon; % convert electrode positions into a layout structure layout.pos = pos; nchans = size(pos,1); for i=1:nchans layout.label{i,1} = sprintf('chan%03d', i); end % add width and height for multiplotting d = dist(pos'); for i=1:nchans d(i,i) = inf; % exclude the diagonal end mindist = min(d(:)); layout.width = ones(nchans,1) * mindist * 0.8; layout.height = ones(nchans,1) * mindist * 0.6; % add mask and outline polygons layout.mask = mask; layout.outline = outline; else error('no layout detected, please specify cfg.layout') end % FIXME there is a conflict between the use of cfg.style here and in topoplot if ~strcmp(cfg.style, '3d') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check whether outline and mask are available % if not, add default "circle with triangle" to resemble the head % in case of "circle with triangle", the electrode positions should also be % scaled %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isfield(layout, 'outline') || ~isfield(layout, 'mask') rmax = 0.5; l = 0:2*pi/100:2*pi; HeadX = cos(l).*rmax; HeadY = sin(l).*rmax; NoseX = [0.18*rmax 0 -0.18*rmax]; NoseY = [rmax-.004 rmax*1.15 rmax-.004]; EarX = [.497 .510 .518 .5299 .5419 .54 .547 .532 .510 .489]; EarY = [.0555 .0775 .0783 .0746 .0555 -.0055 -.0932 -.1313 -.1384 -.1199]; % Scale the electrode positions to fit within a unit circle, i.e. electrode radius = 0.45 ind_scale = strmatch('SCALE', layout.label); ind_comnt = strmatch('COMNT', layout.label); sel = setdiff(1:length(layout.label), [ind_scale ind_comnt]); % these are excluded for scaling x = layout.pos(sel,1); y = layout.pos(sel,2); xrange = range(x); yrange = range(y); % First scale the width and height of the box for multiplotting layout.width = layout.width./xrange; layout.height = layout.height./yrange; % Then shift and scale the electrode positions layout.pos(:,1) = 0.9*((layout.pos(:,1)-min(x))/xrange-0.5); layout.pos(:,2) = 0.9*((layout.pos(:,2)-min(y))/yrange-0.5); % Define the outline of the head, ears and nose layout.outline{1} = [HeadX(:) HeadY(:)]; layout.outline{2} = [NoseX(:) NoseY(:)]; layout.outline{3} = [ EarX(:) EarY(:)]; layout.outline{4} = [-EarX(:) EarY(:)]; % Define the anatomical mask based on a circular head layout.mask{1} = [HeadX(:) HeadY(:)]; end end % make the subset as specified in cfg.channel cfg.channel = ft_channelselection(cfg.channel, setdiff(layout.label, {'COMNT', 'SCALE'})); % COMNT and SCALE are not really channels chansel = match_str(layout.label, cat(1, cfg.channel(:), 'COMNT', 'SCALE')); % include COMNT and SCALE, keep all channels in the order of the layout % return the layout for the subset of channels layout.pos = layout.pos(chansel,:); layout.label = layout.label(chansel); if ~strcmp(cfg.style, '3d') % these don't exist for the 3D layout layout.width = layout.width(chansel); layout.height = layout.height(chansel); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % apply the montage, i.e. combine bipolar channels into a new representation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~strcmp(cfg.montage, 'no') Norg = length(cfg.montage.labelorg); Nnew = length(cfg.montage.labelnew); for i=1:Nnew cfg.montage.tra(i,:) = abs(cfg.montage.tra(i,:)); cfg.montage.tra(i,:) = cfg.montage.tra(i,:) ./ sum(cfg.montage.tra(i,:)); end % pretend it is a sensor structure, this achieves averaging after channel matching tmp.tra = layout.pos; tmp.label = layout.label; new = ft_apply_montage(tmp, cfg.montage); layout.pos = new.tra; layout.label = new.label; % do the same for the width and height tmp.tra = layout.width(:); new = ft_apply_montage(tmp, cfg.montage); layout.width = new.tra; tmp.tra = layout.height(:); new = ft_apply_montage(tmp, cfg.montage); layout.height = new.tra; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % add axes positions for comments and scale information if required %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~any(strcmp('COMNT', layout.label)) && strcmpi(cfg.style, '2d') && ~skipcomnt % add a placeholder for the comment in the upper left corner layout.label{end+1} = 'COMNT'; layout.width(end+1) = mean(layout.width); layout.height(end+1) = mean(layout.height); if ~isempty(layout.pos) XY = layout.pos; else XY = cat(1, layout.outline{:}, layout.mask{:}); end layout.pos(end+1,:) = [min(XY(:,1)) min(XY(:,2))]; elseif any(strcmp('COMNT', layout.label)) && skipcomnt % remove the scale entry sel = find(strcmp('COMNT', layout.label)); layout.label(sel) = []; layout.pos(sel,:) = []; layout.width(sel) = []; layout.height(sel) = []; end if ~any(strcmp('SCALE', layout.label)) && strcmpi(cfg.style, '2d') && ~skipscale % add a placeholder for the scale in the upper right corner layout.label{end+1} = 'SCALE'; layout.width(end+1) = mean(layout.width); layout.height(end+1) = mean(layout.height); if ~isempty(layout.pos) XY = layout.pos; else XY = cat(1, layout.outline{:}, layout.mask{:}); end layout.pos(end+1,:) = [max(XY(:,1)) min(XY(:,2))]; elseif any(strcmp('SCALE', layout.label)) && skipscale % remove the scale entry sel = find(strcmp('SCALE', layout.label)); layout.label(sel) = []; layout.pos(sel,:) = []; layout.width(sel) = []; layout.height(sel) = []; end % ensure proper format of some of label (see bug 1909 -roevdmei) layout.label = layout.label(:); % to plot the layout for debugging, you can use this code snippet if strcmp(cfg.feedback, 'yes') && strcmpi(cfg.style, '2d') tmpcfg = []; tmpcfg.layout = layout; ft_layoutplot(tmpcfg); end % to write the layout to a .mat or text file, you can use this code snippet if ~isempty(cfg.output) && strcmpi(cfg.style, '2d') fprintf('writing layout to ''%s''\n', cfg.output); if strcmpi(cfg.output((end-3):end), '.mat') save(cfg.output,'layout'); else fid = fopen(cfg.output, 'wt'); for i=1:numel(layout.label) fprintf(fid, '%d %f %f %f %f %s\n', i, layout.pos(i,1), layout.pos(i,2), ... layout.width(i), layout.height(i), layout.label{i}); end fclose(fid); end elseif ~isempty(cfg.output) && strcmpi(cfg.style, '3d') % the layout file format does not support 3D positions, furthermore for % a 3D layout the width and height are currently set to NaN error('writing a 3D layout to an output file is not supported'); end % do the general cleanup and bookkeeping at the end of the function ft_postamble provenance ft_postamble previous data ft_postamble history layout %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION % read the layout information from the ascii file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function layout = readlay(filename) if ~exist(filename, 'file') error(sprintf('could not open layout file: %s', filename)); end fid=fopen(filename); lay_string=fread(fid,inf,'char=>char')'; fclose(fid); % pattern to match is integer, than 4 numeric values followed by a % string that can contain whitespaces and plus characters, followed by % newline integer='(\d+)'; float='([\d\.-]+)'; space='\s+'; channel_label='([\w \t\r\f\v\-\+]+)'; single_newline='\n'; pat=[integer, space, ... float, space, ... float, space, ... float, space, ... float, space, ... channel_label, single_newline]; matches=regexp(sprintf('%s\n',lay_string),pat,'tokens'); % convert to (nchannel x 6) matrix layout_matrix=cat(1,matches{:}); % convert values in first five columns to numeric num_values_cell=layout_matrix(:,1:5)'; str_values=sprintf('%s %s %s %s %s; ', num_values_cell{:}); num_values=str2num(str_values); % store layout information (omit channel number in first column) layout.pos = num_values(:,2:3); layout.width = num_values(:,4); layout.height = num_values(:,5); % trim whitespace around channel names label=layout_matrix(:,6); label=regexprep(label,'^\s*',''); label=regexprep(label,'\s*$',''); layout.label = label; return % function readlay %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION % convert 3D electrode positions into 2D layout %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function layout = sens2lay(sens, rz, method, style, overlap) % ensure that the sens structure is according to the latest conventions, % i.e. deal with backward compatibility sens = ft_datatype_sens(sens); % remove the balancing from the sensor definition, e.g. 3rd order gradients, PCA-cleaned data or ICA projections % this not only removed the linear projections, but also ensures that the channel labels are correctly named if isfield(sens, 'chanposorg') chanposorg = sens.chanposorg; else chanposorg = []; end if isfield(sens, 'balance') && ~strcmp(sens.balance.current, 'none') sens = undobalancing(sens); if size(chanposorg, 1) == numel(sens.label) sens.chanpos = chanposorg; end % In case not all the locations have NaNs it might still be useful to plot them % But perhaps it'd be better to have any(any elseif any(all(isnan(sens.chanpos))) [sel1, sel2] = match_str(sens.label, sens.labelorg); sens.chanpos = chanposorg(sel2, :); sens.label = sens.labelorg(sel2); end fprintf('creating layout for %s system\n', ft_senstype(sens)); % apply rotation if isempty(rz) switch ft_senstype(sens) case {'ctf151', 'ctf275', 'bti148', 'bti248', 'ctf151_planar', 'ctf275_planar', 'bti148_planar', 'bti248_planar', 'yokogawa160', 'yokogawa160_planar', 'yokogawa64', 'yokogawa64_planar', 'yokogawa440', 'yokogawa440_planar', 'magnetometer', 'meg'} rz = 90; case {'neuromag122', 'neuromag306'} rz = 0; case 'electrode' rz = 90; otherwise rz = 0; end end sens.chanpos = ft_warp_apply(rotate([0 0 rz]), sens.chanpos, 'homogenous'); % determine the 3D channel positions pnt = sens.chanpos; label = sens.label; if strcmpi(style, '3d') layout.pos = pnt; layout.label = label; else prj = elproj(pnt, method); % this copy will be used to determine the minimum distance between channels % we need a copy because prj retains the original positions, and % prjForDist might need to be changed if the user wants to keep % overlapping channels prjForDist = prj; % check whether many channels occupy identical positions, if so shift % them around if requested if size(unique(prj,'rows'),1) / size(prj,1) < 0.8 if strcmp(overlap, 'shift') ft_warning('the specified sensor configuration has many overlapping channels, creating a layout by shifting them around (use a template layout for better control over the positioning)'); prj = shiftxy(prj', 0.2)'; prjForDist = prj; elseif strcmp(overlap, 'no') error('the specified sensor configuration has many overlapping channels, you specified not to allow that'); elseif strcmp(overlap, 'keep') prjForDist = unique(prj, 'rows'); else error('unknown value for cfg.overlap = ''%s''', overlap); end end d = dist(prjForDist'); d(logical(eye(size(d)))) = inf; % This is a fix for .sfp files, containing positions of 'fiducial % electrodes'. Their presence determines the minimum distance between % projected electrode positions, leading to very small boxes. % This problem has been detected and reported by Matt Mollison. % FIXME: consider changing the box-size being determined by mindist % by a mean distance or so; this leads to overlapping boxes, but that % also exists for some .lay files if any(strmatch('Fid', label)) tmpsel = strmatch('Fid', label); d(tmpsel, :) = inf; d(:, tmpsel) = inf; end if any(isfinite(d(:))) % take mindist as the median of the first quartile of closest channel pairs with non-zero distance mindist = min(d); % get closest neighbour for all channels mindist = sort(mindist(mindist>1e-6),'ascend'); mindist = mindist(1:round(numel(label)/4)); mindist = median(mindist); else mindist = eps; % not sure this is a good value but it's just to prevent crashes when % the EEG sensor definition is meaningless end X = prj(:,1); Y = prj(:,2); Width = ones(size(X)) * mindist * 0.8; Height = ones(size(X)) * mindist * 0.6; layout.pos = [X Y]; layout.width = Width; layout.height = Height; layout.label = label; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION % convert 2D optode positions into 2D layout %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function layout = opto2lay(opto, label) layout = []; layout.pos = []; layout.label = {}; layout.width = []; layout.height = []; [rxnames, rem] = strtok(label, {'-', ' '}); [txnames, rem] = strtok(rem, {'-', ' '}); for i=1:numel(label) % create average positions rxid = ismember(opto.fiberlabel, rxnames(i)); txid = ismember(opto.fiberlabel, txnames(i)); layout.pos(i, :) = opto.fiberpos(rxid, :)/2 + opto.fiberpos(txid, :)/2; layout.label(end+1) = label(i); layout.width(end+1) = 1; layout.height(end+1) = 1; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION % shift 2D positions around so that the minimum distance between any pair % is mindist % % Credit for this code goes to Laurence Hunt at UCL. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function xy = shiftxy(xy,mindist) x = xy(1,:); y = xy(2,:); l=1; i=1; %filler mindist = mindist/0.999; % limits the number of loops while (~isempty(i) && l<50) xdiff = repmat(x,length(x),1) - repmat(x',1,length(x)); ydiff = repmat(y,length(y),1) - repmat(y',1,length(y)); xydist= sqrt(xdiff.^2 + ydiff.^2); %euclidean distance between all sensor pairs [i,j] = find(xydist<mindist*0.999); rm=(i<=j); i(rm)=[]; j(rm)=[]; %only look at i>j for m = 1:length(i); if (xydist(i(m),j(m)) == 0) diffvec = [mindist./sqrt(2) mindist./sqrt(2)]; else xydiff = [xdiff(i(m),j(m)) ydiff(i(m),j(m))]; diffvec = xydiff.*mindist./xydist(i(m),j(m)) - xydiff; end x(i(m)) = x(i(m)) - diffvec(1)/2; y(i(m)) = y(i(m)) - diffvec(2)/2; x(j(m)) = x(j(m)) + diffvec(1)/2; y(j(m)) = y(j(m)) + diffvec(2)/2; end l = l+1; end xy = [x; y];