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
eegplugin_firfilt.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/firfilt1.6.2/eegplugin_firfilt.m
2,667
utf_8
681ba5e0933cafd6bb95672f910816cd
% eegplugin_firfilt() - EEGLAB plugin for filtering data using linear- % phase FIR filters % % Usage: % >> eegplugin_firfilt(fig, trystrs, catchstrs); % % Inputs: % fig - [integer] EEGLAB figure % trystrs - [struct] "try" strings for menu callbacks. % catchstrs - [struct] "catch" strings for menu callbacks. % % Author: Andreas Widmann, University of Leipzig, Germany, 2005 %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2005 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function vers = eegplugin_firfilt(fig, trystrs, catchstrs) vers = 'firfilt1.6.1'; if nargin < 3 error('eegplugin_firfilt requires 3 arguments'); end % add folder to path % ----------------------- if ~exist('pop_firws') p = which('eegplugin_firfilt'); p = p(1:findstr(p,'eegplugin_firfilt.m')-1); addpath([p vers]); end % find import data menu % --------------------- menu = findobj(fig, 'tag', 'filter'); % menu callbacks % -------------- comfirfiltnew = [trystrs.no_check '[EEG LASTCOM] = pop_eegfiltnew(EEG);' catchstrs.new_and_hist]; comfirws = [trystrs.no_check '[EEG LASTCOM] = pop_firws(EEG);' catchstrs.new_and_hist]; comfirpm = [trystrs.no_check '[EEG LASTCOM] = pop_firpm(EEG);' catchstrs.new_and_hist]; comfirma = [trystrs.no_check '[EEG LASTCOM] = pop_firma(EEG);' catchstrs.new_and_hist]; % create menus if necessary % ------------------------- uimenu( menu, 'Label', 'Basic FIR filter (new, default)', 'CallBack', comfirfiltnew, 'Separator', 'on', 'position', 1); uimenu( menu, 'Label', 'Windowed sinc FIR filter', 'CallBack', comfirws, 'position', 2); uimenu( menu, 'Label', 'Parks-McClellan (equiripple) FIR filter', 'CallBack', comfirpm, 'position', 3); uimenu( menu, 'Label', 'Moving average FIR filter', 'CallBack', comfirma, 'position', 4);
github
lcnbeapp/beapp-master
windows.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/firfilt1.6.2/windows.m
2,876
utf_8
581c2f660f641935667a234f9b024f3a
% windows() - Returns handle to window function or window % % Usage: % >> h = windows(t); % >> h = windows(t, m); % >> h = windows(t, m, a); % % Inputs: % t - char array 'rectangular', 'bartlett', 'hann', 'hamming', % 'blackman', 'blackmanharris', or 'kaiser' % % Optional inputs: % m - scalar window length % a - scalar or vector with window parameter(s) % % Output: % h - function handle or column vector window % % Author: Andreas Widmann, University of Leipzig, 2005 %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2005 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function h = windows(t, m, a) if nargin < 1 error('Not enough input arguments.'); end h = str2func(t); switch nargin case 2 h = h(m); case 3 h = h(m, a); end end function w = rectangular(m) w = ones(m, 1); end function w = bartlett(m) w = 1 - abs(-1:2 / (m - 1):1)'; end % von Hann function w = hann(m); w = hamming(m, 0.5); end % Hamming function w = hamming(m, a) if nargin < 2 || isempty(a) a = 25 / 46; end m = [0:1 / (m - 1):1]'; w = a - (1 - a) * cos(2 * pi * m); end % Blackman function w = blackman(m, a) if nargin < 2 || isempty(a) a = [0.42 0.5 0.08 0]; end m = [0:1 / (m - 1):1]'; w = a(1) - a(2) * cos (2 * pi * m) + a(3) * cos(4 * pi * m) - a(4) * cos(6 * pi * m); end % Blackman-Harris function w = blackmanharris(m) w = blackman(m, [0.35875 0.48829 0.14128 0.01168]); end % Kaiser function w = kaiser(m, a) if nargin < 2 || isempty(a) a = 0.5; end m = [-1:2 / (m - 1):1]'; w = besseli(0, a * sqrt(1 - m.^2)) / besseli(0, a); end % Tukey function w = tukey(m, a) if nargin < 2 || isempty(a) a = 0.5; end if a <= 0 w = ones(m, 1); elseif a >= 1 w = hann(m); else a = (m - 1) / 2 * a; tapArray = (0:a)' / a; w = [0.5 - 0.5 * cos(pi * tapArray); ... ones(m - 2 * length(tapArray), 1); ... 0.5 - 0.5 * cos(pi * tapArray(end:-1:1))]; end end
github
lcnbeapp/beapp-master
pop_firpmord.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/firfilt1.6.2/pop_firpmord.m
3,145
utf_8
f4dae3b8e73f8ab3d73c2d207506ddd8
% pop_firpmord() - Estimate Parks-McClellan filter order and weights % % Usage: % >> [m, wtpass, wtstop] = pop_firpmord(f, a); % pop-up window mode % >> [m, wtpass, wtstop] = pop_firpmord(f, a, dev); % >> [m, wtpass, wtstop] = pop_firpmord(f, a, dev, fs); % % Inputs: % f - vector frequency band edges % a - vector desired amplitudes on bands defined by f % dev - vector allowable deviations on bands defined by f % % Optional inputs: % fs - scalar sampling frequency {default 2} % % Output: % m - scalar estimated filter order % wtpass - scalar passband weight % wtstop - scalar stopband weight % % Note: % Requires the signal processing toolbox. Convert passband ripple from % dev to peak-to-peak dB: rp = 20 * log10((1 + dev) / (1 - dev)). % Convert stopband attenuation from dev to dB: rs = 20 * log10(dev). % % Author: Andreas Widmann, University of Leipzig, 2005 % % See also: % pop_firpm, firpm, firpmord %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2005 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [m, wtpass, wtstop] = pop_firpmord(f, a, dev, fs) m = []; wtpass = []; wtstop = []; if exist('firpmord') ~= 2 error('Requires the signal processing toolbox.'); end if nargin < 2 || isempty(f) || isempty(a) error('Not enough input arguments'); end % Sampling frequency if nargin < 4 || isempty(fs) fs = 2; end % GUI if nargin < 3 || isempty(dev) drawnow; uigeom = {[1 1] [1 1]}; uilist = {{'style' 'text' 'string' 'Peak-to-peak passband ripple (dB):'} ... {'style' 'edit'} ... {'style' 'text' 'string' 'Stopband attenuation (dB):'} ... {'style' 'edit'}}; result = inputgui(uigeom, uilist, 'pophelp(''pop_firpmord'')', 'Estimate filter order and weights -- pop_firpmord()'); if length(result) == 0, return, end if ~isempty(result{1}) rp = str2num(result{1}); rp = (10^(rp / 20) - 1) / (10^(rp / 20) + 1); dev(find(a == 1)) = rp; else error('Not enough input arguments.'); end if ~isempty(result{2}) rs = str2num(result{2}); rs = 10^(-abs(rs) / 20); dev(find(a == 0)) = rs; else error('Not enough input arguments.'); end end [m, fo, ao, w] = firpmord(f, a, dev, fs); wtpass = w(find(a == 1, 1)); wtstop = w(find(a == 0, 1));
github
lcnbeapp/beapp-master
firfilt.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/firfilt1.6.2/firfilt.m
4,262
utf_8
d5703bbd52180bfb0661e6db5e649967
% firfilt() - Pad data with DC constant, filter data with FIR filter, % and shift data by the filter's group delay % % Usage: % >> EEG = firfilt(EEG, b, nFrames); % % Inputs: % EEG - EEGLAB EEG structure % b - vector of filter coefficients % % Optional inputs: % nFrames - number of frames to filter per block {default 1000} % % Outputs: % EEG - EEGLAB EEG structure % % Note: % Higher values for nFrames increase speed and working memory % requirements. % % Author: Andreas Widmann, University of Leipzig, 2005 % % See also: % filter, findboundaries %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2005 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % 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 = firfilt(EEG, b, nFrames) if nargin < 2 error('Not enough input arguments.'); end if nargin < 3 || isempty(nFrames) nFrames = 1000; end % Filter's group delay if mod(length(b), 2) ~= 1 error('Filter order is not even.'); end groupDelay = (length(b) - 1) / 2; % Find data discontinuities and reshape epoched data if EEG.trials > 1 % Epoched data EEG.data = reshape(EEG.data, [EEG.nbchan EEG.pnts * EEG.trials]); dcArray = 1 : EEG.pnts : EEG.pnts * (EEG.trials + 1); else % Continuous data dcArray = [findboundaries(EEG.event) EEG.pnts + 1]; end % Initialize progress indicator nSteps = 20; step = 0; fprintf(1, 'firfilt(): |'); strLength = fprintf(1, [repmat(' ', 1, nSteps - step) '| 0%%']); tic for iDc = 1:(length(dcArray) - 1) % Pad beginning of data with DC constant and get initial conditions ziDataDur = min(groupDelay, dcArray(iDc + 1) - dcArray(iDc)); [temp, zi] = filter(b, 1, double([EEG.data(:, ones(1, groupDelay) * dcArray(iDc)) ... EEG.data(:, dcArray(iDc):(dcArray(iDc) + ziDataDur - 1))]), [], 2); blockArray = [(dcArray(iDc) + groupDelay):nFrames:(dcArray(iDc + 1) - 1) dcArray(iDc + 1)]; for iBlock = 1:(length(blockArray) - 1) % Filter the data [EEG.data(:, (blockArray(iBlock) - groupDelay):(blockArray(iBlock + 1) - groupDelay - 1)), zi] = ... filter(b, 1, double(EEG.data(:, blockArray(iBlock):(blockArray(iBlock + 1) - 1))), zi, 2); % Update progress indicator [step, strLength] = mywaitbar((blockArray(iBlock + 1) - groupDelay - 1), size(EEG.data, 2), step, nSteps, strLength); end % Pad end of data with DC constant temp = filter(b, 1, double(EEG.data(:, ones(1, groupDelay) * (dcArray(iDc + 1) - 1))), zi, 2); EEG.data(:, (dcArray(iDc + 1) - ziDataDur):(dcArray(iDc + 1) - 1)) = ... temp(:, (end - ziDataDur + 1):end); % Update progress indicator [step, strLength] = mywaitbar((dcArray(iDc + 1) - 1), size(EEG.data, 2), step, nSteps, strLength); end % Reshape epoched data if EEG.trials > 1 EEG.data = reshape(EEG.data, [EEG.nbchan EEG.pnts EEG.trials]); end % Deinitialize progress indicator fprintf(1, '\n') end function [step, strLength] = mywaitbar(compl, total, step, nSteps, strLength) progStrArray = '/-\|'; tmp = floor(compl / total * nSteps); if tmp > step fprintf(1, [repmat('\b', 1, strLength) '%s'], repmat('=', 1, tmp - step)) step = tmp; ete = ceil(toc / step * (nSteps - step)); strLength = fprintf(1, [repmat(' ', 1, nSteps - step) '%s %3d%%, ETE %02d:%02d'], progStrArray(mod(step - 1, 4) + 1), floor(step * 100 / nSteps), floor(ete / 60), mod(ete, 60)); end end
github
lcnbeapp/beapp-master
pop_firws.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/firfilt1.6.2/pop_firws.m
10,634
utf_8
830347cf85c318140462a11e9257b53b
% pop_firws() - Filter data using windowed sinc FIR filter % % Usage: % >> [EEG, com, b] = pop_firws(EEG); % pop-up window mode % >> [EEG, com, b] = pop_firws(EEG, 'key1', value1, 'key2', ... % value2, 'keyn', valuen); % % Inputs: % EEG - EEGLAB EEG structure % 'fcutoff' - vector or scalar of cutoff frequency/ies (-6 dB; Hz) % 'forder' - scalar filter order. Mandatory even % % Optional inputs: % 'ftype' - char array filter type. 'bandpass', 'highpass', % 'lowpass', or 'bandstop' {default 'bandpass' or % 'lowpass', depending on number of cutoff frequencies} % 'wtype' - char array window type. 'rectangular', 'bartlett', % 'hann', 'hamming', 'blackman', or 'kaiser' {default % 'blackman'} % 'warg' - scalar kaiser beta % 'minphase' - scalar boolean minimum-phase converted causal filter % {default false} % % Outputs: % EEG - filtered EEGLAB EEG structure % com - history string % b - filter coefficients % % Note: % Window based filters' transition band width is defined by filter % order and window type/parameters. Stopband attenuation equals % passband ripple and is defined by the window type/parameters. Refer % to table below for typical parameters. (Windowed sinc) symmetric FIR % filters have linear phase and can be made zero phase (non-causal) by % shifting the data by the filters group delay (what firfilt does by % default). Pi phase jumps noticable in the phase reponse reflect a % negative frequency response and only occur in the stopband. pop_firws % also allows causal filtering with minimum-phase (non-linear!) converted % filter coefficients with similar properties. Non-linear causal % filtering is NOT recommended for most use cases. % % Beta Max stopband Max passband Max passband Transition width Mainlobe width % attenuation deviation ripple (dB) (normalized freq) (normalized rad freq) % (dB) % Rectangular -21 0.0891 1.552 0.9 / m* 4 * pi / m % Bartlett -25 0.0562 0.977 8 * pi / m % Hann -44 0.0063 0.109 3.1 / m 8 * pi / m % Hamming -53 0.0022 0.038 3.3 / m 8 * pi / m % Blackman -74 0.0002 0.003 5.5 / m 12 * pi / m % Kaiser 5.653 -60 0.001 0.017 3.6 / m % Kaiser 7.857 -80 0.0001 0.002 5.0 / m % * m = filter order % % Author: Andreas Widmann, University of Leipzig, 2005 % % See also: % firfilt, firws, pop_firwsord, pop_kaiserbeta, plotfresp, windows %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2005 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % 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, b] = pop_firws(EEG, varargin) com = ''; if nargin < 1 help pop_firws; return; end if isempty(EEG.data) error('Cannot process empty dataset'); end if nargin < 2 drawnow; ftypes = {'bandpass', 'highpass', 'lowpass', 'bandstop'}; ftypesStr = {'Bandpass', 'Highpass', 'Lowpass', 'Bandstop'}; wtypes = {'rectangular', 'bartlett', 'hann', 'hamming', 'blackman', 'kaiser'}; wtypesStr = {'Rectangular (PB dev=0.089, SB att=-21dB)', 'Bartlett (PB dev=0.056, SB att=-25dB)', 'Hann (PB dev=0.006, SB att=-44dB)', 'Hamming (PB dev=0.002, SB att=-53dB)', 'Blackman (PB dev=0.0002, SB att=-74dB)', 'Kaiser'}; uigeom = {[1 0.75 0.75] [1 0.75 0.75] 1 [1 0.75 0.75] [1 0.75 0.75] [1 0.75 0.75] [1 1.5] 1 [1 0.75 0.75]}; uilist = {{'Style' 'text' 'String' 'Cutoff frequency(ies) [hp lp] (-6 dB; Hz):'} ... {'Style' 'edit' 'String' '' 'Tag' 'fcutoffedit'} {} ... {'Style' 'text' 'String' 'Filter type:'} ... {'Style' 'popupmenu' 'String' ftypesStr 'Tag' 'ftypepop'} {} ... {} ... {'Style' 'text' 'String' 'Window type:'} ... {'Style' 'popupmenu' 'String' wtypesStr 'Tag' 'wtypepop' 'Value' 5 'Callback' 'temp = {''off'', ''on''}; set(findobj(gcbf, ''-regexp'', ''Tag'', ''^warg''), ''Enable'', temp{double(get(gcbo, ''Value'') == 6) + 1}), set(findobj(gcbf, ''Tag'', ''wargedit''), ''String'', '''')'} {} ... {'Style' 'text' 'String' 'Kaiser window beta:' 'Tag' 'wargtext' 'Enable' 'off'} ... {'Style' 'edit' 'String' '' 'Tag' 'wargedit' 'Enable' 'off'} ... {'Style' 'pushbutton' 'String' 'Estimate' 'Tag' 'wargpush' 'Enable' 'off' 'Callback' @comwarg} ... {'Style' 'text' 'String' 'Filter order (mandatory even):'} ... {'Style' 'edit' 'String' '' 'Tag' 'forderedit'} ... {'Style' 'pushbutton' 'String' 'Estimate' 'Callback' {@comforder, wtypes, EEG.srate}} ... {} {'Style' 'checkbox', 'String', 'Use minimum-phase converted causal filter (non-linear!; beta)', 'Tag' 'minphase', 'Value', 0} ... {'Style' 'edit' 'Tag' 'devedit' 'Visible' 'off'} ... {} {} {'Style' 'pushbutton' 'String', 'Plot filter responses' 'Callback' {@comfresp, wtypes, ftypes, EEG.srate}}}; result = inputgui(uigeom, uilist, 'pophelp(''pop_firws'')', 'Filter the data -- pop_firws()'); if isempty(result), return; end args = {}; if ~isempty(result{1}) args = [args {'fcutoff'} {str2num(result{1})}]; end args = [args {'ftype'} ftypes(result{2})]; args = [args {'wtype'} wtypes(result{3})]; if ~isempty(result{4}) args = [args {'warg'} {str2double(result{4})}]; end if ~isempty(result{5}) args = [args {'forder'} {str2double(result{5})}]; end args = [args {'minphase'} result{6}]; else args = varargin; end % Convert args to structure args = struct(args{:}); c = parseargs(args, EEG.srate); b = firws(c{:}); % Check arguments if ~isfield(args, 'minphase') || isempty(args.minphase) args.minphase = 0; end % Filter disp('pop_firws() - filtering the data'); if args.minphase b = minphaserceps(b); EEG = firfiltsplit(EEG, b, 1); else EEG = firfilt(EEG, b); end % History string com = sprintf('%s = pop_firws(%s', inputname(1), inputname(1)); for c = fieldnames(args)' if ischar(args.(c{:})) com = [com sprintf(', ''%s'', ''%s''', c{:}, args.(c{:}))]; else com = [com sprintf(', ''%s'', %s', c{:}, mat2str(args.(c{:})))]; end end com = [com ');']; % Convert structure args to cell array firws parameters function c = parseargs(args, srate) % Filter order and cutoff frequencies if ~isfield(args, 'fcutoff') || ~isfield(args, 'forder') || isempty(args.fcutoff) || isempty(args.forder) error('Not enough input arguments.'); end c = [{args.forder} {sort(args.fcutoff / (srate / 2))}]; % Sorting and normalization % Filter type if isfield(args, 'ftype') && ~isempty(args.ftype) if (strcmpi(args.ftype, 'bandpass') || strcmpi(args.ftype, 'bandstop')) && length(args.fcutoff) ~= 2 error('Not enough input arguments.'); elseif (strcmpi(args.ftype, 'highpass') || strcmpi(args.ftype, 'lowpass')) && length(args.fcutoff) ~= 1 error('Too many input arguments.'); end switch args.ftype case 'bandstop' c = [c {'stop'}]; case 'highpass' c = [c {'high'}]; end end % Window type if isfield(args, 'wtype') && ~isempty(args.wtype) if strcmpi(args.wtype, 'kaiser') if isfield(args, 'warg') && ~isempty(args.warg) c = [c {windows(args.wtype, args.forder + 1, args.warg)'}]; else error('Not enough input arguments.'); end else c = [c {windows(args.wtype, args.forder + 1)'}]; end end % Callback estimate Kaiser beta function comwarg(varargin) [warg, dev] = pop_kaiserbeta; set(findobj(gcbf, 'Tag', 'wargedit'), 'String', warg); set(findobj(gcbf, 'Tag', 'devedit'), 'String', dev); % Callback estimate filter order function comforder(obj, evt, wtypes, srate) wtype = wtypes{get(findobj(gcbf, 'Tag', 'wtypepop'), 'Value')}; dev = get(findobj(gcbf, 'Tag', 'devedit'), 'String'); [forder, dev] = pop_firwsord(wtype, srate, [], dev); set(findobj(gcbf, 'Tag', 'forderedit'), 'String', forder); set(findobj(gcbf, 'Tag', 'devedit'), 'String', dev); % Callback plot filter responses function comfresp(obj, evt, wtypes, ftypes, srate) args.fcutoff = str2num(get(findobj(gcbf, 'Tag', 'fcutoffedit'), 'String')); args.ftype = ftypes{get(findobj(gcbf, 'Tag', 'ftypepop'), 'Value')}; args.wtype = wtypes{get(findobj(gcbf, 'Tag', 'wtypepop'), 'Value')}; args.warg = str2num(get(findobj(gcbf, 'Tag', 'wargedit'), 'String')); args.forder = str2double(get(findobj(gcbf, 'Tag', 'forderedit'), 'String')); args.minphase = get(findobj(gcbf, 'Tag', 'minphase'), 'Value'); causal = args.minphase; c = parseargs(args, srate); b = firws(c{:}); if args.minphase b = minphaserceps(b); end H = findobj('Tag', 'filter responses', 'type', 'figure'); if ~isempty(H) figure(H); else H = figure; set(H, 'color', [.93 .96 1], 'Tag', 'filter responses'); end plotfresp(b, 1, [], srate, causal);
github
lcnbeapp/beapp-master
plotfresp.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/firfilt1.6.2/plotfresp.m
3,898
utf_8
71a74a912328b37353e1523b662840fa
% plotfresp() - Plot FIR filter's impulse, step, frequency, magnitude, % and phase response % % Usage: % >> plotfresp(b, a, n, fs); % % Inputs: % b - vector filter coefficients % % Optional inputs: % a - currently unused, reserved for future compatibility with IIR % filters {default 1} % n - scalar number of points % fs - scalar sampling frequency % % Author: Andreas Widmann, University of Leipzig, 2005 % % See also: % pop_firws, pop_firpm, pop_firma %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2005 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function plotfresp(b, a, nfft, fs, causal) if nargin < 5 || isempty(causal) causal = 0; end if nargin < 4 || isempty(fs) fs = 1; end if nargin < 3 || isempty(nfft) nfft = 2^fix(log2(length(b))); if nfft < 512 nfft = 512; end end if nargin < 1 error('Not enough input arguments.'); end n = length(b); f = (0:1 / nfft:1) * fs / 2; % Impulse resonse if causal, xval = 0:n-1; else xval = -(n - 1) / 2:(n - 1) / 2; end ax(1) = subplot(2, 3, 1); stem(xval, b, 'fill') title('Impulse response'); ylabel('Amplitude'); % Step response ax(4) = subplot(2, 3, 4); stem(xval, cumsum(b), 'fill'); title('Step response'); foo = ylim; if foo(2) < -foo(1) + 1; foo(2) = -foo(1) + 1; ylim(foo); end xMin = []; xMax = []; children = get(ax(4), 'Children'); for child =1:length(children) xData = get(children(child), 'XData'); xMin = min([xMin min(xData)]); xMax = max([xMax max(xData)]); end set(ax([1 4]), 'xlim', [xMin xMax]); ylabel('Amplitude'); % Frequency response ax(2) = subplot(2, 3, 2); m = fix((length(b) - 1) / 2); % Filter order z = fft(b, nfft * 2); z = z(1:fix(length(z) / 2) + 1); % foo = real(abs(z) .* exp(-i * (angle(z) + [0:1 / nfft:1] * m * pi))); % needs further testing plot(f, abs(z)); title('Frequency response'); ylabel('Amplitude'); % Magnitude response ax(5) = subplot(2, 3, 5); db = abs(z); db(db < eps^(2 / 3)) = eps^(2 / 3); % Log of zero warning plot(f, 20 * log10(db)); title('Magnitude response'); foo = ylim; if foo(1) < 20 * log10(eps^(2 / 3)) foo(1) = 20 * log10(eps^(2 / 3)); end ylabel('Magnitude (dB)'); ylim(foo); % Phase response ax(3) = subplot(2, 3, 3); z(abs(z) < eps^(2 / 3)) = NaN; % Phase is undefined for magnitude zero phi = angle(z); if causal phi = unwrap(phi); else delay = -mod((0:1 / nfft:1) * m * pi + pi, 2 * pi) + pi; % Zero-phase phi = phi - delay; phi = phi + 2 * pi * (phi <= -pi + eps ^ (1/3)); % Unwrap end plot(f, phi); title('Phase response'); ylabel('Phase (rad)'); % ylim([-pi / 2 1.5 * pi]); set(ax(1:5), 'ygrid', 'on', 'xgrid', 'on', 'box', 'on'); titles = get(ax(1:5), 'title'); set([titles{:}], 'fontweight', 'bold'); xlabels = get(ax(1:5), 'xlabel'); if fs == 1 set([xlabels{[2 3 5]}], 'String', 'Normalized frequency (2 pi rad / sample)'); else set([xlabels{[2 3 5]}], 'String', 'Frequency (Hz)'); end set([xlabels{[1 4]}], 'String', 'Sample'); set(ax([2 3 5]), 'xlim', [0 fs / 2]); set(ax(1:5), 'colororder', circshift(get(ax(1), 'colororder'), -1)); set(ax(1:5), 'nextplot', 'add');
github
lcnbeapp/beapp-master
pop_firwsord.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/firfilt1.6.2/pop_firwsord.m
5,354
utf_8
5150d668b377feb0d9e95b49486978ca
% pop_firwsord() - Estimate windowed sinc filter order depending on % window type and requested transition band width % % Usage: % >> [m, dev] = pop_firwsord; % pop-up window mode % >> m = pop_firwsord(wtype, fs, df); % >> m = pop_firwsord('kaiser', fs, df, dev); % % Inputs: % wtype - char array window type. 'rectangular', 'bartlett', 'hann', % 'hamming', {'blackman'}, or 'kaiser' % fs - scalar sampling frequency {default 2} % df - scalar requested transition band width % dev - scalar maximum passband deviation/ripple (Kaiser window % only) % % Output: % m - scalar estimated filter order % dev - scalar maximum passband deviation/ripple % % References: % [1] Smith, S. W. (1999). The scientist and engineer's guide to % digital signal processing (2nd ed.). San Diego, CA: California % Technical Publishing. % [2] Proakis, J. G., & Manolakis, D. G. (1996). Digital Signal % Processing: Principles, Algorithms, and Applications (3rd ed.). % Englewood Cliffs, NJ: Prentice-Hall % [3] Ifeachor E. C., & Jervis B. W. (1993). Digital Signal % Processing: A Practical Approach. Wokingham, UK: Addison-Wesley % % Author: Andreas Widmann, University of Leipzig, 2005 % % See also: % pop_firws, firws, pop_kaiserbeta, windows %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2005 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [m, dev] = pop_firwsord(wtype, fs, df, dev) m = []; wtypes = {'rectangular' 'bartlett' 'hann' 'hamming' 'blackman' 'kaiser'}; % Window type if nargin < 1 || isempty(wtype) wtype = 5; elseif ~ischar(wtype) || isempty(strmatch(wtype, wtypes)) error('Unknown window type'); else wtype = strmatch(wtype, wtypes); end % Sampling frequency if nargin < 2 || isempty(fs) fs = 2; end % Transition band width if nargin < 3 df = []; end % Maximum passband deviation/ripple if nargin < 4 || isempty(dev) devs = {0.089 0.056 0.0063 0.0022 0.0002 []}; dev = devs{wtype}; end % GUI if nargin < 3 || isempty(df) || (wtype == 6 && isempty(dev)) drawnow; uigeom = {[1 1] [1 1] [1 1] [1 1]}; uilist = {{'style' 'text' 'string' 'Sampling frequency:'} ... {'style' 'edit' 'string' fs} ... {'style' 'text' 'string' 'Window type:'} ... {'style' 'popupmenu' 'string' wtypes 'tag' 'wtypepop' 'value' wtype 'callback' {@comwtype, dev}} ... {'style' 'text' 'string' 'Transition bandwidth (Hz):'} ... {'style' 'edit' 'string' df} ... {'style' 'text' 'string' 'Max passband deviation/ripple:' 'tag' 'devtext'} ... {'style' 'edit' 'tag' 'devedit' 'createfcn' {@comwtype, dev}}}; result = inputgui(uigeom, uilist, 'pophelp(''pop_firwsord'')', 'Estimate filter order -- pop_firwsord()'); if length(result) == 0, return, end if ~isempty(result{1}) fs = str2num(result{1}); else fs = 2; end wtype = result{2}; if ~isempty(result{3}) df = str2num(result{3}); else error('Not enough input arguments.'); end if ~isempty(result{4}) dev = str2num(result{4}); elseif wtype == 6 error('Not enough input arguments.'); end end if length(fs) > 1 || ~isnumeric(fs) || ~isreal(fs) || fs <= 0 error('Sampling frequency must be a positive real scalar.'); end if length(df) > 1 || ~isnumeric(df) || ~isreal(df) || fs <= 0 error('Transition bandwidth must be a positive real scalar.'); end df = df / fs; % Normalize transition band width if wtype == 6 if length(dev) > 1 || ~isnumeric(dev) || ~isreal(dev) || dev <= 0 error('Passband deviation/ripple must be a positive real scalar.'); end devdb = -20 * log10(dev); m = 1 + (devdb - 8) / (2.285 * 2 * pi * df); else dfs = [0.9 2.9 3.1 3.3 5.5]; m = dfs(wtype) / df; end m = ceil(m / 2) * 2; % Make filter order even (type 1) function comwtype(obj, evt, dev) enable = {'off' 'off' 'off' 'off' 'off' 'on'}; devs = {0.089 0.056 0.0063 0.0022 0.0002 dev}; wtype = get(findobj(gcbf, 'tag', 'wtypepop'), 'value'); set(findobj(gcbf, 'tag', 'devtext'), 'enable', enable{wtype}); set(findobj(gcbf, 'tag', 'devedit'), 'enable', enable{wtype}, 'string', devs{wtype});
github
lcnbeapp/beapp-master
pop_kaiserbeta.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/firfilt1.6.2/pop_kaiserbeta.m
2,315
utf_8
9a8a6636653865493068a0e901deeda6
% pop_kaiserbeta() - Estimate Kaiser window beta % % Usage: % >> [beta, dev] = pop_kaiserbeta; % pop-up window mode % >> beta = pop_kaiserbeta(dev); % % Inputs: % dev - scalar maximum passband deviation/ripple % % Output: % beta - scalar Kaiser window beta % dev - scalar maximum passband deviation/ripple % % References: % [1] Proakis, J. G., & Manolakis, D. G. (1996). Digital Signal % Processing: Principles, Algorithms, and Applications (3rd ed.). % Englewood Cliffs, NJ: Prentice-Hall % % Author: Andreas Widmann, University of Leipzig, 2005 % % See also: % pop_firws, firws, pop_firwsord, windows %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2005 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [beta, dev] = pop_kaiserbeta(dev) beta = []; if nargin < 1 || isempty(dev) drawnow; uigeom = {[1 1]}; uilist = {{'style' 'text' 'string' 'Max passband deviation/ripple:'} ... {'style' 'edit' 'string' ''}}; result = inputgui(uigeom, uilist, 'pophelp(''pop_kaiserbeta'')', 'Estimate Kaiser window beta -- pop_kaiserbeta()'); if length(result) == 0, return, end if ~isempty(result{1}) dev = str2num(result{1}); else error('Not enough input arguments.'); end end devdb = -20 * log10(dev); if devdb > 50 beta = 0.1102 * (devdb - 8.7); elseif devdb >= 21 beta = 0.5842 * (devdb - 21)^0.4 + 0.07886 * (devdb - 21); else beta = 0; end end
github
lcnbeapp/beapp-master
findboundaries.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/firfilt1.6.2/findboundaries.m
1,867
utf_8
b4b28dadb5f28c802c41266f791d942c
% findboundaries() - Find boundaries (data discontinuities) in event % structure of continuous EEG dataset % % Usage: % >> boundaries = findboundaries(EEG.event); % % Inputs: % EEG.event - EEGLAB EEG event structure % % Outputs: % boundaries - scalar or vector of boundary event latencies % % Author: Andreas Widmann, University of Leipzig, 2005 %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2005 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function boundaries = findboundaries(event) if isfield(event, 'type') & isfield(event, 'latency') & cellfun('isclass', {event.type}, 'char') % Boundary event indices boundaries = strmatch('boundary', {event.type}); % Boundary event latencies boundaries = [event(boundaries).latency]; % Shift boundary events to epoch onset boundaries = fix(boundaries + 0.5); % Remove duplicate boundary events boundaries = unique(boundaries); % Epoch onset at first sample? if isempty(boundaries) || boundaries(1) ~= 1 boundaries = [1 boundaries]; end else boundaries = 1; end
github
lcnbeapp/beapp-master
publishPrepReport.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/PrepPipeline/publishPrepReport.m
4,425
utf_8
9f98d6c9dcde40a27e2900462a4d1e07
function [] = publishPrepReport(EEG, summaryFilePath, sessionFilePath, ... consoleFID, publishOn) % Create a published report from the PREP pipeline. % % Note: In addition to creating a report for the EEG, it appends a % summary of the file to an existing summary file. This enables the % function to be called successfully on a collection and creates a summary % of the collection. % % Parameters: % EEG EEGLAB structure with the EEG.etc.noiseDetection % structure created by the PREP pipeline % summaryFilePath File name including path of the summary file % sessionFilePath File name including path of the individual report % consoleID Open file descriptor for echoing output (usually 1 % indication the Command Window). % publishOn If true (default), report is published and % figures are closed. If false, output and figures % are displayed in the normal way. The figures % are not closed. This option is useful when % you want to manipulate the figures in some way. % % Output: % If the publish option is on, this function will create a report % for the EEG and will append a summary to a specified summary file. % If the publish option is off, the function will just run the % prepReport script. % % Author: Kay Robbins, UTSA, March 2015. % % %% Handle the parameters if (nargin < 5) error('publishPrepReport:NotEnoughParameters', ... ['Usage: publishPrepReport(EEG, summaryFilePath, ' ... 'sessionFilePath, consoleId, publishOn)']); elseif nargin < 5 || isempty(publishOn) publishOn = true; end %% Setup up files and assign variables needed for publish in base workspace % Session folder is relative to the summary report location [summaryFolder, summaryName, summaryExt] = fileparts(summaryFilePath); [sessionFolder, sessionName, sessionExt] = fileparts(sessionFilePath); summaryReportLocation = [summaryFolder filesep summaryName summaryExt]; sessionReportLocation = [sessionFolder filesep sessionName sessionExt]; tempReportLocation = [sessionFolder filesep 'prepReport.pdf']; relativeReportLocation = getRelativePath(summaryFolder, sessionFolder, ... sessionName, sessionExt); fprintf('Summary: %s session: %s\n', summaryFolder, sessionFolder); fprintf('Relative report location %s \n', relativeReportLocation); summaryFile = fopen(summaryReportLocation, 'a+', 'n', 'UTF-8'); if summaryFile == -1; error('publishPrepReport:BadSummaryFile', ... 'Failed to open summary file %s', summaryReportLocation); end assignin('base', 'EEGReporting', EEG); assignin('base', 'summaryFile', summaryFile); assignin('base', 'consoleFID', consoleFID); assignin('base', 'relativeReportLocation', relativeReportLocation); script_name = 'prepReport.m'; if publishOn publish_options.outputDir = sessionFolder; publish_options.maxWidth = 800; publish_options.format = 'pdf'; publish_options.showCode = false; publish(script_name, publish_options); else prepReport; end writeSummaryItem(summaryFile, '', 'last'); fclose('all'); if publishOn fprintf('temp report location %s\n', tempReportLocation); fprintf('session report location %s\n', sessionReportLocation); movefile(tempReportLocation, sessionReportLocation); close all end end function relativePath = getRelativePath(summaryFolder, sessionFolder, ... sessionName, sessionExt) relativePath = relativize(getCanonicalPath(summaryFolder), ... getCanonicalPath(sessionFolder)); relativePath = getCanonicalPath(relativePath); while(true) relativePathNew = strrep(relativePath, '\\', '\'); if length(relativePathNew) == length(relativePath) break; end relativePath = relativePathNew; end relativePath = strrep(relativePath, '\', '/'); relativePath = [relativePath sessionName sessionExt]; end function canonicalPath = getCanonicalPath(canonicalPath) if canonicalPath(end) ~= filesep canonicalPath = [canonicalPath, filesep]; end end
github
lcnbeapp/beapp-master
pop_prepPipeline.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/PrepPipeline/pop_prepPipeline.m
3,412
utf_8
e1766caf90a400f64abf54ba1dcad5ce
% pop_prepPipeline() - runs the early stage pipeline to reference and to % detect bad channels % % Usage: % >> [OUTEEG, com] = pop_prepPipeline(INEEG, params); % % Inputs: % INEEG - input EEG dataset % params - structure with parameters to override defaults % % Outputs: % OUTEEG - output dataset % % See also: % prepPipeline, prepPipelineReport, EEGLAB % Copyright (C) 2015 Kay Robbins with contributions from Nima % Bigdely-Shamlo, Christian Kothe, Tim Mullen, and Cassidy Matousek % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % 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_prepPipeline(EEG, params) com = ''; % Return something if user presses the cancel button okay = true; if nargin < 1 %% display help if not enough arguments help pop_prepPipeline; return; elseif nargin < 2 params = struct(); end %% Add path to prepPipeline subdirectories if not in the list tmp = which('getPipelineDefaults'); if isempty(tmp) myPath = fileparts(which('prepPipeline')); addpath(genpath(myPath)); end; %% pop up window if nargin < 2 userData = getUserData(); [params, okay] = MasterGUI([],[],userData, EEG); end userData = getUserData(); com = sprintf('pop_prepPipeline(%s, %s);', inputname(1), ... struct2str(params)); reportMode = userData.report.reportMode.value; consoleFID = userData.report.consoleFID.value; publishOn = userData.report.publishOn.value; summaryFilePath = userData.report.summaryFilePath.value; sessionFilePath = userData.report.sessionFilePath.value; if okay if strcmpi(reportMode, 'normal') || strcmpi(reportMode, 'skipReport') EEG = prepPipeline(EEG, params); end if (strcmpi(reportMode, 'normal') || ... strcmpi(reportMode, 'reportOnly')) && publishOn publishPrepReport(EEG, summaryFilePath, sessionFilePath, ... consoleFID, publishOn); end if strcmpi(reportMode, 'normal') || strcmpi(reportMode, 'skipReport') EEG = prepPostProcess(EEG, params); end end function userData = getUserData() %% Gets the userData defaults and merges it with the parameters userData = struct('boundary', [], 'detrend', [], ... 'lineNoise', [], 'reference', [], ... 'report', [], 'postProcess', []); stepNames = fieldnames(userData); for k = 1:length(stepNames) defaults = getPipelineDefaults(EEG, stepNames{k}); [theseValues, errors] = checkStructureDefaults(params, ... defaults); if ~isempty(errors) error('pop_prepPipeline:BadParameters', ['|' ... sprintf('%s|', errors{:})]); end userData.(stepNames{k}) = theseValues; end end % getUserData end % pop_prepPipeline
github
lcnbeapp/beapp-master
eegplugin_prepPipeline.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/PrepPipeline/eegplugin_prepPipeline.m
1,689
utf_8
06dc5f28bddeffcf9c683c28e7f4c4ff
% eegplugin_prepPipeline() - a wrapper to the prepPipeline, which does early stage % % Usage: % >> eegplugin_prepPipeline(fig, try_strings, catch_strings); % % see also: prepPipeline % Author: Kay Robbins, with contributions from Nima Bigdely-Shamlo, Tim Mullen, Christian Kothe, and Cassidy Matousek. % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %function eegplugin_clean_rawdata(fig,try_strings,catch_strings) % create menu % toolsmenu = findobj(fig, 'tag', 'tools'); % uimenu( toolsmenu, 'label', 'Clean continuous data using ASR', 'separator','on',... % 'callback', 'EEG = pop_clean_rawdata(EEG); [ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG); eeglab redraw'); % eegplugin_prepPipeline() - the PREP pipeline plugin function eegplugin_prepPipeline(fig, trystrs, catchstrs) % create menu comprep = [trystrs.no_check '[EEG LASTCOM] = pop_prepPipeline(EEG);' catchstrs.new_and_hist]; menu = findobj(fig, 'tag', 'tools'); uimenu( menu, 'Label', 'Run PREP pipeline', 'callback', comprep, ... 'separator', 'on');
github
lcnbeapp/beapp-master
changeType.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/PrepPipeline/interface/changeType.m
1,591
utf_8
bad5e083eb85339d29a5c24752076bd8
%% *****************************changeType********************************* %Purpose: % This function changes the data type of the parameters returned by % the inputgui function. It allows the parameters to be used as the % correct default type. %Parameters: % I params Structure of parameters to change data type. % I signal Structure of data in the EEGlab format. % I defaults Structure of the default parameters with % attributes. % O outParams Structure of parameters with correct type. %Notes: % %************************************************************************** function [outParams, errors, errorNames] = changeType(params, defaults) %tests each string to make sure it is correct numeric type %splits the strings at whitespace and converts each cell to an int fNames = fieldnames(defaults); errors = cell(0); errorNames = cell(0); outParams = params; for k = 1:length(fNames) if strcmpi(defaults.(fNames{k}).classes, 'numeric') == 1 outParams.(fNames{k}) = str2num(params.(fNames{k})); if isempty(outParams.(fNames{k})) errors{end + 1} =[fNames{k} ... ': contains at least one character of the incorrect type']; %#ok<AGROW> errorNames{end + 1} = fNames{k}; %#ok<AGROW> end elseif strcmpi(defaults.(fNames{k}).classes, 'logical') == 1 outParams.(fNames{k}) = logical(params.(fNames{k})); end end end
github
lcnbeapp/beapp-master
displayErrors.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/PrepPipeline/interface/displayErrors.m
1,092
utf_8
4a6169558283702bcb7068f0320f3497
%% *****************************displayErrors****************************** %Purpose: % This returns the errors (if any) that are found when a user enters % data that does not correspond with the type found by the default % function. It displays the errors in a pop-up GUI. %Parameters: % I errors Cell array of strings; errors found by the % checkDefaults function % O loop Integer that either continues the while loop found % above or exits the loop %Notes: % %Return Value: % 0 No errors % 1 Displays errors and continues loop %************************************************************************** function displayErrors(errors) geometry={}; geomvert=[]; uilist={}; for k=1:length(errors) geometry={geometry{:},1}; uilist={uilist{:},{'style', 'text', 'string', errors(k)}}; end result=inputgui('geometry', geometry, 'geomvert', geomvert, 'uilist', uilist, 'title', 'Reference Errors', 'helpcom', 'pophelp(''pop_eegfiltnew'')'); end
github
lcnbeapp/beapp-master
loadDefaults.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/PrepPipeline/interface/loadDefaults.m
1,266
utf_8
9284af1e1bf7539c9327797a6483466e
%% *****************************loadDefaults******************************* %Purpose: % Loads the default values from the signal to put into the GUI. %Parameters: % I signal Structure from the EEG data set signal. % I tags Cell array listing the names of the parameters. % O defaultParams Return structure of defaults to place into GUI. %Notes: % % ************************************************************************* function [defaultParams,defaultValues]=loadDefaults(signal,type) defaultValues=struct; defaultParams=getPipelineDefaults(signal,type); fNames=fieldnames(defaultParams); for k=1:length(fNames) if(strcmp(defaultParams.(fNames{k}).classes,'struct')==0) changeStr=num2str(defaultParams.(fNames{k}).default); defaultParams.(fNames{k}).default=changeStr; sFind=strfind(defaultParams.(fNames{k}).default,'['); defaultParams.(fNames{k}).default(sFind)=[]; sFind=strfind(defaultParams.(fNames{k}).default,']'); defaultParams.(fNames{k}).default(sFind)=[]; end end for k=1:length(fNames) setVal=defaultParams.(fNames{k}).default; defaultValues.(fNames{k})=setVal; end end
github
lcnbeapp/beapp-master
findNoisyChannels.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/PrepPipeline/utilities/findNoisyChannels.m
18,209
utf_8
959269765651c0faf04e2fe5e5970cc0
function noisyOut = findNoisyChannels(signal, noisyIn) % Identify bad channels in EEG using a two-stage approach % % reference = findNoisyChannels(signal) % reference = findNoisyChannels(signal, reference) % % First remove bad channels by amplitude, noise level, and correlation % Apply ransac after these channels have been removed. % % Input parameters: % signal - structure with srate, chanlocs, chaninfo, and data fields % noisyIn - structure with input parameters % % Notes: the signal is assumed to be high-passed. Removing line noise % is a good idea too. % % noisyIn: (fields are filled in on input if not present and propagated to output) % name - name of the input file % srate - sample rate in HZ % samples - number of samples in the data % evaluationChannels - a vector of channels to use % channelLocations - a structure of EEG channel locations % chaninfo - standard EEGLAB chaninfo (nose direction is relevant) % chanlocs - standard EEGLAB chanlocs structure % robustDeviationThreshold - z score cutoff for robust channel deviation % highFrequencyNoiseThreshold - z score cutoff for SNR (signal above 50 Hz) % correlationWindowSeconds - correlation window size in seconds (default = 1 sec) % correlationThreshold - correlation below which window is bad (default = 0.4) % badTimeThreshold - cutoff fraction of bad corr windows (default = 0.01) % ransacSampleSize - samples for computing ransac (default = 50) % ransacChannelFraction - fraction of channels for robust reconstruction (default = 0.25) % ransacCorrelationThreshold - cutoff correlation for abnormal wrt neighbors(default = 0.75) % ransacUnbrokenTime - cutoff fraction of time channel can have poor ransac predictability (default = 0.4) % ransacWindowSeconds - correlation window for ransac (default = 5 sec) % % Output parameters (c channels, w windows): % ransacPerformed - true if there were enough good channels to do ransac % noisyChannels - list of identified bad channel numbers % badChannelsFromCorrelation - list of bad channels identified by correlation % badChannelsFromDeviation - list of bad channels identified by amplitude % badChannelsFromHFNoise - list of bad channels identified by SNR % badChannelsFromRansac - list of channels identified by ransac % fractionBadCorrelationWindows - c x 1 vector with fraction of bad correlation windows % robustChannelDeviation - c x 1 vector with robust measure of average channel deviation % zscoreHFNoise - c x 1 vector with measure of channel noise level % maximumCorrelations - w x c array with max window correlation % ransacCorrelations = c x wr array with ransac correlations % % This function uses 4 methods for detecting bad channels after removing % from consideration channels that have NaN data or channels that are % identically constant. % % Method 1: too low or high amplitude. If the z score of robust % channel deviation falls below robustDeviationThreshold, the channel is % considered to be bad. % Method 2: too low an SNR. If the z score of estimate of signal above % 50 Hz to that below 50 Hz above highFrequencyNoiseThreshold, the channel % is considered to be bad. % % Method 3: low correlation with other channels. Here correlationWindowSize is the window % size over which the correlation is computed. If the maximum % correlation of the channel to the other channels falls below % correlationThreshold, the channel is considered bad in that window. % If the fraction of bad correlation windows for a channel % exceeds badTimeThreshold, the channel is marked as bad. % % After the channels from methods 2 and 3 are removed, method 4 is % computed on the remaining signals % % Method 4: each channel is predicted using ransac interpolation based % on a ransac fraction of the channels. If the correlation of % the prediction to the actual behavior is too low for too % long, the channel is marked as bad. % % Assumptions: % - The signal is a structure of continuous data with data, srate, chanlocs, % and chaninfo fields. % - The signal.data has been high pass filtered. % - No segments of the EEG data have been removed % Methods 1 and 4 are adapted from code by Christian Kothe and Methods 2 % and 3 are adapted from code by Nima Bigdely-Shamlo % %% Check the incoming parameters if nargin < 1 error('findNoisyChannels:NotEnoughArguments', 'requires at least 1 argument'); elseif isstruct(signal) && ~isfield(signal, 'data') error('findNoisyChannels:NoDataField', 'requires a structure data field'); elseif size(signal.data, 3) ~= 1 error('findNoisyChannels:DataNotContinuous', 'data must be a 2D array'); elseif nargin < 2 || ~exist('noisyIn', 'var') || isempty(noisyIn) noisyIn = struct(); end %% Set the defaults and initialize as needed noisyOut = getNoisyStructure(); defaults = getPipelineDefaults(signal, 'reference'); [noisyOut, errors] = checkDefaults(noisyIn, noisyOut, defaults); if ~isempty(errors) error('findNoisyChannels:BadParameters', ['|' sprintf('%s|', errors{:})]); end %% Fix the channel locations channelLocations = noisyOut.channelLocations; evaluationChannels = sort(noisyOut.evaluationChannels); % Make sure channels are sorted evaluationChannels = evaluationChannels(:)'; % Make sure row vector noisyOut.evaluationChannels = evaluationChannels; originalChannels = 1:size(signal.data, 1); %% Extract the data required data = signal.data; originalNumberChannels = size(data, 1); % Save the original channels data = double(data(evaluationChannels, :))'; % Remove the unneeded channels signalSize = size(data, 1); correlationFrames = noisyOut.correlationWindowSeconds * signal.srate; correlationWindow = 0:(correlationFrames - 1); correlationOffsets = 1:correlationFrames:(signalSize-correlationFrames); WCorrelation = length(correlationOffsets); ransacFrames = noisyOut.ransacWindowSeconds*noisyOut.srate; ransacWindow = 0:(ransacFrames - 1); ransacOffsets = 1:ransacFrames:(signalSize-ransacFrames); WRansac = length(ransacOffsets); noisyOut.zscoreHFNoise = zeros(originalNumberChannels, 1); noisyOut.noiseLevels = zeros(originalNumberChannels, WCorrelation); noisyOut.maximumCorrelations = ones(originalNumberChannels, WCorrelation); noisyOut.dropOuts = zeros(originalNumberChannels, WCorrelation); noisyOut.correlationOffsets = correlationOffsets; noisyOut.channelDeviations = zeros(originalNumberChannels, WCorrelation); noisyOut.robustChannelDeviation = zeros(originalNumberChannels, 1); noisyOut.ransacCorrelations = ones(originalNumberChannels, WRansac); noisyOut.ransacOffsets = ransacOffsets; %% Detect constant or NaN channels and remove from consideration nanChannelMask = sum(isnan(data), 1) > 0; noSignalChannelMask = mad(data, 1, 1) < 10e-10 | std(data, 1, 1) < 10e-10; noisyOut.noisyChannels.badChannelsFromNaNs = evaluationChannels(nanChannelMask); noisyOut.noisyChannels.badChannelsFromNoData = evaluationChannels(noSignalChannelMask); evaluationChannels = setdiff(evaluationChannels, ... union(noisyOut.noisyChannels.badChannelsFromNaNs, ... noisyOut.noisyChannels.badChannelsFromNoData)); data = signal.data; data = double(data(evaluationChannels, :))'; [signalSize, numberChannels] = size(data); %% Method 1: Unusually high or low amplitude (using robust std) channelDeviation = 0.7413 *iqr(data); % Robust estimate of SD channelDeviationSD = 0.7413 * iqr(channelDeviation); channelDeviationMedian = nanmedian(channelDeviation); noisyOut.robustChannelDeviation(evaluationChannels) = ... (channelDeviation - channelDeviationMedian) / channelDeviationSD; % Find channels with unusually high deviation badChannelsFromDeviation = ... abs(noisyOut.robustChannelDeviation) > ... noisyOut.robustDeviationThreshold | ... isnan(noisyOut.robustChannelDeviation); badChannelsFromDeviation = originalChannels(badChannelsFromDeviation); noisyOut.noisyChannels.badChannelsFromDeviation = badChannelsFromDeviation(:)'; noisyOut.channelDeviationMedian = channelDeviationMedian; noisyOut.channelDeviationSD = channelDeviationSD; %% Method 2: Compute the SNR (based on Christian Kothe's clean_channels) % Note: RANSAC uses the filtered values X of the data if noisyOut.srate > 100 % Remove signal content above 50Hz and below 1 Hz B = design_fir(100,[2*[0 45 50]/noisyOut.srate 1],[1 1 0 0]); X = zeros(signalSize, numberChannels); parfor k = 1:numberChannels % Could be changed to parfor X(:,k) = filtfilt_fast(B, 1, data(:, k)); end % Determine z-scored level of EM noise-to-signal ratio for each channel noisiness = mad(data- X, 1)./mad(X, 1); noisinessMedian = nanmedian(noisiness); noisinessSD = mad(noisiness, 1)*1.4826; zscoreHFNoiseTemp = (noisiness - noisinessMedian) ./ noisinessSD; noiseMask = (zscoreHFNoiseTemp > noisyOut.highFrequencyNoiseThreshold) | ... isnan(zscoreHFNoiseTemp); % Remap channels to original numbering badChannelsFromHFNoise = evaluationChannels(noiseMask); noisyOut.noisyChannels.badChannelsFromHFNoise = badChannelsFromHFNoise(:)'; else X = data; noisinessMedian = 0; noisinessSD = 1; zscoreHFNoiseTemp = zeros(numberChannels, 1); noisyOut.noisyChannels.badChannelsFromHFNoise = []; end % Remap the channels to original numbering for the zscoreHFNoise noisyOut.zscoreHFNoise(evaluationChannels) = zscoreHFNoiseTemp; noisyOut.noisinessMedian = noisinessMedian; noisyOut.noisinessSD = noisinessSD; %% Method 3: Global correlation criteria (from Nima Bigdely-Shamlo) channelCorrelations = ones(WCorrelation, numberChannels); noiseLevels = zeros(WCorrelation, numberChannels); channelDeviations = zeros(WCorrelation, numberChannels); n = length(correlationWindow); xWin = reshape(X(1:n*WCorrelation, :)', numberChannels, n, WCorrelation); dataWin = reshape(data(1:n*WCorrelation, :)', numberChannels, n, WCorrelation); parfor k = 1:WCorrelation eegPortion = squeeze(xWin(:, :, k))'; dataPortion = squeeze(dataWin(:, :, k))'; windowCorrelation = corrcoef(eegPortion); abs_corr = abs(windowCorrelation - diag(diag(windowCorrelation))); channelCorrelations(k, :) = quantile(abs_corr, 0.98); noiseLevels(k, :) = mad(dataPortion - eegPortion, 1)./mad(eegPortion, 1); channelDeviations(k, :) = 0.7413 *iqr(dataPortion); end; dropOuts = isnan(channelCorrelations) | isnan(noiseLevels); channelCorrelations(dropOuts) = 0.0; noiseLevels(dropOuts) = 0.0; clear xWin; clear dataWin; noisyOut.maximumCorrelations(evaluationChannels, :) = channelCorrelations'; noisyOut.noiseLevels(evaluationChannels, :) = noiseLevels'; noisyOut.channelDeviations(evaluationChannels, :) = channelDeviations'; noisyOut.dropOuts(evaluationChannels, :) = dropOuts'; thresholdedCorrelations = ... noisyOut.maximumCorrelations < noisyOut.correlationThreshold; fractionBadCorrelationWindows = mean(thresholdedCorrelations, 2); fractionBadDropOutWindows = mean(noisyOut.dropOuts, 2); % Remap channels to their original numbers badChannelsFromCorrelation = find(fractionBadCorrelationWindows > noisyOut.badTimeThreshold); noisyOut.noisyChannels.badChannelsFromCorrelation = badChannelsFromCorrelation(:)'; badChannelsFromDropOuts = find(fractionBadDropOutWindows > noisyOut.badTimeThreshold); noisyOut.noisyChannels.badChannelsFromDropOuts = badChannelsFromDropOuts(:)'; noisyOut.medianMaxCorrelation = median(noisyOut.maximumCorrelations, 2); %% Bad so far by amplitude and correlation (take these out before doing ransac) noisyChannels = union(noisyOut.noisyChannels.badChannelsFromDeviation, ... union(noisyOut.noisyChannels.badChannelsFromCorrelation, ... noisyOut.noisyChannels.badChannelsFromDropOuts)); %% Method 4: Ransac corelation (may not be performed) % Setup for ransac (if a 2-stage algorithm, remove other bad channels first) if noisyOut.ransacOff noisyOut.ransacBadWindowFraction = 0; noisyOut.ransacPerformed = false; elseif isempty(channelLocations) warning('findNoisyChannels:noChannelLocation', ... 'ransac could not be computed because there were no channel locations'); noisyOut.ransacBadWindowFraction = 0; noisyOut.ransacPerformed = false; else % Set up parameters and make sure enough good channels to proceed [ransacChannels, idiff] = setdiff(evaluationChannels, noisyChannels); X = X(:, idiff); % Calculate the parameters for ransac ransacSubset = round(noisyOut.ransacChannelFraction*size(data, 2)); if noisyOut.ransacUnbrokenTime < 0 error('find_noisyChannels:BadUnbrokenParameter', ... 'ransacUnbrokenTime must be greater than 0'); elseif noisyOut.ransacUnbrokenTime < 1 ransacUnbrokenFrames = signalSize*noisyOut.ransacUnbrokenTime; else ransacUnbrokenFrames = srate*noisyOut.ransacUnbrokenTime; end nchanlocs = channelLocations(ransacChannels); if length(nchanlocs) ~= size(nchanlocs, 2) nchanlocs = nchanlocs'; end if length(nchanlocs) < ransacSubset + 1 || length(nchanlocs) < 3 || ... ransacSubset < 2 warning('find_noisyChannels:NotEnoughGoodChannels', ... 'Too many channels have failed quality tests to perform ransac'); noisyOut.ransacBadWindowFraction = 0; noisyOut.ransacPerformed = false; end end if noisyOut.ransacPerformed try % Calculate all-channel reconstruction matrices from random channel subsets locs = [cell2mat({nchanlocs.X}); cell2mat({nchanlocs.Y});cell2mat({nchanlocs.Z})]; catch err error('findNoisyChannels:NoXYZChannelLocations', ... 'Must provide valid channel locations'); end if isempty(locs) || size(locs, 2) ~= length(ransacChannels) ... || any(isnan(locs(:))) error('find_noisyChannels:EmptyChannelLocations', ... 'The signal chanlocs must have valid X, Y, and Z components'); end P = hlp_microcache('cleanchans', @calc_projector, locs, ... noisyOut.ransacSampleSize, ransacSubset); ransacCorrelationsT = zeros(length(locs), WRansac); % Calculate each channel's correlation to its RANSAC reconstruction for each window n = length(ransacWindow); m = length(ransacChannels); p = noisyOut.ransacSampleSize; Xwin = reshape(X(1:n*WRansac, :)', m, n, WRansac); parfor k = 1:WRansac ransacCorrelationsT(:, k) = ... calculateRansacWindow(squeeze(Xwin(:, :, k))', P, n, m, p); end clear Xwin; noisyOut.ransacCorrelations(ransacChannels, :) = ransacCorrelationsT; flagged = noisyOut.ransacCorrelations < noisyOut.ransacCorrelationThreshold; badChannelsFromRansac = find(sum(flagged, 2)*ransacFrames > ransacUnbrokenFrames)'; noisyOut.noisyChannels.badChannelsFromRansac = badChannelsFromRansac(:)'; noisyOut.ransacBadWindowFraction = sum(flagged, 2)/size(flagged, 2); end % Combine bad channels detected from all methods noisy = noisyOut.noisyChannels; noisyOut.noisyChannels.badChannelsFromLowSNR = ... intersect(noisy.badChannelsFromHFNoise, noisy.badChannelsFromCorrelation); noisyChannels = union(noisyChannels, ... union(union(noisy.badChannelsFromRansac, ... noisy.badChannelsFromHFNoise), ... union(noisy.badChannelsFromNaNs, ... noisy.badChannelsFromNoData))); noisyOut.noisyChannels.all = noisyChannels(:)'; noisyOut.medianMaxCorrelation = median(noisyOut.maximumCorrelations, 2); %% Helper functions for findNoisyChannels function P = calc_projector(locs, numberSamples, subsetSize) % Calculate a bag of reconstruction matrices from random channel subsets [permutedLocations, subsets] = getRandomSubsets(locs, subsetSize, numberSamples); randomSamples = cell(1, numberSamples); parfor k = 1:numberSamples tmp = zeros(size(locs, 2)); slice = subsets(k, :); tmp(slice, :) = real(spherical_interpolate(permutedLocations(:, :, k), locs))'; randomSamples{k} = tmp; end P = horzcat(randomSamples{:}); function [permutedLocations, subsets] = getRandomSubsets(locs, subsetSize, numberSamples) stream = RandStream('mt19937ar', 'Seed', 435656); numberChannels = size(locs, 2); permutedLocations = zeros(3, subsetSize, numberSamples); subsets = zeros(numberSamples, subsetSize); for k = 1:numberSamples subset = randsample(1:numberChannels, subsetSize, stream); subsets(k, :) = subset; permutedLocations(:, :, k) = locs(:, subset); end function Y = randsample(X, num, stream) Y = zeros(1, num); for k = 1:num pick = round(1 + (length(X)-1).*rand(stream)); Y(k) = X(pick); X(pick) = []; end function rX = calculateRansacWindow(XX, P, n, m, p) YY = sort(reshape(XX*P, n, m, p),3); YY = YY(:, :, round(end/2)); rX = sum(XX.*YY)./(sqrt(sum(XX.^2)).*sqrt(sum(YY.^2))); function noisyOut = getNoisyStructure() noisyOut = struct('srate', [], ... 'samples', [], ... 'evaluationChannels', [], ... 'channelLocations', [], ... 'robustDeviationThreshold', [], ... 'highFrequencyNoiseThreshold', [], ... 'correlationWindowSeconds', [], ... 'correlationThreshold', [], ... 'badTimeThreshold', [], ... 'ransacSampleSize', [], ... 'ransacChannelFraction', [], ... 'ransacCorrelationThreshold', [], ... 'ransacUnbrokenTime', [], ... 'ransacWindowSeconds', [], ... 'noisyChannels', getBadChannelStructure(), ... 'ransacPerformed', true, ... 'channelDeviationMedian', [], ... 'channelDeviationSD', [], ... 'channelDeviations', [], ... 'robustChannelDeviation', [], ... 'noisinessMedian', [], ... 'noisinessSD', [], ... 'zscoreHFNoise', [], ... 'noiseLevels', [], ... 'maximumCorrelations', [], ... 'dropOuts', [], ... 'medianMaxCorrelation', [], ... 'correlationOffsets', [], ... 'ransacCorrelations', [], ... 'ransacOffsets', [], ... 'ransacBadWindowFraction', []);
github
lcnbeapp/beapp-master
getPipelineDefaults.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/PrepPipeline/utilities/getPipelineDefaults.m
13,856
utf_8
e5ca669768d51d81aa1c2c1fc75f2890
function defaults = getPipelineDefaults(signal, type) % Returns the defaults for a given step in the standard level 2 pipeline % % Parameters: % signal a structure compatible with EEGLAB EEG structure % (must have .data and .srate fields % type a string indicating type of defaults to return: % boundary, resample, detrend, globaltrend, linenoise % reference % % Output: % defaults a structure with the parameters for the default types % in the form of a structure that has fields % value: default value % classes: classes that the parameter belongs to % attributes: attributes of the parameter % description: description of parameter % nyquist = round(signal.srate/2); topMultiple = floor(nyquist/60); lineFrequencies = (1:topMultiple)*60; switch lower(type) case 'boundary' defaults = struct('ignoreBoundaryEvents', ... getRules(false, {'logical'}, {}, ... ['If false and the signal has boundary events, PREP will abort. ' ... 'If true, PREP will temporarily remove boundary events to process ' ... ' and then put boundary events back at the end. This should be ' ... ' done with great care as some EEGLAB ' ... ' functions such as resample, respect boundaries, ' ... 'leading to spurious discontinuities.'])); case 'resample' defaults = struct( ... 'resampleOff', ... getRules(true, {'logical'}, {}, ... 'If true, resampling is not used.'), ... 'resampleFrequency', ... getRules(512, {'numeric'}, {'scalar', 'positive'}, ... ['Frequency to resample at. If signal already has a ' ... 'lower sampling rate, no resampling is done.']), ... 'lowPassFrequency', ... getRules(0, {'numeric'}, {'scalar', 'nonnegative'}, ... ['Frequency to low pass or 0 if not performed. '... 'The purpose of this low pass is to remove resampling ' ... 'artifacts.'])); case 'globaltrend' defaults = struct( ... 'globalTrendChannels', ... getRules(1:size(signal.data, 1), {'numeric'}, ... {'row', 'positive', 'integer', '<=', size(signal.data, 1)}, ... 'Vector of channel numbers of the channels for global detrending.'), ... 'doGlobal', ... getRules(false, {'logical'}, {}, ... 'If true, do a global detrending operation at before other processing.'), ... 'doLocal', ... getRules(true, {'logical'}, {}, ... 'If true, do a local linear trend before the global.'), ... 'localCutoff', ... getRules(1/200, {'numeric'}, ... {'positive', 'scalar', '<', signal.srate/2}, ... 'Frequency cutoff for long term local detrending.'), ... 'localStepSize', ... getRules(40, ... {'numeric'}, {'positive', 'scalar'}, ... 'Seconds for detrend window slide.')); case 'detrend' defaults = struct( ... 'detrendChannels', ... getRules(1:size(signal.data, 1), {'numeric'}, ... {'row', 'positive', 'integer', '<=', size(signal.data, 1)}, ... 'Vector of channel numbers of the channels to detrend.'), ... 'detrendType', ... getRules('high pass', {'char'}, {}, ... ['One of {''high pass'', ''linear'', ''none''}' ... ' indicating detrending type.']), ... 'detrendCutoff', ... getRules(1, {'numeric'}, ... {'positive', 'scalar', '<', signal.srate/2}, ... 'Frequency cutoff for detrending or high pass filtering.'), ... 'detrendStepSize', ... getRules(0.02, ... {'numeric'}, {'positive', 'scalar'}, ... 'Seconds for detrend window slide.') ... ); case 'linenoise' defaults = struct( ... 'lineNoiseChannels', ... getRules(1:size(signal.data, 1), {'numeric'}, ... {'row', 'positive', 'integer', '<=', size(signal.data, 1)}, ... 'Vector of channel numbers of the channels to remove line noise from.'), ... 'Fs', ... getRules(signal.srate, {'numeric'}, ... {'positive', 'scalar'}, ... 'Sampling rate of the signal in Hz.'), ... 'lineFrequencies', ... getRules(lineFrequencies, {'numeric'}, ... {'row', 'positive'}, ... 'Vector of frequencies in Hz of the line noise peaks to remove.'), ... 'p', ... getRules(0.01, ... {'numeric'}, {'positive', 'scalar', '<', 1}, ... 'Significance cutoff level for removing a spectral peak.'), ... 'fScanBandWidth', ... getRules(2, ... {'numeric'}, {'positive', 'scalar'}, ... ['Half of the width of the frequency band centered ' ... 'on each line frequency.']), ... 'taperBandWidth', ... getRules(2, ... {'numeric'}, {'positive', 'scalar'}, ... 'Bandwidth in Hz for the tapers.'), ... 'taperWindowSize', ... getRules(4, ... {'numeric'}, {'positive', 'scalar'}, ... 'Taper sliding window length in seconds.'), ... 'taperWindowStep', ... getRules(1, ... {'numeric'}, {'positive', 'scalar'}, ... 'Taper sliding window step size in seconds. '), ... 'tau', ... getRules(100, ... {'numeric'}, {'positive', 'scalar'}, ... 'Window overlap smoothing factor.'), ... 'pad', ... getRules(0, ... {'numeric'}, {'integer', 'scalar'}, ... ['Padding factor for FFTs (-1= no padding, 0 = pad ' ... 'to next power of 2, 1 = pad to power of two after, etc.).']), ... 'fPassBand', ... getRules([0 signal.srate/2], {'numeric'}, ... {'nonnegative', 'row', 'size', [1, 2], '<=', signal.srate/2}, ... 'Frequency band used (default [0, Fs/2])'), ... 'maximumIterations', ... getRules(10, ... {'numeric'}, {'positive', 'scalar'}, ... ['Maximum number of times the cleaning process ' ... 'applied to remove line noise.']) ... ); case 'reference' defaults = struct( ... 'srate', ... getRules(signal.srate, {'numeric'}, ... {'positive', 'scalar'}, ... 'Sampling rate of the signal in Hz.'), ... 'samples', ... getRules(size(signal.data, 2), {'numeric'}, ... {'positive', 'scalar'}, ... 'Number of frames to use for computation.'), ... 'robustDeviationThreshold', ... getRules(5, {'numeric'}, ... {'positive', 'scalar'}, ... 'Z-score cutoff for robust channel deviation.'), ... 'highFrequencyNoiseThreshold', ... getRules(5, {'numeric'}, ... {'positive', 'scalar'}, ... 'Z-score cutoff for SNR (signal above 50 Hz).'), ... 'correlationWindowSeconds', ... getRules(1, {'numeric'}, ... {'positive', 'scalar'}, ... 'Correlation window size in seconds.'), ... 'correlationThreshold', ... getRules(0.4, {'numeric'}, ... {'positive', 'scalar', '<=', 1}, ... 'Max correlation threshold for channel being bad in a window.'), ... 'badTimeThreshold', ... getRules(0.01, {'numeric'}, ... {'positive', 'scalar'}, ... ['Threshold fraction of bad correlation windows '... 'for designating channel to be bad.']), ... 'ransacOff', ... getRules(false, {'logical'}, {}, ... ['If true, RANSAC is not used for bad channel ' ... '(useful for small headsets).']), ... 'ransacSampleSize', ... getRules(50, {'numeric'}, ... {'positive', 'scalar', 'integer'}, ... 'Number of sample matrices for computing ransac.'), ... 'ransacChannelFraction', ... getRules(0.25, {'numeric'}, ... {'positive', 'scalar', '<=', 1}, ... 'Fraction of evaluation channels RANSAC uses to predict a channel.'), ... 'ransacCorrelationThreshold', ... getRules(0.75, {'numeric'}, ... {'positive', 'scalar', '<=', 1}, ... 'Cutoff correlation for unpredictability by neighbors.'), ... 'ransacUnbrokenTime', ... getRules(0.4, {'numeric'}, ... {'positive', 'scalar', '<=', 1}, ... 'Cutoff fraction of time channel can have poor ransac predictability.'), ... 'ransacWindowSeconds', ... getRules(5, {'numeric'}, ... {'positive', 'scalar'}, ... 'Size of windows in seconds over which to compute RANSAC predictions.'), ... 'referenceType', ... getRules('robust', {'char'}, {}, ... ['Type of reference to be performed: ' ... 'robust (default), average, specific, or none.']), ... 'interpolationOrder', ... getRules('post-reference', {'char'}, {}, ... ['Specifies when interpolation is performed during referencing: ' ... 'post-reference: bad channels are detected again and interpolated after referencing, ' ... 'pre-reference: bad channels detected before referencing and interpolated, ' ... 'none: no interpolation is performed.']), ... 'meanEstimateType', ... getRules('median', {'char'}, {}, ... ['Method for initial estimate of the robust mean: ' ... 'median (default), huber, mean, or none']), ... 'referenceChannels', ... getRules(1:size(signal.data, 1), {'numeric'}, ... {'row', 'positive', 'integer', '<=', size(signal.data, 1)}, ... 'Vector of channel numbers of the channels used for reference.'), ... 'evaluationChannels', ... getRules(1:size(signal.data, 1), {'numeric'}, ... {'row', 'positive', 'integer', '<=', size(signal.data, 1)}, ... 'Vector of channel numbers of the channels to test for noisiness.'), ... 'rereferencedChannels', ... getRules(1:size(signal.data, 1), {'numeric'}, ... {'row', 'positive', 'integer', '<=', size(signal.data, 1)}, ... 'Vector of channel numbers of the channels to rereference.'), ... 'channelLocations', ... getRules(getFieldIfExists(signal, 'chanlocs'), {'struct'}, ... {'nonempty'}, ... 'Structure containing channel locations in EEGLAB chanlocs format.'), ... 'channelInformation', ... getRules(getFieldIfExists(signal, 'chaninfo'), ... {'struct'}, {}, ... 'Channel information --- particularly nose direction.'), ... 'maxReferenceIterations', ... getRules(4, ... {'numeric'}, {'positive', 'scalar'}, ... 'Maximum number of referencing interations.'), ... 'reportingLevel', ... getRules('verbose', ... {'char'}, {}, ... 'Set how much information to store about referencing.') ... ); case 'report' [~, EEGbase] = fileparts(signal.filename); defaults = struct( ... 'reportMode', ... getRules('normal', {'char'}, {}, ... ['Select whether or how report should be generated: ' ... 'normal (default) means report generated after PREP, ' ... 'skip means report not generated at all, ' ... 'reportOnly means PREP is skipped and report generated.']), ... 'summaryFilePath', ... getRules(['.' filesep EEGbase 'Summary.html'], {'char'}, {}, ... 'File name (including necessary path) for html summary file.'), ... 'sessionFilePath', ... getRules(['.' filesep EEGbase 'Report.pdf'], {'char'}, {}, ... 'File name (including necessary path) pdf detail report.'), ... 'consoleFID', ... getRules(1, {'numeric'}, {'positive', 'integer'}, ... 'Open file desriptor for displaying report messages.'), ... 'publishOn', ... getRules(true, {'logical'}, {}, ... 'If true, use MATLAB publish to publish the results.') ... ); case 'postprocess' defaults = struct(... 'keepFiltered', ... getRules(false, {'logical'}, {}, ... 'If true, apply a final filter to remove low frequency trend.'), ... 'removeInterpolatedChannels', ... getRules(false, {'logical'}, {}, ... 'If true, remove channels interpolated by Prep.'), ... 'cleanupReference', ... getRules(false, {'logical'}, {}, ... ['If true, remove many fields in .etc.noiseDetection.reference '... 'resulting in smaller dataset. ' ... 'The Prep report cannot be generated in this case.'])); otherwise end end function s = getRules(value, classes, attributes, description) % Construct the default structure s = struct('value', [], 'classes', [], ... 'attributes', [], 'description', []); s.value = value; s.classes = classes; s.attributes = attributes; s.description = description; end
github
lcnbeapp/beapp-master
spherical_interpolate.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/PrepPipeline/utilities/private/spherical_interpolate.m
4,083
utf_8
fb9968c02ce1ce52a721e5a69a0679ae
function [W, Gss, Gds, Hds] = ... spherical_interpolate(src, dest, lambda, order, type, tol) % Caclulate an interpolation matrix for spherical interpolation % % W = sphericalSplineInterpolate(src, dest, lambda, order, type, tol) % % Inputs: % src - [3 x N] old electrode positions % dest - [3 x M] new electrode positions % lambda - [float] regularisation parameter for smoothing the estimates (1e-5) % order - [float] order of the polynomial interpolation to use (4) % type - [str] one of; ('spline') % 'spline' - spherical Spline % 'slap' - surface Laplacian (aka. CSD) % tol - [float] tolerance for the legendre poly approx (1e-7) % % Outputs: % W - [M x N] linear mapping matrix between old and new co-ords % % Based upon the paper: Perrin89 % Copyright 2009- by Jason D.R. Farquhar ([email protected]) % Permission is granted for anyone to copy, use, or modify this % software and accompanying documents, provided this copyright % notice is retained, and note is made of any changes that have been % made. This software and documents are distributed without any % warranty, express or implied. % % Modified by Kay Robbins 8/24/2014: Minor cleanup and simplification % Warning --- still in progress if ( nargin < 3 || isempty(lambda) ) lambda = 1e-5; end; %#ok<SEPEX> if ( nargin < 4 || isempty(order) ) order = 4; end; %#ok<SEPEX> if ( nargin < 5 || isempty(type)) type = 'spline'; end; %#ok<SEPEX> if ( nargin < 6 || isempty(tol) ) tol = eps; end; %#ok<SEPEX> % Map the positions onto the sphere (not using repop, by JMH) src = src./repmat(sqrt(sum(src.^2)), size(src, 1), 1); dest = dest./repmat(sqrt(sum(dest.^2)), size(dest, 1), 1); % Calculate the cosine of the angle between the new and old electrodes. If % the vectors are on top of each other, the result is 1, if they are % pointing the other way, the result is -1 cosSS = src'*src; % angles between source positions cosDS = dest'*src; % angles between destination positions % Compute the interpolation matrix to tolerance tol [Gss] = interpMx(cosSS, order, tol); % [nSrc x nSrc] [Gds, Hds] = interpMx(cosDS, order, tol); % [nDest x nSrc] % Include the regularisation if lambda > 0 Gss = Gss + lambda*eye(size(Gss)); end % Compute the mapping to the polynomial coefficients space % [nSrc+1 x nSrc+1] % N.B. this can be numerically unstable so use the PINV to solve.. muGss = 1; % Used to improve condition number when inverting. Probably unnecessary C = [Gss muGss*ones(size(Gss, 1),1); muGss*ones(1, size(Gss,2)) 0]; iC = pinv(C); % Compute the mapping from source measurements and positions to destination positions if ( strcmpi(type, 'spline') ) W = [Gds ones(size(Gds, 1), 1).*muGss]*iC(:, 1:end-1); % [nDest x nSrc] elseif (strcmpi(type, 'slap')) W = Hds*iC(1:end-1, 1:end-1); % [nDest x nSrc] end return; %-------------------------------------------------------------------------- function [G, H]=interpMx(cosEE, order, tol) % compute the interpolation matrix for this set of point pairs if ( nargin < 3 || isempty(tol) ) tol = 1e-10; end G = zeros(size(cosEE)); H = zeros(size(cosEE)); for i = 1:numel(cosEE); x = cosEE(i); n = 1; Pns1 = 1; Pn = x; % seeds for the legendre ploy recurrence tmp = ( (2*n + 1) * Pn ) / ((n*n + n).^order); G(i) = tmp ; % 1st element in the sum H(i) = (n*n + n)*tmp; % 1st element in the sum dG = abs(G(i)); dH = abs(H(i)); for n = 2:500; % do the sum Pns2 = Pns1; Pns1 = Pn; Pn=((2*n - 1)*x*Pns1 - (n - 1)*Pns2)./n; % legendre poly recurrence oGi = G(i); oHi = H(i); tmp = ((2*n+1) * Pn) / ((n*n+n).^order); G(i) = G(i) + tmp; % update function estimate, spline interp H(i) = H(i) + (n*n + n)*tmp; % update function estimate, SLAP dG = (abs(oGi - G(i)) + dG)/2; dH = (abs(oHi - H(i)) + dH)/2; % moving ave gradient est for convergence if (dG < tol && dH < tol) break; end; % stop when tol reached end end G = G./(4*pi); H = H./(4*pi); return;
github
lcnbeapp/beapp-master
filter_fast.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/PrepPipeline/utilities/private/filter_fast.m
5,932
utf_8
7bd0d7a6eb2f56ea6ba352a602ddba6b
function [X,Zf] = filter_fast(B,A,X,Zi,dim) % Like filter(), but faster when both the filter and the signal are long. % [Y,Zf] = filter_fast(B,A,X,Zi,Dim) % % Uses FFT convolution. The function is faster than filter when approx. length(B)>256 and % size(X,Dim)>1024, otherwise slower (due size-testing overhead). % % See also: % filter, fftfilt % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-07-09 % % contains fftfilt.m from Octave: % Copyright (C) 1996-1997 John W. Eaton % Copyright (C) Christian Kothe, SCCN, 2010, [email protected] % % This program is free software; you can redistribute it and/or modify it under the terms of the GNU % General Public License as published by the Free Software Foundation; either version 2 of the % License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without % even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU % General Public License for more details. % % You should have received a copy of the GNU General Public License along with this program; if not, % write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 % USA if nargin <= 4 dim = find(size(X)~=1,1); end if nargin <= 3 Zi = []; end lenx = size(X,dim); lenb = length(B); if lenx == 0 % empty X Zf = Zi; elseif lenb < 256 || lenx<1024 || lenx <= lenb || lenx*lenb < 4000000 || ~isequal(A,1) % use the regular filter if nargout > 1 [X,Zf] = filter(B,A,X,Zi,dim); else X = filter(B,A,X,Zi,dim); end else was_single = strcmp(class(X),'single'); % fftfilt can be used if isempty(Zi) % no initial conditions to take care of if nargout < 2 % and no final ones X = unflip(oct_fftfilt(B,flip(double(X),dim)),dim); else % final conditions needed X = flip(X,dim); [dummy,Zf] = filter(B,1,X(end-length(B)+1:end,:),Zi,1); %#ok<ASGLU> X = oct_fftfilt(B,double(X)); X = unflip(X,dim); end else % initial conditions available X = flip(X,dim); % get a Zi-informed piece tmp = filter(B,1,X(1:length(B),:),Zi,1); if nargout > 1 % also need final conditions [dummy,Zf] = filter(B,1,X(end-length(B)+1:end,:),Zi,1); %#ok<ASGLU> end X = oct_fftfilt(B,double(X)); % incorporate the piece X(1:length(B),:) = tmp; X = unflip(X,dim); end if was_single X = single(X); end end function X = flip(X,dim) if dim ~= 1 order = 1:ndims(X); order = order([dim 1]); X = permute(X,order); end function X = unflip(X,dim) if dim ~= 1 order = 1:ndims(X); order = order([dim 1]); X = ipermute(X,order); end function y = oct_fftfilt(b, x, N) % Copyright (C) 1996, 1997 John W. Eaton % % This file is part of Octave. % % Octave is free software; you can redistribute it and/or modify it % under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2, or (at your option) % any later version. % % Octave is distributed in the hope that it will be useful, but % WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU % General Public License for more details. % % You should have received a copy of the GNU General Public License % along with Octave; see the file COPYING. If not, write to the Free % Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA % 02110-1301, USA. % % -*- texinfo -*- % @deftypefn {Function File} {} fftfilt (@var{b}, @var{x}, @var{n}) % % With two arguments, @code{fftfilt} filters @var{x} with the FIR filter % @var{b} using the FFT. % % Given the optional third argument, @var{n}, @code{fftfilt} uses the % overlap-add method to filter @var{x} with @var{b} using an N-point FFT. % % If @var{x} is a matrix, filter each column of the matrix. % @end deftypefn % % Author: Kurt Hornik <[email protected]> % Created: 3 September 1994 % Adapted-By: jwe % If N is not specified explicitly, we do not use the overlap-add % method at all because loops are really slow. Otherwise, we only % ensure that the number of points in the FFT is the smallest power % of two larger than N and length(b). This could result in length % one blocks, but if the user knows better ... transpose = (size(x,1) == 1); if transpose x = x.'; end [r_x,c_x] = size(x); [r_b,c_b] = size(b); if min([r_b, c_b]) ~= 1 error('octave:fftfilt','fftfilt: b should be a vector'); end l_b = r_b*c_b; b = reshape(b,l_b,1); if nargin == 2 % Use FFT with the smallest power of 2 which is >= length (x) + % length (b) - 1 as number of points ... N = 2^(ceil(log(r_x+l_b-1)/log(2))); B = fft(b,N); y = ifft(fft(x,N).*B(:,ones(1,c_x))); else % Use overlap-add method ... if ~isscalar(N) error ('octave:fftfilt','fftfilt: N has to be a scalar'); end N = 2^(ceil(log(max([N,l_b]))/log(2))); L = N - l_b + 1; B = fft(b, N); B = B(:,ones(c_x,1)); R = ceil(r_x / L); y = zeros(r_x, c_x); for r = 1:R lo = (r - 1) * L + 1; hi = min(r * L, r_x); tmp = zeros(N, c_x); tmp(1:(hi-lo+1),:) = x(lo:hi,:); tmp = ifft(fft(tmp).*B); hi = min(lo+N-1, r_x); y(lo:hi,:) = y(lo:hi,:) + tmp(1:(hi-lo+1),:); end end y = y(1:r_x,:); if transpose y = y.'; end % Final cleanups: if both x and b are real respectively integer, y % should also be if isreal(b) && isreal(x) y = real(y); end if ~any(b - round(b)) idx = ~any(x - round(x)); y(:,idx) = round(y(:,idx)); end
github
lcnbeapp/beapp-master
calculateSpectrum.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/PrepPipeline/reporting/calculateSpectrum.m
18,986
utf_8
c31339bc182ac61b1e7ba1e5a90429f2
% spectopo() - Plot the mean log spectrum of a set of data epochs at all channels % as a bundle of traces. At specified frequencies, plot the relative % topographic distribution of power. If available, uses pwelch() from % the Matlab signal processing toolbox, else the EEGLAB spec() function. % Plots the mean spectrum for all of the supplied data, not just % the pre-stimulus baseline. % Usage: % >> spectopo(data, frames, srate); % >> [spectra,freqs,speccomp,contrib,specstd] = ... % spectopo(data, frames, srate, 'key1','val1', 'key2','val2' ...); % Inputs: % data = If 2-D (nchans,time_points); % may be a continuous single epoch, % else a set of concatenated data epochs, else a 3-D set of data % epochs (nchans,frames,epochs) % frames = frames per epoch {default|0 -> data length} % srate = sampling rate per channel (Hz) % % Optional 'keyword',[argument] input pairs: % 'freq' = [float vector (Hz)] vector of frequencies at which to plot power % scalp maps, or else a single frequency at which to plot component % contributions at a single channel (see also 'plotchan'). % 'chanlocs' = [electrode locations filename or EEG.chanlocs structure]. % For format, see >> topoplot example % 'limits' = [xmin xmax ymin ymax cmin cmax] axis limits. Sets x, y, and color % axis limits. May omit final values or use NaNs. % Ex: [0 60 NaN NaN -10 10], [0 60], ... % Default color limits are symmetric around 0 and are different % for each scalp map {default|all NaN's: from the data limits} % 'freqfac' = [integer] ntimes to oversample -> frequency resolution {default: 2} % 'nfft' = [integer] length to zero-pad data to. Overwrites 'freqfac' above. % 'winsize' = [integer] window size in data points {default: from data} % 'overlap' = [integer] window overlap in data points {default: 0} % 'percent' = [float 0 to 100] percent of the data to sample for computing the % spectra. Values < 100 speed up the computation. {default: 100}. % 'freqrange' = [min max] frequency range to plot. Changes x-axis limits {default: % 1 Hz for the min and Nyquist (srate/2) for the max. If specified % power distribution maps are plotted, the highest mapped frequency % determines the max freq}. % 'reref' = ['averef'|'off'] convert data to average reference {default: 'off'} % 'mapnorm' = [float vector] If 'data' contain the activity of an independant % component, this parameter should contain its scalp map. In this case % the spectrum amplitude will be scaled to component RMS scalp power. % Useful for comparing component strengths {default: none} % 'boundaries' = data point indices of discontinuities in the signal {default: none} % 'plot' = ['on'|'off'] 'off' -> disable plotting {default: 'on'} % 'rmdc' = ['on'|'off'] 'on' -> remove DC {default: 'off'} % 'plotmean' = ['on'|'off'] 'on' -> plot the mean channel spectrum {default: 'off'} % 'plotchans' = [integer array] plot only specific channels {default: all} % % Optionally plot component contributions: % 'weights' = ICA unmixing matrix. Here, 'freq' (above) must be a single frequency. % ICA maps of the N ('nicamaps') components that account for the most % power at the selected frequency ('freq') are plotted along with % the spectra of the selected channel ('plotchan') and components % ('icacomps'). % 'plotchan' = [integer] channel at which to compute independent conmponent % contributions at the selected frequency ('freq'). If 0, plot RMS % power at all channels. {defatul|[] -> channel with highest power % at specified 'freq' (above)). Do not confuse with % 'plotchans' which select channels for plotting. % 'mapchans' = [int vector] channels to plot in topoplots {default: all} % 'mapframes'= [int vector] frames to plot {default: all} % 'nicamaps' = [integer] number of ICA component maps to plot {default: 4}. % 'icacomps' = [integer array] indices of ICA component spectra to plot ([] -> all). % 'icamode' = ['normal'|'sub'] in 'sub' mode, instead of computing the spectra of % individual ICA components, the function computes the spectrum of % the data minus their contributions {default: 'normal'} % 'icamaps' = [integer array] force plotting of selected ICA compoment maps % {default: [] = the 'nicamaps' largest contributing components}. % 'icawinv' = [float array] inverse component weight or mixing matrix. Normally, % this is computed by inverting the ICA unmixing matrix 'weights' (above). % However, if any components were removed from the supplied 'weights'mapchans % then the component maps will not be correctly drawn and the 'icawinv' % matrix should be supplied here {default: from component 'weights'} % 'memory' = ['low'|'high'] a 'low' setting will use less memory for computing % component activities, will take longer {default: 'high'} % % Replotting options: % 'specdata' = [freq x chan array ] spectral data % 'freqdata' = [freq] array of frequencies % % Topoplot options: % other 'key','val' options are propagated to topoplot() for map display % (See >> help topoplot) % % Outputs: % spectra = (nchans,nfreqs) power spectra (mean power over epochs), in dB % freqs = frequencies of spectra (Hz) % % Notes: The original input format is still functional for backward compatibility. % psd() has been replaced by pwelch() (see Matlab note 24750 on their web site) % % Authors: Scott Makeig, Arnaud Delorme & Marissa Westerfield, % SCCN/INC/UCSD, La Jolla, 3/01 % % See also: timtopo(), envtopo(), tftopo(), topoplot() % Copyright (C) 3/01 Scott Makeig & Arnaud Delorme & Marissa Westerfield, SCCN/INC/UCSD, % [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 3-20-01 added limits arg -sm % 01-25-02 reformated help & license -ad % 02-15-02 scaling by epoch number line 108 - ad, sm & lf % 03-15-02 add all topoplot options -ad % 03-18-02 downsampling factor to speed up computation -ad % 03-27-02 downsampling factor exact calculation -ad % 04-03-02 added axcopy -sm % Uses: MATLAB pwelch(), changeunits(), topoplot(), textsc() function [eegspecdB,freqs] = calculateSpectrum(data,frames,srate,varargin) % formerly: ... headfreqs,chanlocs,limits,titl,freqfac, percent, varargin) FREQFAC = 2; if nargin<3 help spectopo return end if nargin <= 3 || ischar(varargin{1}) % 'key' 'val' sequence fieldlist = { 'freq' 'real' [] [] ; 'specdata' 'real' [] [] ; 'freqdata' 'real' [] [] ; 'chanlocs' '' [] [] ; 'freqrange' 'real' [0 srate/2] [] ; 'memory' 'string' {'low','high'} 'high' ; 'plotmean' 'string' {'on','off'} 'off' ; 'limits' 'real' [] [nan nan nan nan nan nan]; 'freqfac' 'integer' [] FREQFAC; 'percent' 'real' [0 100] 100 ; 'reref' 'string' { 'averef','off','no' } 'off' ; 'boundaries' 'integer' [] [] ; 'nfft' 'integer' [1 Inf] [] ; 'winsize' 'integer' [1 Inf] [] ; 'overlap' 'integer' [1 Inf] 0 ; 'icamode' 'string' { 'normal','sub' } 'normal' ; 'weights' 'real' [] [] ; 'mapnorm' 'real' [] [] ; 'plotchan' 'integer' 1:size(data,1) [] ; 'plotchans' 'integer' 1:size(data,1) [] ; 'nicamaps' 'integer' [] 4 ; 'icawinv' 'real' [] [] ; 'icacomps' 'integer' [] [] ; 'icachansind' 'integer' [] 1:size(data,1) ; % deprecated 'icamaps' 'integer' [] [] ; 'rmdc' 'string' {'on','off'} 'off'; 'mapchans' 'integer' 1:size(data,1) [] 'mapframes' 'integer' 1:size(data,2) []}; [g, varargin] = finputcheck(varargin, fieldlist, 'spectopo', 'ignore'); if ischar(g), error(g); end; if ~isempty(g.freqrange), g.limits(1:2) = g.freqrange; end; if ~isempty(g.weights) if isempty(g.freq) || length(g.freq) > 2 if ~isempty(get(0,'currentfigure')) && strcmp(get(gcf, 'tag'), 'spectopo'), close(gcf); end; error('spectopo(): for computing component contribution, one must specify a (single) frequency'); end; end; else if ~isnumeric(data) error('spectopo(): Incorrect call format (see >> help spectopo).') end if ~isnumeric(frames) || round(frames) ~= frames error('spectopo(): Incorrect call format (see >> help spectopo).') end if ~isnumeric(srate) % 3rd arg must be the sampling rate in Hz error('spectopo(): Incorrect call format (see >> help spectopo).') end if nargin > 3, g.freq = varargin{1}; else g.freq = []; end; if nargin > 4, g.chanlocs = varargin{2}; else g.chanlocs = []; end; if nargin > 5, g.limits = varargin{3}; else g.limits = [nan nan nan nan nan nan]; end; if nargin > 6, g.freqfac = varargin{4}; else g.freqfac = FREQFAC; end; if nargin > 7, g.percent = varargin{5}; else g.percent = 100; end; if nargin > 9, g.reref = 'averef'; else g.reref = 'off'; end; g.weights = []; g.icamaps = []; end; if g.percent > 1 g.percent = g.percent/100; % make it from 0 to 1 end; if ~isempty(g.freq) && isempty(g.chanlocs) error('spectopo(): needs channel location information'); end; if isempty(g.weights) && ~isempty(g.plotchans) data = data(g.plotchans,:); if ~isempty(g.chanlocs) g.chanlocs = g.chanlocs(g.plotchans); end; end; if strcmpi(g.rmdc, 'on') data = data - repmat(mean(data,2), [ 1 size(data,2) 1]); end data = reshape(data, size(data,1), size(data,2)*size(data,3)); if frames == 0 frames = size(data,2); % assume one epoch end if ~isempty(g.freq) && min(g.freq)<0 if ~isempty(get(0,'currentfigure')) && strcmp(get(gcf, 'tag'), 'spectopo'), close(gcf); end; return end g.chanlocs2 = g.chanlocs; if ~isempty(g.specdata) eegspecdB = g.specdata; freqs = g.freqdata; else epochs = round(size(data,2)/frames); if frames*epochs ~= size(data,2) error('Spectopo: non-integer number of epochs'); end if ~isempty(g.weights) if isempty(g.icawinv) g.icawinv = pinv(g.weights); % maps end; if ~isempty(g.icacomps) g.weights = g.weights(g.icacomps, :); g.icawinv = g.icawinv(:,g.icacomps); else g.icacomps = 1:size(g.weights,1); end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute channel spectra using pwelch() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% epoch_subset = ones(1,epochs); if g.percent ~= 1 && epochs == 1 frames = round(size(data,2)*g.percent); data = data(:, 1:frames); g.boundaries(g.boundaries > frames) = []; if ~isempty(g.boundaries) g.boundaries(end+1) = frames; end; end; if g.percent ~= 1 && epochs > 1 epoch_subset = zeros(1,epochs); nb = ceil( g.percent*epochs); while nb>0 index = ceil(rand*epochs); if ~epoch_subset(index) epoch_subset(index) = 1; nb = nb-1; end; end; epoch_subset = find(epoch_subset == 1); else epoch_subset = find(epoch_subset == 1); end; if isempty(g.weights) %%%%%%%%%%%%%%%%%%%%%%%%%%% % compute data spectra %%%%%%%%%%%%%%%%%%%%%%%%%%% [eegspecdB, freqs] = spectcomp( data, frames, srate, epoch_subset, g); if ~isempty(g.mapnorm) % normalize by component map RMS power (if data contain 1 component %disp('Scaling spectrum by component RMS of scalp map power'); eegspecdB = sqrt(mean(g.mapnorm.^4)) * eegspecdB; % the idea is to take the RMS of the component activity (compact) projected at each channel % spec = sqrt( power(g.mapnorm(1)*compact).^2 + power(g.mapnorm(2)*compact).^2 + ...) % spec = sqrt( g.mapnorm(1)^4*power(compact).^2 + g.mapnorm(1)^4*power(compact).^2 + ...) % spec = sqrt( g.mapnorm(1)^4 + g.mapnorm(1)^4 + ... )*power(compact) end; tmpc = find(eegspecdB(:,1)); % > 0 power chans if length(tmpc) ~= size(eegspecdB,1) eegspecdB = eegspecdB(tmpc,:); if ~isempty(g.chanlocs) g.chanlocs2 = g.chanlocs(tmpc); end end; eegspecdB = 10*log10(eegspecdB); else % compute data spectrum if isempty(g.plotchan) || g.plotchan == 0 [eegspecdB, freqs] = spectcomp( data, frames, srate, epoch_subset, g); else g.reref = 'off'; [eegspecdB, freqs] = spectcomp( data(g.plotchan,:), frames, srate, epoch_subset, g); end; g.reref = 'off'; tmpc = find(eegspecdB(:,1)); % > 0 power chans if length(tmpc) ~= size(eegspecdB,1) eegspecdB = eegspecdB(tmpc,:); if ~isempty(g.chanlocs) g.chanlocs2 = g.chanlocs(tmpc); end end; eegspecdB = 10*log10(eegspecdB); %%%%%%%%%%%%%%%%%%%%%%%%%%% % compute component spectra %%%%%%%%%%%%%%%%%%%%%%%%%%% newweights = g.weights; if strcmp(g.memory, 'high') && strcmp(g.icamode, 'normal') [~, freqs] = spectcomp( newweights*data(:,:), frames, srate, epoch_subset, g); else % in case out of memory error, multiply conmponent sequencially if strcmp(g.icamode, 'sub') && ~isempty(g.plotchan) && g.plotchan == 0 % scan all electrodes for index = 1:size(data,1) g.plotchan = index; [~, freqs] = spectcomp( data, frames, srate, epoch_subset, g, newweights); end; g.plotchan = 0; else [~, freqs] = spectcomp( data, frames, srate, epoch_subset, g, newweights); end; end; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function computing spectrum %%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [eegspecdB, freqs] = spectcomp( data, frames, srate, epoch_subset, g, newweights) if exist('newweights', 'var') == 1 nchans = size(newweights,1); else nchans = size(data,1); end; %fftlength = 2^round(log(srate)/log(2))*g.freqfac; if isempty(g.winsize) winlength = max(pow2(nextpow2(frames)-3),4); %*2 since diveded by 2 later winlength = min(winlength, 512); winlength = max(winlength, 256); winlength = min(winlength, frames); else winlength = g.winsize; end; if isempty(g.nfft) fftlength = 2^(nextpow2(winlength))*g.freqfac; else fftlength = g.nfft; end; % usepwelch = 1; usepwelch = license('checkout','Signal_Toolbox'); % 5/22/2014 Ramon % if ~license('checkout','Signal_Toolbox'), % if ~usepwelch, % end; for c=1:nchans % scan channels or components if exist('newweights', 'var') == 1 if strcmp(g.icamode, 'normal') tmpdata = newweights(c,:)*data; % component activity else % data - component contribution tmpdata = data(g.plotchan,:) - (g.icawinv(g.plotchan,c)*newweights(c,:))*data; end; else tmpdata = data(c,:); % channel activity end; if strcmp(g.reref, 'averef') tmpdata = averef(tmpdata); end; for e=epoch_subset if isempty(g.boundaries) if usepwelch [tmpspec,freqs] = pwelch(matsel(tmpdata,frames,0,1,e),... winlength,g.overlap,fftlength,srate); else [tmpspec,freqs] = spec(matsel(tmpdata,frames,0,1,e),fftlength,srate,... winlength,g.overlap); end; %[tmpspec,freqs] = psd(matsel(tmpdata,frames,0,1,e),fftlength,srate,... % winlength,g.overlap); if c==1 && e==epoch_subset(1) eegspec = zeros(nchans,length(freqs)); end eegspec(c,:) = eegspec(c,:) + tmpspec'; else g.boundaries = round(g.boundaries); for n=1:length(g.boundaries)-1 if g.boundaries(n+1) - g.boundaries(n) >= winlength % ignore segments of less than winlength if usepwelch [tmpspec,freqs] = pwelch(tmpdata(e,g.boundaries(n)+1:g.boundaries(n+1)),... winlength,g.overlap,fftlength,srate); else [tmpspec,freqs] = spec(tmpdata(e,g.boundaries(n)+1:g.boundaries(n+1)),... fftlength,srate,winlength,g.overlap); end; if exist('eegspec', 'var') ~= 1 eegspec = zeros(nchans,length(freqs)); end eegspec(c,:) = eegspec(c,:) + tmpspec'* ... ((g.boundaries(n+1)-g.boundaries(n)+1)/g.boundaries(end)); end; end end; end end n = length(epoch_subset); eegspecdB = eegspec/n; % normalize by the number of sections return;
github
lcnbeapp/beapp-master
matsel.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/PrepPipeline/reporting/helpers/matsel.m
3,756
utf_8
3779008d46e2601576fba59179f48a0c
% matsel() - select rows, columns, and epochs from given multi-epoch data matrix % % Usage: % >> [dataout] = matsel(data,frames,framelist); % >> [dataout] = matsel(data,frames,framelist,chanlist); % >> [dataout] = matsel(data,frames,framelist,chanlist,epochlist); % % Inputs: % data - input data matrix (chans,frames*epochs) % frames - frames (data columns) per epoch (0 -> frames*epochs) % framelist - list of frames per epoch to select (0 -> 1:frames) % chanlist - list of chans to select (0 -> 1:chans) % epochlist - list of epochs to select (0 -> 1:epochs) % % Note: The size of dataout is (length(chanlist), length(framelist)*length(epochlist)) % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 5-21-96 % Copyright (C) 5-21-96 Scott Makeig, SCCN/INC/UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 5-25-96 added chanlist, epochlist -sm % 10-05-97 added out of bounds tests for chanlist and framelist -sm % 02-04-00 truncate to epochs*frames if necessary -sm % 01-25-02 reformated help & license -ad function [dataout] = matsel(data,frames,framelist,chanlist,epochlist) if nargin<1 help matsel return end [chans framestot] = size(data); if isempty(data) fprintf('matsel(): empty data matrix!?\n') help matsel return end if nargin < 5, epochlist = 0; end if nargin < 4, chanlist = 0; end if nargin < 3, fprintf('matsel(): needs at least 3 arguments.\n\n'); return end if frames == 0, frames = framestot; end if framelist == 0, framelist = [1:frames]; end framesout = length(framelist); if isempty(chanlist) | chanlist == 0, chanlist = [1:chans]; end chansout = length(chanlist); epochs = floor(framestot/frames); if epochs*frames ~= framestot fprintf('matsel(): data length %d was not a multiple of %d frames.\n',... framestot,frames); data = data(:,1:epochs*frames); end if isempty(epochlist) | epochlist == 0, epochlist = [1:epochs]; end epochsout = length(epochlist); if max(epochlist)>epochs fprintf('matsel() error: max index in epochlist (%d) > epochs in data (%d)\n',... max(epochlist),epochs); return end if max(framelist)>frames fprintf('matsel() error: max index in framelist (%d) > frames per epoch (%d)\n',... max(framelist),frames); return end if min(framelist)<1 fprintf('matsel() error: framelist min (%d) < 1\n', min(framelist)); return end if min(epochlist)<1 fprintf('matsel() error: epochlist min (%d) < 1\n', min(epochlist)); return end if max(chanlist)>chans fprintf('matsel() error: chanlist max (%d) > chans (%d)\n',... max(chanlist),chans); return end if min(chanlist)<1 fprintf('matsel() error: chanlist min (%d) <1\n',... min(chanlist)); return end dataout = zeros(chansout,framesout*epochsout); for e=1:epochsout dataout(:,framesout*(e-1)+1:framesout*e) = ... data(chanlist,framelist+(epochlist(e)-1)*frames); end
github
lcnbeapp/beapp-master
finputcheck.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/PrepPipeline/reporting/helpers/finputcheck.m
9,133
utf_8
8e445ff93b185f97308409ce1e4300d4
% finputcheck() - check Matlab function {'key','value'} input argument pairs % % Usage: >> result = finputcheck( varargin, fieldlist ); % >> [result varargin] = finputcheck( varargin, fieldlist, ... % callingfunc, mode, verbose ); % Input: % varargin - Cell array 'varargin' argument from a function call using 'key', % 'value' argument pairs. See Matlab function 'varargin'. % May also be a structure such as struct(varargin{:}) % fieldlist - A 4-column cell array, one row per 'key'. The first % column contains the key string, the second its type(s), % the third the accepted value range, and the fourth the % default value. Allowed types are 'boolean', 'integer', % 'real', 'string', 'cell' or 'struct'. For example, % {'key1' 'string' { 'string1' 'string2' } 'defaultval_key1'} % {'key2' {'real' 'integer'} { minint maxint } 'defaultval_key2'} % callingfunc - Calling function name for error messages. {default: none}. % mode - ['ignore'|'error'] ignore keywords that are either not specified % in the fieldlist cell array or generate an error. % {default: 'error'}. % verbose - ['verbose', 'quiet'] print information. Default: 'verbose'. % % Outputs: % result - If no error, structure with 'key' as fields and 'value' as % content. If error this output contain the string error. % varargin - residual varagin containing unrecognized input arguments. % Requires mode 'ignore' above. % % Note: In case of error, a string is returned containing the error message % instead of a structure. % % Example (insert the following at the beginning of your function): % result = finputcheck(varargin, ... % { 'title' 'string' [] ''; ... % 'percent' 'real' [0 1] 1 ; ... % 'elecamp' 'integer' [1:10] [] }); % if isstr(result) % error(result); % end % % Note: % The 'title' argument should be a string. {no default value} % The 'percent' argument should be a real number between 0 and 1. {default: 1} % The 'elecamp' argument should be an integer between 1 and 10 (inclusive). % % Now 'g.title' will contain the title arg (if any, else the default ''), etc. % % Author: Arnaud Delorme, CNL / Salk Institute, 10 July 2002 % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 10 July 2002, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [g, varargnew] = finputcheck( vararg, fieldlist, callfunc, mode, verbose ) if nargin < 2 help finputcheck; return; end; if nargin < 3 callfunc = ''; else callfunc = [callfunc ' ' ]; end; if nargin < 4 mode = 'do not ignore'; end; if nargin < 5 verbose = 'verbose'; end; NAME = 1; TYPE = 2; VALS = 3; DEF = 4; SIZE = 5; varargnew = {}; % create structure % ---------------- if ~isempty(vararg) if isstruct(vararg) g = vararg; else for index=1:length(vararg) if iscell(vararg{index}) vararg{index} = {vararg{index}}; end; end; try g = struct(vararg{:}); catch vararg = removedup(vararg, verbose); try g = struct(vararg{:}); catch g = [ callfunc 'error: bad ''key'', ''val'' sequence' ]; return; end; end; end; else g = []; end; for index = 1:size(fieldlist,NAME) % check if present % ---------------- if ~isfield(g, fieldlist{index, NAME}) g = setfield( g, fieldlist{index, NAME}, fieldlist{index, DEF}); end; tmpval = getfield( g, {1}, fieldlist{index, NAME}); % check type % ---------- if ~iscell( fieldlist{index, TYPE} ) res = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}, ... fieldlist{index, VALS}, tmpval, callfunc ); if isstr(res), g = res; return; end; else testres = 0; tmplist = fieldlist; for it = 1:length( fieldlist{index, TYPE} ) if ~iscell(fieldlist{index, VALS}) res{it} = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}{it}, ... fieldlist{index, VALS}, tmpval, callfunc ); else res{it} = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}{it}, ... fieldlist{index, VALS}{it}, tmpval, callfunc ); end; if ~isstr(res{it}), testres = 1; end; end; if testres == 0, g = res{1}; for tmpi = 2:length(res) g = [ g 10 'or ' res{tmpi} ]; end; return; end; end; end; % check if fields are defined % --------------------------- allfields = fieldnames(g); for index=1:length(allfields) if isempty(strmatch(allfields{index}, fieldlist(:, 1)', 'exact')) if ~strcmpi(mode, 'ignore') g = [ callfunc 'error: undefined argument ''' allfields{index} '''']; return; end; varargnew{end+1} = allfields{index}; varargnew{end+1} = getfield(g, {1}, allfields{index}); end; end; function g = fieldtest( fieldname, fieldtype, fieldval, tmpval, callfunc ) NAME = 1; TYPE = 2; VALS = 3; DEF = 4; SIZE = 5; g = []; switch fieldtype case { 'integer' 'real' 'boolean' 'float' }, if ~isnumeric(tmpval) && ~islogical(tmpval) g = [ callfunc 'error: argument ''' fieldname ''' must be numeric' ]; return; end; if strcmpi(fieldtype, 'boolean') if tmpval ~=0 && tmpval ~= 1 g = [ callfunc 'error: argument ''' fieldname ''' must be 0 or 1' ]; return; end; else if strcmpi(fieldtype, 'integer') if ~isempty(fieldval) if (any(isnan(tmpval(:))) && ~any(isnan(fieldval))) ... && (~ismember(tmpval, fieldval)) g = [ callfunc 'error: wrong value for argument ''' fieldname '''' ]; return; end; end; else % real or float if ~isempty(fieldval) && ~isempty(tmpval) if any(tmpval < fieldval(1)) || any(tmpval > fieldval(2)) g = [ callfunc 'error: value out of range for argument ''' fieldname '''' ]; return; end; end; end; end; case 'string' if ~isstr(tmpval) g = [ callfunc 'error: argument ''' fieldname ''' must be a string' ]; return; end; if ~isempty(fieldval) if isempty(strmatch(lower(tmpval), lower(fieldval), 'exact')) g = [ callfunc 'error: wrong value for argument ''' fieldname '''' ]; return; end; end; case 'cell' if ~iscell(tmpval) g = [ callfunc 'error: argument ''' fieldname ''' must be a cell array' ]; return; end; case 'struct' if ~isstruct(tmpval) g = [ callfunc 'error: argument ''' fieldname ''' must be a structure' ]; return; end; case 'function_handle' if ~isa(tmpval, 'function_handle') g = [ callfunc 'error: argument ''' fieldname ''' must be a function handle' ]; return; end; case ''; otherwise, error([ 'finputcheck error: unrecognized type ''' fieldname '''' ]); end; % remove duplicates in the list of parameters % ------------------------------------------- function cella = removedup(cella, verbose) % make sure if all the values passed to unique() are strings, if not, exist %try [tmp, indices] = unique_bc(cella(1:2:end)); if length(tmp) ~= length(cella)/2 myfprintf(verbose,'Note: duplicate ''key'', ''val'' parameter(s), keeping the last one(s)\n'); end; cella = cella(sort(union(indices*2-1, indices*2))); %catch % some elements of cella were not string % error('some ''key'' values are not string.'); %end; function myfprintf(verbose, varargin) if strcmpi(verbose, 'verbose') fprintf(varargin{:}); end;
github
lcnbeapp/beapp-master
pop_dipfit_manual.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/pop_dipfit_manual.m
1,755
utf_8
eba5714bbc90a749dad3cbbf6d51a4d7
% pop_dipfit_manual() - interactively do dipole fit of selected ICA components % Function deprecated. Use pop_dipfit_nonlinear() % instead % Usage: % >> OUTEEG = pop_dipfit_manual( INEEG ) % % Inputs: % INEEG input dataset % % Outputs: % OUTEEG output dataset % % Author: Robert Oostenveld, SMI/FCDC, Nijmegen 2003 % Arnaud Delorme, SCCN, La Jolla 2003 % SMI, University Aalborg, Denmark http://www.smi.auc.dk/ % FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl/ % Copyright (C) 2003 Robert Oostenveld, SMI/FCDC [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [OUTEEG, com] = pop_dipfit_manual( varargin ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin<1 help pop_dipfit_manual; return else disp('Warning: pop_dipfit_manual is outdated. Use pop_dipfit_nonlinear instead'); [OUTEEG, com] = pop_dipfit_nonlinear( varargin{:} ); end;
github
lcnbeapp/beapp-master
eeglab2fieldtrip.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/eeglab2fieldtrip.m
5,812
utf_8
2191a7e220db8b7bb5ad4e1bfe5a929d
% eeglab2fieldtrip() - do this ... % % Usage: >> data = eeglab2fieldtrip( EEG, fieldbox, transform ); % % Inputs: % EEG - [struct] EEGLAB structure % fieldbox - ['preprocessing'|'freqanalysis'|'timelockanalysis'|'companalysis'] % transform - ['none'|'dipfit'] transform channel locations for DIPFIT % using the transformation matrix in the field % 'coord_transform' of the dipfit substructure of the EEG % structure. % Outputs: % data - FIELDTRIP structure % % Author: Robert Oostenveld, F.C. Donders Centre, May, 2004. % Arnaud Delorme, SCCN, INC, UCSD % % See also: % Copyright (C) 2004 Robert Oostenveld, F.C. Donders Centre, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function data = eeglab2fieldtrip(EEG, fieldbox, transform) if nargin < 2 help eeglab2fieldtrip return; end; % start with an empty data object data = []; % add the objects that are common to all fieldboxes tmpchanlocs = EEG.chanlocs; %data.label = { tmpchanlocs(EEG.icachansind).labels }; data.fsample = EEG.srate; % get the electrode positions from the EEG structure: in principle, the number of % channels can be more or less than the number of channel locations, i.e. not % every channel has a position, or the potential was not measured on every % position. This is not supported by EEGLAB, but it is supported by FIELDTRIP. if strcmpi(fieldbox, 'chanloc_withfid') % insert "no data channels" in channel structure % ---------------------------------------------- if isfield(EEG.chaninfo, 'nodatchans') && ~isempty( EEG.chaninfo.nodatchans ) chanlen = length(EEG.chanlocs); fields = fieldnames( EEG.chaninfo.nodatchans ); for index = 1:length(EEG.chaninfo.nodatchans) ind = chanlen+index; for f = 1:length( fields ) EEG.chanlocs = setfield(EEG.chanlocs, { ind }, fields{f}, ... getfield( EEG.chaninfo.nodatchans, { index }, fields{f})); end; end; end; end; data.elec.pnt = zeros(length( EEG.chanlocs ), 3); for ind = 1:length( EEG.chanlocs ) data.elec.label{ind} = EEG.chanlocs(ind).labels; if ~isempty(EEG.chanlocs(ind).X) data.elec.pnt(ind,1) = EEG.chanlocs(ind).X; data.elec.pnt(ind,2) = EEG.chanlocs(ind).Y; data.elec.pnt(ind,3) = EEG.chanlocs(ind).Z; else data.elec.pnt(ind,:) = [0 0 0]; end; end; if nargin > 2 if strcmpi(transform, 'dipfit') if ~isempty(EEG.dipfit.coord_transform) disp('Transforming electrode coordinates to match head model'); transfmat = traditionaldipfit(EEG.dipfit.coord_transform); data.elec.pnt = transfmat * [ data.elec.pnt ones(size(data.elec.pnt,1),1) ]'; data.elec.pnt = data.elec.pnt(1:3,:)'; else disp('Warning: no transformation of electrode coordinates to match head model'); end; end; end; switch fieldbox case 'preprocessing' for index = 1:EEG.trials data.trial{index} = EEG.data(:,:,index); data.time{index} = linspace(EEG.xmin, EEG.xmax, EEG.pnts); % should be checked in FIELDTRIP end; % data.label = { tmpchanlocs(1:EEG.nbchan).labels }; case 'timelockanalysis' data.avg = mean(EEG.data, 3); data.var = std(EEG.data, [], 3).^2; data.time = linspace(EEG.xmin, EEG.xmax, EEG.pnts); % should be checked in FIELDTRIP data.label = { tmpchanlocs(1:EEG.nbchan).labels }; case 'componentanalysis' if isempty(EEG.icaact) icaacttmp = eeg_getica(EEG); end for index = 1:EEG.trials % the trials correspond to the raw data trials, except that they % contain the component activations try if isempty(EEG.icaact) data.trial{index} = icaacttmp(:,:,index); % Using icaacttmp to not change EEG structure else data.trial{index} = EEG.icaact(:,:,index); end catch end; data.time{index} = linspace(EEG.xmin, EEG.xmax, EEG.pnts); % should be checked in FIELDTRIP end; data.label = []; for comp = 1:size(EEG.icawinv,2) % the labels correspond to the component activations that are stored in data.trial data.label{comp} = sprintf('ica_%03d', comp); end % get the spatial distribution and electrode positions tmpchanlocs = EEG.chanlocs; data.topolabel = { tmpchanlocs(EEG.icachansind).labels }; data.topo = EEG.icawinv; case { 'chanloc' 'chanloc_withfid' } case 'freqanalysis' error('freqanalysis fieldbox not implemented yet') otherwise error('unsupported fieldbox') end try % get the full name of the function data.cfg.version.name = mfilename('fullpath'); catch % required for compatibility with Matlab versions prior to release 13 (6.5) [st, i] = dbstack; data.cfg.version.name = st(i); end % add the version details of this function call to the configuration data.cfg.version.id = '$Id: eeglab2fieldtrip.m,v 1.6 2009-07-02 23:39:29 arno Exp $'; return
github
lcnbeapp/beapp-master
dipfit_reject.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/dipfit_reject.m
1,823
utf_8
7d157ab7d3da320a78bb851d5d3b5669
% dipfit_reject() - remove dipole models with a poor fit % % Usage: % >> dipout = dipfit_reject( model, reject ) % % Inputs: % model struct array with a dipole model for each component % % Outputs: % dipout struct array with a dipole model for each component % % Author: Robert Oostenveld, SMI/FCDC, Nijmegen 2003 % SMI, University Aalborg, Denmark http://www.smi.auc.dk/ % FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl/ % Copyright (C) 2003 Robert Oostenveld, SMI/FCDC [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [dipout] = dipfit_reject(model, reject) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin < 1 help dipfit_reject; return; end; for i=1:length(model) if model(i).rv>reject % reject this dipole model by replacing it by an empty model dipout(i).posxyz = []; dipout(i).momxyz = []; dipout(i).rv = 1; else dipout(i).posxyz = model(i).posxyz; dipout(i).momxyz = model(i).momxyz; dipout(i).rv = model(i).rv; end end
github
lcnbeapp/beapp-master
pop_dipplot.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/pop_dipplot.m
8,649
utf_8
f0e67d40c3bd34a95443673ebb76b95b
% pop_dipplot() - plot dipoles. % % Usage: % >> pop_dipplot( EEG ); % pop up interactive window % >> pop_dipplot( EEG, comps, 'key1', 'val1', 'key2', 'val2', ...); % % Graphic interface: % "Components" - [edit box] enter component number to plot. By % all the localized components are plotted. Command % line equivalent: components. % "Background image" - [edit box] MRI background image. This image % has to be normalized to the MNI brain using SPM2 for % instance. Dipplot() command line equivalent: 'image'. % "Summary mode" - [Checkbox] when checked, plot the 3 views of the % head model and dipole locations. Dipplot() equivalent % is 'summary' and 'num'. % "Plot edges" - [Checkbox] plot edges at the intersection between % MRI slices. Diplot() equivalent is 'drawedges'. % "Plot closest MRI slide" - [Checkbox] plot closest MRI slice to % dipoles although not using the 'tight' view mode. % Dipplot() equivalent is 'cornermri' and 'axistight'. % "Plot dipole's 2-D projections" - [Checkbox] plot a dimed dipole % projection on each 2-D MRI slice. Dipplot() equivalent % is 'projimg'. % "Plot projection lines" - [Checkbox] plot lines originating from % dipoles and perpendicular to each 2-D MRI slice. % Dipplot() equivalent is 'projline'. % "Make all dipole point out" - [Checkbox] make all dipole point % toward outside the brain. Dipplot() equivalent is % 'pointout'. % "Normalized dipole length" - [Checkbox] normalize the length of % all dipoles. Dipplot() command line equivalent: 'normlen'. % "Additionnal dipfit() options" - [checkbox] enter additionnal % sequence of 'key', 'val' argument in this edit box. % % Inputs: % EEG - Input dataset % comps - [integer array] plot component indices. If empty % all the localized components are plotted. % % Optional inputs: % 'key','val' - same as dipplot() % % Author: Arnaud Delorme, CNL / Salk Institute, 26 Feb 2003- % % See also: dipplot() % "Use dipoles from" - [list box] use dipoles from BESA or from the % DIPFIT toolbox. Command line equivalent: type. % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [com] = pop_dipplot( EEG, comps, varargin); com =''; if nargin < 1 help pop_dipplot; return; end; % check input structure % --------------------- if ~isfield(EEG, 'dipfit') & ~isfield(EEG, 'sources') if ~isfield(EEG.dipfit.hdmfile) & ~isfield(EEG, 'sources') error('No dipole information in dataset'); end; error('No dipole information in dataset'); end; if ~isfield(EEG.dipfit, 'model') error('No dipole information in dataset'); end; typedip = 'nonbesa'; if nargin < 2 % popup window parameters % ----------------------- commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ... 'if filename ~=0,' ... ' set(findobj(''parent'', gcbf, ''tag'', ''mrifile''), ''string'', [ filepath filename ]);' ... 'end;' ... 'clear filename filepath tagtest;' ]; geometry = { [2 1] [2 1] [0.8 0.3 1.5] [2.05 0.26 .75] [2.05 0.26 .75] [2.05 0.26 .75] ... [2.05 0.26 .75] [2.05 0.26 .75] [2.05 0.26 .75] [2.05 0.26 .75] [2 1] }; uilist = { { 'style' 'text' 'string' 'Components indices ([]=all avaliable)' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Plot dipoles within RV (%) range ([min max])' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Background image' } ... { 'style' 'pushbutton' 'string' '...' 'callback' commandload } ... { 'style' 'edit' 'string' EEG.dipfit.mrifile 'tag' 'mrifile' } ... { 'style' 'text' 'string' 'Plot summary mode' } ... { 'style' 'checkbox' 'string' '' } {} ... { 'style' 'text' 'string' 'Plot edges' } ... { 'style' 'checkbox' 'string' '' } {} ... { 'style' 'text' 'string' 'Plot closest MRI slide' } ... { 'style' 'checkbox' 'string' '' } {} ... { 'style' 'text' 'string' 'Plot dipole''s 2-D projections' } ... { 'style' 'checkbox' 'string' '' } {} ... { 'style' 'text' 'string' 'Plot projection lines' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'string' 'Make all dipoles point out' } ... { 'style' 'checkbox' 'string' '' } {} ... { 'style' 'text' 'string' 'Normalized dipole length' } ... { 'style' 'checkbox' 'string' '' 'value' 1 } {} ... { 'style' 'text' 'string' 'Additionnal dipplot() options' } ... { 'style' 'edit' 'string' '' } }; result = inputgui( geometry, uilist, 'pophelp(''pop_dipplot'')', 'Plot dipoles - pop_dipplot'); if length(result) == 0 return; end; % decode parameters % ----------------- options = {}; if ~isempty(result{1}), comps = eval( [ '[' result{1} ']' ] ); else comps = []; end; if ~isempty(result{2}), options = { options{:} 'rvrange' eval( [ '[' result{2} ']' ] ) }; end; options = { options{:} 'mri' result{3} }; if result{4} == 1, options = { options{:} 'summary' 'on' 'num' 'on' }; end; if result{5} == 1, options = { options{:} 'drawedges' 'on' }; end; if result{6} == 1, options = { options{:} 'cornermri' 'on' 'axistight' 'on' }; end; if result{7} == 1, options = { options{:} 'projimg' 'on' }; end; if result{8} == 1, options = { options{:} 'projlines' 'on' }; end; if result{9} == 1, options = { options{:} 'pointout' 'on' }; end; if result{10} == 1, options = { options{:} 'normlen' 'on' }; end; if ~isempty( result{11} ), tmpopt = eval( [ '{' result{11} '}' ] ); options = { options{:} tmpopt{:} }; end; else if isstr(comps) typedip = comps; options = varargin(2:end); comps = varargin{1}; else options = varargin; end; end; if strcmpi(typedip, 'besa') if ~isfield(EEG, 'sources'), error('No BESA dipole information in dataset');end; if ~isempty(comps) [tmp1 int] = intersect( [ EEG.sources.component ], comps); if isempty(int), error ('Localization not found for selected components'); end; dipplot(EEG.sources(int), 'sphere', 1, options{:}); else dipplot(EEG.sources, options{:}); end; else if ~isfield(EEG, 'dipfit'), error('No DIPFIT dipole information in dataset');end; % components to plot % ------------------ if ~isempty(comps) if ~isfield(EEG.dipfit.model, 'component') for index = double(comps(:)') EEG.dipfit.model(index).component = index; end; end; else % find localized dipoles comps = []; for index2 = 1:length(EEG.dipfit.model) if ~isempty(EEG.dipfit.model(index2).posxyz) ~= 0 comps = [ comps index2 ]; EEG.dipfit.model(index2).component = index2; end; end; end; % plotting % -------- tmpoptions = { options{:} 'coordformat', EEG.dipfit.coordformat }; if strcmpi(EEG.dipfit.coordformat, 'spherical') dipplot(EEG.dipfit.model(comps), tmpoptions{:}); elseif strcmpi(EEG.dipfit.coordformat, 'CTF') dipplot(EEG.dipfit.model(comps), tmpoptions{:}); else dipplot(EEG.dipfit.model(comps), 'meshdata', EEG.dipfit.hdmfile, tmpoptions{:}); end; end; if nargin < 3 com = sprintf('pop_dipplot( %s,%s);', inputname(1), vararg2str({ comps options{:}})); end; return;
github
lcnbeapp/beapp-master
dipplot.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/dipplot.m
61,455
utf_8
1bc351e760494d6b9df714acf3a089ed
% dipplot() - Visualize EEG equivalent-dipole locations and orientations % in the MNI average MRI head or in the BESA spherical head model. % Usage: % >> dipplot( sources, 'key', 'val', ...); % >> [sources X Y Z XE YE ZE] = dipplot( sources, 'key', 'val', ...); % % Inputs: % sources - structure array of dipole information: can contain % either BESA or DIPFIT dipole information. BESA dipole % information are still supported but may disapear in the % future. For DIPFIT % sources.posxyz: contains 3-D location of dipole in each % column. 2 rows indicate 2 dipoles. % sources.momxyz: contains 3-D moments for dipoles above. % sources.rv : residual variance from 0 to 1. % other fields : used for graphic interface. % % Optional input: % 'rvrange' - [min max] or [max] Only plot dipoles with residual variace % within the given range. Default: plot all dipoles. % 'summary' - ['on'|'off'|'3d'] Build a summary plot with three views (top, % back, side). {default: 'off'} % 'mri' - Matlab file containing an MRI volume and a 4-D transformation % matrix to go from voxel space to electrode space: % mri.anatomy contains a 3-D anatomical data array % mri.transfrom contains a 4-D homogenous transformation matrix. % 'coordformat' - ['MNI'|'spherical'] Consider that dipole coordinates are in % MNI or spherical coordinates (for spherical, the radius of the % head is assumed to be 85 (mm)). See also function sph2spm(). % 'transform' - [real array] traditional transformation matrix to convert % dipole coordinates to MNI space. Default is assumed from % 'coordformat' input above. Type help traditional for more % information. % 'image' - ['besa'|'mri'] Background image. % 'mri' (or 'fullmri') uses mean-MRI brain images from the Montreal % Neurological Institute. This option can also contain a 3-D MRI % volume (dim 1: left to right; dim 2: anterior-posterior; dim 3: % superior-inferior). Use 'coregist' to coregister electrodes % with the MRI. {default: 'mri'} % 'verbose' - ['on'|'off'] comment on operations on command line {default: % 'on'}. % 'plot' - ['on'|'off'] only return outputs {default: 'off'}. % % Plotting options: % 'color' - [cell array of color strings or (1,3) color arrays]. For % exemple { 'b' 'g' [1 0 0] } gives blue, green and red. % Dipole colors will rotate through the given colors if % the number given is less than the number of dipoles to plot. % A single number will be used as color index in the jet colormap. % 'view' - 3-D viewing angle in cartesian coords., % [0 0 1] gives a sagittal view, [0 -1 0] a view from the rear; % [1 0 0] gives a view from the side of the head. % 'mesh' - ['on'|'off'] Display spherical mesh. {Default is 'on'} % 'meshdata' - [cell array|'file_name'] Mesh data in a cell array { 'vertices' % data 'faces' data } or a boundary element model filename (the % function will plot the 3rd mesh in the 'bnd' sub-structure). % 'axistight' - ['on'|'off'] For MRI only, display the closest MRI % slide. {Default is 'off'} % 'gui' - ['on'|'off'] Display controls. {Default is 'on'} If gui 'off', % a new figure is not created. Useful for incomporating a dipplot % into a complex figure. % 'num' - ['on'|'off'] Display component number. Take into account % dipole size. {Default: 'off'} % 'cornermri' - ['on'|'off'] force MRI images to the corner of the MRI volume % (usefull when background is not black). Default: 'off'. % 'drawedges' - ['on'|'off'] draw edges of the 3-D MRI (black in axistight, % white otherwise.) Default is 'off'. % 'projimg' - ['on'|'off'] Project dipole(s) onto the 2-D images, for use % in making 3-D plots {Default 'off'} % 'projlines' - ['on'|'off'] Plot lines connecting dipole with 2-D projection. % Color is dashed black for BESA head and dashed black for the % MNI brain {Default 'off'} % 'projcol' - [color] color for the projected line {Default is same as dipole} % 'dipolesize' - Size of the dipole sphere(s). This option may also contain one % value per dipole {Default: 30} % 'dipolelength' - Length of the dipole bar(s) {Default: 1} % 'pointout' - ['on'|'off'] Point the dipoles outward. {Default: 'off'} % 'sphere' - [float] radius of sphere corresponding to the skin. Default is 1. % 'spheres' - ['on'|'off'] {default: 'off'} plot dipole markers as 3-D spheres. % Does not yet interact with gui buttons, produces non-gui mode. % 'spheresize' - [real>0] size of spheres (if 'on'). {default: 5} % 'normlen' - ['on'|'off'] Normalize length of all dipoles. {Default: 'off'} % 'dipnames' - [cell array] cell array of string with a name for each dipole (or % pair of dipole). % 'holdon' - ['on'|'off'] create a new dipplot figure or plot dipoles within an % an existing figure. Default is 'off'. % 'camera' - ['auto'|'set'] camera position. 'auto' is the default and % an option using camera zoom. 'set' is a fixed view that % does not depend on the content being plotted. % % Outputs: % sources - EEG.source structure with two extra fiels 'mnicoord' and 'talcoord' % containing the MNI and talairach coordinates of the dipoles. Note % that for the BEM model, dipoles are already in MNI coordinates. % X,Y,Z - Locations of dipole heads (Cartesian coordinates in MNI space). % If there is more than one dipole per components, the last dipole % is returned. % XE,YE,ZE - Locations of dipole ends (Cartesian coordinates). The same % remark as above applies. % % Author: Arnaud Delorme, CNL / Salk Institute, 1st July 2002 % % Notes: See DIPFIT web tutorial at sccn.ucsd.edu/eeglab/dipfittut/dipfit.html % for more details about MRI co-registration etc... % % Example: % % define dipoles % sources(1).posxyz = [-59 48 -28]; % position for the first dipole % sources(1).momxyz = [ 0 58 -69]; % orientation for the first dipole % sources(1).rv = 0.036; % residual variance for the first dipole % sources(2).posxyz = [74 -4 -38]; % position for the second dipole % sources(2).momxyz = [43 -38 -16]; % orientation for the second dipole % sources(2).rv = 0.027; % residual variance for the second dipole % % % plot of the two dipoles (first in green, second in blue) % dipplot( sources, 'color', { 'g' 'b' }); % % % To make a stereographic plot % figure( 'position', [153 553 1067 421]; % subplot(1,3,1); dipplot( sources, 'view', [43 10], 'gui', 'off'); % subplot(1,3,3); dipplot( sources, 'view', [37 10], 'gui', 'off'); % % % To make a summary plot % dipplot( sources, 'summary', 'on', 'num', 'on'); % % See also: eeglab(), dipfit() % old options % ----------- % 'std' - [cell array] plot standard deviation of dipoles. i.e. % { [1:6] [7:12] } plot two elipsoids that best fit all the dipoles % from 1 to 6 and 7 to 12 with radius 1 standard deviation. % { { [1:6] 2 'linewidth' 2 } [7:12] } do the same but now the % first elipsoid is 2 standard-dev and the lines are thicker. % Copyright (C) 2002 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 % README -- Plotting strategy: % - All buttons have a tag 'tmp' so they can be removed % - The component-number buttons have 'userdata' equal to 'editor' and % can be found easily by other buttons find('userdata', 'editor') % - All dipoles have a tag 'dipoleX' (X=their number) and can be made % visible/invisible % - The gcf object 'userdat' field stores the handle of the dipole that % is currently being modified % - Gca 'userdata' stores imqge names and position function [outsources, XX, YY, ZZ, XO, YO, ZO] = dipplot( sourcesori, varargin ) DEFAULTVIEW = [0 0 1]; if nargin < 1 help dipplot; return; end; % reading and testing arguments % ----------------------------- sources = sourcesori; if ~isstruct(sources) updatedipplot(sources(1)); % sources countain the figure handler return end; % key type range default g = finputcheck( varargin, { 'color' '' [] []; 'axistight' 'string' { 'on' 'off' } 'off'; 'camera' 'string' { 'auto' 'set' } 'auto'; 'coordformat' 'string' { 'MNI' 'spherical' 'CTF' 'auto' } 'auto'; 'drawedges' 'string' { 'on' 'off' } 'off'; 'mesh' 'string' { 'on' 'off' } 'off'; 'gui' 'string' { 'on' 'off' } 'on'; 'summary' 'string' { 'on2' 'on' 'off' '3d' } 'off'; 'verbose' 'string' { 'on' 'off' } 'on'; 'view' 'real' [] [0 0 1]; 'rvrange' 'real' [0 Inf] []; 'transform' 'real' [0 Inf] []; 'normlen' 'string' { 'on' 'off' } 'off'; 'num' 'string' { 'on' 'off' } 'off'; 'cornermri' 'string' { 'on' 'off' } 'off'; 'mri' { 'string' 'struct' } [] ''; 'dipnames' 'cell' [] {}; 'projimg' 'string' { 'on' 'off' } 'off'; 'projcol' '' [] []; 'projlines' 'string' { 'on' 'off' } 'off'; 'pointout' 'string' { 'on' 'off' } 'off'; 'holdon' 'string' { 'on' 'off' } 'off'; 'dipolesize' 'real' [0 Inf] 30; 'dipolelength' 'real' [0 Inf] 1; 'sphere' 'real' [0 Inf] 1; 'spheres' 'string' {'on' 'off'} 'off'; 'links' 'real' [] []; 'image' { 'string' 'real' } [] 'mri'; 'plot' 'string' { 'on' 'off' } 'on'; 'meshdata' { 'string' 'cell' } [] '' }, 'dipplot'); % 'std' 'cell' [] {}; % 'coreg' 'real' [] []; if isstr(g), error(g); end; if strcmpi(g.holdon, 'on'), g.gui = 'off'; end; if length(g.dipolesize) == 1, g.dipolesize = repmat(g.dipolesize, [1 length(sourcesori)]); end; g.zoom = 1500; if strcmpi(g.image, 'besa') error('BESA image not supported any more. Use EEGLAB version 4.512 or earlier. (BESA dipoles can still be plotted in MNI brain.)'); end; % trying to determine coordformat % ------------------------------- if ~isfield(sources, 'momxyz') g.coordformat = 'spherical'; end; if strcmpi(g.coordformat, 'auto') if ~isempty(g.meshdata) g.coordformat = 'MNI'; if strcmpi(g.verbose, 'on'), disp('Coordinate format unknown: using ''MNI'' since mesh data was provided as input'); end else maxdiplen = 0; for ind = 1:length(sourcesori) maxdiplen = max(maxdiplen, max(abs(sourcesori(ind).momxyz(:)))); end; if maxdiplen>2000 if strcmpi(g.verbose, 'on'), disp('Coordinate format unknown: using ''MNI'' because of large dipole moments'); end else g.coordformat = 'spherical'; if strcmpi(g.verbose, 'on'), disp('Coordinate format unknown: using ''spherical'' since no mesh data was provided as input'); end end; end; end; % axis image and limits % --------------------- dat.axistight = strcmpi(g.axistight, 'on'); dat.drawedges = g.drawedges; dat.cornermri = strcmpi(g.cornermri, 'on'); radius = 85; % look up an MRI file if necessary % -------------------------------- if isempty(g.mri) if strcmpi(g.verbose, 'on'), disp('No MRI file given as input. Looking up one.'); end dipfitdefs; g.mri = template_models(1).mrifile; end; % read anatomical MRI using Fieldtrip and SPM2 functons % ----------------------------------------------------- if isstr(g.mri); try, g.mri = load('-mat', g.mri); g.mri = g.mri.mri; catch, disp('Failed to read Matlab file. Attempt to read MRI file using function ft_read_mri'); try, warning off; g.mri = ft_read_mri(g.mri); %g.mri.anatomy(find(g.mri.anatomy > 255)) = 255; %g.mri.anatomy = uint8(g.mri.anatomy); g.mri.anatomy = round(gammacorrection( g.mri.anatomy, 0.8)); g.mri.anatomy = uint8(round(g.mri.anatomy/max(reshape(g.mri.anatomy, prod(g.mri.dim),1))*255)); % WARNING: if using double instead of int8, the scaling is different % [-128 to 128 and 0 is not good] % WARNING: the transform matrix is not 1, 1, 1 on the diagonal, some slices may be % misplaced warning on; catch, error('Cannot load file using ft_read_mri'); end; end; end; if strcmpi(g.coordformat, 'spherical') dat.sph2spm = sph2spm; elseif strcmpi(g.coordformat, 'CTF') dat.sph2spm = traditionaldipfit([0 0 0 0 0 0 10 -10 10]); else dat.sph2spm = []; %traditional([0 0 0 0 0 pi 1 1 1]); end; if ~isempty(g.transform), dat.sph2spm = traditionaldipfit(g.transform); end; if isfield(g.mri, 'anatomycol') dat.imgs = g.mri.anatomycol; else dat.imgs = g.mri.anatomy; end; dat.transform = g.mri.transform; % MRI coordinates for slices % -------------------------- if ~isfield(g.mri, 'xgrid') g.mri.xgrid = [1:size(dat.imgs,1)]; g.mri.ygrid = [1:size(dat.imgs,2)]; g.mri.zgrid = [1:size(dat.imgs,3)]; end; if strcmpi(g.coordformat, 'CTF') g.mri.zgrid = g.mri.zgrid(end:-1:1); end; dat.imgcoords = { g.mri.xgrid g.mri.ygrid g.mri.zgrid }; dat.maxcoord = [max(dat.imgcoords{1}) max(dat.imgcoords{2}) max(dat.imgcoords{3})]; COLORMESH = 'w'; BACKCOLOR = 'k'; % point 0 % ------- [xx yy zz] = transform(0, 0, 0, dat.sph2spm); % nothing happens for BEM since dat.sph2spm is empty dat.zeroloc = [ xx yy zz ]; % conversion % ---------- if strcmpi(g.normlen, 'on') if isfield(sources, 'besaextori') sources = rmfield(sources, 'besaextori'); end; end; if ~isfield(sources, 'besathloc') & strcmpi(g.image, 'besa') & ~is_sccn error(['For copyright reasons, it is not possible to use the BESA ' ... 'head model to plot non-BESA dipoles']); end; if isfield(sources, 'besathloc') sources = convertbesaoldformat(sources); end; if ~isfield(sources, 'posxyz') sources = computexyzforbesa(sources); end; if ~isfield(sources, 'component') if strcmpi(g.verbose, 'on'), disp('No component indices, making incremental ones...'); end for index = 1:length(sources) sources(index).component = index; end; end; % find non-empty sources % ---------------------- noempt = cellfun('isempty', { sources.posxyz } ); sources = sources( find(~noempt) ); % transform coordinates % --------------------- outsources = sources; for index = 1:length(sources) sources(index).momxyz = sources(index).momxyz/1000; end; % remove 0 second dipoles if any % ------------------------------ for index = 1:length(sources) if size(sources(index).momxyz,1) == 2 if all(sources(index).momxyz(2,:) == 0) sources(index).momxyz = sources(index).momxyz(1,:); sources(index).posxyz = sources(index).posxyz(1,:); end; end; end; % remove sources with out of bound Residual variance % -------------------------------------------------- if isfield(sources, 'rv') & ~isempty(g.rvrange) if length(g.rvrange) == 1, g.rvrange = [ 0 g.rvrange ]; end; for index = length(sources):-1:1 if sources(index).rv < g.rvrange(1)/100 | sources(index).rv > g.rvrange(2)/100 sources(index) = []; end; end; end; % color array % ----------- if isempty(g.color) g.color = { 'g' 'b' 'r' 'm' 'c' 'y' }; if strcmp(BACKCOLOR, 'w'), g.color = { g.color{:} 'k' }; end; end; g.color = g.color(mod(0:length(sources)-1, length(g.color)) +1); if ~isempty(g.color) g.color = strcol2real( g.color, jet(64) ); end; if ~isempty(g.projcol) g.projcol = strcol2real( g.projcol, jet(64) ); g.projcol = g.projcol(mod(0:length(sources)-1, length(g.projcol)) +1); else g.projcol = g.color; for index = 1:length(g.color) g.projcol{index} = g.projcol{index}/2; end; end; % build summarized figure % ----------------------- if strcmpi(g.summary, 'on') | strcmpi(g.summary, 'on2') figure; options = { 'gui', 'off', 'dipolesize', g.dipolesize/1.5,'dipolelength', g.dipolelength, 'sphere', g.sphere ... 'color', g.color, 'mesh', g.mesh, 'num', g.num, 'image', g.image 'normlen' g.normlen ... 'coordformat' g.coordformat 'mri' g.mri 'meshdata' g.meshdata 'axistight' g.axistight }; pos1 = [0 0 0.5 0.5]; pos2 = [0 0.5 0.5 .5]; pos3 = [.5 .5 0.5 .5]; if strcmp(g.summary, 'on2'), tmp = pos1; pos1 =pos3; pos3 = tmp; end; axes('position', pos1); newsources = dipplot(sourcesori, 'view', [1 0 0] , options{:}); axis off; axes('position', pos2); newsources = dipplot(sourcesori, 'view', [0 0 1] , options{:}); axis off; axes('position', pos3); newsources = dipplot(sourcesori, 'view', [0 -1 0], options{:}); axis off; axes('position', [0.5 0 0.5 0.5]); colorcount = 1; if isfield(newsources, 'component') for index = 1:length(newsources) if isempty(g.dipnames), tmpname = sprintf( 'Comp. %d', newsources(index).component); else tmpname = char(g.dipnames{index}); end; talpos = newsources(index).talcoord; if strcmpi(g.coordformat, 'CTF') textforgui(colorcount) = { sprintf( [ tmpname ' (RV:%3.2f%%)' ], 100*newsources(index).rv) }; elseif size(talpos,1) == 1 textforgui(colorcount) = { sprintf( [ tmpname ' (RV:%3.2f%%; Tal:%d,%d,%d)' ], ... 100*newsources(index).rv, ... round(talpos(1,1)), round(talpos(1,2)), round(talpos(1,3))) }; else textforgui(colorcount) = { sprintf( [ tmpname ' (RV:%3.2f%%; Tal:%d,%d,%d & %d,%d,%d)' ], ... 100*newsources(index).rv, ... round(talpos(1,1)), round(talpos(1,2)), round(talpos(1,3)), ... round(talpos(2,1)), round(talpos(2,2)), round(talpos(2,3))) }; end; colorcount = colorcount+1; end; colorcount = colorcount-1; allstr = strvcat(textforgui{:}); h = text(0,0.45, allstr); if colorcount >= 15, set(h, 'fontsize', 8);end; if colorcount >= 20, set(h, 'fontsize', 6);end; if strcmp(BACKCOLOR, 'k'), set(h, 'color', 'w'); end; end; axis off; return; elseif strcmpi(g.summary, '3d') options = { 'gui', 'off', 'dipolesize', g.dipolesize/1.5,'dipolelength', g.dipolelength, 'sphere', g.sphere, 'spheres', g.spheres ... 'color', g.color, 'mesh', g.mesh, 'num', g.num, 'image', g.image 'normlen' g.normlen ... 'coordformat' g.coordformat 'mri' g.mri 'meshdata' g.meshdata 'axistight' g.axistight }; figure('position', [ 100 600 600 200 ]); axes('position', [-0.1 -0.1 1.2 1.2], 'color', 'k'); axis off; blackimg = zeros(10,10,3); image(blackimg); axes('position', [0 0 1/3 1], 'tag', 'rear'); dipplot(sourcesori, options{:}, 'holdon', 'on'); view([0 -1 0]); axes('position', [1/3 0 1/3 1], 'tag', 'top' ); dipplot(sourcesori, options{:}, 'holdon', 'on'); view([0 0 1]); axes('position', [2/3 0 1/3 1], 'tag', 'side'); dipplot(sourcesori, options{:}, 'holdon', 'on'); view([1 -0.01 0]); set(gcf, 'paperpositionmode', 'auto'); return; end; % plot head graph in 3D % --------------------- if strcmp(g.gui, 'on') fig = figure('visible', g.plot); pos = get(gca, 'position'); set(gca, 'position', [pos(1)+0.05 pos(2:end)]); end; indx = ceil(dat.imgcoords{1}(end)/2); indy = ceil(dat.imgcoords{2}(end)/2); indz = ceil(dat.imgcoords{3}(end)/2); if strcmpi(g.holdon, 'off') plotimgs( dat, [indx indy indz], dat.transform); set(gca, 'color', BACKCOLOR); %warning off; a = imread('besaside.pcx'); warning on; % BECAUSE OF A BUG IN THE WARP FUNCTION, THIS DOES NOT WORK (11/02) %hold on; warp([], wy, wz, a); % set camera target % ----------------- % format axis (BESA or MRI) axis equal; set(gca, 'cameraviewanglemode', 'manual'); % disable change size camzoom(1.2^2); if strcmpi(g.coordformat, 'CTF'), g.view(2:3) = -g.view(2:3); end; view(g.view); %set(gca, 'cameratarget', dat.zeroloc); % disable change size %set(gca, 'cameraposition', dat.zeroloc+g.view*g.zoom); % disable change size axis off; end; % plot sphere mesh and nose % ------------------------- if strcmpi(g.holdon, 'off') if isempty(g.meshdata) SPHEREGRAIN = 20; % 20 is also Matlab default [x y z] = sphere(SPHEREGRAIN); hold on; [xx yy zz] = transform(x*0.085, y*0.085, z*0.085, dat.sph2spm); [xx yy zz] = transform(x*85 , y*85 , z*85 , dat.sph2spm); %xx = x*100; %yy = y*100; %zz = z*100; if strcmpi(COLORMESH, 'w') hh = mesh(xx, yy, zz, 'cdata', ones(21,21,3), 'tag', 'mesh'); hidden off; else hh = mesh(xx, yy, zz, 'cdata', zeros(21,21,3), 'tag', 'mesh'); hidden off; end; else try, if isstr(g.meshdata) tmp = load('-mat', g.meshdata); g.meshdata = { 'vertices' tmp.vol.bnd(1).pnt 'faces' tmp.vol.bnd(1).tri }; end; hh = patch(g.meshdata{:}, 'facecolor', 'none', 'edgecolor', COLORMESH, 'tag', 'mesh'); catch, disp('Unrecognize model file (probably CTF)'); end; end; end; %x = x*100*scaling; y = y*100*scaling; z=z*100*scaling; %h = line(xx,yy,zz); set(h, 'color', COLORMESH, 'linestyle', '--', 'tag', 'mesh'); %h = line(xx,zz,yy); set(h, 'color', COLORMESH, 'linestyle', '--', 'tag', 'mesh'); %h = line([0 0;0 0],[-1 -1.2; -1.2 -1], [-0.3 -0.7; -0.7 -0.7]); %set(h, 'color', COLORMESH, 'linewidth', 3, 'tag', 'noze'); % determine max length if besatextori exist % ----------------------------------------- sizedip = []; for index = 1:length(sources) sizedip = [ sizedip sources(index).momxyz(3) ]; end; maxlength = max(sizedip); % diph = gca; % DEBUG % colormap('jet'); % cbar % axes(diph); for index = 1:length(sources) nbdip = 1; if size(sources(index).posxyz, 1) > 1 & any(sources(index).posxyz(2,:)) nbdip = 2; end; % reorder dipoles for plotting if nbdip == 2 if sources(index).posxyz(1,1) > sources(index).posxyz(2,1) tmp = sources(index).posxyz(2,:); sources(index).posxyz(2,:) = sources(index).posxyz(1,:); sources(index).posxyz(1,:) = tmp; tmp = sources(index).momxyz(2,:); sources(index).momxyz(2,:) = sources(index).momxyz(1,:); sources(index).momxyz(1,:) = tmp; end; if isfield(sources, 'active'), nbdip = length(sources(index).active); end; end; % dipole length % ------------- multfactor = 1; if strcmpi(g.normlen, 'on') if nbdip == 1 len = sqrt(sum(sources(index).momxyz(1,:).^2)); else len1 = sqrt(sum(sources(index).momxyz(1,:).^2)); len2 = sqrt(sum(sources(index).momxyz(2,:).^2)); len = mean([len1 len2]); end; if strcmpi(g.coordformat, 'CTF'), len = len*10; end; if len ~= 0, multfactor = 15/len; end; else if strcmpi(g.coordformat, 'spherical') multfactor = 100; else multfactor = 1.5; end; end; for dip = 1:nbdip x = sources(index).posxyz(dip,1); y = sources(index).posxyz(dip,2); z = sources(index).posxyz(dip,3); xo = sources(index).momxyz(dip,1)*g.dipolelength*multfactor; yo = sources(index).momxyz(dip,2)*g.dipolelength*multfactor; zo = sources(index).momxyz(dip,3)*g.dipolelength*multfactor; xc = 0; yc = 0; zc = 0; centvec = [xo-xc yo-yc zo-zc]; % vector pointing into center dipole_orient = [x+xo y+yo z+zo]/norm([x+xo y+yo z+zo]); c = dot(centvec, dipole_orient); if strcmpi(g.pointout,'on') if (c < 0) | (abs([x+xo,y+yo,z+zo]) < abs([x,y,z])) xo1 = x-xo; % make dipole point outward from head center yo1 = y-yo; zo1 = z-zo; %fprintf('invert because: %e \n', c); else xo1 = x+xo; yo1 = y+yo; zo1 = z+zo; %fprintf('NO invert because: %e \n', c); end else xo1 = x+xo; yo1 = y+yo; zo1 = z+zo; %fprintf('NO invert because: %e \n', c); end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw dipole bar %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % tag = [ 'dipole' num2str(index) ]; % from spherical to electrode space % --------------------------------- [xx yy zz] = transform(x, y, z, dat.sph2spm); % nothing happens for BEM [xxo1 yyo1 zzo1] = transform(xo1, yo1, zo1, dat.sph2spm); % because dat.sph2spm = [] if ~strcmpi(g.spheres,'on') % plot dipole direction lines h1 = line( [xx xxo1]', [yy yyo1]', [zz zzo1]'); elseif g.dipolelength>0 % plot dipole direction cylinders with end cap patch [xc yc zc] = cylinder( 2, 10); [xs ys zs] = sphere(10); xc = [ xc; -xs(7:11,:)*2 ]; yc = [ yc; -ys(7:11,:)*2 ]; zc = [ zc; zs(7:11,:)/5+1 ]; colorarray = repmat(reshape(g.color{index}, 1,1,3), [size(zc,1) size(zc,2) 1]); handles = surf(xc, yc, zc, colorarray, 'tag', tag, 'edgecolor', 'none', ... 'backfacelighting', 'lit', 'facecolor', 'interp', 'facelighting', ... 'phong', 'ambientstrength', 0.3); [xc yc zc] = adjustcylinder2( handles, [xx yy zz], [xxo1 yyo1 zzo1] ); cx = mean(xc,2); %cx = [(3*cx(1)+cx(2))/4; (cx(1)+3*cx(2))/4]; cy = mean(yc,2); %cy = [(3*cy(1)+cy(2))/4; (cy(1)+3*cy(2))/4]; cz = mean(zc,2); %cz = [(3*cz(1)+cz(2))/4; (cz(1)+3*cz(2))/4]; tmpx = xc - repmat(cx, [1 size(xc, 2)]); tmpy = yc - repmat(cy, [1 size(xc, 2)]); tmpz = zc - repmat(cz, [1 size(xc, 2)]); l=sqrt(tmpx.^2+tmpy.^2+tmpz.^2); warning('off', 'MATLAB:divideByZero'); % this is due to a Matlab 2008b (or later) normals = reshape([tmpx./l tmpy./l tmpz./l],[size(tmpx) 3]); % in the rotate function in adjustcylinder2 warning('off', 'MATLAB:divideByZero'); % one of the z (the last row is not rotated) set( handles, 'vertexnormals', normals); end [xxmri yymri zzmri ] = transform(xx, yy, zz, pinv(dat.transform)); [xxmrio1 yymrio1 zzmrio1] = transform(xxo1, yyo1, zzo1, pinv(dat.transform)); dipstruct.mricoord = [xxmri yymri zzmri]; % Coordinates in MRI space dipstruct.eleccoord = [ xx yy zz ]; % Coordinates in elec space dipstruct.posxyz = sources(index).posxyz; % Coordinates in spherical space outsources(index).eleccoord(dip,:) = [xx yy zz]; outsources(index).mnicoord(dip,:) = [xx yy zz]; outsources(index).mricoord(dip,:) = [xxmri yymri zzmri]; outsources(index).talcoord(dip,:) = mni2tal([xx yy zz]')'; dipstruct.talcoord = mni2tal([xx yy zz]')'; % copy for output % --------------- XX(index) = xxmri; YY(index) = yymri; ZZ(index) = zzmri; XO(index) = xxmrio1; YO(index) = yymrio1; ZO(index) = zzmrio1; if isempty(g.dipnames) dipstruct.rv = sprintf('%3.2f', sources(index).rv*100); dipstruct.name = sources(index).component; else dipstruct.rv = sprintf('%3.2f', sources(index).rv*100); dipstruct.name = g.dipnames{index}; end; if ~strcmpi(g.spheres,'on') % plot disk markers set(h1,'userdata',dipstruct,'tag',tag,'color','k','linewidth',g.dipolesize(index)/7.5); if strcmp(BACKCOLOR, 'k'), set(h1, 'color', g.color{index}); end; end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw sphere or disk marker %%%%%%%%%%%%%%%%%%%%%%%%% % hold on; if strcmpi(g.spheres,'on') % plot spheres if strcmpi(g.projimg, 'on') if strcmpi(g.verbose, 'on'), disp('Warning: projections cannot be plotted for 3-D sphere'); end %tmpcolor = g.color{index} / 2; %h = plotsphere([xx yy zz], g.dipolesize/6, 'color', g.color{index}, 'proj', ... % [dat.imgcoords{1}(1) dat.imgcoords{2}(end) dat.imgcoords{3}(1)]*97/100, 'projcol', tmpcolor); %set(h(2:end), 'userdata', 'proj', 'tag', tag); else %h = plotsphere([xx yy zz], g.dipolesize/6, 'color', g.color{index}); end; h = plotsphere([xx yy zz], g.dipolesize(index)/6, 'color', g.color{index}); set(h(1), 'userdata', dipstruct, 'tag', tag); else % plot dipole markers h = plot3(xx, yy, zz); set(h, 'userdata', dipstruct, 'tag', tag, ... 'marker', '.', 'markersize', g.dipolesize(index), 'color', g.color{index}); end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% project onto images %%%%%%%%%%%%%%%%%%%%%%%%% % [tmp1xx tmp1yy tmp1zz ] = transform( xxmri , yymri , dat.imgcoords{3}(1), dat.transform); [tmp1xxo1 tmp1yyo1 tmp1zzo1] = transform( xxmrio1, yymrio1, dat.imgcoords{3}(1), dat.transform); [tmp2xx tmp2yy tmp2zz ] = transform( xxmri , dat.imgcoords{2}(end), zzmri , dat.transform); [tmp2xxo1 tmp2yyo1 tmp2zzo1] = transform( xxmrio1, dat.imgcoords{2}(end), zzmrio1, dat.transform); [tmp3xx tmp3yy tmp3zz ] = transform( dat.imgcoords{1}(1), yymri , zzmri , dat.transform); [tmp3xxo1 tmp3yyo1 tmp3zzo1] = transform( dat.imgcoords{1}(1), yymrio1, zzmrio1, dat.transform); if strcmpi(g.projimg, 'on') & strcmpi(g.spheres, 'off') tmpcolor = g.projcol{index}; % project onto z axis tag = [ 'dipole' num2str(index) ]; if ~strcmpi(g.image, 'besa') h = line( [tmp1xx tmp1xxo1]', [tmp1yy tmp1yyo1]', [tmp1zz tmp1zzo1]'); set(h, 'userdata', 'proj', 'tag', tag, 'color','k', 'linewidth', g.dipolesize(index)/7.5); end; if strcmp(BACKCOLOR, 'k'), set(h, 'color', tmpcolor); end; h = plot3(tmp1xx, tmp1yy, tmp1zz); set(h, 'userdata', 'proj', 'tag', tag, ... 'marker', '.', 'markersize', g.dipolesize(index), 'color', tmpcolor); % project onto y axis tag = [ 'dipole' num2str(index) ]; if ~strcmpi(g.image, 'besa') h = line( [tmp2xx tmp2xxo1]', [tmp2yy tmp2yyo1]', [tmp2zz tmp2zzo1]'); set(h, 'userdata', 'proj', 'tag', tag, 'color','k', 'linewidth', g.dipolesize(index)/7.5); end; if strcmp(BACKCOLOR, 'k'), set(h, 'color', tmpcolor); end; h = plot3(tmp2xx, tmp2yy, tmp2zz); set(h, 'userdata', 'proj', 'tag', tag, ... 'marker', '.', 'markersize', g.dipolesize(index), 'color', tmpcolor); % project onto x axis tag = [ 'dipole' num2str(index) ]; if ~strcmpi(g.image, 'besa') h = line( [tmp3xx tmp3xxo1]', [tmp3yy tmp3yyo1]', [tmp3zz tmp3zzo1]'); set(h, 'userdata', 'proj', 'tag', tag, 'color','k', 'linewidth', g.dipolesize(index)/7.5); end; if strcmp(BACKCOLOR, 'k'), set(h, 'color', tmpcolor); end; h = plot3(tmp3xx, tmp3yy, tmp3zz); set(h, 'userdata', 'proj', 'tag', tag, ... 'marker', '.', 'markersize', g.dipolesize(index), 'color', tmpcolor); end; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% project onto axes %%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(g.projlines, 'on') clear h; % project onto z axis tag = [ 'dipole' num2str(index) ]; h(1) = line( [xx tmp1xx]', [yy tmp1yy]', [zz tmp1zz]); set(h(1), 'userdata', 'proj', 'linestyle', '--', ... 'tag', tag, 'color', g.color{index}, 'linewidth', g.dipolesize(index)/7.5/5); % project onto x axis tag = [ 'dipole' num2str(index) ]; h(2) = line( [xx tmp2xx]', [yy tmp2yy]', [zz tmp2zz]); set(h(2), 'userdata', 'proj', 'linestyle', '--', ... 'tag', tag, 'color', g.color{index}, 'linewidth', g.dipolesize(index)/7.5/5); % project onto y axis tag = [ 'dipole' num2str(index) ]; h(3) = line( [xx tmp3xx]', [yy tmp3yy]', [zz tmp3zz]); set(h(3), 'userdata', 'proj', 'linestyle', '--', ... 'tag', tag, 'color', g.color{index}, 'linewidth', g.dipolesize(index)/7.5/5); if ~isempty(g.projcol) set(h, 'color', g.projcol{index}); end; end; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw text %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if isfield(sources, 'component') if strcmp(g.num, 'on') h = text(xx, yy, zz, [ ' ' int2str(sources(index).component)]); set(h, 'userdata', dipstruct, 'tag', tag, 'fontsize', g.dipolesize(index)/2 ); if ~strcmpi(g.image, 'besa'), set(h, 'color', 'w'); end; end; end; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 3-D settings if strcmpi(g.spheres, 'on') lighting phong; material shiny; camlight left; camlight right; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw elipse for group of dipoles %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % does not work because of new scheme, have to be reprogrammed %if ~isempty(g.std) % for index = 1:length(g.std) % if ~iscell(g.std{index}) % plotellipse(sources, g.std{index}, 1, dat.tcparams, dat.coreg); % else % sc = plotellipse(sources, g.std{index}{1}, g.std{index}{2}, dat.tcparams, dat.coreg); % if length( g.std{index} ) > 2 % set(sc, g.std{index}{3:end}); % end; % end; % end; % end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% buttons %%%%%%%%%%%%%%%%%%%%%%%%%%%%% nbsrc = int2str(length(sources)); cbmesh = [ 'if get(gcbo, ''userdata''), ' ... ' set(findobj(''parent'', gca, ''tag'', ''mesh''), ''visible'', ''off'');' ... ' set(gcbo, ''string'', ''Mesh on'');' ... ' set(gcbo, ''userdata'', 0);' ... 'else,' ... ' set(findobj(''parent'', gca, ''tag'', ''mesh''), ''visible'', ''on'');' ... ' set(gcbo, ''string'', ''Mesh off'');' ... ' set(gcbo, ''userdata'', 1);' ... 'end;' ]; cbplot = [ 'if strcmpi(get(gcbo, ''string''), ''plot one''),' ... ' for tmpi = 1:' nbsrc ',' ... ' set(findobj(''parent'', gca, ''tag'', [ ''dipole'' int2str(tmpi) ]), ''visible'', ''off'');' ... ' end; clear tmpi;' ... ' dipplot(gcbf);' ... ' set(gcbo, ''string'', ''Plot all'');' ... 'else,' ... ' for tmpi = 1:' nbsrc ',' ... ' set(findobj(''parent'', gca, ''tag'', [ ''dipole'' int2str(tmpi) ]), ''visible'', ''on'');' ... ' end; clear tmpi;' ... ' set(gcbo, ''string'', ''Plot one'');' ... 'end;' ]; cbview = [ 'tmpuserdat = get(gca, ''userdata'');' ... 'if tmpuserdat.axistight, ' ... ' set(gcbo, ''string'', ''Tight view'');' ... 'else,' ... ' set(gcbo, ''string'', ''Loose view'');' ... 'end;' ... 'tmpuserdat.axistight = ~tmpuserdat.axistight;' ... 'set(gca, ''userdata'', tmpuserdat);' ... 'clear tmpuserdat;' ... 'dipplot(gcbf);' ]; viewstring = fastif(dat.axistight, 'Loose view', 'Tight view'); enmesh = fastif(isempty(g.meshdata) & strcmpi(g.coordformat, 'MNI'), 'off', 'on'); if strcmpi(g.coordformat, 'CTF'), viewcor = 'view([0 1 0]);'; viewtop = 'view([0 0 -1]);'; vis = 'off'; else viewcor = 'view([0 -1 0]);'; viewtop = 'view([0 0 1]);'; vis = 'on'; end; h = uicontrol( 'unit', 'normalized', 'position', [0 0 .15 1], 'tag', 'tmp', ... 'style', 'text', 'string',' '); h = uicontrol( 'unit', 'normalized', 'position', [0 0 .15 .05], 'tag', 'tmp', ... 'style', 'pushbutton', 'fontweight', 'bold', 'string', 'No controls', 'callback', ... 'set(findobj(''parent'', gcbf, ''tag'', ''tmp''), ''visible'', ''off'');'); h = uicontrol( 'unit', 'normalized', 'position', [0 0.05 .15 .05], 'tag', 'tmp', ... 'style', 'pushbutton', 'string', 'Top view', 'callback', viewtop); h = uicontrol( 'unit', 'normalized', 'position', [0 0.1 .15 .05], 'tag', 'tmp', ... 'style', 'pushbutton', 'string', 'Coronal view', 'callback', viewcor); h = uicontrol( 'unit', 'normalized', 'position', [0 0.15 .15 .05], 'tag', 'tmp', ... 'style', 'pushbutton', 'string', 'Sagittal view', 'callback', 'view([1 0 0]);'); h = uicontrol( 'unit', 'normalized', 'position', [0 0.2 .15 .05], 'tag', 'tmp', ... 'style', 'pushbutton', 'string', viewstring, 'callback', cbview); h = uicontrol( 'unit', 'normalized', 'position', [0 0.25 .15 .05], 'tag', 'tmp', ... 'style', 'pushbutton', 'string', 'Mesh on', 'userdata', 0, 'callback', ... cbmesh, 'enable', enmesh, 'visible', vis ); h = uicontrol( 'unit', 'normalized', 'position', [0 0.3 .15 .05], 'tag', 'tmp', ... 'style', 'text', 'string', 'Display:','fontweight', 'bold' ); h = uicontrol( 'unit', 'normalized', 'position', [0 0.35 .15 .02], 'tag', 'tmp',... 'style', 'text', 'string', ''); h = uicontrol( 'unit', 'normalized', 'position', [0 0.37 .15 .05], 'tag', 'tmp','userdata', 'z',... 'style', 'text', 'string', 'Z:', 'visible', vis ); h = uicontrol( 'unit', 'normalized', 'position', [0 0.42 .15 .05], 'tag', 'tmp','userdata', 'y', ... 'style', 'text', 'string', 'Y:', 'visible', vis ); h = uicontrol( 'unit', 'normalized', 'position', [0 0.47 .15 .05], 'tag', 'tmp', 'userdata', 'x',... 'style', 'text', 'string', 'X:', 'visible', vis ); h = uicontrol( 'unit', 'normalized', 'position', [0 0.52 .15 .05], 'tag', 'tmp', 'userdata', 'rv',... 'style', 'text', 'string', 'RV:' ); h = uicontrol( 'unit', 'normalized', 'position', [0 0.57 .15 .05], 'tag', 'tmp', 'userdata', 'comp', ... 'style', 'text', 'string', ''); h = uicontrol( 'unit', 'normalized', 'position', [0 0.62 .15 .05], 'tag', 'tmp', 'userdata', 'editor', ... 'style', 'edit', 'string', '1', 'callback', ... [ 'dipplot(gcbf);' ] ); h = uicontrol( 'unit', 'normalized', 'position', [0 0.67 .15 .05], 'tag', 'tmp', ... 'style', 'pushbutton', 'string', 'Keep|Prev', 'callback', ... [ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ... 'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))-1));' ... 'tmpobj = get(gcf, ''userdata'');' ... 'eval(get(editobj, ''callback''));' ... 'set(tmpobj, ''visible'', ''on'');' ... 'clear editobj tmpobj;' ]); h = uicontrol( 'unit', 'normalized', 'position', [0 0.72 .15 .05], 'tag', 'tmp', ... 'style', 'pushbutton', 'string', 'Prev', 'callback', ... [ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ... 'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))-1));' ... 'eval(get(editobj, ''callback''));' ... 'clear editobj;' ]); h = uicontrol( 'unit', 'normalized', 'position', [0 0.77 .15 .05], 'tag', 'tmp', ... 'style', 'pushbutton', 'string', 'Next', 'callback', ... [ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ... 'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))+1));' ... 'dipplot(gcbf);' ... 'clear editobj;' ]); h = uicontrol( 'unit', 'normalized', 'position', [0 0.82 .15 .05], 'tag', 'tmp', ... 'style', 'pushbutton', 'string', 'Keep|Next', 'callback', ... [ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ... 'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))+1));' ... 'tmpobj = get(gcf, ''userdata'');' ... 'dipplot(gcbf);' ... 'set(tmpobj, ''visible'', ''on'');' ... 'clear editobj tmpobj;' ]); h = uicontrol( 'unit', 'normalized', 'position', [0 0.87 .15 .05], 'tag', 'tmp', ... 'style', 'pushbutton', 'string', 'Plot one', 'callback', cbplot); h = uicontrol( 'unit', 'normalized', 'position', [0 0.92 .15 .05], 'tag', 'tmp', ... 'style', 'text', 'string', [num2str(length(sources)) ' dipoles:'], 'fontweight', 'bold' ); h = uicontrol( 'unit', 'normalized', 'position', [0 0.97 .15 .05], 'tag', 'tmp', ... 'style', 'text', 'string', ''); set(gcf, 'userdata', findobj('parent', gca, 'tag', 'dipole1')); dat.nbsources = length(sources); set(gca, 'userdata', dat ); % last param=1 for MRI view tight/loose set(gcf, 'color', BACKCOLOR); if strcmp(g.gui, 'off') | strcmpi(g.holdon, 'on') set(findobj('parent', gcf, 'tag', 'tmp'), 'visible', 'off'); end; if strcmp(g.mesh, 'off') set(findobj('parent', gca, 'tag', 'mesh'), 'visible', 'off'); end; updatedipplot(gcf); rotate3d on; % close figure if necessary if strcmpi(g.plot, 'off') try, close(fig); catch, end; end; if strcmpi(g.holdon, 'on') box off; axis equal; axis off; end; % set camera positon if strcmpi(g.camera, 'set') set(gca, 'CameraPosition', [2546.94 -894.981 689.613], ... 'CameraPositionMode', 'manual', ... 'CameraTarget', [0 -18 18], ... 'CameraTargetMode', 'manual', ... 'CameraUpVector', [0 0 1], ... 'CameraUpVectorMode', 'manual', ... 'CameraViewAngle', [3.8815], ... 'CameraViewAngleMode', 'manual'); end; return; % electrode space to MRI space % ============================ function [x,y,z] = transform(x, y, z, transmat); if isempty(transmat), return; end; for i = 1:size(x,1) for j = 1:size(x,2) tmparray = transmat * [ x(i,j) y(i,j) z(i,j) 1 ]'; x(i,j) = tmparray(1); y(i,j) = tmparray(2); z(i,j) = tmparray(3); end; end; % does not work any more % ---------------------- function sc = plotellipse(sources, ind, nstd, TCPARAMS, coreg); for i = 1:length(ind) tmpval(1,i) = -sources(ind(i)).posxyz(1); tmpval(2,i) = -sources(ind(i)).posxyz(2); tmpval(3,i) = sources(ind(i)).posxyz(3); [tmpval(1,i) tmpval(2,i) tmpval(3,i)] = transform(tmpval(1,i), tmpval(2,i), tmpval(3,i), TCPARAMS); end; % mean and covariance C = cov(tmpval'); M = mean(tmpval,2); [U,L] = eig(C); % For N standard deviations spread of data, the radii of the eliipsoid will % be given by N*SQRT(eigenvalues). radii = nstd*sqrt(diag(L)); % generate data for "unrotated" ellipsoid [xc,yc,zc] = ellipsoid(0,0,0,radii(1),radii(2),radii(3), 10); % rotate data with orientation matrix U and center M a = kron(U(:,1),xc); b = kron(U(:,2),yc); c = kron(U(:,3),zc); data = a+b+c; n = size(data,2); x = data(1:n,:)+M(1); y = data(n+1:2*n,:)+M(2); z = data(2*n+1:end,:)+M(3); % now plot the rotated ellipse c = ones(size(z)); sc = mesh(x,y,z); alpha(0.5) function newsrc = convertbesaoldformat(src); newsrc = []; count = 1; countdip = 1; if ~isfield(src, 'besaextori'), src(1).besaextori = []; end; for index = 1:length(src) % convert format % -------------- if isempty(src(index).besaextori), src(index).besaextori = 300; end; % 20 mm newsrc(count).possph(countdip,:) = [ src(index).besathloc src(index).besaphloc src(index).besaexent]; newsrc(count).momsph(countdip,:) = [ src(index).besathori src(index).besaphori src(index).besaextori/300]; % copy other fields % ----------------- if isfield(src, 'stdX') newsrc(count).stdX = -src(index).stdY; newsrc(count).stdY = src(index).stdX; newsrc(count).stdZ = src(index).stdZ; end; if isfield(src, 'rv') newsrc(count).rv = src(index).rv; end; if isfield(src, 'elecrv') newsrc(count).rvelec = src(index).elecrv; end; if isfield(src, 'component') newsrc(count).component = src(index).component; if index ~= length(src) & src(index).component == src(index+1).component countdip = countdip + 1; else count = count + 1; countdip = 1; end; else count = count + 1; countdip = 1; end; end; function src = computexyzforbesa(src); for index = 1:length( src ) for index2 = 1:size( src(index).possph, 1 ) % compute coordinates % ------------------- postmp = src(index).possph(index2,:); momtmp = src(index).momsph(index2,:); phi = postmp(1)+90; %% %%%%%%%%%%%%%%% USE BESA COORDINATES %%%%% theta = postmp(2); %% %%%%%%%%%%%%%%% USE BESA COORDINATES %%%%% phiori = momtmp(1)+90; %% %%%%%%%%%%%% USE BESA COORDINATES %%%%% thetaori = momtmp(2); %% %%%%%%%%%%%% USE BESA COORDINATES %%%%% % exentricities are in % of the radius of the head sphere [x y z] = sph2cart(theta/180*pi, phi/180*pi, postmp(3)/1.2); [xo yo zo] = sph2cart(thetaori/180*pi, phiori/180*pi, momtmp(3)*5); % exentricity scaled for compatibility with DIPFIT src(index).posxyz(index2,:) = [-y x z]; src(index).momxyz(index2,:) = [-yo xo zo]; end; end; % update dipplot (callback call) % ------------------------------ function updatedipplot(fig) % find current dipole index and test for authorized range % ------------------------------------------------------- dat = get(gca, 'userdata'); editobj = findobj('parent', fig, 'userdata', 'editor'); tmpnum = str2num(get(editobj(end), 'string')); if tmpnum < 1, tmpnum = 1; end; if tmpnum > dat.nbsources, tmpnum = dat.nbsources; end; set(editobj(end), 'string', num2str(tmpnum)); % hide current dipole, find next dipole and show it % ------------------------------------------------- set(get(gcf, 'userdata'), 'visible', 'off'); newdip = findobj('parent', gca, 'tag', [ 'dipole' get(editobj(end), 'string')]); set(newdip, 'visible', 'on'); set(gcf, 'userdata', newdip); % find all dipolar structures % --------------------------- index = 1; count = 1; for index = 1:length(newdip) if isstruct( get(newdip(index), 'userdata') ) dip_mricoord(count,:) = getfield(get(newdip(index), 'userdata'), 'mricoord'); count = count+1; foundind = index; end; end; % get residual variance % --------------------- if exist('foundind') tmp = get(newdip(foundind), 'userdata'); tal = tmp.talcoord; if ~isstr( tmp.name ) tmprvobj = findobj('parent', fig, 'userdata', 'comp'); set( tmprvobj(end), 'string', [ 'Comp: ' int2str(tmp.name) ] ); else tmprvobj = findobj('parent', fig, 'userdata', 'comp'); set( tmprvobj(end), 'string', tmp.name ); end; tmprvobj = findobj('parent', fig, 'userdata', 'rv'); set( tmprvobj(end), 'string', [ 'RV: ' tmp.rv '%' ] ); tmprvobj = findobj('parent', fig, 'userdata', 'x'); set( tmprvobj(end), 'string', [ 'X tal: ' int2str(round(tal(1))) ]); tmprvobj = findobj('parent', fig, 'userdata', 'y'); set( tmprvobj(end), 'string', [ 'Y tal: ' int2str(round(tal(2))) ]); tmprvobj = findobj('parent', fig, 'userdata', 'z'); set( tmprvobj(end), 'string', [ 'Z tal: ' int2str(round(tal(3))) ]); end % adapt the MRI to the dipole depth % --------------------------------- delete(findobj('parent', gca, 'tag', 'img')); tmpdiv1 = dat.imgcoords{1}(2)-dat.imgcoords{1}(1); tmpdiv2 = dat.imgcoords{2}(2)-dat.imgcoords{2}(1); tmpdiv3 = dat.imgcoords{3}(2)-dat.imgcoords{3}(1); if ~dat.axistight [xx yy zz] = transform(0,0,0, pinv(dat.transform)); % elec -> MRI space indx = minpos(dat.imgcoords{1}-zz); indy = minpos(dat.imgcoords{2}-yy); indz = minpos(dat.imgcoords{3}-xx); else if ~dat.cornermri indx = minpos(dat.imgcoords{1} - mean(dip_mricoord(:,1))) - 3*tmpdiv1; indy = minpos(dat.imgcoords{2} - mean(dip_mricoord(:,2))) + 3*tmpdiv2; indz = minpos(dat.imgcoords{3} - mean(dip_mricoord(:,3))) - 3*tmpdiv3; else % no need to shift slice if not ploted close to the dipole indx = minpos(dat.imgcoords{1} - mean(dip_mricoord(:,1))); indy = minpos(dat.imgcoords{2} - mean(dip_mricoord(:,2))); indz = minpos(dat.imgcoords{3} - mean(dip_mricoord(:,3))); end; end; % middle of the brain % ------------------- plotimgs( dat,min(max([indx indy indz],1),size(dat.imgs)), dat.transform); %end; % plot images (transmat is the uniform matrix MRI coords -> elec coords) % ---------------------------------------------------------------------- function plotimgs(dat, mricoord, transmat); % loading images % -------------- if ndims(dat.imgs) == 4 % true color data img1(:,:,3) = rot90(squeeze(dat.imgs(mricoord(1),:,:,3))); img2(:,:,3) = rot90(squeeze(dat.imgs(:,mricoord(2),:,3))); img3(:,:,3) = rot90(squeeze(dat.imgs(:,:,mricoord(3),3))); img1(:,:,2) = rot90(squeeze(dat.imgs(mricoord(1),:,:,2))); img2(:,:,2) = rot90(squeeze(dat.imgs(:,mricoord(2),:,2))); img3(:,:,2) = rot90(squeeze(dat.imgs(:,:,mricoord(3),2))); img1(:,:,1) = rot90(squeeze(dat.imgs(mricoord(1),:,:,1))); img2(:,:,1) = rot90(squeeze(dat.imgs(:,mricoord(2),:,1))); img3(:,:,1) = rot90(squeeze(dat.imgs(:,:,mricoord(3),1))); else img1 = rot90(squeeze(dat.imgs(mricoord(1),:,:))); img2 = rot90(squeeze(dat.imgs(:,mricoord(2),:))); img3 = rot90(squeeze(dat.imgs(:,:,mricoord(3)))); if ndims(img1) == 2, img1(:,:,3) = img1; img1(:,:,2) = img1(:,:,1); end; if ndims(img2) == 2, img2(:,:,3) = img2; img2(:,:,2) = img2(:,:,1); end; if ndims(img3) == 2, img3(:,:,3) = img3; img3(:,:,2) = img3(:,:,1); end; end; % computing coordinates for planes % -------------------------------- wy1 = [min(dat.imgcoords{2}) max(dat.imgcoords{2}); min(dat.imgcoords{2}) max(dat.imgcoords{2})]; wz1 = [min(dat.imgcoords{3}) min(dat.imgcoords{3}); max(dat.imgcoords{3}) max(dat.imgcoords{3})]; wx2 = [min(dat.imgcoords{1}) max(dat.imgcoords{1}); min(dat.imgcoords{1}) max(dat.imgcoords{1})]; wz2 = [min(dat.imgcoords{3}) min(dat.imgcoords{3}); max(dat.imgcoords{3}) max(dat.imgcoords{3})]; wx3 = [min(dat.imgcoords{1}) max(dat.imgcoords{1}); min(dat.imgcoords{1}) max(dat.imgcoords{1})]; wy3 = [min(dat.imgcoords{2}) min(dat.imgcoords{2}); max(dat.imgcoords{2}) max(dat.imgcoords{2})]; if dat.axistight & ~dat.cornermri wx1 = [ 1 1; 1 1]*dat.imgcoords{1}(mricoord(1)); wy2 = [ 1 1; 1 1]*dat.imgcoords{2}(mricoord(2)); wz3 = [ 1 1; 1 1]*dat.imgcoords{3}(mricoord(3)); else wx1 = [ 1 1; 1 1]*dat.imgcoords{1}(1); wy2 = [ 1 1; 1 1]*dat.imgcoords{2}(end); wz3 = [ 1 1; 1 1]*dat.imgcoords{3}(1); end; % transform MRI coordinates to electrode space % -------------------------------------------- [ elecwx1 elecwy1 elecwz1 ] = transform( wx1, wy1, wz1, transmat); [ elecwx2 elecwy2 elecwz2 ] = transform( wx2, wy2, wz2, transmat); [ elecwx3 elecwy3 elecwz3 ] = transform( wx3, wy3, wz3, transmat); % ploting surfaces % ---------------- options = { 'FaceColor','texturemap', 'EdgeColor','none', 'CDataMapping', ... 'direct','tag','img', 'facelighting', 'none' }; hold on; surface(elecwx1, elecwy1, elecwz1, img1(end:-1:1,:,:), options{:}); surface(elecwx2, elecwy2, elecwz2, img2(end:-1:1,:,:), options{:}); surface(elecwx3, elecwy3, elecwz3, img3(end:-1:1,:,:), options{:}); %xlabel('x'); ylabel('y'); zlabel('z'); axis equal; dsaffd if strcmpi(dat.drawedges, 'on') % removing old edges if any delete(findobj( gcf, 'tag', 'edges')); if dat.axistight & ~dat.cornermri, col = 'k'; else col = [0.5 0.5 0.5]; end; h(1) = line([elecwx3(1) elecwx3(2)]', [elecwy3(1) elecwy2(1)]', [elecwz1(1) elecwz1(2)]'); % sagittal-transverse h(2) = line([elecwx3(1) elecwx2(3)]', [elecwy2(1) elecwy2(2)]', [elecwz1(1) elecwz1(2)]'); % coronal-tranverse h(3) = line([elecwx3(1) elecwx3(2)]', [elecwy2(1) elecwy2(2)]', [elecwz3(1) elecwz1(1)]'); % sagittal-coronal set(h, 'color', col, 'linewidth', 2, 'tag', 'edges'); end; %%fill3([-2 -2 2 2], [-2 2 2 -2], wz(:)-1, BACKCOLOR); %%fill3([-2 -2 2 2], wy(:)-1, [-2 2 2 -2], BACKCOLOR); rotate3d on function index = minpos(vals); vals(find(vals < 0)) = inf; [tmp index] = min(vals); function scalegca(multfactor) xl = xlim; xf = ( xl(2) - xl(1) ) * multfactor; yl = ylim; yf = ( yl(2) - yl(1) ) * multfactor; zl = zlim; zf = ( zl(2) - zl(1) ) * multfactor; xlim( [ xl(1)-xf xl(2)+xf ]); ylim( [ yl(1)-yf yl(2)+yf ]); zlim( [ zl(1)-zf zl(2)+zf ]); function color = strcol2real(colorin, colmap) if ~iscell(colorin) for index = 1:length(colorin) color{index} = colmap(colorin(index),:); end; else color = colorin; for index = 1:length(colorin) if isstr(colorin{index}) switch colorin{index} case 'r', color{index} = [1 0 0]; case 'g', color{index} = [0 1 0]; case 'b', color{index} = [0 0 1]; case 'c', color{index} = [0 1 1]; case 'm', color{index} = [1 0 1]; case 'y', color{index} = [1 1 0]; case 'k', color{index} = [0 0 0]; case 'w', color{index} = [1 1 1]; otherwise, error('Unknown color'); end; end; end; end; function x = gammacorrection(x, gammaval); x = 255 * (double(x)/255).^ gammaval; % image is supposed to be scaled from 0 to 255 % gammaval = 1 is identity of course
github
lcnbeapp/beapp-master
fieldtripchan2eeglab.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/fieldtripchan2eeglab.m
1,612
utf_8
0328813bbaaba65a3bcfde10ecb26e8b
% fieldtripchan2eeglab() - convert Fieldtrip channel location structure % to EEGLAB channel location structure % % Usage: % >> chanlocs = fieldtripchan2eeglab( fieldlocs ); % % Inputs: % fieldlocs - Fieldtrip channel structure. See help readlocs() % % Outputs: % chanlocs - EEGLAB channel location structure. % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2006- % % See also: readlocs() % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function chanlocs = fieldtripchan2eeglab( loc ); if nargin < 1 help fieldtripchan2eeglab; return; end; chanlocs = struct('labels', loc.label(:)', 'X', mattocell(loc.pnt(:,1)'), ... 'Y', mattocell(loc.pnt(:,2)'), ... 'Z', mattocell(loc.pnt(:,3)')); chanlocs = convertlocs(chanlocs, 'cart2all');
github
lcnbeapp/beapp-master
sph2spm.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/sph2spm.m
3,331
utf_8
67c8de53ef88fdbaa69eea504e17997b
% sph2spm() - compute homogenous transformation matrix from % BESA spherical coordinates to SPM 3-D coordinate % % Usage: % >> trans = sph2spm; % % Outputs: % trans - homogenous transformation matrix % % Note: head radius for spherical model is assumed to be 85 mm. % % Author: Robert Oostenveld, SMI/FCDC, Nijmegen 2005 % Arnaud Delorme, SCCN, La Jolla 2005 % SMI, University Aalborg, Denmark http://www.smi.auc.dk/ % FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl/ % Copyright (C) 2003 Robert Oostenveld, SMI/FCDC [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function besa2SPM_result = besa2SPM; if 0 % original transformation: problem occipital part of the haed did not % fit % NAS, Left EAR, Right EAR coordinates in BESA besa_NAS = [0.0000 0.0913 -0.0407]; besa_LPA = [-0.0865 0.0000 -0.0500]; besa_RPA = [0.0865 0.0000 -0.0500]; % NAS, Left EAR, Right EAR coordinates in SPM average SPM_NAS = [0 84 -48]; SPM_LPA = [-82 -32 -54]; SPM_RPA = [82 -32 -54]; % transformation to CTF coordinate system % --------------------------------------- SPM2common = headcoordinates(SPM_NAS , SPM_LPA , SPM_RPA, 0); besa2common = headcoordinates(besa_NAS, besa_LPA, besa_RPA, 0); nazcommon1 = besa2common * [ besa_NAS 1]'; nazcommon2 = SPM2common * [ SPM_NAS 1]'; ratiox = nazcommon1(1)/nazcommon2(1); lpacommon1 = besa2common * [ besa_LPA 1]'; lpacommon2 = SPM2common * [ SPM_LPA 1]'; ratioy = lpacommon1(2)/lpacommon2(2); scaling = eye(4); scaling(1,1) = 1/ratiox; scaling(2,2) = 1/ratioy; scaling(3,3) = mean([ 1/ratioy 1/ratiox]); besa2SPM_result = inv(SPM2common) * scaling * besa2common; end; if 0 % using electrodenormalize to fit standard BESA electrode (haed radius % has to be 85) to BEM electrodes % problem: fit not optimal for temporal electrodes % traditional takes as input the .m field returned in the output from % electrodenormalize besa2SPM_result = traditionaldipfit([0.5588 -14.5541 1.8045 0.0004 0.0000 -1.5623 1.1889 1.0736 132.6198]) end; % adapted manualy from above for temporal electrodes (see factor 0.94 % instead of 1.1889 and x shift of -18.0041 instead of -14.5541) %traditionaldipfit([0.5588 -18.0041 1.8045 0.0004 0.0000 -1.5623 1.1889 0.94 132.6198]) besa2SPM_result = [ 0.0101 -0.9400 0 0.5588 1.1889 0.0080 0.0530 -18.0041 -0.0005 -0.0000 1.1268 1.8045 0 0 0 1.0000 ];
github
lcnbeapp/beapp-master
homogenous2traditional.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/homogenous2traditional.m
5,576
utf_8
1cd0a7b795501f24b35360ecec62e420
function f = homogenous2traditional(H) % HOMOGENOUS2TRADITIONAL estimates the traditional translation, rotation % and scaling parameters from a homogenous transformation matrix. It will % give an error if the homogenous matrix also describes a perspective % transformation. % % Use as % f = homogenous2traditional(H) % where H is a 4x4 homogenous transformation matrix and f is a vector with % nine elements describing % x-shift % y-shift % z-shift % followed by the % pitch (rotation around x-axis) % roll (rotation around y-axis) % yaw (rotation around z-axis) % followed by the % x-rescaling factor % y-rescaling factor % z-rescaling factor % % The order in which the transformations would be done is exactly opposite % as the list above, i.e. first z-rescale ... and finally x-shift. % Copyright (C) 2005, Robert Oostenveld % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % remember the input homogenous transformation matrix Horg = H; % The homogenous transformation matrix is built up according to % H = T * R * S % where % R = Rx * Ry * Rz % estimate the translation tx = H(1,4); ty = H(2,4); tz = H(3,4); T = [ 1 0 0 tx 0 1 0 ty 0 0 1 tz 0 0 0 1 ]; % recompute the homogenous matrix excluding the translation H = inv(T) * H; % estimate the scaling sx = norm(H(1:3,1)); sy = norm(H(1:3,2)); sz = norm(H(1:3,3)); S = [ sx 0 0 0 0 sy 0 0 0 0 sz 0 0 0 0 1 ]; % recompute the homogenous matrix excluding the scaling H = H * inv(S); % the difficult part is to determine the rotations % the order of the rotations matters % compute the rotation using a probe point on the z-axis p = H * [0 0 1 0]'; % the rotation around the y-axis is resulting in an offset in the positive x-direction ry = asin(p(1)); % the rotation around the x-axis can be estimated by the projection on the yz-plane if abs(p(2))<eps && abs(p(2))<eps % the rotation around y was pi/2 or -pi/2, therefore I cannot estimate the rotation around x any more error('need another estimate, not implemented yet'); elseif abs(p(3))<eps % this is an unstable situation for using atan, but the rotation around x is either pi/2 or -pi/2 if p(2)<0 rx = pi/2 else rx = -pi/2; end else % this is the default equation for determining the rotation rx = -atan(p(2)/p(3)); end % recompute the individual rotation matrices Rx = rotate([rx 0 0]); Ry = rotate([0 ry 0]); Rz = inv(Ry) * inv(Rx) * H; % use left side multiplication % compute the remaining rotation using a probe point on the x-axis p = Rz * [1 0 0 0]'; rz = asin(p(2)); % the complete rotation matrix was R = rotate([rx ry rz]); % compare the original translation with the one that was estimated H = T * R * S; %fprintf('remaining difference\n'); %disp(Horg - H); f = [tx ty tz rx ry rz sx sy sz]; function [output] = rotate(R, input); % ROTATE performs a 3D rotation on the input coordinates % around the x, y and z-axis. The direction of the rotation % is according to the right-hand rule. The rotation is first % done around the x-, then the y- and finally the z-axis. % % Use as % [output] = rotate(R, input) % where % R [rx, ry, rz] rotations around each of the axes in degrees % input Nx3 matrix with the points before rotation % output Nx3 matrix with the points after rotation % % Or as % [Tr] = rotate(R) % where % R [rx, ry, rz] in degrees % Tr corresponding homogenous transformation matrix % Copyright (C) 2000-2004, Robert Oostenveld % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA rotx = eye(3); roty = eye(3); rotz = eye(3); rx = pi*R(1) / 180; ry = pi*R(2) / 180; rz = pi*R(3) / 180; if rx~=0 % rotation around x-axis rotx(2,:) = [ 0 cos(rx) -sin(rx) ]; rotx(3,:) = [ 0 sin(rx) cos(rx) ]; end if ry~=0 % rotation around y-axis roty(1,:) = [ cos(ry) 0 sin(ry) ]; roty(3,:) = [ -sin(ry) 0 cos(ry) ]; end if rz~=0 % rotation around z-axis rotz(1,:) = [ cos(rz) -sin(rz) 0 ]; rotz(2,:) = [ sin(rz) cos(rz) 0 ]; end if nargin==1 % compute and return the homogenous transformation matrix rotx(4,4) = 1; roty(4,4) = 1; rotz(4,4) = 1; output = rotz * roty * rotx; else % apply the transformation on the input points output = ((rotz * roty * rotx) * input')'; end
github
lcnbeapp/beapp-master
electroderealign.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/electroderealign.m
26,943
utf_8
c09b21089e582b6d28a1fc065011b317
function [norm] = electroderealign(cfg); % ELECTRODEREALIGN rotates and translates electrode positions to % template electrode positions or towards the head surface. It can % either perform a rigid body transformation, in which only the % coordinate system is changed, or it can apply additional deformations % to the input electrodes. % % Use as % [elec] = electroderealign(cfg) % % Three different methods for aligning the input electrodes are implemented: % based on a warping method, based on the fiducials or interactive with a % graphical user interface. Each of these approaches is described below. % % 1) You can apply a spatial deformation method (i.e. 'warp') that % automatically minimizes the distance between the electrodes and the % averaged standard. The warping methods use a non-linear search to % optimize the error between input and template electrodes or the % head surface. % % 2) You can apply a rigid body realignment based on three fiducial locations. % Realigning using the fiducials only ensures that the fiducials (typically % nose, left and right ear) are along the same axes in the input electrode % set as in the template electrode set. % % 3) You can display the electrode positions together with the skin surface, % and manually (using the graphical user interface) adjust the rotation, % translation and scaling parameters, so that the two match. % % The configuration can contain the following options % cfg.method = different methods for aligning the electrodes % 'rigidbody' apply a rigid-body warp % 'globalrescale' apply a rigid-body warp with global rescaling % 'traditional' apply a rigid-body warp with individual axes rescaling % 'nonlin1' apply a 1st order non-linear warp % 'nonlin2' apply a 2nd order non-linear warp % 'nonlin3' apply a 3rd order non-linear warp % 'nonlin4' apply a 4th order non-linear warp % 'nonlin5' apply a 5th order non-linear warp % 'realignfiducial' realign the fiducials % 'interactive' manually using graphical user interface % cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), % see CHANNELSELECTION for details % cfg.fiducial = cell-array with the name of three fiducials used for % realigning (default = {'nasion', 'lpa', 'rpa'}) % cfg.casesensitive = 'yes' or 'no', determines whether string comparisons % between electrode labels are case sensitive (default = 'yes') % cfg.feedback = 'yes' or 'no' (default = 'no') % % The electrode set that will be realigned is specified as % cfg.elecfile = string with filename, or alternatively % cfg.elec = structure with electrode definition % % If you want to align the electrodes to a single template electrode set % or to multiple electrode sets (which will be averaged), you should % specify the template electrode sets as % cfg.template = single electrode set that serves as standard % or % cfg.template{1..N} = list of electrode sets that are averaged into the standard % The template electrode sets can be specified either as electrode % structures (i.e. when they are already read in memory) or as electrode % files. % % If you want to align the electrodes to the head surface as obtained from % an anatomical MRI (using one of the warping methods), you should specify % the head surface % cfg.headshape = a filename containing headshape, a structure containing a % single triangulated boundary, or a Nx3 matrix with surface % points % % In case you only want to realign the fiducials, the template electrode % set only has to contain the three fiducials, e.g. % cfg.template.pnt(1,:) = [110 0 0] % location of the nose % cfg.template.pnt(2,:) = [0 90 0] % left ear % cfg.template.pnt(3,:) = [0 -90 0] % right ear % cfg.template.label = {''nasion', 'lpa', 'rpa'} % % See also READ_FCDC_ELEC, VOLUMEREALIGN % Copyright (C) 2005-2006, Robert Oostenveld % % $Log: electroderealign.m,v $ % Revision 1.1 2009/01/30 04:02:02 arno % *** empty log message *** % % Revision 1.6 2007/08/06 09:20:14 roboos % added support for bti_hs % % Revision 1.5 2007/07/26 08:00:09 roboos % also deal with cfg.headshape if specified as surface, set of points or ctf_hs file. % the construction of the tri is now done consistently for all headshapes if tri is missing % % Revision 1.4 2007/02/13 15:12:51 roboos % removed cfg.plot3d option % % Revision 1.3 2006/12/12 11:28:33 roboos % moved projecttri subfunction into seperate function % % Revision 1.2 2006/10/04 07:10:07 roboos % updated documentation % % Revision 1.1 2006/09/13 07:20:06 roboos % renamed electrodenormalize to electroderealign, added "deprecated"-warning to the old function % % Revision 1.10 2006/09/13 07:09:24 roboos % Implemented support for cfg.method=interactive, using GUI for specifying and showing transformations. Sofar only for electrodes+headsurface. % % Revision 1.9 2006/09/12 15:26:06 roboos % implemented support for aligning electrodes to the skin surface, extended and improved documentation % % Revision 1.8 2006/04/20 09:58:34 roboos % updated documentation % % Revision 1.7 2006/04/19 15:42:53 roboos % replaced call to warp_pnt with new function name warp_optim % % Revision 1.6 2006/03/14 08:16:00 roboos % changed function call to warp3d into warp_apply (thanks to Arno) % % Revision 1.5 2005/05/17 17:50:37 roboos % changed all "if" occurences of & and | into && and || % this makes the code more compatible with Octave and also seems to be in closer correspondence with Matlab documentation on shortcircuited evaluation of sequential boolean constructs % % Revision 1.4 2005/03/21 15:49:43 roboos % added cfg.casesensitive for string comparison of electrode labels % added cfg.feedback and cfg.plot3d option for debugging % changed output: now ALL electrodes of the input are rerurned, after applying the specified transformation % fixed small bug in feedback regarding distarnce prior/after realignfiducials) % added support for various warping strategies, a.o. traditional, rigidbody, nonlin1-5, etc. % % Revision 1.3 2005/03/16 09:18:56 roboos % fixed bug in fprintf feedback, instead of giving mean squared distance it should give mean distance before and after normalization % % Revision 1.2 2005/01/18 12:04:39 roboos % improved error handling of missing fiducials % added other default fiducials % changed debugging output % % Revision 1.1 2005/01/17 14:56:06 roboos % new implementation % % set the defaults if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end if ~isfield(cfg, 'feedback'), cfg.feedback = 'no'; end if ~isfield(cfg, 'casesensitive'), cfg.casesensitive = 'yes'; end if ~isfield(cfg, 'headshape'), cfg.headshape = []; end if ~isfield(cfg, 'template'), cfg.template = []; end % this is a common mistake which can be accepted if strcmp(cfg.method, 'realignfiducials') cfg.method = 'realignfiducial'; end if strcmp(cfg.method, 'warp') % rename the default warp to one of the method recognized by the warping toolbox cfg.method = 'traditional'; end if strcmp(cfg.feedback, 'yes') % use the global fb field to tell the warping toolbox to print feedback global fb fb = 1; else global fb fb = 0; end usetemplate = isfield(cfg, 'template') && ~isempty(cfg.template); useheadshape = isfield(cfg, 'headshape') && ~isempty(cfg.headshape); if usetemplate % get the template electrode definitions if ~iscell(cfg.template) cfg.template = {cfg.template}; end Ntemplate = length(cfg.template); for i=1:Ntemplate if isstruct(cfg.template{i}) template(i) = cfg.template{i}; else template(i) = read_fcdc_elec(cfg.template{i}); end end elseif useheadshape % get the surface describing the head shape if isstruct(cfg.headshape) && isfield(cfg.headshape, 'pnt') % use the headshape surface specified in the configuration headshape = cfg.headshape; elseif isnumeric(cfg.headshape) && size(cfg.headshape,2)==3 % use the headshape points specified in the configuration headshape.pnt = cfg.headshape; elseif ischar(cfg.headshape) && filetype(cfg.headshape, 'ctf_shape') % read the headshape from file headshape = read_ctf_shape(cfg.headshape); elseif ischar(cfg.headshape) && filetype(cfg.headshape, '4d_hs') % read the headshape from file headshape = []; headshape.pnt = read_bti_hs(cfg.headshape); else error('cfg.headshape is not specified correctly') end if ~isfield(headshape, 'tri') % generate a closed triangulation from the surface points headshape.tri = projecttri(headshape.pnt); end else error('you should either specify template electrode positions, template fiducials or a head shape'); end % get the electrode definition that should be warped if isfield(cfg, 'elec') elec = cfg.elec; else elec = read_fcdc_elec(cfg.elecfile); end % remember the original electrode locations and labels orig = elec; % convert all labels to lower case for string comparisons % this has to be done AFTER keeping the original labels and positions if strcmp(cfg.casesensitive, 'no') for i=1:length(elec.label) elec.label{i} = lower(elec.label{i}); end for j=1:length(template) for i=1:length(template(j).label) template(j).label{i} = lower(template(j).label{i}); end end end if strcmp(cfg.feedback, 'yes') % create an empty figure, continued below... figure axis equal axis vis3d hold on xlabel('x') ylabel('y') zlabel('z') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if usetemplate && any(strcmp(cfg.method, {'rigidbody', 'globalrescale', 'traditional', 'nonlin1', 'nonlin2', 'nonlin3', 'nonlin4', 'nonlin5'})) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % determine electrode selection and overlapping subset for warping cfg.channel = channelselection(cfg.channel, elec.label); for i=1:Ntemplate cfg.channel = channelselection(cfg.channel, template(i).label); end % make subselection of electrodes [cfgsel, datsel] = match_str(cfg.channel, elec.label); elec.label = elec.label(datsel); elec.pnt = elec.pnt(datsel,:); for i=1:Ntemplate [cfgsel, datsel] = match_str(cfg.channel, template(i).label); template(i).label = template(i).label(datsel); template(i).pnt = template(i).pnt(datsel,:); end % compute the average of the template electrode positions all = []; for i=1:Ntemplate all = cat(3, all, template(i).pnt); end avg = mean(all,3); stderr = std(all, [], 3); fprintf('warping electrodes to template... '); % the newline comes later [norm.pnt, norm.m] = warp_optim(elec.pnt, avg, cfg.method); norm.label = elec.label; dpre = mean(sqrt(sum((avg - elec.pnt).^2, 2))); dpost = mean(sqrt(sum((avg - norm.pnt).^2, 2))); fprintf('mean distance prior to warping %f, after warping %f\n', dpre, dpost); if strcmp(cfg.feedback, 'yes') % plot all electrodes before warping my_plot3(elec.pnt, 'r.'); my_plot3(elec.pnt(1,:), 'r*'); my_plot3(elec.pnt(2,:), 'r*'); my_plot3(elec.pnt(3,:), 'r*'); my_text3(elec.pnt(1,:), elec.label{1}, 'color', 'r'); my_text3(elec.pnt(2,:), elec.label{2}, 'color', 'r'); my_text3(elec.pnt(3,:), elec.label{3}, 'color', 'r'); % plot all electrodes after warping my_plot3(norm.pnt, 'm.'); my_plot3(norm.pnt(1,:), 'm*'); my_plot3(norm.pnt(2,:), 'm*'); my_plot3(norm.pnt(3,:), 'm*'); my_text3(norm.pnt(1,:), norm.label{1}, 'color', 'm'); my_text3(norm.pnt(2,:), norm.label{2}, 'color', 'm'); my_text3(norm.pnt(3,:), norm.label{3}, 'color', 'm'); % plot the template electrode locations my_plot3(avg, 'b.'); my_plot3(avg(1,:), 'b*'); my_plot3(avg(2,:), 'b*'); my_plot3(avg(3,:), 'b*'); my_text3(avg(1,:), norm.label{1}, 'color', 'b'); my_text3(avg(2,:), norm.label{2}, 'color', 'b'); my_text3(avg(3,:), norm.label{3}, 'color', 'b'); % plot lines connecting the input/warped electrode locations with the template locations my_line3(elec.pnt, avg, 'color', 'r'); my_line3(norm.pnt, avg, 'color', 'm'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif useheadshape && any(strcmp(cfg.method, {'rigidbody', 'globalrescale', 'traditional', 'nonlin1', 'nonlin2', 'nonlin3', 'nonlin4', 'nonlin5'})) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % determine electrode selection and overlapping subset for warping cfg.channel = channelselection(cfg.channel, elec.label); % make subselection of electrodes [cfgsel, datsel] = match_str(cfg.channel, elec.label); elec.label = elec.label(datsel); elec.pnt = elec.pnt(datsel,:); fprintf('warping electrodes to head shape... '); % the newline comes later [norm.pnt, norm.m] = warp_optim(elec.pnt, headshape, cfg.method); norm.label = elec.label; dpre = warp_error([], elec.pnt, headshape, cfg.method); dpost = warp_error(norm.m, elec.pnt, headshape, cfg.method); fprintf('mean distance prior to warping %f, after warping %f\n', dpre, dpost); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(cfg.method, 'realignfiducial') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % try to determine the fiducials automatically if not specified option1 = {'nasion' 'left' 'right'}; option2 = {'nasion' 'lpa' 'rpa'}; option3 = {'nz' 'lpa' 'rpa'}; if ~isfield(cfg, 'fiducial') if length(match_str(elec.label, option1))==3 cfg.fiducial = option1; elseif length(match_str(elec.label, option2))==3 cfg.fiducial = option2; elseif length(match_str(elec.label, option3))==3 cfg.fiducial = option3; else error('could not determine three fiducials, please specify cfg.fiducial') end end fprintf('using fiducials {''%s'', ''%s'', ''%s''}\n', cfg.fiducial{1}, cfg.fiducial{2}, cfg.fiducial{3}); % determine electrode selection cfg.channel = channelselection(cfg.channel, elec.label); [cfgsel, datsel] = match_str(cfg.channel, elec.label); elec.label = elec.label(datsel); elec.pnt = elec.pnt(datsel,:); if length(cfg.fiducial)~=3 error('you must specify three fiducials'); end % do case-insensitive search for fiducial locations nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1})); lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2})); rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3})); if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1 error('not all fiducials were found in the electrode set'); end elec_nas = elec.pnt(nas_indx,:); elec_lpa = elec.pnt(lpa_indx,:); elec_rpa = elec.pnt(rpa_indx,:); % find the matching fiducials in the template and average them templ_nas = []; templ_lpa = []; templ_rpa = []; for i=1:Ntemplate nas_indx = match_str(lower(template(i).label), lower(cfg.fiducial{1})); lpa_indx = match_str(lower(template(i).label), lower(cfg.fiducial{2})); rpa_indx = match_str(lower(template(i).label), lower(cfg.fiducial{3})); if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1 error(sprintf('not all fiducials were found in template %d', i)); end templ_nas(end+1,:) = template(i).pnt(nas_indx,:); templ_lpa(end+1,:) = template(i).pnt(lpa_indx,:); templ_rpa(end+1,:) = template(i).pnt(rpa_indx,:); end templ_nas = mean(templ_nas,1); templ_lpa = mean(templ_lpa,1); templ_rpa = mean(templ_rpa,1); % realign both to a common coordinate system elec2common = headcoordinates(elec_nas, elec_lpa, elec_rpa); templ2common = headcoordinates(templ_nas, templ_lpa, templ_rpa); % compute the combined transform and realign the electrodes to the template norm = []; norm.m = elec2common * inv(templ2common); norm.pnt = warp_apply(norm.m, elec.pnt, 'homogeneous'); norm.label = elec.label; nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1})); lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2})); rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3})); dpre = mean(sqrt(sum((elec.pnt([nas_indx lpa_indx rpa_indx],:) - [templ_nas; templ_lpa; templ_rpa]).^2, 2))); nas_indx = match_str(lower(norm.label), lower(cfg.fiducial{1})); lpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{2})); rpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{3})); dpost = mean(sqrt(sum((norm.pnt([nas_indx lpa_indx rpa_indx],:) - [templ_nas; templ_lpa; templ_rpa]).^2, 2))); fprintf('mean distance between fiducials prior to realignment %f, after realignment %f\n', dpre, dpost); if strcmp(cfg.feedback, 'yes') % plot the first three electrodes before transformation my_plot3(elec.pnt(1,:), 'r*'); my_plot3(elec.pnt(2,:), 'r*'); my_plot3(elec.pnt(3,:), 'r*'); my_text3(elec.pnt(1,:), elec.label{1}, 'color', 'r'); my_text3(elec.pnt(2,:), elec.label{2}, 'color', 'r'); my_text3(elec.pnt(3,:), elec.label{3}, 'color', 'r'); % plot the template fiducials my_plot3(templ_nas, 'b*'); my_plot3(templ_lpa, 'b*'); my_plot3(templ_rpa, 'b*'); my_text3(templ_nas, ' nas', 'color', 'b'); my_text3(templ_lpa, ' lpa', 'color', 'b'); my_text3(templ_rpa, ' rpa', 'color', 'b'); % plot all electrodes after transformation my_plot3(norm.pnt, 'm.'); my_plot3(norm.pnt(1,:), 'm*'); my_plot3(norm.pnt(2,:), 'm*'); my_plot3(norm.pnt(3,:), 'm*'); my_text3(norm.pnt(1,:), norm.label{1}, 'color', 'm'); my_text3(norm.pnt(2,:), norm.label{2}, 'color', 'm'); my_text3(norm.pnt(3,:), norm.label{3}, 'color', 'm'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(cfg.method, 'interactive') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % open a figure fig = figure; % add the data to the figure set(fig, 'CloseRequestFcn', @cb_close); setappdata(fig, 'elec', elec); setappdata(fig, 'transform', eye(4)); if useheadshape setappdata(fig, 'surf', headshape); end if usetemplate % FIXME interactive realigning to template electrodes is not yet supported % this requires a consistent handling of channel selection etc. setappdata(fig, 'template', template); end % add the GUI elements cb_creategui(gca); cb_redraw(gca); rotate3d on waitfor(fig); % get the data from the figure that was left behind as global variable global norm tmp = norm; clear global norm norm = tmp; clear tmp else error('unknown method'); end % apply the spatial transformation to all electrodes, and replace the % electrode labels by their case-sensitive original values if any(strcmp(cfg.method, {'rigidbody', 'globalrescale', 'traditional', 'nonlin1', 'nonlin2', 'nonlin3', 'nonlin4', 'nonlin5'})) norm.pnt = warp_apply(norm.m, orig.pnt, cfg.method); else norm.pnt = warp_apply(norm.m, orig.pnt, 'homogenous'); end norm.label = orig.label; % add version information to the configuration try % get the full name of the function cfg.version.name = mfilename('fullpath'); catch % required for compatibility with Matlab versions prior to release 13 (6.5) [st, i] = dbstack; cfg.version.name = st(i); end cfg.version.id = '$Id: electroderealign.m,v 1.1 2009/01/30 04:02:02 arno Exp $'; % remember the configuration norm.cfg = cfg; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % some simple SUBFUNCTIONs that facilitate 3D plotting %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = my_plot3(xyz, varargin) h = plot3(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:}); function h = my_text3(xyz, varargin) h = text(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:}); function my_line3(xyzB, xyzE, varargin) for i=1:size(xyzB,1) line([xyzB(i,1) xyzE(i,1)], [xyzB(i,2) xyzE(i,2)], [xyzB(i,3) xyzE(i,3)], varargin{:}) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to layout a moderately complex graphical user interface %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = layoutgui(fig, geometry, position, style, string, value, tag, callback); horipos = geometry(1); % lower left corner of the GUI part in the figure vertpos = geometry(2); % lower left corner of the GUI part in the figure width = geometry(3); % width of the GUI part in the figure height = geometry(4); % height of the GUI part in the figure horidist = 0.05; vertdist = 0.05; options = {'units', 'normalized', 'HorizontalAlignment', 'center'}; % 'VerticalAlignment', 'middle' Nrow = size(position,1); h = cell(Nrow,1); for i=1:Nrow if isempty(position{i}) continue; end position{i} = position{i} ./ sum(position{i}); Ncol = size(position{i},2); ybeg = (Nrow-i )/Nrow + vertdist/2; yend = (Nrow-i+1)/Nrow - vertdist/2; for j=1:Ncol xbeg = sum(position{i}(1:(j-1))) + horidist/2; xend = sum(position{i}(1:(j ))) - horidist/2; pos(1) = xbeg*width + horipos; pos(2) = ybeg*height + vertpos; pos(3) = (xend-xbeg)*width; pos(4) = (yend-ybeg)*height; h{i}{j} = uicontrol(fig, ... options{:}, ... 'position', pos, ... 'style', style{i}{j}, ... 'string', string{i}{j}, ... 'tag', tag{i}{j}, ... 'value', value{i}{j}, ... 'callback', callback{i}{j} ... ); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_creategui(hObject, eventdata, handles); % define the position of each GUI element position = { [2 1 1 1] [2 1 1 1] [2 1 1 1] [1] [1] [1] [1] [1 1] }; % define the style of each GUI element style = { {'text' 'edit' 'edit' 'edit'} {'text' 'edit' 'edit' 'edit'} {'text' 'edit' 'edit' 'edit'} {'pushbutton'} {'pushbutton'} {'toggle'} {'toggle'} {'text' 'edit'} }; % define the descriptive string of each GUI element string = { {'rotate' 0 0 0} {'translate' 0 0 0} {'scale' 1 1 1} {'redisplay'} {'apply'} {'toggle grid'} {'toggle axes'} {'alpha' 0.7} }; % define the value of each GUI element value = { {[] [] [] []} {[] [] [] []} {[] [] [] []} {[]} {[]} {0} {0} {[] []} }; % define a tag for each GUI element tag = { {'' 'rx' 'ry' 'rz'} {'' 'tx' 'ty' 'tz'} {'' 'sx' 'sy' 'sz'} {''} {''} {'toggle grid'} {'toggle axes'} {'' 'alpha'} }; % define the callback function of each GUI element callback = { {[] @cb_redraw @cb_redraw @cb_redraw} {[] @cb_redraw @cb_redraw @cb_redraw} {[] @cb_redraw @cb_redraw @cb_redraw} {@cb_redraw} {@cb_apply} {@cb_redraw} {@cb_redraw} {[] @cb_redraw} }; fig = get(hObject, 'parent'); layoutgui(fig, [0.7 0.05 0.25 0.50], position, style, string, value, tag, callback); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_redraw(hObject, eventdata, handles); fig = get(hObject, 'parent'); surf = getappdata(fig, 'surf'); elec = getappdata(fig, 'elec'); template = getappdata(fig, 'template'); % get the transformation details rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string')); ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string')); rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string')); tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string')); ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string')); tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string')); sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string')); sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string')); sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string')); R = rotate ([rx ry rz]); T = translate([tx ty tz]); S = scale ([sx sy sz]); H = S * T * R; elec.pnt = warp_apply(H, elec.pnt); axis vis3d; cla xlabel('x') ylabel('y') zlabel('z') if ~isempty(surf) triplot(surf.pnt, surf.tri, [], 'faces_skin'); alpha(str2num(get(findobj(fig, 'tag', 'alpha'), 'string'))); end if ~isempty(template) triplot(template.pnt, [], [], 'nodes_blue') end triplot(elec.pnt, [], [], 'nodes'); if isfield(elec, 'line') triplot(elec.pnt, elec.line, [], 'edges'); end if get(findobj(fig, 'tag', 'toggle axes'), 'value') axis on else axis off end if get(findobj(fig, 'tag', 'toggle grid'), 'value') grid on else grid off end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_apply(hObject, eventdata, handles); fig = get(hObject, 'parent'); elec = getappdata(fig, 'elec'); transform = getappdata(fig, 'transform'); % get the transformation details rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string')); ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string')); rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string')); tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string')); ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string')); tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string')); sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string')); sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string')); sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string')); R = rotate ([rx ry rz]); T = translate([tx ty tz]); S = scale ([sx sy sz]); H = S * T * R; elec.pnt = warp_apply(H, elec.pnt); transform = H * transform; set(findobj(fig, 'tag', 'rx'), 'string', 0); set(findobj(fig, 'tag', 'ry'), 'string', 0); set(findobj(fig, 'tag', 'rz'), 'string', 0); set(findobj(fig, 'tag', 'tx'), 'string', 0); set(findobj(fig, 'tag', 'ty'), 'string', 0); set(findobj(fig, 'tag', 'tz'), 'string', 0); set(findobj(fig, 'tag', 'sx'), 'string', 1); set(findobj(fig, 'tag', 'sy'), 'string', 1); set(findobj(fig, 'tag', 'sz'), 'string', 1); setappdata(fig, 'elec', elec); setappdata(fig, 'transform', transform); cb_redraw(hObject); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_close(hObject, eventdata, handles); % make the current transformation permanent and subsequently allow deleting the figure cb_apply(gca); % get the updated electrode from the figure fig = hObject; % hmmm, this is ugly global norm norm = getappdata(fig, 'elec'); norm.m = getappdata(fig, 'transform'); set(fig, 'CloseRequestFcn', @delete); delete(fig);
github
lcnbeapp/beapp-master
pop_dipfit_nonlinear.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/pop_dipfit_nonlinear.m
19,264
utf_8
38b5b9d5f0129b1a4aaf3230c2578eac
% pop_dipfit_nonlinear() - interactively do dipole fit of selected ICA components % % Usage: % >> EEGOUT = pop_dipfit_nonlinear( EEGIN ) % % Inputs: % EEGIN input dataset % % Outputs: % EEGOUT output dataset % % Author: Robert Oostenveld, SMI/FCDC, Nijmegen 2003 % Arnaud Delorme, SCCN, La Jolla 2003 % Thanks to Nicolas Robitaille for his help on the CTF MEG % implementation % SMI, University Aalborg, Denmark http://www.smi.auc.dk/ % FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl/ % Copyright (C) 2003 Robert Oostenveld, SMI/FCDC [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [EEGOUT, com] = pop_dipfit_nonlinear( EEG, subfunction, parent, dipnum ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the code for this interactive dialog has 4 major parts % - draw the graphical user interface % - synchronize the gui with the data % - synchronize the data with the gui % - execute the actual dipole analysis % the subfunctions that perform handling of the gui are % - dialog_selectcomponent % - dialog_checkinput % - dialog_setvalue % - dialog_getvalue % - dialog_plotmap % - dialog_plotcomponent % - dialog_flip % the subfunctions that perform the fitting are % - dipfit_position % - dipfit_moment if ~plugin_askinstall('Fieldtrip-lite', 'ft_sourceanalysis'), return; end; if nargin<1 help pop_dipfit_nonlinear; return elseif nargin==1 EEGOUT = EEG; com = ''; if ~isfield(EEG, 'chanlocs') error('No electrodes present'); end if ~isfield(EEG, 'icawinv') error('No ICA components to fit'); end if ~isfield(EEG, 'dipfit') error('General dipolefit settings not specified'); end if ~isfield(EEG.dipfit, 'vol') & ~isfield(EEG.dipfit, 'hdmfile') error('Dipolefit volume conductor model not specified'); end % select all ICA components as 'fitable' select = 1:size(EEG.icawinv,2); if ~isfield(EEG.dipfit, 'current') % select the first component as the current component EEG.dipfit.current = 1; end % verify the presence of a dipole model if ~isfield(EEG.dipfit, 'model') % create empty dipole model for each component for i=select EEG.dipfit.model(i).posxyz = zeros(2,3); EEG.dipfit.model(i).momxyz = zeros(2,3); EEG.dipfit.model(i).rv = 1; EEG.dipfit.model(i).select = [1]; end end % verify the size of each dipole model for i=select if ~isfield(EEG.dipfit.model, 'posxyz') | length(EEG.dipfit.model) < i | isempty(EEG.dipfit.model(i).posxyz) % replace all empty dipole models with a two dipole model, of which one is active EEG.dipfit.model(i).select = [1]; EEG.dipfit.model(i).rv = 1; EEG.dipfit.model(i).posxyz = zeros(2,3); EEG.dipfit.model(i).momxyz = zeros(2,3); elseif size(EEG.dipfit.model(i).posxyz,1)==1 % replace all one dipole models with a two dipole model EEG.dipfit.model(i).select = [1]; EEG.dipfit.model(i).posxyz = [EEG.dipfit.model(i).posxyz; [0 0 0]]; EEG.dipfit.model(i).momxyz = [EEG.dipfit.model(i).momxyz; [0 0 0]]; elseif size(EEG.dipfit.model(i).posxyz,1)>2 % replace all more-than-two dipole models with a two dipole model warning('pruning dipole model to two dipoles'); EEG.dipfit.model(i).select = [1]; EEG.dipfit.model(i).posxyz = EEG.dipfit.model(i).posxyz(1:2,:); EEG.dipfit.model(i).momxyz = EEG.dipfit.model(i).momxyz(1:2,:); end end % default is not to use symmetry constraint constr = []; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % construct the graphical user interface %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % define the callback functions for the interface elements cb_plotmap = 'pop_dipfit_nonlinear(EEG, ''dialog_plotmap'', gcbf);'; cb_selectcomponent = 'pop_dipfit_nonlinear(EEG, ''dialog_selectcomponent'', gcbf);'; cb_checkinput = 'pop_dipfit_nonlinear(EEG, ''dialog_checkinput'', gcbf);'; cb_fitposition = 'pop_dipfit_nonlinear(EEG, ''dialog_getvalue'', gcbf); pop_dipfit_nonlinear(EEG, ''dipfit_position'', gcbf); pop_dipfit_nonlinear(EEG, ''dialog_setvalue'', gcbf);'; cb_fitmoment = 'pop_dipfit_nonlinear(EEG, ''dialog_getvalue'', gcbf); pop_dipfit_nonlinear(EEG, ''dipfit_moment'' , gcbf); pop_dipfit_nonlinear(EEG, ''dialog_setvalue'', gcbf);'; cb_close = 'close(gcbf)'; cb_help = 'pophelp(''pop_dipfit_nonlinear'');'; cb_ok = 'uiresume(gcbf);'; cb_plotdip = 'pop_dipfit_nonlinear(EEG, ''dialog_plotcomponent'', gcbf);'; cb_flip1 = 'pop_dipfit_nonlinear(EEG, ''dialog_flip'', gcbf, 1);'; cb_flip2 = 'pop_dipfit_nonlinear(EEG, ''dialog_flip'', gcbf, 2);'; cb_sym = [ 'set(findobj(gcbf, ''tag'', ''dip2sel''), ''value'', 1);' cb_checkinput ]; % vertical layout for each line geomvert = [1 1 1 1 1 1 1 1 1]; % horizontal layout for each line geomhoriz = { [0.8 0.5 0.8 1 1] [1] [0.7 0.7 2 2 1] [0.7 0.5 0.2 2 2 1] [0.7 0.5 0.2 2 2 1] [1] [1 1 1] [1] [1 1 1] }; % define each individual graphical user element elements = { ... { 'style' 'text' 'string' 'Component to fit' } ... { 'style' 'edit' 'string' 'dummy' 'tag' 'component' 'callback' cb_selectcomponent } ... { 'style' 'pushbutton' 'string' 'Plot map' 'callback' cb_plotmap } ... { 'style' 'text' 'string' 'Residual variance = ' } ... { 'style' 'text' 'string' 'dummy' 'tag' 'relvar' } ... { } ... { 'style' 'text' 'string' 'dipole' } ... { 'style' 'text' 'string' 'fit' } ... { 'style' 'text' 'string' 'position' } ... { 'style' 'text' 'string' 'moment' } ... { } ... ... { 'style' 'text' 'string' '#1' 'tag' 'dip1' } ... { 'style' 'checkbox' 'string' '' 'tag' 'dip1sel' 'callback' cb_checkinput } { } ... { 'style' 'edit' 'string' '' 'tag' 'dip1pos' 'callback' cb_checkinput } ... { 'style' 'edit' 'string' '' 'tag' 'dip1mom' 'callback' cb_checkinput } ... { 'style' 'pushbutton' 'string' 'Flip (in|out)' 'callback' cb_flip1 } ... ... { 'style' 'text' 'string' '#2' 'tag' 'dip2' } ... { 'style' 'checkbox' 'string' '' 'tag' 'dip2sel' 'callback' cb_checkinput } { } ... { 'style' 'edit' 'string' '' 'tag' 'dip2pos' 'callback' cb_checkinput } ... { 'style' 'edit' 'string' '' 'tag' 'dip2mom' 'callback' cb_checkinput } ... { 'style' 'pushbutton' 'string' 'Flip (in|out)' 'callback' cb_flip2 } ... ... { } { 'style' 'checkbox' 'string' 'Symmetry constrain for dipole #2' 'tag' 'dip2sym' 'callback' cb_sym 'value' 1 } ... { } { } { } ... { 'style' 'pushbutton' 'string' 'Fit dipole(s)'' position & moment' 'callback' cb_fitposition } ... { 'style' 'pushbutton' 'string' 'OR fit only dipole(s)'' moment' 'callback' cb_fitmoment } ... { 'style' 'pushbutton' 'string' 'Plot dipole(s)' 'callback' cb_plotdip } ... }; % add the cancel, help and ok buttons at the bottom geomvert = [geomvert 1 1]; geomhoriz = {geomhoriz{:} [1] [1 1 1]}; elements = { elements{:} ... { } ... { 'Style', 'pushbutton', 'string', 'Cancel', 'callback', cb_close } ... { 'Style', 'pushbutton', 'string', 'Help', 'callback', cb_help } ... { 'Style', 'pushbutton', 'string', 'OK', 'callback', cb_ok } ... }; % activate the graphical interface supergui(0, geomhoriz, geomvert, elements{:}); dlg = gcf; set(gcf, 'name', 'Manual dipole fit -- pop_dipfit_nonlinear()'); set(gcf, 'userdata', EEG); pop_dipfit_nonlinear(EEG, 'dialog_setvalue', dlg); uiwait(dlg); if ishandle(dlg) pop_dipfit_nonlinear(EEG, 'dialog_getvalue', dlg); % FIXME, rv is undefined since the user may have changed dipole parameters % FIXME, see also dialog_getvalue subfucntion EEGOUT = get(dlg, 'userdata'); close(dlg); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % implement all subfunctions through a switch-yard %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif nargin>=3 %disp(subfunction) EEG = get(parent, 'userdata'); switch subfunction case 'dialog_selectcomponent' current = get(findobj(parent, 'tag', 'component'), 'string'); current = str2num(current); current = current(1); current = min(current, size(EEG.icaweights,1)); current = max(current, 1); set(findobj(parent, 'tag', 'component'), 'string', int2str(current)); EEG.dipfit.current = current; % reassign the global EEG object back to the dialogs userdata set(parent, 'userdata', EEG); % redraw the dialog with the current model pop_dipfit_nonlinear(EEG, 'dialog_setvalue', parent); case 'dialog_plotmap' current = str2num(get(findobj(parent, 'tag', 'component'), 'string')); figure; pop_topoplot(EEG, 0, current, [ 'IC ' num2str(current) ], [1 1], 1); title([ 'IC ' int2str(current) ]); case 'dialog_plotcomponent' current = get(findobj(parent, 'tag', 'component'), 'string'); EEG.dipfit.current = str2num(current); if ~isempty( EEG.dipfit.current ) pop_dipplot(EEG, 'DIPFIT', EEG.dipfit.current, 'normlen', 'on', 'projlines', 'on', 'mri', EEG.dipfit.mrifile); end; case 'dialog_checkinput' if get(findobj(parent, 'tag', 'dip1sel'), 'value') & ~get(findobj(parent, 'tag', 'dip1act'), 'value') set(findobj(parent, 'tag', 'dip1act'), 'value', 1); end if get(findobj(parent, 'tag', 'dip2sel'), 'value') & ~get(findobj(parent, 'tag', 'dip2act'), 'value') set(findobj(parent, 'tag', 'dip2act'), 'value', 1); end if ~all(size(str2num(get(findobj(parent, 'tag', 'dip1pos'), 'string')))==[1 3]) set(findobj(parent, 'tag', 'dip1pos'), 'string', sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(EEG.dipfit.current).posxyz(1,:))); else EEG.dipfit.model(EEG.dipfit.current).posxyz(1,:) = str2num(get(findobj(parent, 'tag', 'dip1pos'), 'string')); end if ~all(size(str2num(get(findobj(parent, 'tag', 'dip2pos'), 'string')))==[1 3]) set(findobj(parent, 'tag', 'dip2pos'), 'string', sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(EEG.dipfit.current).posxyz(2,:))); else EEG.dipfit.model(EEG.dipfit.current).posxyz(2,:) = str2num(get(findobj(parent, 'tag', 'dip2pos'), 'string')); end if ~all(size(str2num(get(findobj(parent, 'tag', 'dip1mom'), 'string')))==[1 3]) set(findobj(parent, 'tag', 'dip1mom'), 'string', sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(EEG.dipfit.current).momxyz(1,:))); else EEG.dipfit.model(EEG.dipfit.current).momxyz(1,:) = str2num(get(findobj(parent, 'tag', 'dip1mom'), 'string')); end if ~all(size(str2num(get(findobj(parent, 'tag', 'dip2mom'), 'string')))==[1 3]) set(findobj(parent, 'tag', 'dip2mom'), 'string', sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(EEG.dipfit.current).momxyz(2,:))); else EEG.dipfit.model(EEG.dipfit.current).momxyz(2,:) = str2num(get(findobj(parent, 'tag', 'dip2mom'), 'string')); end if get(findobj(parent, 'tag', 'dip2sel'), 'value') & get(findobj(parent, 'tag', 'dip2sym'), 'value') & ~get(findobj(parent, 'tag', 'dip1sel'), 'value') set(findobj(parent, 'tag', 'dip2sel'), 'value', 0); end set(parent, 'userdata', EEG); case 'dialog_setvalue' % synchronize the gui with the data set(findobj(parent, 'tag', 'component'), 'string', EEG.dipfit.current); set(findobj(parent, 'tag', 'relvar' ), 'string', sprintf('%0.2f%%', EEG.dipfit.model(EEG.dipfit.current).rv * 100)); set(findobj(parent, 'tag', 'dip1sel'), 'value', ismember(1, EEG.dipfit.model(EEG.dipfit.current).select)); set(findobj(parent, 'tag', 'dip2sel'), 'value', ismember(2, EEG.dipfit.model(EEG.dipfit.current).select)); set(findobj(parent, 'tag', 'dip1pos'), 'string', sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(EEG.dipfit.current).posxyz(1,:))); if strcmpi(EEG.dipfit.coordformat, 'CTF') set(findobj(parent, 'tag', 'dip1mom'), 'string', sprintf('%f %f %f', EEG.dipfit.model(EEG.dipfit.current).momxyz(1,:))); else set(findobj(parent, 'tag', 'dip1mom'), 'string', sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(EEG.dipfit.current).momxyz(1,:))); end; Ndipoles = size(EEG.dipfit.model(EEG.dipfit.current).posxyz, 1); if Ndipoles>=2 set(findobj(parent, 'tag', 'dip2pos'), 'string', sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(EEG.dipfit.current).posxyz(2,:))); if strcmpi(EEG.dipfit.coordformat, 'CTF') set(findobj(parent, 'tag', 'dip2mom'), 'string', sprintf('%f %f %f', EEG.dipfit.model(EEG.dipfit.current).momxyz(2,:))); else set(findobj(parent, 'tag', 'dip2mom'), 'string', sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(EEG.dipfit.current).momxyz(2,:))); end; end case 'dialog_getvalue' % synchronize the data with the gui if get(findobj(parent, 'tag', 'dip1sel'), 'value'); select = [1]; else select = []; end; if get(findobj(parent, 'tag', 'dip2sel'), 'value'); select = [select 2]; end; posxyz(1,:) = str2num(get(findobj(parent, 'tag', 'dip1pos'), 'string')); posxyz(2,:) = str2num(get(findobj(parent, 'tag', 'dip2pos'), 'string')); momxyz(1,:) = str2num(get(findobj(parent, 'tag', 'dip1mom'), 'string')); momxyz(2,:) = str2num(get(findobj(parent, 'tag', 'dip2mom'), 'string')); % assign the local values to the global EEG object EEG.dipfit.model(EEG.dipfit.current).posxyz = posxyz; EEG.dipfit.model(EEG.dipfit.current).momxyz = momxyz; EEG.dipfit.model(EEG.dipfit.current).select = select; % FIXME, rv is undefined after a manual change of parameters % FIXME, this should either be undated continuously or upon OK buttonpress % EEG.dipfit.model(EEG.dipfit.current).rv = nan; % reassign the global EEG object back to the dialogs userdata set(parent, 'userdata', EEG); case 'dialog_flip' % flip the orientation of the dipole current = EEG.dipfit.current; moment = EEG.dipfit.model(current).momxyz; EEG.dipfit.model(current).momxyz(dipnum,:) = [ -moment(dipnum,1) -moment(dipnum,2) -moment(dipnum,3)]; set(findobj(parent, 'tag', ['dip' int2str(dipnum) 'mom']), 'string', ... sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(current).momxyz(dipnum,:))); set(parent, 'userdata', EEG); case {'dipfit_moment', 'dipfit_position'} % determine the selected dipoles and components current = EEG.dipfit.current; select = find([get(findobj(parent, 'tag', 'dip1sel'), 'value') get(findobj(parent, 'tag', 'dip2sel'), 'value')]); if isempty(select) warning('no dipoles selected for fitting'); return end % remove the dipoles from the model that are not selected, but keep % the original dipole model (to keep the GUI consistent) model_before_fitting = EEG.dipfit.model(current); EEG.dipfit.model(current).posxyz = EEG.dipfit.model(current).posxyz(select,:); EEG.dipfit.model(current).momxyz = EEG.dipfit.model(current).momxyz(select,:); if strcmp(subfunction, 'dipfit_moment') % the default is 'yes' which should only be overruled for fitting dipole moment cfg.nonlinear = 'no'; end dipfitdefs; if get(findobj(parent, 'tag', 'dip2sym'), 'value') & get(findobj(parent, 'tag', 'dip2sel'), 'value') if strcmpi(EEG.dipfit.coordformat,'MNI') cfg.symmetry = 'x'; else cfg.symmetry = 'y'; end; else cfg.symmetry = []; end cfg.component = current; % convert structure into list of input arguments arg = [fieldnames(cfg)' ; struct2cell(cfg)']; arg = arg(:)'; % make a dialog to interrupt the fitting procedure fig = figure('visible', 'off'); supergui( fig, {1 1}, [], ... {'style' 'text' 'string' 'Press button below to stop fitting' }, ... {'style' 'pushbutton' 'string' 'Interupt' 'callback' 'figure(gcbf); set(gcbf, ''tag'', ''stop'');' } ); drawnow; % start the dipole fitting try warning backtrace off; EEG = dipfit_nonlinear(EEG, arg{:}); warning backtrace on; catch, disp('Dipole localization failed'); end; % should the following string be put into com? ->NOT SUPPORTED % -------------------------------------------------------- com = sprintf('%s = dipfit_nonlinear(%s,%s)\n', inputname(1), inputname(1), vararg2str(arg)); % this GUI always requires two sources in the dipole model % first put the original model back in and then replace the dipole parameters that have been fitted model_after_fitting = EEG.dipfit.model(current); newfields = fieldnames( EEG.dipfit.model ); for index = 1:length(newfields) eval( ['EEG.dipfit.model(' int2str(current) ').' newfields{index} ' = model_after_fitting.' newfields{index} ';' ]); end; EEG.dipfit.model(current).posxyz(select,:) = model_after_fitting.posxyz; EEG.dipfit.model(current).momxyz(select,:) = model_after_fitting.momxyz; EEG.dipfit.model(current).rv = model_after_fitting.rv; %EEG.dipfit.model(current).diffmap = model_after_fitting.diffmap; % reassign the global EEG object back to the dialogs userdata set(parent, 'userdata', EEG); % close the interrupt dialog if ishandle(fig) close(fig); end otherwise error('unknown subfunction for pop_dipfit_nonlinear'); end % switch subfunction end % if nargin
github
lcnbeapp/beapp-master
dipfit_1_to_2.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/dipfit_1_to_2.m
2,252
utf_8
1a1a49c9adb0d94ff59b4a2206a3f2f4
% dipfit_1_to_2() - convert dipfit 1 structure to dipfit 2 structure. % % Usage: % >> EEG.dipfit = dipfit_1_to_2(EEG.dipfit); % % Note: % For non-standard BESA models (where the radii or the conductances % have been modified, users must create a new model in Dipfit2 from % the default BESA model. % % Author: Arnaud Delorme, SCCN, La Jolla 2005 % Copyright (C) Arnaud Delorme, SCCN, La Jolla 2005 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function newdipfit = dipfit_1_to_2( dipfit ); if isfield( dipfit, 'model') newdipfit.model = dipfit.model; end; if isfield( dipfit, 'chansel') newdipfit.chansel = dipfit.chansel; end; ind = 1; % use first template (BESA) newdipfit.coordformat = template_models(ind).coordformat; newdipfit.mrifile = template_models(ind).mrifile; newdipfit.chanfile = template_models(ind).chanfile; if ~isfield(dipfit, 'vol') newdipfit.hdmfile = template_models(ind).hdmfile; else newdipfit.vol = dipfit.vol; %if length(dipfit.vol) == 4 %if ~all(dipfit.vol == [85-6-7-1 85-6-7 85-6 85]) | ... % ~all(dipfit.c == [0.33 1.00 0.0042 0.33]) | ... % ~all(dipfit.o = [0 0 0]) % disp('Warning: Conversion from dipfit 1 to dipfit 2 can only deal'); % disp(' with standard (not modified) BESA model'); % disp(' See "help dipfit_1_to_2" to convert this model'); % newdipfit = []; %end; %end; end;
github
lcnbeapp/beapp-master
dipfit_gridsearch.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/dipfit_gridsearch.m
4,519
utf_8
cc77806c9d0a7de350e540a72dc1c033
% dipfit_gridsearch() - do initial batch-like dipole scan and fit to all % data components and return a dipole model with a % single dipole for each component. % % Usage: % >> EEGOUT = dipfit_gridsearch( EEGIN, varargin) % % Inputs: % ... % % Optional inputs: % 'component' - vector with integers, ICA components to scan % 'xgrid' - vector with floats, grid positions along x-axis % 'ygrid' - vector with floats, grid positions along y-axis % 'zgrid' - vector with floats, grid positions along z-axis % % Output: % ... % % Author: Robert Oostenveld, SMI/FCDC, Nijmegen 2003, load/save by % Arnaud Delorme % Thanks to Nicolas Robitaille for his help on the CTF MEG % implementation % SMI, University Aalborg, Denmark http://www.smi.auc.dk/ % FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl % Copyright (C) 2003 Robert Oostenveld, SMI/FCDC [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [EEGOUT] = dipfit_gridsearch(EEG, varargin) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert the optional arguments into a configuration structure that can be % understood by FIELDTRIPs dipolefitting function if nargin>2 cfg = struct(varargin{:}); else help dipfit_gridsearch return end % specify the FieldTrip DIPOLEFITTING configuration cfg.model = 'moving'; cfg.gridsearch = 'yes'; cfg.nonlinear = 'no'; % add some additional settings from EEGLAB to the configuration tmpchanlocs = EEG.chanlocs; cfg.channel = { tmpchanlocs(EEG.dipfit.chansel).labels }; if isfield(EEG.dipfit, 'vol') cfg.vol = EEG.dipfit.vol; elseif isfield(EEG.dipfit, 'hdmfile') cfg.hdmfile = EEG.dipfit.hdmfile; else error('no head model in EEG.dipfit') end if isfield(EEG.dipfit, 'elecfile') & ~isempty(EEG.dipfit.elecfile) cfg.elecfile = EEG.dipfit.elecfile; end if isfield(EEG.dipfit, 'gradfile') & ~isempty(EEG.dipfit.gradfile) cfg.gradfile = EEG.dipfit.gradfile; end % convert the EEGLAB data structure into a structure that looks as if it % was computed using FIELDTRIPs componentanalysis function comp = eeglab2fieldtrip(EEG, 'componentanalysis', 'dipfit'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Added code to handle CTF data with multipleSphere head model % % This code is copy-pasted in dipfit_gridSearch, dipfit_nonlinear % % The flag .isMultiSphere is used by dipplot % % Nicolas Robitaille, January 2007. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Do some trick to force fieldtrip to use the multiple sphere model if strcmpi(EEG.dipfit.coordformat, 'CTF') cfg = rmfield(cfg, 'channel'); comp = rmfield(comp, 'elec'); cfg.gradfile = EEG.dipfit.chanfile; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % END % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isfield(cfg, 'component') % default is to scan all components cfg.component = 1:size(comp.topo,2); end % for each component scan the whole brain with dipoles using FIELDTRIPs % dipolefitting function source = ft_dipolefitting(cfg, comp); % reformat the output dipole sources into EEGLABs data structure for i=1:length(cfg.component) EEG.dipfit.model(cfg.component(i)).posxyz = source.dip(i).pos; EEG.dipfit.model(cfg.component(i)).momxyz = reshape(source.dip(i).mom, 3, length(source.dip(i).mom)/3)'; EEG.dipfit.model(cfg.component(i)).rv = source.dip(i).rv; end EEGOUT = EEG;
github
lcnbeapp/beapp-master
eegplugin_dipfit.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/eegplugin_dipfit.m
4,444
utf_8
2bcef6898d8184014480e6ed4f2e170b
% eegplugin_dipfit() - DIPFIT plugin version 2.0 for EEGLAB menu. % DIPFIT is the dipole fitting Matlab Toolbox of % Robert Oostenveld (in collaboration with A. Delorme). % % Usage: % >> eegplugin_dipfit(fig, trystrs, catchstrs); % % Inputs: % fig - [integer] eeglab figure. % trystrs - [struct] "try" strings for menu callbacks. % catchstrs - [struct] "catch" strings for menu callbacks. % % Notes: % To create a new plugin, simply create a file beginning with "eegplugin_" % and place it in your eeglab folder. It will then be automatically % detected by eeglab. See also this source code internal comments. % For eeglab to return errors and add the function's results to % the eeglab history, menu callback must be nested into "try" and % a "catch" strings. For more information on how to create eeglab % plugins, see http://www.sccn.ucsd.edu/eeglab/contrib.html % % Author: Arnaud Delorme, CNL / Salk Institute, 22 February 2003 % % See also: eeglab() % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1.07 USA function vers = eegplugin_dipfit(fig, trystrs, catchstrs) vers = 'dipfit2.2'; if nargin < 3 error('eegplugin_dipfit requires 3 arguments'); end; % find tools menu % --------------- menu = findobj(fig, 'tag', 'tools'); % tag can be % 'import data' -> File > import data menu % 'import epoch' -> File > import epoch menu % 'import event' -> File > import event menu % 'export' -> File > export % 'tools' -> tools menu % 'plot' -> plot menu % command to check that the '.source' is present in the EEG structure % ------------------------------------------------------------------- check_dipfit = [trystrs.no_check 'if ~isfield(EEG, ''dipfit''), error(''Run the dipole setting first''); end;' ... 'if isempty(EEG.dipfit), error(''Run the dipole setting first''); end;' ]; check_dipfitnocheck = [ trystrs.no_check 'if ~isfield(EEG, ''dipfit''), error(''Run the dipole setting first''); end; ' ]; check_chans = [ '[EEG tmpres] = eeg_checkset(EEG, ''chanlocs_homogeneous'');' ... 'if ~isempty(tmpres), eegh(tmpres), end; clear tmpres;' ]; % menu callback commands % ---------------------- comsetting = [ trystrs.check_ica check_chans '[EEG LASTCOM]=pop_dipfit_settings(EEG);' catchstrs.store_and_hist ]; combatch = [ check_dipfit check_chans '[EEG LASTCOM] = pop_dipfit_gridsearch(EEG);' catchstrs.store_and_hist ]; comfit = [ check_dipfitnocheck check_chans [ 'EEG = pop_dipfit_nonlinear(EEG); ' ... 'LASTCOM = ''% === History not supported for manual dipole fitting ==='';' ] catchstrs.store_and_hist ]; comauto = [ check_dipfit check_chans '[EEG LASTCOM] = pop_multifit(EEG);' catchstrs.store_and_hist ]; % preserve the '=" sign in the comment above: it is used by EEGLAB to detect appropriate LASTCOM complot = [ check_dipfit check_chans 'LASTCOM = pop_dipplot(EEG);' catchstrs.add_to_hist ]; % create menus % ------------ submenu = uimenu( menu, 'Label', 'Locate dipoles using DIPFIT 2.x', 'separator', 'on'); uimenu( submenu, 'Label', 'Head model and settings' , 'CallBack', comsetting); uimenu( submenu, 'Label', 'Coarse fit (grid scan)' , 'CallBack', combatch); uimenu( submenu, 'Label', 'Fine fit (iterative)' , 'CallBack', comfit); uimenu( submenu, 'Label', 'Autofit (coarse fit, fine fit & plot)', 'CallBack', comauto); uimenu( submenu, 'Label', 'Plot component dipoles' , 'CallBack', complot, 'separator', 'on');
github
lcnbeapp/beapp-master
pop_multifit.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/pop_multifit.m
10,370
utf_8
dd98129d0df98fcdfc6532ff87983696
% pop_multifit() - fit multiple component dipoles using DIPFIT % % Usage: % >> EEG = pop_multifit(EEG); % pop-up graphical interface % >> EEG = pop_multifit(EEG, comps, 'key', 'val', ...); % % Inputs: % EEG - input EEGLAB dataset. % comps - indices component to fit. Empty is all components. % % Optional inputs: % 'dipoles' - [1|2] use either 1 dipole or 2 dipoles contrain in % symmetry. Default is 1. % 'dipplot' - ['on'|'off'] plot dipoles. Default is 'off'. % 'plotopt' - [cell array] dipplot() 'key', 'val' options. Default is % 'normlen', 'on', 'image', 'fullmri' % 'rmout' - ['on'|'off'] remove dipoles outside the head. Artifactual % component often localize outside the head. Default is 'off'. % 'threshold' - [float] rejection threshold during component scan. % Default is 40 (residual variance above 40%). % % Outputs: % EEG - output dataset with updated "EEG.dipfit" field % % Note: residual variance is set to NaN if DIPFIT does not converge % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, Oct. 2003 % Copyright (C) 9/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, com] = pop_multifit(EEG, comps, varargin); if nargin < 1 help pop_multifit; return; end; com = []; ncomps = size(EEG.icaweights,1); if ncomps == 0, error('you must run ICA first'); end; if nargin<2 cb_chans = 'tmplocs = EEG.chanlocs; set(findobj(gcbf, ''tag'', ''chans''), ''string'', int2str(pop_chansel({tmplocs.labels}))); clear tmplocs;'; uilist = { { 'style' 'text' 'string' 'Component indices' } ... { 'style' 'edit' 'string' [ '1:' int2str(ncomps) ] } ... { 'style' 'text' 'string' 'Rejection threshold RV (%)' } ... { 'style' 'edit' 'string' '100' } ... { 'style' 'text' 'string' 'Remove dipoles outside the head' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'string' 'Fit bilateral dipoles (check)' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'string' 'Plot resulting dipoles (check)' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'string' 'dipplot() plotting options' } ... { 'style' 'edit' 'string' '''normlen'' ''on''' } ... { 'style' 'pushbutton' 'string' 'Help' 'callback' 'pophelp(''dipplot'')' } }; results = inputgui( { [1.91 2.8] [1.91 2.8] [3.1 0.8 1.6] [3.1 0.8 1.6] [3.1 0.8 1.6] [2.12 2.2 0.8]}, ... uilist, 'pophelp(''pop_multifit'')', ... 'Fit multiple ICA components -- pop_multifit()'); if length(results) == 0 return; end; comps = eval( [ '[' results{1} ']' ] ); % selecting model % --------------- options = {}; if ~isempty(results{2}) options = { options{:} 'threshold' eval( results{2} ) }; end; if results{3}, options = { options{:} 'rmout' 'on' }; end; if results{4}, options = { options{:} 'dipoles' 2 }; end; if results{5}, options = { options{:} 'dipplot' 'on' }; end; options = { options{:} 'plotopt' eval( [ '{ ' results{6} ' }' ]) }; else options = varargin; end; % checking parameters % ------------------- if isempty(comps), comps = [1:size(EEG.icaweights,1)]; end; g = finputcheck(options, { 'settings' { 'cell' 'struct' } [] {}; % deprecated 'dipoles' 'integer' [1 2] 1; 'threshold' 'float' [0 100] 40; 'dipplot' 'string' { 'on' 'off' } 'off'; 'rmout' 'string' { 'on' 'off' } 'off'; 'plotopt' 'cell' {} {'normlen' 'on' }}); if isstr(g), error(g); end; EEG = eeg_checkset(EEG, 'chanlocs_homogeneous'); % dipfit settings % --------------- if isstruct(g.settings) EEG.dipfit = g.settings; elseif ~isempty(g.settings) EEG = pop_dipfit_settings( EEG, g.settings{:}); % will probably not work but who knows end; % Scanning dipole locations % ------------------------- dipfitdefs; skipscan = 0; try alls = cellfun('size', { EEG.dipfit.model.posxyz }, 2); if length(alls) == ncomps if all(alls == 3) skipscan = 1; end; end; catch, end; if skipscan disp('Skipping scanning since all dipoles have non-null starting positions.'); else disp('Scanning dipolar grid to find acceptable starting positions...'); xg = linspace(-floor(meanradius), floor(meanradius),11); yg = linspace(-floor(meanradius), floor(meanradius),11); zg = linspace(0 , floor(meanradius), 6); EEG = pop_dipfit_gridsearch( EEG, [1:ncomps], ... eval(xgridstr), eval(ygridstr), eval(zgridstr), 100); disp('Scanning terminated. Refining dipole locations...'); end; % set symmetry constraint % ---------------------- if strcmpi(EEG.dipfit.coordformat,'MNI') defaultconstraint = 'x'; else defaultconstraint = 'y'; end; % Searching dipole localization % ----------------------------- disp('Searching dipoles locations...'); chansel = EEG.dipfit.chansel; %elc = getelecpos(EEG.chanlocs, EEG.dipfit); plotcomps = []; for i = comps(:)' if i <= length(EEG.dipfit.model) & ~isempty(EEG.dipfit.model(i).posxyz) if g.dipoles == 2, % try to find a good origin for automatic dipole localization EEG.dipfit.model(i).active = [1 2]; EEG.dipfit.model(i).select = [1 2]; if isempty(EEG.dipfit.model(i).posxyz) EEG.dipfit.model(i).posxyz = zeros(1,3); EEG.dipfit.model(i).momxyz = zeros(2,3); else EEG.dipfit.model(i).posxyz(2,:) = EEG.dipfit.model(i).posxyz; if strcmpi(EEG.dipfit.coordformat, 'MNI') EEG.dipfit.model(i).posxyz(:,1) = [-40;40]; else EEG.dipfit.model(i).posxyz(:,2) = [-40;40]; end; EEG.dipfit.model(i).momxyz(2,:) = EEG.dipfit.model(i).momxyz; end; else EEG.dipfit.model(i).active = [1]; EEG.dipfit.model(i).select = [1]; end; warning backtrace off; try, if g.dipoles == 2, EEG = dipfit_nonlinear(EEG, 'component', i, 'symmetry', defaultconstraint); else EEG = dipfit_nonlinear(EEG, 'component', i, 'symmetry', []); end; catch, EEG.dipfit.model(i).rv = NaN; disp('Maximum number of iterations reached. Fitting failed'); end; warning backtrace on; plotcomps = [ plotcomps i ]; end; end; % set RV to 1 for dipole with higher than 40% residual variance % ------------------------------------------------------------- EEG.dipfit.model = dipfit_reject(EEG.dipfit.model, g.threshold/100); % removing dipoles outside the head % --------------------------------- if strcmpi(g.rmout, 'on') & strcmpi(EEG.dipfit.coordformat, 'spherical') rmdip = []; for index = plotcomps if ~isempty(EEG.dipfit.model(index).posxyz) if any(sqrt(sum(EEG.dipfit.model(index).posxyz.^2,2)) > 85) rmdip = [ rmdip index]; EEG.dipfit.model(index).posxyz = []; EEG.dipfit.model(index).momxyz = []; EEG.dipfit.model(index).rv = 1; end; end; end; plotcomps = setdiff(plotcomps, rmdip); if length(rmdip) > 0 fprintf('%d out of cortex dipoles removed (usually artifacts)\n', length(rmdip)); end; end; % plotting dipoles % ---------------- if strcmpi(g.dipplot, 'on') pop_dipplot(EEG, 'DIPFIT', plotcomps, g.plotopt{:}); end; com = sprintf('%s = pop_multifit(%s, %s);', inputname(1), inputname(1), vararg2str({ comps options{:}})); return; % get electrode positions from eeglag % ----------------------------------- function elc = getelecpos(chanlocs, dipfitstruct); try, elc = [ [chanlocs.X]' [chanlocs.Y]' [chanlocs.Z]' ]; catch disp('No 3-D carthesian coordinates; re-computing them from 2-D polar coordinates'); EEG.chanlocs = convertlocs(EEG.chanlocs, 'topo2all'); elc = [ [chanlocs.X]' [chanlocs.Y]' [chanlocs.Z]' ]; end; % constrain electrode to sphere % ----------------------------- disp('Constraining electrodes to sphere'); elc = elc - repmat( dipfitstruct.vol.o, [size(elc,1) 1]); % recenter % (note the step above is not needed since the origin should always be 0) elc = elc ./ repmat( sqrt(sum(elc.*elc,2)), [1 3]); % normalize elc = elc * max(dipfitstruct.vol.r); % head size %for index= 1:size(elc,1) % elc(index,:) = max(dipfitstruct.vol.r) * elc(index,:) /norm(elc(index,:)); %end;
github
lcnbeapp/beapp-master
pop_dipfit_gridsearch.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/pop_dipfit_gridsearch.m
4,833
utf_8
39566131e1f04827a5eaf4dd7994f07f
% pop_dipfit_gridsearch() - scan all ICA components with a single dipole % on a regular grid spanning the whole brain. Any dipoles that explains % a component with a too large relative residual variance is removed. % % Usage: % >> EEGOUT = pop_dipfit_gridsearch( EEGIN ); % pop up interactive window % >> EEGOUT = pop_dipfit_gridsearch( EEGIN, comps ); % >> EEGOUT = pop_dipfit_gridsearch( EEGIN, comps, xgrid, ygrid, zgrid, thresh ) % % Inputs: % EEGIN - input dataset % comps - [integer array] component indices % xgrid - [float array] x-grid. Default is 10 elements between % -1 and 1. % ygrid - [float array] y-grid. Default is 10 elements between % -1 and 1. % zgrid - [float array] z-grid. Default is 10 elements between % -1 and 1. % thresh - [float] threshold in percent. Default 40. % % Outputs: % EEGOUT output dataset % % Authors: Robert Oostenveld, SMI/FCDC, Nijmegen 2003 % Arnaud Delorme, SCCN, La Jolla 2003 % Thanks to Nicolas Robitaille for his help on the CTF MEG % implementation % SMI, University Aalborg, Denmark http://www.smi.auc.dk/ % FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl/ % Copyright (C) 2003 Robert Oostenveld, SMI/FCDC [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [EEGOUT, com] = pop_dipfit_gridsearch(EEG, select, xgrid, ygrid, zgrid, reject ); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin < 1 help pop_dipfit_gridsearch; return; end; if ~plugin_askinstall('Fieldtrip-lite', 'ft_sourceanalysis'), return; end; EEGOUT = EEG; com = ''; if ~isfield(EEG, 'chanlocs') error('No electrodes present'); end if ~isfield(EEG, 'icawinv') error('No ICA components to fit'); end if ~isfield(EEG, 'dipfit') error('General dipolefit settings not specified'); end if ~isfield(EEG.dipfit, 'vol') & ~isfield(EEG.dipfit, 'hdmfile') error('Dipolefit volume conductor model not specified'); end dipfitdefs if strcmpi(EEG.dipfit.coordformat, 'CTF') maxrad = 8.5; xgridstr = sprintf('linspace(-%2.1f,%2.1f,11)', maxrad, maxrad); ygridstr = sprintf('linspace(-%2.1f,%2.1f,11)', maxrad, maxrad); zgridstr = sprintf('linspace(0,%2.1f,6)', maxrad); end; if nargin < 2 % get the default values and filenames promptstr = { 'Component(s) (not faster if few comp.)', ... 'Grid in X-direction', ... 'Grid in Y-direction', ... 'Grid in Z-direction', ... 'Rejection threshold RV(%)' }; inistr = { [ '1:' int2str(size(EEG.icawinv,2)) ], ... xgridstr, ... ygridstr, ... zgridstr, ... rejectstr }; result = inputdlg2( promptstr, 'Batch dipole fit -- pop_dipfit_gridsearch()', 1, inistr, 'pop_dipfit_gridsearch'); if length(result)==0 % user pressed cancel return end select = eval( [ '[' result{1} ']' ]); xgrid = eval( result{2} ); ygrid = eval( result{3} ); zgrid = eval( result{4} ); reject = eval( result{5} ) / 100; % string is in percent options = { }; else if nargin < 2 select = [1:size(EEG.icawinv,2)]; end; if nargin < 3 xgrid = eval( xgridstr ); end; if nargin < 4 ygrid = eval( ygridstr ); end; if nargin < 5 zgrid = eval( zgridstr ); end; if nargin < 6 reject = eval( rejectstr ); end; options = { 'waitbar' 'none' }; end; % perform batch fit with single dipole for all selected channels and components % warning off; warning backtrace off; EEGOUT = dipfit_gridsearch(EEG, 'component', select, 'xgrid', xgrid, 'ygrid', ygrid, 'zgrid', zgrid, options{:}); warning backtrace on; EEGOUT.dipfit.model = dipfit_reject(EEGOUT.dipfit.model, reject); % FIXME reject is not being used at the moment disp('Done'); com = sprintf('%s = pop_dipfit_gridsearch(%s, %s);', ... inputname(1), inputname(1), vararg2str( { select xgrid, ygrid, zgrid reject }));
github
lcnbeapp/beapp-master
dipfit_erpeeg.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/dipfit_erpeeg.m
3,634
utf_8
c387b5b84e9f4ee03b832f289837c1a2
% dipfit_erpeeg - fit multiple component dipoles using DIPFIT % % Usage: % >> [ dipole model EEG] = dipfit_erpeeg(data, chanlocs, 'key', 'val', ...); % % Inputs: % data - input data [channel x point]. One dipole per point is % returned. % chanlocs - channel location structure (returned by readlocs()). % % Optional inputs: % 'settings' - [cell array] dipfit settings (arguments to the % pop_dipfit_settings() function). Default is none. % 'dipoles' - [1|2] use either 1 dipole or 2 dipoles contrain in % symetry. Default is 1. % 'dipplot' - ['on'|'off'] plot dipoles. Default is 'off'. % 'plotopt' - [cell array] dipplot() 'key', 'val' options. Default is % 'normlen', 'on', 'image', 'fullmri' % % Outputs: % dipole - dipole structure ('posxyz' field is the position; 'momxyz' % field is the moment and 'rv' the residual variance) % model - structure containing model information ('vol.r' field is % radius, 'vol.c' conductances, 'vol.o' the 3-D origin and % 'chansel', the selected channels). % EEG - faked EEG structure containing erp activation at the place % of ICA components but allowing to plot ERP dipoles. % % Note: residual variance is set to NaN if Dipfit does not converge % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, Nov. 2003 % Copyright (C) 10/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 [dipoles, model, EEG] = dipfit_erpeeg(DATA, chanlocs, varargin); if nargin < 1 help dipfit_erpeeg; return; end; ncomps = size(DATA,2); if size(DATA,1) ~= length(chanlocs) error('# of row in ''DATA'' must equal # of channels in ''chanlocs'''); end; % faking an EEG dataset % --------------------- EEG = eeg_emptyset; EEG.data = rand(size(DATA,1), 1000); EEG.nbchan = size(DATA,1); EEG.pnts = 1000; EEG.trials = 1; EEG.chanlocs = chanlocs; EEG.icawinv = [ DATA DATA ]; EEG.icaweights = zeros(size([ DATA DATA ]))'; EEG.icasphere = zeros(size(DATA,1), size(DATA,1)); %EEG = eeg_checkset(EEG); EEG.icaact = EEG.icaweights*EEG.icasphere*EEG.data(:,:); EEG.icaact = reshape( EEG.icaact, size(EEG.icaact,1), size(EEG.data,2), size(EEG.data,3)); % uses mutlifit to fit dipoles % ---------------------------- EEG = pop_multifit(EEG, [1:ncomps], varargin{:}); % process outputs % --------------- dipoles = EEG.dipfit.model; if isfield(dipoles, 'active') dipoles = rmfield(dipoles, 'active'); end; if isfield(dipoles, 'select') dipoles = rmfield(dipoles, 'select'); end; model = EEG.dipfit; if isfield(model, 'model') model = rmfield(model, 'model'); end; return;
github
lcnbeapp/beapp-master
pop_dipfit_batch.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/pop_dipfit_batch.m
2,342
utf_8
349fbd140a3ba8c11fce24b8db9fa20c
% pop_dipfit_batch() - interactively do batch scan of all ICA components % with a single dipole % Function deprecated. Use pop_dipfit_gridsearch() % instead % % Usage: % >> OUTEEG = pop_dipfit_batch( INEEG ); % pop up interactive window % >> OUTEEG = pop_dipfit_batch( INEEG, comps ); % >> OUTEEG = pop_dipfit_batch( INEEG, comps, xgrid, ygrid, zgrid, thresh ) % % Inputs: % INEEG - input dataset % comps - [integer array] component indices % xgrid - [float array] x-grid. Default is 10 elements between % -1 and 1. % ygrid - [float array] y-grid. Default is 10 elements between % -1 and 1. % zgrid - [float array] z-grid. Default is 10 elements between % -1 and 1. % threshold - [float] threshold in percent. Default 40. % % Outputs: % OUTEEG output dataset % % Authors: Robert Oostenveld, SMI/FCDC, Nijmegen 2003 % Arnaud Delorme, SCCN, La Jolla 2003 % SMI, University Aalborg, Denmark http://www.smi.auc.dk/ % FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl/ % Copyright (C) 2003 Robert Oostenveld, SMI/FCDC [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [OUTEEG, com] = pop_dipfit_batch( varargin ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin<1 help pop_dipfit_batch; return else disp('Warning: pop_dipfit_manual is outdated. Use pop_dipfit_nonlinear instead'); [OUTEEG, com] = pop_dipfit_gridsearch( varargin{:} ); end;
github
lcnbeapp/beapp-master
dipfit_nonlinear.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/dipfit_nonlinear.m
4,979
utf_8
74c08245e5fcd0c004b5c7b3357238cf
% dipfit_nonlinear() - perform nonlinear dipole fit on one of the components % to improve the initial dipole model. Only selected dipoles % will be fitted. % % Usage: % >> EEGOUT = dipfit_nonlinear( EEGIN, optarg) % % Inputs: % ... % % Optional inputs are specified in key/value pairs and can be: % ... % % Output: % ... % % Author: Robert Oostenveld, SMI/FCDC, Nijmegen 2003 % Thanks to Nicolas Robitaille for his help on the CTF MEG % implementation % SMI, University Aalborg, Denmark http://www.smi.auc.dk/ % FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl % Copyright (C) 2003 Robert Oostenveld, SMI/FCDC [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [EEGOUT] = dipfit_nonlinear( EEG, varargin ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert the optional arguments into a configuration structure that can be % understood by FIELDTRIPs dipolefitting function if nargin>2 cfg = struct(varargin{:}); else help dipfit_nonlinear return end % specify the FieldTrip DIPOLEFITTING configuration cfg.model = 'moving'; cfg.gridsearch = 'no'; if ~isfield(cfg, 'nonlinear') % if this flag is set to 'no', only the dipole moment will be fitted cfg.nonlinear = 'yes'; end % add some additional settings from EEGLAB to the configuration tmpchanlocs = EEG.chanlocs; cfg.channel = { tmpchanlocs(EEG.dipfit.chansel).labels }; if isfield(EEG.dipfit, 'vol') cfg.vol = EEG.dipfit.vol; elseif isfield(EEG.dipfit, 'hdmfile') cfg.hdmfile = EEG.dipfit.hdmfile; else error('no head model in EEG.dipfit') end if isfield(EEG.dipfit, 'elecfile') & ~isempty(EEG.dipfit.elecfile) cfg.elecfile = EEG.dipfit.elecfile; end if isfield(EEG.dipfit, 'gradfile') & ~isempty(EEG.dipfit.gradfile) cfg.gradfile = EEG.dipfit.gradfile; end % set up the initial dipole model based on the one in the EEG structure cfg.dip.pos = EEG.dipfit.model(cfg.component).posxyz; cfg.dip.mom = EEG.dipfit.model(cfg.component).momxyz'; cfg.dip.mom = cfg.dip.mom(:); % convert the EEGLAB data structure into a structure that looks as if it % was computed using FIELDTRIPs componentanalysis function comp = eeglab2fieldtrip(EEG, 'componentanalysis', 'dipfit'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Added code to handle CTF data with multipleSphere head model % % This code is copy-pasted in dipfit_gridSearch, dipfit_nonlinear % % The flag .isMultiSphere is used by dipplot % % Nicolas Robitaille, January 2007. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Do some trick to force fieldtrip to use the multiple sphere model if strcmpi(EEG.dipfit.coordformat, 'CTF') cfg = rmfield(cfg, 'channel'); comp = rmfield(comp, 'elec'); cfg.gradfile = EEG.dipfit.chanfile; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % END % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fit the dipoles to the ICA component(s) of interest using FIELDTRIPs % dipolefitting function currentPath = pwd; ptmp = which('ft_prepare_vol_sens'); ptmp = fileparts(ptmp); if isempty(ptmp), error('Path to "forward" folder of Fieldtrip missing'); end; cd(fullfile(ptmp, 'private')); try, source = ft_dipolefitting(cfg, comp); catch, cd(currentPath); lasterr error(lasterr); end; cd(currentPath); % reformat the output dipole sources into EEGLABs data structure EEG.dipfit.model(cfg.component).posxyz = source.dip.pos; EEG.dipfit.model(cfg.component).momxyz = reshape(source.dip.mom, 3, length(source.dip.mom)/3)'; EEG.dipfit.model(cfg.component).diffmap = source.Vmodel - source.Vdata; EEG.dipfit.model(cfg.component).sourcepot = source.Vmodel; EEG.dipfit.model(cfg.component).datapot = source.Vdata; EEG.dipfit.model(cfg.component).rv = source.dip.rv; %EEG.dipfit.model(cfg.component).rv = sum((source.Vdata - source.Vmodel).^2) / sum( source.Vdata.^2 ); EEGOUT = EEG;
github
lcnbeapp/beapp-master
adjustcylinder2.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/adjustcylinder2.m
2,197
utf_8
34ff5cb12c3fc11a2456e7d82aedd980
% adjustcylinder() - Adjust 3d object coordinates to match a pair of points % % Usage: % >> [x y z] = adjustcylinder( x, y, z, pos1, pos2); % % Inputs: % x,y,z - 3-D point coordinates % pos1 - position of first point [x y z] % pos2 - position of second point [x y z] % % Outputs: % x,y,z - updated 3-D point coordinates % % Author: Arnaud Delorme, CNL / Salk Institute, 30 Mai 2003 % Copyright (C) 2003 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 [x, y, z] = adjustcylinder2( h, pos1, pos2); % figure; plot3(x(2,:),y(2,:),z(2,:)); [ x(2,:)' y(2,:)' z(2,:)'] % stretch z coordinates to match for vector length % ------------------------------------------------ dist = sqrt(sum((pos1-pos2).^2)); z = get(h, 'zdata'); zrange = max(z(:)) - min(z(:)); set(h, 'zdata', get(h, 'zdata') /zrange*dist); % rotate in 3-D to match vector angle [0 0 1] -> vector angle) % only have to rotate in the x-z and y-z plane % -------------------------------------------- vectrot = [ pos2(1)-pos1(1) pos2(2)-pos1(2) pos2(3)-pos1(3)]; [thvect phivect] = cart2sph( vectrot(1), vectrot(2), vectrot(3) ); rotatematlab(h, [0 0 1], thvect/pi*180, [0 0 0]); rotatematlab(h, [thvect+pi/2 0]/pi*180, (pi/2-phivect)/pi*180, [0 0 0]); x = get(h, 'xdata') + pos1(1); y = get(h, 'ydata') + pos1(2); z = get(h, 'zdata') + pos1(3); set(h, 'xdata', x); set(h, 'ydata', y); set(h, 'zdata', z); return;
github
lcnbeapp/beapp-master
pop_dipfit_settings.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/dipfit2.3/pop_dipfit_settings.m
20,001
utf_8
7ef22305183621c09beb2691d0250fd9
% pop_dipfit_settings() - select global settings for dipole fitting through a pop up window % % Usage: % >> OUTEEG = pop_dipfit_settings ( INEEG ); % pop up window % >> OUTEEG = pop_dipfit_settings ( INEEG, 'key1', 'val1', 'key2', 'val2' ... ) % % Inputs: % INEEG input dataset % % Optional inputs: % 'hdmfile' - [string] file containing a head model compatible with % the Fieldtrip dipolefitting() function ("vol" entry) % 'mrifile' - [string] file containing an anatomical MR head image. % The MRI must be normalized to the MNI brain. See the .mat % files used by the sphere and boundary element models % (For instance, select the sphere model and study 'EEG.dipfit'). % If SPM2 software is installed, dipfit will be able to read % most MRI file formats for plotting purposes (.mnc files, etc...). % To plot dipoles in a subject MRI, first normalize the MRI % to the MNI brain using SPM2. % 'coordformat' - ['MNI'|'Spherical'] Coordinates returned by the selected % head model. May be MNI coordinates or spherical coordinates % (For spherical coordinates, the head radius is assumed to be 85 mm. % 'chanfile' - [string] template channel locations file. (This function will % check whether your channel locations file is compatible with % your selected head model). % 'chansel' - [integer vector] indices of channels to use for dipole fitting. % {default: all} % 'coord_transform' - [float array] Talairach transformation matrix for % aligning the dataset channel locations to the selected % head model. % 'electrodes' - [integer array] indices of channels to include % in the dipole model. {default: all} % Outputs: % OUTEEG output dataset % % Author: Arnaud Delorme, SCCN, La Jolla 2003- % Robert Oostenveld, SMI/FCDC, Nijmegen 2003 % MEG flag: % 'gradfile' - [string] file containing gradiometer locations % ("gradfile" parameter in Fieldtrip dipolefitting() function) % SMI, University Aalborg, Denmark http://www.smi.auc.dk/ % FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl % Copyright (C) 2003 [email protected], Arnaud Delorme, SCCN, La Jolla 2003-2005 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [OUTEEG, com] = pop_dipfit_settings ( EEG, varargin ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin < 1 help pop_dipfit_settings; return; end; if ~plugin_askinstall('Fieldtrip-lite', 'ft_sourceanalysis'), return; end; OUTEEG = EEG; com = ''; % get the default values and filenames dipfitdefs; if nargin < 2 if isstr(EEG) % setmodel tmpdat = get(gcf, 'userdata'); chanfile = tmpdat.chanfile; tmpdat = tmpdat.template_models; tmpval = get(findobj(gcf, 'tag', 'listmodels'), 'value'); set(findobj(gcf, 'tag', 'model'), 'string', char(tmpdat(tmpval).hdmfile)); set(findobj(gcf, 'tag', 'coord'), 'value' , fastif(strcmpi(tmpdat(tmpval).coordformat,'MNI'),2, ... fastif(strcmpi(tmpdat(tmpval).coordformat,'CTF'),3,1))); set(findobj(gcf, 'tag', 'mri' ), 'string', char(tmpdat(tmpval).mrifile)); set(findobj(gcf, 'tag', 'meg'), 'string', char(tmpdat(tmpval).chanfile)); set(findobj(gcf, 'tag', 'coregcheckbox'), 'value', 0); if tmpval < 3, set(findobj(gcf, 'userdata', 'editable'), 'enable', 'off'); else, set(findobj(gcf, 'userdata', 'editable'), 'enable', 'on'); end; if tmpval == 3, set(findobj(gcf, 'tag', 'headstr'), 'string', 'Subject CTF head model file (default.htm)'); set(findobj(gcf, 'tag', 'mristr'), 'string', 'Subject MRI (coregistered with CTF head)'); set(findobj(gcf, 'tag', 'chanstr'), 'string', 'CTF Res4 file'); set(findobj(gcf, 'tag', 'manualcoreg'), 'enable', 'off'); set(findobj(gcf, 'userdata', 'coreg'), 'enable', 'off'); else, set(findobj(gcf, 'tag', 'headstr'), 'string', 'Head model file'); set(findobj(gcf, 'tag', 'mristr'), 'string', 'MRI file'); set(findobj(gcf, 'tag', 'chanstr'), 'string', 'Model template channel locations file'); set(findobj(gcf, 'tag', 'manualcoreg'), 'enable', 'on'); set(findobj(gcf, 'userdata', 'coreg'), 'enable', 'on'); end; tmpl = tmpdat(tmpval).coord_transform; set(findobj(gcf, 'tag', 'coregtext'), 'string', ''); set(findobj(gcf, 'tag', 'coregcheckbox'), 'value', 0); [allkeywordstrue transform] = lookupchantemplate(chanfile, tmpl); if allkeywordstrue, set(findobj(gcf, 'tag', 'coregtext'), 'string', char(vararg2str({ transform }))); if isempty(transform) set(findobj(gcf, 'tag', 'coregcheckbox'), 'value', 1); else set(findobj(gcf, 'tag', 'coregcheckbox'), 'value', 0); end; end; return; end; % detect DIPFIT1.0x structure % --------------------------- if isfield(EEG.dipfit, 'vol') str = [ 'Dipole information structure from DIPFIT v1.02 detected.' ... 'Keep or erase the old dipole information including dipole locations? ' ... 'In either case, a new dipole model can be constructed.' ]; tmpButtonName=questdlg2( strmultiline(str, 60), 'Old DIPFIT structure', 'Keep', 'Erase', 'Keep'); if strcmpi(tmpButtonName, 'Keep'), return; end; elseif isfield(EEG.dipfit, 'hdmfile') % detect previous DIPFIT structure % -------------------------------- str = [ 'Dipole information and settings are present in the dataset. ' ... 'Keep or erase this information?' ]; tmpButtonName=questdlg2( strmultiline(str, 60), 'Old DIPFIT structure', 'Keep', 'Erase', 'Keep'); if strcmpi(tmpButtonName, 'Keep'), return; end; end; % define the callbacks for the buttons % ------------------------------------- cb_selectelectrodes = [ 'tmplocs = EEG.chanlocs; tmp = select_channel_list({tmplocs.label}, ' ... 'eval(get(findobj(gcbf, ''tag'', ''elec''), ''string'')));' ... 'set(findobj(gcbf, ''tag'', ''elec''), ''string'',[''['' num2str(tmp) '']'']); clear tmplocs;' ]; % did not work cb_selectelectrodes = 'tmplocs = EEG.chanlocs; set(findobj(gcbf, ''tag'', ''elec''), ''string'', int2str(pop_chansel({tmplocs.labels}))); clear tmplocs;'; cb_volmodel = [ 'tmpdat = get(gcbf, ''userdata'');' ... 'tmpind = get(gcbo, ''value'');' ... 'set(findobj(gcbf, ''tag'', ''radii''), ''string'', num2str(tmpdat{tmpind}.r,3));' ... 'set(findobj(gcbf, ''tag'', ''conduct''), ''string'', num2str(tmpdat{tmpind}.c,3));' ... 'clear tmpdat tmpind;' ]; cb_changeradii = [ 'tmpdat = get(gcbf, ''userdata'');' ... 'tmpdat.vol.r = str2num(get(gcbo, ''string''));' ... 'set(gcf, ''userdata'', tmpdat)' ]; cb_changeconduct = [ 'tmpdat = get(gcbf, ''userdata'');' ... 'tmpdat.vol.c = str2num(get(gcbo, ''string''));' ... 'set(gcf, ''userdata'', tmpdat)' ]; cb_changeorigin = [ 'tmpdat = get(gcbf, ''userdata'');' ... 'tmpdat.vol.o = str2num(get(gcbo, ''string''));' ... 'set(gcf, ''userdata'', tmpdat)' ]; % cb_fitelec = [ 'if get(gcbo, ''value''),' ... % ' set(findobj(gcbf, ''tag'', ''origin''), ''enable'', ''off'');' ... % 'else' ... % ' set(findobj(gcbf, ''tag'', ''origin''), ''enable'', ''on'');' ... % 'end;' ]; valmodel = 1; userdata = []; if isfield(EEG.chaninfo, 'filename') if ~isempty(findstr(lower(EEG.chaninfo.filename), 'standard-10-5-cap385')), valmodel = 1; end; if ~isempty(findstr(lower(EEG.chaninfo.filename), 'standard_1005')), valmodel = 2; end; end; geomvert = [3 1 1 1 1 1 1 1 1 1 1]; geomhorz = { [1 2] [1] [1 1.3 0.5 0.5 ] [1 1.3 0.9 0.1 ] [1 1.3 0.5 0.5 ] [1 1.3 0.5 0.5 ] [1 1.3 0.5 0.5 ] [1 1.3 0.5 0.5 ] [1] [1] [1] }; % define each individual graphical user element comhelp1 = [ 'warndlg2(strvcat(''The two default head models are in ''standard_BEM'' and ''standard_BESA'''',' ... ''' sub-folders in the DIPFIT2 plugin folder, and may be modified there.''), ''Model type'');' ]; comhelp3 = [ 'warndlg2(strvcat(''Any MR image normalized to the MNI brain model may be used for plotting'',' ... '''(see the DIPFIT 2.0 tutorial for more information)''), ''Model type'');' ]; comhelp2 = [ 'warndlg2(strvcat(''The template location file associated with the head model'',' ... '''you are using must be entered (see tutorial).''), ''Template location file'');' ]; commandload1 = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ... 'if filename ~=0,' ... ' set(findobj(''parent'', gcbf, ''tag'', ''model''), ''string'', [ filepath filename ]);' ... 'end;' ... 'clear filename filepath tagtest;' ]; commandload2 = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ... 'if filename ~=0,' ... ' set(findobj(''parent'', gcbf, ''tag'', ''meg''), ''string'', [ filepath filename ]);' ... 'end;' ... 'clear filename filepath tagtest;' ]; commandload3 = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ... 'if filename ~=0,' ... ' set(findobj(''parent'', gcbf, ''tag'', ''mri''), ''string'', [ filepath filename ]);' ... 'end;' ... 'clear filename filepath tagtest;' ]; cb_selectcoreg = [ 'tmpmodel = get( findobj(gcbf, ''tag'', ''model''), ''string'');' ... 'tmploc2 = get( findobj(gcbf, ''tag'', ''meg'') , ''string'');' ... 'tmploc1 = get( gcbo, ''userdata'');' ... 'tmptransf = get( findobj(gcbf, ''tag'', ''coregtext''), ''string'');' ... '[tmp tmptransf] = coregister(tmploc1{1}, tmploc2, ''mesh'', tmpmodel,' ... ' ''transform'', str2num(tmptransf), ''chaninfo1'', tmploc1{2}, ''helpmsg'', ''on'');' ... 'if ~isempty(tmptransf), set( findobj(gcbf, ''tag'', ''coregtext''), ''string'', num2str(tmptransf)); end;' ... 'clear tmpmodel tmploc2 tmploc1 tmp tmptransf;' ]; setmodel = [ 'pop_dipfit_settings(''setmodel'');' ]; dipfitdefs; % contains template_model templatenames = { template_models.name }; elements = { ... { 'style' 'text' 'string' [ 'Head model (click to select)' 10 '' ] } ... { 'style' 'listbox' 'string' strvcat(templatenames{:}) ... 'callback' setmodel 'value' valmodel 'tag' 'listmodels' } { } ... { 'style' 'text' 'string' '________' 'tag' 'headstr' } ... { 'style' 'edit' 'string' '' 'tag' 'model' 'userdata' 'editable' 'enable' 'off'} ... { 'style' 'pushbutton' 'string' 'Browse' 'callback' commandload1 'userdata' 'editable' 'enable' 'off' } ... { 'style' 'pushbutton' 'string' 'Help' 'callback' comhelp1 } ... { 'style' 'text' 'string' 'Output coordinates' } ... { 'style' 'popupmenu' 'string' 'spherical (head radius 85 mm)|MNI|CTF' 'tag' 'coord' ... 'value' 1 'userdata' 'editable' 'enable' 'off'} ... { 'style' 'text' 'string' 'Click to select' } { } ... { 'style' 'text' 'string' '________' 'tag' 'mristr' } ... { 'style' 'edit' 'string' '' 'tag' 'mri' } ... { 'style' 'pushbutton' 'string' 'Browse' 'callback' commandload3 } ... { 'style' 'pushbutton' 'string' 'Help' 'callback' comhelp3 } ... { 'style' 'text' 'string' '________', 'tag', 'chanstr' } ... { 'style' 'edit' 'string' '' 'tag' 'meg' 'userdata' 'editable' 'enable' 'off'} ... { 'style' 'pushbutton' 'string' 'Browse' 'callback' commandload2 'userdata' 'editable' 'enable' 'off'} ... { 'style' 'pushbutton' 'string' 'Help' 'callback' comhelp2 } ... { 'style' 'text' 'string' 'Co-register chan. locs. with head model' 'userdata' 'coreg' } ... { 'style' 'edit' 'string' '' 'tag' 'coregtext' 'userdata' 'coreg' } ... { 'style' 'pushbutton' 'string' 'Manual Co-Reg.' 'tag' 'manualcoreg' 'callback' cb_selectcoreg 'userdata' { EEG.chanlocs,EEG.chaninfo } } ... { 'style' 'checkbox' 'string' 'No Co-Reg.' 'tag' 'coregcheckbox' 'value' 0 'userdata' 'coreg' } ... { 'style' 'text' 'string' 'Channels to omit from dipole fitting' } ... { 'style' 'edit' 'string' '' 'tag' 'elec' } ... { 'style' 'pushbutton' 'string' 'List' 'callback' cb_selectelectrodes } { } ... { } ... { 'style' 'text' 'string' 'Note: For EEG, check that the channel locations are on the surface of the head model' } ... { 'style' 'text' 'string' '(To do this: ''Set head radius'' to about 85 in the channel editor).' } ... }; % plot GUI and protect parameters % ------------------------------- userdata.template_models = template_models; if isfield(EEG.chaninfo, 'filename') userdata.chanfile = lower(EEG.chaninfo.filename); else userdata.chanfile = ''; end; optiongui = { 'geometry', geomhorz, 'uilist', elements, 'helpcom', 'pophelp(''pop_dipfit_settings'')', ... 'title', 'Dipole fit settings - pop_dipfit_settings()', ... 'userdata', userdata, 'geomvert', geomvert 'eval' 'pop_dipfit_settings(''setmodel'');' }; [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 GUI inputs % ----------------- options = {}; options = { options{:} 'hdmfile' result{2} }; options = { options{:} 'coordformat' fastif(result{3} == 2, 'MNI', fastif(result{3} == 1, 'Spherical', 'CTF')) }; options = { options{:} 'mrifile' result{4} }; options = { options{:} 'chanfile' result{5} }; if ~result{7}, options = { options{:} 'coord_transform' str2num(result{6}) }; end; options = { options{:} 'chansel' setdiff(1:EEG.nbchan, str2num(result{8})) }; else options = varargin; end g = finputcheck(options, { 'hdmfile' 'string' [] ''; 'mrifile' 'string' [] ''; 'chanfile' 'string' [] ''; 'chansel' 'integer' [] [1:EEG.nbchan]; 'electrodes' 'integer' [] []; 'coord_transform' 'real' [] []; 'coordformat' 'string' { 'MNI','spherical','CTF' } 'MNI' }); if isstr(g), error(g); end; OUTEEG = rmfield(OUTEEG, 'dipfit'); OUTEEG.dipfit.hdmfile = g.hdmfile; OUTEEG.dipfit.mrifile = g.mrifile; OUTEEG.dipfit.chanfile = g.chanfile; OUTEEG.dipfit.chansel = g.chansel; OUTEEG.dipfit.coordformat = g.coordformat; OUTEEG.dipfit.coord_transform = g.coord_transform; if ~isempty(g.electrodes), OUTEEG.dipfit.chansel = g.electrodes; end; % removing channels with no coordinates % ------------------------------------- [tmpeloc labels Th Rd indices] = readlocs(EEG.chanlocs); if length(indices) < length(EEG.chanlocs) disp('Warning: Channels removed from dipole fitting no longer have location coordinates!'); OUTEEG.dipfit.chansel = intersect( OUTEEG.dipfit.chansel, indices); end; % checking electrode configuration % -------------------------------- if 0 disp('Checking the electrode configuration'); tmpchan = readlocs(OUTEEG.dipfit.chanfile); [tmp1 ind1 ind2] = intersect( lower({ tmpchan.labels }), lower({ OUTEEG.chanlocs.labels })); if isempty(tmp1) disp('No channel labels in common found between template and dataset channels'); if ~isempty(findstr(OUTEEG.dipfit.hdmfile, 'BESA')) disp('Use the channel editor to fit a head sphere to your channel locations.'); disp('Check for inconsistency in dipole info.'); else disp('Results using standard BEM model are INACCURATE when the chan locations are not on the head surface!'); end; else % common channels: performing best transformation TMP = OUTEEG; elec1 = eeglab2fieldtrip(TMP, 'elec'); elec1 = elec1.elec; TMP.chanlocs = tmpchan; elec2 = eeglab2fieldtrip(TMP, 'elec'); elec2 = elec2.elec; cfg.elec = elec1; cfg.template = elec2; cfg.method = 'warp'; elec3 = electrodenormalize(cfg); % convert back to EEGLAB format OUTEEG.chanlocs = struct( 'labels', elec3.label, ... 'X' , mat2cell(elec3.pnt(:,1)'), ... 'Y' , mat2cell(elec3.pnt(:,2)'), ... 'Z' , mat2cell(elec3.pnt(:,3)') ); OUTEEG.chanlocs = convertlocs(OUTEEG.chanlocs, 'cart2all'); end; end; com = sprintf('%s = pop_dipfit_settings( %s, %s);', inputname(1), inputname(1), vararg2str(options)); % test for wrong parameters % ------------------------- function bool = test_wrong_parameters(hdl) coreg1 = get( findobj( hdl, 'tag', 'coregtext') , 'string' ); coreg2 = get( findobj( hdl, 'tag', 'coregcheckbox'), 'value' ); meg = get( findobj( hdl, 'tag', 'coord'), 'value' ); bool = 0; if meg == 3, return; end; if coreg2 == 0 & isempty(coreg1) bool = 1; warndlg2(strvcat('You must co-register your channel locations', ... 'with the head model (Press buttun, "Manual Co-Reg".', ... 'and follow instructions); To bypass co-registration,', ... 'check the checkbox " No Co-Reg".'), 'Error'); end;
github
lcnbeapp/beapp-master
eegplugin_cleanline.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/eegplugin_cleanline.m
2,154
utf_8
00012f272d3f6c21e4885de250f6e0ef
% eegplugin_cleanline() - EEGLAB plugin for removing line noise % % Usage: % >> eegplugin_cleanline(fig, trystrs, catchstrs); % % Inputs: % fig - [integer] EEGLAB figure % trystrs - [struct] "try" strings for menu callbacks. % catchstrs - [struct] "catch" strings for menu callbacks. % % Notes: % This plugins consist of the following Matlab files: % % Create a plugin: % For more information on how to create an EEGLAB plugin see the % help message of eegplugin_besa() or visit http://www.sccn.ucsd.edu/eeglab/contrib.html % % % See also: pop_cleanline(), cleanline() % Copyright (C) 2011 Tim Mullen, 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 vers = eegplugin_cleanline(fig, trystrs, catchstrs) vers = 'cleanline'; if nargin < 3 error('eegplugin_cleanline requires 3 arguments'); end; % add folder to path % ------------------ if exist('cleanline', 'file') p = which('eegplugin_cleanline.m'); p = p(1:findstr(p,'eegplugin_cleanline.m')-1); addpath(genpath(p)); end; % find import data menu % --------------------- menu = findobj(fig, 'tag', 'tools'); % menu callbacks % -------------- comcnt = [ trystrs.no_check '[EEG LASTCOM] = pop_cleanline(EEG);' catchstrs.new_and_hist ]; % create menus % ------------ uimenu( menu, 'label', 'CleanLine', 'callback', comcnt,'separator', 'on', 'position',length(get(menu,'children'))+1);
github
lcnbeapp/beapp-master
cleanline.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/cleanline.m
27,439
utf_8
db2d5fa2e56fb92bf9e5165018650537
function [EEG, Sorig, Sclean, f, amps, freqs, g] = cleanline(varargin) % Mandatory Information % -------------------------------------------------------------------------------------------------- % EEG EEGLAB data structure % -------------------------------------------------------------------------------------------------- % % Optional Information % -------------------------------------------------------------------------------------------------- % LineFrequencies: Line noise frequencies to remove % Input Range : Unrestricted % Default value: 60 120 % Input Data Type: real number (double) % % ScanForLines: Scan for line noise % This will scan for the exact line frequency in a narrow range around the specified LineFrequencies % Input Range : Unrestricted % Default value: 1 % Input Data Type: boolean % % LineAlpha: p-value for detection of significant sinusoid % Input Range : [0 1] % Default value: 0.01 % Input Data Type: real number (double) % % Bandwidth: Bandwidth (Hz) % This is the width of a spectral peak for a sinusoid at fixed frequency. As such, this defines the % multi-taper frequency resolution. % Input Range : Unrestricted % Default value: 1 % Input Data Type: real number (double) % % SignalType: Type of signal to clean % Cleaned ICA components will be backprojected to channels. If channels are cleaned, ICA activations % are reconstructed based on clean channels. % Possible values: 'Components','Channels' % Default value : 'Components' % Input Data Type: string % % ChanCompIndices: IDs of Chans/Comps to clean % Input Range : Unrestricted % Default value: 1:152 % Input Data Type: any evaluable Matlab expression. % % SlidingWinLength: Sliding window length (sec) % Default is the epoch length. % Input Range : [0 4] % Default value: 4 % Input Data Type: real number (double) % % SlidingWinStep: Sliding window step size (sec) % This determines the amount of overlap between sliding windows. Default is window length (no % overlap). % Input Range : [0 4] % Default value: 4 % Input Data Type: real number (double) % % SmoothingFactor: Window overlap smoothing factor % A value of 1 means (nearly) linear smoothing between adjacent sliding windows. A value of Inf means % no smoothing. Intermediate values produce sigmoidal smoothing between adjacent windows. % Input Range : [1 Inf] % Default value: 100 % Input Data Type: real number (double) % % PaddingFactor: FFT padding factor % Signal will be zero-padded to the desired power of two greater than the sliding window length. The % formula is NFFT = 2^nextpow2(SlidingWinLen*(PadFactor+1)). e.g. For SlidingWinLen = 500, if PadFactor = -1, we % do not pad; if PadFactor = 0, we pad the FFT to 512 points, if PadFactor=1, we pad to 1024 points etc. % Input Range : [-1 Inf] % Default value: 2 % Input Data Type: real number (double) % % ComputeSpectralPower: Visualize Original and Cleaned Spectra % Original and clean spectral power will be computed and visualized at end % Input Range : Unrestricted % Default value: true % Input Data Type: boolean % % NormalizeSpectrum: Normalize log spectrum by detrending (not generally recommended) % Input Range : Unrestricted % Default value: 0 % Input Data Type: boolean % % VerboseOutput: Produce verbose output % Input Range : [true false] % Default value: true % Input Data Type: boolean % % PlotFigures: Plot Individual Figures % This will generate figures of F-statistic, spectrum, etc for each channel/comp while processing % Input Range : Unrestricted % Default value: 0 % Input Data Type: boolean % % -------------------------------------------------------------------------------------------------- % Output Information % -------------------------------------------------------------------------------------------------- % EEG Cleaned EEG dataset % Sorig Original multitaper spectrum for each component/channel % Sclean Cleaned multitaper spectrum for each component/channel % f Frequencies at which spectrum is estimated in Sorig, Sclean % amps Complex amplitudes of sinusoidal lines for each % window (line time-series for window i can be % reconstructed by creating a sinudoid with frequency f{i} and complex % amplitude amps{i}) % freqs Exact frequencies at which lines were removed for % each window (cell array) % g Parameter structure. Function call can be % replicated exactly by calling >> cleanline(EEG,g); % % Usage Example: % EEG = pop_cleanline(EEG, 'Bandwidth',2,'ChanCompIndices',[1:EEG.nbchan], ... % 'SignalType','Channels','ComputeSpectralPower',true, ... % 'LineFrequencies',[60 120] ,'NormalizeSpectrum',false, ... % 'LineAlpha',0.01,'PaddingFactor',2,'PlotFigures',false, ... % 'ScanForLines',true,'SmoothingFactor',100,'VerboseOutput',1, ... % 'SlidingWinLength',EEG.pnts/EEG.srate,'SlidingWinStep',EEG.pnts/EEG.srate); % % See Also: % pop_cleanline() % Author: Tim Mullen, SCCN/INC/UCSD Copyright (C) 2011 % Date: Nov 20, 2011 % % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 3 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA EEG = arg_extract(varargin,'EEG',[],[]); if isempty(EEG) EEG = eeg_emptyset; end if ~isempty(EEG.icawinv); defSigType = {'Components','Channels'}; else defSigType = {'Channels'}; end g = arg_define([0 1], varargin, ... arg_norep('EEG',mandatory), ... arg({'linefreqs','LineFrequencies'},[60 120],[],'Line noise frequencies to remove.'),... arg({'scanforlines','ScanForLines'},true,[],'Scan for line noise. This will scan for the exact line frequency in a narrow range around the specified LineFrequencies'),... arg({'p','LineAlpha','alpha'},0.01,[0 1],'p-value for detection of significant sinusoid'), ... arg({'bandwidth','Bandwidth'},2,[],'Bandwidth (Hz). This is the width of a spectral peak for a sinusoid at fixed frequency. As such, this defines the multi-taper frequency resolution.'), ... arg({'sigtype','SignalType','chantype'},defSigType{1},defSigType,'Type of signal to clean. Cleaned ICA components will be backprojected to channels. If channels are cleaned, ICA activations are reconstructed based on clean channels.'), ... arg({'chanlist','ChanCompIndices','ChanComps'},sprintf('1:%d',EEG.nbchan),[1 EEG.nbchan],'Indices of Channels/Components to clean.','type','expression'),... arg({'winsize','SlidingWinLength'},fastif(EEG.trials==1,4,EEG.pnts/EEG.srate),[0 EEG.pnts/EEG.srate],'Sliding window length (sec). Default for epoched data is the epoch length. Default for continuous data is 4 seconds'), ... arg({'winstep','SlidingWinStep'},fastif(EEG.trials==1,1,EEG.pnts/EEG.srate),[0 EEG.pnts/EEG.srate],'Sliding window step size (sec). This determines the amount of overlap between sliding windows. Default for epoched data is window length (no overlap). Default for continuous data is 1 second.'), ... arg({'tau','SmoothingFactor'},100,[1 Inf],'Window overlap smoothing factor. A value of 1 means (nearly) linear smoothing between adjacent sliding windows. A value of Inf means no smoothing. Intermediate values produce sigmoidal smoothing between adjacent windows.'), ... arg({'pad','PaddingFactor'},2,[-1 Inf],'FFT padding factor. Signal will be zero-padded to the desired power of two greater than the sliding window length. The formula is NFFT = 2^nextpow2(SlidingWinLen*(PadFactor+1)). e.g. For N = 500, if PadFactor = -1, we do not pad; if PadFactor = 0, we pad the FFT to 512 points, if PadFactor=1, we pad to 1024 points etc.'), ... arg({'computepower','ComputeSpectralPower'},true,[],'Visualize Original and Cleaned Spectra. Original and clean spectral power will be computed and visualized at end'), ... arg({'normSpectrum','NormalizeSpectrum'},false,[],'Normalize log spectrum by detrending. Not generally recommended.'), ... arg({'verb','VerboseOutput','VerbosityLevel'},true,[],'Produce verbose output.'), ... arg({'plotfigures','PlotFigures'},false,[],'Plot Individual Figures. This will generate figures of F-statistic, spectrum, etc for each channel/comp while processing') ... ); if any(g.chanlist > fastif(strcmpi(g.sigtype,'channels'),EEG.nbchan,size(EEG.icawinv,1))) error('''ChanCompIndices'' contains indices of channels or components that are not present in the dataset!'); end arg_toworkspace(g); % defaults [Sorig, Sclean, f, amps, freqs] = deal([]); hasica = ~isempty(EEG.icawinv); % set up multi-taper parameters hbw = g.bandwidth/2; % half-bandwidth params.tapers = [hbw, g.winsize, 1]; params.Fs = EEG.srate; params.g.pad = g.pad; movingwin = [g.winsize g.winstep]; % NOTE: params.tapers = [W, T, p] where: % T==frequency range in Hz over which the spectrum is maximally concentrated % on either side of a center frequency (half of the spectral bandwidth) % W==time resolution (seconds) % p is used for num_tapers = 2TW-p (usually p=1). SlidingWinLen = movingwin(1)*params.Fs; if params.g.pad>=0 NFFT = 2^nextpow2(SlidingWinLen*(params.g.pad+1)); else NFFT = SlidingWinLen; end if isempty(EEG.data) && isempty(EEG.icaact) fprintf('Hey! Where''s your EEG data?\n'); return; end if g.verb fprintf('\n\nWelcome to the CleanLine line noise removal toolbox!\n'); fprintf('CleanLine is written by Tim Mullen ([email protected]) and uses multi-taper routines modified from the Chronux toolbox (www.chronux.org)\n'); fprintf('\nTsk Tsk, you''ve allowed your data to get very dirty!\n'); fprintf('Let''s roll up our sleeves and do some cleaning!\n'); fprintf('Today we''re going to be cleaning your %s\n',g.sigtype); if EEG.trials>1 if g.winsize~=g.winstep fprintf('\n[!] Yikes! I noticed you have multiple trials, but you''ve selected overlapping windows.\n'); fprintf(' This probably means one or more of your windows will span two trials, which can be bad news (discontinuities)!\n'); resp = input('\n Are you sure you want to continue? (''y'',''n''): ','s'); if ~strcmpi(resp,'y') return; end end if g.winsize > EEG.pnts/EEG.srate fprintf('\n[!] Yikes! I noticed you have multiple trials, but your window length (%0.4g sec) is greater than the epoch length (%0.4g sec).\n',g.winsize,EEG.pnts/EEG.srate); fprintf(' This means each window will span multiple trials, which can be bad news!\n'); fprintf(' Ideally, your windows should be less than or equal to the epoch length\n'); resp = input('\n Are you sure you want to continue? (''y'',''n''): ','s'); if ~strcmpi(resp,'y') return; end end if g.winsize~=g.winstep || g.winsize > EEG.pnts/EEG.srate fprintf('\nFine, have it your way, but if results are sub-optimal try selecting window length and step size so your windows don''t span multiple trials.\n\n'); pause(2); end end ndiff = rem(EEG.pnts,(g.winsize*EEG.srate)); if ndiff>0 fprintf('\n[!] Please note that because the selected window length does not divide the data length, \n'); fprintf(' %0.4g seconds of data at the end of the record will not be cleaned.\n\n',ndiff/EEG.srate); end fprintf('Multi-taper parameters follow:\n'); fprintf('\tTime-bandwidth product:\t %0.4g\n',hbw*g.winsize); fprintf('\tNumber of tapers:\t %0.4g\n',2*hbw*g.winsize-1); fprintf('\tNumber of FFT points:\t %d\n',NFFT); if ~isempty(g.linefreqs) fprintf('I''m going try to remove lines at these frequencies: [%s] Hz\n',strtrim(num2str(g.linefreqs))); if g.scanforlines fprintf('I''m going to scan the range +/-%0.4g Hz around each of the above frequencies for the exact line frequency.\n',params.tapers(1)); fprintf('I''ll do this by selecting the frequency that maximizes Thompson''s F-statistic above a threshold of p=%0.4g.\n',g.p); end else fprintf('You didn''t specify any lines (Hz) to remove, so I''ll try to find them using Thompson''s F-statistic.\n'); fprintf('I''ll use a p-value threshold of %0.4g.\n',g.p) end fprintf('\nOK, now stand back and let The Maid show you how it''s done!\n\n'); end EEGLAB_backcolor = getbackcolor; if g.plotfigures % plot the overlap smoothing function overlap = g.winsize-g.winstep; toverlap = -overlap/2:(1/EEG.srate):overlap/2; % specify the smoothing function foverlap = 1-1./(1+exp(-g.tau.*toverlap/overlap)); % define some colours yellow = [255, 255, 25]/255; red = [255 0 0]/255; % plot the figure figure('color',EEGLAB_backcolor); axis([-g.winsize+overlap/2 g.winsize-overlap/2 0 1]); set(gca,'ColorOrder',[0 0 0; 0.7 0 0.8; 0 0 1],'fontsize',11); hold on h(1)=hlp_vrect([-g.winsize+overlap/2 -overlap/2], 'yscale',[0 1],'patchProperties',{'FaceColor',yellow, 'FaceAlpha',1,'EdgeColor','none','EdgeAlpha',0.5}); h(2)=hlp_vrect([overlap/2 g.winsize-overlap/2], 'yscale',[0 1],'patchProperties',{'FaceColor',red, 'FaceAlpha',1,'EdgeColor','none','EdgeAlpha',0.5}); h(3)=hlp_vrect([-overlap/2 overlap/2], 'yscale',[0 1],'patchProperties',{'FaceColor',(yellow+red)/2,'FaceAlpha',1,'EdgeColor','none','EdgeAlpha',0.5}); plot(toverlap,foverlap,'linewidth',2); plot(toverlap,1-foverlap,'linewidth',1,'linestyle','--'); hold off; xlabel('Time (sec)'); ylabel('Smoothing weight'); title({'Plot of window overlap smoothing function vs. time',['Smoothing factor is \g.tau = ' num2str(g.tau)]}); legend(h,{'Window 1','Window 2','Overlap'}); end if hasica && isempty(EEG.icaact) EEG = eeg_checkset(EEG,'ica'); end k=0; for ch=g.chanlist if g.verb, fprintf('Cleaning %s %d...\n',fastif(strcmpi(g.sigtype,'Components'),'IC','Chan'),ch); end % extract data as [chans x frames*trials] if strcmpi(g.sigtype,'components') data = squeeze(EEG.icaact(ch,:)); else data = squeeze(EEG.data(ch,:)); end if g.plotfigures % estimate the sinusoidal lines [Fval sig f] = ftestmovingwinc(data,movingwin,params,g.p); % plot the F-statistics [F T] = meshgrid(f,1:size(Fval,1)); figure('color',EEGLAB_backcolor); subplot(311); surf(F,T,Fval); shading interp; caxis([0 prctile(Fval(:),99)]); axis tight sigplane = ones(size(Fval))*sig; hold on; surf(F,T,sigplane,'FaceColor','b','FaceAlpha',0.5); xlabel('Frequency'); ylabel('Window'); zlabel('F-value'); title({[sprintf('%s %d: ',fastif(strcmpi(g.sigtype,'components'),'IC ','Chan '), ch) 'Thompson F-statistic for sinusoid'],sprintf('Black plane is p<%0.4g thresh',g.p)}); shadowplot x shadowplot y axcopy(gca); subplot(312); plot(F,mean(Fval,1),'k'); axis tight hold on plot(get(gca,'xlim'),[sig sig],'r:','linewidth',2); xlabel('Frequency'); ylabel('Thompson F-stat'); title('F-statistic averaged over windows'); legend('F-val',sprintf('p=%0.4g',g.p)); hold off axcopy(gca); end if g.plotfigures subplot(313) end % DO THE MAGIC! [datac,datafit,amps,freqs]=rmlinesmovingwinc(data,movingwin,g.tau,params,g.p,fastif(g.plotfigures,'y','n'),g.linefreqs,fastif(g.scanforlines,params.tapers(1),[])); % append to clean dataset any remaining samples that were not cleaned % due to sliding window and step size not dividing the data length ndiff = length(data)-length(datac); if ndiff>0 datac(end:end+ndiff) = data(end-ndiff:end); end if g.plotfigures axis tight legend('original','cleaned'); xlabel('Frequency (Hz)'); ylabel('Power (dB)'); title(sprintf('Power spectrum for %s %d',fastif(strcmpi(g.sigtype,'components'),'IC','Chan'),ch)); axcopy(gca); end if g.computepower k = k+1; if g.verb, fprintf('Computing spectral power...\n'); end [Sorig(k,:) f] = mtspectrumsegc(data,movingwin(1),params); [Sclean(k,:) f] = mtspectrumsegc(datac,movingwin(1),params); if g.verb && ~isempty(g.linefreqs) fprintf('Average noise reduction: '); for fk=1:length(g.linefreqs) [dummy fidx] = min(abs(f-g.linefreqs(fk))); fprintf('%0.4g Hz: %0.4g dB %s ',f(fidx),10*log10(Sorig(k,fidx))-10*log10(Sclean(k,fidx)),fastif(fk<length(g.linefreqs),'|','')); end fprintf('\n'); end if ch==g.chanlist(1) % First run, so allocate memory for remaining spectra in % Nchans x Nfreqs spectral matrix Sorig = cat(1,Sorig,zeros(length(g.chanlist)-1,length(f))); Sclean = cat(1,Sclean,zeros(length(g.chanlist)-1,length(f))); end end if strcmpi(g.sigtype,'components') EEG.icaact(ch,:) = datac'; else EEG.data(ch,:) = datac'; end end if g.computepower if g.verb, fprintf('Converting spectra to dB...\n'); end % convert to log spectrum Sorig = 10*log10(Sorig); Sclean = 10*log10(Sclean); if g.normSpectrum if g.verb, fprintf('Normalizing log spectra...\n'); end % normalize spectrum by standarization % Sorig = (Sorig-repmat(mean(Sorig,2),1,size(Sorig,2)))./repmat(std(Sorig,[],2),1,size(Sorig,2)); % Sclean = (Sclean-repmat(mean(Sclean,2),1,size(Sclean,2)))./repmat(std(Sclean,[],2),1,size(Sclean,2)); % normalize the spectrum by detrending Sorig = detrend(Sorig')'; Sclean = detrend(Sclean')'; end end if strcmpi(g.sigtype,'components') if g.verb, fprintf('Backprojecting cleaned components to channels...\n'); end try EEG.data = EEG.icawinv*EEG.icaact(1:end,:); catch e % low memory, so back-project channels one by one if g.verb, fprintf('Insufficient memory for fast back-projection. Back-projecting each channel individually...\n'); end EEG.data = zeros(size(EEG.icaact)); for k=1:size(EEG.icaact,1) EEG.data(k,:) = EEG.icawinv(:,k)*EEG.icaact(k,:); end end EEG.data = reshape(EEG.data,EEG.nbchan,EEG.pnts*EEG.trials); elseif hasica if g.verb, fprintf('Recomputing component activations from cleaned channel data...\n'); end EEG.icaact = []; EEG = eeg_checkset(EEG,'ica'); end function BACKCOLOR = getbackcolor BACKCOLOR = 'w'; try, icadefs; catch, end;
github
lcnbeapp/beapp-master
para_dataflow.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/para_dataflow.m
15,079
utf_8
bdf197e6b019efdde172f215e4e5933b
function result = para_dataflow(varargin) % Generic Signal Processing -> Feature Extraction -> Machine Learning BCI framework. % Result = para_dataflow(FilterSetup, FeatureExtractionArguments, FeatureExtractionSetup, MachineLearningSetup, DialogSetup, ForwardedParameters...) % % Most BCI paradigms are implemented as a sequence of three major stages: Signal Processing, Feature Extraction and Machine Learning (see also bci_train). % The Signal Processing stage operates on time series (plus meta-data), represented as EEGLAB datasets, and may contain multiple sub-stages, which together % form a filter graph. The data passed from node to node in this graph is either continuous or epoched EEGLAB datasets, and may contain rich annotations, such as % channel locations, ICA decompositions, DIPFIT models, etc. The nodes are filter components which are shared among many paradigms, and most of them % are found in filters/flt_* and dataset_ops/set_*. For almost all paradigms, a default order of these stages can be defined, because several filters % can be arbitrarily ordered w.r.t. each other (linear operators), and most other filters make sense only when executed before or after certain other stages. % The default signal processing pipeline is implemented in flt_pipeline; its parameters allow to selectively enable processing stages. Paradims derived from % para_dataflow usually set their own defaults for flt_pipeline (i.e., enable and configure various stages by default), which can be further modified by the user. % % The simplest filter components are stateless (such as a surface laplacian filter) and operate on each sample individually, while other filters are % stateful (and have a certain "memory" of past data), such as FIR and IIR filters. Some of the stateful filters are time-variant (such as signal % standardization) and some of those are adaptive (such as ICA). Some adaptive filters may be unsupervised, and others may depend on the target variable. % The majority of filters is causal (i.e. does not need data from future samples to compute the transformed version of some sample) and can therefore be % applied online, while some filters are non-causal (e.g., the signal envelope and zero-phase FIR filter), and can only be used for offline analyses % (e.g. for neuroscience). Finally, most filters operate on continuous data, while some filters operate on epoched/segmented data (such as time window % selection or fourier transform). All of these filter components are written against a unified framework. % % Following the Signal Processing stage, most paradigms implement the Feature Extraction stage (especially those paradigms which do not implement % adaptive statistical signal processing), in which signals are transformed into sets of feature vectors. At this stage, signal meta-data is % largely stripped off. The feature extraction performed by some paradigms is non-adaptive (such as windowed means or log-variance), while it is % adaptive (and usually supervised) for others (e.g., CSP). Feature vectors can be viewed as (labeled) points in a high-dimensional space, the % feature space, which serves as the representation on which the last stage, the machine learning, operates. % % The machine learning stage defines a standardized computational framework: it is practically always adaptive, and thus involves a 'learn' case % and a 'predict' case. In the learning case, labeled sets of feature vectors are received, processed & analyzed, their distribution w.r.t. the % target variables (labels) is estimated, and a predictive model (or prediction function) incorporating these relations is generated. In the prediction case, % the previously computed predictive model is applied to individual feature vectors to predict their label/target value (or a probability distribution % over possible label/target values). % % Likewise, a paradigm can be applied to data in a 'learn' mode, in which data is received, feature-extraction is possibly adapted, and a predictive model % is computed (which is an arbitrary data structure that incorporates the state of all adaptive stages), and a 'predict' mode, in which a previously % computed predictive model is used to map data to a prediction by sending it through all of the paradigm's stages. Finally, a paradigm has a 'preprocess' % mode, in which all the signal processing steps take place. Separating the preprocessing from the other two stages leaves more control to the framework % (bci_train, onl_predict), for example to control the granularity (block size) of data that is fed through the processing stages, buffering, % caching of intermediate results, partitioning of datasets (for cross-validation, nested cross-validation and other resampling techniques) and % various optimizations (such as common subexpression elimination and lazy evaluation). This functionality is invisible to the paradigms. % % The function para_dataflow represents a small sub-framework for the convenient implementation of paradigms that adhere to this overall three-stage system. % Paradigms may implement their functionality by calling into para_dataflow, setting some of its parameters in order to customize its standard system. % Therefore, para_dataflow exposes a set of named parameters for each of the three stages. For signal processing, it exposes all the parameters of % flt_pipeline, the default signal processing pipeline, allowing paradims to enable various pipeline stages without having to care about their relative % order or efficient execution. For feature extraction, it exposes the 'featureextract' and 'featureadapt' parameters, which are function handles which % implement the feature extraction and feature adaption (if any) step of this processing phase; the 'featurevote' parameter specifies whether the 'featureadapt' % stages requires a voting procedure in cases where more than two classes are present in the data. Very few constraints are imposed on the type of % inputs, outputs and internal processing of these functions, or on the type of data that is passed through it (EEGLAB datasets or STUDY sets, for example). % For the machine learning stage, the 'learner' parameter of ml_train is exposed, allowing to specify one of the ml_train*** / ml_predict*** functions % for learning and prediction, respectively. See ml_train for more explanations of the options. % % Paradigms making use of para_dataflow typically pass all user-specified parameters down to para_dataflow (so that the user has maximum control with no % interference from the paradigm), and set up their own characteristic parameterization of para_dataflow as defaults for these user parameters. % % In: % Parameters... : parameters of the paradigm: % * 'op' : one of the modes in which the paradigm can be applied to data: % * 'preprocess', to pre-process the InputSet according to the paradigm (and parameters) % * 'learn', to learn a predictive model from a pre-processed InputSet (and parameters) % * 'predict', to make predictions given a pre-processed InputSet and a predictive model % % * 'data' : some data (usually an EEGLAB dataset) % % if op == 'preprocess': % * all parameters of flt_pipeline can be supplied for preprocessing; (defaults: no defaults are imposed by para_dataflow itself) % % if op == 'learn' % * 'featureadapt': the adaption stage of the feature extraction; function_handle, % receives the preprocessed data and returns a model of feature-extraction parameters (default: returns []) % * 'featureextract': the feature extraction stage; function_handle, receives the preprocessed data and % the model from the featureadapt stage, and returns a NxF array of N feature vectors (for F features) % (default: vectorizes each data epoch) % * 'featurevote': true if the 'featureadapt' function supports only two classes, so that voting is necessary when three % or more classes are in the data (default: false) % * 'learner': parameter of ml_train; defines the machine-learning step that is applied to the features (default: 'lda') % % if op == 'predict' % * 'model': the predictive model (as produced during the learning) % % Out: % Result : depends on the op; % * if 'preprocess', this is the preprocessed dataset % * if 'learn', this is the learned model % * if 'predict', this is the predictions produced by the model, given the data % % Notes: % Pre-processing is usually a purely symbolic operation (i.e. symbolic data processing steps are added to the data expression); the framework % evaluates this expression (and potentially transforms it prior to that, for example for cross-validation) and passes the evaluated expression % back to the paradigm for 'learning' and/or 'prediction' modes. % % Name: % Data-Flow Framework % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-04-29 if length(varargin) > 1 && iscell(varargin{1}) % the paradigm is being invoked via a user function (which sets flt_defaults, etc.) [flt_defaults,fex_declaration,fex_defaults,ml_defaults,dialog_default] = deal(varargin{1:5}); varargin = varargin(6:end); else % the paradigm is being invoked directly [flt_defaults,fex_declaration,fex_defaults,ml_defaults,dialog_default] = deal({}); end cfg = arg_define(varargin, ... ... % core arguments for the paradigm framework (passed by the framework) arg_norep('op',[],{'preprocess','learn','predict'},'Operation to execute on the data. Preprocess the raw data, learn a predictive model, or predict outputs given a model.'), ... arg_norep('data',[],[],'Data to be processed by the paradigm.'), ... arg_norep('model',[],[],'Model according to which to predict.'), ... ... % signal processing arguments (sourced from flt_pipeline) arg_sub({'flt','SignalProcessing'},flt_defaults,@flt_pipeline,'Signal processing stages. These can be enabled, disabled and configured for the given paradigm. The result of this stage flows into the feature extraction stage','cat','Signal Processing'), ... ... % arguments for the feature-extraction plugins (passed by the user paradigms) arg_sub({'fex','FeatureExtraction'},{},fex_declaration,'Parameters for the feature-extraction stage.','cat','Feature Extraction'), ... ... % feature-extraction plugin definitions (passed by the user paradigms) arg_sub({'plugs','PluginFunctions'},fex_defaults,{ ... arg({'adapt','FeatureAdaptor'},@default_feature_adapt,[],'The adaption function of the feature extraction. Function_handle, receives the preprocessed data, an options struct (with feature-extraction), and returns a model (which may just re-represent options).'),... arg({'extract','FeatureExtractor'},@default_feature_extract,[],'The feature extraction function. Function_handle, receives the preprocessed data and the model from the featureadapt stage, and returns a NxF array of N feature vectors (for F features).'), ... arg({'vote','FeatureAdaptorNeedsVoting'},false,[],'Feature-adaption function requires voting. Only relevant if the data contains three or more classes.') ... },'The feature-extraction functions','cat','Feature Extraction'), ... ... % machine learning arguments (sourced from ml_train) arg_sub({'ml','MachineLearning'},ml_defaults,@ml_train,'Machine learning stage of the paradigm. Operates on the feature vectors that are produced by the feature-extraction stage.','cat','Machine Learning'), ... ... % configuration dialog layout arg({'arg_dialogsel','ConfigLayout'},dialog_default,[],'Parameters displayed in the config dialog. Cell array of parameter names to display (dot-notation allowed); blanks are translated into empty rows in the dialog. Referring to a structure argument lists all parameters of that struture, except if it is a switchable structure - in this case, a pulldown menu with switch options is displayed.','type','cellstr','shape','row')); % map all of cfg's fields into the function's workspace, for convenience arg_toworkspace(cfg,true); switch op case 'preprocess' % apply default signal processing result = flt_pipeline('signal',data,flt); case 'learn' classes = unique(set_gettarget(data)); if ~(plugs.vote && numel(classes) > 2) % learn a model [result.featuremodel,result.predictivemodel] = learn_model(data,cfg); else % binary stage and more than two classes: learn 1-vs-1 models for voting result.classes = classes; for i=1:length(classes) for j=i+1:length(classes) [result.voting{i,j}.featuremodel,result.voting{i,j}.predictivemodel] = learn_model(exp_eval(set_picktrials(data,'rank',{i,j})),cfg); end end end result.plugs = plugs; case 'predict' if ~isfield(model,'voting') % predict given the extracted features and the model result = ml_predict(model.plugs.extract(data,model.featuremodel), model.predictivemodel); else % 1-vs-1 voting is necessary, construct the aggregate result trialcount = exp_eval(set_partition(data,[])); result = {'disc' , zeros(trialcount,length(model.classes)), model.classes}; % vote, adding up the probabilities from each vote for i=1:length(model.classes) for j=i+1:length(model.classes) outcome = ml_predict(model.plugs.extract(data,model.voting{i,j}.featuremodel), model.voting{i,j}.predictivemodel); result{2}(:,[i j]) = result{2}(:,[i j]) + outcome{2}; end end % renormalize probabilities result{2} = result{2} ./ repmat(sum(result{2},2),1,size(result{2},2)); end end function [featuremodel,predictivemodel] = learn_model(data,cfg) % adapt the feature extractor switch nargin(cfg.plugs.adapt) case 1 featuremodel = cfg.plugs.adapt(data); case 2 featuremodel = cfg.plugs.adapt(data,cfg.fex); otherwise featuremodel = cfg.plugs.adapt(data,cfg.fex,cfg); end % extract features & learn a predictive model predictivemodel = ml_train('data',{cfg.plugs.extract(data,featuremodel),set_gettarget(data)},'learner',cfg.ml.learner); function mdl = default_feature_adapt(data,args) mdl = args; function data = default_feature_extract(data,mdl) data = squeeze(reshape(data.data,[],1,size(data.data,3)))';
github
lcnbeapp/beapp-master
env_showmenu.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/environment/env_showmenu.m
16,401
utf_8
e922dbf8b0926a434e2012cc7cf148ee
function env_showmenu(varargin) % Links the BCILAB menu into another menu, or creates a new root menu if necessary. % env_showmenu(Options...) % % In: % Options... : optional name-value pairs; names are: % 'parent': parent menu to link into % % 'shortcuts': whether to enable keyboard shortcuts % % 'forcenew': whether to force creation of a new menu % % Example: % % bring up the BCILAB main menu if it had been closed % env_showmenu; % % See also: % env_startup % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-10-29 % parse options... hlp_varargin2struct(varargin,'parent',[], 'shortcuts',true,'forcenew',false); % check if we're an EEGLAB plugin folders = hlp_split(fileparts(mfilename('fullpath')),filesep); within_eeglab = length(folders) >= 5 && strcmp(folders{end-3},'plugins') && ~isempty(strfind(folders{end-4},'eeglab')); % don't open the menu twice if ~isempty(findobj('Tag','bcilab_menu')) && ~forcenew return; end if isempty(parent) %#ok<NODEF> if within_eeglab && ~forcenew % try to link into the EEGLAB main menu try toolsmenu = findobj(0,'tag','tools'); if ~isempty(toolsmenu) parent = uimenu(toolsmenu, 'Label','BCILAB'); set(toolsmenu,'Enable','on'); end catch disp('Unable to link BCILAB menu into EEGLAB menu.'); end end if isempty(parent) % create new root menu, if no parent from_left = 100; from_top = 150; width = 500; height = 1; % determine position on primary monitor import java.awt.GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); gd = ge.getDefaultScreenDevice(); scrheight = gd.getDisplayMode().getHeight(); pos = [from_left, scrheight-from_top, width, height]; % create figure figtitle = ['BCILAB ' env_version ' (on ' hlp_hostname ')']; parent = figure('DockControls','off','NumberTitle','off','Name',figtitle,'Resize','off','MenuBar','none','Position',pos,'Tag','bcilab_toolwnd'); end end % Data Source menu source = uimenu(parent, 'Label','Data Source','Tag','bcilab_menu'); uimenu(source,'Label','Load recording(s)...','Accelerator',char(shortcuts*'l'),'Callback','gui_loadset'); wspace = uimenu(source,'Label','Workspace','Separator','on'); uimenu(wspace,'Label','Load...','Callback','io_loadworkspace'); uimenu(wspace,'Label','Save...','Callback','io_saveworkspace'); uimenu(wspace,'Label','Clear...','Callback','clear'); uimenu(source,'Label','Run script...','Separator','on','Callback',@invoke_script); if isdeployed uimenu(source,'Label','Quit','Separator','on','Callback','exit'); end % Offline Analysis menu offline = uimenu(parent, 'Label','Offline Analysis'); uimenu(offline,'Label','New approach...','Accelerator',char(shortcuts*'n'),'Callback','gui_newapproach'); uimenu(offline,'Label','Modify approach...','Accelerator',char(shortcuts*'m'),'Callback','gui_configapproach([],true);'); uimenu(offline,'Label','Review/edit approach...','Accelerator',char(shortcuts*'r'),'Callback','gui_reviewapproach([],true);'); uimenu(offline,'Label','Save approach...','Accelerator',char(shortcuts*'s'),'Callback','gui_saveapproach'); uimenu(offline,'Label','Train new model...','Accelerator',char(shortcuts*'t'),'Callback','gui_calibratemodel','Separator','on'); uimenu(offline,'Label','Apply model to data...','Accelerator',char(shortcuts*'a'),'Callback','gui_applymodel'); uimenu(offline,'Label','Visualize model...','Accelerator',char(shortcuts*'v'),'Callback','gui_visualizemodel'); uimenu(offline,'Label','Run batch analysis...','Accelerator',char(shortcuts*'b'),'Callback','gui_batchanalysis','Separator','on'); uimenu(offline,'Label','Review results...','Accelerator',char(shortcuts*'i'),'Callback','gui_selectresults','Separator','on'); % Online Analysis menu online = uimenu(parent,'Label','Online Analysis'); pipe = uimenu(online,'Label','Process data within...'); read = uimenu(online,'Label','Read input from...'); write = uimenu(online,'Label','Write output to...'); cm_read = uicontextmenu('Tag','bcilab_cm_read'); cm_write = uicontextmenu('Tag','bcilab_cm_write'); % for each plugin sub-directory... dirs = dir(env_translatepath('functions:/online_plugins')); for d={dirs(3:end).name} % find all files, their names, identifiers, and function handles files = dir(env_translatepath(['functions:/online_plugins/' d{1} '/run_*.m'])); names = {files.name}; idents = cellfun(@(n)n(1:end-2),names,'UniformOutput',false); % for each entry... for f=1:length(idents) try if ~exist(idents{f},'file') && ~isdeployed addpath(env_translatepath(['functions:/online_plugins/' d{1}])); end % get properties... props = arg_report('properties',str2func(idents{f})); % get category if strncmp(idents{f},'run_read',8); cats = [read,cm_read]; elseif strncmp(idents{f},'run_write',9); cats = [write,cm_write]; elseif strncmp(idents{f},'run_pipe',8); cats = pipe; end if isfield(props,'name') % add menu entry for cat=cats uimenu(cat,'Label',[props.name '...'],'Callback',['arg_guidialog(@' idents{f} ');'],'Enable','on'); end else warning('env_showmenu:missing_guiname','The online plugin %s does not declare a GUI name; ignoring...',idents{f}); end catch disp(['Could not integrate the online plugin ' idents{f} '.']); end end end uimenu(online,'Label','Clear all online processing','Callback','onl_clear','Separator','on'); % Settings menu settings = uimenu(parent, 'Label','Settings'); uimenu(settings,'Label','Directory settings...','Callback','gui_configpaths'); uimenu(settings,'Label','Cache settings...','Callback','gui_configcache'); uimenu(settings,'Label','Cluster settings...','Callback','gui_configcluster'); uimenu(settings,'Label','Clear memory cache','Callback','env_clear_memcaches','Separator','on'); % Help menu helping = uimenu(parent,'Label','Help'); uimenu(helping,'Label','BCI Paradigms...','Callback','env_doc code/paradigms'); uimenu(helping,'Label','Filters...','Callback','env_doc code/filters'); uimenu(helping,'Label','Machine Learning...','Callback','env_doc code/machine_learning'); scripting = uimenu(helping,'Label','Scripting'); uimenu(scripting,'Label','File input/output...','Callback','env_doc code/io'); uimenu(scripting,'Label','Dataset editing...','Callback','env_doc code/dataset_editing'); uimenu(scripting,'Label','Offline scripting...','Callback','env_doc code/offline_analysis'); uimenu(scripting,'Label','Online scripting...','Callback','env_doc code/online_analysis'); uimenu(scripting,'Label','BCILAB environment...','Callback','env_doc code/environment'); uimenu(scripting,'Label','Cluster handling...','Callback','env_doc code/parallel'); uimenu(scripting,'Label','Keywords...','Separator','on','Callback','env_doc code/keywords'); uimenu(scripting,'Label','Helpers...','Callback','env_doc code/helpers'); uimenu(scripting,'Label','Internals...','Callback','env_doc code/utils'); authoring = uimenu(helping,'Label','Plugin authoring'); uimenu(authoring,'Label','Argument declaration...','Callback','env_doc code/arguments'); uimenu(authoring,'Label','Expression functions...','Callback','env_doc code/expressions'); uimenu(authoring,'Label','Online processing...','Callback','env_doc code/online_analysis'); uimenu(helping,'Label','About...','Separator','on','Callback',@about); uimenu(helping,'Label','Save bug report...','Separator','on','Callback','io_saveworkspace([],true)'); uimenu(helping,'Label','File bug report...','Callback','arg_guidialog(@env_bugreport);'); % toolbar (if not linked into the EEGLAB menu) if ~(within_eeglab && ~forcenew) global tracking; cluster_requested = isfield(tracking,'cluster_requested') && ~isempty(tracking.cluster_requested); cluster_requested = hlp_rewrite(cluster_requested,false,'off',true,'on'); ht = uitoolbar(parent,'HandleVisibility','callback'); uipushtool(ht,'TooltipString','Load recording(s)',... 'CData',load_icon('bcilab:/resources/icons/file_open.png'),... 'HandleVisibility','callback','ClickedCallback','gui_loadset'); uipushtool(ht,'TooltipString','New approach',... 'CData',load_icon('bcilab:/resources/icons/approach_new.png'),... 'HandleVisibility','callback','ClickedCallback','gui_newapproach','Separator','on'); uipushtool(ht,'TooltipString','Load Approach',... 'CData',load_icon('bcilab:/resources/icons/approach_load.png'),... 'HandleVisibility','callback','ClickedCallback',@load_approach); uipushtool(ht,'TooltipString','Save approach',... 'CData',load_icon('bcilab:/resources/icons/approach_save.png'),... 'HandleVisibility','callback','ClickedCallback','gui_saveapproach'); uipushtool(ht,'TooltipString','Modify approach',... 'CData',load_icon('bcilab:/resources/icons/approach_edit.png'),... 'HandleVisibility','callback','ClickedCallback','gui_configapproach([],true);'); uipushtool(ht,'TooltipString','Review/edit approach',... 'CData',load_icon('bcilab:/resources/icons/approach_review.png'),... 'HandleVisibility','callback','ClickedCallback','gui_reviewapproach([],true);'); uipushtool(ht,'TooltipString','Train new model',... 'CData',load_icon('bcilab:/resources/icons/model_new.png'),... 'HandleVisibility','callback','ClickedCallback','gui_calibratemodel','Separator','on'); uipushtool(ht,'TooltipString','Load Model',... 'CData',load_icon('bcilab:/resources/icons/model_load.png'),... 'HandleVisibility','callback','ClickedCallback',@load_model); uipushtool(ht,'TooltipString','Save Model',... 'CData',load_icon('bcilab:/resources/icons/model_save.png'),... 'HandleVisibility','callback','ClickedCallback','gui_savemodel'); uipushtool(ht,'TooltipString','Apply model to data',... 'CData',load_icon('bcilab:/resources/icons/model_apply.png'),... 'HandleVisibility','callback','ClickedCallback','gui_applymodel'); uipushtool(ht,'TooltipString','Visualize model',... 'CData',load_icon('bcilab:/resources/icons/model_visualize.png'),... 'HandleVisibility','callback','ClickedCallback','gui_visualizemodel'); uipushtool(ht,'TooltipString','Run batch analysis',... 'CData',load_icon('bcilab:/resources/icons/batch_analysis.png'),... 'HandleVisibility','callback','ClickedCallback','gui_batchanalysis'); uipushtool(ht,'TooltipString','Read input from (online)',... 'CData',load_icon('bcilab:/resources/icons/online_in.png'),... 'HandleVisibility','callback','Separator','on','ClickedCallback',@click_read); uipushtool(ht,'TooltipString','Write output to (online)',... 'CData',load_icon('bcilab:/resources/icons/online_out.png'),... 'HandleVisibility','callback','ClickedCallback',@click_write); uipushtool(ht,'TooltipString','Clear online processing',... 'CData',load_icon('bcilab:/resources/icons/online_clear.png'),... 'HandleVisibility','callback','ClickedCallback','onl_clear'); uitoggletool(ht,'TooltipString','Request cluster availability',... 'CData',load_icon('bcilab:/resources/icons/acquire_cluster.png'),'HandleVisibility','callback','Separator','on','State',cluster_requested,'OnCallback','env_acquire_cluster','OffCallback','env_release_cluster'); uipushtool(ht,'TooltipString','About BCILAB',... 'CData',load_icon('bcilab:/resources/icons/help.png'),'HandleVisibility','callback','Separator','on','ClickedCallback',@about); end if within_eeglab && forcenew mainmenu = findobj('Tag','EEGLAB'); % make the EEGLAB menu current again if ~isempty(mainmenu) figure(mainmenu); end end function about(varargin) infotext = strvcat(... 'BCILAB is an open-source toolbox for Brain-Computer Interfacing research.', ... 'It is being developed by Christian Kothe at the Swartz Center for Computational Neuroscience,',... 'Institute for Neural Computation (University of California San Diego).', ... ' ',... 'Development of this software was supported by the Army Research Laboratories under', ... 'Cooperative Agreement Number W911NF-10-2-0022, as well as by a gift from the Swartz Foundation.', ... ' ',... 'The design was inspired by the preceding PhyPA toolbox, written by C. Kothe and T. Zander', ... 'at the Berlin Institute of Technology, Chair Human-Machine Systems.', ... ' ',... 'BCILAB connects to the following toolboxes/libraries:', ... '* AWS SDK (Amazon)', ... '* Amica (SCCN/UCSD)', ... '* Chronux (Mitra Lab, Cold Spring Harbor)', ... '* CVX (Stanford)', ... '* DAL (U. Tokyo)', ... '* DataSuite (SCCN/UCSD)', ... '* EEGLAB (SCCN/UCSD)', ... '* BCI2000import (www.bci2000.org)', ... '* Logreg (Jan Drugowitsch)', ... '* FastICA (Helsinki UT)', ... '* glm-ie (Max Planck Institute for Biological Cybernetics, Tuebingen)', ... '* glmnet (Stanford)', ... '* GMMBayes (Helsinki UT)', ... '* HKL (Francis Bach, INRIA)', ... '* KernelICA (Francis Bach, Berkeley)', ... '* LIBLINEAR (National Taiwan University)', ... '* matlabcontrol (Joshua Kaplan)', ... '* mlUnit (Thomas Dohmke)', ... '* NESTA (Caltech)', ... '* OSC (Andy Schmeder) and LibLO (Steve Harris)', ... '* PROPACK (Stanford)', ... '* PropertyGrid (Levente Hunyadi)', ... '* SparseBayes (Vector Anomaly)', ... '* SVMlight (Thorsten Joachims)', ... '* SVMperf (Thorsten Joachims)', ... '* Talairach (UTHSCSA)', ... '* Time-frequency toolbox (CRNS / Rice University)', ... '* t-SNE (TU Delft)', ... '* VDPGM (Kenichi Kurihara)'); %#ok<REMFF1> warndlg2(infotext,'About'); function click_read(varargin) % pop up a menu when clicking the "read input from" toolbar button tw = findobj('tag','bcilab_toolwnd'); cm = findobj('tag','bcilab_cm_read'); tpos = get(tw,'Position'); ppos = get(0,'PointerLocation'); set(cm,'Position',ppos - tpos(1:2), 'Visible', 'on'); set(cm,'Position',ppos - tpos(1:2), 'Visible', 'on'); function click_write(varargin) % pop up a menu when clicking the "write output to" toolbar button tw = findobj('tag','bcilab_toolwnd'); cm = findobj('tag','bcilab_cm_write'); tpos = get(tw,'Position'); ppos = get(0,'PointerLocation'); set(cm,'Position',ppos - tpos(1:2), 'Visible', 'on'); set(cm,'Position',ppos - tpos(1:2), 'Visible', 'on'); % run a script function invoke_script(varargin) [filename,filepath] = uigetfile({'*.m', 'MATLAB file'},'Select script to run',env_translatepath('bcilab:/')); if ~isnumeric(filename) run_script([filepath filename],true); end % load a toolbar icon function cols = load_icon(filename) [cols,palette,alpha] = imread(env_translatepath(filename)); if ~isempty(palette) error('This function does not handle palettized icons.'); end cls = class(cols); cols = double(cols); cols = cols/double(intmax(cls)); cols([alpha,alpha,alpha]==0) = NaN; % load a BCI model from disk function load_model(varargin) [filename,filepath] = uigetfile({'*.mdl', 'BCI Model'},'Select BCI model to load',env_translatepath('home:/.bcilab/models')); if ~isnumeric(filename) contents = io_load([filepath filename],'-mat'); for fld=fieldnames(contents)' tmp = contents.(fld{1}); if isstruct(tmp) && isfield(tmp,'timestamp') tmp.timestamp = now; assignin('base',fld{1},tmp); end end end % load a BCI approach from disk function load_approach(varargin) [filename,filepath] = uigetfile({'*.apr', 'BCI Approach'},'Select BCI approach to load',env_translatepath('home:/.bcilab/approaches')); if ~isnumeric(filename) contents = io_load([filepath filename],'-mat'); for fld=fieldnames(contents)' tmp = contents.(fld{1}); if isstruct(tmp) && isfield(tmp,'paradigm') tmp.timestamp = now; assignin('base',fld{1},tmp); end end end
github
lcnbeapp/beapp-master
env_startup.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/environment/env_startup.m
21,807
utf_8
100127e2a96b4156d68b8af7fec6c1ef
function env_startup(varargin) % Start the BCILAB toolbox, i.e. set up global data structures and load dependency toolboxes. % env_startup(Options...) % % Does all steps necessary for loading the toolbox -- the functions bcilab.m and eegplugin_bcilab.m % are wrappers around this function which provide a higher level of convenience (configuration files % in particular). Directly calling this function is not recommended. % % In: % Options... : optional name-value pairs; allowed names are: % % --- directory settings --- % % 'data': Path where data sets are stored, used by data loading/saving routines. % (default: path/to/bcilab/userdata) % Note: this may also be a cell array of directories, in which case references % to data:/ are looked up in all of the specified directories, and the % best match is taken. % % 'store': Path in which data shall be stored. Write permissions necessary (by default % identical to the data path) % % 'temp': temp directory (for misc outputs, e.g., AMICA models and dipole fits) % (default: path/to/bcilab-temp, or path/to/cache/bcilab_temp if a cache % directory was specified) % % --- caching settings --- % % 'cache': Path where intermediate data sets are cached. Should be located on a fast % (local) drive with sufficient free capacity. % * if this is left unspecified or empty, the cache is disabled % * if this is a directory, it is used as the default cache location % * a fine-grained cache setup can be defined by specifying a cell array of % cache locations, where each cache location is a cell array of name-value % pairs, with possible names: % 'dir': directory of the cache location (e.g. '/tmp/bcilab_tmp/'), mandatory % 'time': only computations taking more than this many seconds may be stored % in this location, but if a computation takes so long that another % cache location with a higher time applies, that other location is % preferred. For example, the /tmp directory may take computations % that take at least a minute, the home directory may take % computations that take at least an hour, the shared /data/results % location of the lab may take computations that take at least 12 % hours (default: 30 seconds) % 'free': minimum amount of space to keep free on the given location, in GiB, % or, if smaller than 1, free is taken as the fraction of total % space to keep free (default: 0.1) % 'tag': arbitrary identifier for the cache location (default: 'location_i', % for the i'th location) must be a valid MATLAB struct field name, % only for display purposes % % 'mem_capacity': capacity of the memory cache (default: 2) % if this is smaller than 1, it is taken as a fraction of the total % free physical memory at startup time, otherwise it is in GB % % 'data_reuses' : estimated number of reuses of a data set being computed (default: 3) % ... depending on disk access speeds, this determines whether it makes % sense to cache the data set % % --- parallel computing settings --- % % 'parallel' : parallelization options; cell array of name-value pairs, with names: % 'engine': parallelization engine to use, can be 'local', % 'ParallelComputingToolbox', or 'BLS' (BCILAB Scheduler) % (default: 'local') % 'pool': node pool, cell array of 'host:port' strings; necessary for the % BLS scheduler (default: {'localhost:23547','localhost:23548', % ..., 'localhost:23554'}) % 'policy': scheduling policy function; necessary for the BLS scheduler % (default: 'par_reschedule_policy') % % note: Parallel processing has so far received only relatively little % testing. Please use this facility at your own risk and report % any issues (e.g., starving jobs) that you may encounter. % % 'aquire_options' : Cell array of arguments as expected by par_getworkers_ssh % (with bcilab-specific defaults for unspecified arguments) % (default: {}) % % 'worker' : whether this toolbox instance is started as a worker process or not; if % false, diary logging and GUI menus and popups are enabled. If given as a % cell array, the cell contents are passed on to the function par_worker, % which lets the toolbox act as a commandline-less worker (waiting to % receive jobs over the network) (default: false) % % --- misc settings --- % % 'menu' : create a menu bar (default: true) -- if this is set to 'separate', the BCILAB % menu will be detached from the EEGLAB menu, even if run as a plugin. % % 'autocompile' : whether to try to auto-compile mex/java files (default: true) % % Examples: % Note that env_startup is usually not being called directly; instead the bcilab.m function in the % bcilab root directory forwards its arguments (and variables declared in a config script) to this % function. % % % start BCILAB with a custom data directory, and a custom cache directory % env_startup('data','C:\Data', 'cache','C:\Data\Temp'); % % % as before, but specify multiple data paths that are being fused into a common directory view % % where possible (in case of ambiguities, the earlier directories take precedence) % env_startup('data',{'C:\Data','F:\Data2'}, 'cache','C:\Data\Temp'); % % % start BCILAB with a custom data and storage directory, and specify a cache location with some % % additional meta-data (namely: only cache there if a computation takes at least 60 seconds, and % % reserve 15GB free space % env_startup('data','/media/data', 'store','/media/data/results', 'cache',{{'dir','/tmp/tracking','time',60,'free',15}}); % % % as before, but make sure that the free space does not fall below 20% of the disk % env_startup('data','/media/data', 'store','/media/data/results', 'cache',{{'dir','/tmp/tracking','time',60,'free',0.2}}); % % % start BCILAB and set up a very big in-memory cache for working with large data sets (of 16GB) % env_startup('mem_capacity',16) % % % start BCILAB but prevent the main menu from popping up % env_startup('menu',false) % % % start BCILAB and specify which parallel computation resources to use; this assumes that the % % respective hostnames are reachable from this computer, and are running MATLAB sessions which % % execute a command similar to: cd /your/path/to/bcilab; bcilab('worker',true); par_worker; % env_startup('parallel',{'engine','BLS', 'pool',{'computer1','computer2','computer3'}} % % % % start the toolbox as a worker % env_startup('worker',true) % % % start the toolbox as worker, and pass some arguments to par_worker (making it listen on port % % 15456, using a portrange of 0, and using some custom update-checking arguments % env_startup('worker',{15456,0,'update_check',{'/data/bcilab-0.9-beta2b/build/bcilab','/mnt/remote/bcilab-build/bcilab'}}) % % See also: % env_load_dependencies, env_translatepath % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-03-28 % determine the BCILAB core directories if ~isdeployed tmpdir = path_normalize(fileparts(mfilename('fullpath'))); delims = strfind(tmpdir,filesep); base_dir = tmpdir(1:delims(end-1)); else % in deployed mode, we walk up until we find the BCILAB base directory tmpdir = pwd; delims = strfind(tmpdir,filesep); disp(['Launching from directory ' tmpdir ' ...']); for k=length(delims):-1:1 base_dir = tmpdir(1:delims(k)); if exist([base_dir filesep 'code'],'dir') success = true; %#ok<NASGU> break; end end if ~exist('success','var') error('Could not find the ''code'' directory; make sure that the binary is in a sub-directory of a full BCILAB distribution.'); end end function_dir = [base_dir 'code']; dependency_dir = [base_dir 'dependencies']; resource_dir = [base_dir 'resources']; script_dir = [base_dir 'userscripts']; build_dir = [base_dir 'build']; % add them all to the MATLAB path (except for dependencies, which are loaded separately) if ~isdeployed % remove existing BCILAB path references ea = which('env_add'); if ~isempty(ea) % get the bcilab root directory that's currently in the path bad_path = ea(1:strfind(ea,'dependencies')-2); % remove all references paths = strsplit(path,pathsep); retain = cellfun('isempty',strfind(paths,bad_path)); path(sprintf(['%s' pathsep],paths{retain})); if ~all(retain) disp(' BCILAB sub-directories have been detected in the MATLAB path, removing them.'); end end % add core function paths addpath(genpath(function_dir)); if exist(build_dir,'dir') addpath(build_dir); end evalc('addpath(genpath(script_dir))'); evalc('addpath([base_dir ''userdata''])'); % remove existing eeglab path references, if BCILAB is not itself contained as a plugin in this % EEGLAB distribution ep = which('eeglab'); if ~isempty(ep) && isempty(strfind(mfilename('fullpath'),fileparts(which('eeglab')))) paths = strsplit(path,pathsep); ep = strsplit(ep,filesep); retain = cellfun('isempty',strfind(paths,ep{end-1})); path(sprintf(['%s' pathsep],paths{retain})); if ~all(retain) disp(' The previously loaded EEGLAB path has been replaced.'); end end end if hlp_matlab_version < 706 disp('Note: Your version of MATLAB is not supported by BCILAB any more. You may try BCILAB version 0.9, which supports old MATLAB''s back to version 2006a.'); end % get options opts = hlp_varargin2struct(varargin,'data',[],'store',[],'cache',[],'temp',[],'mem_capacity',2,'data_reuses',3,'parallel',{'use','local'}, 'menu',true, 'configscript','', 'worker',false, 'autocompile',true, 'acquire_options',{}); % load all dependencies, recursively... disp('Loading BCILAB dependencies...'); env_load_dependencies(dependency_dir,opts.autocompile); if ischar(opts.worker) try disp(['Evaluating worker argument: ' opts.worker]); opts.worker = eval(opts.worker); catch disp('Failed to evaluate worker; setting it to false.'); opts.worker = false; end elseif ~isequal(opts.worker,false) fprintf('Worker was given as a %s with value %s\n',class(opts.worker),hlp_tostring(opts.worker)); end if ischar(opts.parallel) try disp(['Evaluating parallel argument: ' opts.parallel]); opts.parallel = eval(opts.parallel); catch disp('Failed to evaluate worker; setting it to empty.'); opts.parallel = {}; end end % process data directories if isempty(opts.data) opts.data = {}; end if ~iscell(opts.data) opts.data = {opts.data}; end for d = 1:length(opts.data) opts.data{d} = path_normalize(opts.data{d}); end if isempty(opts.data) || ~any(cellfun(@exist,opts.data)) opts.data = {[base_dir 'userdata']}; end % process store directory if isempty(opts.store) opts.store = opts.data{1}; end opts.store = path_normalize(opts.store); % process cache directories if isempty(opts.cache) opts.cache = {}; end if ischar(opts.cache) opts.cache = {{'dir',opts.cache}}; end if iscell(opts.cache) && ~isempty(opts.cache) && ~iscell(opts.cache{1}) opts.cache = {opts.cache}; end for d=1:length(opts.cache) opts.cache{d} = hlp_varargin2struct(opts.cache{d},'dir','','tag',['location_' num2str(d)],'time',30,'free',0.1); end % remove entries with empty dir opts.cache = opts.cache(cellfun(@(e)~isempty(e.dir),opts.cache)); for d=1:length(opts.cache) % make sure that the BCILAB cache is in its own proper sub-directory opts.cache{d}.dir = [path_normalize(opts.cache{d}.dir) filesep 'bcilab_cache']; % create the directory if necessary if ~isempty(opts.cache{d}.dir) && ~exist(opts.cache{d}.dir,'dir') try io_mkdirs([opts.cache{d}.dir filesep],{'+w','a'}); catch disp(['cache directory ' opts.cache{d}.dir ' does not exist and could not be created']); end end end % process temp directory if isempty(opts.temp) if ~isempty(opts.cache) opts.temp = [fileparts(opts.cache{1}.dir) filesep 'bcilab_temp']; else opts.temp = [base_dir(1:end-1) '-temp']; end end opts.temp = path_normalize(opts.temp); try io_mkdirs([opts.temp filesep],{'+w','a'}); catch disp(['temp directory ' opts.temp ' does not exist and could not be created.']); end % set global variables global tracking tracking.paths = struct('bcilab_path',{base_dir(1:end-1)}, 'function_path',{function_dir}, 'data_paths',{opts.data}, 'store_path',{opts.store}, 'dependency_path',{dependency_dir},'resource_path',{resource_dir},'temp_path',{opts.temp}); for d=1:length(opts.cache) location = rmfield(opts.cache{d},'tag'); % convert GiB to bytes if location.free >= 1 location.free = location.free*1024*1024*1024; end try warning off MATLAB:DELETE:Permission; % probe the cache locations... import java.io.*; % try to add a free space checker (Java File object), which we use to check the quota, etc. location.space_checker = File(opts.cache{d}.dir); filename = [opts.cache{d}.dir filesep '__probe_cache_ ' num2str(round(rand*2^32)) '__.mat']; if exist(filename,'file') delete(filename); end oldvalue = location.space_checker.getFreeSpace; testdata = double(rand(1024)); %#ok<NASGU> objinfo = whos('testdata'); % do a quick read/write test t0=tic; save(filename,'testdata'); location.writestats = struct('size',{0 objinfo.bytes},'time',{0 toc(t0)}); t0=tic; load(filename); location.readstats = struct('size',{0 objinfo.bytes},'time',{0 toc(t0)}); newvalue = location.space_checker.getFreeSpace; if exist(filename,'file') delete(filename); end % test if the space checker works, and also get some quick measurements of disk read/write speeds if newvalue >= oldvalue location = rmfield(location,'space_checker'); end % and turn the free space ratio into an absolute value if location.free < 1 location.free = location.free*location.space_checker.getTotalSpace; end catch e disp(['Could not probe cache file system speed; reason: ' e.message]); end tracking.cache.disk_paths.(opts.cache{d}.tag) = location; end if opts.mem_capacity < 1 free_mem = hlp_memavail(); tracking.cache.capacity = round(opts.mem_capacity * free_mem); if free_mem < 1024*1024*1024 sprintf('Warning: You have less than 1 GB of free memory (reserving %.0f%% = %.0fMB for data caches).\n',100*opts.mem_capacity,tracking.cache.capacity/(1024*1024)); sprintf(' This will severely impact the offline processing speed of BCILAB.\n'); sprintf(' You may force a fixed amount of cache cacpacity by assinging a value greater than 1 (in GB) to the ''mem_capacity'' variable in your bcilab_config.m.'); end else tracking.cache.capacity = opts.mem_capacity*1024*1024*1024; end tracking.cache.reuses = opts.data_reuses; tracking.cache.data = struct(); tracking.cache.sizes = struct(); tracking.cache.times = struct(); if ~isfield(tracking.cache,'disk_paths') tracking.cache.disk_paths = struct(); end % initialize stack mechanisms tracking.stack.base = struct('disable_expressions',false); % set parallelization settings tracking.parallel = hlp_varargin2struct(opts.parallel, ... 'engine','local', ... 'pool',{'localhost:23547','localhost:23548','localhost:23549','localhost:23550','localhost:23551','localhost:23552','localhost:23553','localhost:23554'}, ... 'policy','par_reschedule_policy'); tracking.acquire_options = opts.acquire_options; tracking.configscript = opts.configscript; try cd(script_dir); catch end % set up some microcache properties hlp_microcache('arg','lambda_equality','proper'); hlp_microcache('spec','group_size',5); hlp_microcache('findfunction','lambda_equality','fast','group_size',5); % show toolbox status fprintf('\n'); disp(['code is in ' function_dir]); datalocs = []; for d = opts.data datalocs = [datalocs d{1} ', ']; end %#ok<AGROW> disp(['data is in ' datalocs(1:end-2)]); disp(['results are in ' opts.store]); if ~isempty(opts.cache) fnames = fieldnames(tracking.cache.disk_paths); for f = 1:length(fnames) if f == 1 disp(['cache is in ' tracking.cache.disk_paths.(fnames{f}).dir ' (' fnames{f} ')']); else disp([' ' tracking.cache.disk_paths.(fnames{f}).dir ' (' fnames{f} ')']); end end else disp('cache is disabled'); end disp(['temp is in ' opts.temp]); fprintf('\n'); % turn off a few nasty warnings warning off MATLAB:log:logOfZero warning off MATLAB:divideByZero %#ok<RMWRN> warning off MATLAB:RandStream:ReadingInactiveLegacyGeneratorState % for GMMs.... if isequal(opts.worker,false) || isequal(opts.worker,0) % --- regular mode --- % set up logfile if ~exist([hlp_homedir filesep '.bcilab'],'dir') if ~mkdir(hlp_homedir,'.bcilab'); disp('Cannot create directory .bcilab in your home folder.'); end end tracking.logfile = env_translatepath('home:/.bcilab/logs/bcilab_console.log'); try if ~exist([hlp_homedir filesep '.bcilab' filesep 'logs'],'dir') mkdir([hlp_homedir filesep '.bcilab' filesep 'logs']); end if exist(tracking.logfile,'file') warning off MATLAB:DELETE:Permission delete(tracking.logfile); warning on MATLAB:DELETE:Permission end catch,end try diary(tracking.logfile); catch,end if ~exist([hlp_homedir filesep '.bcilab' filesep 'models'],'dir') mkdir([hlp_homedir filesep '.bcilab' filesep 'models']); end if ~exist([hlp_homedir filesep '.bcilab' filesep 'approaches'],'dir') mkdir([hlp_homedir filesep '.bcilab' filesep 'approaches']); end % create a menu if ~(isequal(opts.menu,false) || isequal(opts.menu,0)) try env_showmenu('forcenew',strcmp(opts.menu,'separate')); catch e disp('Could not open the BCILAB menu; traceback: '); env_handleerror(e); end end % display a version reminder bpath = hlp_split(env_translatepath('bcilab:/'),filesep); if ~isempty(strfind(bpath{end},'-stable')) if isdeployed disp(' This is the stable version.'); else disp(' This is the stable version - please keep this in mind when editing.'); end elseif ~isempty(strfind(bpath{end},'-devel')) if isdeployed disp(' This is the DEVELOPER version.'); else try cprintf([0 0.4 1],'This is the DEVELOPER version.\n'); catch disp(' This is the DEVELOPER version.'); end end end disp([' Welcome to the BCILAB toolbox on ' hlp_hostname '!']) fprintf('\n'); else disp('Now entering worker mode...'); % -- worker mode --- if ~isdeployed % disable standard dialogs in the workers addpath(env_translatepath('dependencies:/disabled_dialogs')); end % close EEGLAB main menu mainmenu = findobj('Tag','EEGLAB'); if ~isempty(mainmenu) close(mainmenu); end drawnow; % translate the options if isequal(opts.worker,true) opts.worker = {}; end if ~iscell(opts.worker) opts.worker = {opts.worker}; end % start! par_worker(opts.worker{:}); end try % pretend to invoke the dependency list so that the compiler finds it... dependency_list; catch end % normalize a directory path function dir = path_normalize(dir) dir = strrep(strrep(dir,'\',filesep),'/',filesep); if dir(end) == filesep dir = dir(1:end-1); end % Split a string according to some delimiter(s). % Not as fast as hlp_split (and doesn't fuse % delimiters), but works without bsxfun. function strings = strsplit(string, splitter) ix = strfind(string, splitter); strings = cell(1,numel(ix)+1); ix = [0 ix numel(string)+1]; for k = 2 : numel(ix) strings{k-1} = string(ix(k-1)+1:ix(k)-1); end
github
lcnbeapp/beapp-master
strsetmatch.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/strsetmatch.m
928
utf_8
73f5541ad337bbbc7179cf71004b7062
% Indicator of which elements of a universal set are in a particular set. % % Input arguments: % strset: % the particular set as a cell array of strings % struniversal: % the universal set as a cell array of strings, all elements in the % particular set are expected to be in the universal set % % Output arguments: % ind: % a logical vector of which elements of the universal set are found in % the particular set % Copyright 2010 Levente Hunyadi function ind = strsetmatch(strset, struniversal) assert(iscellstr(strset), 'strsetmatch:ArgumentTypeMismatch', ... 'The particular set is expected to be a cell array of strings.'); assert(iscellstr(struniversal), 'strsetmatch:ArgumentTypeMismatch', ... 'The particular set is expected to be a cell array of strings.'); ind = false(size(struniversal)); for k = 1 : numel(struniversal) ind(k) = ~isempty(strmatch(struniversal{k}, strset, 'exact')); end
github
lcnbeapp/beapp-master
helptext.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/helptext.m
1,593
utf_8
bd49205fc50aeae5a909c8b58a47be6d
% Help text associated with a function, class, property or method. % Spaces are removed as necessary. % % See also: helpdialog % Copyright 2008-2010 Levente Hunyadi function text = helptext(obj) if ischar(obj) text = gethelptext(obj); else text = gethelptext(class(obj)); end text = texttrim(text); function text = gethelptext(key) persistent dict; if isempty(dict) && usejava('jvm') dict = java.util.Properties(); end if ~isempty(dict) text = char(dict.getProperty(key)); % look up key in cache if ~isempty(text) % help text found in cache return; end text = help(key); if ~isempty(text) % help text returned by help call, save it into cache dict.setProperty(key, text); end else text = help(key); end function lines = texttrim(text) % Trims leading and trailing whitespace characters from lines of text. % The number of leading whitespace characters to trim is determined by % inspecting all lines of text. loc = strfind(text, sprintf('\n')); n = numel(loc); loc = [ 0 loc ]; lines = cell(n,1); if ~isempty(loc) for k = 1 : n lines{k} = text(loc(k)+1 : loc(k+1)); end end lines = deblank(lines); % determine maximum leading whitespace count f = ~cellfun(@isempty, lines); % filter for non-empty lines firstchar = cellfun(@(line) find(~isspace(line), 1), lines(f)); % index of first non-whitespace character if isempty(firstchar) indent = 1; else indent = min(firstchar); end % trim leading whitespace lines(f) = cellfun(@(line) line(min(indent,numel(line)):end), lines(f), 'UniformOutput', false);
github
lcnbeapp/beapp-master
javaclass.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/javaclass.m
3,635
utf_8
7165e1fd27bd4f5898132023dc04662b
% Return java.lang.Class instance for MatLab type. % % Input arguments: % mtype: % the MatLab name of the type for which to return the java.lang.Class % instance % ndims: % the number of dimensions of the MatLab data type % % See also: class % Copyright 2009-2010 Levente Hunyadi function jclass = javaclass(mtype, ndims) validateattributes(mtype, {'char'}, {'nonempty','row'}); if nargin < 2 ndims = 0; else validateattributes(ndims, {'numeric'}, {'nonnegative','integer','scalar'}); end if ndims == 1 && strcmp(mtype, 'char'); % a character vector converts into a string jclassname = 'java.lang.String'; elseif ndims > 0 jclassname = javaarrayclass(mtype, ndims); else % The static property .class applied to a Java type returns a string in % MatLab rather than an instance of java.lang.Class. For this reason, % use a string and java.lang.Class.forName to instantiate a % java.lang.Class object; the syntax java.lang.Boolean.class will not % do so. switch mtype case 'logical' % logical vaule (true or false) jclassname = 'java.lang.Boolean'; case 'char' % a singe character jclassname = 'java.lang.Character'; case {'int8','uint8'} % 8-bit signed and unsigned integer jclassname = 'java.lang.Byte'; case {'int16','uint16'} % 16-bit signed and unsigned integer jclassname = 'java.lang.Short'; case {'int32','uint32'} % 32-bit signed and unsigned integer jclassname = 'java.lang.Integer'; case {'int64','uint64'} % 64-bit signed and unsigned integer jclassname = 'java.lang.Long'; case 'single' % single-precision floating-point number jclassname = 'java.lang.Float'; case 'double' % double-precision floating-point number jclassname = 'java.lang.Double'; case 'cellstr' % a single cell or a character array jclassname = 'java.lang.String'; otherwise error('java:javaclass:InvalidArgumentValue', ... 'MatLab type "%s" is not recognized or supported in Java.', mtype); end end % Note: When querying a java.lang.Class object by name with the method % jclass = java.lang.Class.forName(jclassname); % MatLab generates an error. For the Class.forName method to work, MatLab % requires class loader to be specified explicitly. jclass = java.lang.Class.forName(jclassname, true, java.lang.Thread.currentThread().getContextClassLoader()); function jclassname = javaarrayclass(mtype, ndims) % Returns the type qualifier for a multidimensional Java array. switch mtype case 'logical' % logical array of true and false values jclassid = 'Z'; case 'char' % character array jclassid = 'C'; case {'int8','uint8'} % 8-bit signed and unsigned integer array jclassid = 'B'; case {'int16','uint16'} % 16-bit signed and unsigned integer array jclassid = 'S'; case {'int32','uint32'} % 32-bit signed and unsigned integer array jclassid = 'I'; case {'int64','uint64'} % 64-bit signed and unsigned integer array jclassid = 'J'; case 'single' % single-precision floating-point number array jclassid = 'F'; case 'double' % double-precision floating-point number array jclassid = 'D'; case 'cellstr' % cell array of strings jclassid = 'Ljava.lang.String;'; otherwise error('java:javaclass:InvalidArgumentValue', ... 'MatLab type "%s" is not recognized or supported in Java.', mtype); end jclassname = [repmat('[',1,ndims), jclassid];
github
lcnbeapp/beapp-master
helpdialog.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/helpdialog.m
3,397
utf_8
f16f23c1b608a247bc5298f5ebc6d321
% Displays a dialog to give help information on an object. % % Examples: % helpdialog char % gives information of character arrays % helpdialog plot % gives help on the plot command % helpdialog(obj) % gives help on the MatLab object obj % % See also: helptext, msgbox % Copyright 2008-2010 Levente Hunyadi function helpdialog(obj) if nargin < 1 obj = 'helpdialog'; end if ischar(obj) key = obj; else key = class(obj); end title = [key ' - Quick help']; text = helptext(key); if isempty(text) text = {'No help available.'}; end if 0 % standard MatLab message dialog box createmode = struct( ... 'WindowStyle', 'replace', ... 'Interpreter', 'none'); msgbox(text, title, 'help', createmode); else fig = figure( ... 'MenuBar', 'none', ... 'Name', title, ... 'NumberTitle', 'off', ... 'Position', [0 0 480 160], ... 'Toolbar', 'none', ... 'Visible', 'off', ... 'ResizeFcn', @helpdialog_resize); % information icon icons = load('dialogicons.mat'); icons.helpIconMap(256,:) = get(fig, 'Color'); iconaxes = axes( ... 'Parent', fig, ... 'Units', 'pixels', ... 'Tag', 'IconAxes'); try iconimg = image('CData', icons.helpIconData, 'Parent', iconaxes); set(fig, 'Colormap', icons.helpIconMap); catch me delete(fig); rethrow(me) end if ~isempty(get(iconimg,'XData')) && ~isempty(get(iconimg,'YData')) set(iconaxes, ... 'XLim', get(iconimg,'XData')+[-0.5 0.5], ... 'YLim', get(iconimg,'YData')+[-0.5 0.5]); end set(iconaxes, ... 'Visible', 'off', ... 'YDir', 'reverse'); % help text rgb = get(fig, 'Color'); text = cellfun(@(line) helpdialog_html(line), text, 'UniformOutput', false); html = ['<html>' strjoin(sprintf('\n'), text) '</html>']; jtext = javax.swing.JLabel(html); jcolor = java.awt.Color(rgb(1), rgb(2), rgb(3)); jtext.setBackground(jcolor); jtext.setVerticalAlignment(1); jscrollpane = javax.swing.JScrollPane(jtext, javax.swing.JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); jscrollpane.getViewport().setBackground(jcolor); jscrollpane.setBorder(javax.swing.border.EmptyBorder(0,0,0,0)); [jcontrol,jcontainer] = javacomponent(jscrollpane, [0 0 100 100]); set(jcontainer, 'Tag', 'HelpText'); movegui(fig, 'center'); % center figure on screen set(fig, 'Visible', 'on'); end function helpdialog_resize(fig, event) %#ok<INUSD> position = getpixelposition(fig); width = position(3); height = position(4); iconaxes = findobj(fig, 'Tag', 'IconAxes'); helptext = findobj(fig, 'Tag', 'HelpText'); bottom = 7*height/12; set(iconaxes, 'Position', [12 bottom 51 51]); set(helptext, 'Position', [75 12 width-75-12 height-24]); function html = helpdialog_html(line) preline = deblank(line); % trailing spaces removed line = strtrim(preline); % leading spaces removed leadingspace = repmat('&nbsp;', 1, numel(preline)-numel(line)); % add leading spaces as non-breaking space ix = strfind(line, 'See also'); if ~isempty(ix) ix = ix(1) + numel('See also'); line = [ line(1:ix-1) regexprep(line(ix:end), '(\w[\d\w]+)', '<a href="matlab:helpdialog $1">$1</a>') ]; end html = ['<p>' leadingspace line '</p>'];
github
lcnbeapp/beapp-master
getdependentproperties.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/getdependentproperties.m
907
utf_8
5f87bb7115d9bcacd8556d89a4492c44
% Publicly accessible dependent properties of an object. % % See also: meta.property % Copyright 2010 Levente Hunyadi function dependent = getdependentproperties(obj) dependent = {}; if isstruct(obj) % structures have no dependent properties return; end try clazz = metaclass(obj); catch %#ok<CTCH> return; % old-style class (i.e. not defined with the classdef keyword) have no dependent properties end k = 0; % number of dependent properties found n = numel(clazz.Properties); % maximum number of properties dependent = cell(n, 1); for i = 1 : n property = clazz.Properties{i}; if property.Abstract || property.Hidden || ~strcmp(property.GetAccess, 'public') || ~property.Dependent continue; % skip abstract, hidden, inaccessible and independent properties end k = k + 1; dependent{k} = property.Name; end dependent(k+1:end) = []; % drop unused cells
github
lcnbeapp/beapp-master
example_matrixeditor.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/example_matrixeditor.m
471
utf_8
637b619421d215e7270f8502574e4ff7
% Demonstrates how to use the matrix editor. % % See also: MatrixEditor % Copyright 2010 Levente Hunyadi function example_matrixeditor fig = figure( ... 'MenuBar', 'none', ... 'Name', 'Matrix editor demo - Copyright 2010 Levente Hunyadi', ... 'NumberTitle', 'off', ... 'Toolbar', 'none'); editor = MatrixEditor(fig, ... 'Item', [1,2,3,4;5,6,7,8;9,10,11,12], ... 'Type', PropertyType('denserealdouble','matrix')); uiwait(fig); disp(editor.Item);
github
lcnbeapp/beapp-master
example_propertyeditor.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/example_propertyeditor.m
473
utf_8
49faa2989b2f9c32c26f366e77eaf0b2
% Demonstrates how to use the property editor. % % See also: PropertyEditor % Copyright 2010 Levente Hunyadi function example_propertyeditor % create figure f = figure( ... 'MenuBar', 'none', ... 'Name', 'Property editor demo - Copyright 2010 Levente Hunyadi', ... 'NumberTitle', 'off', ... 'Toolbar', 'none'); items = { SampleObject SampleObject }; editor = PropertyEditor(f, 'Items', items); editor.AddItem(SampleNestedObject, 1); editor.RemoveItem(1);
github
lcnbeapp/beapp-master
nestedfetch.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/nestedfetch.m
1,000
utf_8
1f3b58597c8ee6879bc2650defb0799d
% Fetches the value of the named property of an object or structure. % This function can deal with nested properties. % % Input arguments: % obj: % the handle or value object the value should be assigned to % name: % a property name with dot (.) separating property names at % different hierarchy levels % value: % the value to assign to the property at the deepest hierarchy % level % % Example: % obj = struct('surface', struct('nested', 23)); % value = nestedfetch(obj, 'surface.nested'); % disp(value); % prints 23 % % See also: nestedassign % Copyright 2010 Levente Hunyadi function value = nestedfetch(obj, name) if ~iscell(name) nameparts = strsplit(name, '.'); else nameparts = name; end value = nestedfetch_recurse(obj, nameparts); end function value = nestedfetch_recurse(obj, name) if numel(name) > 1 value = nestedfetch_recurse(obj.(name{1}), name(2:end)); else value = obj.(name{1}); end end
github
lcnbeapp/beapp-master
findobjuser.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/findobjuser.m
1,391
utf_8
3275be54ee6c453c85fd950bb6ac56b5
% Find handle graphics object with user data check. % Retrieves those handle graphics objects (HGOs) that have the specified % Tag property and whose UserData property satisfies the given predicate. % % Input arguments: % fcn: % a predicate (a function that returns a logical value) to test against % the HGO's UserData property % tag (optional): % a string tag to restrict the set of controls to investigate % % See also: findobj % Copyright 2010 Levente Hunyadi function h = findobjuser(fcn, tag) validateattributes(fcn, {'function_handle'}, {'scalar'}); if nargin < 2 || isempty(tag) tag = ''; else validateattributes(tag, {'char'}, {'row'}); end %hh = get(0, 'ShowHiddenHandles'); %cleanup = onCleanup(@() set(0, 'ShowHiddenHandles', hh)); % restore visibility on exit or exception if ~isempty(tag) % look among all handles (incl. hidden handles) to help findobj locate the object it seeks h = findobj(findall(0), '-property', 'UserData', '-and', 'Tag', tag); % more results if multiple matching HGOs exist else h = findobj(findall(0), '-property', 'UserData'); end h = unique(h); try for k=1:length(h) pred = fcn(get(h(k), 'UserData')); if isempty(pred) pred = false; end f(k) = pred; end %f = arrayfun(@(handle) fcn(get(handle, 'UserData')), h, 'UniformOutput',false); catch 1 end h = h(f);
github
lcnbeapp/beapp-master
javaStringArray.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/javaStringArray.m
628
utf_8
fe0389e3b0d1933d49c1a78c416a279c
% Converts a MatLab cell array of strings into a java.lang.String array. % % Input arguments: % str: % a cell array of strings (i.e. a cell array of char row vectors) % % Output arguments: % arr: % a java.lang.String array instance (i.e. java.lang.String[]) % % See also: javaArray % Copyright 2009-2010 Levente Hunyadi function arr = javaStringArray(str) assert(iscellstr(str) && isvector(str), ... 'java:StringArray:InvalidArgumentType', ... 'Cell row or column vector of strings expected.'); arr = javaArray('java.lang.String', length(str)); for k = 1 : numel(str); arr(k) = java.lang.String(str{k}); end
github
lcnbeapp/beapp-master
var2str.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/var2str.m
441
utf_8
5588acb0d18dcfac8183caf10a3b5675
% Textual representation of any MatLab value. % Copyright 2009 Levente Hunyadi function s = var2str(value) if islogical(value) || isnumeric(value) s = num2str(value); elseif ischar(value) && isvector(value) s = reshape(value, 1, numel(value)); elseif isjava(value) s = char(value); % calls java.lang.Object.toString() else try s = char(value); catch %#ok<CTCH> s = '[no preview available]'; end end
github
lcnbeapp/beapp-master
getclassfield.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/getclassfield.m
376
utf_8
e3b87866af8da4dd40243e750a7e53f6
% Field value of each object in an array or cell array. % % See also: getfield % Copyright 2010 Levente Hunyadi function values = getclassfield(objects, field) values = cell(size(objects)); if iscell(objects) for k = 1 : numel(values) values{k} = objects{k}.(field); end else for k = 1 : numel(values) values{k} = objects(k).(field); end end
github
lcnbeapp/beapp-master
arrayfilter.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/arrayfilter.m
488
utf_8
a2649b876169e3d850372917e57a8b68
% Filter elements of array that meet a condition. % Copyright 2010 Levente Hunyadi function array = arrayfilter(fun, array) validateattributes(fun, {'function_handle'}, {'scalar'}); if isobject(array) filter = false(size(array)); for k = 1 : numel(filter) filter(k) = fun(array(k)); end else filter = arrayfun(fun, array); % logical indicator array of elements that satisfy condition end array = array(filter); % array of elements that meet condition
github
lcnbeapp/beapp-master
example_propertygrid.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/example_propertygrid.m
4,929
utf_8
f1e5d6dc7fc518cdb070956ff714353c
% Demonstrates how to use the property pane. % % See also: PropertyGrid % Copyright 2010 Levente Hunyadi function example_propertygrid properties = [ ... PropertyGridField('double', pi, ... 'Category', 'Primitive types', ... 'DisplayName', 'real double', ... 'Description', 'Standard MatLab type.') ... PropertyGridField('single', pi, ... 'Category', 'Primitive types', ... 'DisplayName', 'real single', ... 'Description', 'Single-precision floating point number.') ... PropertyGridField('integer', int32(23), ... 'Category', 'Primitive types', ... 'DisplayName', 'int32', ... 'Description', 'A 32-bit integer value.') ... PropertyGridField('interval', int32(2), ... 'Type', PropertyType('int32', 'scalar', [0 6]), ... 'Category', 'Primitive types', ... 'DisplayName', 'int32', ... 'Description', 'A 32-bit integer value with an interval domain.') ... PropertyGridField('enumerated', int32(-1), ... 'Type', PropertyType('int32', 'scalar', {int32(-1), int32(0), int32(1)}), ... 'Category', 'Primitive types', ... 'DisplayName', 'int32', ... 'Description', 'A 32-bit integer value with an enumerated domain.') ... PropertyGridField('logical', true, ... 'Category', 'Primitive types', ... 'DisplayName', 'logical', ... 'Description', 'A Boolean value that takes either true or false.') ... PropertyGridField('doublematrix', [], ... 'Type', PropertyType('denserealdouble', 'matrix'), ... 'Category', 'Compound types', ... 'DisplayName', 'real double matrix', ... 'Description', 'Matrix of standard MatLab type with empty initial value.') ... PropertyGridField('string', 'a sample string', ... 'Category', 'Compound types', ... 'DisplayName', 'string', ... 'Description', 'A row vector of characters.') ... PropertyGridField('rowcellstr', {'a sample string','spanning multiple','lines'}, ... 'Category', 'Compound types', ... 'DisplayName', 'cell row of strings', ... 'Description', 'A row cell array whose every element is a string (char array).') ... PropertyGridField('colcellstr', {'a sample string';'spanning multiple';'lines'}, ... 'Category', 'Compound types', ... 'DisplayName', 'cell column of strings', ... 'Description', 'A column cell array whose every element is a string (char array).') ... PropertyGridField('season', 'spring', ... 'Type', PropertyType('char', 'row', {'spring','summer','fall','winter'}), ... 'Category', 'Compound types', ... 'DisplayName', 'string', ... 'Description', 'A row vector of characters that can take any of the predefined set of values.') ... PropertyGridField('set', [true false true], ... 'Type', PropertyType('logical', 'row', {'A','B','C'}), ... 'Category', 'Compound types', ... 'DisplayName', 'set', ... 'Description', 'A logical vector that serves an indicator of which elements from a universe are included in the set.') ... PropertyGridField('root', [], ... % [] (and no type explicitly set) indicates that value is not editable 'Category', 'Compound types', ... 'DisplayName', 'root node') ... PropertyGridField('root.parent', int32(23), ... 'Category', 'Compound types', ... 'DisplayName', 'parent node') ... PropertyGridField('root.parent.child', int32(2007), ... 'Category', 'Compound types', ... 'DisplayName', 'child node') ... ]; % arrange flat list into a hierarchy based on qualified names properties = properties.GetHierarchy(); % create figure f = figure( ... 'MenuBar', 'none', ... 'Name', 'Property grid demo - Copyright 2010 Levente Hunyadi', ... 'NumberTitle', 'off', ... 'Toolbar', 'none'); % procedural usage g = PropertyGrid(f, ... % add property pane to figure 'Properties', properties, ... % set properties explicitly 'Position', [0 0 0.5 1]); h = PropertyGrid(f, ... 'Position', [0.5 0 0.5 1]); % declarative usage, bind object to grid obj = SampleObject; % a value object h.Item = obj; % bind object, discards any previously set properties % update the type of a property assigned with type autodiscovery userproperties = PropertyGridField.GenerateFrom(obj); userproperties.FindByName('IntegerMatrix').Type = PropertyType('denserealdouble', 'matrix'); disp(userproperties.FindByName('IntegerMatrix').Type); h.Bind(obj, userproperties); % wait for figure to close uiwait(f); % display all properties and their values on screen disp('Left-hand property grid'); disp(g.GetPropertyValues()); disp('Right-hand property grid'); disp(h.GetPropertyValues()); disp('SampleObject (modified)'); disp(h.Item); disp('SampleNestedObject (modified)'); disp(h.Item.NestedObject);
github
lcnbeapp/beapp-master
constructor.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/constructor.m
2,078
utf_8
c67e647ec8055710896666c9e83b45e0
% Sets public properties of a MatLab object using a name-value list. % Properties are traversed in the order they occur in the class definition. % Copyright 2008-2009 Levente Hunyadi function obj = constructor(obj, varargin) assert(isobject(obj), ... 'Function operates on MatLab new-style objects only.'); if nargin <= 1 return; end if isa(obj, 'hgsetget') set(obj, varargin{:}); return; end assert(is_name_value_list(varargin), ... 'constructor:ArgumentTypeMismatch', ... 'A list of property name--value pairs is expected.'); % instantiate input parser object parser = inputParser; % query class properties using meta-class facility metaobj = metaclass(obj); properties = metaobj.Properties; for i = 1 : numel(properties) property = properties{i}; if is_public_property(property) parser.addParamValue(property.Name, obj.(property.Name)); end end % set property values according to name-value list parser.parse(varargin{:}); for i = 1 : numel(properties) property = properties{i}; if is_public_property(property) && ~is_string_in_vector(property.Name, parser.UsingDefaults) % do not set defaults obj.(property.Name) = parser.Results.(property.Name); end end function tf = is_name_value_list(list) % True if the specified list is a name-value list. % % Input arguments: % list: % a name-value list as a cell array. validateattributes(list, {'cell'}, {'vector'}); n = numel(list); if mod(n, 2) ~= 0 % a name-value list has an even number of elements tf = false; else for i = 1 : 2 : n if ~ischar(list{i}) % each odd element in a name-value list must be a char array tf = false; return; end end tf = true; end function tf = is_string_in_vector(str, vector) tf = any(strcmp(str, vector)); function tf = is_public_property(property) % True if the property designates a public, accessible property. tf = ~property.Abstract && ~property.Hidden && strcmp(property.GetAccess, 'public') && strcmp(property.SetAccess, 'public');
github
lcnbeapp/beapp-master
nestedassign.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/nestedassign.m
1,457
utf_8
12d661bb4df3c64a0707a06f7e3e6afc
% Assigns the given value to the named property of an object or structure. % This function can deal with nested properties. % % Input arguments: % obj: % the structure, handle or value object the value should be assigned to % name: % a property name with dot (.) separating property names at % different hierarchy levels % value: % the value to assign to the property at the deepest hierarchy % level % % Output arguments: % obj: % the updated object or structure, optional for handle objects % % Example: % obj = struct('surface', struct('nested', 10)); % obj = nestedassign(obj, 'surface.nested', 23); % disp(obj.surface.nested); % prints 23 % % See also: nestedfetch % Copyright 2010 Levente Hunyadi function obj = nestedassign(obj, name, value) if ~iscell(name) nameparts = strsplit(name, '.'); else nameparts = name; end obj = nestedassign_recurse(obj, nameparts, value); end function obj = nestedassign_recurse(obj, name, value) % Assigns the given value to the named property of an object. % % Input arguments: % obj: % the handle or value object the value should be assigned to % name: % a cell array of the composite property name % value: % the value to assign to the property at the deepest hierarchy % level if numel(name) > 1 obj.(name{1}) = nestedassign_recurse(obj.(name{1}), name(2:end), value); else obj.(name{1}) = value; end end
github
lcnbeapp/beapp-master
javaArrayList.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/javaArrayList.m
740
utf_8
cb4ad03c4e0fc536bc1ae024bfb8920a
% Converts a MatLab array into a java.util.ArrayList. % % Input arguments: % array: % a MatLab row or column vector (with elements of any type) % % Output arguments: % list: % a java.util.ArrayList instance % % See also: javaArray % Copyright 2010 Levente Hunyadi function list = javaArrayList(array) list = java.util.ArrayList; if ~isempty(array) assert(isvector(array), 'javaArrayList:DimensionMismatch', ... 'Row or column vector expected.'); if iscell(array) % convert cell array into ArrayList for k = 1 : numel(array) list.add(array{k}); end else % convert (numeric) array into ArrayList for k = 1 : numel(array) list.add(array(k)); end end end
github
lcnbeapp/beapp-master
hlp_scope.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_scope.m
3,366
utf_8
4544c2a11f66464cc00f860f36646304
function varargout = hlp_scope(assignments, f, varargin) % Execute a function within a dynamic scope of values assigned to symbols. % Results... = hlp_scope(Assignments, Function, Arguments...) % % This is the only completely reliable way in MATLAB to ensure that symbols that should be assigned % while a function is running get cleared after the function returns orderly, crashes, segfaults, % the user slams Ctrl+C, and so on. Symbols can be looked up via hlp_resolve(). % % In: % Assignments : Cell array of name-value pairs or a struct. Values are associated with symbols of % the given names. The names should be valid MATLAB identifiers. These assigments % form a dynamic scope for the execution of the function; scopes can also be % nested, and assignments in inner scopes override those of outer scopes. % % Function : a function handle to invoke % % Arguments... : arguments to pass to the function % % Out: % Results... : return value(s) of the function % % See also: % hlp_resolve % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-05-03 % add a new stack frame with the evaluated assignments & get its unique id id = make_stackframe(assignments); % also take care that it gets reclaimed after we're done reclaimer = onCleanup(@()return_stackframe(id)); % make a function that is tagged by id func = make_func(id); % evaluate the function with the id introduced into MATLAB's own stack [varargout{1:nargout}] = func(f,varargin); function func = make_func(id) persistent funccache; % (cached, since the eval() below is a bit slow) try func = funccache.(id); catch func = eval(['@(f,a,frame__' id ')feval(f,a{:})']); funccache.(id) = func; end function id = make_stackframe(assignments) % put the assignments into a struct if iscell(assignments) assignments = cell2struct(assignments(2:2:end),assignments(1:2:end),2); end % get a fresh frame id global tracking; try id = tracking.stack.frameids.removeLast(); catch if ~isfield(tracking,'stack') || ~isfield(tracking.stack,'frameids') % need to create the id repository first tracking.stack.frameids = java.util.concurrent.LinkedBlockingDeque(); for k=50000:-1:1 tracking.stack.frameids.addLast(sprintf('f%d',k)); end else if tracking.stack.frameids.size() == 0 % if this happens then either you have 10.000s of parallel executions of hlp_scope(), % or you have a very deep recursion level (the MATLAB default is 500), or your function % has crashed 10.000s of times in a way that keeps onCleanup from doing its job, or you have % substituted onCleanup by a dummy class or function that doesn't actually work (e.g. on % pre-2008a systems). error('We ran out of stack frame ids. This should not happen under normal conditions. Please make sure that your onCleanup implementation is not consistently failing to execute.'); end end id = tracking.stack.frameids.removeLast(); end % and store the assignments under it tracking.stack.frames.(id) = assignments; function return_stackframe(id) % finally return the frame id again... global tracking; tracking.stack.frameids.addLast(id);
github
lcnbeapp/beapp-master
hlp_fingerprint.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_fingerprint.m
7,085
utf_8
ebeb87c5f5aa958473e853a153d261f9
function fp = hlp_fingerprint(data) % Make a fingerprint (hash) of the given data structure. % Fingerprint = hlp_fingerprint(Data) % % This includes all contents; however, large arrays (such as EEG.data) are only spot-checked. For % thorough checking, use hlp_cryptohash. % % In: % Data : some data structure % % Out: % Fingerprint : an integer that identifies the data % % Notes: % The fingerprint is not unique and identifies the data set only with a certain (albeit high) % probability. % % On MATLAB versions prior to 2008b, hlp_fingerprint cannot be used concurrently from timers, % and also may alter the random generator's state if cancelled via Ctrl+C. % % Examples: % % calculate the hash of a large data structure % hash = hlp_fingerprint(data); % % See also: % hlp_cryptohash % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-04-02 warning off MATLAB:structOnObject if hlp_matlab_version >= 707 fp = fingerprint(data,RandStream('swb2712','Seed',5183)); else try % save & override random state randstate = rand('state'); %#ok<*RAND> rand('state',5183); % make the fingerprint fp = fingerprint(data,0); % restore random state rand('state',randstate); catch e % restore random state in case of an error... rand('state',randstate); rethrow(e); end end % make a fingerprint of the given data structure function fp = fingerprint(data,rs) % convert data into a string representation data = summarize(data,rs); % make sure that it does not contain 0's data(data==0) = 'x'; % obtain a hash code via Java (MATLAB does not support proper integer arithmetic...) str = java.lang.String(data); fp = str.hashCode()+2^31; % get a recursive string summary of arbitrary data function x = summarize(x,rs) if isnumeric(x) % numeric array if ~isreal(x) x = [real(x) imag(x)]; end if issparse(x) x = [find(x) nonzeros(x)]; end if numel(x) <= 4096 % small matrices are hashed completely try x = ['n' typecast([size(x) x(:)'],'uint8')]; catch if hlp_matlab_version <= 702 x = ['n' typecast([size(x) double(x(:))'],'uint8')]; end end else % large matrices are spot-checked ne = numel(x); count = floor(256 + (ne-256)/1000); if hlp_matlab_version < 707 indices = 1+floor((ne-1)*rand(1,count)); else indices = 1+floor((ne-1)*rand(rs,1,count)); end if size(x,2) == 1 % x is a column vector: reindexed expression needs to be transposed x = ['n' typecast([size(x) x(indices)'],'uint8')]; else % x is a matrix or row vector: shape follows that of indices x = ['n' typecast([size(x) x(indices)],'uint8')]; end end elseif iscell(x) % cell array sizeprod = cellfun('prodofsize',x(:)); if all(sizeprod <= 1) && any(sizeprod) % all scalar elements (some empty, but not all) if all(cellfun('isclass',x(:),'double')) || all(cellfun('isclass',x(:),'single')) % standard floating-point scalars if cellfun('isreal',x) % all real x = ['cdr' typecast([size(x) x{:}],'uint8')]; else % some complex x = ['cdc' typecast([size(x) real([x{:}]) imag([x{:}])],'uint8')]; end elseif cellfun('isclass',x(:),'logical') % all logical x = ['cl' typecast(uint32(size(x)),'uint8') uint8([x{:}])]; elseif cellfun('isclass',x(:),'char') % all single chars x = ['ccs' typecast(uint32(size(x)),'uint8') x{:}]; else % generic types (structs, cells, integers, handles, ...) tmp = cellfun(@summarize,x,repmat({rs},size(x)),'UniformOutput',false); x = ['cg' typecast(uint32(size(x)),'uint8') tmp{:}]; end elseif isempty(x) % empty cell array x = ['ce' typecast(uint32(size(x)),'uint8')]; else % some non-scalar elements dims = cellfun('ndims',x(:)); size1 = cellfun('size',x(:),1); size2 = cellfun('size',x(:),2); if all((size1+size2 == 0) & (dims == 2)) % all empty and nondegenerate elements if all(cellfun('isclass',x(:),'double')) % []'s x = ['ced' typecast(uint32(size(x)),'uint8')]; elseif all(cellfun('isclass',x(:),'cell')) % {}'s x = ['cec' typecast(uint32(size(x)),'uint8')]; elseif all(cellfun('isclass',x(:),'struct')) % struct()'s x = ['ces' typecast(uint32(size(x)),'uint8')]; elseif length(unique(cellfun(@class,x(:),'UniformOutput',false))) == 1 % same class x = ['cex' class(x{1}) typecast(uint32(size(x)),'uint8')]; else % arbitrary class... tmp = cellfun(@summarize,x,repmat({rs},size(x)),'UniformOutput',false); x = ['cg' typecast(uint32(size(x)),'uint8') tmp{:}]; end elseif all((cellfun('isclass',x(:),'char') & size1 <= 1) | (sizeprod==0 & cellfun('isclass',x(:),'double'))) % all horizontal strings or proper empty strings, possibly some []'s x = ['cch' [x{:}] typecast(uint32(size2'),'uint8')]; else % arbitrary sizes... if all(cellfun('isclass',x(:),'double')) || all(cellfun('isclass',x(:),'single')) % all standard floating-point types... tmp = cellfun(@vectorize,x,'UniformOutput',false); % treat as a big vector... x = ['cn' typecast(uint32(size(x)),'uint8') summarize([tmp{:}],rs)]; else tmp = cellfun(@summarize,x,repmat({rs},size(x)),'UniformOutput',false); x = ['cg' typecast(uint32(size(x)),'uint8') tmp{:}]; end end end elseif ischar(x) % char array x = ['c' x(:)']; elseif isstruct(x) % struct fn = fieldnames(x)'; if numel(x) > length(fn) % summarize over struct fields to expose homogeneity x = cellfun(@(f)summarize({x.(f)},rs),fn,'UniformOutput',false); x = ['s' [fn{:}] ':' [x{:}]]; else % summarize over struct elements x = ['s' [fn{:}] ':' summarize(struct2cell(x),rs)]; end elseif islogical(x) % logical array x = ['l' typecast(uint32(size(x)),'uint8') uint8(x(:)')]; elseif isa(x,'function_handle') x = ['f ' char(x)]; elseif isobject(x) x = ['o' class(x) ':' summarize(struct(x),rs)]; else try x = ['u' class(x) ':' summarize(struct(x),rs)]; catch warning('BCILAB:hlp_fingerprint:unsupported_type','Unsupported type: %s',class(x)); error; %#ok<LTARG> end end function x = vectorize(x) x = x(:)';
github
lcnbeapp/beapp-master
hlp_flattensearch.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_flattensearch.m
4,217
utf_8
9f21976c4c355a8c0ac9432e74a4d31d
function x = hlp_flattensearch(x,form) % Flatten search() clauses in a nested data structure into a flat search() clause. % Result = hlp_flattensearch(Expression, Output-Form) % % Internal tool used by utl_gridsearch to enable the specification of search parameters using % search() clauses. % % In: % Expression : some data structure, usually an argument to utl_gridsearch, may or may not contain % nested search clauses. % % Output-Form : form of the output (default: 'search') % * 'search': the output shall be a flattened search clause (or a plain value if no % search) % * 'cell': the output shall be a cell array of elements to search over % % Out: % Result : a flattened search clause (or plain value), or a cell array of search possibilities. % % See also: % search, utl_gridsearch % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-06-29 x = flatten(x); if ~exist('form','var') || isempty(form) || strcmp(form,'search') % turn from cell format into search format if isscalar(x) % just one option: return the plain value x = x{1}; else % multiple options: return a search expression x = struct('head',{@search},'parts',{x}); end elseif ~strcmp(form,'cell') error(['Unsupported output form: ' form]); end % recursively factor search expressions out of a data structure, to give an overall search % expression (output format is cell array of search options) function parts = flatten(x) if isstruct(x) if isfield(x,{'data','srate','chanlocs','event','epoch'}) % data set? do not descend further parts = {x}; elseif all(isfield(x,{'head','parts'})) && numel(x)==1 && strcmp(char(x.head),'search') % search expression: flatten any nested searches... parts = cellfun(@flatten,x.parts,'UniformOutput',false); % ... and splice their parts in parts = [parts{:}]; else % generic structure: create a cartesian product over field-wise searches if isscalar(x) parts = {x}; % flatten per-field contents fields = cellfun(@flatten,struct2cell(x),'UniformOutput',false); lengths = cellfun('length',fields); % was any one a search? if any(lengths>1) fnames = fieldnames(x); % for each field that is a search... for k=find(lengths>1)' % replicate all parts once for each search item in the current field partnum = length(parts); parts = repmat(parts,1,lengths(k)); % and fill each item into the appropriate place for j=1:length(parts) parts{j}.(fnames{k}) = fields{k}{ceil(j/partnum)}; end end end elseif ~isempty(x) % struct array (either with nested searches or a concatenation of search() expressions): % handle as a cell array of structs parts = flatten(arrayfun(@(s){s},x)); % got a search? if ~isscalar(parts) % re-concatenate the cell contents of each part of the search expression into % struct arrays for i=1:length(parts) parts{i} = reshape([parts{i}{:}],size(parts{i})); end else parts = {x}; end else parts = {x}; end end elseif iscell(x) % cell array: create a cartesian product over cell-wise searches parts = {x}; x = cellfun(@flatten,x,'UniformOutput',false); % for each cell that is a search... for c=find(cellfun('length',x(:)')>1) % replicate all parts once for each search item in the current cell partnum = length(parts); parts = repmat(parts,1,length(x{c})); % and fill in the new item in the appropriate place for j=1:length(parts) parts{j}{c} = x{c}{ceil(j/partnum)}; end end else % anything else: wrap parts = {x}; end
github
lcnbeapp/beapp-master
hlp_tostring.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_tostring.m
6,536
utf_8
7c374a9f8a1954f5289b4e446ea1a30d
function str = hlp_tostring(v) % Get an human-readable string representation of a data structure. % String = hlp_tostring(Data) % % The resulting string representations are usually executable, but there are corner cases (e.g., % certain anonymous function handles and large data sets), which are not supported. For % general-purpose serialization, see hlp_serialize/hlp_deserialize. % % In: % Data : a data structure % % Out: % String : string form of the data structure % % Notes: % hlp_tostring has builtin support for displaying expression data structures. % % Examples: % % get a string representation of a data structure % hlp_tostring({'test',[1 2 3], struct('field','value')}) % % See also: % hlp_serialize % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-04-15 % % adapted from serialize.m % (C) 2006 Joger Hansegord ([email protected]) n = 15; str = serializevalue(v,n); % % Main hub for serializing values % function val = serializevalue(v, n) if isnumeric(v) || islogical(v) val = serializematrix(v, n); elseif ischar(v) val = serializestring(v, n); elseif isa(v,'function_handle') val = serializefunction(v, n); elseif is_impure_expression(v) val = serializevalue(v.tracking.expression, n); elseif has_canonical_representation(v) val = serializeexpression(v, n); elseif is_dataset(v) val = serializedataset(v, n); elseif isstruct(v) val = serializestruct(v, n); elseif iscell(v) val = serializecell(v, n); elseif isobject(v) val = serializeobject(v, n); else try val = serializeobject(v, n); catch error('Unhandled type %s', class(v)); end end % % Serialize a string % function val = serializestring(v,n) if any(v == '''') val = ['''' strrep(v,'''','''''') '''']; try if ~isequal(eval(val),v) val = ['char(' serializevalue(uint8(v), n) ')']; end catch val = ['char(' serializevalue(uint8(v), n) ')']; end else val = ['''' v '''']; end % % Serialize a matrix and apply correct class and reshape if required % function val = serializematrix(v, n) if ndims(v) < 3 if isa(v, 'double') if size(v,1) == 1 && length(v) > 3 && isequal(v,v(1):v(2)-v(1):v(end)) % special case: colon sequence if v(2)-v(1) == 1 val = ['[' num2str(v(1)) ':' num2str(v(end)) ']']; else val = ['[' num2str(v(1)) ':' num2str(v(2)-v(1)) ':' num2str(v(end)) ']']; end elseif size(v,2) == 1 && length(v) > 3 && isequal(v',v(1):v(2)-v(1):v(end)) % special case: colon sequence if v(2)-v(1) == 1 val = ['[' num2str(v(1)) ':' num2str(v(end)) ']''']; else val = ['[' num2str(v(1)) ':' num2str(v(2)-v(1)) ':' num2str(v(end)) ']''']; end else val = mat2str(v, n); end else val = mat2str(v, n, 'class'); end else if isa(v, 'double') val = mat2str(v(:), n); else val = mat2str(v(:), n, 'class'); end val = sprintf('reshape(%s, %s)', val, mat2str(size(v))); end % % Serialize a cell % function val = serializecell(v, n) if isempty(v) val = '{}'; return end cellSep = ', '; if isvector(v) && size(v,1) > 1 cellSep = '; '; end % Serialize each value in the cell array, and pad the string with a cell % separator. vstr = cellfun(@(val) [serializevalue(val, n) cellSep], v, 'UniformOutput', false); vstr{end} = vstr{end}(1:end-2); % Concatenate the elements and add a reshape if requied val = [ '{' vstr{:} '}']; if ~isvector(v) val = ['reshape(' val sprintf(', %s)', mat2str(size(v)))]; end % % Serialize an expression % function val = serializeexpression(v, n) if numel(v) > 1 val = ['[']; for k = 1:numel(v) val = [val serializevalue(v(k), n), ', ']; end val = [val(1:end-2) ']']; else if numel(v.parts) > 0 val = [char(v.head) '(']; for fieldNo = 1:numel(v.parts) val = [val serializevalue(v.parts{fieldNo}, n), ', ']; end val = [val(1:end-2) ')']; else val = char(v.head); end end % % Serialize a data set % function val = serializedataset(v, n) %#ok<INUSD> val = '<EEGLAB data set>'; % % Serialize a struct by converting the field values using struct2cell % function val = serializestruct(v, n) fieldNames = fieldnames(v); fieldValues = struct2cell(v); if ndims(fieldValues) > 6 error('Structures with more than six dimensions are not supported'); end val = 'struct('; for fieldNo = 1:numel(fieldNames) val = [val serializevalue( fieldNames{fieldNo}, n) ', ']; val = [val serializevalue( permute(fieldValues(fieldNo, :,:,:,:,:,:), [2:ndims(fieldValues) 1]) , n) ]; val = [val ', ']; end if numel(fieldNames)==0 val = [val ')']; else val = [val(1:end-2) ')']; end if ~isvector(v) val = sprintf('reshape(%s, %s)', val, mat2str(size(v))); end % % Serialize an object by converting to struct and add a call to the copy % contstructor % function val = serializeobject(v, n) val = sprintf('%s(%s)', class(v), serializevalue(struct(v), n)); function val = serializefunction(v, n) %#ok<INUSD> try val = ['@' char(get_function_symbol(v))]; catch val = char(v); end function result___ = get_function_symbol(expression___) % internal: some function_handle expressions have a function symbol (an @name expression), and this function obtains it % note: we are using funny names here to bypass potential name conflicts within the eval() clause further below if ~isa(expression___,'function_handle') error('the expression has no associated function symbol.'); end string___ = char(expression___); if string___(1) == '@' % we are dealing with a lambda function if is_symbolic_lambda(expression___) result___ = eval(string___(27:end-21)); else error('cannot derive a function symbol from a non-symbolic lambda function.'); end else % we are dealing with a regular function handle result___ = expression___; end function res = is_symbolic_lambda(x) % internal: a symbolic lambda function is one which generates expressions when invoked with arguments (this is what exp_symbol generates) res = isa(x,'function_handle') && ~isempty(regexp(char(x),'@\(varargin\)struct\(''head'',\{.*\},''parts'',\{varargin\}\)','once'));
github
lcnbeapp/beapp-master
hlp_config.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_config.m
12,881
utf_8
7b49f69371781d0161c3a842064a43d0
function result = hlp_config(configname, operation, varargin) % helper function to process human-readable config scripts. % Result = hlp_config(FileName,Operation,VariableName,Value,NVPs...) % % Config scripts consist of assignments of the form name = value; to set configuration options. In % addition, there may be any type of comments, conditional control flow, etc - e.g., setting certain % values on some platforms and others on others. This function allows to get or set the value % assigned to a variable in the place of the script where it is actually assigned on the current % platform. Note that the respective variable has to be already in the config file for this function % to work. % % In: % FileName : name of the configuration file to process % % Operation : operation to perform on the config file % 'get' : get the currently defined value of a given variable % 'set' : replace the current defintion of a given variable % % VariableName : name of the variable to be affected (must be a MATLAB identifier) % % Value : the new value to be assigned, if the operation is 'set', as a string % note that most data structures can be converted into a string via hlp_tostring % % NVPs... : list of further name-value pairs, where each name denotes a config variables and the subsequent % value is the string expression that should be written into the config file. It is % generally a good idea to use hlp_tostring() to turn a data structure into such a string % representation. % % Out: % Result : the current value of the variable of interest, when using the 'get' % operation % % Notes: % There can be multiple successive variable name / value pairs for the set mode. % If an error occurs during a set operation, any changes will be rolled back. % % Examples: % % read out the value of the 'data' config variable from a config file % data = hlp_config('/home/christian/myconfig.m','get','data') % % % override the values of the 'files' and 'capacity' config variables in the given config script % hlp_config('/home/christian/myconfig.m', 'set', 'files',myfiles, 'capacity',1000) % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-11-19 if ~exist(configname,'file') error('hlp_config:file_not_found','The specified config file was not found.'); end switch operation case 'get' varname = varargin{1}; if ~isvarname(varname) error('hlp_config:bad_varname','The variable name must be a valid MATLAB identifier.'); end % get the currently defined value of a variable... result = get_value(configname,varname); case 'set' backupfile = []; try % apply first assignment backupfile = set_value(configname,varargin{1},varargin{2},true); for k = 4:2:length(varargin) % apply all other assignments set_value(configname,varargin{k-1},varargin{k},false); end catch e % got an error; roll back changes if necessary if ~isempty(backupfile) try movefile(backupfile,configname); catch disp(['Could not roll back changes. You can manually revert changes by replacing ' configname ' by ' backupfile '.']); end end rethrow(e); end otherwise error('hlp_config:unsupported_option','Unsupported config operation.'); end % run the given config script and obtain the current value of the given variable... function res = get_value(filename__,varname__) try run_script(filename__); catch e error('hlp_config:erroneous_file',['The config file is erroneous; Error message: ' e.message]); end if ~exist(varname__,'var') error('hlp_config:var_not_found','The variable is not being defined in the config file.'); end res = eval(varname__); function backup_name = set_value(filename,varname,newvalue,makebackup) backup_name = []; if ~exist(filename,'file') error('hlp_config:file_not_found','The config file was not found.'); end if ~isvarname(varname) error('hlp_config:incorrect_value','The variable name must be a valid MATLAB identifier.'); end if ~ischar(newvalue) error('hlp_config:incorrect_value','The value to be assigned must be given as a string.'); end try % read the config file contents contents = {}; f = fopen(filename,'r'); while 1 l = fgetl(f); if ~ischar(l) break; end contents{end+1} = [l 10]; end fclose(f); % turn it into one str contents = [contents{:}]; catch e try fclose(f); catch,end error('hlp_config:cannot_read_config',['Cannot read the config file; Error message: ' e.message]); end % now check if the file is actually writable try f = fopen(filename,'r+'); if f ~= -1 fclose(f); else error('hlp_config:permissions_error','Could not update the config file %s. Please check file permissions and try again.',filename); end catch error('hlp_config:permissions_error','Could not update the config file %s. Please check file permissions and try again.',filename); end % temporarily replace stray semicolons by a special character and contract ellipses, % so that the subsequent assignment regex matching will not get derailed) evalstr = contents; comment_flag = false; string_flag = false; bracket_level = 0; ellipsis_flag = false; substitute = false(1,length(evalstr)); % this mask indicates where we have to subsitute reversibly by special characters spaceout = false(1,length(evalstr)); % this mask indicates where we can substitute irreversibly by whitespace characters... for k=1:length(evalstr) if ellipsis_flag % everything that follows an ellipsis will be spaced out (including the subsequent newline that resets it) spaceout(k) = true; end switch evalstr(k) case ';' % semicolon % in strs, brackets or comments: indicate need for substitution if string_flag || bracket_level>0 || comment_flag substitute(k) = true; end case '''' % quotes % flip str flag, unless in comment if ~comment_flag string_flag = ~string_flag; end case 10 % newline % reset bracket level, unless in ellipsis if ~ellipsis_flag bracket_level = 0; end % reset comment flag, str flag and ellipsis flag comment_flag = false; string_flag = false; ellipsis_flag = false; case {'[','{'} % opening array bracket % if not in str nor comment, increase bracket level if ~string_flag && ~comment_flag bracket_level = bracket_level+1; end case {']','}'} % closing array bracket % if not in str nor comment, decrease bracket level if ~string_flag && ~comment_flag bracket_level = bracket_level-1; end case '%' % comment character % if not in str, switch on comment flag if ~string_flag comment_flag = true; end case '.' % potential ellipsis character % if not in comment nor in str, turn on ellipsis and comment if ~string_flag && ~comment_flag && k>2 && strcmp(evalstr(k-2:k),'...') ellipsis_flag = true; comment_flag = true; % we want to replace the ellipsis and everything that follows up to and including the next newline spaceout(k-2:k) = true; end end end % replace the characters that need to be substituted (by the bell character) evalstr(substitute) = 7; evalstr(spaceout) = ' '; % replace all assignments of the form "varname = *;" by "varname{end+1} = num;" [starts,ends] = regexp(evalstr,[varname '\s*=[^;\n]*;']); for k=length(starts):-1:1 evalstr = [evalstr(1:starts(k)-1) varname '{end+1} = struct(''assignment'',' num2str(k) ');' evalstr(ends(k)+1:end)]; end % add initial assignment evalstr = [sprintf('%s = {};\n',varname) evalstr]; % back-substitute the special character by semicolons evalstr(evalstr==7) = ';'; % evaluate contents and get the matching assignment id's ids = run_protected(evalstr,varname); % check validity of the updated value, and of the updated config file try % check if the value str can in fact be evaluated newvalue_eval = eval(newvalue); catch error('hlp_config:incorrect_value','The value "%s" (to be assigned to variable "%s") cannot be evaluated properly. Note that, for example, string values need to be quoted.',newvalue,varname); end % evaluate the original config script and record the full variable assignment [dummy,wspace_old] = run_protected(contents); %#ok<ASGLU> % splice the new value into the config file contents, for the last assignment in ids id = ids{end}.assignment; contents = [contents(1:starts(id)-1) varname ' = ' newvalue ';' contents(ends(id)+1:end)]; % evaluate the new config script and record the full variable assignment [dummy,wspace_new] = run_protected(contents); %#ok<ASGLU> % make sure that the only thing that has changed is the assignment to the variable of interest wspace_old.(varname) = newvalue_eval; if ~isequalwithequalnans(wspace_old,wspace_new) error('hlp_config:update_failed','The config file can not be properly updated.'); end % apparently, everything went well, except for the following possibilities % * the newly assigned value makes no sense (--> usage error) % * the settings were changed for unanticipated platforms (--> this needs to be documented properly) if makebackup try % make a backup of the original config file using a fresh name (.bak00X) [p,n,x] = fileparts(filename); files = dir([p filesep n '*.bak*']); backup_numbers = cellfun(@(n)str2num(n(end-2:end)),{files.name},'UniformOutput',false); backup_numbers = [backup_numbers{:}]; if ~isempty(backup_numbers) new_number = 1 + max(backup_numbers); else new_number = 1; end backup_name = [p filesep n '.bak' sprintf('%03i',new_number)]; copyfile(filename,backup_name); % set read permissions warning off MATLAB:FILEATTRIB:SyntaxWarning fileattrib(backup_name,'+w','a'); catch error('hlp_config:permissions_error','Could not create a backup of the original config file %s. Please check file permissions and try again.',filename); end end % split the contents into lines again contents = strsplit(contents,10); try % re-create the file, line by line f = fopen(filename,'w+'); for k=1:length(contents) fwrite(f,contents{k}); fprintf(f,'\n'); end fclose(f); % set file attributes warning off MATLAB:FILEATTRIB:SyntaxWarning fileattrib(filename,'+w','a'); catch try fclose(f); catch,end error('hlp_config:permissions_error','Could not override the config file %s. Please check file permissions and try again.',filename); end % run the given config script and obtain the current value of the given variable... function [res,wspace] = run_protected(code__,varname__) try eval(code__); % collect all variables into a workspace struct infos = whos(); for n = {infos.name} if ~any(strcmp(n{1},{'code__','varname__'})) wspace.(n{1}) = eval(n{1}); end end if exist('varname__','var') % if a specific variable was to be inspected... res = eval(varname__); if ~iscell(res) || length(res) < 1 || ~all(cellfun('isclass',res,'struct')) || ~all(cellfun(@(x)isfield(x,'assignment'),res)) error('Not all assignments to the variable were correctly identified.'); end else res = []; end catch e error('hlp_config:update_error',['The config file could not be parsed (probably it is ill-formed); Debug message: ' e.message]); end % split a string without fusing delimiters (unlike hlp_split) function strs = strsplit(str, delim) idx = strfind(str, delim); strs = cell(numel(idx)+1, 1); idx = [0 idx numel(str)+1]; for k = 2:numel(idx) strs{k-1} = str(idx(k-1)+1:idx(k)-1); end % for old MATLABs that can't properly move files... function movefile(src,dst) try builtin('movefile',src,dst); catch e if any([src dst]=='$') && hlp_matlab_version <= 705 if ispc [errcode,text] = system(sprintf('move ''%s'' ''%s''',src,dst)); %#ok<NASGU> else [errcode,text] = system(sprintf('mv ''%s'' ''%s''',src,dst)); %#ok<NASGU> end if errcode error('Failed to move %s to %s.',src,dst); end else rethrow(e); end end
github
lcnbeapp/beapp-master
hlp_deserialize.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_deserialize.m
12,045
utf_8
5973cf16c3a0b718e9f334724d312870
function v = hlp_deserialize(m) % Convert a serialized byte vector back into the corresponding MATLAB data structure. % Data = hlp_deserialize(Bytes) % % In: % Bytes : a representation of the original data as a byte stream % % Out: % Data : some MATLAB data structure % % % See also: % hlp_serialize % % Examples: % bytes = hlp_serialize(mydata); % ... e.g. transfer the 'bytes' array over the network ... % mydata = hlp_deserialize(bytes); % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-04-02 % % adapted from deserialize.m % (C) 2010 Tim Hutt % wrap dispatcher v = deserialize_value(uint8(m(:)),1); end % dispatch function [v,pos] = deserialize_value(m,pos) switch m(pos) case {0,200} [v,pos] = deserialize_string(m,pos); case 128 [v,pos] = deserialize_struct(m,pos); case {33,34,35,36,37,38,39} [v,pos] = deserialize_cell(m,pos); case {1,2,3,4,5,6,7,8,9,10} [v,pos] = deserialize_scalar(m,pos); case 133 [v,pos] = deserialize_logical(m,pos); case {151,152,153} [v,pos] = deserialize_handle(m,pos); case {17,18,19,20,21,22,23,24,25,26} [v,pos] = deserialize_numeric_simple(m,pos); case 130 [v,pos] = deserialize_sparse(m,pos); case 131 [v,pos] = deserialize_complex(m,pos); case 132 [v,pos] = deserialize_char(m,pos); case 134 [v,pos] = deserialize_object(m,pos); otherwise error('Unknown class'); end end % individual scalar function [v,pos] = deserialize_scalar(m,pos) classes = {'double','single','int8','uint8','int16','uint16','int32','uint32','int64','uint64'}; sizes = [8,4,1,1,2,2,4,4,8,8]; sz = sizes(m(pos)); % Data. v = typecast(m(pos+1:pos+sz),classes{m(pos)}); pos = pos + 1 + sz; end % standard string function [v,pos] = deserialize_string(m,pos) if m(pos) == 0 % horizontal string: tag pos = pos + 1; % length (uint32) nbytes = double(typecast(m(pos:pos+3),'uint32')); pos = pos + 4; % data (chars) v = char(m(pos:pos+nbytes-1))'; pos = pos + nbytes; else % proper empty string: tag [v,pos] = deal('',pos+1); end end % general char array function [v,pos] = deserialize_char(m,pos) pos = pos + 1; % Number of dims ndms = double(m(pos)); pos = pos + 1; % Dimensions dms = double(typecast(m(pos:pos+ndms*4-1),'uint32')'); pos = pos + ndms*4; nbytes = prod(dms); % Data. v = char(m(pos:pos+nbytes-1)); pos = pos + nbytes; v = reshape(v,[dms 1 1]); end % general logical array function [v,pos] = deserialize_logical(m,pos) pos = pos + 1; % Number of dims ndms = double(m(pos)); pos = pos + 1; % Dimensions dms = double(typecast(m(pos:pos+ndms*4-1),'uint32')'); pos = pos + ndms*4; nbytes = prod(dms); % Data. v = logical(m(pos:pos+nbytes-1)); pos = pos + nbytes; v = reshape(v,[dms 1 1]); end % simple numerical matrix function [v,pos] = deserialize_numeric_simple(m,pos) classes = {'double','single','int8','uint8','int16','uint16','int32','uint32','int64','uint64'}; sizes = [8,4,1,1,2,2,4,4,8,8]; cls = classes{m(pos)-16}; sz = sizes(m(pos)-16); pos = pos + 1; % Number of dims ndms = double(m(pos)); pos = pos + 1; % Dimensions dms = double(typecast(m(pos:pos+ndms*4-1),'uint32')'); pos = pos + ndms*4; nbytes = prod(dms) * sz; % Data. v = typecast(m(pos:pos+nbytes-1),cls); pos = pos + nbytes; v = reshape(v,[dms 1 1]); end % complex matrix function [v,pos] = deserialize_complex(m,pos) pos = pos + 1; [re,pos] = deserialize_numeric_simple(m,pos); [im,pos] = deserialize_numeric_simple(m,pos); v = complex(re,im); end % sparse matrix function [v,pos] = deserialize_sparse(m,pos) pos = pos + 1; % matrix dims u = double(typecast(m(pos:pos+7),'uint64')); pos = pos + 8; v = double(typecast(m(pos:pos+7),'uint64')); pos = pos + 8; % index vectors [i,pos] = deserialize_numeric_simple(m,pos); [j,pos] = deserialize_numeric_simple(m,pos); if m(pos) % real pos = pos+1; [s,pos] = deserialize_numeric_simple(m,pos); else % complex pos = pos+1; [re,pos] = deserialize_numeric_simple(m,pos); [im,pos] = deserialize_numeric_simple(m,pos); s = complex(re,im); end v = sparse(i,j,s,u,v); end % struct array function [v,pos] = deserialize_struct(m,pos) pos = pos + 1; % Number of field names. nfields = double(typecast(m(pos:pos+3),'uint32')); pos = pos + 4; % Field name lengths fnLengths = double(typecast(m(pos:pos+nfields*4-1),'uint32')); pos = pos + nfields*4; % Field name char data fnChars = char(m(pos:pos+sum(fnLengths)-1)).'; pos = pos + length(fnChars); % Number of dims ndms = double(typecast(m(pos:pos+3),'uint32')); pos = pos + 4; % Dimensions dms = typecast(m(pos:pos+ndms*4-1),'uint32')'; pos = pos + ndms*4; % Field names. fieldNames = cell(length(fnLengths),1); splits = [0; cumsum(double(fnLengths))]; for k=1:length(splits)-1 fieldNames{k} = fnChars(splits(k)+1:splits(k+1)); end % Content. v = reshape(struct(),[dms 1 1]); if m(pos) % using struct2cell pos = pos + 1; [contents,pos] = deserialize_cell(m,pos); v = cell2struct(contents,fieldNames,1); else % using per-field cell arrays pos = pos + 1; for ff = 1:nfields [contents,pos] = deserialize_cell(m,pos); [v.(fieldNames{ff})] = deal(contents{:}); end end end % cell array function [v,pos] = deserialize_cell(m,pos) kind = m(pos); pos = pos + 1; switch kind case 33 % arbitrary/heterogenous cell array % Number of dims ndms = double(m(pos)); pos = pos + 1; % Dimensions dms = double(typecast(m(pos:pos+ndms*4-1),'uint32')'); pos = pos + ndms*4; % Contents v = cell([dms,1,1]); for ii = 1:numel(v) [v{ii},pos] = deserialize_value(m,pos); end case 34 % cell scalars [content,pos] = deserialize_value(m,pos); v = cell(size(content)); for k=1:numel(v) v{k} = content(k); end case 35 % mixed-real cell scalars [content,pos] = deserialize_value(m,pos); v = cell(size(content)); for k=1:numel(v) v{k} = content(k); end [reality,pos] = deserialize_value(m,pos); v(reality) = real(v(reality)); case 36 % cell array with horizontal or empty strings [chars,pos] = deserialize_string(m,pos); [lengths,pos] = deserialize_numeric_simple(m,pos); [empty,pos] = deserialize_logical(m,pos); v = cell(size(lengths)); splits = [0 cumsum(double(lengths(:)))']; for k=1:length(lengths) v{k} = chars(splits(k)+1:splits(k+1)); end [v{empty}] = deal(''); case 37 % empty,known type tag = m(pos); pos = pos + 1; switch tag case 1 % double - [] prot = []; case 33 % cell - {} prot = {}; case 128 % struct - struct() prot = struct(); otherwise error('Unsupported type tag.'); end % Number of dims ndms = double(m(pos)); pos = pos + 1; % Dimensions dms = typecast(m(pos:pos+ndms*4-1),'uint32')'; pos = pos + ndms*4; % Create content v = repmat({prot},dms); case 38 % empty, prototype available % Prototype. [prot,pos] = deserialize_value(m,pos); % Number of dims ndms = double(m(pos)); pos = pos + 1; % Dimensions dms = typecast(m(pos:pos+ndms*4-1),'uint32')'; pos = pos + ndms*4; % Create content v = repmat({prot},dms); case 39 % boolean flags [content,pos] = deserialize_logical(m,pos); v = cell(size(content)); for k=1:numel(v) v{k} = content(k); end otherwise error('Unsupported cell array type.'); end end % object function [v,pos] = deserialize_object(m,pos) pos = pos + 1; % Get class name. [cls,pos] = deserialize_string(m,pos); % Get contents [conts,pos] = deserialize_value(m,pos); % construct object try % try to use the loadobj function v = eval([cls '.loadobj(conts)']); catch try % pass the struct directly to the constructor v = eval([cls '(conts)']); catch try % try to set the fields manually v = feval(cls); for fn=fieldnames(conts)' try set(v,fn{1},conts.(fn{1})); catch % Note: if this happens, your deserialized object might not be fully identical % to the original (if you are lucky, it didn't matter, through). Consider % relaxing the access rights to this property or add support for loadobj from % a struct. warn_once('hlp_deserialize:restricted_access','No permission to set property %s in object of type %s.',fn{1},cls); end end catch v = conts; v.hlp_deserialize_failed = ['could not construct class: ' cls]; end end end end % function handle function [v,pos] = deserialize_handle(m,pos) % Tag kind = m(pos); pos = pos + 1; switch kind case 151 % simple function persistent db_simple; %#ok<TLEV> % database of simple functions (indexed by name) % Name [name,pos] = deserialize_string(m,pos); try % look up from table v = db_simple.(name); catch % otherwise generate & fill table v = str2func(name); db_simple.(name) = v; end case 152 % anonymous function % Function code [code,pos] = deserialize_string(m,pos); % Workspace [wspace,pos] = deserialize_struct(m,pos); % Construct v = restore_function(code,wspace); case 153 % scoped or nested function persistent db_nested; %#ok<TLEV> % database of nested functions (indexed by name) % Parents [parentage,pos] = deserialize_cell(m,pos); try key = sprintf('%s_',parentage{:}); % look up from table v = db_nested.(key); catch % recursively look up from parents, assuming that these support the arg system v = parentage{end}; for k=length(parentage)-1:-1:1 % Note: if you get an error here, you are trying to deserialize a function handle % to a nested function. This is not natively supported by MATLAB and can only be made % to work if your function's parent implements some mechanism to return such a handle. % The below call assumes that your function uses the BCILAB arg system to do this. v = arg_report('handle',v,parentage{k}); end db_nested.(key) = v; end end end % helper for deserialize_handle function f = restore_function(decl__,workspace__) % create workspace for fn__=fieldnames(workspace__)' % we use underscore names here to not run into conflicts with names defined in the workspace eval([fn__{1} ' = workspace__.(fn__{1}) ;']); end clear workspace__ fn__; % evaluate declaration f = eval(decl__); end % emit a specific warning only once (per MATLAB session) function warn_once(varargin) persistent displayed_warnings; % determine the message content if length(varargin) > 1 && any(varargin{1}==':') && ~any(varargin{1}==' ') && ischar(varargin{2}) message_content = [varargin{1} sprintf(varargin{2:end})]; else message_content = sprintf(varargin{1:end}); end % generate a hash of of the message content str = java.lang.String(message_content); message_id = sprintf('x%.0f',str.hashCode()+2^31); % and check if it had been displayed before if ~isfield(displayed_warnings,message_id) % emit the warning warning(varargin{:}); % remember to not display the warning again displayed_warnings.(message_id) = true; end end
github
lcnbeapp/beapp-master
hlp_aggregatestructs.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_aggregatestructs.m
7,805
utf_8
bab3d7ea8549fc71419a8fa5cb42447f
function res = hlp_aggregatestructs(structs,defaultop,varargin) % Aggregate structs (recursively), using the given combiner operations. % Result = hlp_aggregatestructs(Structs,Default-Op,Field-Ops...) % % This results in a single 1x1 struct which has aggregated values in its fields (e.g., arrays, % averages, etc.). For a different use case, see hlp_superimposedata. % % In: % Structs : cell array of structs to be aggregated (recursively) into a single struct % % Default-Op : optional default combiner operation to execute for every field that is not itself a % struct; see notes for the format. % % Field-Ops : name-value pairs of field-specific ops; names can have dots to denote operations % that apply to subfields. field-specific ops that apply to fields that are % themselves structures become the default op for that sub-structure % % Out: % recursively merged structure. % % Notes: % If an operation cannot be applied, a sequence of fall-backs is silently applied. First, % concatenation is tried, then, replacement is tried (which never fails). Therefore, % function_handles are being concatenated up to 2008a, and replaced starting with 2008b. % Operations are specified in one of the following formats: % * 'cat': concatenate values horizontally using [] % * 'replace': replace values by those of later structs (noncommutative) % * 'sum': sum up values % * 'mean': compute the mean value % * 'std': compute the standard deviation % * 'median': compute the median value % * 'random': pick a random value % * 'fillblanks': replace [] by values of later structs % * binary function: apply the function to aggregate pairs of values; applied in this order % f(f(f(first,second),third),fourth)... % * cell array of binary and unary function: apply the binary function to aggregate pairs of % values, then apply the unary function to finalize the result: functions {b,u} are applied in % the following order: u(b(b(b(first,second),third),fourth)) % % Examples: % % calc the average of the respective field values, across structs % hlp_aggregatestructs({result1,result2,result3},'mean') % % % calc the std deviation of the respective field values, across structs % hlp_aggregatestructs({result1,result2,result3},'std') % % % concatenate the field values across structs % hlp_aggregatestructs({result1,result2,result3},'cat') % % % as before, but use different operations for a few fields % hlp_aggregatestructs({result1,result2,result3},'cat','myfield1','mean','myfield2.subfield','median') % % % use a custom combiner operation (here: product) % hlp_aggregatestructs({result1,result2,result3},@times) % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-05-04 warning off MATLAB:warn_r14_function_handle_transition if ~exist('defaultop','var') defaultop = 'cat'; end if ~iscell(structs) structs = {structs}; end fieldops = hlp_varargin2struct(varargin); % translate all ops (if they are specified as strings) defaultop = translateop(defaultop); fieldops = translateop(fieldops); % aggregate, then finalize res = finalize(aggregate(structs,defaultop,fieldops),defaultop,fieldops); function res = aggregate(structs,defaultop,fieldops) % we skip empty records structs = structs(~cellfun('isempty',structs)); % for any struct array in the input, we first merge it recursively as if it were a cell array for k=find(cellfun('length',structs)>1) structs{k} = hlp_aggregatestructs(structarray2cellarray(structs{k}),defaultop,fieldops); end % at this point, we should have a cell array of structs if ~isempty(structs) % we begin with the first struct res = structs{1}; % and aggregate the remaining ones onto it for i=2:length(structs) si = structs{i}; % proceeding field by field... for fn=fieldnames(si)' f = fn{1}; % figure out which operation applies if isfield(fieldops,f) % a field-specific op applies if isstruct(fieldops.(f)) % ... which is itself a struct fop = fieldops.(f); else op = fieldops.(f); end else % the default op applies op = defaultop; fop = fieldops; end % now process the field if ~isfield(res,f) % field is not yet in the aggregate: just assign res.(f) = si.(f); else % need to aggregate it if isstruct(res.(f)) && isstruct(si.(f)) % both are a struct: recursively aggregate res.(f) = aggregate({res.(f),si.(f)},op,fop); else % they are not both structus try % try to apply the combiner op res.(f) = op{1}(res.(f),si.(f)); catch % didn't work: try to concatenate as fallback try res.(f) = [res.(f),si.(f)]; catch % didn't work: try to assign as fallback (dropping previous field) res.(f) = si.(f); end end end end end end else % nothing to aggregate res = []; end function x = finalize(x,defaultop,fieldops) % proceed field by field... for fn=fieldnames(x)' f = fn{1}; % figure out which operation applies if ~isempty(fieldops) && isfield(fieldops,f) % a field-specific op applies if isstruct(fieldops.(f)) % ... which is itself a struct fop = fieldops.(f); else op = fieldops.(f); end else % the default op applies op = defaultop; fop = fieldops; end try % now apply the finalizer if isstruct(x.(f)) % we have a sub-struct: recurse x.(f) = finalize(x.(f),op,fop); else % we have a regular element: apply finalizer x.(f) = op{2}(x.(f)); end catch % for empty structs, x.(f) produces no output end end % translate string ops into actual ops, add the default finalizer if missing function op = translateop(op) if isstruct(op) % recurse op = structfun(@translateop,op,'UniformOutput',false); else % remap strings if ischar(op) switch op case 'cat' op = @(a,b)[a b]; case 'replace' op = @(a,b)b; case 'sum' op = @(a,b)a+b; case 'mean' op = {@(a,b)[a b], @(x)mean(x)}; case 'median' op = {@(a,b)[a b], @(x)median(x)}; case 'std' op = {@(a,b)[a b], @(x)std(x)}; case 'random' op = {@(a,b)[a b], @(x) x(min(length(x),ceil(eps+rand(1)*length(x))))}; case 'fillblanks' op = @(a,b)fastif(isempty(a),b,a); otherwise error('unsupported combiner op specified'); end end % add finalizer if missing if ~iscell(op) op = {op,@(x)x}; end end % inefficiently turn a struct array into a cell array of structs function res = structarray2cellarray(arg) res = {}; for k=1:numel(arg) res = [res {arg(k)}]; end % for the 'fillblanks' translate op function val = fastif(cond,trueval,falseval) if cond val = trueval; else val = falseval; end
github
lcnbeapp/beapp-master
hlp_matlab_version.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_matlab_version.m
642
utf_8
56356c36dd8e15038caa4dc7b15b62b5
function v = hlp_matlab_version() % Get the MATLAB version in a numeric format that can be compared with <, >, etc. persistent vers; try v = vers(1); catch v = strsplit(version,'.'); v = str2num(v{1})*100 + str2num(v{2}); vers = v; end % Split a string according to some delimiter(s). Not as fast as hlp_split (and doesn't fuse % delimiters), but doesn't need bsxfun(). function strings = strsplit(string, splitter) ix = strfind(string, splitter); strings = cell(1,numel(ix)+1); ix = [0 ix numel(string)+1]; for k = 2 : numel(ix) strings{k-1} = string(ix(k-1)+1:ix(k)-1); end strings = strings(~cellfun('isempty',strings));
github
lcnbeapp/beapp-master
hlp_trycompile.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_trycompile.m
50,690
utf_8
cef0c2f78d5b912954b1826f6352d9e1
function ok = hlp_trycompile(varargin) % Try to auto-compile a set of binary files in a folder, and return the status. % OK = hlp_trycompile(Options...) % % This function tries to ensure that a given set of functions or classes (specified by their % MATLAB identifier), whose source files are assumed to be located in a given directory, are % properly compiled. % % The Style parameter determines how the function proceeds: Either compilation is always done % ('force'), or only if necessary ('eager', e.g. if invalid file or changed source code). The check % for re-compilation may be done on every call ('eager'), or once per MATLAB session ('lazy'). % % The most common use case is specifying a given directory (and omitting the identifiers). In this % case, all source files that have a mexFunction declaration are compiled, and all other source % files are also supplied to the compiler as additional files. In case of compilation errors, % hlp_trycompile also tries to omit all additional files during compilation. Both the list of % additional files (or their file name patterns) or the considered file types can be specified. The % list of identifiers to consider can also be specified. % % Another possible use case is to omit both the identifiers and the directory. In this case, % hlp_trycompile assumes that a mex file with the same identifier (and path) as the calling function % shall be compiled. This is would be used in .m files which directly implement some fallback code % in case that the compilation fails (or which are just stubs to trigger the on-demand compilation). % % % Since there can be many different versions of a mex binary under Linux (even with the same name), % .mex files are by default moved into a sub-directory (named according to the hostname) after % compilation. This does not apply to .class files, which are not platform-specific. % % The function supports nearly all features of the underlying MEX compiler, and can thus be used % to compile a large variety of mex packages found in the wild (in some cases with custom defines, % libraries, or include directories). % % If you are debugging code with it, it is best to set Verbose to true, so that you get compilation % output. % % Additional features of this function include: % * Figures out whether the -largeArrayDims switch should be used. % * Repeated calls of this function are very fast if used in 'lazy' mode (so that it can be used in % an inner loop). % * Automatically rebuilds if the mex source has changed (does not apply to misc dependency files), % if used in 'eager' mode. % * By default uses the Mathworks versions of BLAS and LAPACK (if these libraries are pulled in). % * Supports both '/' and '\' in directory names. % * Behaves reasonably in deployed mode (i.e. gives warnings if files are missing). % * Also compiles .java files where appropriate. % * Supports test code. % % If this function produces errors for some mex package, the most common causes are: % * If the platform has never been used to compile code, an appropriate compiler may have to be % selected using "mex -setup". If no supported compiler is installed (e.g. on Win64), it must % first be doenloaded and installed (there is a free standard compiler for every platform). % * Some unused source files are in the directory which produce errors when they are automatically % pulled in. % --> turn on verbose output and identify & remove these (or check the supplied make file for % what files are actually needed) % * The functions require a custom define switch to work. % --> Check the make file, and add the switch(es) using the 'Defines' parameter. % * The functions use non-standard C code (e.g. // comments). % --> Tentatively rename the offending .c files into .cpp. % * The functions require a specific library to work. % --> Check the make file, and add the libraries using the 'Libaries' parameter. % * The functions require specific include directories to work. % --> Check the make file, and add the directories using the 'IncludeDirectories' parameter. % * The functions require additional files that are in a different directory. % --> Check the make file, and add these files using the 'SupportFiles' parameter. Wildcards are % allowed (in particular the special '*' string, which translates into all source files in % the Directory). % * The package assumes that mex is used with the -output option to use a custom identifier name % --> This type of make acrobatic is not supported by hlp_trycompile; instead, rename the source % file which has the mexFunction definition such that it matches the target identifier. % * The functions require specific library directories to work. % --> Check the make file, and add the directories using the 'LibraryDirectories' parameter. % % % In: % Style : execution style, can be one of the following (default: 'lazy') % 'force' : force compilation (regardless of whether the binaries are already there) % 'eager' : compile only if necessary, check every time that this function is called % 'lazy' : compile only if necessary, and don't check again during this MATLAB session % % --- target files --- % % Directory : directory in which the source files are located % (default: directory of the calling function) % % Identifiers : identifier of the target function/class, or cell array of identifiers that should % be compiled (default: Calling function, if no directory given, or names of all % compilable source files in the directory, if a directory is given.) % % FileTypes : file type patterns to consider as sources files for the Identifiers % (default: {'*.f','*.c','*.cpp','*.java'}) % % % --- testing conditions --- % % TestCode : MATLAB code (string) which evaluates to true if the compiled code is behaving % correctly (and false otherwise), or alternatively a function handle which does the % same % % % --- additional compiler inputs --- % % SupportFiles : cell array of additional / supporting source filenames to include in the compilation of all % Identifiers (default: '*') % Note: Any file listed here will not be considered part of the Identifiers, when % all contents of a directory are to be compiled. % Note: If there are support source files in sub-directories, include the full path % to them. % Note: If this is '*', all source files that are not mex files in the given % directory are used as support files. % % Libraries : names of libraries to include in the compilation % (default: {}) % % IncludeDirectories : additional directories in which to search for included source files. % (default: {}) % % LibraryDirectories : additional directories in which to search for referenced library files. % (default: {}) % % Defines : list of defined symbols (either 'name' or 'name=value' strings) % (default: {}) % % Renaming : cell array of {sourcefile,identifier,sourcefile,identifier, ...} indicating that % the MEX functions generated from the respective source files should be renamed to % the given identifiers. Corresponds to MEX's -output option; does not apply to Java files. % (default: {}) % % Arguments : miscellaneous compiler arguments (default: {}) % For possible arguments, type "help mex" in the command line % % DebugBuild : whether to build binaries in debug mode (default: false) % % % --- user messages --- % % ErrorMessage : the detail error message to display which describes what type of functionality % will not be available (if any). % Note: If you have a MATLAB fallback, mention this in the error message. % % PreparationMessage : the message that will be displayed before compilation begins. % (default: {}) % % Verbose : whether to display verbose compiler outputs (default: false) % % % --- misc options --- % % MathworksLibs : whether to use the Mathworks versions of std. libraries instead of OS-supplied % ones, if present (applies to blas and lapack) (default: true) % % DebugCompile : debug the compilation process; halts in the directory prior to invoking mex % (default: false) % % % Examples: % % try to compile all mex / Java files in a given directory: % hlp_trycompile('Directory','/Extern/MySources'); % % % as before, but restrict the set of identifiers to compile to a given set % hlp_trycompile('Directory','/Extern/MySources','Identifiers',{'svmtrain','svmpredict'}); % % % try to compile mex / Java files in a given directory, and include 2 libraries in the compilation % hlp_trycompile('Directory','/Extern/MySources','Libraries',{'blas','lapack'}); % % % like before, but this time include additional source files from two other directories % % (the single '*' means: include non-mex sources in the specified directory) % hlp_trycompile('Directory','/Extern/MySources','SupportFiles',{'*','../blas/*.c','../*.cpp'}); % % % like before, but this time add an include directory, a library directory, and some library % hlp_trycompile('Directory','/Extern/MySources', 'IncludeDirectories','/boost/include','LibraryDirectories','/boost/lib','Libraries','boost_date_time-1.44'); % % % like before, this time specifying some custom #define's % hlp_trycompile('Directory','/Extern/MySources','Defines',{'DEBUG','MAX=((a)>(b)?(a):(b))'}); % % % Use cases: % 1) In addition to a source file mysvd.c (compiling into mysvd.mex*), a stub .m file of the same % name can be placed in the same directory, which contains code to compile the binary when needed. % % function [U,S,V] = mysvd(X) % if hlp_trycompile % [U,S,V] = mysvd(X); % else % % either display an error message or implement some fallback code. % end % % 2) In a MATLAB function which makes use of a few mex files, ensure compilation of these files. % function myprocessing(X,y) % if ~hlp_trycompile('Identifiers',{'svmtrain.c','svmpredict.c'}) % error('Your binary files could not be compiled.'); % else % m = svmtrain(X,y); % l = svmpredict(X,m); % ... % end % % 3) In a startup script. % hlp_trycompile('Directory','/Extern/MySources'); % % See also: % mex % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2011-03-09 persistent results; % a map of result-tag to OK value persistent compiler_selected; % whether a compiler has been selected (true/false, or [] if uncertain) % read options o = hlp_varargin2struct(varargin, ... ... % overall behavior {'style','Style'}, 'lazy', ... ... % target files {'dir','Directory'}, [], ... {'idents','Identifiers'}, [], ... {'types','FileTypes'}, {'*.c','*.C','*.cpp','*.CPP','*.f','*.F','*.java','*.Java'}, ... ... % test condition {'test','TestCode'},'', ... ... % additional compiler inputs {'support','SupportFiles'}, {'*'}, ... {'libs','Libraries'}, {}, ... {'includedirs','IncludeDirectories'}, {}, ... {'libdirs','LibraryDirectories'}, {}, ... {'defines','Defines'}, {}, ... {'args','Arguments'}, '', ... {'renaming','Renaming'}, {}, ... {'debug','DebugBuild'}, false, ... ... % messages {'errmsg','ErrorMessage'}, {'Some BCILAB functionality will likely not be available.'}, ... {'prepmsg','PreparationMessage'}, {}, ... {'verbose','Verbose'}, false, ... ... % misc {'mwlibs','MathworksLibs'}, true, ... {'debugcompile','DebugCompile'}, false ... ); % support for parameterless calls if isempty(o.dir) % if no dir given, use the calling function's directory [name,file] = hlp_getcaller(); o.dir = fileparts(file); if isempty(file) error('If hlp_trycompile is called without a directory, it must be called from within a file.'); end % if neither idents nor dir given, use the calling function's identifier if isempty(o.idents) o.idents = name; end end % uniformize ident format if isa(o.idents,'function_handle') o.idents = char(o.idents); end if ischar(o.idents) o.idents = {o.idents}; end if isempty(o.idents) o.idents = {}; end % decide whether a re-check can be skipped based on identifiers and directory if strcmp(o.style,'lazy') || isdeployed str = java.lang.String(sprintf('%s:',o.dir,o.idents{:})); tag = sprintf('x%.0f',str.hashCode()+3^31); if isfield(results,tag) ok = results.(tag); return; end end % uniformize directory format o.dir = path_normalize(o.dir); % verify style if ~any(strcmp(o.style,{'force','eager','lazy'})) error('Unsupported style: %s',o.style); end % uniformize test condition if isa(o.test,'function_handle') o.test = char(o.test); end % uniformize user messages if ischar(o.errmsg) o.errmsg = {o.errmsg}; end if ischar(o.prepmsg) o.prepmsg = {o.prepmsg}; end % uniformize types if ischar(o.types) o.types = {o.types}; end for t=1:length(o.types) if o.types{t}(1) ~= '*' o.types{t} = ['*' o.types{t}]; end end % uniformize compiler inputs if ischar(o.support) o.support = {o.support}; end if ischar(o.includedirs) o.includedirs = {o.includedirs}; end if ischar(o.libdirs) o.libdirs = {o.libdirs}; end if ischar(o.libs) o.libs = {o.libs}; end if ischar(o.defines) o.defines = {o.defines}; end if ischar(o.args) o.args = {o.args}; end for i=1:length(o.support) o.support{i} = path_normalize(o.support{i}); end for i=1:length(o.includedirs) o.includedirs{i} = path_normalize(o.includedirs{i}); end for i=1:length(o.libdirs) o.libdirs{i} = path_normalize(o.libdirs{i}); end % if a support is given as '*' starred = strcmp('*',o.support); if any(starred) % list all in the given directory that are not mex files infos = []; for t = 1:length(o.types) if ~isempty(infos) infos = [infos; dir([o.dir filesep o.types{t}])]; else infos = dir([o.dir filesep o.types{t}]); end end fnames = {infos.name}; supportfiles = ~cellfun(@(n)is_primary([o.dir filesep n]),fnames); o.support = [fnames(supportfiles) o.support(~starred)]; end % infer directory, if not given (take it from the calling function) if isempty(o.idents) && ~isempty(o.dir) % get all the source files in the given direcctory infos = []; for t = 1:length(o.types) if ~isempty(infos) infos = [infos; dir([o.dir filesep o.types{t}])]; else infos = dir([o.dir filesep o.types{t}]); end end fnames = {infos.name}; % ... but exclude the support files fnames = setdiff(fnames,o.support); % and apply any renamings to get the corresponding identifiers if ~isempty(o.renaming) for n=1:length(fnames) fnames{n} = hlp_rewrite(fnames{n},o.renaming{:}); end end % ... and strip off the extensions for n=1:length(fnames) fnames{n} = hlp_getresult(2,@fileparts,fnames{n}); end o.idents = fnames; end ok = false; missingid = []; % indices of missing identifiers (for dont-retry-next-time beacon files) if isdeployed % --- deployed mode --- % Can not compile, but figure out whether everything needed is present. A special consideration % is that both the mex files calling functions are in a mounted .ctf archive. % check if all identifiers are present (either as mex or class) for i=1:length(o.idents) if ~any(exist(o.idents{i}) == [2 3 8]) missingid(end+1) = i; end end ok = isempty(missingid); if ~isempty(missingid) % not all identifiers are compiled for this platform disp(['Note: The MEX functions/identifiers ' format_cellstr(o.idents(missingid)) ' are not included for your platform.']); elseif strcmp(o.style,'force') % in force mode, we remark that everything is already compiled disp_once(['The functions ' format_cellstr(o.idents) ' are properly compiled.']); end else % --- regular mode --- % here, we *do* compile what needs to be compiled % find out a key configuration settings is64bit = ~isempty(strfind(computer,'64')); has_largearrays = is64bit && hlp_matlab_version >= 703; if ispc warning off MATLAB:FILEATTRIB:SyntaxWarning; end % add a few missing defines if hlp_matlab_version < 703 o.defines = [o.defines {'mwIndex=int','mwSize=int','mwSignedIndex=int'}]; end % rewrite blas & lapack libs.... if o.mwlibs % for each type of library for l={'blas','lapack'} lib = l{1}; % note: this code is based on SeDuMi's compile script (by Michael C. Grant) in_use = strcmp(o.libs,lib); if any(in_use) if ispc if is64bit osdir = 'win64'; else osdir = 'win32'; end libpath = [matlabroot '\extern\lib\' osdir '\microsoft\libmw' lib '.lib']; if ~exist(libpath,'file') libpath = [matlabroot '\extern\lib\' osdir '\microsoft\msvc60\libmw' lib '.lib']; end if exist(libpath,'file') o.libs{in_use} = libpath; else disp_once('Note: The Mathworks library %s was assumed to be in %s, but not found.',lib,libpath); end else o.libs{in_use} = ['mw' lib]; end end end end try % remember the current directory & enter the target directory olddir = pwd; if hlp_matlab_version >= 706 go_back = onCleanup(@()cd(olddir)); end if ~exist(o.dir,'dir') error(['The target directory ' o.dir ' does not exist.']); end cd(o.dir); % expand regex patterns in o.support for i=length(o.support):-1:1 if any(o.support{i} == '*') found = dir(o.support{i}); if ~isempty(found) % ... and splice the results in basepath = fileparts(o.support{i}); items = cellfun(@(x)[basepath filesep x],{found.name},'UniformOutput',false); o.support = [o.support(1:i-1) items o.support(i+1:end)]; end end end % find all source & target files for the respective identifiers... % (note that there might be multiple source files for each one) sources = cell(1,length(o.idents)); % list of all source file names for the corresponding identifiers (indexed like idents) targets = cell(1,length(o.idents)); % list of all target file names for the corresponding identifiers (indexed like idents) for i=1:length(o.idents) if ~isempty(o.renaming) % the renaming may yield additional source file names for the given identifiers idx = strcmp(o.idents{i},o.renaming(2:2:end)); if any(idx) % the identifier is a renaming target: add the corresponding source file name filename = o.renaming{find(idx)*2-1}; % if a source file with this ident & type is present if exist([o.dir filesep filename],'file') % remember it & derive its respective target file name sources{i}{end+1} = filename; targets{i}{end+1} = [o.idents{i} '.' mexext]; end end end for t=1:length(o.types) filename = [o.idents{i} o.types{t}(2:end)]; % if a source file with this ident & type is present if exist([o.dir filesep filename],'file') % remember it sources{i}{end+1} = filename; % and also derive its respective target file name if strcmp(o.types{t},'*.java') targets{i}{end+1} = [o.idents{i} '.class']; else targets{i}{end+1} = [o.idents{i} '.' mexext]; end end end % check whether we have all necessary source files if isempty(sources{i}) error('Did not find source file for %s',o.idents{i}); end if isempty(targets{i}) error('Could not determine target file for %s',o.idents{i}); end end % check for existence (either .mex* or class) of all identifiers % and make a list of missing & present binary files; do this in a different directory, % to not shadow the mex files of interest with whatever .m files live in this directory cd .. binaries = {}; % table of existing binary file paths (indexed like idents) for i=1:length(o.idents) % get current file reference to this identifier binaries{i} = which(o.idents{i}); % if it doesn't point to a .mex or .class file, ignore it if ~any(exist(o.idents{i}) == [3 8]) binaries{i} = []; end if ~isempty(binaries{i}) % check whether it is correct file path if ~any(binaries{i} == filesep) error(['Could not determine the location of the mex file for: ' o.idents{i}]); end % check whether the referenced file actually exists in the file system if isempty(dir(binaries{i})) binaries{i} = []; end end % if no binary found, record it as missing if isempty(binaries{i}) missingid(end+1) = i; end end cd(o.dir); % check which of the existing binaries need to be re-compiled (if out of date) outdatedid = []; % indices of identifiers (in o.idents) that need to be recompiled for i=1:length(binaries) if ~isempty(binaries{i}) % get the date of the binary file bininfo = dir(binaries{i}); % find all corresponding source files srcinfo = []; for s=1:length(sources{i}) srcinfo = [srcinfo; dir([o.dir filesep sources{i}{s}])]; end if ~isfield(bininfo,'datenum') [bininfo.datenum] = celldeal(cellfun(@datenum,{bininfo.date},'UniformOutput',false)); end if ~isfield(srcinfo,'datenum') [srcinfo.datenum] = celldeal(cellfun(@datenum,{srcinfo.date},'UniformOutput',false)); end % if any of the source files has been changed if bininfo.datenum < max([srcinfo.datenum]) % check if their md5 hash is still the same... if exist([binaries{i} '.md5'],'file') try contents = load([binaries{i} '.md5'],'-mat','srchash'); % need to do that over all source files... srchash = []; sorted_sources = sort(sources{i}); for s=1:length(sorted_sources) srchash = [srchash hlp_cryptohash([o.dir filesep sorted_sources{s}],true)]; end if ~isequal(srchash,contents.srchash) % hash is different: mark binary as outdated outdatedid(end+1) = i; end catch % there was a probblem: mark as outdated outdatedid(end+1) = i; end else % no md5 present: mark as outdated outdatedid(end+1) = i; end end end end % we try to recompile both what's missing and what's outdated recompileid = [missingid outdatedid]; javainvolved = false; % for final error/help message generation mexinvolved = false; % same if ~isempty(recompileid) % need to recompile something -- display a few preparatory messages... for l=1:length(o.prepmsg) disp(o.prepmsg{l}); end failedid = []; % list of indices of identifier that failed the build % for each identifier, try to compile it % and record whether it failed for i=recompileid success = false; fprintf(['Compiling the function/class ' o.idents{i} '...']); % for each source file mapping to that identifier for s=1:length(sources{i}) % check type of source if ~isempty(strfind(sources{i}{s},'.java')) % we have a Java source file: compile [errcode,result] = system(['javac ' javac_options(o) sources{i}{s}]); if errcode javainvolved = true; % problem: show display output fprintf('\n'); disp(result); else success = true; break; end else % generate MEX options opts = mex_options(o); supp = sprintf(' %s',o.support{:}); if isempty(compiler_selected) % not clear whether a compiler has been selected yet if hlp_matlab_version >= 708 % we can find it out programmatically try cconf = mex.getCompilerConfigurations; %#ok<NASGU> compiler_selected = true; catch % no compiler has been selected yet... try % display a few useful hints to the user disp(' to compile this feature, you first need to select'); disp('which compiler should be used on your platform.'); if ispc if is64bit disp_once('As you are on 64-bit windows, you may find that no compiler is installed.'); else disp_once('On 32-bit Windows, MATLAB supplies a built-in compiler (LLC), which should'); disp_once('faithfully compile most C code. For broader support across C dialects (as well as C++), '); disp_once('you should make sure that a better compiler is installed on your system and selected in the following.'); end disp_once('A good choice is the free Microsoft Visual Studio 2005/2008/2010 Express compiler suite'); disp_once('together with the Microsoft Platform SDK (6.1 for 2008, 7.1 for 2010) for your Windows Version.'); disp_once('See also: http://argus-home.coas.oregonstate.edu/forums/development/core-software-development/compiling-64-bit-mex-files'); disp_once(' http://www.mathworks.com/support/compilers/R2010b/win64.html'); disp_once('The installation is easier if a professional Intel or Microsoft compiler is used.'); elseif isunix disp_once('On Linux/UNIX, the best choice is usually a supported version of the GCC compiler suite.'); else disp_once('On Mac OS, you need to have a supported version of Xcode/GCC installed.'); end % start the compiler selection tool mex -setup % verify that a compiler has been selected cconf = mex.getCompilerConfigurations; %#ok<NASGU> compiler_selected = true; catch compiler_selected = false; end end else disp(' you may be prompted to select a compiler in the following'); disp('(as BCILAB cannot auto-determine whether one is selected on your platform).'); end end if ~compiler_selected fprintf('skipped (no compiler selected).\n'); else if o.verbose || isempty(compiler_selected) % this variant will also be brought up if not sure whether a compiler % has already been selected... doeval = @eval; else doeval = @evalc; end % try to build the file try mexinvolved = true; % check if a renaming applies... idx = strcmp(sources{i}{s},o.renaming); if any(idx) rename = [' -output ' o.renaming{find(idx,1)+1} ' ']; else rename = ''; end if o.debugcompile % display a debug console to allow the user to debug how their file compiles fprintf('\nExecution has been paused immediately before running mex.\n'); disp(['You are in the directory "' pwd '".']); disp('The mex command that will be invoked in the following is:'); if has_largearrays disp([' mex ' opts ' -largeArrayDims ' rename sources{i}{s} supp]); else disp([' mex ' opts rename sources{i}{s} supp]); end fprintf('\n\nTo proceed normally, type "dbcont".\n'); keyboard; end if has_largearrays try % -largeArrayDims enabled try doeval(['mex ' opts ' -largeArrayDims ' rename sources{i}{s} supp]); % with supporting libaries catch doeval(['mex ' opts ' -largeArrayDims ' rename sources{i}{s}]); % without supporting libraries end catch % -largeArrayDims disabled try doeval(['mex ' opts rename sources{i}{s} supp]); % with supporting libaries catch doeval(['mex ' opts rename sources{i}{s}]); % without supporting libraries end end else % -largeArrayDims disabled try doeval(['mex ' opts rename sources{i}{s} supp]); % with supporting libaries catch doeval(['mex ' opts rename sources{i}{s}]); % without supporting libraries end end % compilation succeeded... if any(i==outdatedid) % there is an outdated binary, which needs to be deleted try delete(binaries{i}); catch disp(['Could not delete outdated binary ' binaries{i}]); end end % check whether the file is being found now if exist(o.idents{i}) == 3 success = true; compiler_selected = true; break; end catch % build failed end end end end % check if compilation of this identifier was successful if success % if so, we sign off the binary with an md5 hash of the sources... newbinary = which(o.idents{i}); try srchash = []; sorted_sources = sort(sources{i}); for s=1:length(sorted_sources) srchash = [srchash hlp_cryptohash([o.dir filesep sorted_sources{s}],true)]; end save([newbinary '.md5'],'srchash','-mat'); fprintf('success.\n'); catch disp('could not create md5 hash for the source files; other than that, successful.'); end else fprintf('failed.\n'); failedid(end+1) = i; end end embed_test = false; if isempty(failedid) % all worked: now run the test code - if any - to verify the correctness of the build if length(recompileid) > 1 if ~isempty(o.test) fprintf('All files in %s compiled successfully; now testing the build outputs...',o.dir); else fprintf('All files in %s compiled successfully.\n',o.dir); end elseif ~isempty(o.test) fprintf('Now testing the build outputs...'); end % test the output try ans = true; %#ok<NOANS> eval(o.test); catch ans = false; %#ok<NOANS> end if ans %#ok<NOANS> % the test was successful; now copy the files into a platform-specific directory if ~isempty(o.test) % only if we have a succeeding non-empty test embed_test = true; fprintf('success.\n'); end retainid = recompileid; eraseid = []; ok = true; else % the test was unsuccessful: remove all newly-compiled files... if ~isempty(o.test) fprintf('failed.\n'); end disp('The code compiled correctly but failed the build tests. Reverting the build...'); disp('If this is unmodified BCILAB code, please consider reporting this issue.'); retainid = []; eraseid = recompileid; end else if length(recompileid) > 1 if isempty(setdiff(recompileid,failedid)) fprintf('All files in %s failed to build; this indicates a problem in your build environment/settings.\n',o.dir); else fprintf('Some files in %s failed to build. Please make sure that you have a supported compiler; otherwise, please report this issue.\n',o.dir); end else disp('Please make sure that you have a supported compiler and that your build environment is set up correctly.'); disp('Also, please consider reporting this issue.'); end % compilation failed; only a part of the binaries may be available... retainid = setdiff(recompileid,failedid); eraseid = []; end % move the mex files into their own directory moveid = retainid(cellfun(@exist,o.idents(retainid)) == 3); if ~isempty(moveid) % some files to be moved dest_path = [o.dir filesep 'build-' hlp_hostname filesep]; % create a new directory if ~exist(dest_path,'dir') if ~mkdir(o.dir,['build-' hlp_hostname]) error(['unable to create directory ' dest_path]); end % set permissions try fileattrib(dest_path,'+w','a'); catch disp(['Note: There are permission problems for the directory ' dest_path]); end end % create a new env_add.m there try filename = [dest_path 'env_add.m']; fid = fopen(filename,'w+'); if embed_test % if we had a successful test, we use this to control inclusion of the mex files fprintf(fid,o.test); else % otherwise we check whether any one of the identifiers is recognized by % MATLAB as a mex function fprintf(fid,'any(cellfun(@exist,%s)==3)',hlp_tostring(o.idents(moveid))); end fclose(fid); fileattrib(filename,'+w','a'); catch disp(['Note: There were write permission problems for the file ' filename]); end % move the targets over there... movefiles = unique(o.idents(moveid)); for t = 1:length(movefiles) [d,n,x] = fileparts(which(movefiles{t})); movefile([d filesep n x],[dest_path n x]); try movefile([d filesep n x '.md5'],[dest_path n x '.md5']); catch end end % add the destination path addpath(dest_path); % and to be entirely sure, CD into that directory to verify that the files are being recognized... % (and don't get shadowed by whatever is in the directory below) cd(dest_path); all_ok = all(strncmp(dest_path,cellfun(@which,o.idents(moveid),'UniformOutput',false),length(dest_path))); cd(o.dir); % make sure that they are still being found... if ~all_ok error('It could not be verified that the MEX file records in %s were successfully updated to their new sub-directories.',o.dir); end end % move the java class files into their own directory infos = dir([o.dir filesep '*.class']); movefiles = {infos.name}; moveid = retainid(cellfun(@exist,o.idents(retainid)) ~= 3); if ~isempty(movefiles) % some files to be moved dest_path = [o.dir filesep 'build-javaclasses' filesep]; % create a new directory if ~exist(dest_path,'dir') if ~mkdir(o.dir,'build-javaclasses') error(['unable to create directory ' dest_path]); end % set permissions try fileattrib(dest_path,'+w','a'); catch disp(['Note: There are permission problems for the directory ' dest_path]); end end % create a new env_add.m there try filename = [dest_path 'env_add.m']; fid = fopen(filename,'w+'); fclose(fid); fileattrib(filename,'+w','a'); catch disp(['Note: There were write permission problems for the file ' filename]); end % move the targets over there... for t = 1:length(movefiles) movefile([o.dir filesep movefiles{t}],[dest_path movefiles{t}]); try movefile([o.dir filesep movefiles{t} '.md5'],[dest_path movefiles{t} '.md5']); catch end end % add the destination path if isdeployed warning off MATLAB:javaclasspath:jarAlreadySpecified; end javaaddpath(dest_path); % check whether the class is found if ~all(cellfun(@exist,o.idents(moveid)) == 8) disp_once('Not all Java binaries in %s could be recognized by MATLAB.',dest_path); end end if ~isempty(eraseid) % some files need to be erased... for k=eraseid for t=1:length(targets{k}) if exist([o.dir filesep targets{k}{t}]) try delete(targets{k}{t}); catch disp(['Could not delete broken binary ' binaries{i}{s}]); end end end end end else % nothing to recompile ok = true; if strcmp(o.style,'eager') && ~isempty(o.idents) && o.verbose disp_once(['The functions ' format_cellstr(o.idents) ' are already compiled.']); end end % go back to the old directory if hlp_matlab_version < 706 cd(olddir); end catch e ok = false; %#ok<NASGU> % go back to the old path in case of an error if hlp_matlab_version < 706 cd(olddir); end rethrow(e); end end % store the OK flag in the results if strcmp(o.style,'lazy') || isdeployed results.(tag) = ok; end if ~ok if ~isdeployed % regular error summary if mexinvolved disp_once('\nIn case you need to use a better / fully supported compiler, please have a look at:'); try v=version; releasename = v(find(v=='(')+1 : find(v==')')-1); if length(releasename) > 3 && releasename(1) == 'R' releasename = releasename(2:end); end site = ['http://www.google.com/search?q=matlab+supported+compilers+' releasename]; catch site = 'http://www.google.com/search?q=matlab+supported+compilers'; end disp_once(' <a href="%s">%s</a>\n',site,site); if ispc if is64bit disp_once('On 64-bit Windows, MATLAB comes with no built-in compiler, so you need to have one installed.'); else disp_once('On 32-bit Windows, MATLAB supplies a built-in compiler (LLC), which is, however, not very good.'); end disp_once('A good choice is the free Microsoft Visual Studio 2005/2008/2010 Express compiler suite'); disp_once('together with the Microsoft Platform SDK (6.1 for 2008, 7.1 for 2010) for your Windows Version.'); disp_once('See also: http://argus-home.coas.oregonstate.edu/forums/development/core-software-development/compiling-64-bit-mex-files'); disp_once(' http://www.mathworks.com/support/compilers/R2010b/win64.html'); disp_once('The installation is easier if a professional Intel or Microsoft compiler is used.'); elseif isunix disp_once('On Linux/UNIX, the best choice is usually a supported version of the GCC compiler suite.'); else disp_once('On Mac OS, you need to have a supported version of Xcode/GCC installed.'); end end if javainvolved disp_once('Please make sure that your system''s java configuration matches the one used by MATLAB (see "ver" command).'); end end end % create javac options string from options struct function opts = javac_options(o) verbosity = hlp_rewrite(o.verbose,true,'-verbose',false,''); if ~isempty(o.libdirs) cpath = ['-classpath ' sprintf('%s;',o.libdirs{:})]; cpath(end) = []; else cpath = ''; end if ~isempty(o.includedirs) ipath = ['-sourcepath ' sprintf('%s;',o.includedirs{:})]; ipath(end) = []; else ipath = ''; end debugness = hlp_rewrite(o.debug,true,'-g',false,'-g:none'); targetsource = '-target 1.6 -source 1.6'; opts = [sprintf(' %s',verbosity,cpath,ipath,debugness,targetsource) ' ']; % create mex options string from options struct function opts = mex_options(o) if ~isempty(o.defines) defs = sprintf(' -D%s',o.defines{:}); else defs = ''; end debugness = hlp_rewrite(o.debug,true,'-g',false,''); if ~isempty(o.includedirs) incdirs = sprintf(' -I"%s"',o.includedirs{:}); else incdirs = ''; end if ~isempty(o.libs) if ispc libs = sprintf(' -l"%s"',o.libs{:}); else libs = sprintf(' -l%s',o.libs{:}); end else libs = ''; end if ~isempty(o.libdirs) libdirs = sprintf(' -L"%s"',o.libdirs{:}); else libdirs = ''; end verbosity = hlp_rewrite(o.verbose,true,'-v',false,''); opts = [sprintf(' %s',defs,debugness,incdirs,libs,libdirs,verbosity) ' ']; % format a non-empty cell-string array into a string function x = format_cellstr(x) if isempty(x) x = ''; else x = ['{' sprintf('%s, ',x{1:end-1}) x{end} '}']; end % check whether a given identifier is frozen in a ctf archive function tf = in_ctf(ident) %#ok<DEFNU> tf = isdeployed && strncmp(ctfroot,which(ident),length(ctfroot)); % normalize a directory path function dir = path_normalize(dir) if filesep == '\'; dir(dir == '/') = filesep; else dir(dir == '\') = filesep; end if dir(end) == filesep dir = dir(1:end-1); end % determine if a given file is a mex source file or a java source file % (and compiles into an identifier that is seen by MATLAB) function tf = is_primary(filename) if length(filename)>5 && strcmp(filename(end-4:end),'.java') tf = true; return; else tf = false; end fid = fopen(filename); if fid ~= -1 try contents = fread(fid); tf = ~isempty(strfind(char(contents)','mexFunction')); %#ok<FREAD> fclose(fid); catch fclose(fid); end end % act like deal, but with a single cell array as input function varargout = celldeal(argin) varargout = argin; % for old MATLABs that can't properly move files... function movefile(src,dst) try builtin('movefile',src,dst); catch e if any([src dst]=='$') && hlp_matlab_version <= 705 if ispc [errcode,text] = system(sprintf('move ''%s'' ''%s''',src,dst)); %#ok<NASGU> else [errcode,text] = system(sprintf('mv ''%s'' ''%s''',src,dst)); %#ok<NASGU> end if errcode error('Failed to move %s to %s.',src,dst); end else rethrow(e); end end % for old MATLABs that don't handle Java classes on the dynamic path... function res = exist(obj,type) if nargin > 1 res = builtin('exist',obj,type); if ~res && (hlp_matlab_version <= 704) && strcmp(type,'class') && builtin('exist',[obj '.class'],'file') res = 8; end else res = builtin('exist',obj); if ~res && (hlp_matlab_version <= 704) && builtin('exist',[obj '.class']) res = 8; end end % for old MATLABs that don't handle Java classes on the dynamic path... function res = which(ident) res = builtin('which',ident); if ~any(res == filesep) if hlp_matlab_version <= 704 if isempty(res) || ~isempty(strfind(res,'not found')) res = builtin('which',[ident '.class']); end else if ~isempty(strfind(res,'Java')) res = builtin('which',[ident '.class']); end end end
github
lcnbeapp/beapp-master
hlp_serialize.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_serialize.m
15,821
utf_8
90ee89875e34a4a84c3e58d9657c04f1
function m = hlp_serialize(v) % Convert a MATLAB data structure into a compact byte vector. % Bytes = hlp_serialize(Data) % % The original data structure can be recovered from the byte vector via hlp_deserialize. % % In: % Data : some MATLAB data structure % % Out: % Bytes : a representation of the original data as a byte stream % % Notes: % The code is a rewrite of Tim Hutt's serialization code. Support has been added for correct % recovery of sparse, complex, single, (u)intX, function handles, anonymous functions, objects, % and structures with unlimited field count. Serialize/deserialize performance is ~10x higher. % % Limitations: % * Java objects cannot be serialized % * Arrays with more than 255 dimensions have their last dimensions clamped % * Handles to nested/scoped functions can only be deserialized when their parent functions % support the BCILAB argument reporting protocol (e.g., by using arg_define). % * New MATLAB objects need to be reasonably friendly to serialization; either they support % construction from a struct, or they support saveobj/loadobj(struct), or all their important % properties can be set via set(obj,'name',value) % * In anonymous functions, accessing unreferenced variables in the workspace of the original % declaration via eval(in) works only if manually enabled via the global variable % tracking.serialize_anonymous_fully (possibly at a significant performance hit). % note: this feature is currently not rock solid and can be broken either by Ctrl+C'ing % in the wrong moment or by concurrently serializing from MATLAB timers. % % See also: % hlp_deserialize % % Examples: % bytes = hlp_serialize(mydata); % ... e.g. transfer the 'bytes' array over the network ... % mydata = hlp_deserialize(bytes); % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-04-02 % % adapted from serialize.m % (C) 2010 Tim Hutt % dispatch according to type if isnumeric(v) m = serialize_numeric(v); elseif ischar(v) m = serialize_string(v); elseif iscell(v) m = serialize_cell(v); elseif isstruct(v) m = serialize_struct(v); elseif isa(v,'function_handle') m = serialize_handle(v); elseif islogical(v) m = serialize_logical(v); elseif isobject(v) m = serialize_object(v); elseif isjava(v) warn_once('hlp_serialize:cannot_serialize_java','Cannot properly serialize Java class %s; using a placeholder instead.',class(v)); m = serialize_string(['<<hlp_serialize: ' class(v) ' unsupported>>']); else try m = serialize_object(v); catch warn_once('hlp_serialize:unknown_type','Cannot properly serialize object of unknown type "%s"; using a placeholder instead.',class(v)); m = serialize_string(['<<hlp_serialize: ' class(v) ' unsupported>>']); end end end % single scalar function m = serialize_scalar(v) % Data type & data m = [class2tag(class(v)); typecast(v,'uint8').']; end % char arrays function m = serialize_string(v) if size(v,1) == 1 % horizontal string: Type, Length, and Data m = [uint8(0); typecast(uint32(length(v)),'uint8').'; uint8(v(:))]; elseif sum(size(v)) == 0 % '': special encoding m = uint8(200); else % general char array: Tag & Number of dimensions, Dimensions, Data m = [uint8(132); ndims(v); typecast(uint32(size(v)),'uint8').'; uint8(v(:))]; end end % logical arrays function m = serialize_logical(v) % Tag & Number of dimensions, Dimensions, Data m = [uint8(133); ndims(v); typecast(uint32(size(v)),'uint8').'; uint8(v(:))]; end % non-complex and non-sparse numerical matrix function m = serialize_numeric_simple(v) % Tag & Number of dimensions, Dimensions, Data m = [16+class2tag(class(v)); ndims(v); typecast(uint32(size(v)),'uint8').'; typecast(v(:).','uint8').']; end % Numeric Matrix: can be real/complex, sparse/full, scalar function m = serialize_numeric(v) if issparse(v) % Data Type & Dimensions m = [uint8(130); typecast(uint64(size(v,1)), 'uint8').'; typecast(uint64(size(v,2)), 'uint8').']; % vectorize % Index vectors [i,j,s] = find(v); % Real/Complex if isreal(v) m = [m; serialize_numeric_simple(i); serialize_numeric_simple(j); 1; serialize_numeric_simple(s)]; else m = [m; serialize_numeric_simple(i); serialize_numeric_simple(j); 0; serialize_numeric_simple(real(s)); serialize_numeric_simple(imag(s))]; end elseif ~isreal(v) % Data type & contents m = [uint8(131); serialize_numeric_simple(real(v)); serialize_numeric_simple(imag(v))]; elseif isscalar(v) % Scalar m = serialize_scalar(v); else % Simple matrix m = serialize_numeric_simple(v); end end % Struct array. function m = serialize_struct(v) % Tag, Field Count, Field name lengths, Field name char data, #dimensions, dimensions fieldNames = fieldnames(v); fnLengths = [length(fieldNames); cellfun('length',fieldNames)]; fnChars = [fieldNames{:}]; dims = [ndims(v) size(v)]; m = [uint8(128); typecast(uint32(fnLengths(:)).','uint8').'; uint8(fnChars(:)); typecast(uint32(dims), 'uint8').']; % Content. if numel(v) > length(fieldNames) % more records than field names; serialize each field as a cell array to expose homogenous content tmp = cellfun(@(f)serialize_cell({v.(f)}),fieldNames,'UniformOutput',false); m = [m; 0; vertcat(tmp{:})]; else % more field names than records; use struct2cell m = [m; 1; serialize_cell(struct2cell(v))]; end end % Cell array of heterogenous contents function m = serialize_cell_heterogenous(v) contents = cellfun(@hlp_serialize,v,'UniformOutput',false); m = [uint8(33); ndims(v); typecast(uint32(size(v)),'uint8').'; vertcat(contents{:})]; end % Cell array of homogenously-typed contents function m = serialize_cell_typed(v,serializer) contents = cellfun(serializer,v,'UniformOutput',false); m = [uint8(33); ndims(v); typecast(uint32(size(v)),'uint8').'; vertcat(contents{:})]; end % Cell array function m = serialize_cell(v) sizeprod = cellfun('prodofsize',v); if sizeprod == 1 % all scalar elements if (all(cellfun('isclass',v(:),'double')) || all(cellfun('isclass',v(:),'single'))) && all(~cellfun(@issparse,v(:))) % uniformly typed floating-point scalars (and non-sparse) reality = cellfun('isreal',v); if reality % all real m = [uint8(34); serialize_numeric_simple(reshape([v{:}],size(v)))]; elseif ~reality % all complex m = [uint8(34); serialize_numeric(reshape([v{:}],size(v)))]; else % mixed reality m = [uint8(35); serialize_numeric(reshape([v{:}],size(v))); serialize_logical(reality(:))]; end else % non-float types if cellfun('isclass',v,'struct') % structs m = serialize_cell_typed(v,@serialize_struct); elseif cellfun('isclass',v,'cell') % cells m = serialize_cell_typed(v,@serialize_cell); elseif cellfun('isclass',v,'logical') % bool flags m = [uint8(39); serialize_logical(reshape([v{:}],size(v)))]; elseif cellfun('isclass',v,'function_handle') % function handles m = serialize_cell_typed(v,@serialize_handle); else % arbitrary / mixed types m = serialize_cell_heterogenous(v); end end elseif isempty(v) % empty cell array m = [uint8(33); ndims(v); typecast(uint32(size(v)),'uint8').']; else % some non-scalar elements dims = cellfun('ndims',v); size1 = cellfun('size',v,1); size2 = cellfun('size',v,2); if cellfun('isclass',v,'char') & size1 <= 1 %#ok<AND2> % all horizontal strings or proper empty strings m = [uint8(36); serialize_string([v{:}]); serialize_numeric_simple(uint32(size2)); serialize_logical(size1(:)==0)]; elseif (size1+size2 == 0) & (dims == 2) %#ok<AND2> % all empty and non-degenerate elements if all(cellfun('isclass',v(:),'double')) || all(cellfun('isclass',v(:),'cell')) || all(cellfun('isclass',v(:),'struct')) % of standard data types: Tag, Type Tag, #Dims, Dims m = [uint8(37); class2tag(class(v{1})); ndims(v); typecast(uint32(size(v)),'uint8').']; elseif length(unique(cellfun(@class,v(:),'UniformOutput',false))) == 1 % of uniform class with prototype m = [uint8(38); hlp_serialize(class(v{1})); ndims(v); typecast(uint32(size(v)),'uint8').']; else % of arbitrary classes m = serialize_cell_heterogenous(v); end else % arbitrary sizes (and types, etc.) m = serialize_cell_heterogenous(v); end end end % Object / class function m = serialize_object(v) try % try to use the saveobj method first to get the contents conts = saveobj(v); if isstruct(conts) || iscell(conts) || isnumeric(conts) || ischar(conts) || islogical(conts) || isa(conts,'function_handle') % contents is something that we can readily serialize conts = hlp_serialize(conts); else % contents is still an object: turn into a struct now conts = serialize_struct(struct(conts)); end catch % saveobj failed for this object: turn into a struct conts = serialize_struct(struct(v)); end % Tag, Class name and Contents m = [uint8(134); serialize_string(class(v)); conts]; end % Function handle function m = serialize_handle(v) % get the representation rep = functions(v); switch rep.type case 'simple' % simple function: Tag & name m = [uint8(151); serialize_string(rep.function)]; case 'anonymous' global tracking; %#ok<TLEV> if isfield(tracking,'serialize_anonymous_fully') && tracking.serialize_anonymous_fully % serialize anonymous function with their entire variable environment (for complete % eval and evalin support). Requires a stack of function id's, as function handles % can reference themselves in their full workspace. persistent handle_stack; %#ok<TLEV> % Tag and Code m = [uint8(152); serialize_string(char(v))]; % take care of self-references str = java.lang.String(rep.function); func_id = str.hashCode(); if ~any(handle_stack == func_id) try % push the function id handle_stack(end+1) = func_id; % now serialize workspace m = [m; serialize_struct(rep.workspace{end})]; % pop the ID again handle_stack(end) = []; catch e % note: Ctrl-C can mess up the handle stack handle_stack(end) = []; %#ok<NASGU> rethrow(e); end else % serialize the empty workspace m = [m; serialize_struct(struct())]; end if length(m) > 2^18 % If you are getting this warning, it is likely that one of your anonymous functions % was created in a scope that contained large variables; MATLAB will implicitly keep % these variables around (referenced by the function) just in case you refer to them. % To avoid this, you can create the anonymous function instead in a sub-function % to which you only pass the variables that you actually need. warn_once('hlp_serialize:large_handle','The function handle with code %s references variables of more than 256k bytes; this is likely very slow.',rep.function); end else % anonymous function: Tag, Code, and reduced workspace if ~isempty(rep.workspace) m = [uint8(152); serialize_string(char(v)); serialize_struct(rep.workspace{1})]; else m = [uint8(152); serialize_string(char(v)); serialize_struct(struct())]; end end case {'scopedfunction','nested'} % scoped function: Tag and Parentage m = [uint8(153); serialize_cell(rep.parentage)]; otherwise warn_once('hlp_serialize:unknown_handle_type','A function handle with unsupported type "%s" was encountered; using a placeholder instead.',rep.type); m = serialize_string(['<<hlp_serialize: function handle of type ' rep.type ' unsupported>>']); end end % *container* class to byte function b = class2tag(cls) switch cls case 'string' b = uint8(0); case 'double' b = uint8(1); case 'single' b = uint8(2); case 'int8' b = uint8(3); case 'uint8' b = uint8(4); case 'int16' b = uint8(5); case 'uint16' b = uint8(6); case 'int32' b = uint8(7); case 'uint32' b = uint8(8); case 'int64' b = uint8(9); case 'uint64' b = uint8(10); % other tags are as follows: % % offset by +16: scalar variants of these... % case 'cell' % b = uint8(33); % case 'cellscalars' % b = uint8(34); % case 'cellscalarsmixed' % b = uint8(35); % case 'cellstrings' % b = uint8(36); % case 'cellempty' % b = uint8(37); % case 'cellemptyprot' % b = uint8(38); % case 'cellbools' % b = uint8(39); % case 'struct' % b = uint8(128); % case 'sparse' % b = uint8(130); % case 'complex' % b = uint8(131); % case 'char' % b = uint8(132); % case 'logical' % b = uint8(133); % case 'object' % b = uint8(134); % case 'function_handle' % b = uint8(150); % case 'function_simple' % b = uint8(151); % case 'function_anon' % b = uint8(152); % case 'function_scoped' % b = uint8(153); % case 'emptystring' % b = uint8(200); otherwise error('Unknown class'); end end % emit a specific warning only once (per MATLAB session) function warn_once(varargin) persistent displayed_warnings; % determine the message content if length(varargin) > 1 && any(varargin{1}==':') && ~any(varargin{1}==' ') && ischar(varargin{2}) message_content = [varargin{1} sprintf(varargin{2:end})]; else message_content = sprintf(varargin{1:end}); end % generate a hash of of the message content str = java.lang.String(message_content); message_id = sprintf('x%.0f',str.hashCode()+2^31); % and check if it had been displayed before if ~isfield(displayed_warnings,message_id) % emit the warning warning(varargin{:}); % remember to not display the warning again displayed_warnings.(message_id) = true; end end
github
lcnbeapp/beapp-master
hlp_varargin2struct.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_varargin2struct.m
6,267
utf_8
a185d699c488adb84cda30f6db5facda
function res = hlp_varargin2struct(args, varargin) % Convert a list of name-value pairs into a struct with values assigned to names. % struct = hlp_varargin2struct(Varargin, Defaults) % % In: % Varargin : cell array of name-value pairs and/or structs (with values assigned to names) % % Defaults : optional list of name-value pairs, encoding defaults; multiple alternative names may % be specified in a cell array % % Example: % function myfunc(x,y,z,varargin) % % parse options, and give defaults for some of them: % options = hlp_varargin2struct(varargin, 'somearg',10, 'anotherarg',{1 2 3}); % % Notes: % * mandatory args can be expressed by specifying them as ..., 'myparam',mandatory, ... in the defaults % an error is raised when any of those is left unspecified % % * the following two parameter lists are equivalent (note that the struct is specified where a name would be expected, % and that it replaces the entire name-value pair): % ..., 'xyz',5, 'a',[], 'test','toast', 'xxx',{1}. ... % ..., 'xyz',5, struct( 'a',{[]},'test',{'toast'} ), 'xxx',{1}, ... % % * names with dots are allowed, i.e.: ..., 'abc',5, 'xxx.a',10, 'xxx.yyy',20, ... % % * some parameters may have multiple alternative names, which shall be remapped to the % standard name within opts; alternative names are given together with the defaults, % by specifying a cell array of names instead of the name in the defaults, as in the following example: % ... ,{'standard_name','alt_name_x','alt_name_y'}, 20, ... % % Out: % Result : a struct with fields corresponding to the passed arguments (plus the defaults that were % not overridden); if the caller function does not retrieve the struct, the variables are % instead copied into the caller's workspace. % % Examples: % % define a function which takes some of its arguments as name-value pairs % function myfunction(myarg1,myarg2,varargin) % opts = hlp_varargin2struct(varargin, 'myarg3',10, 'myarg4',1001, 'myarg5','test'); % % % as before, but this time allow an alternative name for myarg3 % function myfunction(myarg1,myarg2,varargin) % opts = hlp_varargin2struct(varargin, {'myarg3','legacyargXY'},10, 'myarg4',1001, 'myarg5','test'); % % % as before, but this time do not return arguments in a struct, but assign them directly to the % % function's workspace % function myfunction(myarg1,myarg2,varargin) % hlp_varargin2struct(varargin, {'myarg3','legacyargXY'},10, 'myarg4',1001, 'myarg5','test'); % % See also: % hlp_struct2varargin, arg_define % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-04-05 % a struct was specified as first argument if isstruct(args) args = {args}; end % --- handle defaults --- if ~isempty(varargin) % splice substructs into the name-value list if any(cellfun('isclass',varargin(1:2:end),'struct')) varargin = flatten_structs(varargin); end defnames = varargin(1:2:end); defvalues = varargin(2:2:end); % make a remapping table for alternative default names... for k=find(cellfun('isclass',defnames,'cell')) for l=2:length(defnames{k}) name_for_alternative.(defnames{k}{l}) = defnames{k}{1}; end defnames{k} = defnames{k}{1}; end % create default struct if [defnames{:}]~='.' % use only the last assignment for each name [s,indices] = sort(defnames(:)); indices( strcmp(s((1:end-1)'),s((2:end)'))) = []; % and make the struct res = cell2struct(defvalues(indices),defnames(indices),2); else % some dot-assignments are contained in the defaults try res = struct(); for k=1:length(defnames) if any(defnames{k}=='.') eval(['res.' defnames{k} ' = defvalues{k};']); else res.(defnames{k}) = defvalues{k}; end end catch error(['invalid field name specified in defaults: ' defnames{k}]); end end else res = struct(); end % --- handle overrides --- if ~isempty(args) % splice substructs into the name-value list if any(cellfun('isclass',args(1:2:end),'struct')) args = flatten_structs(args); end % rewrite alternative names into their standard form... if exist('name_for_alternative','var') for k=1:2:length(args) if isfield(name_for_alternative,args{k}) args{k} = name_for_alternative.(args{k}); end end end % override defaults with arguments... try if [args{1:2:end}]~='.' for k=1:2:length(args) res.(args{k}) = args{k+1}; end else % some dot-assignments are contained in the overrides for k=1:2:length(args) if any(args{k}=='.') eval(['res.' args{k} ' = args{k+1};']); else res.(args{k}) = args{k+1}; end end end catch if ischar(args{k}) error(['invalid field name specified in arguments: ' args{k}]); else error(['invalid field name specified for the argument at position ' num2str(k)]); end end end % check for missing but mandatory args % note: the used string needs to match mandatory.m missing_entries = strcmp('__arg_mandatory__',struct2cell(res)); if any(missing_entries) fn = fieldnames(res)'; fn = fn(missing_entries); error(['The parameters {' sprintf('%s, ',fn{1:end-1}) fn{end} '} were unspecified but are mandatory.']); end % copy to the caller's workspace if no output requested if nargout == 0 for fn=fieldnames(res)' assignin('caller',fn{1},res.(fn{1})); end end % substitute any structs in place of a name-value pair into the name-value list function args = flatten_structs(args) k = 1; while k <= length(args) if isstruct(args{k}) tmp = [fieldnames(args{k}) struct2cell(args{k})]'; args = [args(1:k-1) tmp(:)' args(k+1:end)]; k = k+numel(tmp); else k = k+2; end end
github
lcnbeapp/beapp-master
hlp_worker.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_worker.m
5,701
utf_8
912f4bd9ba397e3e40f05b77f7bf1fb5
function hlp_worker(varargin) % Act as a lightweight worker process for use with hlp_schedule. % hlp_worker(Options...) % % Receives commands (string expressions) from the network, evaluate them, and send off the result to % some collector (again as a string). Processing is done in a single thread. % % In: % Options... : optional name-value pairs, with possible names: % 'port': port number on which to listen for requests (default: 23547) % if the port is already in use, the next free one will be chosen, % until port+portrange is exceeded; then, a free one will be chosen % if specified as 0, a free one is chosen directly % % 'portrange': number of ports to try following the default/supplied port (default: 16) % % 'backlog': backlog of queued incoming connections (default: 0) % % 'timeout_accept': timeout for accepting connections, in seconds (default: 3) % % 'timeout_send': timeout for sending results, in seconds (default: 10) % % 'timeout_recv': timeout for receiving data, in seconds (default: 5) % % Notes: % * use multiple workers to make use of multiple cores % * use only ports that are not accessible from the internet % * request format: <task_id><collectoraddress_length><collectoraddress><body_length><body> % <task_id>: identifier of the task (needs to be forwarded, with the result, % to a some data collector upon task completion) (int) % <collectoraddress_length>: length, in bytes, of the data collector's address (int) % <collectoraddress>: where to send the result for collection (string, formatted as host:port) % <body_length>: length, in bytes, of the message body (int) % <body>: a MATLAB command that yields, when evaluated, some result in ans (string, as MATLAB expression) % if an exception occurs, the exception struct (as from lasterror) replaces ans % * response format: <task_id><body_length><body> % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-08-26 import java.io.* import java.net.* % read options opts = hlp_varargin2struct(varargin, 'port',23547, 'portrange',16, 'backlog',1, 'timeout_accept',3, ... 'timeout_send',10, 'timeout_recv',5, 'receive_buffer',64000); % open a new server socket (first trying the specified portrange, then falling back to 0) for port = [opts.port:opts.port+opts.portrange 0] try serv = ServerSocket(port, opts.backlog); break; catch,end end disp(['This is ' hlp_hostname ' (' hlp_hostip '). Listening on port ' num2str(serv.getLocalPort())]); % set socket properties (e.g., making the function interruptible) serv.setReceiveBufferSize(opts.receive_buffer); serv.setSoTimeout(round(1000*opts.timeout_accept)); % make sure that the server socket will be closed when this function is terminated cleaner = onCleanup(@()serv.close()); tasknum = 1; disp('waiting for connections...'); while 1 try % wait for an incoming request conn = serv.accept(); conn.setSoTimeout(round(1000*opts.timeout_recv)); conn.setTcpNoDelay(1); disp('connected.'); try % parse request in = DataInputStream(conn.getInputStream()); cr = ChunkReader(in); taskid = in.readInt(); collector = char(cr.readFully(in.readInt())'); task = char(cr.readFully(in.readInt())'); disp('received data; replying.'); out = DataOutputStream(conn.getOutputStream()); out.writeInt(taskid+length(collector)+length(task)); out.flush(); conn.close(); % evaluate task & serialize result disp(['running task ' num2str(taskid) ' (' num2str(tasknum) ') ...']); tasknum = tasknum+1; result = hlp_serialize(evaluate(task)); disp('done with task; opening back link...'); try % send off the result idx = find(collector==':',1); outconn = Socket(collector(1:idx-1), str2num(collector(idx+1:end))); disp('connected; now sending...'); outconn.setTcpNoDelay(1); outconn.setSoTimeout(round(1000*opts.timeout_recv)); out = DataOutputStream(outconn.getOutputStream()); out.writeInt(taskid); out.writeInt(length(result)); out.writeBytes(result); out.flush(); outconn.close(); disp('done.'); disp('waiting for connections...'); catch e = lasterror; %#ok<LERR> if isempty(strfind(e.message,'timed out')) disp(['Exception during result forwarding: ' e.message]); end end catch conn.close(); e = lasterror; %#ok<LERR> if ~isempty(strfind(e.message,'EOFException')) disp(['cancelled.']); elseif isempty(strfind(e.message,'timed out')) disp(['Exception during task receive: ' e.message]); end end catch e = lasterror; %#ok<LERR> if isempty(strfind(e.message,'timed out')) disp(['Exception during accept: ' e.message]); end end end function result = evaluate(task) % evaluate a task try ans = []; %#ok<NOANS> eval([task ';']); result = ans; %#ok<NOANS> catch result = lasterror; %#ok<LERR> end
github
lcnbeapp/beapp-master
hlp_superimposedata.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_superimposedata.m
5,438
utf_8
512675e236e6e374f99cf433a05bb974
function res = hlp_superimposedata(varargin) % Merge multiple partially populated data structures into one fully populated one. % Result = hlp_superimposedata(Data1, Data2, Data3, ...) % % The function is applicable when you have cell arrays or structs/struct arrays with non-overlapping % patterns of non-empty entries, where all entries should be merged into a single data structure % which retains their original positions. If entries exist in multiple data structures at the same % location, entries of later items will be ignored (i.e. earlier data structures take precedence). % % In: % DataK : a data structure that should be super-imposed with the others to form a single data % structure % % Out: % Result : the resulting data structure % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2011-08-19 % first, compactify the data by removing the empty items compact = varargin(~cellfun('isempty',varargin)); % start with the last data structure, then merge the remaining data structures into it (in reverse % order as this avoids having to grow arrays incrementally in typical cases) res = compact{end}; for k=length(compact)-1:-1:1 res = merge(res,compact{k}); end % merge data structures A and B function A = merge(A,B) if iscell(A) && iscell(B) % make sure that both have the same number of dimensions if ndims(A) > ndims(B) B = grow_cell(B,size(A)); elseif ndims(A) < ndims(B) A = grow_cell(A,size(B)); end % make sure that both have the same size if all(size(B)==size(A)) % we're fine elseif all(size(B)>=size(A)) % A is a minor of B: grow A A = grow_cell(A,size(B)); elseif all(size(A)>=size(B)) % B is a minor of A: grow B B = grow_cell(B,size(A)); else % A and B have mixed sizes... grow both as necessary M = max(size(A),size(B)); A = grow_cell(A,M); B = grow_cell(B,M); end % find all non-empty elements in B idx = find(~cellfun(@(x)isequal(x,[]),B)); if ~isempty(idx) % check if any of these is occupied in A clean = cellfun('isempty',A(idx)); if ~all(clean) % merge all conflicting items recursively conflicts = idx(~clean); for k=conflicts(:)' A{k} = merge(A{k},B{k}); end % and transfer the rest if any(clean) A(idx(clean)) = B(idx(clean)); end else % transfer all to A A(idx) = B(idx); end end elseif isstruct(A) && isstruct(B) % first make sure that both have the same fields fnA = fieldnames(A); fnB = fieldnames(B); if isequal(fnA,fnB) % we're fine elseif isequal(sort(fnA),sort(fnB)) % order doesn't match -- impose A's order on B B = orderfields(B,fnA); elseif isempty(setdiff(fnA,fnB)) % B has a superset of A's fields: add the remaining fields to A, and order them according to B remaining = setdiff(fnB,fnA); for fn = remaining' A(1).(fn{1}) = []; end A = orderfields(A,fnB); elseif isempty(setdiff(fnB,fnA)) % A has a superset of B's fields: add the remaining fields to B, and order them according to A remaining = setdiff(fnA,fnB); for fn = remaining' B(1).(fn{1}) = []; end B = orderfields(B,fnA); else % A and B have incommensurable fields; add B's fields to A's fields, add A's fields to B's % and order according to A's fields remainingB = setdiff(fnB,fnA); for fn = remainingB' A(1).(fn{1}) = []; end remainingA = setdiff(fnA,fnB); for fn = remainingA' B(1).(fn{1}) = []; end B = orderfields(B,A); end % that being established, convert them to cell arrays, merge their cell arrays, and convert back to structs merged = merge(struct2cell(A),struct2cell(B)); A = cell2struct(merged,fieldnames(A),1); elseif isstruct(A) && ~isstruct(B) if ~isempty(B) error('One of the sub-items is a struct, and the other one is of a non-struct type.'); else % we retain A end elseif isstruct(B) && ~isstruct(A) if ~isempty(A) error('One of the sub-items is a struct, and the other one is of a non-struct type.'); else % we retain B A = B; end elseif iscell(A) && ~iscell(B) if ~isempty(B) error('One of the sub-items is a cell array, and the other one is of a non-cell type.'); else % we retain A end elseif iscell(B) && ~iscell(A) if ~isempty(A) error('One of the sub-items is a cell array, and the other one is of a non-cell type.'); else % we retain B A = B; end elseif isempty(A) && ~isempty(B) % we retain B A = B; elseif isempty(B) && ~isempty(A) % we retain A elseif ~isequal_weak(A,B) % we retain A and warn about dropping B warn_once('Two non-empty (and non-identical) sub-elements occupied the same index; one was dropped. This warning will only be displayed once.'); end % grow a cell array to accomodate a particular index % (assuming that this index is not contained in the cell array yet) function C = grow_cell(C,idx) tmp = sprintf('%i,',idx); eval(['C{' tmp(1:end-1) '} = [];']);
github
lcnbeapp/beapp-master
arg_guidialog.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_guidialog.m
10,844
utf_8
9a3feeb49fd1fa36ac5971ebb38d1ab9
function varargout = arg_guidialog(func,varargin) % Create an input dialog that displays input fields for a Function and Parameters. % Parameters = arg_guidialog(Function, Options...) % % The Parameters that are passed to the function can be used to override some of its defaults. The % function must declare its arguments via arg_define. In addition, only a Subset of the function's % specified arguments can be displayed. % % In: % Function : the function for which to display arguments % % Options... : optional name-value pairs; possible names are: % 'Parameters' : cell array of parameters to the Function to override some of its % defaults. % % 'Subset' : Cell array of argument names to which the dialog shall be restricted; % these arguments may contain . notation to index into arg_sub and the % selected branch(es) of arg_subswitch/arg_subtoggle specifiers. Empty % cells show up in the dialog as empty rows. % % 'Title' : title of the dialog (by default: functionname()) % % 'Invoke' : whether to invoke the function directly; in this case, the output % arguments are those of the function (default: true, unless called in % the form g = arg_guidialog; e.g., from within some function) % % Out: % Parameters : a struct that is a valid input to the Function. % % Examples: % % bring up a configuration dialog for the given function % settings = arg_guidialog(@myfunction) % % % bring up a config dialog with some pre-specified defaults % settings = arg_guidialog(@myfunction,'Parameters',{4,20,'test'}) % % % bring up a config dialog which displays only a subset of the function's arguments (in a particular order) % settings = arg_guidialog(@myfunction,'Subset',{'blah','xyz',[],'flag'}) % % % bring up a dialog, and invoke the function with the selected settings after the user clicks OK % settings = arg_guidialog(@myfunction,'Invoke',true) % % See also: % arg_guidialog_ex, arg_guipanel, arg_define % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-10-24 if ~exist('func','var') % called with no arguments, from inside a function: open function dialog func = hlp_getcaller; varargin = {'Parameters',evalin('caller','varargin'),'Invoke',nargout==0}; end % parse arguments... hlp_varargin2struct(varargin,{'params','Parameters','parameters'},{}, {'subset','Subset'},{}, {'dialogtitle','title','Title'}, [char(func) '()'], {'buttons','Buttons'},[],{'invoke','Invoke'},true); oldparams = params; % obtain the argument specification for the function rawspec = arg_report('rich', func, params); %#ok<*NODEF> % extract a list of sub arguments... if ~isempty(subset) && subset{1}==-1 % user specified a set of items to *exclude* % convert subset to setdiff(all-arguments,subset) allnames = fieldnames(arg_tovals(rawspec)); subset(1) = []; subset = allnames(~ismember(allnames,[subset 'arg_direct'])); end [spec,subset] = obtain_items(rawspec,subset); % create an inputgui() dialog... geometry = repmat({[0.6 0.35]},1,length(spec)+length(buttons)/2); geomvert = ones(1,length(spec)+length(buttons)/2); % turn the spec into a UI list... uilist = {}; for k = 1:length(spec) s = spec{k}; if isempty(s) uilist(end+1:end+2) = {{} {}}; else if isempty(s.help) error(['Cannot display the argument ' subset{k} ' because it contains no description.']); else tag = subset{k}; uilist{end+1} = {'Style','text', 'string',s.help{1}, 'fontweight','bold'}; % depending on the type, we introduce different types of input widgets here... if iscell(s.range) && strcmp(s.type,'char') % string popup menu uilist{end+1} = {'Style','popupmenu', 'string',s.range,'value',find(strcmp(s.value,s.range)),'tag',tag}; elseif strcmp(s.type,'logical') if length(s.range)>1 % multiselect uilist{end+1} = {'Style','listbox', 'string',s.range, 'value',find(ismember(s.range,s.value)),'tag',tag,'min',1,'max',100000}; geomvert(k) = min(3.5,length(s.range)); else % checkbox uilist{end+1} = {'Style','checkbox', 'string','(set)', 'value',double(s.value),'tag',tag}; end elseif strcmp(s.type,'char') % string edit uilist{end+1} = {'Style','edit', 'string', s.value,'tag',tag}; else % expression edit if isinteger(s.value) s.value = double(s.value); end uilist{end+1} = {'Style','edit', 'string', hlp_tostring(s.value),'tag',tag}; end % append the tooltip string if length(s.help) > 1 uilist{end} = [uilist{end} 'tooltipstring', regexprep(s.help{2},'\.\s+(?=[A-Z])','.\n')]; end end end if ~isempty(buttons) && k==buttons{1} % render a command button uilist(end+1:end+2) = {{} buttons{2}}; buttons(1:2) = []; end end % invoke the GUI, obtaining a list of output values... helptopic = char(func); try if helptopic(1) == '@' fn = functions(func); tmp = struct2cell(fn.workspace{1}); helptopic = class(tmp{1}); end catch disp('Cannot deduce help topic.'); end [outs,dummy,okpressed] = inputgui('geometry',geometry, 'uilist',uilist,'helpcom',['env_doc ' helptopic], 'title',dialogtitle,'geomvert',geomvert); %#ok<ASGLU> if ~isempty(okpressed) % remove blanks from the spec spec = spec(~cellfun('isempty',spec)); subset = subset(~cellfun('isempty',subset)); % turn the raw specification into a parameter struct (a non-direct one, since we will mess with % it) params = arg_tovals(rawspec,false); % for each parameter produced by the GUI... for k = 1:length(outs) s = spec{k}; % current specifier v = outs{k}; % current raw value % do type conversion according to spec if iscell(s.range) && strcmp(s.type,'char') v = s.range{v}; elseif strcmp(s.type,'expression') v = eval(v); elseif strcmp(s.type,'logical') if length(s.range)>1 v = s.range(v); else v = logical(v); end elseif strcmp(s.type,'char') % noting to do else if ~isempty(v) v = eval(v); % convert back to numeric (or object, or cell) value end end % assign the converted value to params struct... params = assign(params,subset{k},v); end % now send the result through the function to check for errors and obtain a values structure... params = arg_report('rich',func,{params}); params = arg_tovals(params,false); % invoke the function, if so desired if ischar(func) func = str2func(func); end if invoke [varargout{1:nargout(func)}] = func(oldparams{:},params); else varargout = {params}; end else varargout = {[]}; end % obtain a cell array of spec entries by name from the given specification function [items,ids] = obtain_items(rawspec,requested,prefix) if ~exist('prefix','var') prefix = ''; end items = {}; ids = {}; % determine what subset of (possibly nested) items is requested if isempty(requested) % look for a special argument/property arg_dialogsel, which defines the standard dialog % representation for the given specification dialog_sel = find(cellfun(@(x)any(strcmp(x,'arg_dialogsel')),{rawspec.names})); if ~isempty(dialog_sel) requested = rawspec(dialog_sel).value; end end if isempty(requested) % empty means that all items are requested for k=1:length(rawspec) items{k} = rawspec(k); ids{k} = [prefix rawspec(k).names{1}]; end else % otherwise we need to obtain those items for k=1:length(requested) if ~isempty(requested{k}) try [items{k},subid] = obtain(rawspec,requested{k}); catch error(['The specified identifier (' prefix requested{k} ') could not be found in the function''s declared arguments.']); end ids{k} = [prefix subid]; end end end % splice items that have children (recursively) into this list for k = length(items):-1:1 % special case: switch arguments are not spliced, but instead the argument that defines the % option popupmenu will be retained if ~isempty(items{k}) && ~isempty(items{k}.children) && (~iscellstr(items{k}.range) || isempty(requested)) [subitems, subids] = obtain_items(items{k}.children,{},[ids{k} '.']); if ~isempty(subitems) % and introduce blank rows around them items = [items(1:k-1) {{}} subitems {{}} items(k+1:end)]; ids = [ids(1:k-1) {{}} subids {{}} ids(k+1:end)]; end end end % remove items that cannot be displayed retain = cellfun(@(x)isempty(x)||x.displayable,items); items = items(retain); ids = ids(retain); % remove double blank rows empties = cellfun('isempty',ids); items(empties(1:end-1) & empties(2:end)) = []; ids(empties(1:end-1) & empties(2:end)) = []; % obtain a spec entry by name from the given specification function [item,id] = obtain(rawspec,identifier,prefix) if ~exist('prefix','var') prefix = ''; end % parse the . notation dot = find(identifier=='.',1); if ~isempty(dot) [head,rest] = deal(identifier(1:dot-1), identifier(dot+1:end)); else head = identifier; rest = []; end % search for the identifier at this level names = {rawspec.names}; for k=1:length(names) if any(strcmp(names{k},head)) % found a match! if isempty(rest) % return it item = rawspec(k); id = [prefix names{k}{1}]; else % obtain the rest of the identifier [item,id] = obtain(rawspec(k).children,rest,[prefix names{k}{1} '.']); end return; end end error(['The given identifier (' head ') was not found among the function''s declared arguments.']); % assign a field with dot notation in a struct function s = assign(s,id,v) % parse the . notation dot = find(id=='.',1); if ~isempty(dot) [head,rest] = deal(id(1:dot-1), id(dot+1:end)); if ~isfield(s,head) s.(head) = struct(); end s.(head) = assign(s.(head),rest,v); else s.(id) = v; end
github
lcnbeapp/beapp-master
arg_define.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_define.m
28,888
utf_8
79e413010787b04cc5fec2c1d1aa0d04
function res = arg_define(vals,varargin) % Declare function arguments with optional defaults and built-in GUI support. % Struct = arg_define(Values, Specification...) % Struct = arg_define(Format, Values, Specification...) % % This is essentially an improved replacement for the parameter declaration line of a function. % Assigns Values (a cell array of values, typically the "varargin" of the calling function, % henceforth named the "Function") to fields in the output Struct, with parsing implemented % according to a Specification of argument names and their order (optionally with a custom argument % Format description). % % By default, values can be a list of a fixed number of positional arguments (i.e., the typical % MATLAB calling format), optionally followed by a list of name-value pairs (NVPs, e.g., as the % format accepted by figure()), in which, as well, instead of any given NVP, a struct may be % passed (thus, one may pass a mix of 'name',value,struct,'name',value,'name',value, ... % parameters). Alternatively, by default the entire list of positional arguments can instead be be % specified as a list of NVPs/structs. Only names that are allowed by the Specification may be used, % if positional syntax is allowed by the Format (which is the default). % % The special feature over hlp_varargin2struct()-like functionality is that arguments defined via % arg_define can be reported to outside functions (if triggered by arg_report()). The resulting % specification can be rendered in a GUI or be processed otherwise. % % In: % Format : Optional format description (default: [0 Inf]): % * If this is a number (say, k), it indicates that the first k arguments are specified % in a positional manner, and the following arguments are specified as list of % name-value pairs and/or structs. % * If this is a vector of two numbers [0 k], it indicates that the first k arguments MAY % be specified in a positional manner (the following arguments must be be specified as % NVPs/structs) OR alternatively, all arguments can be specified as NVPs / structs. % Only names that are listed in the specification may be used as names (in NVPs and % structs) in this case. % * If this is a function handle, the function is used to transform the Values prior to % any other processing into a new Values cell array. The function may specify a new % (numeric) Format as its second output argument (if not specified, this is 0). % % Values : A cell array of values passed to the function (usually the calling function's % "varargin"). Interpreted according to the Format and the Specification. % % Specification... : The specification of the calling function's arguments; this is a sequence of % arg(), arg_norep(), arg_nogui(), arg_sub(), arg_subswitch(), arg_subtoggle() % specifiers. The special keywords mandatory and unassigned can be used in the % declaration of default values, where "mandatory" declares that this argument % must be assigned some value via Values (otherwise, an error is raised before % the arg is passed to the Function) and "unassigned" declares that the % variable will not be assigned unless passed as an argument (akin to the % default behavior of regular MATLAB function arguments). % % Out: % Struct : A struct with values assigned to fields, according to the Specification and Format. % % If this is not captured by the Function in a variable, the contents of Struct are % instead assigned to the Function's workspace (default practice) -- but note that this % only works for variable names are *not& also names of functions in the path (due to a % flaw in MATLAB's treatment of identifiers). Thus, it is good advice to use long/expressive % variable names to avoid this situation, or possibly CamelCase names. % % See also: % arg, arg_nogui, arg_norep, arg_sub, arg_subswitch, arg_subtoggle % % Notes: % 1) If the Struct output argument is omitted by the user, the arguments are not returned as a % struct but instead directly copied into the Function's workspace. % % 2) Someone may call the user's Function with the request to deliver the parameter specification, % instead of following the normal execution flow. arg_define() automatically handles this task % by throwing an exception of the type 'BCILAB:arg:report_args' using arg_issuereport(), which % is to be caught by the requesting function. % % Performance Tips: % 1) If a struct with a field named 'arg_direct' is passed (and is set to true), or a name-value % pair 'arg_direct',true is passed, then all type checking, specification parsing, fallback to % default values and reporting functionality are skipped. This is a fast path to call a function, % and it usually requires that all of its arguments are passed. The function arg_report allows % to get a struct of all function arguments that can be used subsequently as part of a direct % call. % % Please make sure not to pass multiple occurrences of 'arg_direct' with conflicting values to % arg_define, as the behavior will then be undefined. % % 2) The function is about 2x as fast (in direct mode) if arguments are returned as a struct instead % of being written into the caller's workspace. % % Examples: % function myfunction(varargin) % % % begin a default argument declaration and declare a few arguments; The arguments can be passed either: % % - by position: myfunction(4,20); including the option to leave some values at their defaults, e.g. myfunction(4) or myfunction() % % - by name: myfunction('test',4,'blah',20); myfunction('blah',21,'test',4); myfunction('blah',22); % % - as a struct: myfunction(struct('test',4,'blah',20)) % % - as a sequence of either name-value pairs or structs: myfunction('test',4,struct('blah',20)) (note that this is not ambiguous, as the struct would come in a place where only a name could show up otherwise % arg_define(varargin, ... % arg('test',3,[],'A test.'), ... % arg('blah',25,[],'Blah.')); % % % a special syntax that is allowed is passing a particular parameter multiple times - in which case only the last specification is effective % % myfunction('test',11, 'blah',21, 'test',3, struct('blah',15,'test',5), 'test',10) --> test will be 10, blah will be 15 % % % begin an argument declaration which allows 0 positional arguments (i.e. everything must be passed by name % arg_define(0,varargin, ... % % % begin an argument declaration which allows exactly 1 positional arguments, i.e. the first one must be passed by position and the other one by name (or struct) % % valid calls would be: myfunction(3,'blah',25); myfunction(3); myfunction(); (the last one assumes the default for both) % arg_define(1,varargin, ... % arg('test',3,[],'A test.'), ... % arg('blah',25,[],'Blah.')); % % % begin an argument decalration which allows either 2 positional arguments or 0 positional arguments (i.e. either the first two are passed by position, or all are passed by name) % % some valid calls are: myfunction(4,20,'flag',true); myfunction(4,20); myfunction(4,20,'xyz','test','flag',true); myfunction(4); myfunction('flag',true,'test',4,'blah',21); myfunction('flag',true) % arg_define([0 2],varargin, ... % arg('test',3,[],'A test.'), ... % arg('blah',25,[],'Blah.'), ... % arg('xyz','defaultstr',[],'XYZ.'), ... % arg('flag',false,[],'Some flag.')); % % % begin an argument declaration in which the formatting of arguments is completely arbitrary, and a custom function takes care of bringing them into a form understood by % % the arg_define implementation. This function takes a cell array of arguments (in any formatting), and returns a cell array of a standard formatting (e.g. name-value pairs, or structs) % arg_define(@myparser,varargin, ... % arg('test',3,[],'A test.'), ... % arg('blah',25,[],'Blah.')); % % % return the arguments as fields in a struct (here: opts), instead of directly in the workspace % opts = arg_define(varargin, ... % arg('test',3,[],'A test.'), ... % arg('blah',25,[],'Blah.')); % % % note: in the current implementation, the only combinations of allowed argument numbers are: arg_define(...); arg_define(0, ...); arg_define(X, ...); arg_define([0 X], ...); arg_define(@somefunc, ...); % % the implicit default is arg_define([0 Inf], ...) % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-09-24 % --- get Format, Values and Specification --- if iscell(vals) % no Format specifier was given: use default fmt = [0 Inf]; spec = varargin; try % quick checks for direct (fast) mode if isfield(vals{end},'arg_direct') direct_mode = vals{end}.arg_direct; elseif strcmp(vals{1},'arg_direct') direct_mode = vals{2}; else % figure it out later direct_mode = false; end structs = cellfun('isclass',vals,'struct'); catch % vals was empty: default behavior direct_mode = false; end else % a Format specifier was given as the first argument (instead of vals as the first argument) ... if isempty(vals) % ... but it was empty: use default behavior fmt = [0 Inf]; else % ... and was nonempty: use it fmt = vals; end % shift the remaining two args vals = varargin{1}; spec = varargin(2:end); if isa(fmt,'function_handle') % Format was a function: run it if nargout(fmt) == 1 vals = fmt(vals); fmt = 0; else [vals,fmt] = feval(fmt,vals); end end direct_mode = false; end % --- if not yet known, determine conclusively if we are in direct mode (specificationless and therefore fast) --- % this mode is only applicable when all arguments can be passed as NVPs/structs if ~direct_mode && any(fmt == 0) % search for an arg_direct argument structs = cellfun('isclass',vals,'struct'); indices = find(structs | strcmp(vals,'arg_direct')); for k = indices(end:-1:1) if ischar(vals{k}) && k<length(vals) % found it in the NVPs direct_mode = vals{k+1}; break; elseif isfield(vals{k},'arg_direct') % found it in a struct direct_mode = vals{k}.arg_direct; break; end end end if direct_mode % --- direct mode: quickly collect NVPs from the arguments and produce a result --- % obtain flat NVP list if any(structs(1:2:end)) vals = flatten_structs(vals); end if nargout % get names & values names = vals(1:2:end); values = vals(2:2:end); % use only the last assignment for each name [s,indices] = sort(names); indices(strcmp(s(1:end-1),s(2:end))) = []; % build & return a struct res = cell2struct(values(indices),names(indices),2); else % place the arguments in the caller's workspace for k=1:2:length(vals) assignin('caller',vals{k},vals{k+1}); end end try % also return the arguments in NVP form assignin('caller','arg_nvps',vals); catch % this operation might be disallowed under some circumstances end else % --- full parsing mode: determine the reporting type --- % usually, the reporting type is 'none', except if called (possibly indirectly) by % arg_report('type', ...): in this case, the reporting type is 'type' reporting is a special way to % call arg_define, which requests the argument specification, so that it can be displayed by GUIs, % etc. % % * 'none' normal execution: arg_define returns a Struct of Values to the Function or assigns the % Struct's fields to the Function's workspace % * 'rich' arg_define yields a rich specifier list to arg_report(), basically an array of specifier % structs (see arg_specifier for the field names) % * 'lean' arg_define yields a lean specifier list to arg_report(), basically an array of specifier % structs but without alternatives for multi-option specifiers % * 'vals' arg_define yields a struct of values to arg_report(), wich can subsequently be used as % the full specification of arguments to pass to the Function try throw; %#ok<LTARG> % faster than error() catch context names = {context.stack(3:min(6,end)).name}; % function names at the considered levels of indirection... matches = find(strncmp(names,'arg_report_',11)); % ... which start with 'arg_report_' if isempty(matches) reporting_type = 'none'; % no report requested (default case) else % the reporting type is the suffix of the deepest arg_report_* function in the call stack reporting_type = names{matches(end)}(11+1:end); end end % --- deal with 'handle' and 'properties' reports --- if strcmp(reporting_type,'handle') % very special report type: 'handle'--> this asks for function handles to nested / scoped % functions. unfortunately, these cannot be obtained using standard MATLAB functionality. if ~iscellstr(vals) error('The arguments passed for handle report must denote function names.'); end unresolved = {}; for f=1:length(vals) % resolve each function name in the caller scope funcs{f} = evalin('caller',['@' vals{f}]); % check if the function could be retrieved tmp = functions(funcs{f}); if isempty(tmp.file) unresolved{f} = vals{f}; end end if ~isempty(unresolved) % search the remaining ones in the specification for f=find(~cellfun('isempty',unresolved)) funcs{f} = hlp_microcache('findfunction',@find_function_cached,spec,vals{f}); end end % report it if length(funcs) == 1 funcs = funcs{1}; end arg_issuereport(funcs); elseif strcmp(reporting_type,'properties') % 'properties' report, but no properties were declared arg_issuereport(struct()); end % --- one-time evaluation of the Specification list into a struct array --- % evaluate the specification or retrieve it from cache [spec,all_names,joint_names,remap] = hlp_microcache('spec',@evaluate_spec,spec,reporting_type,nargout==0); % --- transform vals to a pure list of name-value pairs (NVPs) --- if length(fmt) == 2 if fmt(1) ~= 0 || fmt(2) <= 0 % This error is thrown when the first parameter to arg_define() was not a cell array (i.e., not varargin), % so that it is taken to denote the optional Format parameter. % Format is usually a numeric array that specifies the number of positional arguments that are % accepted by the function, and if numeric, it can only be either a number or a two-element array % that contains 0 and a non-zero number. error('For two-element formats, the first entry must be 0 and the second entry must be > 0.'); end % there are two possible options: either 0 arguments are positional, or k arguments are % positional; assuming at first that 0 arguments are positional, splice substructs into one % uniform NVP list (this is because structs are allowed instead of individual NVPs) if any(cellfun('isclass',vals(1:2:end),'struct')) nvps = flatten_structs(vals); else nvps = vals; end % check if all the resulting names are in the set of allowed names (a disambiguation % condition in this case) if iscellstr(nvps(1:2:end)) try disallowed_nvp = fast_setdiff(nvps(1:2:end),[joint_names {'arg_selection','arg_direct'}]); catch disallowed_nvp = setdiff(nvps(1:2:end),[joint_names {'arg_selection','arg_direct'}]); end else disallowed_nvp = {'or the sequence of names and values was confused'}; end if isempty(disallowed_nvp) % the assumption was correct: 0 arguments are positional fmt = 0; else % the assumption was violated: k arguments are positional, and we enfore strict naming % for the remaining ones (i.e. names must be in the Specification). strict_names = true; fmt = fmt(2); end elseif fmt == 0 % 0 arguments are positional nvps = flatten_structs(vals); elseif fmt > 0 % k arguments are positional, the rest are NVPs (no need to enforce strict naming here) strict_names = false; else % This error refers to the optional Format argument. error('Negative or NaN formats are not allowed.'); end % (from now on fmt holds the determined # of positional arguments) if fmt > 0 % the first k arguments are positional % Find out if we are being called by another arg_define; in this case, this definition % appears inside an arg_sub/arg_*, and the values passed to the arg_define are part of the % defaults declaration of one of these. If these defaults are specified positionally, the % first k arg_norep() arguments in Specification are implicitly skipped. if ~strcmp(reporting_type,'none') && any(strcmp('arg_define',{context.stack(2:end).name})); % we implicitly skip the leading non-reportable arguments in the case of positional % assignment (assuming that these are supplied by the outer function), by shifting the % name/value assignment by the appropriate number of places shift_positionals = min(fmt,find([spec.reportable],1)-1); else shift_positionals = 0; end % get the effective number of positional arguments fmt = min(fmt,length(vals)+shift_positionals); % the NVPs begin only after the k'th argument (defined by the Format) nvps = vals(fmt+1-shift_positionals:end); % splice in any structs if any(cellfun('isclass',nvps(1:2:end),'struct')) nvps = flatten_structs(nvps); end % do minimal error checking... if ~iscellstr(nvps(1:2:end)) % If you are getting this error, the order of names and values passed as name-value pairs % to the function in question was likely mixed up. The error mentions structs because it % is also allowed to pass in a struct in place of any 'name',value pair. error('Some of the specified arguments that should be names or structs, are not.'); end if strict_names % enforce strict names try disallowed_pos = fast_setdiff(nvps(1:2:end),[joint_names {'arg_selection','arg_direct'}]); catch disallowed_pos = setdiff(nvps(1:2:end),[joint_names {'arg_selection','arg_direct'}]); end if ~isempty(disallowed_pos) % If you are getting this error, it is most likely due to a mis-typed argument name % in the list of name-value pairs passed to the function in question. % % Because some functions may support also positional arguments, it is also possible % that something that was supposed to be the value for one of the positional % arguments was interpreted as part of the name-value pairs lit that may follow the % positional arguments of the function. This error is likely because the wrong number % of positional arguments was passed (a safer alternative is to instead pass everything % by name). error(['Some of the specified arguments do not appear in the argument specification; ' format_cellstr(disallowed_pos) '.']); end end try % remap the positionals (everything up to the k'th argument) into an NVP list, using the % code names poss = [cellfun(@(x)x{1},all_names(shift_positionals+1:fmt),'UniformOutput',false); vals(1:fmt-shift_positionals)]; catch if strict_names % maybe the user intended to pass 0 positionals, but used some disallowed names error(['Apparently, some of the used argument names are not known to the function: ' format_cellstr(disallowed_nvp) '.']); else error(['The first ' fmt ' arguments must be passed by position, and the remaining ones must be passed by name (either in name-value pairs or structs).']); end end % ... and concatenate them with the remaining NVPs into one big NVP list nvps = [poss(:)' nvps]; end % --- assign values to names using the assigner functions of the spec --- for k=1:2:length(nvps) if isfield(remap,nvps{k}) idx = remap.(nvps{k}); spec(idx) = spec(idx).assigner(spec(idx),nvps{k+1}); else % append it to the spec (note: this might need some optimization... it would be better % if the spec automatically contained the arg_selection field) tmp = arg_nogui(nvps{k},nvps{k+1}); spec(end+1) = tmp{1}([],tmp{2}{:}); end end % --- if requested, yield a 'vals', 'lean' or 'rich' report --- if ~strcmp(reporting_type,'none') % but deliver only the reportable arguments, and only if the values are not unassigned tmp = spec([spec.reportable] & ~strcmp(unassigned,{spec.value})); if strcmp(reporting_type,'vals') tmp = arg_tovals(tmp); end arg_issuereport(tmp); end % --- otherwise post-process the outputs and create a result struct to pass to the Function --- % generate errors for mandatory arguments that were not assigned missing_entries = strcmp(mandatory,{spec.value}); if any(missing_entries) missing_names = cellfun(@(x)x{1},{spec(missing_entries).names},'UniformOutput',false); error(['The arguments ' format_cellstr(missing_names) ' were unspecified but are mandatory.']); end % strip non-returned arguments, and convert it all to a struct of values res = arg_tovals(spec); % also emit a final NVPs list tmp = [fieldnames(res) struct2cell(res)]'; try assignin('caller','arg_nvps',tmp(:)'); catch % this operation might be disallowed under some circumstances end % if requested, place the arguments in the caller's workspace if nargout==0 for fn=fieldnames(res)' assignin('caller',fn{1},res.(fn{1})); end end end % substitute any structs in place of a name-value pair into the name-value list function args = flatten_structs(args) k = 1; while k <= length(args) if isstruct(args{k}) tmp = [fieldnames(args{k}) struct2cell(args{k})]'; args = [args(1:k-1) tmp(:)' args(k+1:end)]; k = k+numel(tmp); else k = k+2; end end % evaluate a specification into a struct array function [spec,all_names,joint_names,remap] = evaluate_spec(spec,reporting_type,require_namecheck) if strcmp(reporting_type,'rich') subreport_type = 'rich'; else subreport_type = 'lean'; end % evaluate the functions to get (possibly arrays of) specifier structs for k=1:length(spec) spec{k} = spec{k}{1}(subreport_type,spec{k}{2}{:}); end % concatenate the structs to one big struct array spec = [spec{:}]; % make sure that spec has the correct fields, even if empty if isempty(spec) spec = arg_specifier; spec = spec([]); end % obtain the argument names and the joined names all_names = {spec.names}; joint_names = [all_names{:}]; % create a name/index remapping table remap = struct(); for n=1:length(all_names) for k=1:length(all_names{n}) remap.(all_names{n}{k}) = n; end end % check for duplicate argument names in the Specification sorted_names = sort(joint_names); duplicates = joint_names(strcmp(sorted_names(1:end-1),sorted_names(2:end))); if ~isempty(duplicates) error(['The names ' format_cellstr(duplicates) ' refer to multiple arguments.']); end % if required, check for name clashes with functions on the path % (this is due to a glitch in MATLAB's handling of variables that were assigned to a function's scope % from the outside, which are prone to clashes with functions on the path...) if require_namecheck && strcmp(reporting_type,'none') try check_names(cellfun(@(x)x{1},all_names,'UniformOutput',false)); catch e disp_once('The function check_names failed; reason: %s',e.message); end end % check for name clashes (once) function check_names(code_names) persistent name_table; if ~isstruct(name_table) name_table = struct(); end for name_cell = fast_setdiff(code_names,fieldnames(name_table)) current_name = name_cell{1}; existing_func = which(current_name); if ~isempty(existing_func) if ~exist('function_caller','var') function_caller = hlp_getcaller(4); if function_caller(1) == '@' function_caller = hlp_getcaller(14); end end if isempty(strfind(existing_func,'Java method')) [path_part,file_part,ext_part] = fileparts(existing_func); if ~any(strncmp('@',hlp_split(path_part,filesep),1)) % If this happens, it means that there is a function in one of the directories in % MATLAB's path which has the same name as an argument of the specification. If this % argument variable is copied into the function's workspace by arg_define, most MATLAB % versions will (incorrectly) try to call that function instead of accessing the % variable. I hope that they handle this issue at some point. One workaround is to use % a longer argument name (that is less likely to clash) and, if it should still be % usable for parameter passing, to retain the old name as a secondary or ternary % argument name (using a cell array of names in arg()). The only really good % solution at this point is to generally assign the output of arg_define to a % struct. disp([function_caller ': The argument name "' current_name '" clashes with the function "' [file_part ext_part] '" in directory "' path_part '"; it is strongly recommended that you either rename the function or remove it from the path.']); end else % these Java methods are probably spurious "false positives" of the which() function disp([function_caller ': There is a Java method named "' current_name '" on your path; if you experience any name clash with it, please report this issue.']); end end name_table.(current_name) = existing_func; end % recursively find a function handle by name in a specification % the first occurrence of a handle to a function with the given name is returned function r = find_function(spec,name) r = []; for k=1:length(spec) if isa(spec(k).value,'function_handle') && strcmp(char(spec(k).value),name) r = spec(k).value; return; elseif ~isempty(spec(k).alternatives) for n = 1:length(spec(k).alternatives) r = find_function(spec(k).alternatives{n},name); if ~isempty(r) return; end end elseif ~isempty(spec(k).children) r = find_function(spec(k).children,name); if ~isempty(r) return; end end end % find a function handle by name in a specification function f = find_function_cached(spec,name) % evaluate the functions to get (possibly arrays of) specifier structs for k=1:length(spec) spec{k} = spec{k}{1}('rich',spec{k}{2}{:}); end % concatenate the structs to one big struct array spec = [spec{:}]; % now search the function in it f = find_function(spec,name); % format a non-empty cell-string array into a string function x = format_cellstr(x) x = ['{' sprintf('%s, ',x{1:end-1}) x{end} '}'];
github
lcnbeapp/beapp-master
arg_guidialog_old.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_guidialog_old.m
8,955
utf_8
4da1a90f92312aea4043460655d5f6aa
function params = arg_guidialog(func,varargin) % Create an input dialog that displays input fields for a Function and Parameters. % Parameters = arg_guidialog(Function, Options...) % % The Parameters that are passed to the function can be used to override some of its defaults. % The function must declare its arguments via arg_define. In addition, only a Subset of the function's specified arguments can be displayed. % % In: % Function : the function for which to display arguments % % Options... : optional name-value pairs; possible names are: % 'Parameters' : cell array of parameters to the Function to override some of its defaults. % % 'Subset' : Cell array of argument names to which the dialog shall be restricted; these arguments may contain . notation to index % into arg_sub and the selected branch(es) of arg_subswitch/arg_subtoggle specifiers. % Empty cells show up in the dialog as empty rows. % % 'Title' : title of the dialog (by default: functionname()) % % Out: % Parameters : a struct that is a valid input to the Function. % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-10-24 % parse arguments... hlp_varargin2struct(varargin,{'params','Parameters'},{}, {'subset','Subset'},{}, {'dialogtitle','title','Title'}, [char(func) '()'], {'buttons','Buttons'},[]); % obtain the argument specification for the function rawspec = arg_report('rich', func, params); %#ok<*NODEF> % extract a list of sub arguments... if ~isempty(subset) && subset{1}==-1 % user specified a set of items to *exclude* % convert subset to setdiff(all-arguments,subset) allnames = fieldnames(arg_tovals(rawspec)); subset(1) = []; subset = allnames(~ismember(allnames,[subset 'arg_direct'])); end [spec,subset] = obtain_items(rawspec,subset); % create an inputgui() dialog... geometry = repmat({[0.6 0.35]},1,length(spec)+length(buttons)/2); geomvert = ones(1,length(spec)+length(buttons)/2); % turn the spec into a UI list... uilist = {}; for k = 1:length(spec) s = spec{k}; if isempty(s) uilist(end+1:end+2) = {{} {}}; else if isempty(s.help) error(['Cannot display the argument ' subset{k} ' because it contains no description.']); else tag = subset{k}; uilist{end+1} = {'Style','text', 'string',s.help{1}, 'fontweight','bold'}; % depending on the type, we introduce different types of input widgets here... if iscell(s.range) && strcmp(s.type,'char') % string popup menu uilist{end+1} = {'Style','popupmenu', 'string',s.range,'value',find(strcmp(s.value,s.range)),'tag',tag}; elseif strcmp(s.type,'logical') if length(s.range)>1 % multiselect uilist{end+1} = {'Style','listbox', 'string',s.range, 'value',find(ismember(s.range,s.value)),'tag',tag,'min',1,'max',100000}; geomvert(k) = min(3.5,length(s.range)); else % checkbox uilist{end+1} = {'Style','checkbox', 'string','(set)', 'value',double(s.value),'tag',tag}; end elseif strcmp(s.type,'char') % string edit uilist{end+1} = {'Style','edit', 'string', s.value,'tag',tag}; else % expression edit if isinteger(s.value) s.value = double(s.value); end uilist{end+1} = {'Style','edit', 'string', hlp_tostring(s.value),'tag',tag}; end % append the tooltip string if length(s.help) > 1 uilist{end} = [uilist{end} 'tooltipstring', regexprep(s.help{2},'\.\s+(?=[A-Z])','.\n')]; end end end if ~isempty(buttons) && k==buttons{1} % render a command button uilist(end+1:end+2) = {{} buttons{2}}; buttons(1:2) = []; end end % invoke the GUI, obtaining a list of output values... [outs,dummy,okpressed] = inputgui('geometry',geometry, 'uilist',uilist,'helpcom','disp(''coming soon...'')', 'title',dialogtitle,'geomvert',geomvert); if ~isempty(okpressed) % remove blanks from the spec spec = spec(~cellfun('isempty',spec)); subset = subset(~cellfun('isempty',subset)); % turn the raw specification into a parameter struct (a non-direct one, since we will mess with it) params = arg_tovals(rawspec,false); % for each parameter produced by the GUI... for k = 1:length(outs) s = spec{k}; % current specifier v = outs{k}; % current raw value % do type conversion according to spec if iscell(s.range) && strcmp(s.type,'char') v = s.range{v}; elseif strcmp(s.type,'expression') v = eval(v); elseif strcmp(s.type,'logical') if length(s.range)>1 v = s.range(v); else v = logical(v); end elseif strcmp(s.type,'char') % noting to do else if ~isempty(v) v = eval(v); % convert back to numeric (or object, or cell) value end end % assign the converted value to params struct... params = assign(params,subset{k},v); end % now send the result through the function to check for errors and obtain a values structure... params = arg_report('rich',func,{params}); params = arg_tovals(params,false); else params = []; end % obtain a cell array of spec entries by name from the given specification function [items,ids] = obtain_items(rawspec,requested,prefix) if ~exist('prefix','var') prefix = ''; end items = {}; ids = {}; % determine what subset of (possibly nested) items is requested if isempty(requested) % look for a special argument/property arg_dialogsel, which defines the standard dialog representation for the given specification dialog_sel = find(cellfun(@(x)any(strcmp(x,'arg_dialogsel')),{rawspec.names})); if ~isempty(dialog_sel) requested = rawspec(dialog_sel).value; end end if isempty(requested) % empty means that all items are requested for k=1:length(rawspec) items{k} = rawspec(k); ids{k} = [prefix rawspec(k).names{1}]; end else % otherwise we need to obtain those items for k=1:length(requested) if ~isempty(requested{k}) try items{k} = obtain(rawspec,requested{k}); catch error(['The specified identifier (' prefix requested{k} ') could not be found in the function''s declared arguments.']); end ids{k} = [prefix requested{k}]; end end end % splice items that have children (recursively) into this list for k = length(items):-1:1 % special case: switch arguments are not spliced, but instead the argument that defines the option popupmenu will be retained if ~isempty(items{k}) && ~isempty(items{k}.children) && (~iscellstr(items{k}.range) || isempty(requested)) [subitems, subids] = obtain_items(items{k}.children,{},[ids{k} '.']); if ~isempty(subitems) % and introduce blank rows around them items = [items(1:k-1) {{}} subitems {{}} items(k+1:end)]; ids = [ids(1:k-1) {{}} subids {{}} ids(k+1:end)]; end end end % remove items that cannot be displayed retain = cellfun(@(x)isempty(x)||x.displayable,items); items = items(retain); ids = ids(retain); % remove double blank rows empties = cellfun('isempty',ids); items(empties(1:end-1) & empties(2:end)) = []; ids(empties(1:end-1) & empties(2:end)) = []; % obtain a spec entry by name from the given specification function item = obtain(rawspec,identifier) % parse the . notation dot = find(identifier=='.',1); if ~isempty(dot) [head,rest] = deal(identifier(1:dot-1), identifier(dot+1:end)); else head = identifier; rest = []; end % search for the identifier at this level names = {rawspec.names}; for k=1:length(names) if any(strcmp(names{k},head)) % found a match! if isempty(rest) % return it item = rawspec(k); else % obtain the rest of the identifier item = obtain(rawspec(k).children,rest); end return; end end error(['The given identifier (' head ') was not found among the function''s declared arguments.']); % assign a field with dot notation in a struct function s = assign(s,id,v) % parse the . notation dot = find(id=='.',1); if ~isempty(dot) [head,rest] = deal(id(1:dot-1), id(dot+1:end)); if ~isfield(s,head) s.(head) = struct(); end s.(head) = assign(s.(head),rest,v); else s.(id) = v; end
github
lcnbeapp/beapp-master
arg_guidialog_ex.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_guidialog_ex.m
8,675
utf_8
82a7c00e1dfc74a921a596040b742fd9
function params = arg_guidialog(func,varargin) % Create an input dialog that displays input fields for a Function and Parameters. % Parameters = arg_guidialog(Function, Options...) % % The Parameters that are passed to the function can be used to override some of its defaults. % The function must declare its arguments via arg_define. In addition, only a Subset of the function's specified arguments can be displayed. % % In: % Function : the function for which to display arguments % % Options... : optional name-value pairs; possible names are: % 'Parameters' : cell array of parameters to the Function to override some of its defaults. % % 'Subset' : Cell array of argument names to which the dialog shall be restricted; these arguments may contain . notation to index % into arg_sub and the selected branch(es) of arg_subswitch/arg_subtoggle specifiers. % Empty cells show up in the dialog as empty rows. % % 'Title' : title of the dialog (by default: functionname()) % % Out: % Parameters : a struct that is a valid input to the Function. % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-10-24 % parse arguments... hlp_varargin2struct(varargin,{'params','Parameters'},{}, {'subset','Subset'},{}, {'dialogtitle','title','Title'}, [char(func) '()'], {'buttons','Buttons'},[]); % obtain the argument specification for the function rawspec = arg_report('rich', func, params); %#ok<*NODEF> % extract a list of sub arguments... [spec,subset] = obtain_items(rawspec,subset); % create an inputgui() dialog... geometry = repmat({[0.6 0.35]},1,length(spec)+length(buttons)/2); geomvert = ones(1,length(spec)+length(buttons)/2); % turn the spec into a UI list... uilist = {}; for k = 1:length(spec) s = spec{k}; if isempty(s) uilist(end+1:end+2) = {{} {}}; else if isempty(s.help) error(['Cannot display the argument ' subset{k} ' because it contains no description.']); else tag = subset{k}; uilist{end+1} = {'Style','text', 'string',s.help{1}, 'fontweight','bold'}; % depending on the type, we introduce different types of input widgets here... if iscell(s.range) && strcmp(s.type,'char') % string popup menu uilist{end+1} = {'Style','popupmenu', 'string',s.range,'value',find(strcmp(s.value,s.range)),'tag',tag}; elseif strcmp(s.type,'logical') if length(s.range)>1 % multiselect uilist{end+1} = {'Style','listbox', 'string',s.range, 'value',find(strcmp(s.value,s.range)),'tag',tag,'min',1,'max',100000}; geomvert(k) = min(3.5,length(s.range)); else % checkbox uilist{end+1} = {'Style','checkbox', 'string','(set)', 'value',double(s.value),'tag',tag}; end elseif strcmp(s.type,'char') % string edit uilist{end+1} = {'Style','edit', 'string', s.value,'tag',tag}; else % expression edit if isinteger(s.value) s.value = double(s.value); end uilist{end+1} = {'Style','edit', 'string', hlp_tostring(s.value),'tag',tag}; end % append the tooltip string if length(s.help) > 1 uilist{end} = [uilist{end} 'tooltipstring', regexprep(s.help{2},'\.\s+(?=[A-Z])','.\n')]; end end end if ~isempty(buttons) && k==buttons{1} % render a command button uilist(end+1:end+2) = {{} buttons{2}}; buttons(1:2) = []; end end % invoke the GUI, obtaining a list of output values... [outs,dummy,okpressed] = inputgui('geometry',geometry, 'uilist',uilist,'helpcom','disp(''coming soon...'')', 'title',dialogtitle,'geomvert',geomvert); if ~isempty(okpressed) % remove blanks from the spec spec = spec(~cellfun('isempty',spec)); subset = subset(~cellfun('isempty',subset)); % turn the raw specification into a parameter struct (a non-direct one, since we will mess with it) params = arg_tovals(rawspec,false); % for each parameter produced by the GUI... for k = 1:length(outs) s = spec{k}; % current specifier v = outs{k}; % current raw value % do type conversion according to spec if iscell(s.range) && strcmp(s.type,'char') v = s.range{v}; elseif strcmp(s.type,'expression') v = eval(v); elseif strcmp(s.type,'logical') if length(s.range)>1 v = s.range(v); else v = logical(v); end elseif strcmp(s.type,'char') % noting to do else if ~isempty(v) v = eval(v); % convert back to numeric (or object, or cell) value end end % assign the converted value to params struct... params = assign(params,subset{k},v); end % now send the result through the function to check for errors and obtain a values structure... params = arg_report('rich',func,{params}); params = arg_tovals(params,false); else params = []; end % obtain a cell array of spec entries by name from the given specification function [items,ids] = obtain_items(rawspec,requested,prefix) if ~exist('prefix','var') prefix = ''; end items = {}; ids = {}; % determine what subset of (possibly nested) items is requested if isempty(requested) % look for a special argument/property arg_dialogsel, which defines the standard dialog representation for the given specification dialog_sel = find(cellfun(@(x)any(strcmp(x,'arg_dialogsel')),{rawspec.names})); if ~isempty(dialog_sel) requested = rawspec(dialog_sel).value; end end if isempty(requested) % empty means that all items are requested for k=1:length(rawspec) items{k} = rawspec(k); ids{k} = [prefix rawspec(k).names{1}]; end else % otherwise we need to obtain those items for k=1:length(requested) if ~isempty(requested{k}) try items{k} = obtain(rawspec,requested{k}); catch error(['The specified identifier (' prefix requested{k} ') could not be found in the function''s declared arguments.']); end ids{k} = [prefix requested{k}]; end end end % splice items that have children (recursively) into this list for k = length(items):-1:1 % special case: switch arguments are not spliced, but instead the argument that defines the option popupmenu will be retained if ~isempty(items{k}) && ~isempty(items{k}.children) && (~iscellstr(items{k}.range) || isempty(requested)) [subitems, subids] = obtain_items(items{k}.children,{},[ids{k} '.']); if ~isempty(subitems) % and introduce blank rows around them items = [items(1:k-1) {{}} subitems {{}} items(k+1:end)]; ids = [ids(1:k-1) {{}} subids {{}} ids(k+1:end)]; end end end % remove items that cannot be displayed retain = cellfun(@(x)isempty(x)||x.displayable,items); items = items(retain); ids = ids(retain); % remove double blank rows empties = cellfun('isempty',ids); items(empties(1:end-1) & empties(2:end)) = []; ids(empties(1:end-1) & empties(2:end)) = []; % obtain a spec entry by name from the given specification function item = obtain(rawspec,identifier) % parse the . notation dot = find(identifier=='.',1); if ~isempty(dot) [head,rest] = deal(identifier(1:dot-1), identifier(dot+1:end)); else head = identifier; rest = []; end % search for the identifier at this level names = {rawspec.names}; for k=1:length(names) if any(strcmp(names{k},head)) % found a match! if isempty(rest) % return it item = rawspec(k); else % obtain the rest of the identifier item = obtain(rawspec(k).children,rest); end return; end end error(['The given identifier (' head ') was not found among the function''s declared arguments.']); % assign a field with dot notation in a struct function s = assign(s,id,v) % parse the . notation dot = find(id=='.',1); if ~isempty(dot) [head,rest] = deal(id(1:dot-1), id(dot+1:end)); if ~isfield(s,head) s.(head) = struct(); end s.(head) = assign(s.(head),rest,v); else s.(id) = v; end
github
lcnbeapp/beapp-master
invoke_arg_internal.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/invoke_arg_internal.m
4,456
utf_8
cde8b4f57b2bc16a8b03c45c255fe35d
function spec = invoke_arg_internal(reptype,varargin) %#ok<INUSL> % same type of invoke function as in arg_sub, arg_subswitch, etc. - but shared between % arg, arg_norep, and arg_nogui spec = hlp_microcache('arg',@invoke_arg,varargin{:}); % the function that does the actual work of building the argument specifier function spec = invoke_arg(names,default,range,help,varargin) % start with a base specification spec = arg_specifier('head',@arg); % override properties if exist('names','var') spec.names = names; end if exist('default','var') spec.value = default; end if exist('range','var') spec.range = range; end if exist('help','var') spec.help = help; end for k=1:2:length(varargin) if isfield(spec,varargin{k}) spec.(varargin{k}) = varargin{k+1}; else error('BCILAB:arg:no_new_fields','It is not allowed to introduce fields into a specifier that are not declared in arg_specifier.'); end end % do fixups & checking if ~iscell(spec.names) spec.names = {spec.names}; end if isempty(spec.names) || ~iscellstr(spec.names) error('The argument must have a name or cell array of names.'); end % parse the help if ~isempty(spec.help) try spec.help = parse_help(spec.help); catch e disp(['Problem with the help text for argument ' spec.names{1} ': ' e.message]); spec.help = {}; end elseif spec.reportable && spec.displayable disp(['Please specify a description for argument ' spec.names{1} ', or specify it via arg_nogui() instead.']); end % do type inference [spec.type,spec.shape,spec.range,spec.value] = infer_type(spec.type,spec.shape,spec.range,spec.value); % infer the type & range of the argument, based on provided info (note: somewhat messy) function [type,shape,range,value] = infer_type(type,shape,range,value) try if isempty(type) % try to auto-discover the type (or leave empty, if impossible) if ~isempty(value) type = PropertyType.AutoDiscoverType(value); elseif ~isempty(range) if isnumeric(range) type = PropertyType.AutoDiscoverType(range); elseif iscell(range) types = cellfun(@PropertyType.AutoDiscoverType,range,'UniformOutput',false); if length(unique(types)) == 1 type = types{1}; end end end end if isempty(shape) % try to auto-discover the shape if ~isempty(value) shape = PropertyType.AutoDiscoverShape(value); elseif ~isempty(range) if isnumeric(range) shape = 'scalar'; elseif iscell(range) shapes = cellfun(@PropertyType.AutoDiscoverShape,range,'UniformOutput',false); if length(unique(shapes)) == 1 shape = shapes{1}; end end end end catch end % rule: if in doubt, fall back to denserealdouble and/or matrix if isempty(type) type = 'denserealdouble'; end if isempty(shape) shape = 'matrix'; end % rule: if both the value and the range are cell-string arrays, the type is 'logical'; % this means that the value is a subset of the range if iscellstr(value) && iscellstr(range) type = 'logical'; end % rule: if the value is empty, but the range is a cell-string array and the type is not 'logical', % the value is the first range element; here, the value is exactly one out of the possible % strings in range (and cannot be empty) if isempty(value) && iscellstr(range) && ~strcmp(type,'logical') value = range{1}; end % rule: if the value is an empty char array, the shape is by default 'row' if isequal(value,'') && ischar(value) shape = 'row'; end % rule: if the value is []; convert to the appropriate MATLAB type (e.g., int, etc.) if isequal(value,[]) if strcmp(type,'cellstr') value = {}; else try pt = PropertyType(type,shape,range); value = pt.ConvertFromMatLab(value); catch end end end % rule: if the value is a logical scalar and the type is logical, and the range is a cell-string % array (i.e. a set of strings), the value is mapped to either the entire set or the empty set % (i.e. either all elements are in, or none) if isscalar(value) && islogical(value) && strcmp(type,'logical') && iscell(range) if value value = range; else value = {}; end end
github
lcnbeapp/beapp-master
arg_report.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_report.m
6,925
utf_8
eb8f94b9fd0693dbde5cbfa2824b7e8d
function res = arg_report(type,func,args) % Report information of a certain Type from the given Function. % Result = arg_report(Type,Function,Arguments) % % Functions that declare their arguments via arg_define() make their parameter specification % accessible to outside functions. This can be used to display auto-generated settings dialogs, to % record function calls, and so on. % % Varying amounts of meta-data can be obtained in addition to the raw parameter values, including % just the bare-bones value struct ('vals'), the meta-data associated with the passed arguments, % and the full set of meta-data for all possible options (for multi-option parameters), even if these % options were not actually prompted by the Arguments. % % In: % Type : Type of information to report, can be one of the following: % 'rich' : Report a rich declaration of the function's arguments as a struct array, with % fields as in arg_specifier. % 'lean' : Report a lean declaration of the function's arguments as a struct array, with % fields as in arg_specifier, like rich, but excluding the alternatives field. % 'vals' : Report the values of the function's arguments as a struct, possibly with % sub-structs. % % 'properties' : Report properties of the function, if any (these can be declared via % declare_properties) % % 'handle': Report function handles to scoped functions within the Function (i.e., % subfunctions). The named of those functions are listed as a cell string array % in place of Arguments, unless there is exactly one returned function. Then, % this function is returned as-is. This functionality is a nice-to-have feature % for some use cases but not essential to the operation of the argument system. % % Function : a function handle to a function which defines some arguments (via arg_define) % % Arguments : cell array of parameters to be passed to the function; depending on the function's % implementation, this can affect the current value assignment (or structure) of the % parameters being returned If this is not a cell, it is automatically wrapped inside % one (note: to specify the first positional argument as [] to the function, always % pass it as {[]}; this is only relevant if the first argument's default is non-[]). % % Out: % Result : the reported data. % % Notes: % In all cases except 'properties', the Function must use arg_define() to define its arguments. % % Examples: % % for a function call with some arguments assigned, obtain a struct with all parameter % % names and values, including defaults % params = arg_report('vals',@myfunction,{4,10,true,'option1','xxx','option5',10}) % % % obtain a specification of all function arguments, with defaults, help text, type, shape, and other % % meta-data (with a subset of settings customized according to arguments) % spec = arg_report('rich',@myfunction,myarguments) % % % obtain a report of properties of the function (declared via declared_properties() within the % % function) % props = arg_report('properties',@myfunction) % % See also: % arg_define, declare_properties % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-09-24 % uniformize arguments if ~exist('args','var') args = {}; end if isequal(args,[]) args = {}; end if ~iscell(args) args = {args}; end if ischar(func) func = str2func(func); end % make sure that the direct mode is disabled for the function being called (because in direct mode % it doesn't report) indices = find(cellfun('isclass',args,'struct') | strcmp(args,'arg_direct')); for k = indices(end:-1:1) if ischar(args{k}) && k<length(args) % found it in the NVPs args{k+1} = false; break; elseif isfield(args{k},'arg_direct') % found it in a struct args{k}.arg_direct = false; break; end end if any(strcmpi(type,{'rich','lean','vals','handle'})) % issue the report res = do_report(type,func,args); elseif strcmpi(type,'properties') if isempty(args) % without arguments we can do a quick hash map lookup % (based on the MD5 hash of the file in question) info = functions(func); hash = ['h' utl_fileinfo(info.file,char(func))]; try % try lookup persistent cached_properties; %#ok<TLEV> res = cached_properties.(hash); catch % fall back to actually reporting it res = do_report('properties',func,args); % and store it for the next time cached_properties.(hash) = res; end else % with arguments we don't try to cache (as the properties might be argument-dependent) res = do_report('properties',func,args); end end function res = do_report(type,func,args) global tracking; persistent have_expeval; if isempty(have_expeval) have_expeval = exist('exp_eval','file'); end try % the presence of one of the arg_report_*** functions in the stack communicates to the receiver % that a report is requested and what type of report... feval(['arg_report_' lower(type)],func,args,have_expeval); catch report if strcmp(report.identifier,'BCILAB:arg:report_args') % get the ticket of the report ticket = sscanf(report.message((find(report.message=='=',1,'last')+1):end),'%f'); % read out the payload res = tracking.arg_sys.reports{ticket}; % and return the ticket tracking.arg_sys.tickets.addLast(ticket); else % other error: if strcmp(type,'properties') % almost certainly no properties clause defined res = {}; else % genuine error: pass it on rethrow(report); end end end % --- a bit of boilerplate below (as the caller's name is relevant here) --- function arg_report_rich(func,args,have_expeval) %#ok<DEFNU> if have_expeval && nargout(func) > 0 exp_eval(func(args{:})); else func(args{:}); end function arg_report_lean(func,args,have_expeval) %#ok<DEFNU> if have_expeval && nargout(func) > 0 exp_eval(func(args{:})); else func(args{:}); end function arg_report_vals(func,args,have_expeval) %#ok<DEFNU> if have_expeval && nargout(func) > 0 exp_eval(func(args{:})); else func(args{:}); end function arg_report_handle(func,args,have_expeval) %#ok<DEFNU> if have_expeval && nargout(func) > 0 exp_eval(func(args{:})); else func(args{:}); end function arg_report_properties(func,args,have_expeval) %#ok<DEFNU> if have_expeval && nargout(func) > 0 exp_eval(func(args{:})); else func(args{:}); end
github
lcnbeapp/beapp-master
arg_subswitch.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_subswitch.m
17,047
utf_8
f8e71db07aba22fedb0dce863f122c40
function res = arg_subswitch(varargin) % Specify a function argument that can be one of several alternative structs. % Spec = arg_subswitch(Names,Defaults,Alternatives,Help,Options...) % % The correct struct is chosen according to a selection rule (the mapper). Accessible to the % function as a struct, and visible in the GUI as an expandable sub-list of arguments (with a % drop-down list of alternative options). The chosen option (usually one out of a set of strings) is % delivered to the Function as the special struct field 'arg_selection'. % % In: % Names : The name(s) of the argument. At least one must be specified, and if multiple are % specified, they must be passed in a cell array. % * The first name specified is the argument's "code" name, as it should appear in the % function's code (= the name under which arg_define() returns it to the function). % * The second name, if specified, is the "Human-readable" name, which is exposed in the % GUIs (if omitted, the code name is displayed). % * Further specified names are alternative names for the argument (e.g., for backwards % compatibility with older function syntaxes/parameter names). % % Defaults : A cell array of arguments to override defaults for the Source (sources declared as % part of Alternatives); all syntax accepted by the (selected) Source is allowed here, % whereas in the case of positional arguments, the leading arg_norep() arguments of the % source are implicitly skipped. Note: Which one out of the several alternatives should % be selected is determined via the 'mapper' (which can be overridden in form of an % optional parameter). By default, the mapper maps the first argument to the Selector, % and assigns the rest to the matching Source. % % Alternatives : Definition of the switchable option groups. This is a cell array of the form: % {{'selector', Source}, {'selector', Source}, {'selector', Source}, ...} Each % Source is either a function handle (referring to a function that exposes % arguments via an arg_define() clause), or an in-line cell array of argument % specifications, analogously to the more detailed explanation in arg_sub(). In the % latter case (Source is a cell array), the option group may also be a 3-element % cell array of the form {'selector',Source,Format} ... where Format is a format % specifier as explained in arg_define(). % % Help : The help text for this argument (displayed inside GUIs), optional. (default: []). % (Developers: Please do *not* omit this, as it is the key bridge between ease of use and % advanced functionality.) % % The first sentence should be the executive summary (max. 60 chars), any further sentences % are a detailed explanation (examples, units, considerations). The end of the first % sentence is indicated by a '. ' followed by a capital letter (beginning of the next % sentence). If ambiguous, the help can also be specified as a cell array of 2 cells. % % Options... : Optional name-value pairs to denote additional properties: % 'cat' : The human-readable category of this argument, helpful to present a list % of many parameters in a categorized list, and to separate "Core % Parameters" from "Miscellaneous" arguments. Developers: When choosing % names, every bit of consistency with other function in the toolbox helps % the uses find their way (default: []). % % 'mapper' : A function that maps the value (cell array of arguments like Defaults) % to a value in the domain of selectors (first output), and a potentially % updated argument list (second output). The mapper is applied to the % argument list prior to any parsing (i.e. it faces the raw argument % list) to determine the current selection, and its second output (the % potentially updated argument list) is forwarded to the Source that was % selected, for further parsing. % % The default mapper takes the first argument in the argument list as the % Selector and passes the remaining list entries to the Source. If there % is only a single argument that is a struct with a field % 'arg_selection', this field's value is taken as the Selector, and the % struct is passed as-is to the Source. % % 'merge': Whether a value (cell array of arguments) assigned to this argument % should completely replace all arguments of the default, or whether it % should instead the two cell arrays should be concatenated ('merged'), so % that defaults are only selectively overridden. Note that for % concatenation to make sense, the cell array of Defaults cannot be some % subset of all allowed positional arguments, but must instead either be % the full set of positional arguments (and possibly some NVPs) or be % specified as NVPs in the first place. % % Out: % Spec : A cell array, that, when called as spec{1}(reptype,spec{2}{:}), yields a specification of % the argument, for use by arg_define. Technical note: Upon assignment with a value (via % the assigner field), the 'children' field of the specifier struct is populated according % to how the selected (by the mapper) Source (from Alternatives) parses the value into % arguments. The additional struct field 'arg_selection 'is introduced at this point. % % Examples: % % define a function with a multiple-choice argument, with different sub-arguments for each choice % % (where the default is 'kmeans'; some valid calls are: % % myfunction('method','em','flagXY',true) % % myfunction('flagXY',true, 'method',{'em', 'myarg',1001}) % % myfunction({'vb', 'myarg1',1001, 'myarg2','test'},false) % % myfunction({'kmeans', struct('arg2','test')}) % function myfunction(varargin) % arg_define(varargin, ... % arg_subswitch('method','kmeans',{ ... % {'kmeans', {arg('arg1',10,[],'argument for kmeans.'), arg('arg2','test',[],'another argument for it.')}, ... % {'em', {arg('myarg',1000,[],'argument for the EM method.')}, ... % {'vb', {arg('myarg1',test',[],'argument for the VB method.'), arg('myarg2','xyz',[],'another argument for VB.')} ... % }, 'Method to use. Three methods are supported: k-means, EM and VB, and each method has optional parameters that can be specified if chosen.'), ... % arg('flagXY',false,[],'And some flag.')); % % % define a function with a multiple-choice argument, where the arguments for the choices come % % from a different function each % function myfunction(varargin) % arg_define(varargin, ... % arg_subswitch('method','kmeans',{{'kmeans', @kmeans},{'em', @expectation_maximization},{'vb',@variational_bayes}}, 'Method to use. Each has optional parameters that can be specified if chosen.'), ... % arg('flagXY',false,[],'And some flag.')); % % % as before, but specify a different default and override some of the arguments for that default % function myfunction(varargin) % arg_define(varargin, ... % arg_subswitch('method',{'vb','myarg1','toast'},{{'kmeans', @kmeans},{'em', @expectation_maximization},{'vb',@variational_bayes}}, 'Method to use. Each has optional parameters that can be specified if chosen.'), ... % arg('flagXY',false,[],'And some flag.')); % % % specify a custom function to determine the format of the argument (and in particular the % % mapping of assigned value to chosen selection % arg_subswitch('method','kmeans',{{'kmeans', @kmeans},{'em',@expectation_maximization},{'vb',@variational_bayes}}, ... % 'Method to use. Each has optional parameters that can be specified if chosen.', 'mapper',@mymapper), ... % % See also: % arg, arg_nogui, arg_norep, arg_sub, arg_subtoggle, arg_define % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-09-24 % we return a function that an be invoked to yield a specification (its output is cached for % efficiency) packed in a cell array together with the remaining arguments res = {@invoke_argsubswitch_cached,varargin}; function spec = invoke_argsubswitch_cached(varargin) spec = hlp_microcache('arg',@invoke_argsubswitch,varargin{:}); % the function that does the actual work of building the argument specifier function spec = invoke_argsubswitch(reptype,names,defaults,alternatives,help,varargin) suppressNames = {}; % start with a base specification spec = arg_specifier('head',@arg_subswitch, 'type','char', 'shape','row', 'mapper',@map_argsubswitch); % override properties if exist('names','var') spec.names = names; end if exist('help','var') spec.help = help; end for k=1:2:length(varargin) if isfield(spec,varargin{k}) spec.(varargin{k}) = varargin{k+1}; elseif strcmpi(varargin{k},'suppress') suppressNames = varargin{k+1}; else error(['BCILAB:arg:no_new_fields','It is not allowed to introduce fields (here: ' varargin{k} ') into a specifier that are not declared in arg_specifier.']); end end % do checking if ~iscell(spec.names) spec.names = {spec.names}; end if isempty(spec.names) || ~iscellstr(spec.names) error('The argument must have a name or cell array of names.'); end if isempty(alternatives) error('BCILAB:args:no_options','The Alternatives argument for arg_subswitch() may not be omitted.'); end %#ok<*NODEF> if nargin(spec.mapper) == 1 spec.mapper = @(x,y,z) spec.mapper(x); end % parse the help if ~isempty(spec.help) try spec.help = parse_help(spec.help,100); catch e disp(['Problem with the help text for argument ' spec.names{1} ': ' e.message]); spec.help = {}; end elseif spec.reportable && spec.displayable disp(['Please specify a description for argument ' spec.names{1} ', or specify it via arg_nogui() instead.']); end % uniformize Alternatives syntax into {{'selector1',@function1, ...}, {'selector2',@function2, ...}, ...} if iscellstr(alternatives(1:2:end)) && all(cellfun(@(x)iscell(x)||isa(x,'function_handle'),alternatives(2:2:end))) alternatives = mat2cell(alternatives,1,repmat(2,length(alternatives)/2,1)); end % derive range spec.range = cellfun(@(c)c{1},alternatives,'UniformOutput',false); % turn Alternatives into a cell array of Source functions for k=1:length(alternatives) sel = alternatives{k}; selector = sel{1}; source = sel{2}; if ~ischar(selector) error('In arg_subswitch, each selector must be a string.'); end if length(sel) > 2 fmt = sel{3}; else fmt = []; end % uniformize Source syntax... if iscell(source) % args is a cell array instead of a function: we effectively turn this into a regular % arg_define-using function (taking & parsing values) source = @(varargin) arg_define(fmt,varargin,source{:}); else % args is a function: was a custom format specified? if isa(fmt,'function_handle') source = @(varargin) source(fmt(varargin)); elseif ~isempty(fmt) error('The only allowed form in which the Format of a Source that is a function may be overridden is as a pre-parser (given as a function handle)'); end end alternatives{k} = source; end sources = alternatives; % wrap the defaults into a cell if necessary (note: this is convenience syntax) if ~iscell(defaults) if ~(isstruct(defaults) || ischar(defaults)) error(['It is not allowed to use anything other than a cell, a struct, or a (selector) string as default for an arg_subswitch argument (here:' spec.names{1} ')']); end defaults = {defaults}; end % find out what index and value set the default configuration maps to; this is relevant for the % merging option: in this case, we need to pull up the correct default and merge it with the passed % value [default_sel,default_val] = spec.mapper(defaults,spec.range,spec.names); default_idx = find(strcmp(default_sel,spec.range)); % create the regular assigner... spec.assigner = @(spec,value) assign_argsubswitch(spec,value,reptype,sources,default_idx,default_val,suppressNames); % and assign the default itself if strcmp(reptype,'rich') spec = assign_argsubswitch(spec,defaults,'build',sources,0,{},suppressNames); else spec = assign_argsubswitch(spec,defaults,'lean',sources,0,{},suppressNames); end function spec = assign_argsubswitch(spec,value,reptype,sources,default_idx,default_val,suppressNames) % for convenience (in scripts calling the function), also support values that are not cell arrays if ~iscell(value) if ~(isstruct(value) || ischar(value)) error(['It is not allowed to assign anything other than a cell, a struct, or a (selector) string to an arg_subswitch argument (here:' spec.names{1} ')']); end value = {value}; end % run the mapper to get the selection according to the value (selectors is here for error checking); % also update the value [selection,value] = spec.mapper(value,spec.range,spec.names); % find the appropriate index in the selections... idx = find(strcmp(selection,spec.range)); % if we should build the set of alternatives, do so now.... if strcmp(reptype,'build') for n=setdiff(1:length(sources),idx) arg_sel = arg_nogui('arg_selection',spec.range{n}); spec.alternatives{n} = [arg_report('rich',sources{n}) arg_sel{1}([],arg_sel{2}{:})]; end reptype = 'rich'; end % build children and override the appropriate item in the aternatives arg_sel = arg_nogui('arg_selection',spec.range{idx}); if spec.merge && idx == default_idx spec.children = [arg_report(reptype,sources{idx},[default_val value]) arg_sel{1}([],arg_sel{2}{:})]; else spec.children = [arg_report(reptype,sources{idx},value) arg_sel{1}([],arg_sel{2}{:})]; end % toggle the displayable option for children which should be suppressed if ~isempty(suppressNames) % identify which children we want to suppress display hidden = find(cellfun(@any,cellfun(@(x,y) ismember(x,suppressNames),{spec.children.names},'UniformOutput',false))); % set display flag to false for k=hidden(:)' spec.children(k).displayable = false; end % identify which alternatives we want to suppress display for alt_idx = 1:length(spec.alternatives) if isempty(spec.alternatives{alt_idx}) continue; end hidden = find(cellfun(@any,cellfun(@(x,y) ismember(x,suppressNames),{spec.alternatives{alt_idx}.names},'UniformOutput',false))); % set display flag to false for k=hidden(:)' spec.alternatives{alt_idx}(k).displayable = false; end end end spec.alternatives{idx} = spec.children; % and set the value of the selector field itself to the current selection spec.value = selection; function [selection,args] = map_argsubswitch(args,selectors,names) if isempty(args) selection = selectors{1}; elseif isfield(args{1},'arg_selection') selection = args{1}.arg_selection; elseif any(strcmp(args{1},selectors)) [selection,args] = deal(args{1},args(2:end)); else % find the arg_selection in the cell array pos = find(strcmp('arg_selection',args(1:end-1)),1,'last'); [selection,args] = deal(args{pos+1},args([1:pos-1 pos+2:end])); end % Note: If this error is triggered, an value was passed for an argument which has a flexible structure (chosen out of a set of possibilities), but the possibility % which was chosen according to the passed value does not match any of the specified ones. For a value that is a cell array of arguments, the choice is % made based on the first element in the cell. For a value that is a structure of arguments, the choice is made based on the 'arg_selection' field. % The error is usually resolved by reviewing the argument specification of the offending function carefully, and comparing the passed value to the Alternatives % declared in the arg_subswitch() clause in which the offending argument is declared. if ~any(strcmpi(selection,selectors)) error(['The chosen selector argument (' selection ') does not match any of the possible options (' sprintf('%s, ',selectors{1:end-1}) selectors{end} ') in the function argument ' names{1} '.']); end
github
lcnbeapp/beapp-master
arg_sub.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_sub.m
12,136
utf_8
579d06548d7bb9eba5580ea1d6d33322
function res = arg_sub(varargin) % Specify an argument of a function which is a structure of sub-arguments. % Spec = arg_sub(Names,Defaults,Source,Help,Options...) % % Delivered to the function as a struct, and visible in the GUI as a an expandable sub-list of % arguments. A function may have an argument which itself consists of several arguments. For % example, a function may be passing the contents of this struct as arguments to another function, % or may just collect several arguments into sub-fields of a single struct. Differs from the default % arg() function by allowing, instead of the Range, either a Source function which exposes a list of % arguments (itself using arg_define), or a cell array with argument specifications, identical in % format to the Specification part of an arg_define() clause. % % In: % Names : The name(s) of the argument. At least one must be specified, and if multiple are % specified, they must be passed in a cell array. % * The first name specified is the argument's "code" name, as it should appear in the % function's code (= the name under which arg_define() returns it to the function). % * The second name, if specified, is the "Human-readable" name, which is exposed in the % GUIs (if omitted, the code name is displayed). % * Further specified names are alternative names for the argument (e.g., for backwards % compatibility with older function syntaxes/parameter names). % % Defaults : A cell array of arguments to override defaults for the Source; all syntax accepted by % the Source is allowed here, whereas in the case of positional arguments, the leading % arg_norep() arguments of the source are implicitly skipped. If empty, the defaults of % the Source are unaffected. % % Source : A source of argument specifications, usually a function handle (referring to a function % which defines arguments via arg_define()). % % For convenience, a cell array with a list of argument declarations, formatted like the % Specification part of an arg_define() clause can be given, instead. In this case, the % effect is the same as specifying @some_function, for a function implemented as: % % function some_function(varargin) arg_define(Format,varargin,Source{:}); % % Help : The help text for this argument (displayed inside GUIs), optional. (default: []). % (Developers: Please do *not* omit this, as it is the key bridge between ease of use and % advanced functionality.) % % The first sentence should be the executive summary (max. 60 chars), any further sentences % are a detailed explanation (examples, units, considerations). The end of the first % sentence is indicated by a '. ' followed by a capital letter (beginning of the next % sentence). If ambiguous, the help can also be specified as a cell array of 2 cells. % % Options... : Optional name-value pairs to denote additional properties: % 'cat' : The human-readable category of this argument, helpful to present a list % of many parameters in a categorized list, and to separate "Core % Parameters" from "Miscellaneous" arguments. Developers: When choosing % names, every bit of consistency with other function in the toolbox helps % the uses find their way (default: []). % % 'fmt' : Optional format specification for the Source (if it is a cell array) % (default: []). See arg_define() for a detailed explanation. % % 'merge': Whether a value (cell array of arguments) assigned to this argument % should completely replace all arguments of the default, or whether % instead the two cell arrays should be concatenated ('merged'), so that % defaults are only selectively overridden. Note that for concatenation to % make sense, the cell array of Defaults cannot be some subset of all % allowed positional arguments, but must instead either be the full set of % positional arguments (and possibly some NVPs) or be specified as NVPs in % the first place. (default: true) % % Out: % Spec : A cell array, that, when called as spec{1}(reptype,spec{2}{:}), yields a specification of % the argument, for use by arg_define. Technical note: Upon assignment with a value (via % the assigner field), the 'children' field of the specifier struct is populated according % to how the Source parses the value into arguments. % % Notes: % for MATLAB versions older than 2008a, type and shape checking is not necessarily enforced. % % Examples: % % define 3 arguments for a function, including one which is a struct of two other arguments. % % some valid calls to the function are: % % myfunction('somearg',false, 'anotherarg',10, 'structarg',{'myarg1',5,'myarg2','xyz'}) % % myfunction(false, 10, {'myarg1',5,'myarg2','xyz'}) % % myfunction('structarg',{'myarg2','xyz'}, 'somearg',false) % % myfunction('structarg',struct('myarg2','xyz','myarg1',10), 'somearg',false) % function myfunction(varargin) % arg_define(varargin, ... % arg('somearg',true,[],'Some argument.'),... % arg_sub('structarg',{},{ ... % arg('myarg1',4,[],'Some sub-argument. This is a sub-argument of the argument named structarg in the function'), ... % arg('myarg2','test',[],'Another sub-argument. This, too, is a sub-argument of structarg.') % }, 'Struct argument. This argument has sub-structure. It can generally be assigned a cell array of name-value pairs, or a struct.'), ... % arg('anotherarg',5,[],'Another argument. This is a regular numeric argument of myfunction again.)); % % % define a struct argument with some overridden defaults % arg_sub('structarg',{'myarg2','toast'},{ ... % arg('myarg1',4,[],'Some sub-argument. This is a sub-argument of the argument named structarg in the function'), ... % arg('myarg2','test',[],'Another sub-argument. This, too, is a sub-argument of structarg.') % }, 'Struct argument. This argument has sub-structure. It can generally be assigned a cell array of name-value pairs, or a struct.'), ... % % % define an arguments including one whose sub-parameters match those that are declared in some % % other function (@myotherfunction), which uses arg_define itself % function myfunction(varargin) % arg_define(varargin, ... % arg('somearg',[],[],'Some help text.'), ... % arg_sub('structarg',{},@myotherfunction, 'A struct argument. Arguments are as in myotherfunction(), can be assigned as a cell array of name-value pairs or structs.')); % % % define an argument with sub-parameters sourced from some other function, but with partially overridden defaults % arg_sub('structarg',{'myarg1',1001},@myotherfunction, 'A struct argument. Arguments are as in myotherfunction(), can be assigned as a cell array of name-value pairs or structs.')); % % % define an argument with sub-parameters sourced from some other function, with a particular set of custom defaults % % which are jointly replaced when a value is assigned to structarg (including an empty cell array) % arg_sub('structarg',{'myarg1',1001},@myotherfunction, 'A struct argument. Arguments are as in myotherfunction().', 'merge',false)); % % % define a struct argument with a custom formatting function (analogously to the optional Format function in arg_define) % % myparser shall be a function that takes a string and returns a cell array of name-value pairs (names compatible to the sub-argument names) % arg_sub('structarg',{},{ ... % arg('myarg1',4,[],'Some sub-argument. This is a sub-argument of the argument named structarg in the function'), ... % arg('myarg2','test',[],'Another sub-argument. This, too, is a sub-argument of structarg.') % }, 'Struct argument. This argument has sub-structure. Assign it as a string of the form ''name=value; name=value;''.', 'fmt',@myparser), ... % % See also: % arg, arg_nogui, arg_norep, arg_subswitch, arg_subtoggle, arg_define % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-09-24 % we return a function that an be invoked to yield a specification (its output is cached for % efficiency) packed in a cell array together with the remaining arguments res = {@invoke_argsub_cached,varargin}; function spec = invoke_argsub_cached(varargin) spec = hlp_microcache('arg',@invoke_argsub,varargin{:}); % the function that does the actual work of building the argument specifier function spec = invoke_argsub(reptype,names,defaults,source,help,varargin) % start with a base specification spec = arg_specifier('head',@arg_sub,'fmt',[], 'value','', 'type','char', 'shape','row'); suppressNames = {}; % override properties if exist('names','var') spec.names = names; end if exist('help','var') spec.help = help; end for k=1:2:length(varargin) if isfield(spec,varargin{k}) spec.(varargin{k}) = varargin{k+1}; elseif strcmpi(varargin{k},'suppress') suppressNames = varargin{k+1}; else error('BCILAB:arg:no_new_fields','It is not allowed to introduce fields into a specifier that are not declared in arg_specifier.'); end end % do checking if ~iscell(spec.names) spec.names = {spec.names}; end if isempty(spec.names) || ~iscellstr(spec.names) error('The argument must have a name or cell array of names.'); end if ~exist('source','var') || isequal(source,[]) error('BCILAB:args:no_source','The Source argument for arg_sub() may not be omitted.'); end %#ok<*NODEF> % parse the help if ~isempty(spec.help) try spec.help = parse_help(spec.help,100); catch e disp(['Problem with the help text for argument ' spec.names{1} ': ' e.message]); spec.help = {}; end elseif spec.reportable && spec.displayable disp(['Please specify a description for argument ' spec.names{1} ', or specify it via arg_nogui() instead.']); end if ~isempty(source) % uniformize Source syntax if iscell(source) % args is a cell array instead of a function: we effectively turn this into a regular % arg_define-using function (taking & parsing values) source = @(varargin) arg_define(spec.fmt,varargin,source{:}); else % args is a function: was a custom format specified? if isa(spec.fmt,'function_handle') source = @(varargin) source(spec.fmt(varargin)); elseif ~isempty(spec.fmt) error('The only allowed form in which the Format of a Source that is a function may be overridden is as a pre-parser (given as a function handle)'); end end end spec = rmfield(spec,'fmt'); % assignment to this object does not touch the value, but instead creates a new children structure spec.assigner = @(spec,value) assign_argsub(spec,value,reptype,source,defaults,suppressNames); % assign the default spec = assign_argsub(spec,defaults,reptype,source,[],suppressNames); % function to do the value assignment function spec = assign_argsub(spec,value,reptype,source,default,suppressNames) if ~isempty(source) if spec.merge spec.children = arg_report(reptype,source,[default,value]); else spec.children = arg_report(reptype,source,value); end end % toggle the displayable option for children which should be suppressed if ~isempty(suppressNames) % identify which children we want to suppress display hidden = find(cellfun(@any,cellfun(@(x,y) ismember(x,suppressNames),{spec.children.names},'UniformOutput',false))); % set display flag to false for k=hidden(:)' spec.children(k).displayable = false; end end
github
lcnbeapp/beapp-master
arg_subtoggle.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_subtoggle.m
15,337
utf_8
6bfc9dc025de4ebf873f2152b77f7ee4
function res = arg_subtoggle(varargin) % Specify an argument of a function which is a struct of sub-arguments that can be disabled. % Spec = arg_subtoggle(Names,Default,Source,Help,Options...) % % Accessible to the function as a struct, and visible in the GUI as a an expandable sub-list of % arguments (with a checkbox to toggle). The special field 'arg_selection' (true/false) indicates % whether the argument is enabled or not. The value assigned to the argument determines whether it % is turned on or off, as determined by the mapper option. % % In: % Names : The name(s) of the argument. At least one must be specified, and if multiple are % specified, they must be passed in a cell array. % * The first name specified is the argument's "code" name, as it should appear in the % function's code (= the name under which arg_define() returns it to the function). % * The second name, if specified, is the "Human-readable" name, which is exposed in the % GUIs (if omitted, the code name is displayed). % * Further specified names are alternative names for the argument (e.g., for backwards % compatibility with older function syntaxes/parameter names). % % Defaults : A cell array of arguments to override defaults for the Source; all syntax accepted by % the (selected) Source is allowed here, whereas in the case of positional arguments, % the leading arg_norep() arguments of the source are implicitly skipped. Note: Whether % the argument is turned on or off is determined via the 'mapper' option. By default, % [] and 'off' are mapped to off, whereas {}, non-empty cell arrays and structs are % mapped to on. % % Source : A source of argument specifications, usually a function handle (referring to a function % which defines arguments via arg_define()). % % For convenience, a cell array with a list of argument declarations, formatted like the % Specification part of an arg_define() clause can be given, instead. In this case, the % effect is the same as specifying @some_function, for a function implemented as: % % function some_function(varargin) arg_define(Format,varargin,Source{:}); % % Help : The help text for this argument (displayed inside GUIs), optional. (default: []). % (Developers: Please do *not* omit this, as it is the key bridge between ease of use and % advanced functionality.) % % The first sentence should be the executive summary (max. 60 chars), any further sentences % are a detailed explanation (examples, units, considerations). The end of the first % sentence is indicated by a '. ' followed by a capital letter (beginning of the next % sentence). If ambiguous, the help can also be specified as a cell array of 2 cells. % % Options... : Optional name-value pairs to denote additional properties: % 'cat' : The human-readable category of this argument, helpful to present a list % of many parameters in a categorized list, and to separate % "Core Parameters" from "Miscellaneous" arguments. Developers: When % choosing names, every bit of consistency with other function in the % toolbox helps the uses find their way (default: []). % % 'fmt' : Optional format specification for the Source (if it is a cell array) % (default: []). See arg_define() for a detailed explanation. % % 'mapper' : A function that maps the argument list (e.g., Defaults) to a value in % the domain of selectors, and a potentially updated argument list. The % mapper is applied to the argument list prior to any parsing (i.e. it % faces the raw argument list) to determine the current selection, and % its its second output (the potentially updated argument list) is % forwarded to the Source that was selected, for further parsing. % % The default mapper maps [] and 'off' to off, whereas 'on', empty or % non-empty cell arrays and structs are mapped to on. % % 'merge': Whether a value (cell array of arguments) assigned to this argument % should completely replace all arguments of the default, or whether it % should instead the two cell arrays should be concatenated ('merged'), so % that defaults are only selectively overridden. Note that for % concatenation to make sense, the cell array of Defaults cannot be some % subset of all allowed positional arguments, but must instead either be % the full set of positional arguments (and possibly some NVPs) or be % specified as NVPs in the first place. % % % Out: % Spec : A cell array, that, when called as spec{1}(reptype,spec{2}{:}), yields a specification of % the argument, for use by arg_define. Technical note: Upon assignment with a value (via % the assigner field), the 'children' field of the specifier struct is populated according % to how the selected (by the mapper) Source parses the value into arguments. The % additional struct field 'arg_selection 'is introduced at this point. % % Examples: % % define a function with an argument that can be turned on or off, and which has sub-arguments % % that are effective if the argument is turned on (default: on); some valid calls are: % % myfunction('somearg','testtest', 'myoption','off') % % myfunction('somearg','testtest', 'myoption',[]) % alternative for: off % % myfunction('somearg','testtest', 'myoption','on') % % myfunction('somearg','testtest', 'myoption',{}) % alternatie for: on % % myfunction('somearg','testtest', 'myoption',{'param1','test','param2',10}) % % myfunction('somearg','testtest', 'myoption',{'param2',10}) % % myfunction('testtest', {'param2',10}) % % myfunction('myoption', {'param2',10}) % function myfunction(varargin) % arg_define(varargin, ... % arg('somearg','test',[],'Some help.'), ... % arg_subtoggle('myoption',},{},{ ... % arg('param1',[],[],'Parameter 1.'), ... % arg('param2',5,[],'Parameter 2.') ... % }, 'Optional processing step. If selected, several sub-argument can be specified.')); % % % define a function with an argument that can be turned on or off, and whose sub-arguments match % % those of some other function (there declared via arg_define) % function myfunction(varargin) % arg_define(varargin, ... % arg_subtoggle('myoption',},{},@someotherfunction, 'Optional processing step. If selected, several sub-argument can be specified.')); % % % as before, but override some of the defaults of someotherfunction % function myfunction(varargin) % arg_define(varargin, ... % arg_subtoggle('myoption',},{'param1',10},@someotherfunction, 'Optional processing step. If selected, several sub-argument can be specified.')); % % % as before, but specify a custom mapper function that determines how myoption is passed, and % % what forms map to 'on' and 'off' % function myfunction(varargin) % arg_define(varargin, ... % arg_subtoggle('myoption',},{},@someotherfunction, 'Optional processing step. If selected, several sub-argument can be specified.'.'mapper',@mymapper)); % % % as before, but specify a custom formatting function that determines the arguments in myoption % % may be passed (keeping the defaults regarding what forms map to 'on' and 'off') % function myfunction(varargin) % arg_define(varargin, ... % arg_subtoggle('myoption',},{},@someotherfunction, 'Optional processing step. If selected, several sub-argument can be specified.'.'fmt',@myparser)); % % See also: % arg, arg_nogui, arg_norep, arg_sub, arg_subswitch, arg_define % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-09-24 % we return a function that an be invoked to yield a specification (its output is cached for % efficiency) packed in a cell array together with the remaining arguments res = {@invoke_argsubtoggle_cached,varargin}; function spec = invoke_argsubtoggle_cached(varargin) spec = hlp_microcache('arg',@invoke_argsubtoggle,varargin{:}); % the function that does the actual work of building the argument specifier function spec = invoke_argsubtoggle(reptype,names,defaults,source,help,varargin) % start with a base specification spec = arg_specifier('head',@arg_subtoggle, 'fmt',[], 'type','logical', 'shape','scalar', 'mapper',@map_argsubtoggle); suppressNames = {}; % override properties if exist('names','var') spec.names = names; end if exist('help','var') spec.help = help; end for k=1:2:length(varargin) if isfield(spec,varargin{k}) spec.(varargin{k}) = varargin{k+1}; elseif strcmpi(varargin{k},'suppress') suppressNames = varargin{k+1}; else error('BCILAB:arg:no_new_fields','It is not allowed to introduce fields into a specifier that are not declared in arg_specifier.'); end end % do checking if ~iscell(spec.names) spec.names = {spec.names}; end if isempty(spec.names) || ~iscellstr(spec.names) error('The argument must have a name or cell array of names.'); end if ~exist('source','var') || isempty(source) error('BCILAB:args:no_options','The Source argument for arg_subtoggle() may not be omitted.'); end %#ok<*NODEF> if nargin(spec.mapper) == 1 spec.mapper = @(x,y,z) spec.mapper(x); end % parse the help if ~isempty(spec.help) try spec.help = parse_help(spec.help,100); catch e disp(['Problem with the help text for argument ' spec.names{1} ': ' e.message]); spec.help = {}; end elseif spec.reportable && spec.displayable disp(['Please specify a description for argument ' spec.names{1} ', or specify it via arg_nogui() instead.']); end % uniformize Source syntax if iscell(source) % args is a cell array instead of a function: we effectively turn this into a regular % arg_define-using function (taking & parsing values) source = @(varargin) arg_define(spec.fmt,varargin,source{:}); else % args is a function: was a custom format specified? if isa(spec.fmt,'function_handle') source = @(varargin) source(spec.fmt(varargin)); elseif ~isempty(spec.fmt) error('The only allowed form in which the Format of a Source that is a function may be overridden is as a pre-parser (given as a function handle)'); end end spec = rmfield(spec,'fmt'); % wrap the default into a cell if necessary (note: this is convenience syntax) if isstruct(defaults) defaults = {defaults}; elseif strcmp(defaults,'off') defaults = []; elseif strcmp(defaults,'on') defaults = {}; elseif ~iscell(defaults) && ~isequal(defaults,[]) error(['It is not allowed to use anything other than a cell array, a struct, [] or ''off'' and ''on'' as defaults of an arg_subtoggle argument (here:' spec.names{1} ')']); end % resolve the default configuration into the boolean flag and value set; this is relevant for % the merging option: in this case, we need to pull up the currect default and merge it with the % passed value [default_sel,default_val] = spec.mapper(defaults); % set up the regular assigner spec.assigner = @(spec,value) assign_argsubtoggle(spec,value,reptype,source,default_sel,default_val,suppressNames); % assign the default if strcmp(reptype,'rich') spec = assign_argsubtoggle(spec,defaults,'build',source,NaN,{},suppressNames); else spec = assign_argsubtoggle(spec,defaults,'lean',source,NaN,{},suppressNames); end function spec = assign_argsubtoggle(spec,value,reptype,source,default_sel,default_val,suppressNames) % precompute things that we might need later persistent arg_sel arg_desel; if isempty(arg_sel) || isempty(arg_sel) arg_sel = arg_nogui('arg_selection',true); arg_sel = arg_sel{1}([],arg_sel{2}{:}); arg_desel = arg_nogui('arg_selection',false); arg_desel = arg_desel{1}([],arg_desel{2}{:}); end % wrap the value into a cell if necessary (note: this is convenience syntax) if isstruct(value) value = {value}; elseif ~iscell(value) && ~isequal(value,[]) && ~isempty(default_val) error(['For an arg_subtoggle argument that has non-empty defaults (here:' spec.names{1} '), it is not allowed to assign anything other than a cell array, a struct, or [] to it.']); end % retrieve the values for the realized switch option... [selected,value] = spec.mapper(value); % build the complementary alternative, if requested if strcmp(reptype,'build') if selected spec.alternatives{1} = arg_desel; else spec.alternatives{2} = [arg_report('rich',source,{}) arg_sel]; end reptype = 'rich'; end % obtain the children if ~selected spec.children = arg_desel; elseif spec.merge && (default_sel==true) spec.children = [arg_report(reptype,source,[default_val value]) arg_sel]; else spec.children = [arg_report(reptype,source,value) arg_sel]; end % toggle the displayable option for children which should be suppressed if ~isempty(suppressNames) % identify which children we want to suppress display hidden = find(cellfun(@any,cellfun(@(x,y) ismember(x,suppressNames),{spec.children.names},'UniformOutput',false))); % set display flag to false for k=hidden(:)' spec.children(k).displayable = false; end % identify which alternatives we want to suppress display for alt_idx = 1:length(spec.alternatives) if isempty(spec.alternatives{alt_idx}) continue; end hidden = find(cellfun(@any,cellfun(@(x,y) ismember(x,suppressNames),{spec.alternatives{alt_idx}.names},'UniformOutput',false))); % set display flag to false for k=hidden(:)' spec.alternatives{alt_idx}(k).displayable = false; end end end spec.alternatives{selected+1} = spec.children; % and set the cell's value spec.value = selected; % this function maps an argument list onto a binary flag (enabled status) plus value set to assign function [selected,args] = map_argsubtoggle(args) if isequal(args,'on') selected = true; args = {}; elseif isequal(args,'off') || isequal(args,[]) selected = false; args = []; elseif length(args) == 1 && isfield(args,'arg_selection') selected = args.arg_selection; elseif length(args) == 1 && iscell(args) && isstruct(args{1}) && isfield(args{1},'arg_selection') selected = args{1}.arg_selection; elseif isequal(args,{'arg_selection',0}) selected = false; args = {}; elseif isequal(args,{'arg_selection',1}) selected = true; args = {}; elseif iscell(args) % find the arg_selection in the cell array pos = find(strcmp('arg_selection',args(1:end-1)),1,'last'); if isempty(pos) selected = true; else [selected,args] = deal(args{pos+1},args([1:pos-1 pos+2:end])); end else selected = true; end
github
lcnbeapp/beapp-master
arg_tovals.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_tovals.m
2,531
utf_8
d6b62007b294e20f330fd415633ef2ad
function res = arg_tovals(spec,direct) % Convert a 'rich' argument report into a 'vals' report. % Vals = arg_tovals(Rich) % % In: % Rich : a 'rich' argument report, as obtained via arg_report('rich',some_function) % % Direct : whether to endow the result with an 'arg_direct' flag set to true, which indicates to % the function taking the Vals struct that the contents of the struct directly correspond % to workspace variables of the function. If enabled, contents of Vals must be changed % with care - for example, removing/renaming fields will likely lead to errors in the % function. (default: true) % % Out: % Vals : a 'vals' argument report, as obtained via arg_report('vals',some_function) this data % structure can be used as a valid argument to some_function. % % Examples: % % report arguments of myfunction % report = arg_report('rich',@myfunction) % % convert the report to a valid argument to the function % values = arg_tovals(report); % % See also: % arg_define % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-10-18 if ~exist('direct','var') direct = false; end % remove unassigned specifiers spec = spec(~strcmp(unassigned,{spec.value})); % evaluate expressions expressions = strcmp('expression',{spec.type}) & cellfun('isclass',{spec.value},'char'); if any(expressions) try [spec(expressions).value] = dealout(evalin('base',format_cellstr({spec(expressions).value}))); catch for e=find(expressions) try spec(e).value = evalin('base',spec(e).value); catch end end end end % and replace by structs res = struct('arg_direct',{direct}); for k=1:length(spec) if isstruct(spec(k).children) % has children: replace by struct val = arg_tovals(spec(k).children,direct); else % no children: take value (and possibly convert to double) val = spec(k).value; if spec(k).to_double && isinteger(val) val = double(val); end end % and assign the value res.(spec(k).names{1}) = val; end res.arg_direct = direct; % like deal(), except that the inputs are given as a cell array instead of a comma-separated list function varargout = dealout(argin) varargout = argin; % format a non-empty cell-string array into a string function x = format_cellstr(x) x = ['{' sprintf('%s, ',x{1:end-1}) x{end} '}'];
github
lcnbeapp/beapp-master
arg_specifier.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_specifier.m
2,714
utf_8
45a0f0bbe159b1d73d533fcbbf4c2576
function spec = arg_specifier(varargin) % Internal: create a base specifier struct for an argument. % Specifier = arg_specifier(Overrides...) % % In: % Overrides... : name-value pairs of fields that should be overridden % % Out: % A specifier that is recognized by arg_define. % % See also: % arg_define % % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD % 2010-09-25 spec = struct(... ... % core properties 'head',{@arg_specifier},...% the expression type that generated this specifier (@arg, @arg_sub, ...) 'names',{{}}, ... % cell array of argument names; first is the "code" name (reported to the function), second (if present) is the human-readable name (reported to the GUI) 'value',{[]}, ... % the assigned value of the argument; can be any data structure 'assigner',{@assign},...% function to be invoked in order to assign a new value the specifier ... % properties for (possibly dependent) child arguments 'children',{{}}, ... % cell array of child arguments (returned to the function in a struct, and made available to the GUI in a subgroup) 'mapper',@(x)x, ... % mapping function: maps a value into the index space of alternatives (possibly via range) 'alternatives',{{}}, ...% cell array of alternative children structures; only used for arg_subtoggle, arg_subswitch 'merge',{true},... % whether the value (a cell array of arguments) should completely replace the default, or be merged with it, such that sub-arguments are only selectively overridden ... % type-related properties 'range',{[]}, ... % the allowed range of the argument (for type checking in GUI and elsewhere); can be [], [lo hi], {'option1','option2','option3',...} 'type',{[]}, ... % the type of the argument: string, only touches the type-checking system & GUI 'shape',{[]}, ... % the shape of the argument: empty. scalar, row, column, matrix ... % user interface properties 'help',{''}, ... % the help text / description for the argument 'cat',{''}, ... % the human-readable category of the argument ... % misc attributes 'to_double',{true}, ... % convert numeric values to double before returning them to the function 'reportable',{true},... % whether the argument can be reported to outer function (given that it is assigned), or not (true/false) 'displayable',{true}... % whether the argument may be displayed by GUIs (true/false) ); % selectively override fields for k=1:2:length(varargin) spec.(varargin{k}) = varargin{k+1}; end function spec = assign(spec,value) spec.value = value;
github
lcnbeapp/beapp-master
is_needing_search.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/queries/is_needing_search.m
808
utf_8
b4e0ea02b09d80b71d7e2970b648578f
function res = is_needing_search(argform,args) % test whether some argument pack requires a search or not (according to the specified argument format) if strcmp(argform,'direct') % a search is specified by multielement arguments res = prod(max(1,cellfun(@length,args))) > 1; elseif strcmp(argform,'clauses') % a search is specified by (possibly nested) search clauses res = contains_search(args); else error('unsupported argument form.'); end % test whether the given data structure contains a search clause function res = contains_search(x) if has_canonical_representation(x) && isequal(x.head,@search) res = true; elseif iscell(x) res = any(cellfun(@contains_search,x)); elseif isstruct(x) && numel(x) == 1 res = contains_search(struct2cell(x)); else res = false; end
github
lcnbeapp/beapp-master
is_raw_dataset.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/queries/is_raw_dataset.m
184
utf_8
6bcaef74ea534a299898aa10b68af85a
% determine whether some object is a raw EEGLAB data set with no BCILAB constituents function res = is_raw_dataset(x) res = all(isfield(x,{'data','srate'})) && ~isfield(x,'tracking');
github
lcnbeapp/beapp-master
shadowplot.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/tmullen-cleanline-696a7181b7d0/external/shadowplot/shadowplot.m
7,604
utf_8
ae6097ee1343157565bb24e6a5f27a32
function varargout = shadowplot(varargin) % SHADOWPLOT Add a shadow to an existing surface or patch plot % % For some surface plots, it can be helpful to visualize the shadow (2D % projection) of the surface. This can give a quick perspective on the % data's variance. % % SHADOWPLOT PLANE Adds a shadow plot on the PLANE boundary % PLANE can be: % x, y, or z: Plots on back/top wall of x, y or z % 1 .. 6 : Plots on Nth wall, numbered as in AXIS: % [xmin xmax ymin ymax zmin zmax] % % SHADOWPLOT(HAX,PLANE) Adds a shadow plot on the Nth wall on axes HAX % HS = SHADOWPLOT(...) Returns a handle to the shadow (a patch) % % Examples: % figure % surf(peaks) % shading interp % shadowplot x % Back X Wall % shadowplot y % Back Y Wall % % figure % surf(peaks);hold on % surf(peaks+10) % shading interp % hs = shadowplot(1); % set(hs,'FaceColor','r'); % Red shadow % alpha(hs,.1) % More transparent % set(hs(1),'XData',get(hs(1),'XData')*.9) % Move farther away % % UPDATE (9/07): Now includes limited support for data encapsulated in % HGTRANSFORMS, thanks to Patrick Barney ([email protected]). % Scott Hirsch % [email protected] % Copyright 2004-2007 The MathWorks, Inc %% We define three dimensions. 1=x, 2=y, 3=z % dimplane - dimension that's constant in the projection plane (user-specified) % dimvar - dimension in which data varies (typically 3) % dimother - the other dimension (couldn't come up with a good name!). %% Parse input arguments. if nargin==1 hAx = gca; plane = lower(varargin{1}); elseif nargin==2 hAx = varargin{1}; plane = lower(varargin{2}); end; %% Convert plane to numeric dimension % plane can be specified as a string (x,y,z) or as a number (1..6) if ~isstr(plane) dimplane = ceil(plane/2); axind = plane; % Index into AXIS to get boundary plane else % string switch plane case 'x' dimplane = 1; axind = 2; % Index into AXIS to get boundary plane case 'y' dimplane = 2; axind = 4; case 'z' dimplane = 3; axind = 6; otherwise error('Plane must be one of: ''x'', ''y'', or ''z'' or a number between 1 and 6'); end; end; %% Get coordinates for placing surface from axis limits ax = axis; % ============ force axis into 3d mode ============= if length(axis==4) % axis problem. get the current view, rotate it, then % redo the axis and return to the original view. [az,el] = view; view(45,45) ax = axis; view(az,el) end planecoord = ax(axind); % Plane Coordinate - back wall %% Turn hold on hold_current = ishold(hAx); if hold_current == 0 hold_current = 'off'; else hold_current = 'on'; end; hold(hAx,'on') %% Get handles to all surfaces kids = findobj(hAx,'Type','surface'); h = []; % Also get handles to all patch objects kidsp = findobj(hAx,'Type','patch'); hp = []; for ii=1:length(kids) % Do separately for each surface hSurf = kids(ii); % Current surface % We do everything with the X, Y, and ZData of the surface surfdata = get(hSurf,{'XData','YData','ZData'}); % XData and YData might be vectors or matrices. Force them to be % matrices (a la griddata) [Ny,Nx] = size(surfdata{3}); if isvector(surfdata{1}) surfdata{1} = repmat(surfdata{1},Ny,1); end; if isvector(surfdata{2}) surfdata{2} = repmat(surfdata{2},1,Nx); end; % Figure out which two axes are independent (i.e., monotonic) grids = [ismeshgrid(surfdata{1}) ismeshgrid(surfdata{2}) ismeshgrid(surfdata{3})]; if sum(grids)<2, error('Surface must have at least 2 monotonically increasing dimensions');end % The remaining dimension is the one along which data varies dimvar = find(~grids); % Dimension where data varies if isempty(dimvar) % All 3 dimensions are monotonic. not sure what to do dimvar = max(setdiff(1:3,dimplane));% pick largest value that isn't dimplane end; if dimvar==dimplane error('Can not project data in the dimension that varies. Try another plane') end; %dimdiff: dimension for taking difference (figure out through trial and error) % dimplane=1, dimvar=3: 2 % dimplane=1, dimvar=2: 2 % dimplane=2, dimvar=1: 2 % dimplane=2, dimvar=3: 1 % dimplane=3, dimvar=2: 1 % dimplane=3, dimvar=1: 1 dimdiff = 2; % Most cases if (dimplane==2&&dimvar==3) | (dimplane==3) dimdiff = 1; end; % Compute projection dmin = min(surfdata{dimvar},[],dimdiff); % Min of data projected onto this plane dmax = max(surfdata{dimvar},[],dimdiff); % Max of data projected onto this plane dmin = dmin(:); % Force into row vector dmax = dmax(:); nval = length(dmin)*2 + 1; % Total number of values we'll use for shadow % Compute shadow coordinates % Pull out independent variable dimother = setxor([dimvar dimplane],1:3); % Remaining dimension d1 = surfdata{dimother}(:,1); % Not sure if should take row or col. find the dimension that varies d2 = surfdata{dimother}(1,:); if d1(1) ~= d1(end) dind = d1; else dind = d2'; end; shadow{dimplane} = repmat(planecoord,nval,1); % In the plane shadow{dimother} = [dind;flipud(dind);dind(1)]; % Independent variable shadow{dimvar} = [dmin;flipud(dmax);dmin(1)]; % the varying data h(ii) = patch(shadow{1},shadow{2},shadow{3},[.3 .3 .3]); alpha(h(ii),.3) set(h(ii),'LineStyle','none') % set a tag, so that a shadow will not try to cast a shadow set(h(ii),'Tag','Shadow') end; %% Shadow any patches, unless they are already shadows. hp = []; for ii=1:length(kidsp) % Do separately for each patch object hPat = kidsp(ii); % Current patch % Is this patch already tagged as a Shadow? if ~strcmpi(get(hPat,'Tag'),'Shadow') % We do everything with the X, Y, and ZData of the surface patdata = get(hPat,{'XData','YData','ZData'}); switch get(get(hPat,'par'),'Type') case 'hgtransform' M=get(get(hPat,'par'),'Matrix'); try switch get(get(get(hPat,'par'),'par'),'type') case 'hgtransform' M2=get(get(get(hPat,'par'),'par'),'Matrix'); M=M2*M; end end M=M(1:3,1:3); xyz=[patdata{1}(:),patdata{2}(:),patdata{3}(:)]*M'; [n,m]=size(patdata{1}); patdata{1}=reshape(xyz(:,1),n,m); patdata{2}=reshape(xyz(:,2),n,m); patdata{3}=reshape(xyz(:,3),n,m); otherwise end % Just replace the x, y, or z coordinate as indicated by dimplane patdata{dimplane} = repmat(planecoord,size(patdata{dimplane})); % then its just a call to patch hp(ii) = patch(patdata{1},patdata{2},patdata{3},[.3 .3 .3]); alpha(hp(ii),.3) set(hp(ii),'LineStyle','none') % set a tag, so that a shadow will not try to cast a shadow set(hp(ii),'Tag','Shadow') end end; h=[h,hp]; hold(hAx,hold_current) % Return to original state if nargout varargout{1} = h; end; function isgrid = ismeshgrid(d) % Check if d looks like it came from griddata dd = diff(d); ddt = diff(d'); if all(~dd(:)) | all(~ddt(:)) isgrid = 1; else isgrid = 0; end; % if ~any(d(:,1) - d(:,end)) | ~any(d(1,:) - d(end,:)) % isgrid = 1; % else % isgrid = 0; % end;
github
lcnbeapp/beapp-master
readbvconf.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/bvaio1.57/readbvconf.m
2,844
utf_8
4eb0324e1e56dd1240dfaf9a3437c489
% readbvconf() - read Brain Vision Data Exchange format configuration % file % % Usage: % >> CONF = readbvconf(pathname, filename); % % Inputs: % pathname - path to file % filename - filename % % Outputs: % CONF - structure configuration % % Author: Andreas Widmann, University of Leipzig, 2007 %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2007 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % $Id: readbvconf.m 44 2009-11-12 02:00:56Z arnodelorme $ function CONF = readbvconf(pathname, filename) if nargin < 2 error('Not enough input arguments'); end % Open and read file [IN, message] = fopen(fullfile(pathname, filename)); if IN == -1 [IN, message] = fopen(fullfile(pathname, lower(filename))); if IN == -1 error(message) end; end raw={}; while ~feof(IN) raw = [raw; {fgetl(IN)}]; end fclose(IN); % Remove comments and empty lines raw(strmatch(';', raw)) = []; raw(cellfun('isempty', raw) == true) = []; % Find sections sectionArray = [strmatch('[', raw)' length(raw) + 1]; for iSection = 1:length(sectionArray) - 1 % Convert section name fieldName = lower(char(strread(raw{sectionArray(iSection)}, '[%s', 'delimiter', ']'))); fieldName(isspace(fieldName) == true) = []; % Fill structure with parameter value pairs switch fieldName case {'commoninfos' 'binaryinfos'} for line = sectionArray(iSection) + 1:sectionArray(iSection + 1) - 1 splitArray = strfind(raw{line}, '='); CONF.(fieldName).(lower(raw{line}(1:splitArray(1) - 1))) = raw{line}(splitArray(1) + 1:end); end case {'channelinfos' 'coordinates' 'markerinfos'} for line = sectionArray(iSection) + 1:sectionArray(iSection + 1) - 1 splitArray = strfind(raw{line}, '='); CONF.(fieldName)(str2double(raw{line}(3:splitArray(1) - 1))) = {raw{line}(splitArray(1) + 1:end)}; end case 'comment' CONF.(fieldName) = raw(sectionArray(iSection) + 1:sectionArray(iSection + 1) - 1); end end
github
lcnbeapp/beapp-master
pop_loadbv.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/bvaio1.57/pop_loadbv.m
12,215
utf_8
87d1ce71415fbd8735ab37c7e88fa227
% pop_loadbv() - load Brain Vision Data Exchange format dataset and % return EEGLAB EEG structure % % Usage: % >> [EEG, com] = pop_loadbv; % pop-up window mode % >> [EEG, com] = pop_loadbv(path, hdrfile); % >> [EEG, com] = pop_loadbv(path, hdrfile, srange); % >> [EEG, com] = pop_loadbv(path, hdrfile, [], chans); % >> [EEG, com] = pop_loadbv(path, hdrfile, srange, chans); % % Optional inputs: % path - path to files % hdrfile - name of Brain Vision vhdr-file (incl. extension) % srange - scalar first sample to read (up to end of file) or % vector first and last sample to read (e.g., [7 42]; % default: all) % chans - vector channels channels to read (e.g., [1:2 4]; % default: all) % % Outputs: % EEG - EEGLAB EEG structure % com - history string % % Author: Andreas Widmann & Arnaud Delorme, 2004- %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % $Id: pop_loadbv.m 42 2009-11-12 01:45:54Z arnodelorme $ function [EEG, com] = pop_loadbv(path, hdrfile, srange, chans) com = ''; EEG = []; if nargin < 2 [hdrfile path] = uigetfile2('*.vhdr', 'Select Brain Vision vhdr-file - pop_loadbv()'); if hdrfile(1) == 0, return; end drawnow; uigeom = {[1 0.5] [1 0.5]}; uilist = {{ 'style' 'text' 'string' 'Interval (samples; e.g., [7 42]; default: all):'} ... { 'style' 'edit' 'string' ''} ... { 'style' 'text' 'string' 'Channels (e.g., [1:2 4]; default: all):'} ... { 'style' 'edit' 'string' ''}}; result = inputgui(uigeom, uilist, 'pophelp(''pop_loadbv'')', 'Load a Brain Vision Data Exchange format dataset'); if isempty(result), return, end if ~isempty(result{1}), srange = str2num(result{1}); end if ~isempty(result{2}), chans = str2num(result{2}); end end % Header file disp('pop_loadbv(): reading header file'); hdr = readbvconf(path, hdrfile); % Common Infos try EEG = eeg_emptyset; catch end EEG.comments = ['Original file: ' hdr.commoninfos.datafile]; hdr.commoninfos.numberofchannels = str2double(hdr.commoninfos.numberofchannels); EEG.srate = 1000000 / str2double(hdr.commoninfos.samplinginterval); % Binary Infos if strcmpi(hdr.commoninfos.dataformat, 'binary') switch lower(hdr.binaryinfos.binaryformat) case 'int_16', binformat = 'int16'; bps = 2; case 'uint_16', binformat = 'uint16'; bps = 2; case 'ieee_float_32', binformat = 'float32'; bps = 4; otherwise, error('Unsupported binary format'); end end % Channel Infos if ~exist('chans', 'var') chans = 1:hdr.commoninfos.numberofchannels; EEG.nbchan = hdr.commoninfos.numberofchannels; elseif isempty(chans) chans = 1:hdr.commoninfos.numberofchannels; EEG.nbchan = hdr.commoninfos.numberofchannels; else EEG.nbchan = length(chans); end if any(chans < 1) || any(chans > hdr.commoninfos.numberofchannels) error('chans out of available channel range'); end if isfield(hdr, 'channelinfos') for chan = 1:length(chans) [EEG.chanlocs(chan).labels, chanlocs(chan).ref, chanlocs(chan).scale, chanlocs(chan).unit] = strread(hdr.channelinfos{chans(chan)}, '%s%s%s%s', 1, 'delimiter', ','); EEG.chanlocs(chan).labels = char(EEG.chanlocs(chan).labels); chanlocs(chan).scale = str2double(char(chanlocs(chan).scale)); % chanlocs(chan).unit = native2unicode(double(char(chanlocs(chan).scale)), 'UTF-8'); % EEG.chanlocs(chan).datachan = chans(chan); end if isempty([chanlocs.scale]) chanlocs = rmfield(chanlocs, 'scale'); end end; % [EEG.chanlocs.type] = deal([]); % Coordinates if isfield(hdr, 'coordinates') hdr.coordinates(end+1:length(chans)) = { [] }; for chan = 1:length(chans) if ~isempty(hdr.coordinates{chans(chan)}) [EEG.chanlocs(chan).sph_radius, theta, phi] = strread(hdr.coordinates{chans(chan)}, '%f%f%f', 'delimiter', ','); if EEG.chanlocs(chan).sph_radius == 0 && theta == 0 && phi == 0 EEG.chanlocs(chan).sph_radius = []; EEG.chanlocs(chan).sph_theta = []; EEG.chanlocs(chan).sph_phi = []; else EEG.chanlocs(chan).sph_theta = phi - 90 * sign(theta); EEG.chanlocs(chan).sph_phi = -abs(theta) + 90; end end; end try, [EEG.chanlocs, EEG.chaninfo] = pop_chanedit(EEG.chanlocs, 'convert', 'sph2topo'); [EEG.chanlocs, EEG.chaninfo] = pop_chanedit(EEG.chanlocs, 'convert', 'sph2cart'); catch, end end % Open data file and find the number of data points % ------------------------------------------------- disp('pop_loadbv(): reading EEG data'); [IN, message] = fopen(fullfile(path, hdr.commoninfos.datafile)); if IN == -1 [IN, message] = fopen(fullfile(path, lower(hdr.commoninfos.datafile))); if IN == -1 error(message) end; end if isfield(hdr.commoninfos, 'datapoints') hdr.commoninfos.datapoints = str2double(hdr.commoninfos.datapoints); elseif strcmpi(hdr.commoninfos.dataformat, 'binary') fseek(IN, 0, 'eof'); hdr.commoninfos.datapoints = ftell(IN) / (hdr.commoninfos.numberofchannels * bps); fseek(IN, 0, 'bof'); else hdr.commoninfos.datapoints = NaN; end if ~strcmpi(hdr.commoninfos.dataformat, 'binary') % ASCII tmppoint = hdr.commoninfos.datapoints; tmpchan = fscanf(IN, '%s', 1); tmpdata = fscanf(IN, '%f', inf); hdr.commoninfos.datapoints = length(tmpdata); chanlabels = 1; if str2double(tmpchan) == 0, hdr.commoninfos.datapoints = hdr.commoninfos.datapoints+1; chanlabels = 0; end; if ~isnan(tmppoint) if tmppoint ~= hdr.commoninfos.datapoints error('Error in computing number of data points; try exporting in a different format'); end; end; end; % Sample range if ~exist('srange', 'var') || isempty(srange) srange = [ 1 hdr.commoninfos.datapoints]; EEG.pnts = hdr.commoninfos.datapoints; elseif length(srange) == 1 EEG.pnts = hdr.commoninfos.datapoints - srange(1) + 1; else EEG.pnts = srange(2) - srange(1) + 1; end if any(srange < 1) || any(srange > hdr.commoninfos.datapoints) error('srange out of available data range'); end % Read data if strcmpi(hdr.commoninfos.dataformat, 'binary') switch lower(hdr.commoninfos.dataorientation) case 'multiplexed' if EEG.nbchan == hdr.commoninfos.numberofchannels % Read all channels fseek(IN, (srange(1) - 1) * EEG.nbchan * bps, 'bof'); EEG.data = fread(IN, [EEG.nbchan, EEG.pnts], [binformat '=>float32']); else % Read channel subset EEG.data = repmat(single(0), [EEG.nbchan, EEG.pnts]); % Preallocate memory for chan = 1:length(chans) fseek(IN, (srange(1) - 1) * hdr.commoninfos.numberofchannels * bps + (chans(chan) - 1) * bps, 'bof'); EEG.data(chan, :) = fread(IN, [1, EEG.pnts], [binformat '=>float32'], (hdr.commoninfos.numberofchannels - 1) * bps); end end case 'vectorized' if isequal(EEG.pnts, hdr.commoninfos.datapoints) && EEG.nbchan == hdr.commoninfos.numberofchannels % Read entire file EEG.data = fread(IN, [EEG.pnts, EEG.nbchan], [binformat '=>float32']).'; else % Read fraction of file EEG.data = repmat(single(0), [EEG.nbchan, EEG.pnts]); % Preallocate memory for chan = 1:length(chans) fseek(IN, ((chans(chan) - 1) * hdr.commoninfos.datapoints + srange(1) - 1) * bps, 'bof'); EEG.data(chan, :) = fread(IN, [1, EEG.pnts], [binformat '=>float32']); end end otherwise error('Unsupported data orientation') end else % ASCII data disp('If this function does not work, export your data in binary format'); EEG.data = repmat(single(0), [EEG.nbchan, EEG.pnts]); if strcmpi(lower(hdr.commoninfos.dataorientation), 'vectorized') count = 1; fseek(IN, 0, 'bof'); len = inf; for chan = 1:hdr.commoninfos.numberofchannels if chanlabels, tmpchan = fscanf(IN, '%s', 1); end; tmpdata = fscanf(IN, '%f', len); len = length(tmpdata); if ismember(chan, chans) EEG.data(count, :) = tmpdata(srange(1):srange(2))'; count = count + 1; end; end; elseif strcmpi(lower(hdr.commoninfos.dataorientation), 'multiplexed') fclose(IN); error('ASCII multiplexed reading not implemeted yet; export as a different format'); end; end; fclose(IN); EEG.trials = 1; EEG.xmin = 0; EEG.xmax = (EEG.pnts - 1) / EEG.srate; % Convert to EEG.data to double for MATLAB < R14 if str2double(version('-release')) < 14 EEG.data = double(EEG.data); end % Scale data if exist('chanlocs', 'var') && isfield(chanlocs, 'scale') disp('pop_loadbv(): scaling EEG data'); for chan = 1:EEG.nbchan if ~isnan(chanlocs(chan).scale) EEG.data(chan, :) = EEG.data(chan, :) * chanlocs(chan).scale; end; end end % Marker file if isfield(hdr.commoninfos, 'markerfile') disp('pop_loadbv(): reading marker file'); MRK = readbvconf(path, hdr.commoninfos.markerfile); if hdr.commoninfos.datafile ~= MRK.commoninfos.datafile disp('pop_loadbv() warning: data files in header and marker files inconsistent.'); end % Marker infos if isfield(MRK, 'markerinfos') EEG.event = parsebvmrk(MRK); % Correct event latencies by first sample offset latency = num2cell([EEG.event(:).latency] - srange(1) + 1); [EEG.event(:).latency] = deal(latency{:}); % Remove unreferenced events EEG.event = EEG.event([EEG.event.latency] >= 1 & [EEG.event.latency] <= EEG.pnts); % Copy event structure to urevent structure EEG.urevent = rmfield(EEG.event, 'urevent'); % find if boundaries at homogenous intervals % ------------------------------------------ boundaries = strmatch('boundary', {EEG.event.type}); boundlats = unique([EEG.event(boundaries).latency]); if (isfield(hdr.commoninfos, 'segmentationtype') && (strcmpi(hdr.commoninfos.segmentationtype, 'markerbased') || strcmpi(hdr.commoninfos.segmentationtype, 'fixtime'))) && length(boundaries) > 1 && length(unique(diff([boundlats EEG.pnts + 1]))) == 1 EEG.trials = length(boundlats); EEG.pnts = EEG.pnts / EEG.trials; EEG.event(boundaries) = []; % adding epoch field % ------------------ for index = 1:length(EEG.event) EEG.event(index).epoch = ceil(EEG.event(index).latency / EEG.pnts); end % finding minimum time % -------------------- tles = strmatch('time 0', lower({EEG.event.code}))'; if ~isempty(tles) [EEG.event(tles).type] = deal('TLE'); EEG.xmin = -(EEG.event(tles(1)).latency - 1) / EEG.srate; end end end end EEG.ref = 'common'; try EEG = eeg_checkset(EEG); catch end if nargout == 2 com = sprintf('EEG = pop_loadbv(''%s'', ''%s'', %s, %s);', path, hdrfile, mat2str(srange), mat2str(chans)); end
github
lcnbeapp/beapp-master
eegplugin_bva_io.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/bvaio1.57/eegplugin_bva_io.m
2,999
utf_8
e0ed0e164c42929edc9d2ebaac2fa2b0
% eegplugin_bva_io() - EEGLAB plugin for importing Brainvision % .vhdr data files. % % Usage: % >> eegplugin_bva_io(fig, trystrs, catchstrs); % % Inputs: % fig - [integer] EEGLAB figure % trystrs - [struct] "try" strings for menu callbacks. % catchstrs - [struct] "catch" strings for menu callbacks. % % Author: Andreas Widmann for binary import, 2004 % Arnaud Delorme for Matlab import and EEGLAB interface % % See also: pop_loadbv() %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 Andreas Widmann & 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 % $Id: eegplugin_bva_io.m 48 2009-12-22 12:23:09Z andreaswidmann $ function vers = eegplugin_bva_io(fig, trystrs, catchstrs) vers = 'bva_io1.57'; if nargin < 3 error('eegplugin_bva_io requires 3 arguments'); end; % add folder to path % ------------------ if ~exist('eegplugin_bva_io') p = which('eegplugin_bva_io.m'); p = p(1:findstr(p,'eegplugin_bva_io.m')-1); addpath( p ); end; % find import data menu % --------------------- menui = findobj(fig, 'tag', 'import data'); menuo = findobj(fig, 'tag', 'export'); % menu callbacks % -------------- icadefs; versiontype = 1; if exist('EEGLAB_VERSION') if EEGLAB_VERSION(1) == '4' versiontype = 0; end; end; if versiontype == 0 comcnt1 = [ trystrs.no_check '[EEGTMP LASTCOM] = pop_loadbv;' catchstrs.new_non_empty ]; comcnt2 = [ trystrs.no_check '[EEGTMP LASTCOM] = pop_loadbva;' catchstrs.new_non_empty ]; else comcnt1 = [ trystrs.no_check '[EEG LASTCOM] = pop_loadbv;' catchstrs.new_non_empty ]; comcnt2 = [ trystrs.no_check '[EEG LASTCOM] = pop_loadbva;' catchstrs.new_non_empty ]; end; comcnt3 = [ trystrs.no_check 'LASTCOM = pop_writebva(EEG);' catchstrs.add_to_hist ]; % create menus % ------------ uimenu( menui, 'label', 'From Brain Vis. Rec. .vhdr file', 'callback', comcnt1, 'separator', 'on' ); uimenu( menui, 'label', 'From Brain Vis. Anal. Matlab file', 'callback', comcnt2 ); uimenu( menuo, 'label', 'Write Brain Vis. exchange format file', 'callback', comcnt3, 'separator', 'on' );
github
lcnbeapp/beapp-master
parsebvmrk.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/bvaio1.57/parsebvmrk.m
1,754
utf_8
5913b2393594c4821248cf06b3001af7
% parsebvmrk() - convert Brain Vision Data Exchange format marker % configuration structure to EEGLAB event structure % % Usage: % >> EVENT = parsebvmrk(MRK); % % Inputs: % MRK - marker configuration structure % % Outputs: % EVENT - EEGLAB event structure % % Author: Andreas Widmann, University of Leipzig, 2007 %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2007 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % $Id: parsebvmrk.m 37 2007-06-26 12:56:17Z andreaswidmann $ function EVENT = parsebvmrk(MRK) for idx = 1:length(MRK.markerinfos) [mrkType mrkDesc EVENT(idx).latency EVENT(idx).duration EVENT(idx).channel EVENT(idx).bvtime] = ... strread(MRK.markerinfos{idx}, '%s%s%f%d%d%d', 'delimiter', ','); if strcmpi(mrkType, 'New Segment') || strcmpi(mrkType, 'DC Correction') EVENT(idx).type = 'boundary'; else EVENT(idx).type = char(mrkDesc); end EVENT(idx).code = char(mrkType); EVENT(idx).urevent = idx; end
github
lcnbeapp/beapp-master
pop_writebva.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/bvaio1.57/pop_writebva.m
7,792
utf_8
594e34cc5c304928f68fe095cab80d4a
% pop_writebva() - export EEG dataset % % Usage: % >> EEG = pop_writebva(EEG); % a window pops up % >> EEG = pop_writebva(EEG, filename); % % Inputs: % EEG - eeglab dataset % filename - file name % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2005- %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2005, 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 % $Log$ % Revision 1.6 2005/12/01 19:39:53 arnodelorme % double labeling % % Revision 1.5 2005/12/01 19:20:13 arnodelorme % Nothing % % Revision 1.4 2005/12/01 19:15:33 arnodelorme % Nothing % % Revision 1.3 2005/12/01 18:49:31 arnodelorme % Time 0 and stimulus % % Revision 1.2 2005/11/22 18:59:57 arnodelorme % Updating pop_loadbv & pop_writebva % % Revision 1.1.1.1 2005/11/03 22:57:36 arnodelorme % initial import into CVS % % Revision 1.5 2005/09/27 22:20:57 arno % fix event labels and colors (and channel coordinate) % % Revision 1.4 2005/08/04 20:23:24 arno % segmentationtype & marker file error for continous data % % Revision 1.3 2005/07/22 18:17:46 arno % same % % Revision 1.2 2005/07/22 18:16:11 arno % convert type to string % % Revision 1.1 2005/07/22 18:06:55 arno % Initial revision % function com = pop_writebva(EEG, filename); com = ''; if nargin < 1 help pop_writebva; return; end; if nargin < 2 [filename, filepath] = uiputfile('*', 'Output file'); if length( filepath ) == 0 return; end; filename = [ filepath filename ]; end; % remove extension if any % ----------------------- posdot = find(filename == '.'); if ~isempty(posdot), filename = filename(1:posdot(end)-1); end; % open output file % ---------------- fid1 = fopen( [ filename '.vhdr' ], 'w' ); fid2 = fopen( [ filename '.vmrk' ], 'w' ); fid3 = fopen( [ filename '.dat' ], 'wb', 'ieee-le'); [ tmppath basename ] = fileparts( filename ); % write data % ---------- for index = 1:EEG.nbchan fwrite(fid3, EEG.data(index,:), 'float' ); end; % write header % ------------ fprintf(fid1, 'Brain Vision Data Exchange Header File Version 1.0\n'); fprintf(fid1, '; Data created from the EEGLAB software\n'); fprintf(fid1, '\n'); fprintf(fid1, '[Common Infos]\n'); fprintf(fid1, 'DataFile=%s\n', [ basename '.dat' ]); if ~isempty(EEG.event) fprintf(fid1, 'MarkerFile=%s\n', [ basename '.vmrk' ]); end; fprintf(fid1, 'DataFormat=BINARY\n'); fprintf(fid1, '; Data orientation: VECTORIZED=ch1,pt1, ch1,pt2..., MULTIPLEXED=ch1,pt1, ch2,pt1 ...\n'); fprintf(fid1, 'DataOrientation=VECTORIZED\n'); fprintf(fid1, 'DataType=TIMEDOMAIN\n'); fprintf(fid1, 'NumberOfChannels=%d\n', EEG.nbchan); fprintf(fid1, 'DataPoints=%d\n', EEG.pnts*EEG.trials); fprintf(fid1, '; Sampling interval in microseconds if time domain (convert to Hertz:\n'); fprintf(fid1, '; 1000000 / SamplingInterval) or in Hertz if frequency domain:\n'); fprintf(fid1, 'SamplingInterval=%d\n', 1000000/EEG.srate); if EEG.trials > 1 fprintf(fid1, 'SegmentationType=MARKERBASED\n'); end; fprintf(fid1, '\n'); fprintf(fid1, '[Binary Infos]\n'); fprintf(fid1, 'BinaryFormat=IEEE_FLOAT_32\n'); fprintf(fid1, '\n'); if ~isempty(EEG.chanlocs) fprintf(fid1, '[Channel Infos]\n'); fprintf(fid1, '; Each entry: Ch<Channel number>=<Name>,<Reference channel name>,\n'); fprintf(fid1, '; <Resolution in microvolts>,<Future extensions..\n'); fprintf(fid1, '; Fields are delimited by commas, some fields might be omited (empty).\n'); fprintf(fid1, '; Commas in channel names are coded as "\1".\n'); for index = 1:EEG.nbchan fprintf(fid1, 'Ch%d=%s,, \n', index, EEG.chanlocs(index).labels); end; fprintf(fid1, '\n'); disp('Warning: channel location were not exported to BVA (it will use default'); disp(' 10-20 BESA locations based on channel names)'); %if isfield(EEG.chanlocs, 'sph_radius') % fprintf(fid1, '[Coordinates]\n'); % fprintf(fid1, '; Each entry: Ch<Channel number>=<Radius>,<Theta>,<Phi>\n'); % loc = convertlocs(EEG.chanlocs, 'sph2sphbesa'); % for index = 1:EEG.nbchan % fprintf(fid1, 'Ch%d=%d,%d,%d\n', index, round(loc(index).sph_theta_besa), ... % round(loc(index).sph_phi_besa), 0); % end; %end; end; % export event information % ------------------------ if ~isempty(EEG.event) fprintf(fid2, 'Brain Vision Data Exchange Marker File, Version 1.0\n'); fprintf(fid2, '; Data created from the EEGLAB software\n'); fprintf(fid2, '; The channel numbers are related to the channels in the exported file.\n'); fprintf(fid2, '\n'); fprintf(fid2, '[Common Infos]\n'); fprintf(fid2, 'DataFile=%s\n', [ basename '.dat' ]); fprintf(fid2, '\n'); fprintf(fid2, '[Marker Infos]\n'); fprintf(fid2, '; Each entry: Mk<Marker number>=<Type>,<Description>,<Position in data points>,\n'); fprintf(fid2, '; <Size in data points>, <Channel number (0 = marker is related to all channels)>,\n'); fprintf(fid2, '; <Date (YYYYMMDDhhmmssuuuuuu)>\n'); fprintf(fid2, '; Fields are delimited by commas, some fields might be omited (empty).\n'); fprintf(fid2, '; Commas in type or description text are coded as "\1".\n'); % rename type and comments % ------------------------ for index = 1:length(EEG.event) EEG.event(index).comment = EEG.event(index).type; EEG.event(index).type = 'Stimulus'; end; % make event cell array % --------------------- for index = 1:EEG.trials EEG.event(end ).latency = (index-1)*EEG.pnts+1; EEG.event(end+1).type = 'New Segment'; end; [tmp latorder ] = sort( [ EEG.event.latency ] ); EEG.event = EEG.event(latorder); % rename latency events % --------------------- time0ind = []; for index = 1:length(EEG.event) if mod( EEG.event(index).latency, EEG.pnts) == -EEG.xmin*EEG.srate+1 time0ind = [ time0ind index ]; end; end; for index = length(time0ind):-1:1 EEG.event(time0ind(index)+1:end+1) = EEG.event(time0ind(index):end); EEG.event(time0ind(index)).type = 'Time 0'; EEG.event(time0ind(index)).comment = ''; end; % write events % ------------ e = EEG.event; for index = 1:length(e) % duration field % -------------- if isfield(e, 'duration') if ~isempty(e(index).duration) tmpdur = e(index).duration; else tmpdur = 0; end; else tmpdur = 0; end; % comment field % ------------- if isfield(e, 'comment') if ~isempty(e(index).comment) tmpcom = e(index).comment; else tmpcom = ''; end; else tmpcom = num2str(e(index).type); end; fprintf(fid2, 'Mk1=%s,%s,%d,%d,0,0\n', num2str(e(index).type), num2str(tmpcom), e(index).latency, tmpdur); end; end fclose(fid1); fclose(fid2); fclose(fid3); com = sprintf('pop_writebva(%s,''%s'');', inputname(1), filename); return;
github
lcnbeapp/beapp-master
pop_loadbva.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/bvaio1.57/pop_loadbva.m
6,637
utf_8
699ce4104ad5d376f6c610f5d5f26252
% pop_loadbva() - import a Matlab file from brain vision analyser % software. % % Usage: % >> OUTEEG = pop_loadbva( filename ); % % Inputs: % filename - file name % % Outputs: % OUTEEG - EEGLAB data structure % % Author: Arnaud Delorme, SCCN/INC/UCSD, Dec 2003 % % See also: eeglab() %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % $Log$ % Revision 1.1 2005/11/03 22:57:36 arnodelorme % Initial revision % % Revision 1.11 2005/10/27 05:27:07 arno % filename % % Revision 1.10 2005/10/26 02:00:41 arno % filename % % Revision 1.9 2005/03/21 22:44:47 arno % making ur events % % Revision 1.8 2004/03/11 17:41:30 arno % remove dbug msg % % Revision 1.7 2004/03/11 17:41:10 arno % dbug msg % % Revision 1.6 2004/03/11 17:39:38 arno % debug channel name % % Revision 1.5 2004/01/22 16:32:59 arno % debuging channel names % % Revision 1.4 2004/01/22 08:31:01 arno % suppressing fields while loading data % % Revision 1.3 2003/12/17 00:44:23 arno % creating empty channels % % Revision 1.2 2003/12/17 00:17:06 arno % remove besa fields % % Revision 1.1 2003/12/16 23:29:13 arno % Initial revision % function [EEG, com] = pop_loadbva(filename) EEG = []; com = ''; if nargin < 1 [tmpfilename, filepath] = uigetfile('*.mat;*.MAT', 'Choose a Matlab file from Brain Vision Analyser -- pop_loadbva'); if tmpfilename == 0 return; end; filename = [ filepath tmpfilename ]; end; disp('Importing data'); EEG = eeg_emptyset; bva = load(filename, '-mat'); allfields = fieldnames(bva); chanstruct = bva.Channels; channames = lower({ chanstruct.Name }); for index = 1:length(allfields) switch lower(allfields{index}) case { 't' 'markercount' 'markers' 'samplerate' 'segmentcount' 'channelcount' 'channels' }, otherwise count1 = strmatch(lower(allfields{index}), channames, 'exact'); count2 = strmatch(lower(allfields{index}(2:end)), channames, 'exact'); if ~isempty(count1) | ~isempty(count2) count = [ count1 count2 ]; count = count(1); else disp(['Warning: channel ''' lower(allfields{index}) ''' not in channel location structure']); count = length(chanstruct)+1; chanstruct(end+1).Name = allfields{index}; chanstruct(end+1).Phi = []; chanstruct(end+1).Theta = []; chanstruct(end+1).Radius = []; end; if bva.SegmentCount > 1 EEG.data(count,:,:) = getfield(bva, allfields{index})'; bva = rmfield(bva, allfields{index}); else EEG.data(count,:) = getfield(bva, allfields{index}); bva = rmfield(bva, allfields{index}); end; end; end; EEG.nbchan = size(EEG.data,1); EEG.srate = bva.SampleRate; EEG.xmin = bva.t(1)/1000; EEG.xmax = bva.t(end)/1000; EEG.pnts = size(EEG.data,2); EEG.trials = size(EEG.data,3); EEG.setname = 'Brain Vision Analyzer file'; EEG.comments = [ 'Original file: ' filename ]; % convert channel location structure % ---------------------------------- disp('Importing channel location information'); for index = 1:length(chanstruct) EEG.chanlocs(index).labels = chanstruct(index).Name; if chanstruct(index).Radius ~= 0 EEG.chanlocs(index).sph_theta_besa = chanstruct(index).Theta; EEG.chanlocs(index).sph_phi_besa = chanstruct(index).Phi; EEG.chanlocs(index).sph_radius = chanstruct(index).Radius; else EEG.chanlocs(index).sph_theta_besa = []; EEG.chanlocs(index).sph_phi_besa = []; EEG.chanlocs(index).sph_radius = []; end; end; EEG.chanlocs = convertlocs(EEG.chanlocs, 'sphbesa2all'); EEG.chanlocs = rmfield(EEG.chanlocs, 'sph_theta_besa'); EEG.chanlocs = rmfield(EEG.chanlocs, 'sph_phi_besa'); % convert event information % ------------------------- disp('Importing events'); index = 0; for index1 = 1:size(bva.Markers,1) for index2 = 0:size(bva.Markers,2)-1 if ~isempty(bva.Markers(index2*size(bva.Markers,1)+index1).Description) index = index + 1; EEG.event(index).type = bva.Markers(index2*size(bva.Markers,1)+index1).Description; EEG.event(index).latency = bva.Markers(index2*size(bva.Markers,1)+index1).Position; EEG.event(index).Points = bva.Markers(index2*size(bva.Markers,1)+index1).Points; try EEG.event(index).bvatype = bva.Markers(index2*size(bva.Markers,1)+index1).Type; EEG.event(index).description = bva.Markers(index2*size(bva.Markers,1)+index1).Description; catch, end; try EEG.event(index).chan = bva.Markers(index2*size(bva.Markers,1)+index1).Chan; catch, end; try EEG.event(index).channelnumber = bva.Markers(index2*size(bva.Markers,1)+index1).ChannelNumber; catch, end; if bva.SegmentCount > 1 EEG.event(index).epoch = index1; EEG.event(index).latency = bva.Markers(index2*size(bva.Markers,1)+index1).Position+(index1-1)*EEG.pnts; else EEG.event(index).latency = bva.Markers(index2*size(bva.Markers,1)+index1).Position; end; end; end; end; EEG = eeg_checkset(EEG, 'makeur'); EEG = eeg_checkset(EEG, 'eventconsistency'); com = sprintf('EEG = pop_loadbva(''%s'');', filename);
github
lcnbeapp/beapp-master
eegplugin_MARA.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/MARA-master/eegplugin_MARA.m
2,770
utf_8
7619f29fb825e45ca839265d7d4046e0
% eegplugin_MARA() - EEGLab plugin to classify artifactual ICs based on % 6 features from the time domain, the frequency domain, % and the pattern % % Inputs: % fig - [integer] EEGLAB figure % try_strings - [struct] "try" strings for menu callbacks. % catch_strings - [struct] "catch" strings for menu callbacks. % % See also: pop_processMARA(), processMARA(), MARA() % Copyright (C) 2013 Irene Winkler and Eric Waldburger % Berlin Institute of Technology, Germany % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function eegplugin_MARA( fig, try_strings, catch_strings) toolsmenu = findobj(fig, 'tag', 'tools'); h = uimenu(toolsmenu, 'label', 'IC Artifact Classification (MARA)'); uimenu(h, 'label', 'MARA Classification', 'callback', ... [try_strings.no_check ... '[ALLEEG,EEG,CURRENTSET,LASTCOM]= pop_processMARA( ALLEEG ,EEG ,CURRENTSET );' ... catch_strings.add_to_hist ]); uimenu(h, 'label', 'Visualize Components', 'tag', 'MARAviz', 'Enable', ... 'off', 'callback', [try_strings.no_check ... 'EEG = pop_selectcomps_MARA(EEG); pop_visualizeMARAfeatures(EEG.reject.gcompreject, EEG.reject.MARAinfo); ' ... catch_strings.add_to_hist ]); uimenu(h, 'label', 'About', 'Separator', 'on', 'Callback', ... ['warndlg2(sprintf([''MARA automatizes the process of hand-labeling independent components for ', ... 'artifact rejection. It is a supervised machine learning algorithm that learns from ', ... 'expert ratings of 1290 components. Features were optimized to solve the binary classification problem ', ... 'reject vs. accept.\n \n', ... 'If you have questions or suggestions about the toolbox, please contact \n ', ... 'Irene Winkler, TU Berlin [email protected] \n \n ', ... 'Reference: \nI. Winkler, S. Haufe, and M. Tangermann, Automatic classification of artifactual', ... 'ICA-components for artifact removal in EEG signals, Behavioral and Brain Functions, 7, 2011.''])', ... ',''About MARA'');']);
github
lcnbeapp/beapp-master
pop_visualizeMARAfeatures.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/MARA-master/pop_visualizeMARAfeatures.m
4,558
utf_8
c888a9b58c7e7893d090883d152d5e09
% pop_visualizeMARAfeatures() - Display features that MARA's decision % for artifact rejection is based on % % Usage: % >> pop_visualizeMARAfeatures(gcompreject, MARAinfo); % % Inputs: % gcompreject - array <1 x nIC> containing 1 if component was rejected % MARAinfo - struct containing more information about MARA classification % (output of function <MARA>) % .posterior_artefactprob : posterior probability for each % IC of being an artefact according to % .normfeats : <6 x nIC > features computed by MARA for each IC, % normalized by the training data % The features are: (1) Current Density Norm, (2) Range % in Pattern, (3) Local Skewness of the Time Series, % (4) Lambda, (5) 8-13 Hz, (6) FitError. % % See also: MARA(), processMARA(), pop_selectcomps_MARA() % Copyright (C) 2013 Irene Winkler and Eric Waldburger % Berlin Institute of Technology, Germany % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function pop_visualizeMARAfeatures(gcompreject, MARAinfo) %try set(0,'units','pixels'); resolution = get(0, 'Screensize'); width = resolution(3); height = resolution(4); panelsettings.rowsize = 200; panelsettings.columnsize = 200; panelsettings.columns = floor(width/(2*panelsettings.columnsize)); panelsettings.rows = floor(height/panelsettings.rowsize); panelsettings.numberPerPage = panelsettings.columns * panelsettings.rows; panelsettings.pages = ceil(length(gcompreject)/ panelsettings.numberPerPage); % display components on a number of different pages for page=1:panelsettings.pages selectcomps_1page(page, panelsettings, gcompreject, MARAinfo); end; %catch % eeglab_error %end function EEG = selectcomps_1page(page, panelsettings, gcompreject, MARAinfo) try, icadefs; catch, BACKCOLOR = [0.8 0.8 0.8]; GUIBUTTONCOLOR = [0.8 0.8 0.8]; end; % set up the figure % %%%%%%%%%%%%%%%% if ~exist('fig') mainFig = figure('name', 'Visualize MARA features', 'numbertitle', 'off'); set(mainFig, 'Color', BACKCOLOR) set(gcf,'MenuBar', 'none'); pos = get(gcf,'Position'); set(gcf,'Position', [20 20 panelsettings.columnsize*panelsettings.columns panelsettings.rowsize*panelsettings.rows]); end; % compute range of components to display if page < panelsettings.pages range = (1 + (panelsettings.numberPerPage * (page-1))) : (panelsettings.numberPerPage + ( panelsettings.numberPerPage * (page-1))); else range = (1 + (panelsettings.numberPerPage * (page-1))) : length(gcompreject); end % draw each component % %%%%%%%%%%%%%%%% for i = 1:length(range) subplot(panelsettings.rows, panelsettings.columns, i) for j = 1:6 h = barh(j, MARAinfo.normfeats(j, range(i))); hold on; if j <= 4 && MARAinfo.normfeats(j, range(i)) > 0 set(h, 'FaceColor', [0.4 0 0]); end if j > 4 && MARAinfo.normfeats(j, range(i)) < 0 set(h, 'FaceColor', [0.4 0 0]); end end axis square; if mod(i, panelsettings.columns) == 1 set(gca,'YTick', 1:6, 'YTickLabel', {'Current Density Norm', ... 'Range in Pattern', 'Local Skewness', 'lambda', '8-13Hz', 'FitError'}) else set(gca,'YTick', 1:6, 'YTickLabel', cell(1,6)) end if gcompreject(range(i)) == 1 title(sprintf('IC %d, p-artifact = %1.2f', range(i),MARAinfo.posterior_artefactprob(range(i))),... 'Color', [0.4 0 0]); set(gca, 'Color', [1 0.7 0.7]) %keyboard else title(sprintf('IC %d, p-artifact = %1.2f', range(i),MARAinfo.posterior_artefactprob(range(i)))); end end
github
lcnbeapp/beapp-master
processMARA.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/MARA-master/processMARA.m
6,510
utf_8
896a41c6475ec80bf7706cc7166ce7a8
% processMARA() - Processing for Automatic Artifact Classification with MARA. % processMARA() calls MACA and saves the identified artifactual components % in EEG.reject.gcompreject. % The functions optionally filters the data, runs ICA, plots components or % reject artifactual components immediately. % % Usage: % >> [ALLEEG,EEG,CURRENTSET] = processMARA(ALLEEG,EEG,CURRENTSET,options) % % Inputs and Outputs: % ALLEEG - array of EEG dataset structures % EEG - current dataset structure or structure array % (EEG.reject.gcompreject will be updated) % CURRENTSET - index(s) of the current EEG dataset(s) in ALLEEG % % % Optional Input: % options - 1x5 array specifing optional operations, default is [0,0,0,0,0] % - option(1) = 1 => filter the data before MARA classification % - option(2) = 1 => run ica before MARA classification % - option(3) = 1 => plot components to label them for rejection after MARA classification % (for rejection) % - option(4) = 1 => plot MARA features for each IC % - option(4) = 1 => automatically reject MARA's artifactual % components without inspecting them % % See also: pop_eegfilt(), pop_runica, MARA(), pop_selectcomps_MARA(), pop_subcomp % Copyright (C) 2013 Irene Winkler and Eric Waldburger % Berlin Institute of Technology, Germany % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [ALLEEG,EEG,CURRENTSET] = processMARA(ALLEEG,EEG,CURRENTSET,varargin) if isempty(EEG.chanlocs) try error('No channel locations. Aborting MARA.') catch eeglab_error; return; end end if not(isempty(varargin)) options = varargin{1}; else options = [0 0 0 0 0]; end %% filter the data if options(1) == 1 disp('Filtering data'); [EEG, LASTCOM] = pop_eegfilt(EEG); eegh(LASTCOM); [ALLEEG EEG CURRENTSET, LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET); eegh(LASTCOM); end %% run ica if options(2) == 1 disp('Run ICA'); [EEG, LASTCOM] = pop_runica(EEG); [ALLEEG EEG CURRENTSET, LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET); eegh(LASTCOM); end %% check if ica components are present [EEG LASTCOM] = eeg_checkset(EEG, 'ica'); if LASTCOM < 0 disp('There are no ICA components present. Aborting classification.'); return else eegh(LASTCOM); end %% classify artifactual components with MARA [artcomps, MARAinfo] = MARA(EEG); EEG.reject.MARAinfo = MARAinfo; disp('MARA marked the following components for rejection: ') if isempty(artcomps) disp('None') else disp(artcomps) disp(' ') end if isempty(EEG.reject.gcompreject) EEG.reject.gcompreject = zeros(1,size(EEG.icawinv,2)); gcompreject_old = EEG.reject.gcompreject; else % if gcompreject present check whether labels differ from MARA if and(length(EEG.reject.gcompreject) == size(EEG.icawinv,2), ... not(isempty(find(EEG.reject.gcompreject)))) tmp = zeros(1,size(EEG.icawinv,2)); tmp(artcomps) = 1; if not(isequal(tmp, EEG.reject.gcompreject)) answer = questdlg(... 'Some components are already labeled for rejection. What do you want to do?',... 'Labels already present','Merge artifactual labels','Overwrite old labels', 'Cancel','Cancel'); switch answer, case 'Overwrite old labels', gcompreject_old = EEG.reject.gcompreject; EEG.reject.gcompreject = zeros(1,size(EEG.icawinv,2)); disp('Overwrites old labels') case 'Merge artifactual labels' disp('Merges MARA''s and old labels') gcompreject_old = EEG.reject.gcompreject; case 'Cancel', return; end else gcompreject_old = EEG.reject.gcompreject; end else EEG.reject.gcompreject = zeros(1,size(EEG.icawinv,2)); gcompreject_old = EEG.reject.gcompreject; end end EEG.reject.gcompreject(artcomps) = 1; try EEGLABfig = findall(0, 'tag', 'EEGLAB'); MARAvizmenu = findobj(EEGLABfig, 'tag', 'MARAviz'); set(MARAvizmenu, 'Enable', 'on'); catch keyboard end %% display components with checkbox to label them for artifact rejection if options(3) == 1 if isempty(artcomps) answer = questdlg2(... 'MARA identied no artifacts. Do you still want to visualize components?',... 'No artifacts identified','Yes', 'No', 'No'); if strcmp(answer,'No') return; end end [EEG, LASTCOM] = pop_selectcomps_MARA(EEG, gcompreject_old); eegh(LASTCOM); if options(4) == 1 pop_visualizeMARAfeatures(EEG.reject.gcompreject, EEG.reject.MARAinfo); end end %% automatically remove artifacts if and(and(options(5) == 1, not(options(3) == 1)), not(isempty(artcomps))) try [EEG LASTCOM] = pop_subcomp(EEG); eegh(LASTCOM); catch eeglab_error end [ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET); eegh(LASTCOM); disp('Artifact rejection done.'); end