plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
lcnbeapp/beapp-master
pop_editeventvals.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_editeventvals.m
25,793
utf_8
de89caf08acbbceb7572ea96a994e688
% pop_editeventvals() - Edit events contained in an EEG dataset structure. % If the dataset is the only input, a window pops up % allowing the user to insert the relevant parameter values. % % Usage: >> EEGOUT = pop_editeventvals( EEG, 'key1', value1, ... % 'key2', value2, ... ); % Input: % EEG - EEG dataset % % Optional inputs: % 'sort' - { field1 dir1 field2 dir2 } Sort events based on field1 % then on optional field2. Arg dir1 indicates the sort % direction (0 = increasing, 1 = decreasing). % 'changefield' - {num field value} Insert the given value into the specified % field in event num. (Ex: {34 'latency' 320.4}) % 'changeevent' - {num value1 value2 value3 ...} Change the values of % all fields in event num. % 'add','append','insert' - {num value1 value2 value3 ...} Insert event % before or at event num, and assign value to structure % fields. Note that the latency field must be in second % and will be converted to data sample. Note also that % the index of the event is often irrelevant, as events % will be automatically resorted by latencies. % 'delete' - vector of indices of events to delete % % Outputs: % EEGOUT - EEG dataset with the selected events only % % Ex: EEG = pop_editeventvals(EEG,'changefield', { 1 'type' 'target'}); % % set field type of event number 1 to 'target' % % Author: Arnaud Delorme & Hilit Serby, SCCN, UCSD, 15 March 2002 % % See also: pop_selectevent(), pop_importevent() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 15 March 2002, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 03-16-02 text interface editing -sm & ad % 03-18-02 automatic latency switching display (epoch/continuous) - ad & sm % 03-18-02 debug soring order - ad % 03-18-02 put latencies in ms - ad, lf & sm % 03-29-02 debug latencies in ms - ad & sm % 04-02-02 debuging test - ad & sm function [EEG, com] = pop_editeventvals(EEG, varargin); com =''; if nargin < 1 help pop_editeventvals; return; end; if nargin >= 2 | isstr(EEG) % interpreting command from GUI or command line if isstr(EEG) % GUI gui = 1; varargin = { EEG varargin{:} }; % user data % --------- userdata = get(gcf, 'userdata'); EEG = userdata{1}; oldcom = userdata{2}; allfields = fieldnames(EEG.event); tmpind = strmatch('urevent', allfields); allfields(tmpind) = []; % current event % ------------- objevent = findobj('parent', gcf, 'tag', 'numval'); valnum = str2num(get(objevent, 'string')); shift = 0; else % command line gui = 0; if isempty(EEG.event) disp('Getevent: cannot deal with empty event structure'); return; end; allfields = fieldnames(EEG.event); tmpind = strmatch('urevent', allfields); allfields(tmpind) = []; end; % retinterpret inputs (fix BUG 454) % -------------------------------- if ~gui newvararg = {}; for indfield = 1:2:length(varargin) com = varargin{ indfield }; tmpargs = varargin{ indfield+1 }; newvararg = { newvararg{:} com }; if any(strcmpi({'add','insert','append'},com)) evtind = tmpargs{1}; fields = fieldnames(EEG.event); emptycells = cell(1,length(fields)-1); newvararg = { newvararg{:}, { evtind emptycells{:} } }; if strcmpi(com, 'append'), evtind = evtind+1; end; for ind = 2:length( tmpargs ) if ~strcmpi(fields{ind-1}, 'urevent') newvararg = { newvararg{:},'changefield',{ evtind fields{ind-1} tmpargs{ind} } }; end; end; else newvararg = { newvararg{:} tmpargs }; end; end; varargin = newvararg; end; % scan inputs % ----------- for indfield = 1:2:length(varargin) if length(varargin) >= indfield+1 tmparg = varargin{ indfield+1 }; end; switch lower(varargin{indfield}) case 'goto', % ******************** GUI ONLY *********************** % shift time % ---------- shift = tmparg; valnum = valnum + shift; if valnum < 1, valnum = 1; end; if valnum > length(EEG.event), valnum = length(EEG.event); end; set(objevent, 'string', num2str(valnum,5)); % update fields % ------------- for index = 1:length(allfields) enable = 'on'; if isfield(EEG.event, 'type') if strcmpi(EEG.event(valnum).type, 'boundary'), enable = 'off'; end; end; if strcmp( allfields{index}, 'latency') & ~isempty(EEG.event(valnum).latency) if isfield(EEG.event, 'epoch') value = eeg_point2lat( EEG.event(valnum).latency, EEG.event(valnum).epoch, ... EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3); else value = (EEG.event(valnum).latency-1)/EEG.srate+EEG.xmin; end; elseif strcmp( allfields{index}, 'duration') & ~isempty(EEG.event(valnum).duration) if isfield(EEG.event, 'epoch') value = EEG.event(valnum).duration/EEG.srate*1000; % milliseconds else value = EEG.event(valnum).duration/EEG.srate; % seconds end; else value = getfield( EEG.event(valnum), allfields{index}); end; % update interface % ---------------- tmpobj = findobj('parent', gcf, 'tag', allfields{index}); set(tmpobj, 'string', num2str(value,5), 'enable', enable); end; % update original % --------------- tmpobj = findobj('parent', gcf, 'tag', 'original'); if isfield(EEG.event, 'urevent') & EEG.event(valnum).urevent ~= valnum set(tmpobj, 'string', [ 'originally ' int2str(EEG.event(valnum).urevent)], ... 'horizontalalignment', 'center'); else set(tmpobj, 'string', ' '); end; return; % NO NEED TO SAVE ANYTHING case { 'append' 'insert' 'add' }, % ********************************************************** if gui shift = tmparg; % shift is for adding before or after the event % add epoch number if data epoch % ------------------------------ tmpcell = cell(1,1+length(fieldnames(EEG.event))); tmpcell{1} = valnum; if EEG.trials > 1 indepoch = strmatch('epoch', fieldnames(EEG.event), 'exact'); if valnum > 1, tmpprevval = valnum-1; else tmpprevval = valnum+1; end; if tmpprevval <= length(EEG.event) tmpcell{indepoch+1} = EEG.event(tmpprevval).epoch; end; end; % update commands % --------------- if shift oldcom = { oldcom{:} 'append', tmpcell }; else oldcom = { oldcom{:} 'insert', tmpcell }; end; else if strcmpi(lower(varargin{indfield}), 'append') % not 'add' for backward compatibility shift = 1; else shift = 0; end; valnum = tmparg{1}; end; % find ur index % ------------- valnum = valnum + shift; if isfield(EEG.event, 'epoch'), curepoch = EEG.event(valnum).epoch; end; if isfield(EEG, 'urevent') & isfield(EEG.event, 'urevent') % find non empty urvalnum urvalnum = []; count = 0; while isempty(urvalnum) tmpindex = mod(valnum+count-1, length(EEG.event)+1)+1; urvalnum = EEG.event(valnum+count).urevent; count = count+1; end; if isfield(EEG.urevent, 'epoch'), urcurepoch = EEG.urevent(urvalnum).epoch; end; urvalnum = urvalnum; end; % update urevents % --------------- if isfield(EEG, 'urevent') & isfield(EEG.event, 'urevent') EEG.urevent(end+3) = EEG.urevent(end); EEG.urevent(urvalnum+1:end-2) = EEG.urevent(urvalnum:end-3); EEG.urevent(urvalnum) = EEG.urevent(end-1); EEG.urevent = EEG.urevent(1:end-2); if isfield(EEG.urevent, 'epoch'), EEG.urevent(urvalnum).epoch = urcurepoch; end; end; % update events % ------------- EEG.event(end+3) = EEG.event(end); EEG.event(valnum+1:end-2) = EEG.event(valnum:end-3); EEG.event(valnum) = EEG.event(end-1); EEG.event = EEG.event(1:end-2); if isfield(EEG.event, 'epoch'), EEG.event(valnum).epoch = curepoch; end; if isfield(EEG, 'urevent') & isfield(EEG.event, 'urevent') EEG.event(valnum).urevent = urvalnum; for index = valnum+1:length(EEG.event) EEG.event(index).urevent = EEG.event(index).urevent+1; end; end; % update type field % ----------------- for tmpind = 1:length(allfields) EEG.event = checkconsistency(EEG.event, valnum, allfields{tmpind}); end; case 'delete', % ********************************************************** if ~gui valnum = tmparg; end EEG.event(valnum) = []; if gui, valnum = min(valnum,length(EEG.event)); set(objevent, 'string', num2str(valnum)); % update commands % --------------- oldcom = { oldcom{:} 'delete', valnum }; end; case { 'assign' 'changefield' }, % ********************************************************** if gui, % GUI case field = tmparg; objfield = findobj('parent', gcf, 'tag', field); editval = get(objfield, 'string'); if ~isempty(editval) & ~isempty(str2num(editval)), editval = str2num(editval); end; % update history % -------------- oldcom = { oldcom{:},'changefield',{ valnum field editval }}; else % command line case valnum = tmparg{1}; field = tmparg{2}; editval = tmparg{3}; end; % latency and duration case % ------------------------- if strcmp( field, 'latency') & ~isempty(editval) if isfield(EEG.event, 'epoch') editval = eeg_lat2point( editval, EEG.event(valnum).epoch, ... EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3); else editval = (editval- EEG.xmin)*EEG.srate+1; end; end; if strcmp( field, 'duration') & ~isempty(editval) if isfield(EEG.event, 'epoch') editval = editval/1000*EEG.srate; % milliseconds else editval = editval*EEG.srate; % seconds end; end; % adapt to other formats % ---------------------- EEG.event(valnum) = setfield(EEG.event(valnum), field, editval); EEG.event = checkconsistency(EEG.event, valnum, field); % update urevents % --------------- if isfield(EEG, 'urevent') & isfield(EEG.event, 'urevent') urvalnum = EEG.event(valnum).urevent; % latency case % ------------ if strcmp( field, 'latency') & ~isempty(editval) if isfield(EEG.urevent, 'epoch') urepoch = EEG.urevent(urvalnum).epoch; % find closest event latency % -------------------------- if valnum<length(EEG.event) if EEG.event(valnum+1).epoch == urepoch urlatency = EEG.urevent(EEG.event(valnum+1).urevent).latency; latency = EEG.event(valnum+1).latency; end; end; if valnum>1 if EEG.event(valnum-1).epoch == urepoch urlatency = EEG.urevent(EEG.event(valnum-1).urevent).latency; latency = EEG.event(valnum-1).latency; end; end; % update event % ------------ if exist('urlatency') ~=1 disp('Urevent not updated: could not find other event in the epoch'); else editval = urlatency - ( latency - editval ); % new latency value end; else editval = eeg_urlatency(EEG.event, EEG.event(valnum).latency); end; elseif strcmp( field, 'latency') % empty editval EEG.event(valnum).latency = NaN; end; % duration case % ------------ if strcmp( field, 'duration') & ~isempty(editval) if isfield(EEG.event, 'epoch') editval = editval/1000*EEG.srate; % milliseconds -> point else editval = editval*EEG.srate; % seconds -> point end; end; EEG.urevent = setfield(EEG.urevent, {urvalnum}, field, editval); end; case 'sort', % ********************************************************** if gui % retrieve data field1 = get(findobj('parent', gcf, 'tag', 'listbox1'), 'value'); field2 = get(findobj('parent', gcf, 'tag', 'listbox2'), 'value'); dir1 = get(findobj('parent', gcf, 'tag', 'order1'), 'value'); dir2 = get(findobj('parent', gcf, 'tag', 'order2'), 'value'); if field1 > 1, field1 = allfields{field1-1}; else return; end; if field2 > 1, field1 = allfields{field2-1}; else field2 = []; end; % update history % -------------- oldcom = { oldcom{:},'sort',{ field1 dir1 field2 dir2 } }; else % command line field1 = tmparg{1}; if length(tmparg) < 2, dir1 = 0; else dir1 = tmparg{2}; end; if length(tmparg) < 3, field2 = []; else field2 = tmparg{3}; end; if length(tmparg) < 4, dir2 = 0; else dir2 = tmparg{4}; end; end; % Toby edit 11/16/2005 This section is scrambling the eeg.event % fields. Requires further investigation. if ~isempty(field2) tmpevent = EEG.event; if ~ischar(EEG.event(1).(field2)) tmparray = [ tmpevent.(field2) ]; else tmparray = { tmpevent.(field2) }; end % Commented out 11/18/2005, Toby % These lines were incorrectly sorting the event.latency field in % units of time (seconds) relevant to each event's relative % latency time as measured from the start of each epoch. It is % possible that there are occasions when it is desirable to do % so, but in the case of pop_mergset() it is not. %if strcmp(field2, 'latency') & EEG.trials > 1 % tmparray = eeg_point2lat(tmparray, {EEG.event.epoch}, EEG.srate, [EEG.xmin EEG.xmax], 1); %end; [X I] = mysort( tmparray ); if dir2 == 1, I = I(end:-1:1); end; events = EEG.event(I); else events = EEG.event; end; tmpevent = EEG.event; if ~ischar(EEG.event(1).(field1)) tmparray = [ tmpevent.(field1) ]; else tmparray = { tmpevent.(field1) }; end % Commented out 11/18/2005, Toby %if strcmp( field1, 'latency') & EEG.trials > 1 % tmparray = eeg_point2lat(tmparray, {events.epoch}, EEG.srate, [EEG.xmin EEG.xmax], 1); %end; [X I] = mysort( tmparray ); if dir1 == 1, I = I(end:-1:1); end; EEG.event = events(I); if gui % warn user % --------- warndlg2('Sorting done'); else noeventcheck = 1; % otherwise infinite recursion with eeg_checkset end; end; % end switch end; % end loop % save userdata % ------------- if gui userdata{1} = EEG; userdata{2} = oldcom; set(gcf, 'userdata', userdata); pop_editeventvals('goto', shift); else if ~exist('noeventcheck','var') EEG = eeg_checkset(EEG, 'eventconsistency'); EEG = eeg_checkset(EEG, 'checkur'); end; end; return; end; % ---------------------- % graphic interface part % ---------------------- if isempty(EEG.event) disp('Getevent: cannot deal with empty event structure'); return; end; allfields = fieldnames(EEG.event); tmpind = strmatch('urevent', allfields); allfields(tmpind) = []; if nargin<2 % add field values % ---------------- geometry = { [2 0.5] }; tmpstr = sprintf('Edit event field values (currently %d events)',length(EEG.event)); uilist = { { 'Style', 'text', 'string', tmpstr, 'fontweight', 'bold' } ... { 'Style', 'pushbutton', 'string', 'Delete event', 'callback', 'pop_editeventvals(''delete'');' }}; for index = 1:length(allfields) geometry = { geometry{:} [1 1 1 1] }; % input string % ------------ if strcmp( allfields{index}, 'latency') | strcmp( allfields{index}, 'duration') if EEG.trials > 1 inputstr = [ allfields{index} ' (ms)']; else inputstr = [ allfields{index} ' (sec)']; end; else inputstr = allfields{index}; end; % callback for displaying help % ---------------------------- if index <= length( EEG.eventdescription ) tmptext = EEG.eventdescription{ index }; if ~isempty(tmptext) if size(tmptext,1) > 15, stringtext = [ tmptext(1,1:15) '...' ]; else stringtext = tmptext(1,:); end; else stringtext = 'no-description'; tmptext = 'no-description'; end; else stringtext = 'no-description'; tmptext = 'no-description'; end; cbbutton = ['questdlg2(' vararg2str(tmptext) ... ',''Description of field ''''' allfields{index} ''''''', ''OK'', ''OK'');' ]; % create control % -------------- cbedit = [ 'pop_editeventvals(''assign'', ''' allfields{index} ''');' ]; uilist = { uilist{:}, { }, ... { 'Style', 'pushbutton', 'string', inputstr, 'callback',cbbutton }, ... { 'Style', 'edit', 'tag', allfields{index}, 'string', '', 'callback', cbedit } ... { } }; end; % add buttons % ----------- geometry = { geometry{:} [1] [1.2 0.6 0.6 1 0.6 0.6 1.2] [1.2 0.6 0.6 1 0.6 0.6 1.2] [2 1 2] }; tpappend = 'Append event after the current event'; tpinsert = 'Insert event before the current event'; tporigin = 'Original index of the event (in EEG.urevent table)'; uilist = { uilist{:}, ... { }, ... { },{ },{ }, {'Style', 'text', 'string', 'Event Num', 'fontweight', 'bold' }, { },{ },{ }, ... { 'Style', 'pushbutton', 'string', 'Insert event', 'callback', 'pop_editeventvals(''append'', 0);', 'tooltipstring', tpinsert }, ... { 'Style', 'pushbutton', 'string', '<<', 'callback', 'pop_editeventvals(''goto'', -10);' }, ... { 'Style', 'pushbutton', 'string', '<', 'callback', 'pop_editeventvals(''goto'', -1);' }, ... { 'Style', 'edit', 'string', '1', 'callback', 'pop_editeventvals(''goto'', 0);', 'tag', 'numval' }, ... { 'Style', 'pushbutton', 'string', '>', 'callback', 'pop_editeventvals(''goto'', 1);' }, ... { 'Style', 'pushbutton', 'string', '>>', 'callback', 'pop_editeventvals(''goto'', 10);' }, ... { 'Style', 'pushbutton', 'string', 'Append event', 'callback', 'pop_editeventvals(''append'', 1);', 'tooltipstring', tpappend }, ... { }, { 'Style', 'text', 'string', ' ', 'tag', 'original' 'horizontalalignment' 'center' 'tooltipstring' tporigin } { } }; % add sorting options % ------------------- listboxtext = 'No field selected'; for index = 1:length(allfields) listboxtext = [ listboxtext '|' allfields{index} ]; end; geometry = { geometry{:} [1] [1 1 1] [1 1 1] [1 1 1] }; uilist = { uilist{:}, ... { 'Style', 'text', 'string', 'Re-order events (for review only)', 'fontweight', 'bold' }, ... { 'Style', 'text', 'string', 'Main sorting field:' }, ... { 'Style', 'popupmenu', 'string', listboxtext, 'tag', 'listbox1' }, ... { 'Style', 'checkbox', 'string', 'Click for decreasing order', 'tag', 'order1' } ... { 'Style', 'text', 'string', 'Secondary sorting field:' }, ... { 'Style', 'popupmenu', 'string', listboxtext, 'tag', 'listbox2' }, ... { 'Style', 'checkbox', 'string', 'Click for decreasing order', 'tag', 'order2' }, ... { } { 'Style', 'pushbutton', 'string', 'Re-sort', 'callback', 'pop_editeventvals(''sort'');' }, ... { } }; userdata = { EEG {} }; inputgui( geometry, uilist, 'pophelp(''pop_editeventvals'');', ... 'Edit event values -- pop_editeventvals()', userdata, 'plot'); pop_editeventvals('goto', 0); % wait for figure % --------------- fig = gcf; waitfor( findobj('parent', fig, 'tag', 'ok'), 'userdata'); try, userdata = get(fig, 'userdata'); close(fig); % figure still exist ? catch, return; end; % transfer events % --------------- if ~isempty(userdata{2}) com = sprintf('%s = pop_editeventvals(%s,%s);', inputname(1), inputname(1), vararg2str(userdata{2})); end; if isempty(findstr('''sort''', com)) if ~isempty(userdata{2}) % some modification have been done EEG = userdata{1}; disp('Checking event consistency...'); EEG = eeg_checkset(EEG, 'eventconsistency'); EEG = eeg_checkset(EEG, 'checkur'); end; else com = ''; disp('WARNING: all edits discarded because of event resorting. The EEGLAB event structure'); disp(' must contain events sorted by latency (you may obtain an event structure'); disp(' with resorted event by calling this function from the command line).'); end; return; end; return; % format the output field % ----------------------- function strval = reformat( val, latencycondition, trialcondition, eventnum) if latencycondition if trialcondition strval = ['eeg_lat2point(' num2str(val) ', EEG.event(' int2str(eventnum) ').epoch, EEG.srate,[EEG.xmin EEG.xmax]*1000, 1E-3);' ]; else strval = [ '(' num2str(val) '-EEG.xmin)*EEG.srate+1;' ]; end; else if isstr(val), strval = [ '''' val '''' ]; else strval = num2str(val); end; end; % sort also empty values % ---------------------- function [X, I] = mysort(tmparray); if iscell(tmparray) if all(cellfun('isreal', tmparray)) tmpempty = cellfun('isempty', tmparray); tmparray(tmpempty) = { 0 }; tmparray = [ tmparray{:} ]; end; end; try, [X I] = sort(tmparray); catch, disp('Sorting failed. Check that selected fields contain uniform value format.'); X = tmparray; I = 1:length(X); end; % checkconsistency of new event % ----------------------------- function eventtmp = checkconsistency(eventtmp, valnum, field) otherval = mod(valnum+1, length(eventtmp))+1; if isstr(getfield(eventtmp(valnum), field)) & ~isstr(getfield(eventtmp(otherval), field)) eventtmp(valnum) = setfield(eventtmp(valnum), field, str2num(getfield(eventtmp(valnum), field))); end; if ~isstr(getfield(eventtmp(valnum), field)) & isstr(getfield(eventtmp(otherval), field)) eventtmp(valnum) = setfield(eventtmp(valnum), field, num2str(getfield(eventtmp(valnum), field))); end; if strcmpi(field, 'latency') & isempty(getfield(eventtmp(valnum), field)) eventtmp(valnum).latency = NaN; end;
github
lcnbeapp/beapp-master
pop_icathresh.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_icathresh.m
14,758
utf_8
365bfcb08f0dd1c0da09de203c810155
% pop_icathresh() - main menu for choosing threshold for component % rejection in EEGLAB. % % Usage: % >> [OUTEEG rej] = pop_icathresh(INEEG, threshval, rejmethod, % rejvalue, interact); % % Inputs: % INEEG - input dataset % threshval - values of thresholds for each of the 3 statistical % measures. Default is [] and the program uses the value % in the dataset. % rejmethod - either 'percent', 'dataset' or 'current'. 'percent' % will reject a given percentage of components with % the highest value in one or several statistical % measure. 'dataset' will use an other dataset for % calibration. 'current' will use the current dataset % for calibration. Default is 'current'. % rejvalue - percentage if rejmethod is 'percent', dataset number % if rejmethod is 'dataset' (no input if 'current'). If it % is a percentage, '25' for instance means that the 25% % independent components with the highest values of one % statistical measure are rejected. Note that, one can % also enter one percentage per statistical value (such as % 25 20 30). % interact - interactive windows or just rejection % % Inputs: % OUTEEG - output dataset with updated thresholds % rej - new rejection array % % Graphic interface: % The graphic interface is divided into 3 parts. On the top, the % experimenter chooses the basis for the component rejection (see % rejmethod input). On the middle panel, the user can tune thresholds % manually and plot the distribution of statistical values. Each time % that setting of one of these two top panels is modified, the curve % on the third panel are redrawn. % The third panel is composed of 3 graphs, one for each statistical % measure. The blue curve on each graph indicates the accuracy of the % measure to detect artifactual components and non-artifactual % components of a dataset. Note that 'artifactual components are % defined with the rejection methods fields on the top (if you use % the percentage methods, these artifactual components may not actually % be artifactual). For accurate rejection, one should first reject % artifactual component manually and then set up the threshold to % approximate this manual rejection. The green curve indicate the % rejection when all measure are considered. Points on the blue and % on the green curves indicate the position of the current threshold on % the parametric curve. Not that for the green cumulative curve, this % point is at the same location for all graphs. % How to tune the threshold? To tune the threshold, one should try to % maximize the detection of non-artifactual components (because it is % preferable to miss some artifactual components than to classify as % artifactual non-artifact components). % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %PROBLEM: when the % is set and we change manually yhe threshold, % the software comes back to the percentage rejection % 01-25-02 reformated help & license -ad function [EEG, rej, com] = pop_icathresh( EEG, threshval, rejmethod, rejvalue, interact); com = []; rej = EEG.reject.gcompreject; if nargin < 1 help pop_icathresh; return; end; if nargin < 2 threshval = []; end; if nargin < 3 rejmethod = 'current'; end; if nargin < 4 rejvalue = 25; end; if nargin < 5 interact = 1; end; if ~isempty(threshval) EEG.reject.threshentropy = threshval(1); EEG.reject.threshkurtact = threshval(2); EEG.reject.threshkurtdist = threshval(3); end; tagmenu = 'pop_icathresh'; if ~isempty( findobj('tag', tagmenu)) error('cannot open two identical windows, close the first one first'); end; % the current rejection will be stored in userdata of the figure % -------------------------------------------------------------- gcf = figure('visible', 'off', 'numbertitle', 'off', 'name', 'Choose thresholds', 'tag', tagmenu, 'userdata', rej); pos = get(gca, 'position'); q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]./100; axis off; % definition of callbacks % ----------------------- cb_cancel = [ 'userdat = get(gcbo, ''userdata'');' ... % restore thresholds 'EEG.reject.threshentropy = userdat{1};' ... 'EEG.reject.threshkurtact = userdat{2};' ... 'EEG.reject.threshkurtdist = userdat{3};' ... 'clear userdat; close(gcbf);' ]; drawgraphs = [ 'if isempty( gcbf ), fig = gcf; else fig = gcbf; end;' ... % determine the figure handler 'if get( findobj(''parent'', fig, ''tag'', ''Ipercent''), ''value'') == 1, ' ... % test if percentage ' perc = str2num(get( findobj(''parent'', fig, ''tag'', ''Ipercenttext''), ''String''));' ... ' if length(perc < 2), perc = [perc perc perc]; end;' ... ' perc = round((100-perc) * length( EEG.stats.compenta) / 100);' ... % convert the percentage ' method = zeros( size( EEG.stats.compenta ) );' ... ' [tmprej tmpindex] = sort(EEG.stats.compenta(:));' ... ' method( tmpindex(perc(1)+1:end) ) = 1;' ... ' set( findobj(''parent'', fig, ''tag'', ''entstring''), ''string'', num2str(tmprej(perc(1)+1)));' ... % update threshold ' [tmprej tmpindex] = sort(EEG.stats.compkurta(:));' ... ' method( tmpindex(perc(2)+1:end) ) = 1;' ... ' set( findobj(''parent'', fig, ''tag'', ''kurtstring''), ''string'', num2str(tmprej(perc(1)+1)));' ... % update threshold ' [tmprej tmpindex] = sort(EEG.stats.compkurtdist(:));' ... ' method( tmpindex(perc(3)+1:end) ) = 1;' ... ' set( findobj(''parent'', fig, ''tag'', ''kurtdiststring''), ''string'', num2str(tmprej(perc(1)+1)));' ... % update threshold ' allvalues = [EEG.stats.compenta(:) EEG.stats.compkurta(:) EEG.stats.compkurtdist(:) ];' ... ' clear perc tmprej tmpindex;' ... 'end;' ... 'if get( findobj(''parent'', fig, ''tag'', ''Iother''), ''value'') == 1, ' ... % test if other dataset ' di = str2num(get( findobj(''parent'', fig, ''tag'', ''Iothertext''), ''String''));' ... ' if isempty( di ), clear fig; return; end;' ... ' method = ALLEEG(di).reject.gcompreject'';' ... ' allvalues = [ALLEEG(di).stats.compenta(:) ALLEEG(di).stats.compkurta(:) ALLEEG(di).stats.compkurtdist(:) ];' ... ' clear di;' ... 'end;' ... 'if get( findobj(''parent'', fig, ''tag'', ''Icurrent''), ''value'') == 1, ' ... % test if current dataset ' method = EEG.reject.gcompreject'';' ... ' allvalues = [EEG.stats.compenta(:) EEG.stats.compkurta(:) EEG.stats.compkurtdist(:) ];' ... 'end;' ... 'axes( findobj( ''parent'', fig, ''tag'', ''graphent'')); cla;' ... '[tmp1 tmp2 tmp3] = drawproba( method, allvalues, [0 EEG.reject.threshkurtact EEG.reject.threshkurtdist ], ' ... ' { ''&'' ''|'' }, EEG.reject.threshentropy, ''Entropy of activity'',''Artifact detection (%)'', ''Non-artifact detection (%)'');' ... 'set(gca, ''tag'', ''graphent'');' ... 'axes( findobj( ''parent'', fig, ''tag'', ''graphkurt'')); cla;' ... '[tmp1 tmp2 tmp3] = drawproba( method, allvalues, [EEG.reject.threshentropy 0 EEG.reject.threshkurtdist ], ' ... ' { ''&'' ''|'' }, EEG.reject.threshkurtact, ''Kurtosis of activity'', ''Artifact detection (%)'', '''');' ... 'set(gca, ''tag'', ''graphkurt'');' ... 'axes( findobj( ''parent'', fig, ''tag'', ''graphkurtdist'')); cla;' ... '[tmp1 tmp2 tmp3] = drawproba( method, allvalues, [EEG.reject.threshentropy EEG.reject.threshkurtact 0 ], ' ... ' { ''&'' ''|'' }, EEG.reject.threshkurtdist, ''Kurtosis of topography'', ''Artifact detection (%)'', '''');' ... 'set(gca, ''tag'', ''graphkurtdist'');' ... 'clear method allvalues fig;' ... ]; cb_percent = [ 'if isempty( gcbf ), fig = gcf; else fig = gcbf; end;' ... % determine the figure handler 'set( findobj(''parent'', fig, ''tag'', ''Ipercent''), ''value'', 1);'... 'set( findobj(''parent'', fig, ''tag'', ''Iother''), ''value'', 0);' ... 'set( findobj(''parent'', fig, ''tag'', ''Icurrent''), ''value'', 0);' ... 'set( findobj(''parent'', fig, ''tag'', ''Ipercenttext''), ''enable'', ''on'');' ... 'set( findobj(''parent'', fig, ''tag'', ''Iothertext''), ''enable'', ''off''); clear fig;' drawgraphs ]; cb_other = [ 'if isempty( gcbf ), fig = gcf; else fig = gcbf; end;' ... % determine the figure handler 'set( findobj(''parent'', fig, ''tag'', ''Iother''), ''value'', 1);'... 'set( findobj(''parent'', fig, ''tag'', ''Ipercent''), ''value'', 0);' ... 'set( findobj(''parent'', fig, ''tag'', ''Icurrent''), ''value'', 0);' ... 'set( findobj(''parent'', fig, ''tag'', ''Ipercenttext''), ''enable'', ''off'');' ... 'set( findobj(''parent'', fig, ''tag'', ''Iothertext''), ''enable'', ''on''); clear fig;' drawgraphs ]; cb_current = [ 'if isempty( gcbf ), fig = gcf; else fig = gcbf; end;' ... % determine the figure handler 'set( findobj(''parent'', fig, ''tag'', ''Icurrent''), ''value'', 1);'... 'set( findobj(''parent'', fig, ''tag'', ''Iother''), ''value'', 0);' ... 'set( findobj(''parent'', fig, ''tag'', ''Ipercent''), ''value'', 0);' ... 'set( findobj(''parent'', fig, ''tag'', ''Ipercenttext''), ''enable'', ''off'');' ... 'set( findobj(''parent'', fig, ''tag'', ''Iothertext''), ''enable'', ''off''); clear fig;' drawgraphs ]; cb_entropy = [ 'EEG.reject.threshentropy = str2num(get(gcbo, ''string''));' ... drawgraphs ]; cb_kurtact = [ 'EEG.reject.threshkurtact = str2num(get(gcbo, ''string''));' ... drawgraphs ]; cb_kurtdist = [ 'EEG.reject.threshkurtdist = str2num(get(gcbo, ''string''));' ... drawgraphs ]; if interact cb_calrej = [ 'ButtonName=questdlg2( ''This will erase previous projections'', ''Confirmation'', ''CANCEL'', ''OK'', ''OK'');' ] else cb_calrej = [ 'ButtonName= ''OK''' ]; end; cb_calrej = [ cb_calrej ... 'switch ButtonName,' ... ' case ''OK'',' ... ' rej1 = find(EEG.stats.compenta > EEG.reject.threshentropy);' ... ' rej2 = find(EEG.stats.compkurta > EEG.reject.threshkurtact);' ... ' rej3 = find(EEG.stats.compkurtdist > EEG.reject.threshkurtdist);' ... ' EEG.reject.gcompreject = (rej1 & rej2) | rej3;' ... ' clear rej1 rej2 rej3;' ... 'end; clear ButtonName;' ]; % default value for rejection methods % ----------------------------------- rejvalother = ''; rejvalpercent = '25'; switch rejmethod case 'percent', rejvalpercent = num2str( rejvalue); case 'dataset', rejvalother = num2str( rejvalue); end; % ----------------------------------------------------- allh = supergui(gcf, { [1] ... [2 1] [2 1] [2 1] ... [1] ... [1] ... [1.5 0.5 1] [1.5 0.5 1] [1.5 0.5 1] ... [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] ... [1 1 1 1 1] ... }, [], ... { 'Style', 'text', 'string', 'Calibration method', 'FontSize', 13, 'fontweight', 'bold' }, ... ... { 'style', 'checkbox', 'String', '% of artifactual components (can also put one % per rejection)', 'tag', 'Ipercent', 'value', 1, 'callback', cb_percent}, ... { 'style', 'edit', 'String', rejvalpercent, 'tag', 'Ipercenttext', 'callback', drawgraphs }, ... ... { 'style', 'checkbox', 'String', 'Specific dataset (enter dataset number)', 'tag', 'Iother', 'value', 0, 'callback', cb_other}, ... { 'style', 'edit', 'String', rejvalother, 'tag', 'Iothertext', 'enable', 'off', 'callback', drawgraphs }, ... ... { 'style', 'checkbox', 'String', 'Current dataset', 'tag', 'Icurrent', 'value', 0, 'callback', cb_current}, ... { }, ... ... { }, ... ... { 'Style', 'text', 'string', 'Threshold values', 'FontSize', 13, 'fontweight', 'bold' }, ... ... { 'style', 'text', 'String', 'Entropy of activity threshold' }, ... { 'style', 'edit', 'String', num2str(EEG.reject.threshentropy), 'tag', 'entstring', 'callback', cb_entropy }, ... { 'style', 'pushbutton', 'String', 'Histogram', 'callback', 'figure; hist(EEG.stats.compenta,20); title(''Entropy of activity'');' }, ... ... { 'style', 'text', 'String', 'Kurtosis of activity threshold' }, ... { 'style', 'edit', 'String', num2str(EEG.reject.threshkurtact), 'tag', 'kurtstring', 'callback', cb_kurtact }, ... { 'style', 'pushbutton', 'String', 'Histogram', 'callback', 'figure; hist(EEG.stats.compkurta,200); title(''Kurtosis of activity'');' }, ... ... { 'style', 'text', 'String', 'Kurtosis of topography threshold' }, ... { 'style', 'edit', 'String', num2str(EEG.reject.threshkurtdist), 'tag', 'kurtdiststring', 'callback', cb_kurtdist }, ... { 'style', 'pushbutton', 'String', 'Histogram', 'callback', 'figure; hist(EEG.stats.compkurtdist,20); title(''Kurtosis of topography'');' }, ... ... { }, { }, { }, { }, { }, { }, { }, { }, { }, { }, ... ... { 'style', 'pushbutton', 'String', 'Cancel', 'callback', cb_cancel, 'userdata', { EEG.reject.threshentropy EEG.reject.threshkurtact EEG.reject.threshkurtdist }}, ... { 'style', 'pushbutton', 'String', 'Auto thresh' , 'callback', '', 'enable', 'off' }, ... { 'style', 'pushbutton', 'String', 'Help' , 'callback', 'pophelp(''pop_icathresh'');' }, ... { 'style', 'pushbutton', 'String', 'Accept thresh.' , 'callback', 'close(gcbf);' }, ... { 'style', 'pushbutton', 'String', 'Calc. rejection' , 'callback', 'close(gcbf);' } ... ... ); h = axes('position', [0 15 30 30].*s+q, 'tag', 'graphent'); h = axes('position', [35 15 30 30].*s+q, 'tag', 'graphkurt'); h = axes('position', [70 15 30 30].*s+q, 'tag', 'graphkurtdist'); rejmethod switch rejmethod case 'dataset', eval([ 'gcbf = [];' cb_other]); case 'current', eval([ 'gcbf = [];' cb_current]); otherwise, eval([ 'gcbf = [];' cb_percent]); end; return;
github
lcnbeapp/beapp-master
pop_eegthresh.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_eegthresh.m
10,919
utf_8
9d094caa6dcd548bca0d55978b85170a
% pop_eegthresh() - reject artifacts by detecting outlier values. This has % long been a standard method for selecting data to reject. % Applied either for electrode data or component activations. % Usage: % >> pop_eegthresh( INEEG, typerej); % pop-up interactive window % >> [EEG Indexes] = pop_eegthresh( INEEG, typerej, elec_comp, lowthresh, ... % upthresh, starttime, endtime, superpose, reject); % % Graphic interface: % "Electrode|Component indices(s)" - [edit box] indices of the electrode(s) or % component(s) to take into consideration. Same as the 'elec_comp' % parameter from the command line. % "Minimum rejection threshold(s)" - [edit box] lower threshold limit(s) % (in uV|std. dev.). Sets command line parameter 'lowthresh'. % "Maximum rejection threshold(s)" - [edit box] upper threshold limit(s) % (in uV|std. dev.). Sets command line parameter 'upthresh'. % "Start time limit(s)" - [edit box] starting time limit(s) (in seconds). % Sets command line parameter 'starttime'. % "End time limit(s)" - [edit box] ending time limit(s) (in seconds). % Sets command line parameter 'endtime'. % "Display previous rejection marks: " - [Checkbox]. Sets the command line % input option 'eegplotplotallrej'. % "Reject marked trials: " - [Checkbox] Sets the command line % input option 'eegplotreject'. % % Inputs: % INEEG - input EEG dataset % typerej - type of rejection (0 = independent components; 1 = raw % data). Default is 1. For independent components, before % thresholding the activations are normalized (to have std. dev. 1). % elec_comp - [e1 e2 ...] electrode|component numbers to take % into consideration for rejection % lowthresh - lower threshold limit (in uV|std. dev. For components, the % threshold(s) are in std. dev.). Can be an array if more than one % electrode|component number is given in elec_comp (above). % If fewer values than the number of electrodes|components, the % last value is used for the remaining electrodes|components. % upthresh - upper threshold limit (in uV|std dev) (see lowthresh above) % starttime - rejection window start time(s) in seconds (see lowthresh above) % endtime - rejection window end time(s) in seconds (see lowthresh) % superpose - [0|1] 0=do not superpose rejection markings on previous % rejection marks stored in the dataset: 1=show both current and % previously marked rejections using different colors. {Default: 0}. % reject - [1|0] 0=do not actually reject the marked trials (but store the % marks: 1=immediately reject marked trials. {Default: 1}. % Outputs: % Indexes - index of rejected trials % When eegplot() is called, modifications are applied to the current % dataset at the end of the call to eegplot() when the user presses % the 'Reject' button. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eegthresh(), eeglab(), eegplot(), pop_rejepoch() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-07-02 added srate argument to eegplot call -ad function [EEG, Irej, com] = pop_eegthresh( EEG, icacomp, elecrange, negthresh, posthresh, ... starttime, endtime, superpose, reject, topcommand); Irej = []; com = ''; if nargin < 1 help pop_eegthresh; return; end; if nargin < 2 icacomp = 1; end; if icacomp == 0 if isempty( EEG.icasphere ) disp('Error: you must run ICA first'); return; end; end; if exist('reject') ~= 1 reject = 1; end; if nargin < 3 % which set to save % ----------------- promptstr = { fastif(icacomp,'Electrode (indices(s), Ex: 2 4 5):' , 'Component (indices, Ex: 2 6:8 10):'), ... fastif(icacomp,'Minimum rejection threshold(s) (uV, Ex:-20 -10 -15):', 'Minimum rejection threshold(s) (std. dev, Ex: -3 -2.5 -2):'), ... fastif(icacomp,'Maximum rejection threshold(s) (uV, Ex: 20 10 15):' , 'Maximum rejection threshold(s) (std. dev, Ex: 2 2 2.5):'), ... 'Start time limit(s) (seconds, Ex -0.1 0.3):', ... 'End time limit(s) (seconds, Ex 0.2):', ... 'Display previous rejection marks', ... 'Reject marked trial(s)' }; inistr = { fastif(icacomp, ['1:' int2str(EEG.nbchan)], '1:5'), ... fastif(icacomp, '-10', '-20'), ... fastif(icacomp, '10', '20'), ... num2str(EEG.xmin), ... num2str(EEG.xmax), ... '0', ... '0' }; g1 = [1 0.1 0.75]; g2 = [1 0.22 0.85]; geometry = {g1 g1 g1 g1 g1 1 g2 g2}; uilist = {... { 'Style', 'text', 'string', promptstr{1}} {} { 'Style','edit' ,'string' ,inistr{1} 'tag' 'cpnum'}... { 'Style', 'text', 'string', promptstr{2}} {} { 'Style','edit' ,'string' ,inistr{2} 'tag' 'lowlim' }... { 'Style', 'text', 'string', promptstr{3}} {} { 'Style','edit' ,'string' ,inistr{3} 'tag' 'highlim'}... { 'Style', 'text', 'string', promptstr{4}} {} { 'Style','edit' ,'string' ,inistr{4} 'tag' 'starttime'}... { 'Style', 'text', 'string', promptstr{5}} {} { 'Style','edit' ,'string' ,inistr{5} 'tag' 'endtime'}... {}... { 'Style', 'text', 'string', promptstr{6}} {} { 'Style','checkbox' ,'string' ,' ' 'value' str2double(inistr{6}) 'tag','rejmarks' }... { 'Style', 'text', 'string', promptstr{7}} {} { 'Style','checkbox' ,'string' ,' ' 'value' str2double(inistr{7}) 'tag' 'rejtrials'} ... }; figname = fastif(icacomp == 0, 'Rejection abnormal comp. values -- pop_eegthresh()','Rejection abnormal elec. values -- pop_eegthresh()'); result = inputgui( geometry,uilist,'pophelp(''pop_eegthresh'');', figname); size_result = size( result ); if size_result(1) == 0 return; end; elecrange = result{1}; negthresh = result{2}; posthresh = result{3}; starttime = result{4}; endtime = result{5}; superpose = result{6}; reject = result{7}; end; if isstr(elecrange) % convert arguments if they are in text format calldisp = 1; elecrange = eval( [ '[' elecrange ']' ] ); negthresh = eval( [ '[' negthresh ']' ] ); posthresh = eval( [ '[' posthresh ']' ] ); if isstr(starttime) starttime = eval( [ '[' starttime ']' ] ); end; if isstr(endtime) endtime = eval( [ '[' endtime ']' ] ); end; else calldisp = 0; end; if any(starttime < EEG.xmin) fprintf('Warning : starttime inferior to minimum time, adjusted\n'); starttime(find(starttime < EEG.xmin)) = EEG.xmin; end; if any(endtime > EEG.xmax) fprintf('Warning : endtime superior to maximum time, adjusted\n'); endtime(find(endtime > EEG.xmax)) = EEG.xmax; end; if icacomp == 1 [Itmp Irej NS Erejtmp] = eegthresh( EEG.data, EEG.pnts, elecrange, negthresh, posthresh, [EEG.xmin EEG.xmax], starttime, endtime); tmpelecIout = zeros(EEG.nbchan, EEG.trials); tmpelecIout(elecrange,Irej) = Erejtmp; else icaacttmp = eeg_getdatact(EEG, 'component', elecrange); [Itmp Irej NS Erejtmp] = eegthresh( icaacttmp, EEG.pnts, 1:length(elecrange), negthresh, posthresh, [EEG.xmin EEG.xmax], starttime, endtime); tmpelecIout = zeros(size(EEG.icaweights,1), EEG.trials); tmpelecIout(elecrange,Irej) = Erejtmp; end; fprintf('%d channel selected\n', size(elecrange(:), 1)); fprintf('%d/%d trials marked for rejection\n', length(Irej), EEG.trials); tmprejectelec = zeros( 1, EEG.trials); tmprejectelec(Irej) = 1; rej = tmprejectelec; rejE = tmpelecIout; if calldisp if icacomp == 1 macrorej = 'EEG.reject.rejthresh'; macrorejE = 'EEG.reject.rejthreshE'; else macrorej = 'EEG.reject.icarejthresh'; macrorejE = 'EEG.reject.icarejthreshE'; end; colrej = EEG.reject.rejthreshcol; eeg_rejmacro; % script macro for generating command and old rejection arrays if icacomp == 1 eegplot( EEG.data(elecrange,:,:), 'srate', EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}); else eegplot( icaacttmp, 'srate', EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}); end; else if reject == 1 EEG = pop_rejepoch(EEG, rej, 0); end; end; if ~isempty(rej) if icacomp == 1 EEG.reject.rejthresh = rej; EEG.reject.rejthreshE = rejE; else EEG.reject.icarejthresh = rej; EEG.reject.icarejthreshE = rejE; end; end; %com = sprintf('Indexes = pop_eegthresh( %s, %d, [%s], [%s], [%s], [%s], [%s], %d, %d);', ... % inputname(1), icacomp, num2str(elecrange), num2str(negthresh), ... % num2str(posthresh), num2str(starttime ) , num2str(endtime), superpose, reject ); com = [ com sprintf('%s = pop_eegthresh(%s,%s);', inputname(1), ... inputname(1), vararg2str({icacomp,elecrange,negthresh,posthresh,starttime,endtime,superpose,reject})) ]; if nargin < 3 Irej = com; end; return; % reject artifacts in a sequential fashion to save memory (ICA ONLY) % ------------------------------------------------------- function [Irej, Erej] = thresh( data, elecrange, timerange, negthresh, posthresh, starttime, endtime); Irej = []; Erej = zeros(size(data,1), size(data,2)); for index = 1:length(elecrange) tmpica = data(index,:,:); tmpica = reshape(tmpica, 1, size(data,2)*size(data,3)); % perform the rejection % --------------------- tmpica = (tmpica-mean(tmpica,2)*ones(1,size(tmpica,2)))./ (std(tmpica,0,2)*ones(1,size(tmpica,2))); [I1 Itmprej NS Etmprej] = eegthresh( tmpica, size(data,2), 1, negthresh, posthresh, ... timerange, starttime, endtime); Irej = union_bc(Irej, Itmprej); Erej(elecrange(index),Itmprej) = Etmprej; end;
github
lcnbeapp/beapp-master
pop_timef.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_timef.m
8,964
utf_8
479d128417dbb0d8ab96a1795c580e3b
% pop_timef() - Returns estimates and plots of event-related (log) spectral % perturbation (ERSP) and inter-trial coherence (ITC) changes % timelocked to a set of input events in one data channel. % % Usage: % >> pop_timef(EEG, typeplot); % pop_up window % >> pop_timef(EEG, typeplot, lastcom); % pop_up window % >> pop_timef(EEG, typeplot, channel); % do not pop-up % >> pop_timef(EEG, typeproc, num, tlimits,cycles, % 'key1',value1,'key2',value2, ... ); % % Inputs: % INEEG - input EEG dataset % typeproc - type of processing. 1 process the raw % data and 0 the ICA components % num - component or channel number % tlimits - [mintime maxtime] (ms) sub-epoch time limits % cycles - >0 -> Number of cycles in each analysis wavelet % 0 -> Use FFTs (with constant window length) % % Optional inputs: % See the timef() function. % % Outputs: same as timef(), no outputs are returned when a % window pops-up to ask for additional arguments % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: timef(), eeglab() % Copyright (C) 2002 [email protected], Arnaud Delorme, CNL / Salk Institute % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-08-02 add eeglab option & optimize variable sizes -ad % 03-10-02 change timef call -ad % 03-18-02 added title -ad & sm % 04-04-02 added outputs -ad & sm function varargout = pop_timef(EEG, typeproc, num, tlimits, cycles, varargin ); varargout{1} = ''; % display help if not enough arguments % ------------------------------------ if nargin < 2 help pop_timef; return; end; lastcom = []; if nargin < 3 popup = 1; else popup = isstr(num) | isempty(num); if isstr(num) lastcom = num; end; end; % pop up window % ------------- if popup [txt vars] = gethelpvar('timef.m'); geometry = { [1 0.5 0.5] [1 0.5 0.5] [1 0.5 0.5] [0.92 0.1 0.78] [1 0.5 0.5] [1 0.8 0.2] [1] [1 1]}; uilist = { ... { 'Style', 'text', 'string', fastif(typeproc, 'Channel number', 'Component number'), 'fontweight', 'bold' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,3,[],'1') } {} ... { 'Style', 'text', 'string', 'Epoch time range [min max] (msec)', 'fontweight', 'bold', ... 'tooltipstring', 'Sub epoch time limits' } ... { 'Style', 'edit', 'string', getkeyval(lastcom,4,[],[ int2str(EEG.xmin*1000) ' ' int2str(EEG.xmax*1000) ]) } {} ... { 'Style', 'text', 'string', 'Wavelet cycles (0->FFT, see >> help timef)', 'fontweight', 'bold', ... 'tooltipstring', context('cycles',vars,txt) } ... { 'Style', 'edit', 'string', getkeyval(lastcom,5,[],'3 0.5') } {} ... { 'Style', 'text', 'string', '[set]->Linear coher / [unset]->Phase coher', 'fontweight', 'bold', ... 'tooltipstring', ['Compute linear inter-trial coherence (coher)' 10 ... 'OR Amplitude-normalized inter-trial phase coherence (phasecoher)'] } ... { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'phasecoher','present',1) } { } ... { 'Style', 'text', 'string', 'Bootstrap significance level (Ex: 0.01 -> 1%)', 'fontweight', 'bold', ... 'tooltipstring', context('alpha',vars,txt) } ... { 'Style', 'edit', 'string', getkeyval(lastcom,'alpha') } {} ... { 'Style', 'text', 'string', 'Optional timef() arguments (see Help)', 'fontweight', 'bold', ... 'tooltipstring', 'See timef() help via the Help button on the right...' } ... { 'Style', 'edit', 'string', '''padratio'', 4, ''plotphase'',''off''' } ... { 'Style', 'pushbutton', 'string', 'Help', 'callback', 'pophelp(''timef'');' } ... {} ... { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotersp','present',0), 'string', ... 'Plot Event Related Spectral Power', 'tooltipstring', ... 'Plot log spectral perturbation image in the upper panel' } ... { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotitc','present',0), 'string', ... 'Plot Inter Trial Coherence', 'tooltipstring', ... 'Plot the inter-trial coherence image in the lower panel' } ... }; % { 'Style', 'edit', 'string', '''padratio'', 4, ''plotphase'', ''off''' } ... %{ 'Style', 'text', 'string', '[set] -> Plot ITC phase sign', 'fontweight', 'bold', ... % 'tooltipstring', ['Plot the sign (+/-) of inter-trial coherence phase' 10 ... % 'as red (+) or blue (-)'] } ... % { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotphase','present',1) } { } ... result = inputgui( geometry, uilist, 'pophelp(''pop_timef'');', ... fastif(typeproc, 'Plot channel time frequency -- pop_timef()', ... 'Plot component time frequency -- pop_timef()')); if length( result ) == 0 return; end; num = eval( [ '[' result{1} ']' ] ); tlimits = eval( [ '[' result{2} ']' ] ); cycles = eval( [ '[' result{3} ']' ] ); if result{4} options = [ ',''type'', ''coher''' ]; else options = [',''type'', ''phasecoher''' ]; end; % add topoplot % ------------ if isfield(EEG.chanlocs, 'theta') if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end; if typeproc == 1 options = [options ', ''topovec'', ' int2str(num) ... ', ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ]; else options = [options ', ''topovec'', EEG.icawinv(:,' int2str(num) ... '), ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ]; end; end; % add title % --------- if isempty( findstr( '''title''', result{6})) if ~isempty(EEG.chanlocs) & typeproc chanlabel = EEG.chanlocs(num).labels; else chanlabel = int2str(num); end; switch lower(result{4}) case 'coher', options = [options ', ''title'',' fastif(typeproc, '''Channel ', '''Component ') chanlabel ... ' power and inter-trial coherence' fastif(~ isempty(EEG.setname), [' (' EEG.setname ')''' ], '''') ]; otherwise, options = [options ', ''title'',' fastif(typeproc, '''Channel ', '''Component ') chanlabel ... ' power and inter-trial phase coherence' fastif(~ isempty(EEG.setname), [' (' EEG.setname ')''' ], '''') ]; end; end; if ~isempty( result{5} ) options = [ options ', ''alpha'',' result{5} ]; end; if ~isempty( result{6} ) options = [ options ',' result{6} ]; end; if ~result{7} options = [ options ', ''plotersp'', ''off''' ]; end; if ~result{8} options = [ options ', ''plotitc'', ''off''' ]; end; figure; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; else options = [ ',' vararg2str(varargin) ]; end; % compute epoch limits % -------------------- if isempty(tlimits) tlimits = [EEG.xmin, EEG.xmax]*1000; end; pointrange1 = round(max((tlimits(1)/1000-EEG.xmin)*EEG.srate, 1)); pointrange2 = round(min((tlimits(2)/1000-EEG.xmin)*EEG.srate, EEG.pnts)); pointrange = [pointrange1:pointrange2]; % call function sample either on raw data or ICA data % --------------------------------------------------- if typeproc == 1 tmpsig = EEG.data(num,pointrange,:); else if ~isempty( EEG.icasphere ) tmpsig = eeg_getdatact(EEG, 'component', num, 'samples', pointrange); else error('You must run ICA first'); end; end; % outputs % ------- outstr = ''; if ~popup for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end; if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end; end; % plot the datas and generate output command % -------------------------------------------- if length( options ) < 2 options = ''; end; if nargin < 4 varargout{1} = sprintf('figure; pop_timef( %s, %d, %d, %s, %s %s);', inputname(1), typeproc, num, ... vararg2str({tlimits}), vararg2str({cycles}), options); end; com = sprintf('%s timef( tmpsig(:, :), length(pointrange), [tlimits(1) tlimits(2)], EEG.srate, cycles %s);', outstr, options); eval(com) return; % get contextual help % ------------------- function txt = context(var, allvars, alltext); loc = strmatch( var, allvars); if ~isempty(loc) txt= alltext{loc(1)}; else disp([ 'warning: variable ''' var ''' not found']); txt = ''; end;
github
lcnbeapp/beapp-master
eeg_chantype.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/eeg_chantype.m
2,353
utf_8
cc106eb578fad38a9d0ce04e66c68cc5
% eeg_chantype() - Returns the channel indices of the desired channel type(s). % % Usage: % >> indices = eeg_chantype(struct, types ) % % Inputs: % struct - EEG.chanlocs data structure returned by readlocs() containing % channel location, type and gain information. % % Optional input % types - [cell array] cell array containing types ... % % Output: % indices - % % Author: Toby Fernsler, Arnaud Delorme, Scott Makeig % % See also: topoplot() % Copyright (C) 2005 Toby Fernsler, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function indices = eeg_chantype(data,chantype) if nargin < 1 help eeg_chantype; end; if ischar(chantype), chantype = cellstr(chantype); end if ~iscell(chantype), error( 'chantype must be cell array, e.g. {''EEG'', ''EOG''}, or single character string, e.g.''EEG''.'); end % Define 'datatype' variable, listing the type of each channel. % ------------------------------------------------------------ if isfield(data,'type') datatype = {data.type}; elseif isfield(data,'chanlocs') & isfield(data.chanlocs,'type') datatype = {data.chanlocs.type}; else error('Incorrect ''data'' input. Should be ''EEG'' or ''loc_file'' structure variable in the format associated with EEGLAB.'); end % seach for types % --------------- k = 1; plotchans = []; for i = 1:length(chantype) for j = 1:length(datatype) if strcmpi(chantype{i},char(datatype{j})) plotchans(k) = j; k = k + 1; end; end end indices = sort(plotchans);
github
lcnbeapp/beapp-master
eeg_eegrej.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/eeg_eegrej.m
8,907
utf_8
ec782c68ea906075cf66532189b71e35
% eeg_eegrej() - reject porition of continuous data in an EEGLAB % dataset % % Usage: % >> EEGOUT = eeg_eegrej( EEGIN, regions ); % % Inputs: % INEEG - input dataset % regions - array of regions to suppress. number x [beg end] of % regions. 'beg' and 'end' are expressed in term of points % in the input dataset. Size of the array is % number x 2 of regions. % % Outputs: % INEEG - output dataset with updated data, events latencies and % additional boundary events. % % Author: Arnaud Delorme, CNL / Salk Institute, 8 August 2002 % % See also: eeglab(), eegplot(), pop_rejepoch() % Copyright (C) 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, com] = eeg_eegrej( EEG, regions); com = ''; if nargin < 2 help eeg_eegrej; return; end; if nargin<3 probadded = []; end if isempty(regions) return; end; % regions = sortrows(regions,3); % Arno and Ramon on 5/13/2014 for bug 1605 % Ramon on 5/29/2014 for bug 1619 if size(regions,2) > 2 regions = sortrows(regions,3); else regions = sortrows(regions,1); end; try % For AMICA probabilities...Temporarily add model probabilities as channels %----------------------------------------------------- if isfield(EEG.etc, 'amica') && ~isempty(EEG.etc.amica) && isfield(EEG.etc.amica, 'v_smooth') && ~isempty(EEG.etc.amica.v_smooth) && ~isfield(EEG.etc.amica,'prob_added') if isfield(EEG.etc.amica, 'num_models') && ~isempty(EEG.etc.amica.num_models) if size(EEG.data,2) == size(EEG.etc.amica.v_smooth,2) && size(EEG.data,3) == size(EEG.etc.amica.v_smooth,3) && size(EEG.etc.amica.v_smooth,1) == EEG.etc.amica.num_models EEG = eeg_formatamica(EEG); %------------------------------------------- [EEG com] = eeg_eegrej(EEG,regions); %------------------------------------------- EEG = eeg_reformatamica(EEG); EEG = eeg_checkamica(EEG); return; else disp('AMICA probabilities not compatible with size of data, probabilities cannot be epoched') disp('Load AMICA components before extracting epochs') disp('Resuming rejection...') end end end % ------------------------------------------------------ catch warnmsg = strcat('your dataset contains amica information, but the amica plugin is not installed. Continuing and ignoring amica information.'); warning(warnmsg) end if isfield(EEG.event, 'latency'), tmpevent = EEG.event; tmpdata = EEG.data; % REMOVE THIS, THIS IS FOR DEBUGGING % tmpalllatencies = [ tmpevent.latency ]; else tmpalllatencies = []; end; % handle regions from eegplot % --------------------------- if size(regions,2) > 2, regions = regions(:, 3:4); end; regions = combineregions(regions); [EEG.data, EEG.xmax, event2, boundevents] = eegrej( EEG.data, regions, EEG.xmax-EEG.xmin, EEG.event); oldEEGpnts = EEG.pnts; oldEEGevents = EEG.event; EEG.pnts = size(EEG.data,2); EEG.xmax = EEG.xmax+EEG.xmin; % add boundary events % ------------------- [ EEG.event ] = eeg_insertbound(EEG.event, oldEEGpnts, regions); EEG = eeg_checkset(EEG, 'eventconsistency'); if ~isempty(EEG.event) && EEG.trials == 1 && EEG.event(end).latency > EEG.pnts EEG.event(end) = []; % remove last event if necessary end; % double check event latencies % the function that insert boundary events and recompute latency is % delicate so we do it twice using different methods and check % the results. It is longer, but accuracy is paramount. if isfield(EEG.event, 'latency') && length(EEG.event) < 3000 % assess difference between old and new event latencies [ eventtmp ] = eeg_insertboundold(oldEEGevents, oldEEGpnts, regions); if ~isempty(eventtmp) && length(eventtmp) > length(EEG.event) && isfield(eventtmp, 'type') && isequal(eventtmp(1).type, 'boundary') eventtmp(1) = []; end if isfield(eventtmp, 'duration') for iEvent=1:length(eventtmp) if isempty(eventtmp(iEvent).duration) eventtmp(iEvent).duration = 0; end end end differs = 0; for iEvent=1:min(length(EEG.event), length(eventtmp)-1) if ~issameevent(EEG.event(iEvent), eventtmp(iEvent)) && ~issameevent(EEG.event(iEvent), eventtmp(iEvent+1)) differs = differs+1; end end if 100*differs/length(EEG.event) > 50 fprintf(['BUG 1971 WARNING: IF YOU ARE USING A SCRIPT WITTEN FOR A PREVIOUS VERSION OF\n' ... 'EEGLAB TO CALL THIS FUNCTION, BECAUSE YOU ARE REJECTING THE ONSET OF THE DATA,\n' ... 'EVENTS WERE CORRUPTED. EVENT LATENCIES ARE NOW CORRECT (SEE https://sccn.ucsd.edu/wiki/EEGLAB_bug1971);\n' ]); end alllats = [ EEG.event.latency ]; if ~isempty(event2) otherlatencies = [event2.latency]; if ~isequal(alllats, otherlatencies) warning([ 'Discrepency when recomputing event latency.' 10 'Try to reproduce the problem and send us your dataset' ]); end end end % double check boundary event latencies if ~isempty(EEG.event) && length(EEG.event) < 3000 && ischar(EEG.event(1).type) && isfield(EEG.event, 'duration') && isfield(event2, 'duration') try indBound1 = find(cellfun(@(x)strcmpi(num2str(x), 'boundary'), { EEG.event(:).type })); indBound2 = find(cellfun(@(x)strcmpi(num2str(x), 'boundary'), { event2(:).type })); duration1 = [EEG.event(indBound1).duration]; duration1(isnan(duration1)) = []; duration2 = [event2(indBound2).duration]; duration2(isnan(duration2)) = []; if ~isequal(duration1, duration2) warning(['Inconsistency in boundary event duration.' 10 'Try to reproduce the problem and send us your dataset' ]); end; catch, warning('Unknown error when checking event latency - please send us your dataset'); end; end; % debuging code below % regions, n1 = 1525; n2 = 1545; n = n2-n1+1; % a = zeros(1,n); a(:) = 1; a(strmatch('boundary', { event2(n1:n2).type })') = 8; % [[n1:n2]' alllats(n1:n2)' [event2(n1:n2).latency]' alllats(n1:n2)'-[event2(n1:n2).latency]' otherorilatencies(n1:n2)' a'] % figure; ev = 17; range = [-1000:1000]; plot(EEG.data(1,EEG.event(ev).latency+range)); hold on; plot(tmpdata(1,tmpevent(EEG.event(ev).urevent).latency+range+696), 'r'); grid on; com = sprintf('%s = eeg_eegrej( %s, %s);', inputname(1), inputname(1), vararg2str({ regions })); % combine regions if necessary % it should not be necessary but a % bug in eegplot makes that it sometimes is % ---------------------------- % function newregions = combineregions(regions) % newregions = regions; % for index = size(regions,1):-1:2 % if regions(index-1,2) >= regions(index,1) % disp('Warning: overlapping regions detected and fixed in eeg_eegrej'); % newregions(index-1,:) = [regions(index-1,1) regions(index,2) ]; % newregions(index,:) = []; % end; % end; function res = issameevent(evt1, evt2) res = true; if isequal(evt1,evt2) return; elseif isfield(evt1, 'duration') && isnan(evt1.duration) && isfield(evt2, 'duration') && isnan(evt2.duration) evt1.duration = 1; evt2.duration = 1; if isequal(evt1,evt2) return; end; end; res = false; return; function newregions = combineregions(regions) % 9/1/2014 RMC regions = sortrows(sort(regions,2)); % Sorting regions allreg = [ regions(:,1)' regions(:,2)'; ones(1,numel(regions(:,1))) -ones(1,numel(regions(:,2)')) ].'; allreg = sortrows(allreg,1); % Sort all start and stop points (column 1), mboundary = cumsum(allreg(:,2)); % Rationale: regions will start always with 1 and close with 0, since starts=1 end=-1 indx = 0; count = 1; while indx ~= length(allreg) newregions(count,1) = allreg(indx+1,1); [tmp,I]= min(abs(mboundary(indx+1:end))); newregions(count,2) = allreg(I + indx,1); indx = indx + I ; count = count+1; end % Verbose if size(regions,1) ~= size(newregions,1) disp('Warning: overlapping regions detected and fixed in eeg_eegrej'); end
github
lcnbeapp/beapp-master
eeg_point2lat.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/eeg_point2lat.m
3,118
utf_8
e0dbc1311eceee071f6dcfb1dfcfb9bb
% eeg_point2lat() - convert latency in data points to latency in ms relative % to the time locking. Used in eeglab(). % Usage: % >> [newlat ] = eeg_point2lat( lat_array, [], srate); % >> [newlat ] = eeg_point2lat( lat_array, epoch_array,... % srate, timelimits, timeunit); % Inputs: % lat_array - latency array in data points assuming concatenated % data epochs (see eeglab() event structure) % epoch_array - epoch number corresponding to each latency value % srate - data sampling rate in Hz % timelimits - [min max] timelimits in 'timeunit' units (see below) % timeunit - time unit in second. Default is 1 = seconds. % % Outputs: % newlat - converted latency values (in 'timeunit' units) for each epoch % % Example: % tmpevent = EEG.event; % eeg_point2lat( [ tmpevent.latency ], [], EEG.srate, [EEG.xmin EEG.xmax]); % % returns the latency of all events in second for a continuous % % dataset EEG % % eeg_point2lat( [ tmpevent.latency ], [ tmpevent.epoch ], % EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3); % % returns the latency of all events in millisecond for a dataset % % containing data epochs. % % % Author: Arnaud Delorme, CNL / Salk Institute, 2 Mai 2002 % % See also: eeg_lat2point(), eeglab(), pop_editieventvals(), pop_loaddat() % Copyright (C) 2 Mai 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function newlat = eeg_point2lat( lat_array, epoch_array, srate, timewin, timeunit); if nargin <3 help eeg_point2lat; return; end; if isempty( epoch_array ) epoch_array = ones( size(lat_array) ); end; if nargin <4 timewin = 0; end; if nargin <5 timeunit = 1; end; if length(lat_array) ~= length(epoch_array) if length(epoch_array)~= 1 disp('eeg_point2lat: latency and epoch arrays must have the same length'); return; else epoch_array = ones(1,length(lat_array))*epoch_array; end; end; if length(timewin) ~= 2 disp('eeg_point2lat: timelimits array must have length 2'); return; end; if iscell(epoch_array) epoch_array = [ epoch_array{:} ]; end; if iscell(lat_array) lat_array = [ lat_array{:} ]; end timewin = timewin*timeunit; if length(timewin) == 2 pnts = (timewin(2)-timewin(1))*srate+1; else pnts = 0; end; newlat = ((lat_array - (epoch_array-1)*pnts-1)/srate+timewin(1))/timeunit; newlat = round(newlat*1E9)*1E-9;
github
lcnbeapp/beapp-master
pop_averef.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_averef.m
2,591
utf_8
13d6362c4bcdd4d0c831e5b62379549f
% pop_averef() - Convert an EEG dataset to average reference. % This function is obsolete. See pop_reref() instead. % % Usage: % >> EEGOUT = pop_averef( EEG ); % % Author: Arnaud Delorme, CNL / Salk Institute, 22 March 2002 % % See also: eeglab(), reref(), averef() % Copyright (C) 22 March 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, com] = pop_averef( EEG, confirm); [EEG, com] = pop_reref(EEG, []); return; com = ''; if nargin < 1 help pop_averef; return; end; if isempty(EEG.data) error('Pop_averef: cannot process empty data'); end; if nargin < 2 | confirm == 1 % which set to save % ----------------- ButtonName=questdlg2( strvcat('Convert the data to average reference?', ... 'Note: ICA activations will also be converted if they exist...'), ... 'Average reference confirmation -- pop_averef()', 'Cancel', 'Yes','Yes'); switch lower(ButtonName), case 'cancel', return; end; confirm = 0; end; EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts*EEG.trials); if ~isempty(EEG.icaweights) disp('pop_averef(): converting ICA weight matrix to average reference (see >> help averef)'); [EEG.data EEG.icaweights EEG.icasphere EEG.rmave] = averef(EEG.data,EEG.icaweights,EEG.icasphere); EEG.icawinv = []; if size(EEG.icaweights,1) > EEG.nbchan disp('Warning: one or more channels may have been removed; component weight re-referencing may be inaccurate'); end; if size(EEG.icasphere,1) < EEG.nbchan disp('Warning: one or more components may have been removed; component weight re-referencing could be inaccurate'); end; else EEG.data = averef(EEG.data); end; EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts, EEG.trials); EEG.averef = 'Yes'; EEG.icaact = []; EEG = eeg_checkset(EEG); com = sprintf('%s = pop_averef( %s, %d);', inputname(1), inputname(1), confirm); return;
github
lcnbeapp/beapp-master
eeg_matchchans.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/eeg_matchchans.m
5,088
utf_8
070c5b272529f4f74dc88932ce5baa77
% eeg_matchchans() - find closest channels in a larger EEGLAB chanlocs structure % to channels in a smaller chanlocs structure % Usage: % >> [selchans,distances,selocs] = eeg_matchchans(BIGlocs,smalllocs,'noplot'); % Inputs: % BIGlocs - larger (or equal-sized) EEG.chanlocs structure array % smalllocs - smaller (or equal-sized) EEG.chanlocs structure array % Optional inputs: % 'noplot' - [optional string 'noplot'] -> do not produce plots {default: % produce illustrative plots of the BIG and small locations} % Outputs: % selchans - indices of BIGlocs channels closest to the smalllocs channels % distances - vector of distances between the selected BIGlocs and smalllocs chans % selocs - EEG.chanlocs structure array containing nearest BIGlocs channels % to each smalllocs channel: 1, 2, 3,... n. This structure has % two extra fields: % bigchan - original channel index in BIGlocs % bigdist - distance between bigchan and smalllocs chan % ==> bigdist assumes both input locs have sph_radius 1. % % Author: Scott Makeig, SCCN/INC/UCSD, April 9, 2004 % Copyright (C) 2004 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % History: began Jan 27, 2004 as selectchans.m(?) -sm function [selchans,dists,selocs] = eeg_matchchans(bglocs,ltlocs,noplot) if nargin < 2 help eeg_matchchans return end no_plot = 0; % yes|no flag if nargin > 2 & strcmp(lower(noplot),'noplot') no_plot = 1; end if ~isstruct(bglocs) | ~isstruct(ltlocs) help eeg_matchchans end ltchans = length(ltlocs); bgchans = length(bglocs); if ltchans > bgchans fprintf('BIGlocs chans (%d) < smalllocs chans (%d)\n',bgchans,ltchans); return end selchans = zeros(ltchans,1); dists = zeros(ltchans,1); bd = zeros(bgchans,1); % %%%%%%%%%%%%%%%%% Compute the distances %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fprintf('BIG ltl Dist\n'); for c=1:ltchans for C=1:bgchans if ~isempty(ltlocs(c).X) & ~isempty(bglocs(C).X) bd(C) = sqrt((ltlocs(c).X/ltlocs(c).sph_radius - bglocs(C).X/bglocs(C).sph_radius)^2 + ... (ltlocs(c).Y/ltlocs(c).sph_radius - bglocs(C).Y/bglocs(C).sph_radius)^2 + ... (ltlocs(c).Z/ltlocs(c).sph_radius - bglocs(C).Z/bglocs(C).sph_radius)^2); end end % %%%%%%%%%%%%%%%%% Find the nearest BIGlocs channel %%%%%%%%%%%%%%%%%%%%%%% % [bd ix] = sort(bd); % find smallest distance c <-> C bglocs(1).bigchan = []; k=1; while ~isempty(bglocs(ix(k)).bigchan) & k<=bgchans % avoid empty channels k=k+1; end if k>bgchans fprintf('No match found for smalllocs channel %d - error!?\n',c); return % give up - should not reach here! end while k<length(ix) if c>1 & sum(ismember(ix(k),selchans(1:c-1)))>0 % avoid chans already chosen k = k+1; else break end end if k==length(ix) fprintf('NO available nearby channel for littlechan %d - using %d\n',... c,ix(k)); end selchans(c) = ix(k); % note the nearest BIGlocs channel dists(c) = bd(k); % note its distance bglocs(ix(k)).bigchan = selchans(c); % add this info to the output bglocs(ix(k)).bigdist = dists(c); fprintf('.bigchan %4d, c %4d, k %d, .bigdist %3.2f\n',... bglocs(ix(k)).bigchan,c,k,bglocs(ix(k)).bigdist); % commandline printout end; % c selocs = bglocs(selchans); % return the selected BIGlocs struct array subset % %%%%%%%%%%%%%%%%% Plot the results %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if ~no_plot figure; titlestring = sprintf('%d-channel subset closest to %d channel locations',ltchans,bgchans); tl=textsc(titlestring,'title'); set(tl,'fontweight','bold'); set(tl,'fontsize',15); sbplot(7,2,[3 13]); hist(dists,length(dists)); title('Distances between corresponding channels'); xlabel('Euclidian distance (sph. rad. 1)'); ylabel('Number of channels'); sbplot(7,5,[8,35]); topoplot(dists,selocs,'electrodes','numbers','style','both'); title('Distances'); clen = size(colormap,1); sbnull = sbplot(7,2,[10 12]) cb=cbar; cbar(cb,[clen/2+1:clen]); set(sbnull,'visible','off') axcopy; % turn on axcopy end
github
lcnbeapp/beapp-master
eeg_insertbound.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/eeg_insertbound.m
5,043
utf_8
a3e502740369f695218d0309e13a6578
% eeg_insertbound() - insert boundary event in an EEG event structure. % % Usage: % >> [eventout indnew] = eeg_insertbound( eventin, pnts, ... % abslatency, duration); % Required Inputs: % eventin - EEGLAB event structure (EEG.event) % pnts - data points in EEG dataset (EEG.pnts * EEG.trials) % abslatency - absolute latency of regions in original dataset. Can % also be an array of [beg end] latencies with one row % per region removed. Then 'lengths' argument is ignored. % Optional Inputs: % lengths - lengths of removed regions % % Outputs: % eventout - EEGLAB event output structure with added boundaries % indnew - Indices of the new events % % Notes: % This function performs the following: % 1) add boundary events to the 'event' structure; % remove nested boundaries; % recompute the latencies of all events. % 2) all latencies are given in (float) data points. % e.g., a latency of 2000.3 means 0.3 samples (at EEG.srate) % after the 2001st data frame (since first frame has latency 0). % % Author: Arnaud Delorme and Hilit Serby, SCCN, INC, UCSD, April, 19, 2004 % % See also: eeg_eegrej(), pop_mergeset() % Copyright (C) 2004 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [eventin, newind] = eeg_insertbound( eventin, pnts, regions, lengths) if nargin < 3 help eeg_insertbound; return; end; regions = round(regions); regions(regions < 1) = 1; regions(regions > pnts) = pnts; for i=2:size(regions,1) if regions(i-1,2) >= regions(i,1) regions(i,1) = regions(i-1,2)+1; end; end; if ~isempty(regions) fprintf('eeg_insertbound(): %d boundary (break) events added.\n', size(regions, 1)); else return; end; % recompute latencies of boundevents (in new dataset) % --------------------------------------------------- [tmp, tmpsort] = sort(regions(:,1)); regions = regions(tmpsort,:); lengths = regions(:,2)-regions(:,1)+1; if ~isempty(eventin) eventLatencies = [ eventin.latency ]; else eventLatencies = []; end; newEventLatencies = eventLatencies; oriLen = length(eventin); rmEvent = []; for iRegion = 1:size(regions,1) % sorted in decreasing order % find event succeding boundary to insert event % at the correct location in the event structure % ---------------------------------------------- tmpind = find( eventLatencies - regions(iRegion,1) > 0 ); newEventLatencies(tmpind) = newEventLatencies(tmpind)-lengths(iRegion); % insert event % ------------ [tmpnest, addlength ] = findnested(eventin, eventLatencies, regions(iRegion,:)); rmEvent = [ rmEvent tmpnest ]; if regions(iRegion,1)>1 eventin(end+1).type = 'boundary'; eventin(end).latency = regions(iRegion,1)-sum(lengths(1:iRegion-1))-0.5; eventin(end).duration = lengths(iRegion,1)+addlength; end; end % copy latencies % -------------- for iEvent = 1:oriLen eventin(iEvent).latency = newEventLatencies(iEvent); end; eventin(rmEvent) = []; % resort events % ------------- if ~isempty(eventin) && isfield(eventin, 'latency') eventin([ eventin.latency ] < 1) = []; alllatencies = [ eventin.latency ]; [tmp, sortind] = sort(alllatencies); eventin = eventin(sortind); newind = sortind(oriLen+1:end); end; if ~isempty(rmEvent) fprintf('eeg_insertbound(): event latencies recomputed and %d events removed.\n', length(rmEvent)); end; % look for nested events % retrun indices of nested events and % their total length % ----------------------------------- function [ indEvents, addlen ] = findnested(event, eventlat, region) indEvents = find( eventlat > region(1) & eventlat < region(2)); if ~isempty(event) && isstr(event(1).type) && isfield(event, 'duration') boundaryInd = strmatch('boundary', { event(indEvents).type }); addlen = sum( [ event(indEvents(boundaryInd)).duration ] ); else addlen = 0; end;
github
lcnbeapp/beapp-master
pop_reref.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_reref.m
12,991
utf_8
14d26bdeeaca5ad12a0890e8f01c25df
% pop_reref() - Convert an EEG dataset to average reference or to a % new common reference channel (or channels). Calls reref(). % Usage: % >> EEGOUT = pop_reref( EEG ); % pop up interactive window % >> EEGOUT = pop_reref( EEG, ref, 'key', 'val' ...); % % Graphic interface: % "Compute average reference" - [edit box] Checking this box (for 'yes') is % the same as giving an empty value for the commandline 'ref' % argument. Unchecked, the data are transformed to common reference. % "Re-reference data to channel(s)" - [checkbox] Checking this option % automatically unchecks the checkbox above, allowing reference % channel indices to be entered in the text edit box to its right % (No commandline equivalent). % "Retain old reference channels in data" - [checkbox] When re-referencing the % data, checking this checkbox includes the data for the % previous reference channel. % "Exclude channel indices (EMG, EOG)" - [edit box] exclude the given % channel indices from rereferencing. % "Add current reference channel back to the data" - [edit box] When % re-referencing the data, checking this checkbox % reconstitutes the data for the previous reference % channel. If the location for this channel was not % defined, it can be specified using the text box below. % Inputs: % EEG - input dataset % ref - reference: [] = convert to average reference % [int vector] = new reference electrode number(s) % Optional inputs: % 'exclude' - [integer array] List of channels to exclude. Default: none. % 'keepref' - ['on'|'off'] keep the reference channel. Default: 'off'. % 'refloc' - [structure] Previous reference channel structure. Default: none. % % Outputs: % EEGOUT - re-referenced output dataset % % Notes: % For other options, call reref() directly. See >> help reref % % Author: Arnaud Delorme, CNL / Salk Institute, 12 Nov 2002 % % See also: reref(), eeglab() % Copyright (C) 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, com] = pop_reref( EEG, ref, varargin); com = ''; if nargin < 1 help pop_reref; return; end; if isempty(EEG.data) error('Pop_reref: cannot process empty data'); end; % gui inputs % ---------- orichanlocs = EEG.chanlocs; orinbchan = EEG.nbchan; if nargin < 2 % find initial reference % ---------------------- if length(EEG.chanlocs) == EEG.nbchan+1 includeref = 1; end; geometry = { [1] [1] [1.8 1 0.3] [1] [1] [1.8 1 0.3] [1.8 1 0.3] }; cb_setref = [ 'set(findobj(''parent'', gcbf, ''tag'', ''refbr'') , ''enable'', ''on'');' ... 'set(findobj(''parent'', gcbf, ''tag'', ''reref'') , ''enable'', ''on'');' ... 'set(findobj(''parent'', gcbf, ''tag'', ''keepref'') , ''enable'', ''on'');' ]; cb_setave = [ 'set(findobj(''parent'', gcbf, ''tag'', ''refbr'') , ''enable'', ''off'');' ... 'set(findobj(''parent'', gcbf, ''tag'', ''reref'') , ''enable'', ''off'');' ... 'set(findobj(''parent'', gcbf, ''tag'', ''keepref'') , ''enable'', ''off'', ''value'', 0);' ]; cb_averef = [ 'set(findobj(''parent'', gcbf, ''tag'', ''rerefstr'') , ''value'', ~get(gcbo, ''value''));' ... 'if get(gcbo, ''value''),' cb_setave ... 'else,' cb_setref ... 'end;' ]; cb_ref = [ 'set(findobj(''parent'', gcbf, ''tag'', ''ave'') , ''value'', ~get(gcbo, ''value''));' ... 'if get(gcbo, ''value''),' cb_setref ... 'else,' cb_setave ... 'end;' ]; cb_chansel1 = 'tmpchanlocs = EEG(1).chanlocs; [tmp tmpval] = pop_chansel({tmpchanlocs.labels}, ''withindex'', ''on''); set(findobj(gcbf, ''tag'', ''reref'' ), ''string'',tmpval); clear tmpchanlocs tmp tmpval'; cb_chansel2 = 'tmpchanlocs = EEG(1).chanlocs; [tmp tmpval] = pop_chansel({tmpchanlocs.labels}, ''withindex'', ''on''); set(findobj(gcbf, ''tag'', ''exclude'' ), ''string'',tmpval); clear tmpchanlocs tmp tmpval'; cb_chansel3 = [ 'if ~isfield(EEG(1).chaninfo, ''nodatchans''), ' ... ' warndlg2(''There are no Reference channel defined, add it using the channel location editor'');' ... 'elseif isempty(EEG(1).chaninfo.nodatchans),' ... ' warndlg2(''There are no Reference channel defined, add it using the channel location editor'');' ... 'else,' ... ' tmpchaninfo = EEG(1).chaninfo; [tmp tmpval] = pop_chansel({tmpchaninfo.nodatchans.labels}, ''withindex'', ''on''); set(findobj(gcbf, ''tag'', ''refloc'' ), ''string'',tmpval); clear tmpchanlocs tmp tmpval;' ... 'end;' ]; if isempty(EEG.chanlocs), cb_chansel1 = ''; cb_chansel2 = ''; cb_chansel3 = ''; end; % find current reference (= reference most used) % ---------------------------------------------- if isfield(EEG(1).chanlocs, 'ref') tmpchanlocs = EEG(1).chanlocs; [curref tmp allinds] = unique_bc( { tmpchanlocs.ref }); maxind = 1; for ind = unique_bc(allinds) if length(find(allinds == ind)) > length(find(allinds == maxind)) maxind = ind; end; end; curref = curref{maxind}; if isempty(curref), curref = 'unknown'; end; else curref = 'unknown'; end; uilist = { { 'style' 'text' 'string' [ 'Current data reference state is: ' curref] } ... ... { 'style' 'checkbox' 'tag' 'ave' 'value' 1 'string' 'Compute average reference' 'callback' cb_averef } ... ... { 'style' 'checkbox' 'tag' 'rerefstr' 'value' 0 'string' 'Re-reference data to channel(s):' 'callback' cb_ref } ... { 'style' 'edit' 'tag' 'reref' 'string' '' 'enable' 'off' } ... { 'style' 'pushbutton' 'string' '...' 'callback' cb_chansel1 'enable' 'off' 'tag' 'refbr' } ... ... {} ... ... { 'style' 'checkbox' 'value' 0 'enable' 'off' 'tag' 'keepref' 'string' 'Retain old reference channels in data' } ... ... { 'style' 'text' 'string' 'Exclude channel indices (EMG, EOG)' } ... { 'style' 'edit' 'tag' 'exclude' 'string' '' } ... { 'style' 'pushbutton' 'string' '...' 'callback' cb_chansel2 } ... ... { 'style' 'text' 'tag' 'reflocstr' 'string' 'Add current reference channel back to the data' } ... { 'style' 'edit' 'tag' 'refloc' 'string' '' } ... { 'style' 'pushbutton' 'string' '...' 'callback' cb_chansel3 } }; [result tmp tmp2 restag] = inputgui(geometry, uilist, 'pophelp(''pop_reref'')', 'pop_reref - average reference or re-reference data'); if isempty(result), return; end; % decode inputs % ------------- options = {}; if ~isempty(restag.refloc), try tmpchaninfo = EEG.chaninfo; tmpallchans = lower({ tmpchaninfo.nodatchans.labels }); allelecs = parsetxt(lower(restag.refloc)); chanind = []; for iElec = 1:length(allelecs) chanind = [chanind strmatch( allelecs{iElec}, tmpallchans, 'exact') ]; end; options = { options{:} 'refloc' EEG.chaninfo.nodatchans(chanind) }; catch, disp('Error with old reference: ignoring it'); end; end; if ~isempty(restag.exclude), options = { options{:} 'exclude' eeg_chaninds(EEG, restag.exclude) }; end; if restag.keepref, options = { options{:} 'keepref' 'on' }; end; if restag.ave, ref = []; end; if restag.rerefstr if isempty(restag.reref) warndlg2('Abording: you must enter one or more reference channels'); return; else ref = eeg_chaninds(EEG, restag.reref); end; end; else options = varargin; end; optionscall = options; % include channel location file % ----------------------------- if ~isempty(EEG.chanlocs) optionscall = { optionscall{:} 'elocs' EEG.chanlocs }; end; nchans = EEG.nbchan; fprintf('Re-referencing data\n'); oldchanlocs = EEG.chanlocs; [EEG.data EEG.chanlocs refchan ] = reref(EEG.data, ref, optionscall{:}); g = struct(optionscall{:}); if ~isfield(g, 'exclude'), g.exclude = []; end; if ~isfield(g, 'keepref'), g.keepref = 'off'; end; if ~isfield(g, 'refloc') , g.refloc = []; end; % deal with reference % ------------------- if ~isempty(refchan) if ~isfield(EEG.chaninfo, 'nodatchans') EEG.chaninfo.nodatchans = refchan; elseif isempty(EEG.chaninfo.nodatchans) EEG.chaninfo.nodatchans = refchan; else allf = fieldnames(refchan); n = length(EEG.chaninfo.nodatchans); for ind = 1:length(allf) EEG.chaninfo.nodatchans = setfield(EEG.chaninfo.nodatchans, { n }, ... allf{ind}, getfield(refchan, allf{ind})); end; end; end; if ~isempty(g.refloc) allinds = []; tmpchaninfo = EEG.chaninfo; for iElec = 1:length(g.refloc) allinds = [allinds strmatch( g.refloc(iElec).labels, { tmpchaninfo.nodatchans.labels }) ]; end; EEG.chaninfo.nodatchans(allinds) = []; end; % legacy EEG.ref field % -------------------- if isfield(EEG, 'ref') if strcmpi(EEG.ref, 'common') && isempty(ref) EEG.ref = 'averef'; elseif strcmpi(EEG.ref, 'averef') && ~isempty(ref) EEG.ref = 'common'; end; end; EEG.nbchan = size(EEG.data,1); EEG = eeg_checkset(EEG); % include ICA or not % ------------------ if ~isempty(EEG.icaweights) if ~isempty(intersect(EEG.icachansind, g.exclude)) disp('Warning: some channels used for ICA were excluded from referencing'); disp(' the ICA decomposition has been removed'); EEG.icaweights = []; EEG.icasphere = []; elseif length(EEG.icachansind) ~= nchans - length(g.exclude) disp('Error: some channels not used for ICA decomposition are used for rereferencing'); disp(' the ICA decomposition has been removed'); EEG.icaweights = []; EEG.icasphere = []; else fprintf('Re-referencing ICA matrix\n'); if isempty(orichanlocs) error('Cannot re-reference ICA decomposition without channel locations') end; newICAchaninds = zeros(orinbchan, size(EEG.icawinv,2)); newICAchaninds(EEG.icachansind,:) = EEG.icawinv; [newICAchaninds newchanlocs] = reref(newICAchaninds, ref, optionscall{:}); % convert channel indices in icachanlocs (uses channel labels) % ------------------------------------------------------------ icachansind = EEG.icachansind; rminds = [1:size(newICAchaninds,1)]; for i=length(icachansind):-1:1 oldLabel = orichanlocs(icachansind(i)).labels; newLabelPos = strmatch(oldLabel, { newchanlocs.labels }, 'exact'); if ~isempty( newLabelPos ) icachansind(i) = newLabelPos; rminds(find(icachansind(i) == rminds)) = []; else icachansind(i) = []; end; end; newICAchaninds(rminds,:) = []; EEG.icawinv = newICAchaninds; EEG.icachansind = icachansind; if length(EEG.icachansind) ~= size(EEG.icawinv,1) warning('Wrong channel indices, removing ICA decomposition'); EEG.icaweights = []; EEG.icasphere = []; else EEG.icaweights = pinv(EEG.icawinv); EEG.icasphere = eye(length(icachansind)); end; end; EEG = eeg_checkset(EEG); end; % generate the output command % --------------------------- com = sprintf('%s = pop_reref( %s, %s);', inputname(1), inputname(1), vararg2str({ref, options{:}}));
github
lcnbeapp/beapp-master
eeg_dipselect.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/eeg_dipselect.m
2,895
utf_8
b9770dbf991cd2bc42e30f80792ce7a4
% eeg_dipselect() - select componet dipoles from an EEG dataset with % reisdual variance (rv) less than a selected threshold % and equivalent dipole location inside the brain volume. % Usage: % >> selctedComponents = eeg_dipselect(EEG, rvThreshold, selectionType, depthThreshold) % % Inputs: % EEG - EEGLAB dataset structure % % Optional Inputs % rvThreshold - residual variance threshold (%). Dipoles with residual variance % less than this value will be selected. {default = 15} % selectionType - criteria for selecting dipoles: % 'rv' = only by residual variance, % 'inbrain' = inside brain volume and residual variance. % {default = 'inbrain'} % % depthThreshold - maximum accepted distance outside brain volume (mm) {default = 1} % % Outputs: % selctedComponents - vector of selected components % % Example: % >> selctedComponents = eeg_dipselect(EEG) % select in-brain dipoles with rv less than 0.15 (default value) % >> selctedComponents = eeg_dipselect(EEG, 20,'rv') % select dipoles with rv less than 0.2 % % Author: Nima Bigdely Shamlo, Copyright (C) September 2007 % based on an script from Julie Onton and sourcedepth() function % provided by Robert Oostenveld. % % See also: sourcedepth() function brainComponents = eeg_dipselect(EEG, rvThreshold, selectionType, depthThreshold); if nargin<2 rvThreshold = 0.15; fprintf('Maximum residual variance for selected dipoles set to %1.2f (default).\n',rvThreshold); else rvThreshold = rvThreshold/100; % change from percent to value if rvThreshold>1 error('Error: residual variance threshold should be less than 1.\n'); end; end if nargin<4 depthThreshold = 1; end; % find components with low residual variance for ic = 1:length(EEG.dipfit.model) residualvariance(1,ic) =EEG.dipfit.model(ic).rv; end; compLowResidualvariance = find(residualvariance <rvThreshold); if isempty(compLowResidualvariance) || ( (nargin>=3) && strcmp(selectionType, 'rv')) % if only rv is requested (not in-brain) brainComponents = compLowResidualvariance; return; else if ~exist('ft_sourcedepth') selectionType = 'rv'; tmpWarning = warning('backtrace'); warning backtrace off; warning('You need to install the Fieldtrip extension to be able to select "in brain" dipoles'); warning(tmpWarning); brainComponents = compLowResidualvariance; return; end; load(EEG.dipfit.hdmfile); posxyz = []; for c = compLowResidualvariance posxyz = cat(1,posxyz,EEG.dipfit.model(c).posxyz(1,:)); end; depth = ft_sourcedepth(posxyz, vol); brainComponents = compLowResidualvariance(find(depth<=depthThreshold)); end;
github
lcnbeapp/beapp-master
pop_loadcnt.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_loadcnt.m
9,914
utf_8
196225b3e7d78dc84817620c2a7cffab
% pop_loadcnt() - load a neuroscan CNT file (pop out window if no arguments). % % Usage: % >> EEG = pop_loadcnt; % pop-up window mode % >> EEG = pop_loadcnt( filename, 'key', 'val', ...); % % Graphic interface: % "Data fomat" - [checkbox] 16-bits or 32-bits. We couldn't find in the % data file where this information was stored. Command % line equivalent in loadcnt() 'dataformat'. % "Time interval in seconds" - [edit box] specify time interval [min max] % to import portion of data. Command line equivalent % in loadcnt: 't1' and 'lddur' % "Import keystrokes" - [checkbox] set this option to import keystroke % event types in dataset. Command line equivalent % 'keystroke'. % "loadcnt() 'key', 'val' params" - [edit box] Enter optional loadcnt() % parameters. % % Inputs: % filename - file name % % Optional inputs: % 'keystroke' - ['on'|'off'] set the option to 'on' to import % keystroke event types. Default is off. % 'memmapfile' - ['memmapfile_name'] use this option if the .cnt file % is too large to read in conventially. The suffix of % the memmapfile_name must be .fdt. the memmapfile % functions process files based on their suffix and an % error will occur if you use a different suffix. % Same as loadcnt() function. % % Outputs: % EEG - EEGLAB data structure % % Note: % 1) This function extract all non-null event from the CNT data structure. % Null events are usually associated with internal signals (recalibrations...). % 2) The "Average reference" edit box had been remove since the re-referencing % menu of EEGLAB offers more options to re-reference data. % 3) The 'blockread' has been disabled since we found where this information % was stored in the file. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: loadcnt(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad function [EEG, command] = pop_loadcnt(filename, varargin); command = ''; EEG = []; if nargin < 1 % ask user [filename, filepath] = uigetfile('*.CNT;*.cnt', 'Choose a CNT file -- pop_loadcnt()'); drawnow; if filename == 0 return; end; % popup window parameters % ----------------------- callback16 = 'set(findobj(gcbf, ''tag'', ''B32''), ''value'', ~get(gcbo, ''value'')); set(findobj(gcbf, ''tag'', ''AD''), ''value'', ~get(gcbo, ''value''));'; callback32 = 'set(findobj(gcbf, ''tag'', ''B16''), ''value'', ~get(gcbo, ''value'')); set(findobj(gcbf, ''tag'', ''AD''), ''value'', ~get(gcbo, ''value''));'; callbackAD = 'set(findobj(gcbf, ''tag'', ''B16''), ''value'', ~get(gcbo, ''value'')); set(findobj(gcbf, ''tag'', ''B32''), ''value'', ~get(gcbo, ''value''));'; uigeom = { [1.3 0.5 0.5 0.5] [1 0.5] [1.09 0.13 0.4] [1 0.5] [1 0.5] 1 } ; uilist = { { 'style' 'text' 'string' 'Data format 16 or 32 bit (Default = Autodetect)' } ... { 'style' 'checkbox' 'tag' 'B16' 'string' '16-bits' 'value' 0 'callback' callback16 } ... { 'style' 'checkbox' 'tag' 'B32' 'string' '32-bits' 'value' 0 'callback' callback32 } ... { 'style' 'checkbox' 'tag' 'AD' 'string' 'Autodetect' 'value' 1 'callback' callbackAD } ... { 'style' 'text' 'string' 'Time interval in s (i.e. [0 100]):' } ... { 'style' 'edit' 'string' '' 'callback' 'warndlg2([ ''Events latency might be innacurate when'' 10 ''importing time intervals (this is an open issue)'']);' } ... { 'style' 'text' 'string' 'Check to Import keystrokes:' } ... { 'style' 'checkbox' 'string' '' } { } ... { 'style' 'text' 'string' 'loadcnt() ''key'', ''val'' params' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' [ 'Large files, enter a file name for memory mapping (xxx.fdt)' ] } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' ' Note: requires to enable memory mapping in EEGLAB memory options and only works for 32-bit files' } }; result = inputgui( uigeom, uilist, 'pophelp(''pop_loadcnt'')', 'Load a CNT dataset'); if length( result ) == 0 return; end; % decode parameters % ----------------- options = []; if result{1}, options = [ options ', ''dataformat'', ''int16''' ]; elseif result{2}, options = [ options ', ''dataformat'', ''int32''' ]; elseif result{3}, options = [ options ', ''dataformat'', ''auto''' ]; end; if ~isempty(result{4}), timer = eval( [ '[' result{4} ']' ]); options = [ options ', ''t1'', ' num2str(timer(1)) ', ''lddur'', ' num2str(timer(2)-timer(1)) ]; end; if result{5}, options = [ options ', ''keystroke'', ''on''' ]; end; if ~isempty(result{6}), options = [ options ',' result{6} ]; end; % Conditional pass if ~isempty(result{7}), options = ... % [options ', ''memmapfile''', result{7} ] ; end ; % Always pass the memmapfile paramter? options = [ options ', ''memmapfile'', ''', result{7} '''' ] ; else options = vararg2str(varargin); end; % load datas % ---------- EEG = eeg_emptyset; if exist('filepath') fullFileName = sprintf('%s%s', filepath, filename); else fullFileName = filename; end; if nargin > 0 if ~isempty(varargin) r = loadcnt( fullFileName, varargin{:}); else r = loadcnt( fullFileName); end; else eval( [ 'r = loadcnt( fullFileName ' options ');' ]); end; if isfield(r, 'dat') error('pop_loadcnt is not compatible with current loadcnt version, please use latest loadcnt() version'); end; % Check to see if data is in memory or in a file. EEG.data = r.data; EEG.comments = [ 'Original file: ' fullFileName ]; EEG.setname = 'CNT file'; EEG.nbchan = r.header.nchannels; % inport events % ------------- I = 1:length(r.event); if ~isempty(I) EEG.event(1:length(I),1) = [ r.event(I).stimtype ]; EEG.event(1:length(I),2) = [ r.event(I).offset ]+1; EEG.event = eeg_eventformat (EEG.event, 'struct', { 'type' 'latency' }); end; % modified by Andreas Widmann 2005/05/12 14:15:00 try, % this piece of code makes the function crash sometimes - Arnaud Delorme 2006/04/27 temp = find([r.event.accept_ev1] == 14 | [r.event.accept_ev1] == 11); % 14: Discontinuity, 11: DC reset if ~isempty(temp) disp('pop_loadcnt note: event field ''type'' set to ''boundary'' for data discontinuities'); for index = 1:length(temp) EEG.event(temp(index)).type = 'boundary'; end; end catch, end; % end modification % process keyboard entries % ------------------------ if ~isempty(findstr('keystroke', lower(options))) tmpkbd = [ r.event(I).keyboard ]; tmpkbd2 = [ r.event(I).keypad_accept ]; for index = 1:length(EEG.event) if EEG.event(index).type == 0 if r.event(index).keypad_accept, EEG.event(index).type = [ 'keypad' num2str(r.event(index).keypad_accept) ]; else EEG.event(index).type = [ 'keyboard' num2str(r.event(index).keyboard) ]; end; end; end; else % removeing keystroke events % -------------------------- rmind = []; for index = 1:length(EEG.event) if EEG.event(index).type == 0 rmind = [rmind index]; end; end; if ~isempty(rmind) fprintf('Ignoring %d keystroke events\n', length(rmind)); EEG.event(rmind) = []; end; end; % import channel locations (Neuroscan coordinates are not wrong) % ------------------------ %x = celltomat( { r.electloc.x_coord } ); %y = celltomat( { r.electloc.y_coord } ); for index = 1:length(r.electloc) names{index} = deblank(char(r.electloc(index).lab')); if size(names{index},1) > size(names{index},2), names{index} = names{index}'; end; end; EEG.chanlocs = struct('labels', names); %EEG.chanlocs = readneurolocs( { names x y } ); %disp('WARNING: Electrode locations imported from CNT files may not reflect true locations'); % Check to see if data is in a file or in memory % If in memory, leave alone % If in a file, use values set in loadcnt.m for nbchan and pnts. EEG.srate = r.header.rate; EEG.nbchan = size(EEG.data,1) ; EEG.nbchan = r.header.nchannels ; % EEG.nbchan = size(EEG.data,1); EEG.trials = 1; EEG.pnts = r.ldnsamples ; %size(EEG.data,2) %EEG.pnts = r.header.pnts %size(EEG.data,2); EEG = eeg_checkset(EEG, 'eventconsistency'); EEG = eeg_checkset(EEG, 'makeur'); if ((size(EEG.data,1) ~= EEG.nbchan) && (size(EEG.data,2) ~= EEG.pnts)) % Assume a data file EEG = eeg_checkset(EEG, 'loaddata'); end if length(options) > 2 command = sprintf('EEG = pop_loadcnt(''%s'' %s);',fullFileName, options); else command = sprintf('EEG = pop_loadcnt(''%s'');',fullFileName); end; return;
github
lcnbeapp/beapp-master
eeg_amplitudearea.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/eeg_amplitudearea.m
7,019
utf_8
712e8efc8565d2b601dd9ec225a4d36c
% eeg_amplitudearea() - Resamples an ERP average using spline interpolation % at a new sample rate (resrate) in Hz to get the exact limits % of the window of integration. Finely samples the window % and adds together very narrow rectangles capped by % right-angled triangles under the window. Output is in uV. % Trade-off between speed and number of resamples and number of % channels selected occurs. % Usage: % >> [channels, amplitude] = eeg_amplitudearea(EEG,channels, resrate, wstart, wend); % Inputs: % EEG - EEGLAB data struct containing a (3-D) epoched data matrix % channels - vector of channel indices % resrate - resampling rate for window of integration in Hz % wstart - start of window of integration in ms post stimulus-onset % wend - end of window of integration in ms post stimulus-onset % % Outputs: % channels - a vector of channel indices. % amplitude - 1-dimensional array in uV for the channels % % Example % >> [channels, amplitude] = eeg_amplitudearea(EEG,[12 18 25 29], 2000, 90.52, 120.52); % % Author: Tom Campbell, Helsinki Collegium for Advanced Studies, Biomag Laboratory, % Engineering Centre, Helsinki University Central Hospital Helsinki Brain % Research Centre ([email protected]) Spartam nanctus es: Hanc exorna. % Combined with amplitudearea_msuV() by Darren Weber, UCSF 28/1/05 % Retested and debugged Tom Campbell 2/2/05 % Reconceived, factored somewhat, tested and debugged Tom Campbell 13:24 23.3.2005 function [channels,overall_amplitude] = eeg_amplitudearea2(EEG, channels, resrate, wstart, wend) if wstart > wend error ('ERROR: wstart must be greater than wend') else [channels, overall_amplitude] = eeg_amplitudearea_msuV (EEG,channels, resrate, wstart, wend) overall_amplitude = overall_amplitude/(wend - wstart) end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [channels, overall_area] = eeg_amplitudearea_msuV (EEG, channels, resrate, wstart, wend) %if ndim(EEG.data) ~= 3 % error('EEG.data must be 3-D data epochs'); %end erp = mean(EEG.data,3); [tmp ind1] =min( abs( EEG.times - wstart ) ); % closest time index to wstart [tmp ind2] =min( abs( EEG.times - wend ) ); % closest time index to wend restep = 1/resrate if EEG.times(ind1) > wstart ind1= ind1 -1; end if EEG.times(ind2) < wend ind2= ind2 +1; end for x= ind1:ind2 t = (x -ind1)+1; tim(t) = EEG.times(x); end tr = 1 timr(tr) = wstart; while timr(tr) < wend tr = tr + 1; timr(tr) = timr(tr-1)+ restep; end for x = 1:size(channels,2) channel = channels(x) %resamples rerp(x, 1:tr) = spline(tim(:),erp(channel, ind1:ind2), timr(1:tr)) pent = timr(tr - 1) overall_area(x) = 0 for y = 1:(tr -1) v1 = rerp(x,(y)) v2 = rerp(x,(y+1)) if ((v1 > 0) & (v2 < 0)) | ((v1 < 0) & (v2 > 0)) if (y == (tr-1)) & (timr(y+1)> wend) area1 = zero_crossing_truncated(v1, v2, restep, wend, pent) else area1 = zero_crossing(v1, v2, restep) end else if( y == (tr-1)) & (timr(y+1)> wend) area1 = rect_tri_truncated(v1, v2, restep,wend,pent) else area1 = rect_tri(v1, v2, restep) end end overall_area(x) = overall_area(x) + area1 end end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [area] = zero_crossing(v1,v2,step) if (v1 > v2) T1 = v1 T2 = v2 else T1 = v2 T2 = v1 end tantheta = (abs(T1)+ abs(T2))/step if (v1 > v2) %decline z = abs(T1)/tantheta tr1= abs(T1)*(z/2) tr2= abs(T2)*((step-z)/2) else %incline z = abs(T2)/tantheta tr2= abs(T2)*(z/2) tr1= abs(T1)*((step-z)/2) end [area] = (tr1 - tr2) return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [area] = zero_crossing_truncated(v1,v2,step,wend,pent) if (v1 > v2) T1 = v1 T2 = v2 else T1 = v2 T2 = v1 end tantheta = (abs(T1)+ abs(T2))/step s = wend - pent if (v1 > v2) z = abs(T1)/tantheta if s < z %decline,truncated before zerocrossing t1 = tantheta * s r1 = abs(T1)-abs(t1) tr1= abs(t1)*(s/2) tr2= 0 rect1 = r1*s rect2 = 0 else %decline,truncated after zerocrossing t2= tantheta*(s-z) tr1= abs(T1)*(z/2) tr2 = abs(t2)*((s-z)/2) rect1 = 0 rect2 = 0 end else z = abs(T2)/tantheta if s < z %incline,truncated before zerocrossing t2 = tantheta * s r2 = abs(T2)-abs(t2) tr1= 0 tr2= abs(t2)*(s/2) rect1 = 0 rect2 = r2*s else %incline,truncated after zerocrossing t1= tantheta*(s-z) tr1 = abs(t1)*((s-z)/2) tr2 = abs(T2) * (z/2) rect1 = 0 rect2 = 0 end end [area] = ((rect1 + tr1) - (rect2 + tr2)) return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [area] = rect_tri(v1,v2,step) if (abs(v1) > abs(v2)) T = abs(v1)-abs(v2) R = abs(v2) else T = abs(v2)-abs(v1) R = abs(v1) end rect = R*step tri = T*(step/2) if v1 > 0 area = 1* (rect+tri) else area = -1 * (rect+tri) end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [area] = rect_tri_truncated(v1,v2,step,wend,pent) if (abs(v1) > abs(v2)) T = abs(v1)-abs(v2) R = abs(v2) else T = abs(v2)-abs(v1) R = abs(v1) end tantheta = abs(T)/step s = wend -pent if (v1>0) if v1 >v2 %positive decline t = tantheta*s e = abs(T)-abs(t) rect = s*R exrect = s*e tri = (s/2)*R else %positive incline t = tantheta*s rect = s*R exrect = 0 tri = (s/2)*R end else if v1 >v2 %negative decline t = tantheta*s rect = s*R exrect = 0 tri = (s/2)*R else %negative incline t = tantheta*s e = abs(T)-abs(t) rect = s*R exrect = s*e tri = (s/2)*R end end tri = T*(step/2) if v1 > 0 area = 1* (rect+exrect+tri) else area = -1 * (rect+exrect+tri) end return
github
lcnbeapp/beapp-master
pop_eegplot.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_eegplot.m
9,395
utf_8
694d3469c8e08a65956f474715744049
% pop_eegplot() - Visually inspect EEG data using a scrolling display. % Perform rejection or marking for rejection of visually % (and/or previously) selected data portions (i.e., stretches % of continuous data or whole data epochs). % Usage: % >> pop_eegplot( EEG ) % Scroll EEG channel data. Allow marking for rejection via % % button 'Update Marks' but perform no actual data rejection. % % Do not show or use marks from previous visual inspections % % or from semi-auotmatic rejection. % >> pop_eegplot( EEG, icacomp, superpose, reject ); % % Graphic interface: % "Add to previously marked rejections" - [edit box] Either YES or NO. % Command line equivalent: 'superpose'. % "Reject marked trials" - [edit box] Either YES or NO. Command line % equivalent 'reject'. % Inputs: % EEG - input EEG dataset % icacomp - type of rejection 0 = independent components; % 1 = data channels. {Default: 1 = data channels} % superpose - 0 = Show new marks only: Do not color the background of data portions % previously marked for rejection by visual inspection. Mark new data % portions for rejection by first coloring them (by dragging the left % mouse button), finally pressing the 'Update Marks' or 'Reject' % buttons (see 'reject' below). Previous markings from visual inspection % will be lost. % 1 = Show data portions previously marked by visual inspection plus % data portions selected in this window for rejection (by dragging % the left mouse button in this window). These are differentiated % using a lighter and darker hue, respectively). Pressing the % 'Update Marks' or 'Reject' buttons (see 'reject' below) % will then mark or reject all the colored data portions. % {Default: 0, show and act on new marks only} % reject - 0 = Mark for rejection. Mark data portions by dragging the left mouse % button on the data windows (producing a background coloring indicating % the extent of the marked data portion). Then press the screen button % 'Update Marks' to store the data portions marked for rejection % (stretches of continuous data or whole data epochs). No 'Reject' button % is present, so data marked for rejection cannot be actually rejected % from this eegplot() window. % 1 = Reject marked trials. After inspecting/selecting data portions for % rejection, press button 'Reject' to reject (remove) them from the EEG % dataset (i.e., those portions plottted on a colored background. % {default: 1, mark for rejection only} % % topcommand - Input deprecated. Kept for compatibility with other function calls % Outputs: % Modifications are applied to the current EEG dataset at the end of the % eegplot() call, when the user presses the 'Update Marks' or 'Reject' button. % NOTE: The modifications made are not saved into EEGLAB history. As of v4.2, % events contained in rejected data portions are remembered in the EEG.urevent % structure (see EEGLAB tutorial). % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab(), eegplot(), pop_rejepoch() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-07-02 added srate argument to eegplot call -ad % 03-27-02 added event latency recalculation for continuous data -ad function com = pop_eegplot( EEG, icacomp, superpose, reject, topcommand, varargin) com = ''; if nargin < 1 help pop_eegplot; return; end; if nargin < 2 icacomp = 1; end; if nargin < 3 superpose = 0; end; if nargin < 4 reject = 1; end; if icacomp == 0 if isempty( EEG.icasphere ) disp('Error: you must run ICA first'); return; end; end; if nargin < 3 & EEG.trials > 1 % which set to save % ----------------- uilist = { { 'style' 'text' 'string' 'Add to previously marked rejections? (checked=yes)'} , ... { 'style' 'checkbox' 'string' '' 'value' 1 } , ... { 'style' 'text' 'string' 'Reject marked trials? (checked=yes)'} , ... { 'style' 'checkbox' 'string' '' 'value' 0 } }; result = inputgui( { [ 2 0.2] [ 2 0.2]} , uilist, 'pophelp(''pop_eegplot'');', ... fastif(icacomp==0, 'Manual component rejection -- pop_eegplot()', ... 'Reject epochs by visual inspection -- pop_eegplot()')); size_result = size( result ); if size_result(1) == 0 return; end; if result{1}, superpose=1; end; if ~result{2}, reject=0; end; end; if EEG.trials > 1 if icacomp == 1 macrorej = 'EEG.reject.rejmanual'; macrorejE = 'EEG.reject.rejmanualE'; else macrorej = 'EEG.reject.icarejmanual'; macrorejE = 'EEG.reject.icarejmanualE'; end; if icacomp == 1 elecrange = [1:EEG.nbchan]; else elecrange = [1:size(EEG.icaweights,1)]; end; colrej = EEG.reject.rejmanualcol; rej = eval(macrorej); rejE = eval(macrorejE); eeg_rejmacro; % script macro for generating command and old rejection arrays else % case of a single trial (continuous data) %if icacomp, % command = ['if isempty(EEG.event) EEG.event = [eegplot2event(TMPREJ, -1)];' ... % 'else EEG.event = [EEG.event(find(EEG.event(:,1) ~= -1),:); eegplot2event(TMPREJ, -1, [], [0.8 1 0.8])];' ... % 'end;']; %else, command = ['if isempty(EEG.event) EEG.event = [eegplot2event(TMPREJ, -1)];' ... % 'else EEG.event = [EEG.event(find(EEG.event(:,1) ~= -2),:); eegplot2event(TMPREJ, -1, [], [0.8 1 0.8])];' ... % 'end;']; %end; %if reject % command = ... % [ command ... % '[EEG.data EEG.xmax] = eegrej(EEG.data, EEG.event(find(EEG.event(:,1) < 0),3:end), EEG.xmax-EEG.xmin);' ... % 'EEG.xmax = EEG.xmax+EEG.xmin;' ... % 'EEG.event = EEG.event(find(EEG.event(:,1) >= 0),:);' ... % 'EEG.icaact = [];' ... % 'EEG = eeg_checkset(EEG);' ]; eeglab_options; % changed from eeglaboptions 3/30/02 -sm if reject == 0, command = []; else command = ... [ '[EEGTMP LASTCOM] = eeg_eegrej(EEG,eegplot2event(TMPREJ, -1));' ... 'if ~isempty(LASTCOM),' ... ' [ALLEEG EEG CURRENTSET tmpcom] = pop_newset(ALLEEG, EEGTMP, CURRENTSET);' ... ' if ~isempty(tmpcom),' ... ' EEG = eegh(LASTCOM, EEG);' ... ' eegh(tmpcom);' ... ' eeglab(''redraw'');' ... ' end;' ... 'end;' ... 'clear EEGTMP tmpcom;' ]; if nargin < 4 res = questdlg2( strvcat('Mark stretches of continuous data for rejection', ... 'by dragging the left mouse button. Click on marked', ... 'stretches to unmark. When done,press "REJECT" to', ... 'excise marked stretches (Note: Leaves rejection', ... 'boundary markers in the event table).'), 'Warning', 'Cancel', 'Continue', 'Continue'); if strcmpi(res, 'Cancel'), return; end; end; end; eegplotoptions = { 'events', EEG.event }; if ~isempty(EEG.chanlocs) & icacomp eegplotoptions = { eegplotoptions{:} 'eloc_file', EEG.chanlocs }; end; end; if EEG.nbchan > 100 disp('pop_eegplot() note: Baseline subtraction disabled to speed up display'); eegplotoptions = { eegplotoptions{:} 'submean' 'off' }; end; if icacomp == 1 eegplot( EEG.data, 'srate', EEG.srate, 'title', 'Scroll channel activities -- eegplot()', ... 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}, varargin{:}); else tmpdata = eeg_getdatact(EEG, 'component', [1:size(EEG.icaweights,1)]); eegplot( tmpdata, 'srate', EEG.srate, 'title', 'Scroll component activities -- eegplot()', ... 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}, varargin{:}); end; com = [ com sprintf('pop_eegplot( %s, %d, %d, %d);', inputname(1), icacomp, superpose, reject) ]; return;
github
lcnbeapp/beapp-master
pop_editset.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_editset.m
29,573
utf_8
d0871f09de508485acd7c591ec9228ae
% pop_editset() - Edit EEG dataset structure fields. % % Usage: % >> EEGOUT = pop_editset( EEG ); % pops-up a data entry window % >> EEGOUT = pop_editset( EEG, 'key', val,...); % no pop-up window % % Graphic interface: % "Dataset name" - [Edit box] Name for the new dataset. % In the right column of the graphic interface, the "EEG.setname" % text indicates which field of the EEG structure this parameter % corresponds to (in this case, .'setname'). % Command line equivalent: 'setname'. % "Data sampling rate" - [Edit box] In Hz. Command line equivalent: 'srate' % "Time points per epoch" - [Edit box] Number of data frames (points) per epoch. % Changing this value will change the number of data epochs. % Command line equivalent: 'pnts'. % "Start time" - [Edit box] This edit box is only present for epoched data % and specifies the epoch start time in ms. Epoch end time % is automatically calculated. Command line equivalent: 'xmin' % "Number of channels" - [Edit box] Number of data channels. Command line % equivalent: 'nbchan'. This edit box cannot be edited. % "Ref. channel indices or mode" - [edit box] current reference. This edit box % cannot be edited. To change the data reference, use menu item, % 'Tools > Re-reference', calling function pop_reref(). The % reference can be either a string (channel name), 'common', % indicating an unknown common reference, 'averef' indicating % average reference, or an array of integers containing indices % of the reference channel(s). % "Subject code" - [Edit box] subject code. For example, 'S01'. The command % line equivalent is 'subject'. % "Task Condition" - [Edit box] task condition. For example, 'Targets'. % The command line equivalent 'condition'. % "Session number" - [Edit box] session number (from the same subject). % All datasets from the same subject and session will be % assumed to use the same ICA decomposition. The command % line equivalent 'session'. % "Subject group" - [Edit box] subject group. For example 'Patients' or % 'Control'. The command line equivalent is 'group'. % "About this dataset" - [Edit box] Comments about the dataset. Command line % equivalent is 'comments'. % "Channel locations file or array" - [Edit box] For channel data formats, see % >> readlocs help Command line equivalent: 'chanlocs' % "ICA weights array or text/binary file" - [edit box] Import ICA weights from % other decompositions (e.g., same session, different conditions). % To use the ICA weights from another loaded dataset (n), enter % ALLEEG(n).icaweights. Command line equivalent: 'icaweights' % "ICA sphere array or text/binary file" - [edit box] Import ICA sphere matrix. % In EEGLAB, ICA decompositions require a sphere matrix and % an unmixing weight matrix (see above). To use the sphere % matrix from a loaded dataset (n), enter ALLEEG(n).icasphere % Command line equivalent: 'icasphere'. % "From other dataset" - [push button] Press this button to enter the index % of another dataset. This will update the channel locations or % the ICA edit box. % Inputs: % EEG - EEG dataset structure % % Optional inputs: % 'setname' - Name of the EEG dataset % 'data' - ['varname'|'filename'] Import data from a Matlab variable or % mat file into an EEG data structure % 'dataformat' - ['array|matlab|ascii|float32le|float32be'] Input data format. % 'array' is a Matlab array in the global workspace. % 'matlab' is a Matlab file (containing a single variable). % 'ascii' is an ascii file. % 'float32le' and 'float32be' are 32-bit float data files % with little-endian and big-endian byte order, respectively. % Data must be organised as 2-D (channels, timepoints), i.e. % channels = rows, timepoints = columns; else as 3-D (channels, % timepoints, epochs). For convenience, the data file is % transposed if the number of rows is larger than the number % of columns, as the program assumes that there are more % channels than data points. % 'subject' - [string] subject code. For example, 'S01'. % {default: none -> each dataset from a different subject} % 'condition' - [string] task condition. For example, 'Targets' % {default: none -> all datasets from one condition} % 'group' - [string] subject group. For example 'Patients' or 'Control'. % {default: none -> all subjects in one group} % 'session' - [integer] session number (from the same subject). All datasets % from the same subject and session will be assumed to use the % same ICA decomposition {default: none -> each dataset from % a different session} % 'chanlocs' - ['varname'|'filename'] Import a channel location file. % For file formats, see >> help readlocs % 'nbchan' - [int] Number of data channels. % 'xmin' - [real] Data epoch start time (in seconds). % {default: 0} % 'pnts' - [int] Number of data points per data epoch. The number of % data trials is automatically calculated. % {default: length of the data -> continuous data assumed} % 'srate' - [real] Data sampling rate in Hz {default: 1Hz} % 'ref' - [string or integer] reference channel indices; 'averef' % indicates average reference. Note that this does not perform % referencing but only sets the initial reference when the data % are imported. % 'icaweight' - [matrix] ICA weight matrix. % 'icasphere' - [matrix] ICA sphere matrix. By default, the sphere matrix % is initialized to the identity matrix if it is left empty. % 'comments' - [string] Comments on the dataset, accessible through the % EEGLAB main menu using ('Edit > About This Dataset'). % Use this to attach background information about the % experiment or the data to the dataset. % Outputs: % EEGOUT - Modified EEG dataset structure % % Note: % To create a new dataset: % >> EEG = pop_editset( eeg_emptyset ); % eeg_emptyset() returns an empty dataset % % To erase a variable, use '[]'. The following suppresses channel locations: % >> EEG = pop_editset( EEG, 'chanlocs', '[]'); % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: pop_importdata(), pop_select(), eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-16-02 text interface editing -sm & ad % 03-16-02 remove EEG.xmax et EEG.xmin (for continuous) -ad & sm % 03-31-02 changed interface, reprogrammed all function -ad % 04-02-02 recompute event latencies when modifying xmin -ad function [EEGOUT, com] = pop_editset(EEG, varargin); com = ''; if nargin < 1 help pop_editset; return; end; EEGOUT = EEG; if nargin < 2 % if several arguments, assign values % popup window parameters % ----------------------- % popup window parameters % ----------------------- geometry = { [2 3.38] [1] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] ... [1] [1.4 0.7 .8 0.5] [1] [1.4 0.7 .8 0.5] [1.4 0.7 .8 0.5] [1.4 0.7 .8 0.5] }; editcomments = [ 'tmp = pop_comments(get(gcbf, ''userdata''), ''Edit comments of current dataset'');' ... 'if ~isempty(tmp), set(gcf, ''userdata'', tmp); end; clear tmp;' ]; commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ... 'if filename(1) ~=0,' ... ' set(findobj(''parent'', gcbf, ''tag'', tagtest), ''string'', [ filepath filename ]);' ... ' if strcmpi(tagtest, ''weightfile''),' ... ' set(findobj( ''parent'', gcbf, ''tag'', ''sphfile''), ''string'', ''eye(' num2str(EEG.nbchan) ')'');' ... ' end;' ... 'end;' ... 'clear filename filepath tagtest;' ]; commandselica = [ 'res = inputdlg2({ ''Enter dataset number'' }, ''Select ICA weights and sphere from other dataset'', 1, { ''1'' });' ... 'if ~isempty(res),' ... ' set(findobj( ''parent'', gcbf, ''tag'', ''weightfile''), ''string'', sprintf(''ALLEEG(%s).icaweights'', res{1}));' ... ' set(findobj( ''parent'', gcbf, ''tag'', ''sphfile'') , ''string'', sprintf(''ALLEEG(%s).icasphere'' , res{1}));' ... ' set(findobj( ''parent'', gcbf, ''tag'', ''icainds'') , ''string'', sprintf(''ALLEEG(%s).icachansind'' , res{1}));' ... 'end;' ]; commandselchan = [ 'res = inputdlg2({ ''Enter dataset number'' }, ''Select channel information from other dataset'', 1, { ''1'' });' ... 'if ~isempty(res),' ... ' set(findobj( ''parent'', gcbf, ''tag'', ''chanfile''), ' ... ' ''string'', sprintf(''{ ALLEEG(%s).chanlocs ALLEEG(%s).chaninfo ALLEEG(%s).urchanlocs }'', res{1}, res{1}, res{1}));' ... 'end;' ]; if isstr(EEGOUT.ref) curref = EEGOUT.ref; else if length(EEGOUT.ref) > 1 curref = [ int2str(abs(EEGOUT.ref)) ]; else curref = [ int2str(abs(EEGOUT.ref)) ]; end; end; uilist = { ... { 'Style', 'text', 'string', 'Dataset name', 'horizontalalignment', 'right', ... 'fontweight', 'bold' }, { 'Style', 'edit', 'string', EEG.setname }, { } ... ... { 'Style', 'text', 'string', 'Data sampling rate (Hz)', 'horizontalalignment', 'right', 'fontweight', ... 'bold' }, { 'Style', 'edit', 'string', num2str(EEGOUT.srate) }, ... { 'Style', 'text', 'string', 'Subject code', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', EEG.subject }, ... { 'Style', 'text', 'string', 'Time points per epoch (0->continuous)', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', num2str(EEGOUT.pnts) }, ... { 'Style', 'text', 'string', 'Task condition', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', EEG.condition }, ... { 'Style', 'text', 'string', 'Start time (sec) (only for data epochs)', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', num2str(EEGOUT.xmin) }, ... { 'Style', 'text', 'string', 'Session number', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', EEG.session }, ... { 'Style', 'text', 'string', 'Number of channels (0->set from data)', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', EEG.nbchan 'enable' 'off' }, ... { 'Style', 'text', 'string', 'Subject group', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', EEG.group }, ... { 'Style', 'text', 'string', 'Ref. channel indices or mode (see help)', 'horizontalalignment', 'right', ... }, { 'Style', 'edit', 'string', curref 'enable' 'off' }, ... { 'Style', 'text', 'string', 'About this dataset', 'horizontalalignment', 'right', ... }, { 'Style', 'pushbutton', 'string', 'Enter comments' 'callback' editcomments }, ... { } ... { 'Style', 'text', 'string', 'Channel location file or info', 'horizontalalignment', 'right', 'fontweight', ... 'bold' }, {'Style', 'pushbutton', 'string', 'From other dataset', 'callback', commandselchan }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'chanfile' }, ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''chanfile'';' commandload ] }, ... ... { 'Style', 'text', 'string', ... ' Note: The file format may be auto-detected from its file extension. See menu "Edit > Channel locations" for other options.', ... 'horizontalalignment', 'right' }, ... ... { 'Style', 'text', 'string', 'ICA weights array or text/binary file (if any):', 'horizontalalignment', 'right' }, ... { 'Style', 'pushbutton' 'string' 'from other dataset' 'callback' commandselica }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'weightfile' }, ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''weightfile'';' commandload ] }, ... ... { 'Style', 'text', 'string', 'ICA sphere array:', 'horizontalalignment', 'right' }, ... { 'Style', 'pushbutton' 'string' 'from other dataset' 'callback' commandselica }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'sphfile' } ... { } ... ... { 'Style', 'text', 'string', 'ICA channel indices (by default all):', 'horizontalalignment', 'right' }, ... { 'Style', 'pushbutton' 'string' 'from other dataset' 'callback' commandselica }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'icainds' } ... { } }; [ results newcomments ] = inputgui( geometry, uilist, 'pophelp(''pop_editset'');', 'Edit dataset information - pop_editset()', ... EEG.comments); if length(results) == 0, return; end; args = {}; i = 1; if ~strcmp( results{i }, EEG.setname ) , args = { args{:}, 'setname', results{i } }; end; if ~strcmp( results{i+1}, num2str(EEG.srate) ) , args = { args{:}, 'srate', str2num(results{i+1}) }; end; if ~strcmp( results{i+2}, EEG.subject ) , args = { args{:}, 'subject', results{i+2} }; end; if ~strcmp( results{i+3}, num2str(EEG.pnts) ) , args = { args{:}, 'pnts', str2num(results{i+3}) }; end; if ~strcmp( results{i+4}, EEG.condition ) , args = { args{:}, 'condition', results{i+4} }; end; if ~strcmp( results{i+5}, num2str(EEG.xmin) ) , args = { args{:}, 'xmin', str2num(results{i+5}) }; end; if ~strcmp( results{i+6}, num2str(EEG.session) ) , args = { args{:}, 'session', str2num(results{i+6}) }; end; if ~strcmp( results{i+7}, num2str(EEG.nbchan) ) , args = { args{:}, 'nbchan', str2num(results{i+7}) }; end; if ~strcmp( results{i+8}, EEG.group ) , args = { args{:}, 'group', results{i+8} }; end; if ~strcmp( results{i+9}, num2str(EEG.ref) ) , args = { args{:}, 'ref', results{i+9} }; end; if ~strcmp(EEG.comments, newcomments) , args = { args{:}, 'comments' , newcomments }; end; if abs(str2num(results{i+5})) > 10, fprintf('WARNING: are you sure the epoch start time (%3.2f) is in seconds\n', str2num(results{i+5})); end; if ~isempty( results{i+12} ) , args = { args{:}, 'icachansind', results{i+13} }; end; if ~isempty( results{i+10} ) , args = { args{:}, 'chanlocs' , results{i+10} }; end; if ~isempty( results{i+11} ), args = { args{:}, 'icaweights', results{i+11} }; end; if ~isempty( results{i+12} ) , args = { args{:}, 'icasphere', results{i+12} }; end; else % no interactive inputs args = varargin; % Do not copy varargin % -------------------- %for index=1:2:length(args) % if ~isempty(inputname(index+2)) & ~isstr(args{index+1}) & length(args{index+1})>1, % args{index+1} = inputname(index+1); % end; %end; end; % create structure % ---------------- if ~isempty(args) try, g = struct(args{:}); catch, disp('Setevent: wrong syntax in function arguments'); return; end; else g = []; end; % test the presence of variables % ------------------------------ try, g.dataformat; catch, g.dataformat = 'ascii'; end; % assigning values % ---------------- tmpfields = fieldnames(g); for curfield = tmpfields' switch lower(curfield{1}) case {'dataformat' }, ; % do nothing now case 'setname' , EEGOUT.setname = getfield(g, {1}, curfield{1}); case 'subject' , EEGOUT.subject = getfield(g, {1}, curfield{1}); case 'condition' , EEGOUT.condition = getfield(g, {1}, curfield{1}); case 'group' , EEGOUT.group = getfield(g, {1}, curfield{1}); case 'session' , EEGOUT.session = getfield(g, {1}, curfield{1}); case 'setname' , EEGOUT.setname = getfield(g, {1}, curfield{1}); case 'setname' , EEGOUT.setname = getfield(g, {1}, curfield{1}); case 'pnts' , EEGOUT.pnts = getfield(g, {1}, curfield{1}); case 'comments' , EEGOUT.comments = getfield(g, {1}, curfield{1}); case 'nbchan' , tmp = getfield(g, {1}, curfield{1}); if tmp ~=0, EEGOUT.nbchan = tmp; end; case 'averef' , disp('The ''averef'' argument is obsolete; use function pop_reref() instead'); case 'ref' , EEGOUT.ref = getfield(g, {1}, curfield{1}); disp('WARNING: CHANGING REFERENCE DOES NOT RE-REFERENCE THE DATA, use menu Tools > Rereference instead'); if ~isempty(str2num( EEGOUT.ref )), EEG,ref = str2num(EEG.ref); end; case 'xmin' , oldxmin = EEG.xmin; EEGOUT.xmin = getfield(g, {1}, curfield{1}); if oldxmin ~= EEGOUT.xmin if ~isempty(EEG.event) if nargin < 2 if ~popask( ['Warning: changing the starting point of epochs will' 10 'lead to recomputing epoch event latencies, Continue?'] ) com = ''; warndlg2('pop_editset(): transformation cancelled by user'); return; end; end; if isfield(EEG.event, 'latency') for index = 1:length(EEG.event) EEG.event(index).latency = EEG.event(index).latency - (EEG.xmin-oldxmin)*EEG.srate; end; end; end; end; case 'srate' , EEGOUT.srate = getfield(g, {1}, curfield{1}); case 'chanlocs', varname = getfield(g, {1}, curfield{1}); if isempty(varname) EEGOUT.chanlocs = []; elseif isstr(varname) & exist( varname ) == 2 fprintf('pop_editset(): channel locations file ''%s'' found\n', varname); [ EEGOUT.chanlocs lab theta rad ind ] = readlocs(varname); elseif isstr(varname) EEGOUT.chanlocs = evalin('base', varname, 'fprintf(''pop_editset() warning: variable ''''%s'''' not found, ignoring\n'', varname)' ); if iscell(EEGOUT.chanlocs) if length(EEGOUT.chanlocs) > 1, EEGOUT.chaninfo = EEGOUT.chanlocs{2}; end; if length(EEGOUT.chanlocs) > 2, EEGOUT.urchanlocs = EEGOUT.chanlocs{3}; end; EEGOUT.chanlocs = EEGOUT.chanlocs{1}; end; else EEGOUT.chanlocs = varname; end; case 'icaweights', varname = getfield(g, {1}, curfield{1}); if isstr(varname) & exist( varname ) == 2 fprintf('pop_editset(): ICA weight matrix file ''%s'' found\n', varname); if ~isempty(EEGOUT.icachansind), nbcol = length(EEGOUT.icachansind); else nbcol = EEG.nbchan; end; try, EEGOUT.icaweights = load(varname, '-ascii'); EEGOUT.icawinv = []; catch, try EEGOUT.icaweights = floatread(varname, [1 Inf]); EEGOUT.icaweights = reshape( EEGOUT.icaweights, [length(EEGOUT.icaweights)/nbcol nbcol]); catch fprintf('pop_editset() warning: error while reading filename ''%s'' for ICA weight matrix\n', varname); end; end; else if isempty(varname) EEGOUT.icaweights = []; elseif isstr(varname) EEGOUT.icaweights = evalin('base', varname, 'fprintf(''pop_editset() warning: variable ''''%s'''' not found, ignoring\n'', varname)' ); EEGOUT.icawinv = []; else EEGOUT.icaweights = varname; EEGOUT.icawinv = []; end; end; if ~isempty(EEGOUT.icaweights) & isempty(EEGOUT.icasphere) EEGOUT.icasphere = eye(size(EEGOUT.icaweights,2)); end; case 'icachansind', varname = getfield(g, {1}, curfield{1}); if isempty(varname) EEGOUT.icachansind = []; elseif isstr(varname) EEGOUT.icachansind = evalin('base', varname, 'fprintf(''pop_editset() warning: variable ''''%s'''' not found, ignoring\n'', varname)' ); else EEGOUT.icachansind = varname; end; case 'icasphere', varname = getfield(g, {1}, curfield{1}); if isstr(varname) & exist( varname ) == 2 fprintf('pop_editset(): ICA sphere matrix file ''%s'' found\n', varname); if ~isempty(EEGOUT.icachansind), nbcol = length(EEGOUT.icachansind); else nbcol = EEG.nbchan; end; try, EEGOUT.icasphere = load(varname, '-ascii'); EEGOUT.icawinv = []; catch, try EEGOUT.icasphere = floatread(varname, [1 Inf]); EEGOUT.icasphere = reshape( EEGOUT.icasphere, [length(EEGOUT.icasphere)/nbcol nbcol]); catch fprintf('pop_editset() warning: erro while reading filename ''%s'' for ICA weight matrix\n', varname); end; end; else if isempty(varname) EEGOUT.icasphere = []; elseif isstr(varname) EEGOUT.icasphere = evalin('base', varname, 'fprintf(''pop_editset() warning: variable ''''%s'''' not found, ignoring\n'', varname)' ); EEGOUT.icawinv = []; else EEGOUT.icaweights = varname; EEGOUT.icawinv = []; end; end; if ~isempty(EEGOUT.icaweights) & isempty(EEGOUT.icasphere) EEGOUT.icasphere = eye(size(EEGOUT.icaweights,2)); end; case 'data' , varname = getfield(g, {1}, curfield{1}); if isnumeric(varname) EEGOUT.data = varname; elseif exist( varname ) == 2 & ~strcmp(lower(g.dataformat), 'array'); fprintf('pop_editset(): raw data file ''%s'' found\n', varname); switch lower(g.dataformat) case 'ascii' , try, EEGOUT.data = load(varname, '-ascii'); catch, disp(lasterr); error(['pop_editset() error: cannot read ascii file ''' varname ''' ']); end; if ndims(EEGOUT.data)<3 & size(EEGOUT.data,1) > size(EEGOUT.data,2), EEGOUT.data = transpose(EEGOUT.data); end; case 'matlab', try, x = whos('-file', varname); if length(x) > 1, error('pop_editset() error: .mat file must contain a single variable'); end; tmpdata = load(varname, '-mat'); EEGOUT.data = getfield(tmpdata,{1},x(1).name); clear tmpdata; catch, error(['pop_editset() error: cannot read .mat file ''' varname ''' ']); end; if ndims(EEGOUT.data)<3 & size(EEGOUT.data,1) > size(EEGOUT.data,2), EEGOUT.data = transpose(EEGOUT.data); end; case {'float32le' 'float32be'}, if EEGOUT.nbchan == 0, error(['pop_editset() error: to read float32 data you must first specify the number of channels']); end; try, EEGOUT.data = floatread(varname, [EEGOUT.nbchan Inf], ... fastif(strcmpi(g.dataformat, 'float32le'), 'ieee-le', 'ieee-be')); catch, error(['pop_editset() error: cannot read float32 data file ''' varname ''' ']); end; otherwise, error('pop_editset() error: unrecognized file format'); end; elseif isstr(varname) % restoration command %-------------------- try res = evalin('base', ['exist(''' varname ''') == 1']); catch disp('pop_editset() warning: cannot find specified variable in global workspace!'); end; if ~res, error('pop_editset(): cannot find specified variable.'); end; warning off; try, testval = evalin('base', ['isglobal(' varname ')']); catch, testval = 0; end; if ~testval commandrestore = [ ' tmpp = ' varname '; clear global ' varname ';' varname '=tmpp;clear tmpp;' ]; else commandrestore = []; end; % make global, must make these variable global, if you try to evaluate them direclty in the base % workspace, with a large array the computation becomes incredibly slow. %-------------------------------------------------------------------- comglobal = sprintf('global %s;', varname); evalin('base', comglobal); eval(comglobal); eval( ['EEGOUT.data = ' varname ';' ]); try, evalin('base', commandrestore); catch, end; warning on; else EEGOUT.data = varname; if ndims(EEGOUT.data)<3 & size(EEGOUT.data,1) > size(EEGOUT.data,2), EEGOUT.data = transpose(EEGOUT.data); end; end; otherwise, error(['pop_editset() error: unrecognized field ''' curfield{1} '''']); end; end; EEGOUT = eeg_checkset(EEGOUT); % generate the output command % --------------------------- if nargout > 1 com = sprintf( '%s = pop_editset(%s', inputname(1), inputname(1) ); for i=1:2:length(args) if ~isempty( args{i+1} ) if isstr( args{i+1} ) com = sprintf('%s, ''%s'', %s', com, args{i}, vararg2str(args{i+1}) ); else com = sprintf('%s, ''%s'', [%s]', com, args{i}, num2str(args{i+1}) ); end; else com = sprintf('%s, ''%s'', []', com, args{i} ); end; end; com = [com ');']; end; return; function num = popask( text ) ButtonName=questdlg2( text, ... 'Confirmation', 'Cancel', 'Yes','Yes'); switch lower(ButtonName), case 'cancel', num = 0; case 'yes', num = 1; end;
github
lcnbeapp/beapp-master
pop_snapread.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_snapread.m
3,759
utf_8
28b076d60861433397b0c0dd49338875
% pop_snapread() - load an EEG SnapMaster file (pop out window if no arguments). % % Usage: % >> [dat] = pop_snapread( filename, gain); % % Graphic interface: % "Relative gain" - [edit box] to compute the relative gain, fisrt look at % the text header of the snapmater file with a text editor. % Find the recording unit, usually in volts (UNITS field). % Then, find the voltage range in the "CHANNEL.RANGE" [cmin cmax] % field. Finally, determine the gain of the amplifiers (directly % on the machine, not in the header file). % Knowing that the recording precision is 12 bits. The folowing % formula % 1/2^12*[cmax-cmin]*1e6/gain % returns the relative gain. You have to compute it and enter % it in the edit box. Enter 1, for preserving the data file units. % (note that if the voltage range is not the same for all channels % or if the CONVERSION.POLY field in the file header % is not "0 + 1x" for all channels, you will have to load the data % using snapread() and scale manually all channels, then import % the Matlab array into EEGLAB). % % Inputs: % filename - SnapMaster file name % gain - relative gain. See graphic interface help. % % Outputs: % dat - EEGLAB data structure % % Author: Arnaud Delorme, CNL/Salk Institute, 13 March 2002 % % See also: eeglab(), snapread() % Copyright (C) 13 March 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, command] = pop_snapread(filename, gain); command = ''; EEG = []; if nargin < 1 % ask user [filename, filepath] = uigetfile('*.SMA', 'Choose a SnapMaster file -- pop_snapread()'); if filename == 0 return; end; filename = [filepath filename]; promptstr = { 'Relative gain (see help)' }; inistr = { '400' }; result = inputdlg2( promptstr, 'Import SnapMaster file -- pop_snapread()', 1, inistr, 'pop_snapread'); if length(result) == 0 return; end; gain = eval( result{1} ); end; if exist('gain') ~= 1 gain = 1; end; % load datas % ---------- EEG = eeg_emptyset; [EEG.data,params,events, head] = snapread(filename); EEG.data = EEG.data*gain; EEG.comments = [ 'Original file: ' filename ]; EEG.filepath = ''; EEG.setname = 'SnapMaster file'; EEG.nbchan = params(1); EEG.pnts = params(2); EEG.trials = 1; EEG.srate = params(3); EEG.xmin = 0; A = find(events ~= 0); if ~isempty(A) EEG.event = struct( 'type', mattocell(events(A), [1], ones(1,length(events(A)))), ... 'latency', mattocell(A(:)', [1], ones(1,length(A))) ); end; EEG = eeg_checkset(EEG, 'eventconsistency'); EEG = eeg_checkset(EEG, 'makeur'); command = sprintf('EEG = pop_snapread(''%s'', %f);', filename, gain); return;
github
lcnbeapp/beapp-master
eeg_decodechan.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/eeg_decodechan.m
3,799
utf_8
600c82eb2fe26e4e9b5b1d1af79b383d
% eeg_decodechan() - given an input EEG dataset structure, output a new EEG data structure % retaining and/or excluding specified time/latency, data point, channel, % and/or epoch range(s). % Usage: % >> [chaninds chanlist] = eeg_decodechan(chanlocs, chanlist); % % Inputs: % chanlocs - channel location structure % chanlist - list of channels, numerical indices [1 2 3 ...] or string % 'cz pz fz' or cell array { 'cz' 'pz' 'fz' } % % Outputs: % chaninds - integer array with the list of channel indices % chanlist - cell array with a list of channel labels % % Author: Arnaud Delorme, SCCN/INC/UCSD, 2009- % % see also: eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [ chaninds chanlist ] = eeg_decodechan(chanlocs, chanstr); if nargin < 2 help eeg_decodechan; return; end; if isempty(chanlocs) && isstr(chanstr) chaninds = str2num(chanstr); chanlist = chaninds; return; end; if isstr(chanstr) % convert chanstr % --------------- chanstr(find(chanstr == ']')) = []; chanstr(find(chanstr == '[')) = []; chanlistnum = []; chanstr = [ ' ' chanstr ' ' ]; chanlist = {}; sp = find(chanstr == ' '); for i = 1:length(sp)-1 c = chanstr(sp(i)+1:sp(i+1)-1); if ~isempty(c) chanlist{end+1} = c; if isnan(str2double(chanlocs(1).labels)) % channel labels are not numerical if ~isnan(str2double(c)) chanlistnum(end+1) = str2double(c); end; end; end; end; if length(chanlistnum) == length(chanlist) chanlist = chanlistnum; end; else chanlist = chanstr; end; % convert to values % ----------------- chanval = 0; if isnumeric(chanlist) chanval = chanlist; end; % chanval = []; % if iscell(chanlist) % for ind = 1:length(chanlist) % % valtmp = str2double(chanlist{ind}); % if ~isnan(valtmp) % chanval(end+1) = valtmp; % else chanval(end+1) = 0; % end; % end; % else % chanval = chanlist; % end; % convert to numerical % -------------------- if all(chanval) > 0 chaninds = chanval; chanlist = chanval; else chaninds = []; alllabs = lower({ chanlocs.labels }); chanlist = lower(chanlist); for ind = 1:length(chanlist) indmatch = find(strcmp(alllabs,chanlist{ind})); %#ok<STCI> if ~isempty(indmatch) for tmpi = 1:length(indmatch) chaninds(end+1) = indmatch(tmpi); end; else try, eval([ 'chaninds = ' chanlist{ind} ';' ]); if isempty(chaninds) error([ 'Channel ''' chanlist{ind} ''' not found' ]); else end; catch error([ 'Channel ''' chanlist{ind} ''' not found' ]); end; end; end; end; chaninds = sort(chaninds); if ~isempty(chanlocs) chanlist = { chanlocs(chaninds).labels }; else chanlist = {}; end;
github
lcnbeapp/beapp-master
eeg_getica.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/eeg_getica.m
1,704
utf_8
00350d1cd6a4ab711db93297dd29454d
% eeg_getica() - get ICA component activation. Recompute if necessary. % % >> mergelocs = eeg_getica(EEG, comp); % % Inputs: % EEG - EEGLAB dataset structure % comp - component index % % Output: % icaact - ICA component activity % % Author: Arnaud Delorme, 2006 % Copyright (C) Arnaud Delorme, CERCO, 2006, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function icaact = eeg_getica(EEG, comp) if nargin < 1 help eeg_getica; return; end; if nargin < 2 comp = 1:size(EEG.icaweights,1); end; if ~isempty(EEG.icaact) icaact = EEG.icaact(comp,:,:); else disp('Recomputing ICA activations'); if isempty(EEG.icachansind) EEG.icachansind = 1:EEG.nbchan; disp('Channels indices are assumed to be in regular order and arranged accordingly'); end icaact = (EEG.icaweights(comp,:)*EEG.icasphere)*reshape(EEG.data(EEG.icachansind,:,:), length(EEG.icachansind), EEG.trials*EEG.pnts); icaact = reshape( icaact, size(icaact,1), EEG.pnts, EEG.trials); end;
github
lcnbeapp/beapp-master
pop_mergeset.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_mergeset.m
13,668
utf_8
307f42bbcf51af31a20f499cdc766249
% pop_mergeset() - Merge two or more datasets. If only one argument is given, % a window pops up to ask for more arguments. % Usage: % >> OUTEEG = pop_mergeset( ALLEEG ); % use a pop-up window % >> OUTEEG = pop_mergeset( ALLEEG, indices, keepall); % >> OUTEEG = pop_mergeset( INEEG1, INEEG2, keepall); % % Inputs: % INEEG1 - first input dataset % INEEG2 - second input dataset % % else % ALLEEG - array of EEG dataset structures % indices - indices of EEG datasets to merge % % keepall - [0|1] 0 -> remove, or 1 -> preserve, ICA activations % of the first dataset and recompute the activations % of the merged data {default: 0} % % Outputs: % OUTEEG - merged dataset % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 01-26-02 change format for events and trial conditions -ad function [INEEG1, com] = pop_mergeset( INEEG1, INEEG2, keepall); com = ''; if nargin < 1 help pop_mergeset; return; end; if isempty(INEEG1) error('needs at least two datasets'); end; if nargin < 2 & length(INEEG1) == 1 error('needs at least two datasets'); end; if nargin == 1 uilist = { { 'style' 'text' 'string' 'Dataset indices to merge' } ... { 'style' 'edit' 'string' '1' } ... { 'style' 'text' 'string' 'Preserve ICA weights of the first dataset ?' } ... { 'style' 'checkbox' 'string' '' } }; res = inputgui( 'uilist', uilist, 'geometry', { [3 1] [3 1] }, 'helpcom', 'pophelp(''pop_mergeset'')'); if isempty(res) return; end; INEEG2 = eval( [ '[' res{1} ']' ] ); keepall = res{2}; else if nargin < 3 keepall = 0; % default end; end; fprintf('Merging datasets...\n'); if ~isstruct(INEEG2) % if INEEG2 is a vector of ALLEEG indices indices = INEEG2; NEWEEG = eeg_retrieve(INEEG1, indices(1)); % why abandoned? for index = 2:length(indices) INEEG2 = eeg_retrieve(INEEG1, indices(index)); NEWEEG = pop_mergeset(NEWEEG, INEEG2, keepall); % recursive call end; INEEG1 = NEWEEG; else % INEEG is an EEG struct % check consistency % ----------------- if INEEG1.nbchan ~= INEEG2.nbchan error('The two datasets must have the same number of channels'); end; if INEEG1.srate ~= INEEG2.srate error('The two datasets must have the same sampling rate'); end; if INEEG1.trials > 1 | INEEG2.trials > 1 if INEEG1.pnts ~= INEEG2.pnts error('The two epoched datasets must have the same number of points'); end; if INEEG1.xmin ~= INEEG2.xmin INEEG2.xmin = INEEG1.xmin; fprintf('Warning: the two epoched datasets do not have the same time onset, adjusted'); end; if INEEG1.xmax ~= INEEG2.xmax INEEG2.xmax = INEEG1.xmax; fprintf('Warning: the two epoched datasets do not have the same time offset, adjusted'); end; end; % repopulate epoch field if necessary % ----------------------------------- if INEEG1.trials > 1 && INEEG2.trials == 1 for iEvent = 1:length(INEEG2.event) INEEG2.event(iEvent).epoch = 1; end; end; if INEEG1.trials == 1 && INEEG2.trials > 1 for iEvent = 1:length(INEEG1.event) INEEG1.event(iEvent).epoch = 1; end; end; % Merge the epoch field % --------------------- if INEEG1.trials > 1 || INEEG2.trials > 1 INEEGX = {INEEG1,INEEG2}; for n = 1:2 % make sure that both have an (appropriately-sized) epoch field % ------------------------------------------------------------- if ~isfield(INEEGX{n},'epoch') INEEGX{n}.epoch = repmat(struct(),[1,INEEGX{n}.trials]); end % make sure that the epoch number is correct in each dataset % ---------------------------------------------------------- if ~isempty(INEEGX{n}.epoch) && length(INEEGX{n}.epoch) ~= INEEGX{n}.trials disp('Warning: The number of trials does not match the length of the EEG.epoch field in one of'); disp(' the datasets. Its epoch info will be reset and derived from the respective events.'); INEEGX{n}.epoch = repmat(struct(),[1,INEEGX{n}.trials]); end end for n=1:2 % purge all event-related epoch fields from each dataset (EEG.epoch.event* fields) % -------------------------------------------------------------------------------- if isstruct(INEEGX{n}.epoch) fn = fieldnames(INEEGX{n}.epoch); INEEGX{n}.epoch = rmfield(INEEGX{n}.epoch,{fn{strmatch('event',fn)}}); % copy remaining field names to the other dataset % ----------------------------------------------- for f = fieldnames(INEEGX{n}.epoch)' if ~isfield(INEEGX{3-n}.epoch,f{1}) INEEGX{3-n}.epoch(1).(f{1}) = []; end end % after this, both sets have an epoch field with the appropriate number of items % and possibly some user-defined fields, but no event* fields. end end % concatenate epochs % ------------------ if isstruct(INEEGX{1}.epoch) && isstruct(INEEGX{2}.epoch) if length(fieldnames(INEEGX{2}.epoch)) > 0 INEEGX{1}.epoch(end+1:end+INEEGX{2}.trials) = orderfields(INEEGX{2}.epoch,INEEGX{1}.epoch); else INEEGX{1}.epoch(end+1:end+INEEGX{2}.trials) = INEEGX{2}.epoch; end; end % and write back INEEG1 = INEEGX{1}; INEEG2 = INEEGX{2}; INEEGX = {}; end % Concatenate data % ---------------- if INEEG1.trials > 1 | INEEG2.trials > 1 INEEG1.data(:,:,end+1:end+size(INEEG2.data,3)) = INEEG2.data(:,:,:); else INEEG1.data(:,end+1:end+size(INEEG2.data,2)) = INEEG2.data(:,:); end; INEEG1.setname = 'Merged datasets'; INEEG1trials = INEEG1.trials; INEEG2trials = INEEG2.trials; INEEG1pnts = INEEG1.pnts; INEEG2pnts = INEEG2.pnts; if INEEG1.trials > 1 | INEEG2.trials > 1 % epoched data INEEG1.trials = INEEG1.trials + INEEG2.trials; else % continuous data INEEG1.pnts = INEEG1.pnts + INEEG2.pnts; end; if isfield(INEEG1, 'reject') INEEG1 = rmfield(INEEG1, 'reject' ); end; INEEG1.specicaact = []; INEEG1.specdata = []; if keepall == 0 INEEG1.icaact = []; INEEG1.icawinv = []; INEEG1.icasphere = []; INEEG1.icaweights = []; if isfield(INEEG1, 'stats') INEEG1 = rmfield(INEEG1, 'stats' ); end; else INEEG1.icaact = []; end; % concatenate events % ------------------ if isempty(INEEG2.event) && INEEG2.trials == 1 && INEEG1.trials == 1 % boundary event % ------------- disp('Inserting boundary event...'); INEEG1.event(end+1).type = 'boundary'; % add boundary event between datasets INEEG1.event(end ).latency = INEEG1pnts+0.5; % make boundary halfway between last,first pts % check urevents % -------------- if ~isfield(INEEG1, 'urevent'), INEEG1.urevent = []; fprintf('Warning: first dataset has no urevent structure.\n'); end; % add boundary urevent % -------------------- disp('Inserting boundary urevent...'); INEEG1.urevent(end+1).type = 'boundary'; if length(INEEG1.urevent) > 1 % if previous INEEG1 urevents INEEG1.urevent(end ).latency = max(INEEG1pnts, INEEG1.urevent(end-1).latency)+0.5; else INEEG1.urevent(end ).latency = INEEG1pnts+0.5; end; else % is ~isempty(INEEG2.event) % concatenate urevents % -------------------- if isfield(INEEG2, 'urevent') if ~isempty(INEEG2.urevent) && isfield(INEEG1.urevent, 'latency') % insert boundary event % --------------------- disp('Inserting boundary event...'); INEEG1.urevent(end+1).type = 'boundary'; try INEEG1.urevent(end ).latency = max(INEEG1pnts, INEEG1.urevent(end-1).latency)+0.5; catch % cko: sometimes INEEG1 has no events / urevents INEEG1.urevent(end ).latency = INEEG1pnts+0.5; end % update urevent indices for second dataset % ----------------------------------------- disp('Concatenating urevents...'); orilen = length(INEEG1.urevent); newlen = length(INEEG2.urevent); INEEG2event = INEEG2.event; % update urevent index in INEEG2.event tmpevents = INEEG2.event; nonemptymask = ~cellfun('isempty',{tmpevents.urevent}); [tmpevents(nonemptymask).urevent] = celldeal(num2cell([INEEG2event.urevent]+orilen)); INEEG2.event = tmpevents; % reserve space and append INEEG2.urevent INEEG1.urevent(orilen+newlen).latency = []; INEEG2urevent = INEEG2.urevent; tmpevents = INEEG1.urevent; for f = fieldnames(INEEG2urevent)' [tmpevents((orilen+1):(orilen+newlen)).(f{1})] = INEEG2urevent.(f{1}); end INEEG1.urevent = tmpevents; else INEEG1.urevent = []; INEEG2.urevent = []; fprintf('Warning: second dataset has empty urevent structure.\n'); end end; % concatenate events % ------------------ disp('Concatenating events...'); orilen = length(INEEG1.event); newlen = length(INEEG2.event); %allfields = fieldnames(INEEG2.event); % add discontinuity event if continuous % ------------------------------------- if INEEG1trials == 1 & INEEG2trials == 1 disp('Adding boundary event...'); INEEG1.event(end+1).type = 'boundary'; INEEG1.event(end ).latency = INEEG1pnts+0.5; INEEG1.event(end ).duration = NaN; orilen = orilen+1; % eeg_insertbound(INEEG1.event, INEEG1.pnts, INEEG1pnts+1, 0); % +1 since 0.5 is subtracted end; % ensure similar event structures % ------------------------------- if ~isempty(INEEG2.event) if isstruct(INEEG1.event) for f = fieldnames(INEEG1.event)' if ~isfield(INEEG2.event,f{1}) INEEG2.event(1).(f{1}) = []; end end end if isstruct(INEEG2.event) for f = fieldnames(INEEG2.event)' if ~isfield(INEEG1.event,f{1}) INEEG1.event(1).(f{1}) = []; end end end INEEG2.event = orderfields(INEEG2.event, INEEG1.event); end; % append % ------ INEEG1.event(orilen + (1:newlen)) = INEEG2.event; INEEG2event = INEEG2.event; if isfield(INEEG1.event,'latency') && isfield(INEEG2.event,'latency') % update latency tmpevents = INEEG1.event; [tmpevents(orilen + (1:newlen)).latency] = celldeal(num2cell([INEEG2event.latency] + INEEG1pnts*INEEG1trials)); INEEG1.event = tmpevents; end if isfield(INEEG1.event,'epoch') && isfield(INEEG2.event,'epoch') % update epoch index tmpevents = INEEG1.event; [tmpevents(orilen + (1:newlen)).epoch] = celldeal(num2cell([INEEG2event.epoch]+INEEG1trials)); INEEG1.event = tmpevents; end end; INEEG1.pnts = size(INEEG1.data,2); if ~isfield(INEEG1.event,'epoch') && ~isempty(INEEG1.event) && (size(INEEG1.data,3)>1 || ~isempty(INEEG1.epoch)) INEEG1.event(1).epoch = []; end % rebuild event-related epoch fields % ---------------------------------- disp('Reconstituting epoch information...'); INEEG1.epoch = []; INEEG1 = eeg_checkset(INEEG1, 'eventconsistency'); end % build the command % ----------------- if exist('indices') == 1 com = sprintf('EEG = pop_mergeset( %s, [%s], %d);', inputname(1), int2str(indices), keepall); else com = sprintf('EEG = pop_mergeset( %s, %s, %d);', inputname(1), inputname(2), keepall); end return function varargout = celldeal(X) varargout = X;
github
lcnbeapp/beapp-master
pop_importevent.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_importevent.m
12,593
utf_8
6b64e9391f0dca41020312951341bd55
% pop_importevent() - Import events into an EEG dataset. If the EEG dataset % is the only input, a window pops up to ask for the relevant % parameter values. % % Usage: >> EEG = pop_importevent( EEG ); % pop-up window mode % >> EEG = pop_importevent( EEG, 'key1', 'value1', ...); % % Graphic interface: % "Event indices" - [edit box] Enter indices of events to modify. % Leave this field blank to import new events. % Command line equivalent: 'indices'. % "Append events?" - [checkbox] Check this checkbox to clear prior % event information. In addition, see the "Align event latencies ..." % edit box. Command line equivalent: 'append'. % "Event file or array" - [edit box] Enter event file name. Use "Browse" % button to browse for a file. If a file with the given name % cannot be found, the function search for a variable with % this name in the global workspace. % Command line equivalent: 'filename'. % "Input field (column) name" - [edit box] Enter a name for each of the % columns in the event text file. If column names are defined % in the text file, they cannnot be used and you must copy % the names into this edit box (and skip the name row). Must % provide a name for each column. The keywords "type", % "latency", and "duration" are recognized EEGLAB keywords and % should be used to define the event log file columns containing % event types, latencies, and durations. Column names can be % separated by commas, quoted or not. % Command line equivalent: fields. % "Latency time unit (sec)" - [edit box] Specify the time unit for the % latency column defined above relative to seconds. % Command line equivalent: 'timeunit'. % "Number of header lines to ignore" - [edit box] For some text files, the % first rows do not contain epoch information and need to be % skipped. Command line equivalent: 'skiplines'. % "Align event latencies to data events" - [edit box] For most EEG datasets, % basic event information is defined along with the EEG, and % a more detailed file is recorded separately. This option % helps fuse the two sources of information by realigning the % imported data text file information into the existing event. % A value of 0 indicates that the first events of the pre-defined % events and imported events will be aligned. A positive value (num) % aligns the first event to the num-th pre-existing event. % A negative value can also be used; then event number (-num) % is aligned to the first pre-existing event. Default is 0. % (NaN-> no alignment). Command line equivalent is 'align'. % "Auto adjust event sampling rate" - [checkbox] When checked, the function % automatically adjusts the sampling rate of the new events so % they best align with the closest old events. This may account % for small differences in sampling rate that could lead to % big differences at the end of the experiement (e.g., A 0.01% % clock difference over an hour would lead to a 360-ms difference % if not corrected). Command line line equivalent is 'optimalim'. % Input: % EEG - input dataset % % Optional file or array input: % 'event' - [ 'filename'|array ] Filename of a text file, or name of s % Matlab array in the global workspace containing an % array of events in the folowing format: The first column % is the type of the event, the second the latency. % The others are user-defined. The function can read % either numeric or text entries in ascii files. % 'fields' - [Cell array] List of the name of each user-defined column, % optionally followed by a description. Ex: { 'type', 'latency' } % 'skipline' - [Interger] Number of header rows to skip in the text file % 'timeunit' - [ latency unit rel. to seconds ]. Default unit is 1 = seconds. % 'delim' - [string] String of delimiting characters in the input file. % Default is tab|space. % % Optional oldevent input: % 'append' - ['yes'|'no'] 'yes' = Append events to the current events in % the EEG dataset {default}: 'no' = Erase the previous events. % 'indices' - {integer vector] Vector indicating the indices of the events to % modify. % 'align' - [num] Align the first event latency to the latency of existing % event number (num), and check latency consistency. % 'optimalign' - ['on'|'off'] Optimize the sampling rate of the new events so % they best align with old events. Default is 'on'. % % Outputs: % EEG - EEG dataset with updated event fields % % Example: >> [EEG, eventnumbers] = pop_importevent(EEG, 'event', ... % 'event_values.txt', 'fields', {'type', 'latency','condition' }, ... % 'append', 'no', 'align', 0, 'timeunit', 1E-3 ); % % This loads the ascii file 'event_values.txt' containing 3 columns % (event_type, latency, and condition). Latencies in the file are % in ms (1E-3). The first event latency is re-aligned with the % beginning of the dataset ('align', 0). Any previous events % are erased ('append', 'no'). % % Author: Arnaud Delorme & Scott Makeig, CNL / Salk Institute, 9 Feb 2002 % % See also: importevent(), pop_editeventfield(), pop_selectevent() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 9 Feb 2002, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG, com] = pop_importevent(EEG, varargin); com =''; if nargin < 1 help pop_importevent; return; end; if isempty(EEG.data) disp('pop_importevent(): error: cannot process empty dataset'); return; end; I = []; % warning if data epochs % ---------------------- if nargin<2 & EEG.trials > 1 questdlg2(strvcat('Though epoch information is defined in terms of the event structure,', ... 'this function is usually used to import events into continuous data.', ... 'For epoched data, use menu item ''File > Import epoch info'''), ... 'pop_importevent warning', 'OK', 'OK'); end; % remove the event field % ---------------------- if ~isempty(EEG.event), allfields = fieldnames(EEG.event); else allfields = {}; end; if nargin<2 commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ... 'if filename ~=0,' ... ' set(findobj(''parent'', gcbf, ''tag'', tagtest), ''string'', [ filepath filename ]);' ... 'end;' ... 'clear filename filepath tagtest;' ]; helpfields = ['latency field (lowercase) must be present; field ''type'' and' 10 ... '''duration'' are also recognized keywords and it is recommended to define them']; uilist = { ... { 'Style', 'text', 'string', 'Event indices', 'fontweight', 'bold' }, ... { 'Style', 'text', 'string', 'Append events?', 'fontweight', 'bold' } }; geometry = { [ 1 1.1 1.1 1] [ 1 1 2] [1 1 2] [ 1.2 1 1] }; uilist = { uilist{:}, ... { 'Style', 'text', 'string', 'Event file or array', 'horizontalalignment', 'right', 'fontweight', 'bold' }, ... { 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''globfile'';' commandload ] }, ... { 'Style', 'edit' } ... { 'Style', 'checkbox', 'string', 'Yes/No', 'value', 0 }, ... { 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'globfile' }, ... { }, { 'Style', 'text', 'string', 'NB: No = overwrite', 'value', 0 }, { }, ... { 'Style', 'text', 'string', 'Input field (column) names ', 'fontweight', 'bold', 'tooltipstring', helpfields } ... { 'Style', 'edit', 'string', '' } { 'Style', 'text', 'string', 'Ex: type latency duration', 'tooltipstring', helpfields } }; geometry = { geometry{:} [1.2 1 1] [1.2 1 1] [1.2 1 1] [1.2 0.2 1.8] }; uilist = { uilist{:}, ... { 'Style', 'text', 'string', 'Number of file header lines', 'horizontalalignment', 'left' }, { 'Style', 'edit', 'string', '0' }, ... { 'Style', 'text', 'string', '(latency field required above)', 'tooltipstring', helpfields },... { 'Style', 'text', 'string', 'Time unit (sec)', 'horizontalalignment', 'left' }, { 'Style', 'edit', 'string', '1' } ... { 'Style', 'text', 'string', 'Ex: If ms, 1E-3; if points, NaN' },... { 'Style', 'text', 'string', 'Align event latencies to data events', 'horizontalalignment', 'left' }, ... { 'Style', 'edit', 'string', fastif(isempty(EEG.event),'NaN','0') } { 'Style', 'text', 'string', 'See Help' },... { 'Style', 'text', 'string', 'Auto adjust new events sampling rate', 'horizontalalignment', 'left' }, ... { 'Style', 'checkbox', 'value' 1 } { },... }; results = inputgui( geometry, uilist, 'pophelp(''pop_importevent'');', 'Import event info -- pop_importevent()' ); if length(results) == 0, return; end; % decode top inputs % ----------------- args = {}; if ~isempty( results{1} ), args = { args{:}, 'indices', eval( [ '[' results{1} ']' ]) }; end; if results{2} == 0 & ~isempty(EEG.event), args = { args{:}, 'append', 'no' }; end; if ~isempty( results{3} ), if isstr( results{3} ) && ~exist(results{3}) args = { args{:}, 'event', evalin('base', results{3}) }; else args = { args{:}, 'event', results{3} }; end; end; if ~isempty( results{4} ), args = { args{:}, 'fields', parsetxt(results{4}) }; end; % handle skipline % --------------- if ~isempty(eval(results{end-3})), if eval(results{end-3}) ~= 0, args = { args{:}, 'skipline', eval(results{end-3}) }; end; end; % handle timeunit % ------------- if ~isempty(eval(results{end-2})), if eval(results{end-2}) ~= 0, args = { args{:}, 'timeunit', eval(results{end-2}) }; end; end; % handle alignment % ---------------- if ~isempty(eval(results{end-1})), if ~isnan(eval(results{end-1})), args = { args{:}, 'align', eval(results{end-1}) }; end; end; if ~results{end} ~= 0, args = { args{:}, 'optimalign', 'off' }; end; else % no interactive inputs args = varargin; % scan args to modify array/file format % array are transformed into string % files are transformed into string of string % (this is usefull to build the string command for the function) % -------------------------------------------------------------- for index=1:2:length(args) if iscell(args{index+1}), if iscell(args{index+1}{1}) args{index+1} = args{index+1}{1}; end; end; % double nested if isstr(args{index+1}) & length(args{index+1}) > 2 & args{index+1}(1) == '''' & args{index+1}(end) == '''' args{index+1} = args{index+1}(2:end-1); end; %else if ~isempty( inputname(index+2) ), args{index+1} = inputname(index+2); end; %end; end; end; EEG.event = importevent( [], EEG.event, EEG.srate, args{:}); % generate ur variables % --------------------- EEG = eeg_checkset(EEG, 'eventconsistency'); EEG = eeg_checkset(EEG, 'makeur'); % generate the output command % --------------------------- com = sprintf('%s = pop_importevent( %s, %s);', inputname(1), inputname(1), vararg2str(args));
github
lcnbeapp/beapp-master
eeg_eventtypes.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/eeg_eventtypes.m
5,504
utf_8
d106acb9a7c18278b36620b4a206edb5
% eeg_eventtypes() - return a list of event or urevent types in a dataset and % the respective number of events of each type. Ouput event % types are sorted in reverse order of their number. If no % outputs, print this list on the commandline instead. % % Usage: % >> [types,numbers] = eeg_eventtypes(EEG); % Inputs: % EEG - EEGLAB dataset structure % Outputs: % types - cell array of event type strings % numbers - vector giving the numbers of each event type in the data % % Example: % >> eeg_eventtypes(EEG); % print numner of each event types % % Author: Scott Makeig, SCCN/INC/UCSD, April 28, 2004- % >> [types,numbers] = eeg_eventtypes(EEG,types); % >> [types,numbers] = eeg_eventtypes(EEG,'urevents',types); % Inputs: % EEG - EEGLAB dataset structure % 'urevents' - return event information for the EEG.urevent structure % types - {cell array} of event types to return or print. % Outputs: % types - cell array of event type strings % numbers - vector giving the numbers of each event type in the data % % Note: Numeric (ur)event types are converted to strings, so, for example, % types {13} and {'13'} are not distinguished. % % Example: % >> eeg_eventtypes(EEG); % print numner of each event types % % Curently disabled: % >> eeg_eventtypes(EEG,'urevent'); % print hist. of urevent types % >> eeg_eventtypes(EEG,{'rt'});% print number of 'rt' events % >> eeg_eventtypes(EEG,'urevent',{'rt','break'}); % % print numbers of 'rt' and 'break' % % type urevents % Copyright (C) 2004 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % % % event types can be numbers, Stefan Debener, 05/12/2006, % added 2nd and 3rd args, sorted outputs by number, Scott Makeig, 09/12/06 function [types,numbers] = eeg_eventtypes(EEG,arg2,arg3) if nargin< 1 help eeg_eventtypes return end if ~isstruct(EEG) error('EEG argument must be a dataset structure') end if ~isfield(EEG,'event') error('EEG.event field not found'); end if nargin > 1 error('Multiple input arguments are currently disabled'); end; UREVENTS = 0; % flag returning infor for urevents instead of events typelist = []; if nargin>1 if ischar(arg2) if strcmp(arg2,'urevent') | strcmp(arg2,'urevents') UREVENTS = 1; % change flag else error('second argument string not understood') end if nargin>2 if iscell(arg3) typelist = arg3; end end elseif iscell(arg2) typelist = arg2; end end if ~isempty(typelist) % cast to cell array of strings for k=1:length(typelist) if isnumeric(typelist{k}) typelist{k} = num2str(typelist{k}); end end end if ~UREVENTS nevents = length(EEG.event); alltypes = cell(nevents,1); for k=1:nevents if isnumeric(EEG.event(k).type) alltypes{k} = num2str(EEG.event(k).type); else alltypes{k} = EEG.event(k).type; end end else nevents = length(EEG.urevent); alltypes = cell(nevents,1); for k=1:nevents if isnumeric(EEG.urevent(k).type) alltypes{k} = num2str(EEG.urevent(k).type); else alltypes{k} = EEG.urevent(k).type; end end end [types i j] = unique_bc(alltypes); istypes = 1:length(types); notistypes = []; if ~isempty(typelist) notistypes = ismember_bc(typelist,types); istypes = ismember_bc(types,typelist(find(notistypes==1))); % types in typelist? notistypes = typelist(find(notistypes==0)); end types(~istypes) = []; % restrict types to typelist ntypes = length(types); numbers = zeros(ntypes + length(notistypes),1); for k=1:ntypes numbers(k) = length(find(j==k)); end types = [types(:); notistypes(:)]; % concatenate the types not found ntypes = length(types); for j = 1:length(notistypes) numbers(k+j) = 0; end % sort types in reverse order of event numbers [numbers nsort] = sort(numbers); numbers = numbers(end:-1:1); types = types(nsort(end:-1:1)); % % print output on commandline %%%%%%%%%%%%%%%%%%%%%%%%%%%% % if nargout < 1 fprintf('\n'); if UREVENTS fprintf('EEG urevent types:\n\n') else fprintf('EEG event types:\n\n') end maxx = 0; for k=1:ntypes x = length(types{k}); if x > maxx maxx = x; % find max type name length end end for k=1:ntypes fprintf(' %s',types{k}); for j=length(types{k})+1:maxx+4 fprintf(' '); end fprintf('%d\n',numbers(k)); end fprintf('\n'); clear types % no return variables end
github
lcnbeapp/beapp-master
pop_signalstat.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_signalstat.m
5,079
utf_8
5066bdd6d63e075bfeaf649483b7b2bb
% pop_signalstat() - Computes and plots statistical characteristics of a signal, % including the data histogram, a fitted normal distribution, % a normal ditribution fitted on trimmed data, a boxplot, and % the QQ-plot. The estimates value are printed in a panel and % can be read as output. See SIGNALSTAT. % Usage: % >> OUTEEG = pop_signalstat( EEG, type ); % pops up % >> [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh] = pop_signalstat( EEG, type, cnum ); % >> [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh] = pop_signalstat( EEG, type, cnum, percent ); % % Inputs: % EEG - input EEG dataset % type - type of processing % 1: process the raw data; 0: the ICA components % cnum - selected channel or component % % Outputs: % OUTEEG - output dataset % % Author: Luca Finelli, CNL / Salk Institute - SCCN, 2 August 2002 % % See also: % SIGNALSTAT, EEGLAB % Copyright (C) 2002 Luca Finelli, Salk/SCCN, La Jolla, CA % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function varargout = pop_signalstat( EEG, typeproc, cnum, percent ); % the command output is a hidden output that does not have to % be described in the header com = ''; % this initialization ensure that the function will return something % if the user press the cancel button varargout{1} = ''; % display help if not enough arguments % ------------------------------------ if nargin < 2 help pop_signalstat; return; end; popup=0; if nargin < 3 popup = 1; end; if nargin < 4 percent=5; end; % pop up window % ------------- if (nargin < 3 & typeproc==1) promptstr = { 'Channel number:'; 'Trim percentage (each end):' }; inistr = { '1';'5' }; result = inputdlg2( promptstr, 'Plot signal statistics -- pop_signalstat()', 1, inistr, 'signalstat'); if length( result ) == 0 return; end; cnum = eval( [ '[' result{1} ']' ] ); % the brackets allow processing Matlab arrays percent = eval( [ '[' result{2} ']' ] ); elseif (nargin < 3 & typeproc==0) promptstr = { 'Component number:'; 'Trim percentage (each end):' }; inistr = { '1'; '5' }; result = inputdlg2( promptstr, 'Plot signal statistics -- pop_signalstat()', 1, inistr, 'signalstat'); if length( result ) == 0 return; end; cnum = eval( [ '[' result{1} ']' ] ); % the brackets allow processing Matlab arrays percent = eval( [ '[' result{2} ']' ] ); end; if length(cnum) ~= 1 | (cnum-floor(cnum)) ~= 0 error('pop_signalstat(): Channel/component number must be a single integer'); end if cnum < 1 | cnum > EEG.nbchan error('pop_signalstat(): Channel/component number out of range'); end; % call function signalstat() either on raw data or ICA data % --------------------------------------------------------- if typeproc == 1 tmpsig=EEG.data(cnum,:); % [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh]=signalstat( EEG.data(cnum,:),1,[], percent); dlabel=[]; dlabel2=['Channel ' num2str(cnum)]; map = cnum; else if ~isempty( EEG.icasphere ) tmpsig = eeg_getdatact(EEG, 'component', cnum); tmpsig = tmpsig(:,:); % [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh]=signalstat( tmpsig,1,'Component Activity',percent); dlabel='Component Activity'; dlabel2=['Component ' num2str(cnum)]; map = EEG.icawinv(:,cnum); else error('You must run ICA first'); end; end; % outputs % ------- outstr = ''; if ~popup for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end; if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end; end; % return the string command % ------------------------- %fprintf('Pop_signalstat: computing statistics...\n'); varargout{1} = sprintf('pop_signalstat( %s, %d, %d );', inputname(1), typeproc, cnum); plotloc = 0; if ~isempty(EEG.chanlocs) if isfield(EEG.chanlocs, 'theta') if ~isempty(EEG.chanlocs(cnum).theta) plotloc = 1; end; end; end; if plotloc if typeproc == 1 com = sprintf('%s signalstat( tmpsig, 1, dlabel, percent, dlabel2, map, EEG.chanlocs );', outstr); else com = sprintf('%s signalstat( tmpsig, 1, dlabel, percent, dlabel2, map, EEG.chanlocs(EEG.icachansind) );', outstr); end; else com = sprintf('%s signalstat( tmpsig, 1, dlabel, percent, dlabel2);', outstr); end; eval(com) try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; return;
github
lcnbeapp/beapp-master
pop_rejchanspec.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_rejchanspec.m
10,691
utf_8
8549b5c2d8a05e2ca0aa177b4a248efc
% pop_rejchanspec() - reject artifacts channels in an EEG dataset using % channel spectrum. The average spectrum for all selected % is computed and a threshold is applied. % % Usage: % >> pop_rejchanspec( INEEG ) % pop-up interative window mode % >> [OUTEEG, indelec] = pop_rejchanspec( INEEG, 'key', 'val'); % % Inputs: % INEEG - input EEGLAB dataset % % Optional inputs: % 'freqlims' - [min max] frequency limits. May also be an array where % each row defines a different set of limits. Default is % 35 to the Niquist frequency of the data. % 'stdthresh' - [max] positive threshold in terms of standard deviation. % Default is 5. % 'absthresh' - [max] positive threshold in terms of spectrum units % (overides the option above). % 'averef' - ['on'|'off'] 'on' computes average reference before % applying threshold. Default is 'off'. % 'plothist' - ['on'|'off'] 'on' plot the histogram of values along % with the threshold. % 'plotchans' - ['on'|'off'] 'on' plot the channels scrollplot with % selected channels for rejection in red. Allow selected % channels rejection with the 'REJECT' button. % 'elec' - [integer array] only include specific channels. Default % is to use all channels. % 'specdata' - [fload array] use this array containing the precomputed % spectrum instead of computing the spectrum. Default is % empty. % 'specfreqs' - [fload array] frequency array for precomputed spectrum % above. % 'verbose' - ['on'|'off'] display information. Default is 'off'. % % Outputs: % OUTEEG - output dataset with updated joint probability array % indelec - indices of rejected electrodes % specdata - data spectrum for the selected channels % specfreqs - frequency array for spectrum above % % Author: Arnaud Delorme, CERCO, UPS/CNRS, 2008- % Copyright (C) 2008 Arnaud Delorme, CERCO, UPS/CNRS % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [EEG allrmchan specdata specfreqs com] = pop_rejchanspec(EEG, varargin) if nargin < 1 help pop_rejchanspec; return; end; allrmchan = []; specdata = []; specfreqs = []; com = ''; if nargin < 2 uilist = { { 'style' 'text' 'string' 'Electrode (number(s); Ex: 2 4 5)' } ... { 'style' 'edit' 'string' ['1:' int2str(EEG.nbchan)] } ... { 'style' 'text' 'string' 'Frequency limits [min max]' } ... { 'style' 'edit' 'string' [ '35 ' int2str(floor(EEG.srate/2)) ] } ... { 'style' 'text' 'string' 'Standard dev. threshold limits [max]' } ... { 'style' 'edit' 'string' '5' } ... { 'style' 'text' 'string' 'OR absolute threshold limit [min max]' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Compute average reference first (check=on)' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } { } ... { 'style' 'text' 'string' 'Plot histogram of power values (check=on)' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } { } ... { 'style' 'text' 'string' 'Plot channels scrollplot (check=on)' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } { } ... }; geom = { [2 1] [2 1] [2 1] [2 1] [2 0.3 0.7] [2 0.3 0.7] [2 0.3 0.7] }; result = inputgui( 'uilist', uilist, 'geometry', geom, 'title', 'Reject channel using spectrum -- pop_rejchanspec()', ... 'helpcom', 'pophelp(''pop_rejchan'')'); if isempty(result), return; end; options = { 'elec' eval( [ '[' result{1} ']' ] ) 'stdthresh' str2num(result{3}) 'freqlims' str2num(result{2}) }; if ~isempty(result{4}) options = { options{:} 'absthresh' str2num(result{4}) }; end; if result{5}, options = { options{:} 'averef', 'on' }; end; if result{6}, options = { options{:} 'plothist', 'on' }; end; % Begin: Added by Romain on 22 July 2010 if result{7}, options = { options{:} 'plotchans', 'on' }; end; % End: Added by Romain on 22 July 2010 else options = varargin; end; % decode options % -------------- opt = finputcheck( options, { 'averef' 'string' { 'on';'off' } 'off'; 'plothist' 'string' { 'on';'off' } 'off'; 'plotchans' 'string' { 'on';'off' } 'off'; 'verbose' 'string' { 'on';'off' } 'off'; 'elec' 'integer' [] [1:EEG.nbchan]; 'freqlims' 'real' [] [35 EEG.srate/2]; 'specdata' 'real' [] []; 'specfreqs' 'real' [] []; 'absthresh' 'real' [] []; 'stdthresh' 'real' [] 5 }, 'pop_rejchanspec'); if isstr(opt), error(opt); end; % compute average referecne if necessary if strcmpi(opt.averef, 'on') NEWEEG = pop_reref(EEG, [], 'exclude', setdiff([1:EEG.nbchan], opt.elec)); else NEWEEG = EEG; end; if isempty(opt.specdata) [tmpspecdata specfreqs] = pop_spectopo(NEWEEG, 1, [], 'EEG' , 'percent', 100, 'freqrange',[0 EEG.srate/2], 'plot', 'off'); % add back 0 channels devStd = std(EEG.data(:,:), [], 2); if any(devStd == 0) goodchan = find(devStd ~= 0); specdata = zeros(length(opt.elec), size(tmpspecdata,2)); specdata(goodchan,:) = tmpspecdata; else specdata = tmpspecdata; end; else specdata = opt.specdata; specfreqs = opt.specfreqs; end; if size(opt.stdthresh,1) == 1 && size(opt.freqlims,1) > 1 opt.stdthresh = ones(length(opt.stdthresh), size(opt.freqlims,1))*opt.stdthresh; end; allrmchan = []; for index = 1:size(opt.freqlims,1) % select frequencies, compute median and std then reject channels % --------------------------------------------------------------- [tmp fbeg] = min(abs(specfreqs - opt.freqlims(index,1))); [tmp fend] = min(abs(specfreqs - opt.freqlims(index,2))); selectedspec = mean(specdata(opt.elec, fbeg:fend), 2); if ~isempty(opt.absthresh) rmchan = find(selectedspec <= opt.absthresh(1) | selectedspec >= opt.absthresh(2)); else m = median(selectedspec); s = std( selectedspec); nbTresh = size(opt.stdthresh); if length(opt.stdthresh) > 1 rmchan = find(selectedspec <= m+s*opt.stdthresh(index,1) | selectedspec >= m+s*opt.stdthresh(index,2)); else rmchan = find(selectedspec > m+s*opt.stdthresh(index)); end end; % print out results % ----------------- if isempty(rmchan) textout = sprintf('Range %2.1f-%2.1f Hz: no channel removed\n', opt.freqlims(index,1), opt.freqlims(index,2)); else textout = sprintf('Range %2.1f-%2.1f Hz: channels %s removed\n', opt.freqlims(index,1), opt.freqlims(index,2), int2str(opt.elec(rmchan'))); end; fprintf(textout); if strcmpi(opt.verbose, 'on') for inde = 1:length(opt.elec) if ismember(inde, rmchan) fprintf('Elec %s power: %1.2f *\n', EEG.chanlocs(opt.elec(inde)).labels, selectedspec(inde)); else fprintf('Elec %s power: %1.2f\n', EEG.chanlocs(opt.elec(inde)).labels , selectedspec(inde)); end; end; end; allrmchan = [ allrmchan rmchan' ]; % plot histogram % -------------- if strcmpi(opt.plothist, 'on') figure; hist(selectedspec); hold on; yl = ylim; if ~isempty(opt.absthresh) plot([opt.absthresh(1) opt.absthresh(1)], yl, 'r'); plot([opt.absthresh(2) opt.absthresh(2)], yl, 'r'); else if length(opt.stdthresh) > 1 threshold1 = m+s*opt.stdthresh(index,1); threshold2 = m+s*opt.stdthresh(index,2); plot([m m], yl, 'g'); plot([threshold1 threshold1], yl, 'r'); plot([threshold2 threshold2], yl, 'r'); else threshold = m+s*opt.stdthresh(index,1); plot([threshold threshold], yl, 'r'); end end; title(textout); end; end; allrmchan = unique_bc(allrmchan); com = sprintf('EEG = pop_rejchan(EEG, %s);', vararg2str(options)); if strcmpi(opt.plotchans, 'on') tmpcom = [ 'EEGTMP = pop_select(EEG, ''nochannel'', [' num2str(opt.elec(allrmchan)) ']);' ]; tmpcom = [ tmpcom ... 'LASTCOM = ' vararg2str(com) ';' ... '[ALLEEG EEG CURRENTSET tmpcom] = pop_newset(ALLEEG, EEGTMP, CURRENTSET);' ... ' if ~isempty(tmpcom),' ... ' EEG = eegh(LASTCOM, EEG);' ... ' eegh(tmpcom);' ... ' eeglab(''redraw'');' ... ' end; clear EEGTMP tmpcom;' ]; colors = cell(1,length(opt.elec)); colors(:) = { 'k' }; colors(allrmchan) = { 'r' }; colors = colors(end:-1:1); fprintf('%d electrodes labeled for rejection\n', length(find(allrmchan))); tmpchanlocs = EEG.chanlocs; if ~isempty(EEG.chanlocs), tmplocs = EEG.chanlocs(opt.elec); tmpelec = { tmpchanlocs(opt.elec).labels }'; else tmplocs = []; tmpelec = mattocell([1:EEG.nbchan]'); end; eegplot(EEG.data(opt.elec,:,:), 'srate', EEG.srate, 'title', 'Scroll component activities -- eegplot()', ... 'limits', [EEG.xmin EEG.xmax]*1000, 'color', colors, 'eloc_file', tmplocs, 'command', tmpcom); else EEG = pop_select(EEG, 'nochannel', opt.elec(allrmchan)); end; if nargin < 2 allrmchan = sprintf('EEG = pop_rejchanspec(EEG, %s);', vararg2str(options)); end;
github
lcnbeapp/beapp-master
pop_rejtrend.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_rejtrend.m
9,362
utf_8
8dba06eafda1461d9b44d39f9dfa3e5f
% pop_rejtrend() - Measure linear trends in EEG data; reject data epochs % containing strong trends. % Usage: % >> pop_rejtrend( INEEG, typerej); % pop up an interactive window % >> OUTEEG = pop_rejtrend( INEEG, typerej, elec_comp, ... % winsize, maxslope, minR, superpose, reject,calldisp); % % Pop-up window interface: % "Electrode|Component indices(s)" - [edit box] electrode or component indices % to take into consideration during rejection. Sets the 'elec_comp' % parameter in the command line call (see below). % "Slope window width" - [edit box] integer number of consecutive data % points to use in detecting linear trends. Sets the 'winsize' % parameter in the command line call. % "Maximum slope to allow" - [edit box] maximal absolute slope of the % linear trend to allow in the data. If electrode data, uV/epoch; % if component data, std. dev./epoch. Sets the 'maxslope' % parameter in the command line call. % "R-square limit" -[edit box] maximal regression R-square (0 to 1) value % to allow. Sets the 'minR' parameter in the command line call. % This represents how "line-like" the rejected data should be; 0 % accepts everything that meets the slope requirement, 0.9 is visibly % flat. % "Display with previous rejection(s)" - [checkbox] This checkbox set the % command line input option 'superpose'. % "Reject marked trial(s)" - [checkbox] This checkbox set the command % line input option 'reject'. % Command line inputs: % INEEG - input EEG dataset % typerej - [1|0] data to reject on: 0 = component activations; % 1 = electrode data. {Default: 1}. % elec_comp - [e1 e2 ...] electrode|component number(s) to take into % consideration during rejection % winsize - (integer) number of consecutive points % to use in detecing linear trends % maxslope - maximal absolute slope of the linear trend to allow in the data % minR - minimal linear regression R-square value to allow in the data % (= coefficient of determination, between 0 and 1) % superpose - [0|1] 0 = Do not superpose marks on previous marks % stored in the dataset; 1 = Show both types of marks using % different colors. {Default: 0} % reject - [1|0] 0 = Do not reject marked trials but store the % labels; 1 = Reject marked trials. {Default: 1} % calldisp - [0|1] 1 = Open scroll window indicating rejected trials % 0 = Do not open scroll window. {Default: 1} % % Outputs: % OUTEEG - output dataset with rejected trials marked for rejection % Note: When eegplot() is called, modifications are applied to the current % dataset at the end of the call to eegplot() (e.g., when the user presses % the 'Reject' button). % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: rejtrend(), eeglab(), eegplot(), pop_rejepoch() % Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 01-25-02 reformated help & license -ad % 03-07-02 added srate argument to eegplot call -ad % 03-07-02 add the eeglab options -ad function [EEG, com] = pop_rejtrend( EEG, icacomp, elecrange, winsize, ... minslope, minstd, superpose, reject, calldisp); com = ''; if nargin < 1 help pop_rejtrend; return; end; if nargin < 2 icacomp = 1; end; if icacomp == 0 if isempty( EEG.icasphere ) ButtonName=questdlg( 'Do you want to run ICA now ?', ... 'Confirmation', 'NO', 'YES', 'YES'); switch ButtonName, case 'NO', disp('Operation cancelled'); return; case 'YES', [ EEG com ] = pop_runica(EEG); end % switch end; end; if exist('reject') ~= 1 reject = 1; end; if nargin < 3 % which set to save % ----------------- promptstr = { [fastif(icacomp, 'Electrode', 'Component') ' (indices; Ex: 2 6:8 10):' ], ... 'Slope window width (in points)', ... [fastif(icacomp,'Maximum slope to allow (std. dev./epoch)','Maximum slope to allow (uV/epoch)')], ... 'R-square limit to allow ([0:1], Ex: 0.8)', ... 'Display previous rejection marks', ... 'Reject marked trial(s)' }; inistr = { ['1:' int2str(EEG.nbchan)], ... int2str(EEG.pnts), ... '0.5', ... '0.3', ... '0', ... '0' }; g1 = [1 0.1 0.75]; g2 = [1 0.22 0.85]; geometry = {g1 g1 g1 g1 1 g2 g2}; uilist = {... { 'Style', 'text', 'string', promptstr{1}} {} { 'Style','edit' ,'string' ,inistr{1} 'tag' 'cpnum'}... { 'Style', 'text', 'string', promptstr{2}} {} { 'Style','edit' ,'string' ,inistr{2} 'tag' 'win' }... { 'Style', 'text', 'string', promptstr{3}} {} { 'Style','edit' ,'string' ,inistr{3} 'tag' 'maxslope'}... { 'Style', 'text', 'string', promptstr{4}} {} { 'Style','edit' ,'string' ,inistr{4} 'tag' 'rlim'}... {}... { 'Style', 'text', 'string', promptstr{5}} {} { 'Style','checkbox' ,'string' ,' ' 'value' str2double(inistr{6}) 'tag','rejmarks' }... { 'Style', 'text', 'string', promptstr{6}} {} { 'Style','checkbox' ,'string' ,' ' 'value' str2double(inistr{6}) 'tag' 'rejtrials'} ... }; figname = fastif(~icacomp, 'Trend rejection in component(s) -- pop_rejtrend()','Data trend rejection -- pop_rejtrend()'); result = inputgui( geometry,uilist,'pophelp(''pop_rejtrend'');', figname); size_result = size( result ); if size_result(1) == 0 return; end; elecrange = result{1}; winsize = result{2}; minslope = result{3}; minstd = result{4}; superpose = result{5}; reject = result{6}; calldisp = 1; end; if ~exist('superpose','var'), superpose = 0; end; if ~exist('reject','var'), reject = 0; end; if ~exist('calldisp','var'), calldisp = 1; end; if nargin < 9 calldisp = 1; end if isstr(elecrange) % convert arguments if they are in text format calldisp = 1; elecrange = eval( [ '[' elecrange ']' ] ); winsize = eval( [ '[' winsize ']' ] ); minslope = eval( [ '[' minslope ']' ] ); minstd = eval( [ '[' minstd ']' ] ); end; fprintf('Selecting trials...\n'); if icacomp == 1 [rej tmprejE] = rejtrend( EEG.data(elecrange, :, :), winsize, minslope, minstd); rejE = zeros(EEG.nbchan, length(rej)); rejE(elecrange,:) = tmprejE; else % test if ICA was computed or if one has to compute on line % --------------------------------------------------------- icaacttmp = eeg_getdatact(EEG, 'component', elecrange); [rej tmprejE] = rejtrend( icaacttmp, winsize, minslope, minstd); rejE = zeros(size(icaacttmp,1), length(rej)); rejE(elecrange,:) = tmprejE; end rejtrials = find(rej > 0); fprintf('%d channel(s) selected\n', size(elecrange(:), 1)); fprintf('%d/%d trial(s) marked for rejection\n', length(rejtrials), EEG.trials); fprintf('The following trials have been marked for rejection\n'); fprintf([num2str(rejtrials) '\n']); if calldisp if icacomp == 1 macrorej = 'EEG.reject.rejconst'; macrorejE = 'EEG.reject.rejconstE'; else macrorej = 'EEG.reject.icarejconst'; macrorejE = 'EEG.reject.icarejconstE'; end; colrej = EEG.reject.rejconstcol; eeg_rejmacro; % script macro for generating command and old rejection arrays if icacomp == 1 eegplot( EEG.data(elecrange,:,:), 'srate', ... EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}); else eegplot( icaacttmp, 'srate', ... EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:}); end; end; if ~isempty(rej) if icacomp == 1 EEG.reject.rejconst = rej; EEG.reject.rejconstE = rejE; else EEG.reject.icarejconst = rej; EEG.reject.icarejconstE = rejE; end; if reject EEG = pop_rejepoch(EEG, rej, 0); end; end; %com = sprintf('Indexes = pop_rejtrend( %s, %d, [%s], %s, %s, %s, %d, %d);', ... % inputname(1), icacomp, num2str(elecrange), num2str(winsize), num2str(minslope), num2str(minstd), superpose, reject ); com = [ com sprintf('%s = pop_rejtrend(%s,%s);', inputname(1), ... inputname(1), vararg2str({icacomp,elecrange,winsize,minslope,minstd,superpose,reject})) ]; return;
github
lcnbeapp/beapp-master
pop_selectevent.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_saveh.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_resample.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_resample.m
14,124
utf_8
52b242667b55f1f380dd7af602a5dd30
% 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; % % Recompute event latencies if isfield(EEG.event, 'duration') && ~isempty(EEG.event(iEvt).duration) EEG.event( iEvt ).duration = EEG.event( iEvt ).duration * p/q; end 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 % Recompute event duration relative to segment onset if isfield(EEG.event, 'duration') && ~isempty(EEG.event(iEvt).duration) EEG.event( iEvt ).duration = EEG.event( iEvt ).duration * p/q; 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
lcnbeapp/beapp-master
eeg_eventformat.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_newset.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_runscript.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_headplot.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_loadset.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_selectcomps.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_readsegegi.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_rmbase.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_rmbase.m
7,439
utf_8
45f9353a46caf1ebb9c14f4c7932108c
% 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 -> 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
lcnbeapp/beapp-master
pop_fileiodir.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_prop.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_getepochevent.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_timeinterp.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_comments.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_emptyset.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_eventstat.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
getchanlist.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_biosig.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_export.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_rejchan.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_countepochs.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_chanedit.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_newcrossf.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_spectopo.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_epoch.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_epoch.m
17,195
utf_8
cb4172d9f03084762bf3df81100a49d3
% 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,1)) ' ' num2str(round(EEG.xmax,1))]; % Units in seconds as in GUI % epochlim = [num2str( round(EEG.xmin*1000,1)) ' 'num2str(round(EEG.xmax*1000,1))]; % Units in miliseconds 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
lcnbeapp/beapp-master
pop_importerplab.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_eventhist.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_latencyur.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_importev2.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_biosig16ying.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_insertboundold.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_oldica.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_plotdata.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_eegfilt.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_subcomp.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_topoplot.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_pvaf.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_copyset.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_chaninds.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_readegi.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_erpimage.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_epochformat.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_urlatency.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_context.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_biosig16.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_chanevent.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_rejspec.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_topoplot.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_mergechan.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_interp.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_importepoch.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_writeeeg.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_chancenter.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_rejsuperpose.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_rejcont.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_chansel.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_importpres.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_rejkurt.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_writelocs.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_mergelocs.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_plottopo.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_loaddat.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_crossf.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_timtopo.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_multieegplot.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_chancoresp.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_select.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_rmdat.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_editeventfield.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/popfunc/pop_editeventfield.m
21,898
utf_8
e895d5ffff1cfc32d48b50e0c74ae4d2
% 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). % Units must be in seconds (s). % '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
lcnbeapp/beapp-master
eeg_mergelocs_diffstruct.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_envtopo.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_readlocs.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pop_runica.m
.m
beapp-master/Packages/eeglab14_1_2b/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;